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/WHPP-ejb/src/main/java/org/courses/whpp/session/WorktimeFacade.java b/WHPP-ejb/src/main/java/org/courses/whpp/session/WorktimeFacade.java index d85dbef..6805e69 100644 --- a/WHPP-ejb/src/main/java/org/courses/whpp/session/WorktimeFacade.java +++ b/WHPP-ejb/src/main/java/org/courses/whpp/session/WorktimeFacade.java @@ -1,93 +1,96 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.courses.whpp.session; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.courses.whpp.entity.Employee; import org.courses.whpp.entity.Worktime; import java.util.Date; import java.util.List; /** * @author Roman Kostyrko <[email protected]> * Created on Jun 13, 2012, 8:11:44 PM */ @Stateless public class WorktimeFacade extends AbstractFacade<Worktime> { protected EmployeeFacade employeeFacade = null; @PersistenceContext(unitName = "org.courses_WHPP-ejb_ejb_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public WorktimeFacade() { super(Worktime.class); employeeFacade = new EmployeeFacade(); } public Worktime findOpenedByEmployeeId(Integer EmployeeId) { return (Worktime) em.createNamedQuery("Worktime.findOpenedByEmployeeId").setParameter("EmployeeId", EmployeeId).getSingleResult(); } public Boolean logIn(Integer EmployeeId) { Boolean result = true; Employee employeeForId = employeeFacade.findById(EmployeeId); if(employeeForId == null) + { result = false; + return result; + } Worktime worktimeForId = findOpenedByEmployeeId(EmployeeId); if(worktimeForId != null ) result = result && logOut(worktimeForId); this.create(new Worktime(new Date(), null, employeeForId)); return result; } public Boolean logOut(Integer EmployeeId) { Boolean result = true; Worktime worktimeForId = findOpenedByEmployeeId(EmployeeId); if(worktimeForId == null ) result = false; else result = result && logOut(worktimeForId); return result; } protected Boolean logOut(Worktime tl) { Date curTime = new Date(); if((curTime.getTime() - tl.getIntime().getTime()) > 43200) { tl.setOuttime(new Date(tl.getIntime().getTime()+43200)); } else { tl.setOuttime(curTime); } this.edit(tl); return true; // working ideal by default } }
false
true
public Boolean logIn(Integer EmployeeId) { Boolean result = true; Employee employeeForId = employeeFacade.findById(EmployeeId); if(employeeForId == null) result = false; Worktime worktimeForId = findOpenedByEmployeeId(EmployeeId); if(worktimeForId != null ) result = result && logOut(worktimeForId); this.create(new Worktime(new Date(), null, employeeForId)); return result; }
public Boolean logIn(Integer EmployeeId) { Boolean result = true; Employee employeeForId = employeeFacade.findById(EmployeeId); if(employeeForId == null) { result = false; return result; } Worktime worktimeForId = findOpenedByEmployeeId(EmployeeId); if(worktimeForId != null ) result = result && logOut(worktimeForId); this.create(new Worktime(new Date(), null, employeeForId)); return result; }
diff --git a/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java b/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java index b2266557..284e28b2 100644 --- a/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java +++ b/src/powercrystals/minefactoryreloaded/modhelpers/twilightforest/TwilightForestEggHandler.java @@ -1,33 +1,33 @@ package powercrystals.minefactoryreloaded.modhelpers.twilightforest; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityEggInfo; import net.minecraft.item.ItemStack; import powercrystals.minefactoryreloaded.api.IMobEggHandler; public class TwilightForestEggHandler implements IMobEggHandler { @SuppressWarnings("unchecked") @Override public EntityEggInfo getEgg(ItemStack safariNet) { try { Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class")); EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true); - if(er.getContainer() != null && er.getContainer() == TwilightForest.twilightForestContainer) + if(er != null && er.getContainer() == TwilightForest.twilightForestContainer) { return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId()); } return null; } catch(ClassNotFoundException e) { e.printStackTrace(); return null; } } }
true
true
public EntityEggInfo getEgg(ItemStack safariNet) { try { Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class")); EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true); if(er.getContainer() != null && er.getContainer() == TwilightForest.twilightForestContainer) { return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId()); } return null; } catch(ClassNotFoundException e) { e.printStackTrace(); return null; } }
public EntityEggInfo getEgg(ItemStack safariNet) { try { Class<? extends Entity> entityClass = (Class<? extends Entity>)Class.forName(safariNet.getTagCompound().getString("_class")); EntityRegistration er = EntityRegistry.instance().lookupModSpawn(entityClass, true); if(er != null && er.getContainer() == TwilightForest.twilightForestContainer) { return (EntityEggInfo)TwilightForest.entityEggs.get(er.getModEntityId()); } return null; } catch(ClassNotFoundException e) { e.printStackTrace(); return null; } }
diff --git a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/CpdPlugin.java b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/CpdPlugin.java index d4b7a55386..71edec05f8 100644 --- a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/CpdPlugin.java +++ b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/CpdPlugin.java @@ -1,73 +1,73 @@ /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.cpd; import com.google.common.collect.ImmutableList; import org.sonar.api.CoreProperties; import org.sonar.api.PropertyType; import org.sonar.api.SonarPlugin; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import org.sonar.plugins.cpd.decorators.DuplicationDensityDecorator; import org.sonar.plugins.cpd.decorators.SumDuplicationsDecorator; import org.sonar.plugins.cpd.index.IndexFactory; import java.util.List; public final class CpdPlugin extends SonarPlugin { public List<?> getExtensions() { return ImmutableList.of( PropertyDefinition.builder(CoreProperties.CPD_CROSS_RPOJECT) .defaultValue(CoreProperties.CPD_CROSS_RPOJECT_DEFAULT_VALUE + "") .name("Cross project duplication detection") .description("SonarQube supports the detection of cross project duplications. Activating this property will slightly increase each SonarQube analysis time.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_SKIP_PROPERTY) .defaultValue("false") .name("Skip") .description("Disable detection of duplications") .hidden() .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_EXCLUSIONS) .defaultValue("") - .name("Duplication exclusions") + .name("Duplication Exclusions") .description("Patterns used to exclude some source files from the duplication detection mechanism. " + - "See the \"Exclusions\" category to know how to use wildcards to specify this property.") + "See below to know how to use wildcards to specify this property.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_DUPLICATIONS_EXCLUSIONS) .multiValues(true) .build(), CpdSensor.class, SumDuplicationsDecorator.class, DuplicationDensityDecorator.class, IndexFactory.class, SonarEngine.class, SonarBridgeEngine.class); } }
false
true
public List<?> getExtensions() { return ImmutableList.of( PropertyDefinition.builder(CoreProperties.CPD_CROSS_RPOJECT) .defaultValue(CoreProperties.CPD_CROSS_RPOJECT_DEFAULT_VALUE + "") .name("Cross project duplication detection") .description("SonarQube supports the detection of cross project duplications. Activating this property will slightly increase each SonarQube analysis time.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_SKIP_PROPERTY) .defaultValue("false") .name("Skip") .description("Disable detection of duplications") .hidden() .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_EXCLUSIONS) .defaultValue("") .name("Duplication exclusions") .description("Patterns used to exclude some source files from the duplication detection mechanism. " + "See the \"Exclusions\" category to know how to use wildcards to specify this property.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_DUPLICATIONS_EXCLUSIONS) .multiValues(true) .build(), CpdSensor.class, SumDuplicationsDecorator.class, DuplicationDensityDecorator.class, IndexFactory.class, SonarEngine.class, SonarBridgeEngine.class); }
public List<?> getExtensions() { return ImmutableList.of( PropertyDefinition.builder(CoreProperties.CPD_CROSS_RPOJECT) .defaultValue(CoreProperties.CPD_CROSS_RPOJECT_DEFAULT_VALUE + "") .name("Cross project duplication detection") .description("SonarQube supports the detection of cross project duplications. Activating this property will slightly increase each SonarQube analysis time.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_SKIP_PROPERTY) .defaultValue("false") .name("Skip") .description("Disable detection of duplications") .hidden() .category(CoreProperties.CATEGORY_DUPLICATIONS) .type(PropertyType.BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_EXCLUSIONS) .defaultValue("") .name("Duplication Exclusions") .description("Patterns used to exclude some source files from the duplication detection mechanism. " + "See below to know how to use wildcards to specify this property.") .onQualifiers(Qualifiers.PROJECT, Qualifiers.MODULE) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_DUPLICATIONS_EXCLUSIONS) .multiValues(true) .build(), CpdSensor.class, SumDuplicationsDecorator.class, DuplicationDensityDecorator.class, IndexFactory.class, SonarEngine.class, SonarBridgeEngine.class); }
diff --git a/tools/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java b/tools/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java index a9e8afae..6cae085a 100755 --- a/tools/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java +++ b/tools/sdkmanager/libs/sdkuilib/src/com/android/sdkuilib/internal/repository/UpdaterData.java @@ -1,536 +1,536 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.sdkuilib.internal.repository; import com.android.prefs.AndroidLocation.AndroidLocationException; import com.android.sdklib.ISdkLog; import com.android.sdklib.SdkManager; import com.android.sdklib.internal.avd.AvdManager; import com.android.sdklib.internal.repository.AddonPackage; import com.android.sdklib.internal.repository.Archive; import com.android.sdklib.internal.repository.ITask; import com.android.sdklib.internal.repository.ITaskFactory; import com.android.sdklib.internal.repository.ITaskMonitor; import com.android.sdklib.internal.repository.LocalSdkParser; import com.android.sdklib.internal.repository.Package; import com.android.sdklib.internal.repository.RepoSource; import com.android.sdklib.internal.repository.RepoSources; import com.android.sdklib.internal.repository.ToolPackage; import com.android.sdklib.internal.repository.Package.UpdateInfo; import com.android.sdkuilib.internal.repository.icons.ImageFactory; import com.android.sdkuilib.repository.UpdaterWindow.ISdkListener; import org.eclipse.swt.widgets.Shell; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Data shared between {@link UpdaterWindowImpl} and its pages. */ class UpdaterData { private String mOsSdkRoot; private final ISdkLog mSdkLog; private ITaskFactory mTaskFactory; private boolean mUserCanChangeSdkRoot; private SdkManager mSdkManager; private AvdManager mAvdManager; private final LocalSdkParser mLocalSdkParser = new LocalSdkParser(); private final RepoSources mSources = new RepoSources(); private final LocalSdkAdapter mLocalSdkAdapter = new LocalSdkAdapter(this); private final RepoSourcesAdapter mSourcesAdapter = new RepoSourcesAdapter(this); private ImageFactory mImageFactory; private final SettingsController mSettingsController = new SettingsController(); private final ArrayList<ISdkListener> mListeners = new ArrayList<ISdkListener>(); private Shell mWindowShell; public UpdaterData(String osSdkRoot, ISdkLog sdkLog) { mOsSdkRoot = osSdkRoot; mSdkLog = sdkLog; initSdk(); } // ----- getters, setters ---- public void setOsSdkRoot(String osSdkRoot) { if (mOsSdkRoot == null || mOsSdkRoot.equals(osSdkRoot) == false) { mOsSdkRoot = osSdkRoot; initSdk(); } } public String getOsSdkRoot() { return mOsSdkRoot; } public void setTaskFactory(ITaskFactory taskFactory) { mTaskFactory = taskFactory; } public ITaskFactory getTaskFactory() { return mTaskFactory; } public void setUserCanChangeSdkRoot(boolean userCanChangeSdkRoot) { mUserCanChangeSdkRoot = userCanChangeSdkRoot; } public boolean canUserChangeSdkRoot() { return mUserCanChangeSdkRoot; } public RepoSources getSources() { return mSources; } public RepoSourcesAdapter getSourcesAdapter() { return mSourcesAdapter; } public LocalSdkParser getLocalSdkParser() { return mLocalSdkParser; } public LocalSdkAdapter getLocalSdkAdapter() { return mLocalSdkAdapter; } public ISdkLog getSdkLog() { return mSdkLog; } public void setImageFactory(ImageFactory imageFactory) { mImageFactory = imageFactory; } public ImageFactory getImageFactory() { return mImageFactory; } public SdkManager getSdkManager() { return mSdkManager; } public AvdManager getAvdManager() { return mAvdManager; } public SettingsController getSettingsController() { return mSettingsController; } public void addListeners(ISdkListener listener) { if (mListeners.contains(listener) == false) { mListeners.add(listener); } } public void removeListener(ISdkListener listener) { mListeners.remove(listener); } public void setWindowShell(Shell windowShell) { mWindowShell = windowShell; } public Shell getWindowShell() { return mWindowShell; } // ----- /** * Initializes the {@link SdkManager} and the {@link AvdManager}. */ private void initSdk() { mSdkManager = SdkManager.createManager(mOsSdkRoot, mSdkLog); try { mAvdManager = null; // remove the old one if needed. mAvdManager = new AvdManager(mSdkManager, mSdkLog); } catch (AndroidLocationException e) { mSdkLog.error(e, "Unable to read AVDs"); } // notify adapters/parsers // TODO // notify listeners. notifyListeners(); } /** * Reloads the SDK content (targets). * <p/> This also reloads the AVDs in case their status changed. * <p/>This does not notify the listeners ({@link ISdkListener}). */ public void reloadSdk() { // reload SDK mSdkManager.reloadSdk(mSdkLog); // reload AVDs if (mAvdManager != null) { try { mAvdManager.reloadAvds(mSdkLog); } catch (AndroidLocationException e) { // FIXME } } // notify adapters? mLocalSdkParser.clearPackages(); // TODO // notify listeners notifyListeners(); } /** * Reloads the AVDs. * <p/>This does not notify the listeners. */ public void reloadAvds() { // reload AVDs if (mAvdManager != null) { try { mAvdManager.reloadAvds(mSdkLog); } catch (AndroidLocationException e) { mSdkLog.error(e, null); } } } /** * Returns the list of installed packages, parsing them if this has not yet been done. */ public Package[] getInstalledPackage() { LocalSdkParser parser = getLocalSdkParser(); Package[] packages = parser.getPackages(); if (packages == null) { // load on demand the first time packages = parser.parseSdk(getOsSdkRoot(), getSdkManager(), getSdkLog()); } return packages; } /** * Notify the listeners ({@link ISdkListener}) that the SDK was reloaded. * <p/>This can be called from any thread. */ public void notifyListeners() { if (mWindowShell != null && mListeners.size() > 0) { mWindowShell.getDisplay().syncExec(new Runnable() { public void run() { for (ISdkListener listener : mListeners) { try { listener.onSdkChange(); } catch (Throwable t) { mSdkLog.error(t, null); } } } }); } } /** * Install the list of given {@link Archive}s. This is invoked by the user selecting some * packages in the remote page and then clicking "install selected". * * @param archives The archives to install. Incompatible ones will be skipped. */ public void installArchives(final Collection<Archive> archives) { if (mTaskFactory == null) { throw new IllegalArgumentException("Task Factory is null"); } final boolean forceHttp = getSettingsController().getForceHttp(); mTaskFactory.start("Installing Archives", new ITask() { public void run(ITaskMonitor monitor) { final int progressPerArchive = 2 * Archive.NUM_MONITOR_INC; monitor.setProgressMax(archives.size() * progressPerArchive); monitor.setDescription("Preparing to install archives"); boolean installedAddon = false; boolean installedTools = false; int numInstalled = 0; for (Archive archive : archives) { int nextProgress = monitor.getProgress() + progressPerArchive; try { if (monitor.isCancelRequested()) { break; } if (archive.getParentPackage() instanceof AddonPackage) { installedAddon = true; } else if (archive.getParentPackage() instanceof ToolPackage) { installedTools = true; } if (archive.install(mOsSdkRoot, forceHttp, mSdkManager, monitor)) { numInstalled++; } } catch (Throwable t) { // Display anything unexpected in the monitor. String msg = t.getMessage(); if (msg != null) { - monitor.setResult("Unexpected Error installing '%1%s: %2$s", + monitor.setResult("Unexpected Error installing '%1$s: %2$s", archive.getParentPackage().getShortDescription(), msg); } else { // no error info? get the stack call to display it // At least that'll give us a better bug report. ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(baos)); // and display it monitor.setResult("Unexpected Error installing '%1$s\n%2$s", archive.getParentPackage().getShortDescription(), baos.toString()); } } finally { // Always move the progress bar to the desired position. // This allows internal methods to not have to care in case // they abort early monitor.incProgress(nextProgress - monitor.getProgress()); } } if (installedAddon) { // Update the USB vendor ids for adb try { mSdkManager.updateAdb(); } catch (Exception e) { mSdkLog.error(e, "Update ADB failed"); } } if (installedAddon || installedTools) { // We need to restart ADB. Actually since we don't know if it's even // running, maybe we should just kill it and not start it. // Note: it turns out even under Windows we don't need to kill adb // before updating the tools folder, as adb.exe is (surprisingly) not // locked. // TODO either bring in ddmlib and use its existing methods to stop adb // or use a shell exec to tools/adb. } if (numInstalled == 0) { monitor.setDescription("Done. Nothing was installed."); } else { monitor.setDescription("Done. %1$d %2$s installed.", numInstalled, numInstalled == 1 ? "package" : "packages"); //notify listeners something was installed, so that they can refresh reloadSdk(); } } }); } /** * Tries to update all the *existing* local packages. * This first refreshes all sources, then compares the available remote packages when * the current local ones and suggest updates to be done to the user. Finally all * selected updates are installed. * * @param selectedArchives The list of remote archive to consider for the update. * This can be null, in which case a list of remote archive is fetched from all * available sources. */ public void updateOrInstallAll(Collection<Archive> selectedArchives) { if (selectedArchives == null) { refreshSources(true); } final Map<Archive, Archive> updates = findUpdates(selectedArchives); if (selectedArchives != null) { // Not only we want to perform updates but we also want to install the // selected archives. If they do not match an update, list them anyway // except they map themselves to null (no "old" archive) for (Archive a : selectedArchives) { if (!updates.containsValue(a)) { updates.put(a, null); } } } UpdateChooserDialog dialog = new UpdateChooserDialog(this, updates); dialog.open(); Collection<Archive> result = dialog.getResult(); if (result != null && result.size() > 0) { installArchives(result); } } /** * Refresh all sources. This is invoked either internally (reusing an existing monitor) * or as a UI callback on the remote page "Refresh" button (in which case the monitor is * null and a new task should be created.) * * @param forceFetching When true, load sources that haven't been loaded yet. * When false, only refresh sources that have been loaded yet. */ public void refreshSources(final boolean forceFetching) { assert mTaskFactory != null; final boolean forceHttp = getSettingsController().getForceHttp(); mTaskFactory.start("Refresh Sources",new ITask() { public void run(ITaskMonitor monitor) { RepoSource[] sources = mSources.getSources(); monitor.setProgressMax(sources.length); for (RepoSource source : sources) { if (forceFetching || source.getPackages() != null || source.getFetchError() != null) { source.load(monitor.createSubMonitor(1), forceHttp); } monitor.incProgress(1); } } }); } /** * Check the local archives vs the remote available packages to find potential updates. * Return a map [remote archive => local archive] of suitable update candidates. * Returns null if there's an unexpected error. Otherwise returns a map that can be * empty but not null. * * @param selectedArchives The list of remote archive to consider for the update. * This can be null, in which case a list of remote archive is fetched from all * available sources. */ private Map<Archive, Archive> findUpdates(Collection<Archive> selectedArchives) { // Map [remote archive => local archive] of suitable update candidates Map<Archive, Archive> result = new HashMap<Archive, Archive>(); // First go thru all sources and make a local list of all available archives // sorted by package class. HashMap<Class<? extends Package>, ArrayList<Archive>> availPkgs = new HashMap<Class<? extends Package>, ArrayList<Archive>>(); if (selectedArchives != null) { // Only consider the archives given for (Archive a : selectedArchives) { // Only add compatible archives if (a.isCompatible()) { Class<? extends Package> clazz = a.getParentPackage().getClass(); ArrayList<Archive> list = availPkgs.get(clazz); if (list == null) { availPkgs.put(clazz, list = new ArrayList<Archive>()); } list.add(a); } } } else { // Get all the available archives from all loaded sources RepoSource[] remoteSources = getSources().getSources(); for (RepoSource remoteSrc : remoteSources) { Package[] remotePkgs = remoteSrc.getPackages(); if (remotePkgs != null) { for (Package remotePkg : remotePkgs) { Class<? extends Package> clazz = remotePkg.getClass(); ArrayList<Archive> list = availPkgs.get(clazz); if (list == null) { availPkgs.put(clazz, list = new ArrayList<Archive>()); } for (Archive a : remotePkg.getArchives()) { // Only add compatible archives if (a.isCompatible()) { list.add(a); } } } } } } Package[] localPkgs = getLocalSdkParser().getPackages(); if (localPkgs == null) { // This is unexpected. The local sdk parser should have been called first. return null; } for (Package localPkg : localPkgs) { // get the available archive list for this package type ArrayList<Archive> list = availPkgs.get(localPkg.getClass()); // if this list is empty, we'll never find anything that matches if (list == null || list.size() == 0) { continue; } // local packages should have one archive at most Archive[] localArchives = localPkg.getArchives(); if (localArchives != null && localArchives.length > 0) { Archive localArchive = localArchives[0]; // only consider archive compatible with the current platform if (localArchive != null && localArchive.isCompatible()) { // We checked all this archive stuff because that's what eventually gets // installed, but the "update" mechanism really works on packages. So now // the real question: is there a remote package that can update this // local package? for (Archive availArchive : list) { UpdateInfo info = localPkg.canBeUpdatedBy(availArchive.getParentPackage()); if (info == UpdateInfo.UPDATE) { // Found one! result.put(availArchive, localArchive); break; } } } } } return result; } }
true
true
public void installArchives(final Collection<Archive> archives) { if (mTaskFactory == null) { throw new IllegalArgumentException("Task Factory is null"); } final boolean forceHttp = getSettingsController().getForceHttp(); mTaskFactory.start("Installing Archives", new ITask() { public void run(ITaskMonitor monitor) { final int progressPerArchive = 2 * Archive.NUM_MONITOR_INC; monitor.setProgressMax(archives.size() * progressPerArchive); monitor.setDescription("Preparing to install archives"); boolean installedAddon = false; boolean installedTools = false; int numInstalled = 0; for (Archive archive : archives) { int nextProgress = monitor.getProgress() + progressPerArchive; try { if (monitor.isCancelRequested()) { break; } if (archive.getParentPackage() instanceof AddonPackage) { installedAddon = true; } else if (archive.getParentPackage() instanceof ToolPackage) { installedTools = true; } if (archive.install(mOsSdkRoot, forceHttp, mSdkManager, monitor)) { numInstalled++; } } catch (Throwable t) { // Display anything unexpected in the monitor. String msg = t.getMessage(); if (msg != null) { monitor.setResult("Unexpected Error installing '%1%s: %2$s", archive.getParentPackage().getShortDescription(), msg); } else { // no error info? get the stack call to display it // At least that'll give us a better bug report. ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(baos)); // and display it monitor.setResult("Unexpected Error installing '%1$s\n%2$s", archive.getParentPackage().getShortDescription(), baos.toString()); } } finally { // Always move the progress bar to the desired position. // This allows internal methods to not have to care in case // they abort early monitor.incProgress(nextProgress - monitor.getProgress()); } } if (installedAddon) { // Update the USB vendor ids for adb try { mSdkManager.updateAdb(); } catch (Exception e) { mSdkLog.error(e, "Update ADB failed"); } } if (installedAddon || installedTools) { // We need to restart ADB. Actually since we don't know if it's even // running, maybe we should just kill it and not start it. // Note: it turns out even under Windows we don't need to kill adb // before updating the tools folder, as adb.exe is (surprisingly) not // locked. // TODO either bring in ddmlib and use its existing methods to stop adb // or use a shell exec to tools/adb. } if (numInstalled == 0) { monitor.setDescription("Done. Nothing was installed."); } else { monitor.setDescription("Done. %1$d %2$s installed.", numInstalled, numInstalled == 1 ? "package" : "packages"); //notify listeners something was installed, so that they can refresh reloadSdk(); } } }); }
public void installArchives(final Collection<Archive> archives) { if (mTaskFactory == null) { throw new IllegalArgumentException("Task Factory is null"); } final boolean forceHttp = getSettingsController().getForceHttp(); mTaskFactory.start("Installing Archives", new ITask() { public void run(ITaskMonitor monitor) { final int progressPerArchive = 2 * Archive.NUM_MONITOR_INC; monitor.setProgressMax(archives.size() * progressPerArchive); monitor.setDescription("Preparing to install archives"); boolean installedAddon = false; boolean installedTools = false; int numInstalled = 0; for (Archive archive : archives) { int nextProgress = monitor.getProgress() + progressPerArchive; try { if (monitor.isCancelRequested()) { break; } if (archive.getParentPackage() instanceof AddonPackage) { installedAddon = true; } else if (archive.getParentPackage() instanceof ToolPackage) { installedTools = true; } if (archive.install(mOsSdkRoot, forceHttp, mSdkManager, monitor)) { numInstalled++; } } catch (Throwable t) { // Display anything unexpected in the monitor. String msg = t.getMessage(); if (msg != null) { monitor.setResult("Unexpected Error installing '%1$s: %2$s", archive.getParentPackage().getShortDescription(), msg); } else { // no error info? get the stack call to display it // At least that'll give us a better bug report. ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(baos)); // and display it monitor.setResult("Unexpected Error installing '%1$s\n%2$s", archive.getParentPackage().getShortDescription(), baos.toString()); } } finally { // Always move the progress bar to the desired position. // This allows internal methods to not have to care in case // they abort early monitor.incProgress(nextProgress - monitor.getProgress()); } } if (installedAddon) { // Update the USB vendor ids for adb try { mSdkManager.updateAdb(); } catch (Exception e) { mSdkLog.error(e, "Update ADB failed"); } } if (installedAddon || installedTools) { // We need to restart ADB. Actually since we don't know if it's even // running, maybe we should just kill it and not start it. // Note: it turns out even under Windows we don't need to kill adb // before updating the tools folder, as adb.exe is (surprisingly) not // locked. // TODO either bring in ddmlib and use its existing methods to stop adb // or use a shell exec to tools/adb. } if (numInstalled == 0) { monitor.setDescription("Done. Nothing was installed."); } else { monitor.setDescription("Done. %1$d %2$s installed.", numInstalled, numInstalled == 1 ? "package" : "packages"); //notify listeners something was installed, so that they can refresh reloadSdk(); } } }); }
diff --git a/src/com/werebug/randomsequencegenerator/SaveDialog.java b/src/com/werebug/randomsequencegenerator/SaveDialog.java index 25611b6..88b0af6 100644 --- a/src/com/werebug/randomsequencegenerator/SaveDialog.java +++ b/src/com/werebug/randomsequencegenerator/SaveDialog.java @@ -1,63 +1,63 @@ package com.werebug.randomsequencegenerator; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.widget.EditText; public class SaveDialog extends DialogFragment { private EditText edit_name; public interface SaveDialogListener { public void onDialogPositiveClick(DialogFragment dialog, String name); public void onDialogNegativeClick(DialogFragment dialog); } SaveDialogListener mListener; // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener @Override public void onAttach(Activity activity) { super.onAttach(activity); // Verify that the host activity implements the callback interface try { // Instantiate the NoticeDialogListener so we can send events to the host mListener = (SaveDialogListener) activity; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(activity.toString() + " must implement SaveDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); edit_name = new EditText(this.getActivity()); - builder.setMessage(R.string.save_dialog) + builder.setMessage(R.string.save_as) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Send the negative button event back to the host activity mListener.onDialogNegativeClick(SaveDialog.this); } }) - .setPositiveButton(R.string.confirm_saving, new DialogInterface.OnClickListener() { + .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Retrieving name String name = edit_name.getText().toString(); // Send the positive button event back to the host activity mListener.onDialogPositiveClick(SaveDialog.this, name); } }) .setView(edit_name); return builder.create(); } }
false
true
public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); edit_name = new EditText(this.getActivity()); builder.setMessage(R.string.save_dialog) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Send the negative button event back to the host activity mListener.onDialogNegativeClick(SaveDialog.this); } }) .setPositiveButton(R.string.confirm_saving, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Retrieving name String name = edit_name.getText().toString(); // Send the positive button event back to the host activity mListener.onDialogPositiveClick(SaveDialog.this, name); } }) .setView(edit_name); return builder.create(); }
public Dialog onCreateDialog(Bundle savedInstanceState) { // Build the dialog and set up the button click handlers AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); edit_name = new EditText(this.getActivity()); builder.setMessage(R.string.save_as) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Send the negative button event back to the host activity mListener.onDialogNegativeClick(SaveDialog.this); } }) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Retrieving name String name = edit_name.getText().toString(); // Send the positive button event back to the host activity mListener.onDialogPositiveClick(SaveDialog.this, name); } }) .setView(edit_name); return builder.create(); }
diff --git a/src/com/sun/javanet/cvsnews/cli/UpdateCommand.java b/src/com/sun/javanet/cvsnews/cli/UpdateCommand.java index 851e6ff..9e6d400 100644 --- a/src/com/sun/javanet/cvsnews/cli/UpdateCommand.java +++ b/src/com/sun/javanet/cvsnews/cli/UpdateCommand.java @@ -1,311 +1,313 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. * */ package com.sun.javanet.cvsnews.cli; import com.sun.javanet.cvsnews.CVSChange; import com.sun.javanet.cvsnews.CVSCommit; import com.sun.javanet.cvsnews.CodeChange; import com.sun.javanet.cvsnews.Commit; import com.sun.javanet.cvsnews.SubversionCommit; import org.kohsuke.jnt.IssueEditor; import org.kohsuke.jnt.IssueResolution; import org.kohsuke.jnt.JNIssue; import org.kohsuke.jnt.JNProject; import org.kohsuke.jnt.JavaNet; import org.kohsuke.jnt.ProcessingException; import java.io.File; import java.io.IOException; import java.io.FileInputStream; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.Properties; import java.util.regex.Pattern; import java.net.URL; import hudson.plugins.jira.soap.JiraSoapServiceService; import hudson.plugins.jira.soap.JiraSoapServiceServiceLocator; import hudson.plugins.jira.soap.JiraSoapService; import hudson.plugins.jira.soap.RemoteComment; import hudson.plugins.jira.soap.RemoteFieldValue; /** * Subcommand that reads e-mail from stdin and updates the issue tracker. * * @author Kohsuke Kawaguchi */ public class UpdateCommand extends AbstractIssueCommand { private final File credential = new File(HOME, ".java.net.scm_issue_link"); public int execute() throws Exception { System.out.println("Parsing stdin"); Commit commit = parseStdin(); Set<Issue> issues = parseIssues(commit); System.out.println("Found "+issues); if(issues.isEmpty()) return 0; // no issue link String msg = createUpdateMessage(commit); boolean markedAsFixed = FIXED.matcher(commit.log).find(); JavaNet con = JavaNet.connect(credential); for (Issue issue : issues) { JNProject p = con.getProject(issue.projectName); if(!con.getMyself().getMyProjects().contains(p)) // not a participating project continue; System.out.println("Updating "+issue); try { if (issue.projectName.equals("hudson")) { // update JIRA JiraSoapServiceService jiraSoapServiceGetter = new JiraSoapServiceServiceLocator(); Properties props = new Properties(); props.load(new FileInputStream(credential)); String id = "HUDSON-" + issue.number; JiraSoapService service = jiraSoapServiceGetter.getJirasoapserviceV2(new URL(new URL("http://issues.hudson-ci.org/"), "rpc/soap/jirasoapservice-v2")); String securityToken = service.login(props.getProperty("userName"),props.getProperty("password")); // if an issue doesn't exist an exception will be thrown service.getIssue(securityToken, id); // add comment service.addComment(securityToken, id, new RemoteComment(msg)); // resolve. // comment set here doesn't work. see http://jira.atlassian.com/browse/JRA-11278 - service.progressWorkflowAction(securityToken,id,"5" /*this is apparently the ID for "resolved"*/, + if (markedAsFixed && issues.size()==1) { + service.progressWorkflowAction(securityToken,id,"5" /*this is apparently the ID for "resolved"*/, new RemoteFieldValue[]{new RemoteFieldValue("comment",new String[]{"closing comment"})}); + } } else { // update java.net JNIssue i = p.getIssueTracker().get(issue.number); IssueEditor e = i.beginEdit(); if(markedAsFixed && issues.size()==1) e.resolve(IssueResolution.FIXED); e.commit(msg); } } catch (ProcessingException e) { e.printStackTrace(); return 1; } } return 0; } private String createUpdateMessage(Commit _commit) { StringBuilder buf = new StringBuilder(); buf.append("Code changed in "+_commit.project+"\n"); buf.append(MessageFormat.format("User: {0}\n",_commit.userName)); buf.append("Path:\n"); if (_commit instanceof CVSCommit) { CVSCommit commit = (CVSCommit) _commit; boolean hasFisheye = FISHEYE_CVS_PROJECT.contains(commit.project); for (CVSChange cc : commit.getCodeChanges()) { buf.append(MessageFormat.format(" {0} ({1})\n",cc.fileName,cc.revision)); if(!hasFisheye) buf.append(" "+cc.url+"\n"); } if(hasFisheye) { try { buf.append(MessageFormat.format( " http://fisheye5.cenqua.com/changelog/{0}/?cs={1}:{2}:{3}\n", commit.project, commit.branch==null?"MAIN":commit.branch, commit.userName, DATE_FORMAT.format(commit.getCodeChanges().get(0).determineTimstamp()))); } catch (IOException e) { e.printStackTrace(); buf.append("Failed to compute FishEye link "+e+"\n"); } catch (InterruptedException e) { e.printStackTrace(); buf.append("Failed to compute FishEye link "+e+"\n"); } } } else { SubversionCommit commit = (SubversionCommit) _commit; boolean hasFisheye = FISHEYE_SUBVERSION_PROJECT.contains(commit.project); for (CodeChange cc : commit.getCodeChanges()) { buf.append(MessageFormat.format(" {0}\n",cc.fileName)); if(!hasFisheye) buf.append(" "+cc.url+"\n"); } if(hasFisheye) { buf.append(MessageFormat.format( "http://fisheye4.cenqua.com/changelog/{0}/?cs={1}", commit.project, String.valueOf(commit.revision))); } } buf.append("\n"); buf.append("Log:\n"); buf.append(_commit.log); return buf.toString(); } /** * Marked for marking bug as fixed. */ private static final Pattern FIXED = Pattern.compile("\\[.*(fixed|FIXED).*\\]"); // taken from http://fisheye5.cenqua.com/ private static final Set<String> FISHEYE_CVS_PROJECT = new HashSet<String>(Arrays.asList( "actions", "cejug-classifieds", "clickstream", "databinding", "dwr", "equinox", "fi", "flamingo", "genericjmsra", "genesis", "glassfish", "hyperjaxb", "hyperjaxb2", "hyperubl", "javaserverfaces-sources", "jax-rpc", "jax-rpc-sources", "jax-rpc-tck", "jax-ws-sources", "jax-ws-tck", "jax-wsa", "jax-wsa-sources", "jax-wsa-tck", "jaxb", "jaxb-architecture-document", "jaxb-sources", "jaxb-tck", "jaxb-verification", "jaxb-workshop", "jaxb2-commons", "jaxb2-sources", "jaxmail", "jaxp-sources", "jaxwsunit", "jdic", "jdnc", "jwsdp", "jwsdp-samples", "l2fprod-common", "laf-plugin", "laf-widget", "lg3d", "ognl", "open-esb", "open-jbi-components", "osuser", "osworkflow", "quartz", "saaj", "sailfin", "sbfb", "schoolbus", "semblance", "shard", "sitemesh", "sjsxp", "skinlf", "stax-utils", "substance", "swing-layout", "swinglabs", "swinglabs-demos", "swingworker", "swingx", "tda", "tonic", "truelicense", "truezip", "txw", "webleaf", "webleaftest", "webwork", "wizard", "wsit", "xmlidfilter", "xom", "xsom", "xwork", "xwss")); // taken from http://fisheye4.cenqua.com/ private static final Set<String> FISHEYE_SUBVERSION_PROJECT = new HashSet<String>(Arrays.asList( "appfuse", "appfuse-light", "cougarsquared", "cqme", "diy", "glassfish-svn", "hk2", "hudson", "jax-ws-commons", "jmimeinfo", "jtharness", "jxse-cms", "jxse-metering", "jxse-shell", "jxta-jxse", "mifos", "opencds", "openjdk", "openjfx-compiler", "phoneme", "rife-crud", "rife-jumpstart" )); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); }
false
true
public int execute() throws Exception { System.out.println("Parsing stdin"); Commit commit = parseStdin(); Set<Issue> issues = parseIssues(commit); System.out.println("Found "+issues); if(issues.isEmpty()) return 0; // no issue link String msg = createUpdateMessage(commit); boolean markedAsFixed = FIXED.matcher(commit.log).find(); JavaNet con = JavaNet.connect(credential); for (Issue issue : issues) { JNProject p = con.getProject(issue.projectName); if(!con.getMyself().getMyProjects().contains(p)) // not a participating project continue; System.out.println("Updating "+issue); try { if (issue.projectName.equals("hudson")) { // update JIRA JiraSoapServiceService jiraSoapServiceGetter = new JiraSoapServiceServiceLocator(); Properties props = new Properties(); props.load(new FileInputStream(credential)); String id = "HUDSON-" + issue.number; JiraSoapService service = jiraSoapServiceGetter.getJirasoapserviceV2(new URL(new URL("http://issues.hudson-ci.org/"), "rpc/soap/jirasoapservice-v2")); String securityToken = service.login(props.getProperty("userName"),props.getProperty("password")); // if an issue doesn't exist an exception will be thrown service.getIssue(securityToken, id); // add comment service.addComment(securityToken, id, new RemoteComment(msg)); // resolve. // comment set here doesn't work. see http://jira.atlassian.com/browse/JRA-11278 service.progressWorkflowAction(securityToken,id,"5" /*this is apparently the ID for "resolved"*/, new RemoteFieldValue[]{new RemoteFieldValue("comment",new String[]{"closing comment"})}); } else { // update java.net JNIssue i = p.getIssueTracker().get(issue.number); IssueEditor e = i.beginEdit(); if(markedAsFixed && issues.size()==1) e.resolve(IssueResolution.FIXED); e.commit(msg); } } catch (ProcessingException e) { e.printStackTrace(); return 1; } }
public int execute() throws Exception { System.out.println("Parsing stdin"); Commit commit = parseStdin(); Set<Issue> issues = parseIssues(commit); System.out.println("Found "+issues); if(issues.isEmpty()) return 0; // no issue link String msg = createUpdateMessage(commit); boolean markedAsFixed = FIXED.matcher(commit.log).find(); JavaNet con = JavaNet.connect(credential); for (Issue issue : issues) { JNProject p = con.getProject(issue.projectName); if(!con.getMyself().getMyProjects().contains(p)) // not a participating project continue; System.out.println("Updating "+issue); try { if (issue.projectName.equals("hudson")) { // update JIRA JiraSoapServiceService jiraSoapServiceGetter = new JiraSoapServiceServiceLocator(); Properties props = new Properties(); props.load(new FileInputStream(credential)); String id = "HUDSON-" + issue.number; JiraSoapService service = jiraSoapServiceGetter.getJirasoapserviceV2(new URL(new URL("http://issues.hudson-ci.org/"), "rpc/soap/jirasoapservice-v2")); String securityToken = service.login(props.getProperty("userName"),props.getProperty("password")); // if an issue doesn't exist an exception will be thrown service.getIssue(securityToken, id); // add comment service.addComment(securityToken, id, new RemoteComment(msg)); // resolve. // comment set here doesn't work. see http://jira.atlassian.com/browse/JRA-11278 if (markedAsFixed && issues.size()==1) { service.progressWorkflowAction(securityToken,id,"5" /*this is apparently the ID for "resolved"*/, new RemoteFieldValue[]{new RemoteFieldValue("comment",new String[]{"closing comment"})}); } } else { // update java.net JNIssue i = p.getIssueTracker().get(issue.number); IssueEditor e = i.beginEdit(); if(markedAsFixed && issues.size()==1) e.resolve(IssueResolution.FIXED); e.commit(msg); } } catch (ProcessingException e) { e.printStackTrace(); return 1; } }
diff --git a/src/ratSaccharine/PcoaViaTTest.java b/src/ratSaccharine/PcoaViaTTest.java index f837c2fc..6c8a7524 100644 --- a/src/ratSaccharine/PcoaViaTTest.java +++ b/src/ratSaccharine/PcoaViaTTest.java @@ -1,117 +1,117 @@ /** * Author: [email protected] * This code 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, * provided that any use properly credits the author. * 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 at http://www.gnu.org * * */ package ratSaccharine; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import utils.ConfigReader; import utils.TTest; public class PcoaViaTTest { public static void main(String[] args) throws Exception { BufferedWriter writer = new BufferedWriter(new FileWriter(new File(ConfigReader.getSaccharineRatDir() + File.separator + "pcoaAxes.txt"))); writer.write("axis\tcecum\tcolon\tstool\n"); String[] tissues = { "CECUM", "COLON" ,"STOOL"}; for( int x=1; x <=20; x++) { writer.write( "" + x ); for( String s : tissues) { writer.write("\t" + getPValue(s, x) ); } writer.write("\n"); } writer.flush(); writer.close(); } private static double getPValue( String tissue, int axisNum ) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getSaccharineRatDir() + File.separator + "mergedMapBrayCurtisPCOA.txt" ))); HashMap<String, List<Double>> highCages = new HashMap<String, List<Double>>(); HashMap<String, List<Double>> lowCages = new HashMap<String, List<Double>>(); reader.readLine(); for( String s= reader.readLine(); s != null ; s= reader.readLine()) { String[] splits = s.split("\t"); if(splits[3].equals(tissue)) { - double val = Double.parseDouble(splits[20+axisNum]); + double val = Double.parseDouble(splits[23+axisNum]); String cage = splits[8]; if( splits[7].equals("Low")) addToMap(val, cage, lowCages); else if( splits[7].equals("High")) addToMap(val, cage, highCages); else throw new Exception("No"); } } List<Number> lowVals = new ArrayList<Number>(); List<Number> highVals = new ArrayList<Number>(); for( String s : lowCages.keySet() ) lowVals.add(MedianOfCage.getMedian(lowCages.get(s))); for( String s : highCages.keySet()) highVals.add(MedianOfCage.getMedian(highCages.get(s))); double pValue = 1; try { pValue = TTest.ttestFromNumber(lowVals, highVals).getPValue(); } catch(Exception ex) { } return pValue; } private static void addToMap( double val, String cage, HashMap<String, List<Double>> map ) { List<Double> list = map.get(cage); if( list == null) { list = new ArrayList<Double>(); map.put(cage,list); } list.add(val); } }
true
true
private static double getPValue( String tissue, int axisNum ) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getSaccharineRatDir() + File.separator + "mergedMapBrayCurtisPCOA.txt" ))); HashMap<String, List<Double>> highCages = new HashMap<String, List<Double>>(); HashMap<String, List<Double>> lowCages = new HashMap<String, List<Double>>(); reader.readLine(); for( String s= reader.readLine(); s != null ; s= reader.readLine()) { String[] splits = s.split("\t"); if(splits[3].equals(tissue)) { double val = Double.parseDouble(splits[20+axisNum]); String cage = splits[8]; if( splits[7].equals("Low")) addToMap(val, cage, lowCages); else if( splits[7].equals("High")) addToMap(val, cage, highCages); else throw new Exception("No"); } } List<Number> lowVals = new ArrayList<Number>(); List<Number> highVals = new ArrayList<Number>(); for( String s : lowCages.keySet() ) lowVals.add(MedianOfCage.getMedian(lowCages.get(s))); for( String s : highCages.keySet()) highVals.add(MedianOfCage.getMedian(highCages.get(s))); double pValue = 1; try { pValue = TTest.ttestFromNumber(lowVals, highVals).getPValue(); } catch(Exception ex) { } return pValue; }
private static double getPValue( String tissue, int axisNum ) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(new File( ConfigReader.getSaccharineRatDir() + File.separator + "mergedMapBrayCurtisPCOA.txt" ))); HashMap<String, List<Double>> highCages = new HashMap<String, List<Double>>(); HashMap<String, List<Double>> lowCages = new HashMap<String, List<Double>>(); reader.readLine(); for( String s= reader.readLine(); s != null ; s= reader.readLine()) { String[] splits = s.split("\t"); if(splits[3].equals(tissue)) { double val = Double.parseDouble(splits[23+axisNum]); String cage = splits[8]; if( splits[7].equals("Low")) addToMap(val, cage, lowCages); else if( splits[7].equals("High")) addToMap(val, cage, highCages); else throw new Exception("No"); } } List<Number> lowVals = new ArrayList<Number>(); List<Number> highVals = new ArrayList<Number>(); for( String s : lowCages.keySet() ) lowVals.add(MedianOfCage.getMedian(lowCages.get(s))); for( String s : highCages.keySet()) highVals.add(MedianOfCage.getMedian(highCages.get(s))); double pValue = 1; try { pValue = TTest.ttestFromNumber(lowVals, highVals).getPValue(); } catch(Exception ex) { } return pValue; }
diff --git a/jamwiki-web/src/main/java/org/jamwiki/db/AnsiDataHandler.java b/jamwiki-web/src/main/java/org/jamwiki/db/AnsiDataHandler.java index 1f30dee5..09916c8b 100644 --- a/jamwiki-web/src/main/java/org/jamwiki/db/AnsiDataHandler.java +++ b/jamwiki-web/src/main/java/org/jamwiki/db/AnsiDataHandler.java @@ -1,2086 +1,2090 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.db; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import net.sf.ehcache.Element; import org.apache.commons.lang.StringUtils; import org.jamwiki.DataAccessException; import org.jamwiki.DataHandler; import org.jamwiki.WikiBase; import org.jamwiki.WikiException; import org.jamwiki.WikiMessage; import org.jamwiki.authentication.JAMWikiAuthenticationConfiguration; import org.jamwiki.authentication.RoleImpl; import org.jamwiki.authentication.WikiUserDetails; import org.jamwiki.model.Category; import org.jamwiki.model.LogItem; import org.jamwiki.model.RecentChange; import org.jamwiki.model.Role; import org.jamwiki.model.RoleMap; import org.jamwiki.model.Topic; import org.jamwiki.model.TopicVersion; import org.jamwiki.model.VirtualWiki; import org.jamwiki.model.Watchlist; import org.jamwiki.model.WikiFile; import org.jamwiki.model.WikiFileVersion; import org.jamwiki.model.WikiGroup; import org.jamwiki.model.WikiUser; import org.jamwiki.parser.ParserException; import org.jamwiki.parser.ParserOutput; import org.jamwiki.parser.ParserUtil; import org.jamwiki.utils.Encryption; import org.jamwiki.utils.LinkUtil; import org.jamwiki.utils.NamespaceHandler; import org.jamwiki.utils.Pagination; import org.jamwiki.utils.WikiCache; import org.jamwiki.utils.WikiLink; import org.jamwiki.utils.WikiLogger; import org.jamwiki.utils.WikiUtil; import org.springframework.transaction.TransactionStatus; /** * Default implementation of the {@link org.jamwiki.DataHandler} interface for * ANSI SQL compatible databases. */ public class AnsiDataHandler implements DataHandler { private static final String CACHE_TOPICS = "org.jamwiki.db.AnsiDataHandler.CACHE_TOPICS"; private static final String CACHE_TOPIC_VERSIONS = "org.jamwiki.db.AnsiDataHandler.CACHE_TOPIC_VERSIONS"; private static final String CACHE_USER_BY_USER_ID = "org.jamwiki.db.AnsiDataHandler.CACHE_USER_BY_USER_ID"; private static final String CACHE_USER_BY_USER_NAME = "org.jamwiki.db.AnsiDataHandler.CACHE_USER_BY_USER_NAME"; private static final String CACHE_VIRTUAL_WIKI = "org.jamwiki.db.AnsiDataHandler.CACHE_VIRTUAL_WIKI"; private static final WikiLogger logger = WikiLogger.getLogger(AnsiDataHandler.class.getName()); private final QueryHandler queryHandler = new AnsiQueryHandler(); /** * */ private void addCategory(Category category, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(category.getVirtualWiki()); this.validateCategory(category); try { this.queryHandler().insertCategory(category, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addGroupMember(String username, int groupId, Connection conn) throws DataAccessException { try { this.queryHandler().insertGroupMember(username, groupId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addLogItem(LogItem logItem, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(logItem.getVirtualWiki()); this.validateLogItem(logItem); try { this.queryHandler().insertLogItem(logItem, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addRecentChange(RecentChange change, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(change.getVirtualWiki()); this.validateRecentChange(change); try { this.queryHandler().insertRecentChange(change, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addTopic(Topic topic, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(topic.getVirtualWiki()); try { this.validateTopic(topic); this.queryHandler().insertTopic(topic, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addTopicVersion(TopicVersion topicVersion, Connection conn) throws DataAccessException, WikiException { try { this.validateTopicVersion(topicVersion); this.queryHandler().insertTopicVersion(topicVersion, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addUserDetails(WikiUserDetails userDetails, Connection conn) throws DataAccessException, WikiException { this.validateUserDetails(userDetails); try { this.queryHandler().insertUserDetails(userDetails, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addVirtualWiki(VirtualWiki virtualWiki, Connection conn) throws DataAccessException, WikiException { try { this.validateVirtualWiki(virtualWiki); this.queryHandler().insertVirtualWiki(virtualWiki, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addWatchlistEntry(int virtualWikiId, String topicName, int userId, Connection conn) throws DataAccessException, WikiException { this.validateWatchlistEntry(topicName); try { this.queryHandler().insertWatchlistEntry(virtualWikiId, topicName, userId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addWikiFile(WikiFile wikiFile, Connection conn) throws DataAccessException, WikiException { try { int virtualWikiId = this.lookupVirtualWikiId(wikiFile.getVirtualWiki()); this.validateWikiFile(wikiFile); this.queryHandler().insertWikiFile(wikiFile, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addWikiFileVersion(WikiFileVersion wikiFileVersion, Connection conn) throws DataAccessException, WikiException { try { this.validateWikiFileVersion(wikiFileVersion); this.queryHandler().insertWikiFileVersion(wikiFileVersion, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addWikiGroup(WikiGroup group, Connection conn) throws DataAccessException, WikiException { try { this.validateWikiGroup(group); this.queryHandler().insertWikiGroup(group, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void addWikiUser(WikiUser user, Connection conn) throws DataAccessException, WikiException { try { this.validateWikiUser(user); this.queryHandler().insertWikiUser(user, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public boolean authenticate(String username, String password) throws DataAccessException { boolean result = false; TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); // password is stored encrypted, so encrypt password if (!StringUtils.isBlank(password)) { String encryptedPassword = Encryption.encrypt(password); return this.queryHandler().authenticateUser(username, encryptedPassword, conn); } } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); return result; } /** * Utility method for retrieving a user display name. */ private String authorName(Integer authorId, String authorName) throws DataAccessException { if (authorId != null) { WikiUser user = this.lookupWikiUser(authorId); authorName = user.getUsername(); } return authorName; } /** * */ public boolean canMoveTopic(Topic fromTopic, String destination) throws DataAccessException { Topic toTopic = this.lookupTopic(fromTopic.getVirtualWiki(), destination, false, null); if (toTopic == null || toTopic.getDeleteDate() != null) { // destination doesn't exist or is deleted, so move is OK return true; } if (toTopic.getRedirectTo() != null && toTopic.getRedirectTo().equals(fromTopic.getName())) { // source redirects to destination, so move is OK return true; } return false; } /** * */ private static void checkLength(String value, int maxLength) throws WikiException { if (value != null && value.length() > maxLength) { throw new WikiException(new WikiMessage("error.fieldlength", value, Integer.valueOf(maxLength).toString())); } } /** * */ private void deleteRecentChanges(Topic topic, Connection conn) throws DataAccessException { try { this.queryHandler().deleteRecentChanges(topic.getTopicId(), conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public void deleteTopic(Topic topic, TopicVersion topicVersion) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); if (topicVersion != null) { // delete old recent changes deleteRecentChanges(topic, conn); } // update topic to indicate deleted, add delete topic version. parser output // should be empty since nothing to add to search engine. ParserOutput parserOutput = new ParserOutput(); topic.setDeleteDate(new Timestamp(System.currentTimeMillis())); this.writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks()); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ private void deleteTopicCategories(Topic topic, Connection conn) throws DataAccessException { try { this.queryHandler().deleteTopicCategories(topic.getTopicId(), conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void deleteWatchlistEntry(int virtualWikiId, String topicName, int userId, Connection conn) throws DataAccessException { try { this.queryHandler().deleteWatchlistEntry(virtualWikiId, topicName, userId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public void executeUpgradeQuery(String prop, Connection conn) throws SQLException { this.queryHandler().executeUpgradeQuery(prop, conn); } /** * */ public void executeUpgradeUpdate(String prop, Connection conn) throws SQLException { this.queryHandler().executeUpgradeUpdate(prop, conn); } /** * */ public List<Category> getAllCategories(String virtualWiki, Pagination pagination) throws DataAccessException { List<Category> results = new ArrayList<Category>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().getCategories(virtualWikiId, pagination); while (rs.next()) { Category category = new Category(); category.setName(rs.getString("category_name")); // child topic name not initialized since it is not needed category.setVirtualWiki(virtualWiki); category.setSortKey(rs.getString("sort_key")); // topic type not initialized since it is not needed results.add(category); } } catch (SQLException e) { throw new DataAccessException(e); } return results; } /** * */ public List<Role> getAllRoles() throws DataAccessException { List<Role> results = new ArrayList<Role>(); WikiResultSet rs = null; try { rs = this.queryHandler().getRoles(); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { results.add(this.initRole(rs)); } return results; } /** * */ public List<String> getAllTopicNames(String virtualWiki) throws DataAccessException { List<String> all = new ArrayList<String>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().getAllTopicNames(virtualWikiId); while (rs.next()) { all.add(rs.getString("topic_name")); } } catch (SQLException e) { throw new DataAccessException(e); } return all; } /** * */ public List<WikiFileVersion> getAllWikiFileVersions(String virtualWiki, String topicName, boolean descending) throws DataAccessException { List<WikiFileVersion> all = new ArrayList<WikiFileVersion>(); WikiFile wikiFile = lookupWikiFile(virtualWiki, topicName); if (wikiFile == null) { throw new DataAccessException("No topic exists for " + virtualWiki + " / " + topicName); } try { WikiResultSet rs = this.queryHandler().getAllWikiFileVersions(wikiFile, descending); while (rs.next()) { all.add(initWikiFileVersion(rs)); } } catch (SQLException e) { throw new DataAccessException(e); } return all; } /** * */ public List<LogItem> getLogItems(String virtualWiki, int logType, Pagination pagination, boolean descending) throws DataAccessException { List<LogItem> all = new ArrayList<LogItem>(); WikiResultSet rs = null; int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { rs = this.queryHandler().getLogItems(virtualWikiId, logType, pagination, descending); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { LogItem logItem = initLogItem(rs); all.add(logItem); } return all; } /** * */ public List<RecentChange> getRecentChanges(String virtualWiki, Pagination pagination, boolean descending) throws DataAccessException { List<RecentChange> all = new ArrayList<RecentChange>(); WikiResultSet rs = null; try { rs = this.queryHandler().getRecentChanges(virtualWiki, pagination, descending); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { RecentChange change = initRecentChange(rs); all.add(change); } return all; } /** * */ public List<RoleMap> getRoleMapByLogin(String loginFragment) throws DataAccessException { LinkedHashMap<Integer, RoleMap> roleMaps = new LinkedHashMap<Integer, RoleMap>(); try { WikiResultSet rs = this.queryHandler().getRoleMapByLogin(loginFragment); while (rs.next()) { Integer userId = rs.getInt("wiki_user_id"); RoleMap roleMap = new RoleMap(); if (roleMaps.containsKey(userId)) { roleMap = roleMaps.get(userId); } else { roleMap.setUserId(userId); roleMap.setUserLogin(rs.getString("username")); } roleMap.addRole(rs.getString("authority")); roleMaps.put(userId, roleMap); } } catch (SQLException e) { throw new DataAccessException(e); } return new ArrayList<RoleMap>(roleMaps.values()); } /** * */ public List<RoleMap> getRoleMapByRole(String authority) throws DataAccessException { LinkedHashMap<String, RoleMap> roleMaps = new LinkedHashMap<String, RoleMap>(); try { WikiResultSet rs = this.queryHandler().getRoleMapByRole(authority); while (rs.next()) { int userId = rs.getInt("wiki_user_id"); int groupId = rs.getInt("group_id"); RoleMap roleMap = new RoleMap(); String key = userId + "|" + groupId; if (roleMaps.containsKey(key)) { roleMap = roleMaps.get(key); } else { if (userId > 0) { roleMap.setUserId(userId); roleMap.setUserLogin(rs.getString("username")); } if (groupId > 0) { roleMap.setGroupId(groupId); roleMap.setGroupName(rs.getString("group_name")); } } roleMap.addRole(rs.getString("authority")); roleMaps.put(key, roleMap); } } catch (SQLException e) { throw new DataAccessException(e); } return new ArrayList<RoleMap>(roleMaps.values()); } /** * */ public List<Role> getRoleMapGroup(String groupName) throws DataAccessException { List<Role> results = new ArrayList<Role>(); WikiResultSet rs = null; try { rs = this.queryHandler().getRoleMapGroup(groupName); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { Role role = this.initRole(rs); results.add(role); } return results; } /** * */ public List<RoleMap> getRoleMapGroups() throws DataAccessException { LinkedHashMap<Integer, RoleMap> roleMaps = new LinkedHashMap<Integer, RoleMap>(); try { WikiResultSet rs = this.queryHandler().getRoleMapGroups(); while (rs.next()) { Integer groupId = rs.getInt("group_id"); RoleMap roleMap = new RoleMap(); if (roleMaps.containsKey(groupId)) { roleMap = roleMaps.get(groupId); } else { roleMap.setGroupId(groupId); roleMap.setGroupName(rs.getString("group_name")); } roleMap.addRole(rs.getString("authority")); roleMaps.put(groupId, roleMap); } } catch (SQLException e) { throw new DataAccessException(e); } return new ArrayList<RoleMap>(roleMaps.values()); } /** * */ public List<Role> getRoleMapUser(String login) throws DataAccessException { List<Role> results = new ArrayList<Role>(); WikiResultSet rs = null; try { rs = this.queryHandler().getRoleMapUser(login); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { Role role = this.initRole(rs); results.add(role); } return results; } /** * */ public List<RecentChange> getTopicHistory(String virtualWiki, String topicName, Pagination pagination, boolean descending) throws DataAccessException { List<RecentChange> all = new ArrayList<RecentChange>(); Topic topic = this.lookupTopic(virtualWiki, topicName, true, null); if (topic == null) { return all; } WikiResultSet rs = null; try { rs = this.queryHandler().getTopicHistory(topic.getTopicId(), pagination, descending); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { RecentChange change = initRecentChange(rs); all.add(change); } return all; } /** * */ public List<String> getTopicsAdmin(String virtualWiki, Pagination pagination) throws DataAccessException { List<String> all = new ArrayList<String>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().getTopicsAdmin(virtualWikiId, pagination); while (rs.next()) { String topicName = rs.getString("topic_name"); all.add(topicName); } } catch (SQLException e) { throw new DataAccessException(e); } return all; } /** * */ public List<RecentChange> getUserContributions(String virtualWiki, String userString, Pagination pagination, boolean descending) throws DataAccessException { List<RecentChange> all = new ArrayList<RecentChange>(); WikiResultSet rs = null; try { if (this.lookupWikiUser(userString) != null) { rs = this.queryHandler().getUserContributionsByLogin(virtualWiki, userString, pagination, descending); } else { rs = this.queryHandler().getUserContributionsByUserDisplay(virtualWiki, userString, pagination, descending); } } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { RecentChange change = initRecentChange(rs); all.add(change); } return all; } /** * Return a List of all VirtualWiki objects that exist for the Wiki. */ public List<VirtualWiki> getVirtualWikiList() throws DataAccessException { List<VirtualWiki> results = new ArrayList<VirtualWiki>(); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiResultSet rs = this.queryHandler().getVirtualWikis(conn); while (rs.next()) { VirtualWiki virtualWiki = initVirtualWiki(rs); results.add(virtualWiki); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); return results; } /** * Retrieve a watchlist containing a List of topic ids and topic * names that can be used to determine if a topic is in a user's current * watchlist. */ public Watchlist getWatchlist(String virtualWiki, int userId) throws DataAccessException { List<String> all = new ArrayList<String>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().getWatchlist(virtualWikiId, userId); while (rs.next()) { String topicName = rs.getString("topic_name"); all.add(topicName); } } catch (SQLException e) { throw new DataAccessException(e); } return new Watchlist(virtualWiki, all); } /** * Retrieve a watchlist containing a List of RecentChanges objects * that can be used for display on the Special:Watchlist page. */ public List<RecentChange> getWatchlist(String virtualWiki, int userId, Pagination pagination) throws DataAccessException { List<RecentChange> all = new ArrayList<RecentChange>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); WikiResultSet rs = null; try { rs = this.queryHandler().getWatchlist(virtualWikiId, userId, pagination); } catch (SQLException e) { throw new DataAccessException(e); } while (rs.next()) { RecentChange change = initRecentChange(rs); all.add(change); } return all; } /** * */ private LogItem initLogItem(WikiResultSet rs) throws DataAccessException { try { LogItem logItem = new LogItem(); int userId = rs.getInt("wiki_user_id"); if (userId > 0) { logItem.setUserId(userId); } logItem.setUserDisplayName(rs.getString("display_name")); int topicId = rs.getInt("topic_id"); if (topicId > 0) { logItem.setTopicId(topicId); } int topicVersionId = rs.getInt("topic_version_id"); if (topicVersionId > 0) { logItem.setTopicVersionId(topicVersionId); } logItem.setLogDate(rs.getTimestamp("log_date")); logItem.setLogComment(rs.getString("log_comment")); logItem.setLogParamString(rs.getString("log_params")); logItem.setLogType(rs.getInt("log_type")); String virtualWiki = this.lookupVirtualWikiName(rs.getInt("virtual_wiki_id")); logItem.setVirtualWiki(virtualWiki); return logItem; } catch (SQLException e) { logger.severe("Failure while initializing log item", e); throw new DataAccessException(e); } } /** * */ private RecentChange initRecentChange(WikiResultSet rs) throws DataAccessException { try { RecentChange change = new RecentChange(); int topicVersionId = rs.getInt("topic_version_id"); if (topicVersionId > 0) { change.setTopicVersionId(topicVersionId); } int previousTopicVersionId = rs.getInt("previous_topic_version_id"); if (previousTopicVersionId > 0) { change.setPreviousTopicVersionId(previousTopicVersionId); } int topicId = rs.getInt("topic_id"); if (topicId > 0) { change.setTopicId(topicId); } change.setTopicName(rs.getString("topic_name")); change.setCharactersChanged(rs.getInt("characters_changed")); change.setChangeDate(rs.getTimestamp("change_date")); change.setChangeComment(rs.getString("change_comment")); int userId = rs.getInt("wiki_user_id"); if (userId > 0) { change.setAuthorId(userId); } change.setAuthorName(rs.getString("display_name")); int editType = rs.getInt("edit_type"); if (editType > 0) { change.setEditType(editType); change.initChangeWikiMessageForVersion(editType, rs.getString("log_params")); } int logType = rs.getInt("log_type"); if (logType > 0) { change.setLogType(logType); change.initChangeWikiMessageForLog(logType, rs.getString("log_params")); } change.setVirtualWiki(rs.getString("virtual_wiki_name")); return change; } catch (SQLException e) { logger.severe("Failure while initializing recent change", e); throw new DataAccessException(e); } } /** * */ private Role initRole(WikiResultSet rs) throws DataAccessException { try { Role role = new RoleImpl(rs.getString("role_name")); role.setDescription(rs.getString("role_description")); return role; } catch (SQLException e) { logger.severe("Failure while initializing role", e); throw new DataAccessException(e); } } /** * */ private Topic initTopic(WikiResultSet rs) throws DataAccessException { try { // if a topic by this name has been deleted then there will be // multiple results. the first will be a non-deleted topic (if // one exists), otherwise the last is the most recently deleted // topic. if (rs.size() > 1 && rs.getTimestamp("delete_date") != null) { // go to the last result rs.last(); } int virtualWikiId = rs.getInt("virtual_wiki_id"); String virtualWiki = this.lookupVirtualWikiName(virtualWikiId); Topic topic = new Topic(); topic.setAdminOnly(rs.getInt("topic_admin_only") != 0); topic.setName(rs.getString("topic_name")); topic.setVirtualWiki(virtualWiki); int currentVersionId = rs.getInt("current_version_id"); if (currentVersionId > 0) { topic.setCurrentVersionId(currentVersionId); } topic.setTopicContent(rs.getString("version_content")); // FIXME - Oracle cannot store an empty string - it converts them // to null - so add a hack to work around the problem. if (topic.getTopicContent() == null) { topic.setTopicContent(""); } topic.setTopicId(rs.getInt("topic_id")); topic.setReadOnly(rs.getInt("topic_read_only") != 0); topic.setDeleteDate(rs.getTimestamp("delete_date")); topic.setTopicType(rs.getInt("topic_type")); topic.setRedirectTo(rs.getString("redirect_to")); return topic; } catch (SQLException e) { logger.severe("Failure while initializing topic", e); throw new DataAccessException(e); } } /** * */ private TopicVersion initTopicVersion(WikiResultSet rs) throws DataAccessException { try { TopicVersion topicVersion = new TopicVersion(); topicVersion.setTopicVersionId(rs.getInt("topic_version_id")); topicVersion.setTopicId(rs.getInt("topic_id")); topicVersion.setEditComment(rs.getString("edit_comment")); topicVersion.setVersionContent(rs.getString("version_content")); // FIXME - Oracle cannot store an empty string - it converts them // to null - so add a hack to work around the problem. if (topicVersion.getVersionContent() == null) { topicVersion.setVersionContent(""); } int previousTopicVersionId = rs.getInt("previous_topic_version_id"); if (previousTopicVersionId > 0) { topicVersion.setPreviousTopicVersionId(previousTopicVersionId); } int userId = rs.getInt("wiki_user_id"); if (userId > 0) { topicVersion.setAuthorId(userId); } topicVersion.setCharactersChanged(rs.getInt("characters_changed")); topicVersion.setVersionParamString(rs.getString("version_params")); topicVersion.setEditDate(rs.getTimestamp("edit_date")); topicVersion.setEditType(rs.getInt("edit_type")); topicVersion.setAuthorDisplay(rs.getString("wiki_user_display")); return topicVersion; } catch (SQLException e) { logger.severe("Failure while initializing topic version", e); throw new DataAccessException(e); } } /** * */ private VirtualWiki initVirtualWiki(WikiResultSet rs) throws DataAccessException { try { VirtualWiki virtualWiki = new VirtualWiki(); virtualWiki.setVirtualWikiId(rs.getInt("virtual_wiki_id")); virtualWiki.setName(rs.getString("virtual_wiki_name")); virtualWiki.setDefaultTopicName(rs.getString("default_topic_name")); return virtualWiki; } catch (SQLException e) { logger.severe("Failure while initializing virtual wiki", e); throw new DataAccessException(e); } } /** * */ private WikiFile initWikiFile(WikiResultSet rs) throws DataAccessException { try { int virtualWikiId = rs.getInt("virtual_wiki_id"); String virtualWiki = this.lookupVirtualWikiName(virtualWikiId); WikiFile wikiFile = new WikiFile(); wikiFile.setFileId(rs.getInt("file_id")); wikiFile.setAdminOnly(rs.getInt("file_admin_only") != 0); wikiFile.setFileName(rs.getString("file_name")); wikiFile.setVirtualWiki(virtualWiki); wikiFile.setUrl(rs.getString("file_url")); wikiFile.setTopicId(rs.getInt("topic_id")); wikiFile.setReadOnly(rs.getInt("file_read_only") != 0); wikiFile.setDeleteDate(rs.getTimestamp("delete_date")); wikiFile.setMimeType(rs.getString("mime_type")); wikiFile.setFileSize(rs.getInt("file_size")); return wikiFile; } catch (SQLException e) { logger.severe("Failure while initializing file", e); throw new DataAccessException(e); } } /** * */ private WikiFileVersion initWikiFileVersion(WikiResultSet rs) throws DataAccessException { try { WikiFileVersion wikiFileVersion = new WikiFileVersion(); wikiFileVersion.setFileVersionId(rs.getInt("file_version_id")); wikiFileVersion.setFileId(rs.getInt("file_id")); wikiFileVersion.setUploadComment(rs.getString("upload_comment")); wikiFileVersion.setUrl(rs.getString("file_url")); int userId = rs.getInt("wiki_user_id"); if (userId > 0) { wikiFileVersion.setAuthorId(userId); } wikiFileVersion.setUploadDate(rs.getTimestamp("upload_date")); wikiFileVersion.setMimeType(rs.getString("mime_type")); wikiFileVersion.setAuthorDisplay(rs.getString("wiki_user_display")); wikiFileVersion.setFileSize(rs.getInt("file_size")); return wikiFileVersion; } catch (SQLException e) { logger.severe("Failure while initializing wiki file version", e); throw new DataAccessException(e); } } /** * */ private WikiGroup initWikiGroup(WikiResultSet rs) throws DataAccessException { try { WikiGroup wikiGroup = new WikiGroup(); wikiGroup.setGroupId(rs.getInt("group_id")); wikiGroup.setName(rs.getString("group_name")); wikiGroup.setDescription(rs.getString("group_description")); return wikiGroup; } catch (SQLException e) { logger.severe("Failure while initializing group", e); throw new DataAccessException(e); } } /** * */ private WikiUser initWikiUser(WikiResultSet rs) throws DataAccessException { try { String username = rs.getString("login"); WikiUser user = new WikiUser(username); user.setUserId(rs.getInt("wiki_user_id")); user.setDisplayName(rs.getString("display_name")); user.setCreateDate(rs.getTimestamp("create_date")); user.setLastLoginDate(rs.getTimestamp("last_login_date")); user.setCreateIpAddress(rs.getString("create_ip_address")); user.setLastLoginIpAddress(rs.getString("last_login_ip_address")); user.setDefaultLocale(rs.getString("default_locale")); user.setEmail(rs.getString("email")); user.setEditor(rs.getString("editor")); user.setSignature(rs.getString("signature")); return user; } catch (SQLException e) { logger.severe("Failure while initializing user", e); throw new DataAccessException(e); } } /** * */ public List<Category> lookupCategoryTopics(String virtualWiki, String categoryName) throws DataAccessException { List<Category> results = new ArrayList<Category>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().lookupCategoryTopics(virtualWikiId, categoryName); while (rs.next()) { Category category = new Category(); category.setName(categoryName); category.setVirtualWiki(virtualWiki); category.setChildTopicName(rs.getString("topic_name")); category.setSortKey(rs.getString("sort_key")); category.setTopicType(rs.getInt("topic_type")); results.add(category); } } catch (SQLException e) { throw new DataAccessException(e); } return results; } /** * */ public Topic lookupTopic(String virtualWiki, String topicName, boolean deleteOK, Object transactionObject) throws DataAccessException { if (StringUtils.isBlank(virtualWiki) || StringUtils.isBlank(topicName)) { return null; } String key = WikiCache.key(virtualWiki, topicName); if (transactionObject == null) { // retrieve topic from the cache only if this call is not currently a part // of a transaction to avoid retrieving data that might have been updated // as part of this transaction and would thus now be out of date Element cacheElement = WikiCache.retrieveFromCache(CACHE_TOPICS, key); if (cacheElement != null) { Topic cacheTopic = (Topic)cacheElement.getObjectValue(); return (cacheTopic == null || (!deleteOK && cacheTopic.getDeleteDate() != null)) ? null : new Topic(cacheTopic); } } WikiLink wikiLink = LinkUtil.parseWikiLink(topicName); String namespace = wikiLink.getNamespace(); boolean caseSensitive = true; if (namespace != null) { if (namespace.equals(NamespaceHandler.NAMESPACE_SPECIAL)) { // invalid namespace return null; } if (namespace.equals(NamespaceHandler.NAMESPACE_TEMPLATE) || namespace.equals(NamespaceHandler.NAMESPACE_USER) || namespace.equals(NamespaceHandler.NAMESPACE_CATEGORY)) { // user/template/category namespaces are case-insensitive caseSensitive = false; } } Topic topic = null; TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); WikiResultSet rs = this.queryHandler().lookupTopic(virtualWikiId, topicName, caseSensitive, conn); if (rs.size() != 0) { topic = initTopic(rs); } if (transactionObject == null) { // add topic to the cache only if it is not currently a part of a transaction // to avoid caching something that might need to be rolled back Topic cacheTopic = (topic == null) ? null : new Topic(topic); WikiCache.addToCache(CACHE_TOPICS, key, cacheTopic); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); return (topic == null || (!deleteOK && topic.getDeleteDate() != null)) ? null : topic; } /** * Return a count of all topics, including redirects, comments pages and templates, * currently available on the Wiki. This method excludes deleted topics. * * @param virtualWiki The virtual wiki for which the total topic count is being returned * for. */ public int lookupTopicCount(String virtualWiki) throws DataAccessException { int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().lookupTopicCount(virtualWikiId); return rs.getInt("topic_count"); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public List<String> lookupTopicByType(String virtualWiki, int topicType, Pagination pagination) throws DataAccessException { List<String> results = new ArrayList<String>(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().lookupTopicByType(virtualWikiId, topicType, pagination); while (rs.next()) { results.add(rs.getString("topic_name")); } } catch (SQLException e) { throw new DataAccessException(e); } return results; } /** * */ public TopicVersion lookupTopicVersion(int topicVersionId) throws DataAccessException { Element cacheElement = WikiCache.retrieveFromCache(CACHE_TOPIC_VERSIONS, topicVersionId); if (cacheElement != null) { return (TopicVersion)cacheElement.getObjectValue(); } TopicVersion result = null; TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiResultSet rs = this.queryHandler().lookupTopicVersion(topicVersionId, conn); result = (rs.size() == 0) ? null : this.initTopicVersion(rs); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); WikiCache.addToCache(CACHE_TOPIC_VERSIONS, topicVersionId, result); return result; } /** * */ public VirtualWiki lookupVirtualWiki(String virtualWikiName) throws DataAccessException { Element cacheElement = WikiCache.retrieveFromCache(CACHE_VIRTUAL_WIKI, virtualWikiName); if (cacheElement != null) { return (VirtualWiki)cacheElement.getObjectValue(); } List<VirtualWiki> virtualWikis = this.getVirtualWikiList(); for (VirtualWiki virtualWiki : virtualWikis) { if (virtualWiki.getName().equals(virtualWikiName)) { WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWikiName, virtualWiki); return virtualWiki; } } WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWikiName, null); return null; } /** * */ private int lookupVirtualWikiId(String virtualWikiName) throws DataAccessException { VirtualWiki virtualWiki = this.lookupVirtualWiki(virtualWikiName); WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWikiName, virtualWiki); return (virtualWiki == null) ? -1 : virtualWiki.getVirtualWikiId(); } /** * */ private String lookupVirtualWikiName(int virtualWikiId) throws DataAccessException { Element cacheElement = WikiCache.retrieveFromCache(CACHE_VIRTUAL_WIKI, virtualWikiId); if (cacheElement != null) { VirtualWiki virtualWiki = (VirtualWiki)cacheElement.getObjectValue(); return (virtualWiki == null) ? null : virtualWiki.getName(); } List<VirtualWiki> virtualWikis = this.getVirtualWikiList(); for (VirtualWiki virtualWiki : virtualWikis) { if (virtualWiki.getVirtualWikiId() == virtualWikiId) { WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWikiId, virtualWiki); return virtualWiki.getName(); } } WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWikiId, null); return null; } /** * */ public WikiFile lookupWikiFile(String virtualWiki, String topicName) throws DataAccessException { Topic topic = this.lookupTopic(virtualWiki, topicName, false, null); if (topic == null) { return null; } int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); WikiResultSet rs = null; try { rs = this.queryHandler().lookupWikiFile(virtualWikiId, topic.getTopicId()); } catch (SQLException e) { throw new DataAccessException(e); } return (rs.size() == 0) ? null : initWikiFile(rs); } /** * Return a count of all wiki files currently available on the Wiki. This * method excludes deleted files. * * @param virtualWiki The virtual wiki of the files being retrieved. */ public int lookupWikiFileCount(String virtualWiki) throws DataAccessException { int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); try { WikiResultSet rs = this.queryHandler().lookupWikiFileCount(virtualWikiId); return rs.getInt("file_count"); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public WikiGroup lookupWikiGroup(String groupName) throws DataAccessException { WikiResultSet rs = null; try { rs = this.queryHandler().lookupWikiGroup(groupName); } catch (SQLException e) { throw new DataAccessException(e); } return (rs.size() == 0) ? null : initWikiGroup(rs); } /** * */ public WikiUser lookupWikiUser(int userId) throws DataAccessException { Element cacheElement = WikiCache.retrieveFromCache(CACHE_USER_BY_USER_ID, userId); if (cacheElement != null) { return (WikiUser)cacheElement.getObjectValue(); } WikiUser result = null; TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiResultSet rs = this.queryHandler().lookupWikiUser(userId, conn); result = (rs.size() == 0) ? null : initWikiUser(rs); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); WikiCache.addToCache(CACHE_USER_BY_USER_ID, userId, result); return result; } /** * */ public WikiUser lookupWikiUser(String username) throws DataAccessException { Element cacheElement = WikiCache.retrieveFromCache(CACHE_USER_BY_USER_NAME, username); if (cacheElement != null) { return (WikiUser)cacheElement.getObjectValue(); } WikiUser result = null; TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiResultSet rs = this.queryHandler().lookupWikiUser(username, conn); if (rs.size() == 0) { result = null; } else { int userId = rs.getInt("wiki_user_id"); result = lookupWikiUser(userId); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); WikiCache.addToCache(CACHE_USER_BY_USER_NAME, username, result); return result; } /** * Return a count of all wiki users. */ public int lookupWikiUserCount() throws DataAccessException { try { WikiResultSet rs = this.queryHandler().lookupWikiUserCount(); return rs.getInt("user_count"); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public String lookupWikiUserEncryptedPassword(String username) throws DataAccessException { try { WikiResultSet rs = this.queryHandler().lookupWikiUserEncryptedPassword(username); return (rs.size() == 0) ? null : rs.getString("password"); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ public List<String> lookupWikiUsers(Pagination pagination) throws DataAccessException { List<String> results = new ArrayList<String>(); try { WikiResultSet rs = this.queryHandler().lookupWikiUsers(pagination); while (rs.next()) { results.add(rs.getString("login")); } } catch (SQLException e) { throw new DataAccessException(e); } return results; } /** * */ public void moveTopic(Topic fromTopic, TopicVersion fromVersion, String destination) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); if (!this.canMoveTopic(fromTopic, destination)) { throw new WikiException(new WikiMessage("move.exception.destinationexists", destination)); } Topic toTopic = this.lookupTopic(fromTopic.getVirtualWiki(), destination, false, conn); boolean detinationExistsFlag = (toTopic != null && toTopic.getDeleteDate() == null); if (detinationExistsFlag) { // if the target topic is a redirect to the source topic then the // target must first be deleted. this.deleteTopic(toTopic, null); } // first rename the source topic with the new destination name String fromTopicName = fromTopic.getName(); fromTopic.setName(destination); // only one version needs to create a recent change entry, so do not create a log entry // for the "from" version fromVersion.setRecentChangeAllowed(false); ParserOutput fromParserOutput = ParserUtil.parserOutput(fromTopic.getTopicContent(), fromTopic.getVirtualWiki(), fromTopic.getName()); writeTopic(fromTopic, fromVersion, fromParserOutput.getCategories(), fromParserOutput.getLinks()); // now either create a new topic that is a redirect with the // source topic's old name, or else undelete the new topic and // rename. if (detinationExistsFlag) { // target topic was deleted, so rename and undelete toTopic.setName(fromTopicName); writeTopic(toTopic, null, null, null); this.undeleteTopic(toTopic, null); } else { // create a new topic that redirects to the destination toTopic = fromTopic; toTopic.setTopicId(-1); toTopic.setName(fromTopicName); } String content = ParserUtil.parserRedirectContent(destination); toTopic.setRedirectTo(destination); toTopic.setTopicType(Topic.TYPE_REDIRECT); toTopic.setTopicContent(content); TopicVersion toVersion = fromVersion; toVersion.setTopicVersionId(-1); toVersion.setVersionContent(content); toVersion.setRecentChangeAllowed(true); ParserOutput toParserOutput = ParserUtil.parserOutput(toTopic.getTopicContent(), toTopic.getVirtualWiki(), toTopic.getName()); writeTopic(toTopic, toVersion, toParserOutput.getCategories(), toParserOutput.getLinks()); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (ParserException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ protected QueryHandler queryHandler() { return this.queryHandler; } /** * */ public void reloadLogItems() throws DataAccessException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); List<VirtualWiki> virtualWikis = this.getVirtualWikiList(); for (VirtualWiki virtualWiki : virtualWikis) { this.queryHandler().reloadLogItems(virtualWiki.getVirtualWikiId(), conn); } } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); } /** * */ public void reloadRecentChanges() throws DataAccessException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); this.queryHandler().reloadRecentChanges(conn); } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } DatabaseConnection.commit(status); } /** * */ public void setup(Locale locale, WikiUser user, String username, String encryptedPassword) throws DataAccessException, WikiException { WikiDatabase.initialize(); // determine if database exists try { DatabaseConnection.executeQuery(WikiDatabase.getExistenceValidationQuery()); return; } catch (SQLException e) { // database not yet set up } WikiDatabase.setup(locale, user, username, encryptedPassword); } /** * */ public void setupSpecialPages(Locale locale, WikiUser user, VirtualWiki virtualWiki) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); // create the default topics WikiDatabase.setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_STARTING_POINTS, user, false); WikiDatabase.setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_LEFT_MENU, user, true); WikiDatabase.setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_BOTTOM_AREA, user, true); WikiDatabase.setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_STYLESHEET, user, true); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void undeleteTopic(Topic topic, TopicVersion topicVersion) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); // update topic to indicate deleted, add delete topic version. if // topic has categories or other metadata then parser document is // also needed. ParserOutput parserOutput = ParserUtil.parserOutput(topic.getTopicContent(), topic.getVirtualWiki(), topic.getName()); topic.setDeleteDate(null); this.writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks()); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (ParserException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void updateSpecialPage(Locale locale, String virtualWiki, String topicName, String userDisplay) throws DataAccessException, WikiException { logger.info("Updating special page " + virtualWiki + " / " + topicName); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); String contents = WikiUtil.readSpecialPage(locale, topicName); Topic topic = this.lookupTopic(virtualWiki, topicName, false, conn); int charactersChanged = StringUtils.length(contents) - StringUtils.length(topic.getTopicContent()); topic.setTopicContent(contents); // FIXME - hard coding TopicVersion topicVersion = new TopicVersion(null, userDisplay, "Automatically updated by system upgrade", contents, charactersChanged); ParserOutput parserOutput = ParserUtil.parserOutput(topic.getTopicContent(), virtualWiki, topicName); writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks()); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (IOException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (ParserException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ private void updateTopic(Topic topic, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(topic.getVirtualWiki()); this.validateTopic(topic); try { this.queryHandler().updateTopic(topic, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void updateUserDetails(WikiUserDetails userDetails, Connection conn) throws DataAccessException, WikiException { this.validateUserDetails(userDetails); try { this.queryHandler().updateUserDetails(userDetails, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void updateVirtualWiki(VirtualWiki virtualWiki, Connection conn) throws DataAccessException, WikiException { this.validateVirtualWiki(virtualWiki); try { this.queryHandler().updateVirtualWiki(virtualWiki, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void updateWikiFile(WikiFile wikiFile, Connection conn) throws DataAccessException, WikiException { int virtualWikiId = this.lookupVirtualWikiId(wikiFile.getVirtualWiki()); this.validateWikiFile(wikiFile); try { this.queryHandler().updateWikiFile(wikiFile, virtualWikiId, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void updateWikiGroup(WikiGroup group, Connection conn) throws DataAccessException, WikiException { this.validateWikiGroup(group); try { this.queryHandler().updateWikiGroup(group, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ private void updateWikiUser(WikiUser user, Connection conn) throws DataAccessException, WikiException { this.validateWikiUser(user); try { this.queryHandler().updateWikiUser(user, conn); } catch (SQLException e) { throw new DataAccessException(e); } } /** * */ protected void validateAuthority(String role) throws WikiException { checkLength(role, 30); } /** * */ protected void validateCategory(Category category) throws WikiException { checkLength(category.getName(), 200); checkLength(category.getSortKey(), 200); } /** * */ protected void validateLogItem(LogItem logItem) throws WikiException { checkLength(logItem.getUserDisplayName(), 200); checkLength(logItem.getLogParamString(), 500); logItem.setLogComment(StringUtils.substring(logItem.getLogComment(), 0, 200)); } /** * */ protected void validateRecentChange(RecentChange change) throws WikiException { checkLength(change.getTopicName(), 200); checkLength(change.getAuthorName(), 200); checkLength(change.getVirtualWiki(), 100); change.setChangeComment(StringUtils.substring(change.getChangeComment(), 0, 200)); checkLength(change.getParamString(), 500); } /** * */ protected void validateRole(Role role) throws WikiException { checkLength(role.getAuthority(), 30); role.setDescription(StringUtils.substring(role.getDescription(), 0, 200)); } /** * */ protected void validateTopic(Topic topic) throws WikiException { checkLength(topic.getName(), 200); checkLength(topic.getRedirectTo(), 200); } /** * */ protected void validateTopicVersion(TopicVersion topicVersion) throws WikiException { checkLength(topicVersion.getAuthorDisplay(), 100); checkLength(topicVersion.getVersionParamString(), 500); topicVersion.setEditComment(StringUtils.substring(topicVersion.getEditComment(), 0, 200)); } /** * */ protected void validateUserDetails(WikiUserDetails userDetails) throws WikiException { checkLength(userDetails.getUsername(), 100); // do not throw exception containing password info if (userDetails.getPassword() != null && userDetails.getPassword().length() > 100) { throw new WikiException(new WikiMessage("error.fieldlength", "-", "100")); } } /** * */ protected void validateVirtualWiki(VirtualWiki virtualWiki) throws WikiException { checkLength(virtualWiki.getName(), 100); checkLength(virtualWiki.getDefaultTopicName(), 200); } /** * */ protected void validateWatchlistEntry(String topicName) throws WikiException { checkLength(topicName, 200); } /** * */ protected void validateWikiFile(WikiFile wikiFile) throws WikiException { checkLength(wikiFile.getFileName(), 200); checkLength(wikiFile.getUrl(), 200); checkLength(wikiFile.getMimeType(), 100); } /** * */ protected void validateWikiFileVersion(WikiFileVersion wikiFileVersion) throws WikiException { checkLength(wikiFileVersion.getUrl(), 200); checkLength(wikiFileVersion.getMimeType(), 100); checkLength(wikiFileVersion.getAuthorDisplay(), 100); wikiFileVersion.setUploadComment(StringUtils.substring(wikiFileVersion.getUploadComment(), 0, 200)); } /** * */ protected void validateWikiGroup(WikiGroup group) throws WikiException { checkLength(group.getName(), 30); group.setDescription(StringUtils.substring(group.getDescription(), 0, 200)); } /** * */ protected void validateWikiUser(WikiUser user) throws WikiException { checkLength(user.getUsername(), 100); checkLength(user.getDisplayName(), 100); checkLength(user.getCreateIpAddress(), 39); checkLength(user.getLastLoginIpAddress(), 39); checkLength(user.getDefaultLocale(), 8); checkLength(user.getEmail(), 100); checkLength(user.getEditor(), 50); checkLength(user.getSignature(), 255); } /** * */ public void writeFile(WikiFile wikiFile, WikiFileVersion wikiFileVersion) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiUtil.validateTopicName(wikiFile.getFileName()); if (wikiFile.getFileId() <= 0) { addWikiFile(wikiFile, conn); } else { updateWikiFile(wikiFile, conn); } wikiFileVersion.setFileId(wikiFile.getFileId()); // write version addWikiFileVersion(wikiFileVersion, conn); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeRole(Role role, boolean update) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); this.validateRole(role); if (update) { this.queryHandler().updateRole(role, conn); } else { this.queryHandler().insertRole(role, conn); } // FIXME - add caching } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeRoleMapGroup(int groupId, List<String> roles) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); this.queryHandler().deleteGroupAuthorities(groupId, conn); for (String authority : roles) { this.validateAuthority(authority); this.queryHandler().insertGroupAuthority(groupId, authority, conn); } // refresh the current role requirements JAMWikiAuthenticationConfiguration.resetJamwikiAnonymousAuthorities(); JAMWikiAuthenticationConfiguration.resetDefaultGroupRoles(); } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeRoleMapUser(String username, List<String> roles) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); this.queryHandler().deleteUserAuthorities(username, conn); for (String authority : roles) { this.validateAuthority(authority); this.queryHandler().insertUserAuthority(username, authority, conn); } } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * Commit changes to a topic (and its version) to the database or * filesystem. * * @param topic The topic object that is to be committed. If the topic * id is empty or less than zero then the topic is added, otherwise an * update is performed. * @param topicVersion The version associated with the topic that is * being added. This parameter should never be null UNLESS the change is * not user visible, such as when deleting a topic temporarily during * page moves. * @param categories A mapping of categories and their associated sort keys (if any) * for all categories that are associated with the current topic. * @param links A List of all topic names that are linked to from the * current topic. These will be passed to the search engine to create * searchable metadata. */ public void writeTopic(Topic topic, TopicVersion topicVersion, LinkedHashMap<String, String> categories, List<String> links) throws DataAccessException, WikiException { long start = System.currentTimeMillis(); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); String key = WikiCache.key(topic.getVirtualWiki(), topic.getName()); WikiCache.removeFromCache(WikiBase.CACHE_PARSED_TOPIC_CONTENT, key); WikiCache.removeFromCache(CACHE_TOPICS, key); Connection conn = DatabaseConnection.getConnection(); WikiUtil.validateTopicName(topic.getName()); if (topic.getTopicId() <= 0) { // create the initial topic record addTopic(topic, conn); + } else if (topicVersion == null) { + // if there is no version record then update the topic. if there is a version + // record then the topic will be updated AFTER the version record is created. + this.updateTopic(topic, conn); } if (topicVersion != null) { if (topicVersion.getPreviousTopicVersionId() == null && topic.getCurrentVersionId() != null) { topicVersion.setPreviousTopicVersionId(topic.getCurrentVersionId()); } topicVersion.setTopicId(topic.getTopicId()); topicVersion.initializeVersionParams(topic); // write version addTopicVersion(topicVersion, conn); topic.setCurrentVersionId(topicVersion.getTopicVersionId()); // update the topic AFTER creating the version so that the current_topic_version_id parameter is set properly this.updateTopic(topic, conn); String authorName = this.authorName(topicVersion.getAuthorId(), topicVersion.getAuthorDisplay()); LogItem logItem = LogItem.initLogItem(topic, topicVersion, authorName); RecentChange change = null; if (logItem != null) { this.addLogItem(logItem, conn); change = RecentChange.initRecentChange(logItem); } else { change = RecentChange.initRecentChange(topic, topicVersion, authorName); } if (topicVersion.isRecentChangeAllowed()) { this.addRecentChange(change, conn); } } if (categories != null) { // add / remove categories associated with the topic this.deleteTopicCategories(topic, conn); for (String categoryName : categories.keySet()) { Category category = new Category(); category.setName(categoryName); category.setSortKey(categories.get(categoryName)); category.setVirtualWiki(topic.getVirtualWiki()); category.setChildTopicName(topic.getName()); this.addCategory(category, conn); } } if (links != null) { WikiBase.getSearchEngine().updateInIndex(topic, links); } logger.fine("Wrote topic " + topic.getName() + " with params [categories is null: " + (categories == null) + "] / [links is null: " + (links == null) + "] in " + ((System.currentTimeMillis() - start) / 1000.000) + " s."); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeVirtualWiki(VirtualWiki virtualWiki) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); WikiUtil.validateTopicName(virtualWiki.getName()); if (virtualWiki.getVirtualWikiId() <= 0) { this.addVirtualWiki(virtualWiki, conn); } else { this.updateVirtualWiki(virtualWiki, conn); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); // update the cache AFTER the commit WikiCache.removeFromCache(CACHE_VIRTUAL_WIKI, virtualWiki.getName()); WikiCache.removeFromCache(CACHE_VIRTUAL_WIKI, virtualWiki.getVirtualWikiId()); WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWiki.getName(), virtualWiki); WikiCache.addToCache(CACHE_VIRTUAL_WIKI, virtualWiki.getVirtualWikiId(), virtualWiki); } /** * */ public void writeWatchlistEntry(Watchlist watchlist, String virtualWiki, String topicName, int userId) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); int virtualWikiId = this.lookupVirtualWikiId(virtualWiki); String article = WikiUtil.extractTopicLink(topicName); String comments = WikiUtil.extractCommentsLink(topicName); if (watchlist.containsTopic(topicName)) { // remove from watchlist this.deleteWatchlistEntry(virtualWikiId, article, userId, conn); this.deleteWatchlistEntry(virtualWikiId, comments, userId, conn); watchlist.remove(article); watchlist.remove(comments); } else { // add to watchlist this.addWatchlistEntry(virtualWikiId, article, userId, conn); this.addWatchlistEntry(virtualWikiId, comments, userId, conn); watchlist.add(article); watchlist.add(comments); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeWikiGroup(WikiGroup group) throws DataAccessException, WikiException { TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); if (group.getGroupId() <= 0) { this.addWikiGroup(group, conn); } else { this.updateWikiGroup(group, conn); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); } /** * */ public void writeWikiUser(WikiUser user, String username, String encryptedPassword) throws DataAccessException, WikiException { WikiUtil.validateUserName(user.getUsername()); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); Connection conn = DatabaseConnection.getConnection(); if (user.getUserId() <= 0) { WikiUserDetails userDetails = new WikiUserDetails(username, encryptedPassword, true, true, true, true, JAMWikiAuthenticationConfiguration.getDefaultGroupRoles()); this.addUserDetails(userDetails, conn); this.addWikiUser(user, conn); // add all users to the registered user group this.addGroupMember(user.getUsername(), WikiBase.getGroupRegisteredUser().getGroupId(), conn); // FIXME - reconsider this approach of separate entries for every virtual wiki List<VirtualWiki> virtualWikis = this.getVirtualWikiList(); for (VirtualWiki virtualWiki : virtualWikis) { LogItem logItem = LogItem.initLogItem(user, virtualWiki.getName()); this.addLogItem(logItem, conn); RecentChange change = RecentChange.initRecentChange(logItem); this.addRecentChange(change, conn); } } else { if (!StringUtils.isBlank(encryptedPassword)) { WikiUserDetails userDetails = new WikiUserDetails(username, encryptedPassword, true, true, true, true, JAMWikiAuthenticationConfiguration.getDefaultGroupRoles()); this.updateUserDetails(userDetails, conn); } this.updateWikiUser(user, conn); } } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); // update the cache AFTER the commit WikiCache.removeFromCache(CACHE_USER_BY_USER_ID, user.getUserId()); WikiCache.removeFromCache(CACHE_USER_BY_USER_NAME, user.getUsername()); WikiCache.addToCache(CACHE_USER_BY_USER_ID, user.getUserId(), user); WikiCache.addToCache(CACHE_USER_BY_USER_NAME, user.getUsername(), user); } }
true
true
public void writeTopic(Topic topic, TopicVersion topicVersion, LinkedHashMap<String, String> categories, List<String> links) throws DataAccessException, WikiException { long start = System.currentTimeMillis(); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); String key = WikiCache.key(topic.getVirtualWiki(), topic.getName()); WikiCache.removeFromCache(WikiBase.CACHE_PARSED_TOPIC_CONTENT, key); WikiCache.removeFromCache(CACHE_TOPICS, key); Connection conn = DatabaseConnection.getConnection(); WikiUtil.validateTopicName(topic.getName()); if (topic.getTopicId() <= 0) { // create the initial topic record addTopic(topic, conn); } if (topicVersion != null) { if (topicVersion.getPreviousTopicVersionId() == null && topic.getCurrentVersionId() != null) { topicVersion.setPreviousTopicVersionId(topic.getCurrentVersionId()); } topicVersion.setTopicId(topic.getTopicId()); topicVersion.initializeVersionParams(topic); // write version addTopicVersion(topicVersion, conn); topic.setCurrentVersionId(topicVersion.getTopicVersionId()); // update the topic AFTER creating the version so that the current_topic_version_id parameter is set properly this.updateTopic(topic, conn); String authorName = this.authorName(topicVersion.getAuthorId(), topicVersion.getAuthorDisplay()); LogItem logItem = LogItem.initLogItem(topic, topicVersion, authorName); RecentChange change = null; if (logItem != null) { this.addLogItem(logItem, conn); change = RecentChange.initRecentChange(logItem); } else { change = RecentChange.initRecentChange(topic, topicVersion, authorName); } if (topicVersion.isRecentChangeAllowed()) { this.addRecentChange(change, conn); } } if (categories != null) { // add / remove categories associated with the topic this.deleteTopicCategories(topic, conn); for (String categoryName : categories.keySet()) { Category category = new Category(); category.setName(categoryName); category.setSortKey(categories.get(categoryName)); category.setVirtualWiki(topic.getVirtualWiki()); category.setChildTopicName(topic.getName()); this.addCategory(category, conn); } } if (links != null) { WikiBase.getSearchEngine().updateInIndex(topic, links); } logger.fine("Wrote topic " + topic.getName() + " with params [categories is null: " + (categories == null) + "] / [links is null: " + (links == null) + "] in " + ((System.currentTimeMillis() - start) / 1000.000) + " s."); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); }
public void writeTopic(Topic topic, TopicVersion topicVersion, LinkedHashMap<String, String> categories, List<String> links) throws DataAccessException, WikiException { long start = System.currentTimeMillis(); TransactionStatus status = null; try { status = DatabaseConnection.startTransaction(); String key = WikiCache.key(topic.getVirtualWiki(), topic.getName()); WikiCache.removeFromCache(WikiBase.CACHE_PARSED_TOPIC_CONTENT, key); WikiCache.removeFromCache(CACHE_TOPICS, key); Connection conn = DatabaseConnection.getConnection(); WikiUtil.validateTopicName(topic.getName()); if (topic.getTopicId() <= 0) { // create the initial topic record addTopic(topic, conn); } else if (topicVersion == null) { // if there is no version record then update the topic. if there is a version // record then the topic will be updated AFTER the version record is created. this.updateTopic(topic, conn); } if (topicVersion != null) { if (topicVersion.getPreviousTopicVersionId() == null && topic.getCurrentVersionId() != null) { topicVersion.setPreviousTopicVersionId(topic.getCurrentVersionId()); } topicVersion.setTopicId(topic.getTopicId()); topicVersion.initializeVersionParams(topic); // write version addTopicVersion(topicVersion, conn); topic.setCurrentVersionId(topicVersion.getTopicVersionId()); // update the topic AFTER creating the version so that the current_topic_version_id parameter is set properly this.updateTopic(topic, conn); String authorName = this.authorName(topicVersion.getAuthorId(), topicVersion.getAuthorDisplay()); LogItem logItem = LogItem.initLogItem(topic, topicVersion, authorName); RecentChange change = null; if (logItem != null) { this.addLogItem(logItem, conn); change = RecentChange.initRecentChange(logItem); } else { change = RecentChange.initRecentChange(topic, topicVersion, authorName); } if (topicVersion.isRecentChangeAllowed()) { this.addRecentChange(change, conn); } } if (categories != null) { // add / remove categories associated with the topic this.deleteTopicCategories(topic, conn); for (String categoryName : categories.keySet()) { Category category = new Category(); category.setName(categoryName); category.setSortKey(categories.get(categoryName)); category.setVirtualWiki(topic.getVirtualWiki()); category.setChildTopicName(topic.getName()); this.addCategory(category, conn); } } if (links != null) { WikiBase.getSearchEngine().updateInIndex(topic, links); } logger.fine("Wrote topic " + topic.getName() + " with params [categories is null: " + (categories == null) + "] / [links is null: " + (links == null) + "] in " + ((System.currentTimeMillis() - start) / 1000.000) + " s."); } catch (DataAccessException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } catch (SQLException e) { DatabaseConnection.rollbackOnException(status, e); throw new DataAccessException(e); } catch (WikiException e) { DatabaseConnection.rollbackOnException(status, e); throw e; } DatabaseConnection.commit(status); }
diff --git a/src/net/appositedesigns/fileexplorer/FileListAdapter.java b/src/net/appositedesigns/fileexplorer/FileListAdapter.java index 31f7117..fa609b0 100644 --- a/src/net/appositedesigns/fileexplorer/FileListAdapter.java +++ b/src/net/appositedesigns/fileexplorer/FileListAdapter.java @@ -1,112 +1,118 @@ package net.appositedesigns.fileexplorer; import java.io.File; import java.util.List; import net.apposite.fileexplorer.R; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class FileListAdapter extends BaseAdapter { public static class ViewHolder { public TextView resName; public ImageView resIcon; public ImageView resActions; public TextView resMeta; } private Context mContext; private List<File> files; private LayoutInflater mInflater; public FileListAdapter(Context context, List<File> files) { super(); mContext = context; this.files = files; mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(files == null) { return 0; } else { return files.size(); } } @Override public Object getItem(int arg0) { if(files == null) return null; else return files.get(arg0); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.explorer_item, parent, false); holder = new ViewHolder(); holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName); holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta); holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon); holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } File currentFile = files.get(position); holder.resName.setText(currentFile.getName()); holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile)); holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length())); if(FileExplorerUtils.isProtected(currentFile)) { holder.resActions.setVisibility(View.INVISIBLE); } else { holder.resActions.setVisibility(View.VISIBLE); holder.resActions.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { - Log.d(Constants.TAG, "Clicked list item more button"); - showPopupMenu(v); + try + { + Log.d(Constants.TAG, "Clicked list item more button"); + showPopupMenu(v); + } + catch (Exception e) { + e.printStackTrace(); + } } }); } return convertView; } public void showPopupMenu(View v) { QuickActionHelper helper = new QuickActionHelper(mContext); helper.onShowBar(v); } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.explorer_item, parent, false); holder = new ViewHolder(); holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName); holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta); holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon); holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } File currentFile = files.get(position); holder.resName.setText(currentFile.getName()); holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile)); holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length())); if(FileExplorerUtils.isProtected(currentFile)) { holder.resActions.setVisibility(View.INVISIBLE); } else { holder.resActions.setVisibility(View.VISIBLE); holder.resActions.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d(Constants.TAG, "Clicked list item more button"); showPopupMenu(v); } }); } return convertView; }
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.explorer_item, parent, false); holder = new ViewHolder(); holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName); holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta); holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon); holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } File currentFile = files.get(position); holder.resName.setText(currentFile.getName()); holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile)); holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length())); if(FileExplorerUtils.isProtected(currentFile)) { holder.resActions.setVisibility(View.INVISIBLE); } else { holder.resActions.setVisibility(View.VISIBLE); holder.resActions.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { Log.d(Constants.TAG, "Clicked list item more button"); showPopupMenu(v); } catch (Exception e) { e.printStackTrace(); } } }); } return convertView; }
diff --git a/test/org/guanxi/test/common/filters/GenericDecoderTest.java b/test/org/guanxi/test/common/filters/GenericDecoderTest.java index c9a614b..bd320a1 100644 --- a/test/org/guanxi/test/common/filters/GenericDecoderTest.java +++ b/test/org/guanxi/test/common/filters/GenericDecoderTest.java @@ -1,203 +1,203 @@ /** * */ package org.guanxi.test.common.filters; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import org.guanxi.common.filters.GenericDecoderSubclass; import org.guanxi.common.filters.GenericEncoderSubclass; import org.guanxi.test.TestUtils; import org.junit.Test; /** * @author matthew * */ public class GenericDecoderTest { /** * This will test passing strings to the decoder * that do not feature the control character. * @throws IOException */ @Test public void testNoDecoding() throws IOException { GenericDecoderSubclass decoder; String input; StringBuffer buffer; StringWriter writer; writer = new StringWriter(); buffer = writer.getBuffer(); decoder = new GenericDecoderSubclass(writer, (char)0); for ( int i = 0;i < 100;i++ ) { input = TestUtils.randomString(100); decoder.write(input); assertEquals("GenericDecoder has altered the input in an invalid way", input, buffer.toString()); buffer.delete(0, buffer.length()); } } /** * This tests the result of writing an invalid escape sequence to the * decoder. * * @throws IOException * */ @Test(expected = NumberFormatException.class) public void testInvalidEscapes() throws IOException { GenericDecoderSubclass decoder; decoder = new GenericDecoderSubclass(new StringWriter(), '%'); // the escape sequences are the escape character followed by // two hexadecimal characters. therefore anything outside the // range 0-9,a-f is invalid decoder.write("aaa%zzaaa"); } /** * This tests known decoding sequences. * * @throws IOException */ @Test public void testKnownEscapes() throws IOException { GenericDecoderSubclass decoder; StringBuffer buffer; StringWriter writer; writer = new StringWriter(); buffer = writer.getBuffer(); decoder = new GenericDecoderSubclass(writer, '%'); for ( String[] currentPair : new String[][]{ new String[] { "aaa", "aaa" }, new String[] { "%2A", "*" }, new String[] { "%2a", "*" }, new String[] { "%2525", "%25" }, new String[] { "25%25", "25%" }, }) { decoder.write(currentPair[0]); assertEquals("GenericDecoder has altered the input in an invalid way", currentPair[1], buffer.toString()); buffer.delete(0, buffer.length()); } } /** * This uses the generic encoder to test the decoding of the generic decoder * with random strings and random escape characters * * @throws IOException */ @Test public void testRandomEscapes() throws IOException { // This performs only encoding of the control character class GenericEncoder extends GenericEncoderSubclass { // This is the character that starts any escape sequence protected char controlCharacter; public GenericEncoder(Writer writer, char controlCharacter) { super(writer); this.controlCharacter = controlCharacter; } @Override protected String escape(char c) { return controlCharacter + String.format("%02X", (int)c); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter; } }; // this encodes every character class GenericEncodeEverything extends GenericEncoder { public GenericEncodeEverything(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return true; } } // this randomly selects characters to encode. // the control character is always encoded class GenericEncodeRandom extends GenericEncoder { public GenericEncodeRandom(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter || (Math.abs(TestUtils.random.nextInt()) & 1) == 0; // using & 1 because this is equivalent to % 2 but faster } } StringBuffer encoderBuffer, decoderBuffer; StringWriter encoderWriter, decoderWriter; GenericEncoder encoder; GenericDecoderSubclass decoder; String input; char controlCharacter; encoderWriter = new StringWriter(); encoderBuffer = encoderWriter.getBuffer(); decoderWriter = new StringWriter(); decoderBuffer = decoderWriter.getBuffer(); for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncoder(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); - assertEquals("GenericDecoder does not decode what GenericEncoder produces", input, decoderBuffer.toString()); + assertEquals("GenericDecoder does not decode what GenericEncoder produces", input.toString(), decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeEverything(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeEverything produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeRandom(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeRandom produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } } }
true
true
public void testRandomEscapes() throws IOException { // This performs only encoding of the control character class GenericEncoder extends GenericEncoderSubclass { // This is the character that starts any escape sequence protected char controlCharacter; public GenericEncoder(Writer writer, char controlCharacter) { super(writer); this.controlCharacter = controlCharacter; } @Override protected String escape(char c) { return controlCharacter + String.format("%02X", (int)c); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter; } }; // this encodes every character class GenericEncodeEverything extends GenericEncoder { public GenericEncodeEverything(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return true; } } // this randomly selects characters to encode. // the control character is always encoded class GenericEncodeRandom extends GenericEncoder { public GenericEncodeRandom(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter || (Math.abs(TestUtils.random.nextInt()) & 1) == 0; // using & 1 because this is equivalent to % 2 but faster } } StringBuffer encoderBuffer, decoderBuffer; StringWriter encoderWriter, decoderWriter; GenericEncoder encoder; GenericDecoderSubclass decoder; String input; char controlCharacter; encoderWriter = new StringWriter(); encoderBuffer = encoderWriter.getBuffer(); decoderWriter = new StringWriter(); decoderBuffer = decoderWriter.getBuffer(); for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncoder(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncoder produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeEverything(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeEverything produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeRandom(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeRandom produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } }
public void testRandomEscapes() throws IOException { // This performs only encoding of the control character class GenericEncoder extends GenericEncoderSubclass { // This is the character that starts any escape sequence protected char controlCharacter; public GenericEncoder(Writer writer, char controlCharacter) { super(writer); this.controlCharacter = controlCharacter; } @Override protected String escape(char c) { return controlCharacter + String.format("%02X", (int)c); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter; } }; // this encodes every character class GenericEncodeEverything extends GenericEncoder { public GenericEncodeEverything(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return true; } } // this randomly selects characters to encode. // the control character is always encoded class GenericEncodeRandom extends GenericEncoder { public GenericEncodeRandom(Writer writer, char controlCharacter) { super(writer, controlCharacter); } @Override protected boolean requiresEscaping(char c) { return c == controlCharacter || (Math.abs(TestUtils.random.nextInt()) & 1) == 0; // using & 1 because this is equivalent to % 2 but faster } } StringBuffer encoderBuffer, decoderBuffer; StringWriter encoderWriter, decoderWriter; GenericEncoder encoder; GenericDecoderSubclass decoder; String input; char controlCharacter; encoderWriter = new StringWriter(); encoderBuffer = encoderWriter.getBuffer(); decoderWriter = new StringWriter(); decoderBuffer = decoderWriter.getBuffer(); for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncoder(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncoder produces", input.toString(), decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeEverything(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeEverything produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } for ( int i = 0;i < 100;i++ ) { controlCharacter = TestUtils.randomString('1').toCharArray()[0]; encoder = new GenericEncodeRandom(encoderWriter, controlCharacter); decoder = new GenericDecoderSubclass(decoderWriter, controlCharacter); input = TestUtils.randomString(100); encoder.write(input); decoder.write(encoderBuffer.toString()); assertEquals("GenericDecoder does not decode what GenericEncodeRandom produces", input, decoderBuffer.toString()); encoderBuffer.delete(0, encoderBuffer.length()); decoderBuffer.delete(0, decoderBuffer.length()); } }
diff --git a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/EuropeanaAggregationFieldInput.java b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/EuropeanaAggregationFieldInput.java index 1a9660ff..3f693d24 100644 --- a/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/EuropeanaAggregationFieldInput.java +++ b/corelib-solr/src/main/java/eu/europeana/corelib/solr/server/importer/util/EuropeanaAggregationFieldInput.java @@ -1,312 +1,320 @@ /* * 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.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.solr.common.SolrInputDocument; import com.google.code.morphia.query.UpdateOperations; import eu.europeana.corelib.definitions.jibx.AggregatedCHO; import eu.europeana.corelib.definitions.jibx.Aggregates; import eu.europeana.corelib.definitions.jibx.EuropeanaAggregationType; import eu.europeana.corelib.definitions.jibx.HasView; import eu.europeana.corelib.definitions.jibx.IsShownBy; import eu.europeana.corelib.definitions.jibx.LandingPage; import eu.europeana.corelib.definitions.jibx.Preview; import eu.europeana.corelib.definitions.model.EdmLabel; import eu.europeana.corelib.definitions.solr.entity.EuropeanaAggregation; import eu.europeana.corelib.definitions.solr.entity.WebResource; import eu.europeana.corelib.solr.MongoServer; import eu.europeana.corelib.solr.entity.EuropeanaAggregationImpl; import eu.europeana.corelib.solr.entity.WebResourceImpl; import eu.europeana.corelib.solr.server.EdmMongoServer; import eu.europeana.corelib.solr.utils.MongoUtils; import eu.europeana.corelib.solr.utils.SolrUtils; /** * Constructor of a Europeana Aggregation * * @author Yorgos.Mamakis@ kb.nl * */ public final class EuropeanaAggregationFieldInput { /** * The prefix of a valid europeana record in the portal */ private final static String EUROPEANA_URI = "http://www.europeana.eu/portal/record"; public EuropeanaAggregationFieldInput() { } /** * Create the corresponding EuropeanaAggregation fields in a solr document * * @param aggregation * The EuropeanaAggregation to store * @param solrInputDocument * The solr doocument to save the EuropeanaAggregation in * @return * @throws InstantiationException * @throws IllegalAccessException */ public SolrInputDocument createAggregationSolrFields( EuropeanaAggregationType aggregation, SolrInputDocument solrInputDocument) throws InstantiationException, IllegalAccessException { solrInputDocument = SolrUtils.addFieldFromResourceOrLiteral( solrInputDocument, aggregation.getCreator(), EdmLabel.EUROPEANA_AGGREGATION_DC_CREATOR); solrInputDocument = SolrUtils.addFieldFromLiteral(solrInputDocument, aggregation.getCountry(), EdmLabel.EUROPEANA_AGGREGATION_EDM_COUNTRY); solrInputDocument.addField( EdmLabel.EDM_EUROPEANA_AGGREGATION.toString(), aggregation.getAbout()); if (aggregation.getHasViewList() != null) { for (HasView hasView : aggregation.getHasViewList()) { solrInputDocument.addField( EdmLabel.EUROPEANA_AGGREGATION_EDM_HASVIEW.toString(), hasView.getResource()); } } solrInputDocument.addField(EdmLabel.EUROPEANA_AGGREGATION_EDM_ISSHOWNBY .toString(), aggregation.getIsShownBy() != null ? aggregation .getIsShownBy().getResource() : null); solrInputDocument .addField( EdmLabel.EUROPEANA_AGGREGATION_EDM_LANDINGPAGE .toString(), aggregation.getLandingPage() != null ? aggregation .getLandingPage().getResource() : EUROPEANA_URI + aggregation.getAggregatedCHO().getResource()); solrInputDocument = SolrUtils.addFieldFromLiteral(solrInputDocument, aggregation.getLanguage(), EdmLabel.EUROPEANA_AGGREGATION_EDM_LANGUAGE); solrInputDocument = SolrUtils.addFieldFromResourceOrLiteral( solrInputDocument, aggregation.getRights(), EdmLabel.EUROPEANA_AGGREGATION_EDM_RIGHTS); solrInputDocument.addField( EdmLabel.EUROPEANA_AGGREGATION_ORE_AGGREGATEDCHO.toString(), aggregation.getAggregatedCHO() != null ? aggregation .getAggregatedCHO().getResource() : null); solrInputDocument.addField(EdmLabel.EUROPEANA_AGGREGATION_EDM_PREVIEW .toString(), aggregation.getPreview() != null ? aggregation .getPreview().getResource() : null); if (aggregation.getAggregateList() != null) { for (Aggregates aggregates : aggregation.getAggregateList()) { solrInputDocument.addField( EdmLabel.EUROPEANA_AGGREGATION_ORE_AGGREGATES .toString(), aggregates.getResource()); } } return solrInputDocument; } /** * Append a web resource to a Europeana Aggregation * * @param aggregation * The EuropeanaAggregation * @param webResource * The webResource to append * @param mongoServer * The mongo Server to save both the Aggregation and the * WebResource * @return * @throws InstantiationException * @throws IllegalAccessException */ @SuppressWarnings("unchecked") public EuropeanaAggregation appendWebResource( EuropeanaAggregation aggregation, WebResourceImpl webResource, MongoServer mongoServer) throws InstantiationException, IllegalAccessException { if (belongsTo(aggregation, webResource)) { List<WebResource> webResources = (List<WebResource>) (aggregation .getWebResources() != null ? aggregation.getWebResources() : new ArrayList<WebResource>()); aggregation.setWebResources(webResources); if (aggregation.getAbout() != null) { MongoUtils.update(EuropeanaAggregationImpl.class, aggregation.getAbout(), mongoServer, "webResources", webResources); } else { mongoServer.getDatastore().save(aggregation); } } return aggregation; } /** * Append a list of web resource to a Europeana Aggregation * * @param aggregation * The EuropeanaAggregation * @param webResources * The list of webResources to append * @param mongoServer * The mongo Server to save both the Aggregation and the * WebResource * @return * @throws InstantiationException * @throws IllegalAccessException */ public EuropeanaAggregation appendWebResource( EuropeanaAggregation aggregation, List<WebResource> webResources, MongoServer mongoServer) throws InstantiationException, IllegalAccessException { aggregation.setWebResources(webResources); if (aggregation.getAbout() != null) { MongoUtils.update(EuropeanaAggregationImpl.class, aggregation.getAbout(), mongoServer, "webResources", webResources); } else { mongoServer.getDatastore().save(aggregation); } return aggregation; } /** * Create a EuropeanaAggregation to save in MongoDB storage * * @param aggregation * The RDF EuropeanaAggregation representation * @param mongoServer * The MongoServer to use to save the EuropeanaAggregation * @return the EuropeanaAggregation created * @throws InstantiationException * @throws IllegalAccessException */ public EuropeanaAggregationImpl createAggregationMongoFields( eu.europeana.corelib.definitions.jibx.EuropeanaAggregationType aggregation, MongoServer mongoServer) throws InstantiationException, IllegalAccessException { EuropeanaAggregationImpl mongoAggregation = new EuropeanaAggregationImpl(); UpdateOperations<EuropeanaAggregationImpl> ops = mongoServer .getDatastore().createUpdateOperations( EuropeanaAggregationImpl.class); mongoAggregation.setAbout(aggregation.getAbout()); Map<String, List<String>> creator = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getCreator()); if (creator != null) { ops.set("dcCreator", creator); mongoAggregation.setDcCreator(creator); } Map<String, List<String>> country = MongoUtils .createLiteralMapFromString(aggregation.getCountry()); if (country != null) { mongoAggregation.setEdmCountry(country); ops.set("edmCountry", country); } String isShownBy = SolrUtils.exists(IsShownBy.class, aggregation.getIsShownBy()).getResource(); if (isShownBy != null) { mongoAggregation.setEdmIsShownBy(isShownBy); ops.set("edmIsShownBy", isShownBy); } String landingPage = SolrUtils.exists(LandingPage.class, aggregation.getLandingPage()).getResource(); + if(landingPage!=null){ mongoAggregation.setEdmLandingPage(landingPage); ops.set("edmLandingPage", landingPage); + } else { + mongoAggregation.setEdmLandingPage(EUROPEANA_URI + + aggregation.getAggregatedCHO().getResource()); + ops.set("edmLandingPage", EUROPEANA_URI + + aggregation.getAggregatedCHO().getResource()); + } Map<String, List<String>> language = MongoUtils .createLiteralMapFromString(aggregation.getLanguage()); mongoAggregation.setEdmLanguage(language); ops.set("edmLanguage", language); String agCHO = SolrUtils.exists(AggregatedCHO.class, aggregation.getAggregatedCHO()).getResource(); mongoAggregation.setAggregatedCHO(agCHO); ops.set("aggregatedCHO", agCHO); Map<String, List<String>> edmRights = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getRights()); if (edmRights != null) { mongoAggregation.setEdmRights(edmRights); ops.set("edmRights", edmRights); } String[] aggregates = SolrUtils.resourceListToArray(aggregation .getAggregateList()); if (aggregates != null) { mongoAggregation.setAggregates(aggregates); ops.set("aggregates", aggregates); } String[] hasViewList = SolrUtils.resourceListToArray(aggregation .getHasViewList()); mongoAggregation.setEdmHasView(hasViewList); ops.set("edmHasView", hasViewList); String preview = SolrUtils.exists(Preview.class, aggregation.getPreview()).getResource(); if(preview!=null){ mongoAggregation.setEdmPreview(preview); ops.set("edmPreview", preview); } else { mongoAggregation.setEdmPreview(EUROPEANA_URI+agCHO+"&size=BRIEF_DOC"); + ops.set("edmPreview", EUROPEANA_URI+agCHO+"&size=BRIEF_DOC"); } EuropeanaAggregationImpl retrievedAggregation = ((EdmMongoServer) mongoServer) .getDatastore().find(EuropeanaAggregationImpl.class) .filter("about", mongoAggregation.getAbout()).get(); if (retrievedAggregation != null) { mongoServer.getDatastore().update(retrievedAggregation, ops); } else { mongoServer.getDatastore().save(mongoAggregation); } return mongoAggregation; } /** * Check if a webResource belongs to a EuropeanaAggregation * @param aggregation The EuropeanaAggregation to check against * @param webResource The WebResource to check * @return true if it belongs to the EuropeanaAggregation, false otherwise */ private boolean belongsTo(EuropeanaAggregation aggregation, WebResource webResource) { if (aggregation.getEdmHasView() != null) { for (String hasView : aggregation.getEdmHasView()) { if (StringUtils.equals(hasView, webResource.getAbout())) { return true; } } } if (aggregation.getEdmIsShownBy() != null) { if (StringUtils.equals(aggregation.getEdmIsShownBy(), webResource.getAbout())) { return true; } } return false; } }
false
true
public EuropeanaAggregationImpl createAggregationMongoFields( eu.europeana.corelib.definitions.jibx.EuropeanaAggregationType aggregation, MongoServer mongoServer) throws InstantiationException, IllegalAccessException { EuropeanaAggregationImpl mongoAggregation = new EuropeanaAggregationImpl(); UpdateOperations<EuropeanaAggregationImpl> ops = mongoServer .getDatastore().createUpdateOperations( EuropeanaAggregationImpl.class); mongoAggregation.setAbout(aggregation.getAbout()); Map<String, List<String>> creator = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getCreator()); if (creator != null) { ops.set("dcCreator", creator); mongoAggregation.setDcCreator(creator); } Map<String, List<String>> country = MongoUtils .createLiteralMapFromString(aggregation.getCountry()); if (country != null) { mongoAggregation.setEdmCountry(country); ops.set("edmCountry", country); } String isShownBy = SolrUtils.exists(IsShownBy.class, aggregation.getIsShownBy()).getResource(); if (isShownBy != null) { mongoAggregation.setEdmIsShownBy(isShownBy); ops.set("edmIsShownBy", isShownBy); } String landingPage = SolrUtils.exists(LandingPage.class, aggregation.getLandingPage()).getResource(); mongoAggregation.setEdmLandingPage(landingPage); ops.set("edmLandingPage", landingPage); Map<String, List<String>> language = MongoUtils .createLiteralMapFromString(aggregation.getLanguage()); mongoAggregation.setEdmLanguage(language); ops.set("edmLanguage", language); String agCHO = SolrUtils.exists(AggregatedCHO.class, aggregation.getAggregatedCHO()).getResource(); mongoAggregation.setAggregatedCHO(agCHO); ops.set("aggregatedCHO", agCHO); Map<String, List<String>> edmRights = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getRights()); if (edmRights != null) { mongoAggregation.setEdmRights(edmRights); ops.set("edmRights", edmRights); } String[] aggregates = SolrUtils.resourceListToArray(aggregation .getAggregateList()); if (aggregates != null) { mongoAggregation.setAggregates(aggregates); ops.set("aggregates", aggregates); } String[] hasViewList = SolrUtils.resourceListToArray(aggregation .getHasViewList()); mongoAggregation.setEdmHasView(hasViewList); ops.set("edmHasView", hasViewList); String preview = SolrUtils.exists(Preview.class, aggregation.getPreview()).getResource(); if(preview!=null){ mongoAggregation.setEdmPreview(preview); ops.set("edmPreview", preview); } else { mongoAggregation.setEdmPreview(EUROPEANA_URI+agCHO+"&size=BRIEF_DOC"); } EuropeanaAggregationImpl retrievedAggregation = ((EdmMongoServer) mongoServer) .getDatastore().find(EuropeanaAggregationImpl.class) .filter("about", mongoAggregation.getAbout()).get(); if (retrievedAggregation != null) { mongoServer.getDatastore().update(retrievedAggregation, ops); } else { mongoServer.getDatastore().save(mongoAggregation); } return mongoAggregation; }
public EuropeanaAggregationImpl createAggregationMongoFields( eu.europeana.corelib.definitions.jibx.EuropeanaAggregationType aggregation, MongoServer mongoServer) throws InstantiationException, IllegalAccessException { EuropeanaAggregationImpl mongoAggregation = new EuropeanaAggregationImpl(); UpdateOperations<EuropeanaAggregationImpl> ops = mongoServer .getDatastore().createUpdateOperations( EuropeanaAggregationImpl.class); mongoAggregation.setAbout(aggregation.getAbout()); Map<String, List<String>> creator = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getCreator()); if (creator != null) { ops.set("dcCreator", creator); mongoAggregation.setDcCreator(creator); } Map<String, List<String>> country = MongoUtils .createLiteralMapFromString(aggregation.getCountry()); if (country != null) { mongoAggregation.setEdmCountry(country); ops.set("edmCountry", country); } String isShownBy = SolrUtils.exists(IsShownBy.class, aggregation.getIsShownBy()).getResource(); if (isShownBy != null) { mongoAggregation.setEdmIsShownBy(isShownBy); ops.set("edmIsShownBy", isShownBy); } String landingPage = SolrUtils.exists(LandingPage.class, aggregation.getLandingPage()).getResource(); if(landingPage!=null){ mongoAggregation.setEdmLandingPage(landingPage); ops.set("edmLandingPage", landingPage); } else { mongoAggregation.setEdmLandingPage(EUROPEANA_URI + aggregation.getAggregatedCHO().getResource()); ops.set("edmLandingPage", EUROPEANA_URI + aggregation.getAggregatedCHO().getResource()); } Map<String, List<String>> language = MongoUtils .createLiteralMapFromString(aggregation.getLanguage()); mongoAggregation.setEdmLanguage(language); ops.set("edmLanguage", language); String agCHO = SolrUtils.exists(AggregatedCHO.class, aggregation.getAggregatedCHO()).getResource(); mongoAggregation.setAggregatedCHO(agCHO); ops.set("aggregatedCHO", agCHO); Map<String, List<String>> edmRights = MongoUtils .createResourceOrLiteralMapFromString(aggregation.getRights()); if (edmRights != null) { mongoAggregation.setEdmRights(edmRights); ops.set("edmRights", edmRights); } String[] aggregates = SolrUtils.resourceListToArray(aggregation .getAggregateList()); if (aggregates != null) { mongoAggregation.setAggregates(aggregates); ops.set("aggregates", aggregates); } String[] hasViewList = SolrUtils.resourceListToArray(aggregation .getHasViewList()); mongoAggregation.setEdmHasView(hasViewList); ops.set("edmHasView", hasViewList); String preview = SolrUtils.exists(Preview.class, aggregation.getPreview()).getResource(); if(preview!=null){ mongoAggregation.setEdmPreview(preview); ops.set("edmPreview", preview); } else { mongoAggregation.setEdmPreview(EUROPEANA_URI+agCHO+"&size=BRIEF_DOC"); ops.set("edmPreview", EUROPEANA_URI+agCHO+"&size=BRIEF_DOC"); } EuropeanaAggregationImpl retrievedAggregation = ((EdmMongoServer) mongoServer) .getDatastore().find(EuropeanaAggregationImpl.class) .filter("about", mongoAggregation.getAbout()).get(); if (retrievedAggregation != null) { mongoServer.getDatastore().update(retrievedAggregation, ops); } else { mongoServer.getDatastore().save(mongoAggregation); } return mongoAggregation; }
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java index a89ea4b98..1c3b504c3 100644 --- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java +++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/DataInputStream.java @@ -1,154 +1,154 @@ /* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package java.io; import com.google.gwt.corp.compatibility.Numbers; public class DataInputStream extends InputStream implements DataInput { private final InputStream is; public DataInputStream (final InputStream is) { this.is = is; } @Override public int read () throws IOException { return is.read(); } public boolean readBoolean () throws IOException { return readByte() != 0; } public byte readByte () throws IOException { int i = read(); if (i == -1) { throw new EOFException(); } return (byte)i; } public char readChar () throws IOException { int a = is.read(); int b = readUnsignedByte(); return (char)((a << 8) | b); } public double readDouble () throws IOException { return Double.longBitsToDouble(readLong()); } public float readFloat () throws IOException { return Numbers.intBitsToFloat(readInt()); } public void readFully (byte[] b) throws IOException { readFully(b, 0, b.length); } public void readFully (byte[] b, int off, int len) throws IOException { while (len > 0) { int count = is.read(b, off, len); if (count <= 0) { throw new EOFException(); } off += count; len -= count; } } public int readInt () throws IOException { int a = is.read(); int b = is.read(); int c = is.read(); int d = readUnsignedByte(); return (a << 24) | (b << 16) | (c << 8) | d; } public String readLine () throws IOException { throw new RuntimeException("readline NYI"); } public long readLong () throws IOException { long a = readInt(); long b = readInt() & 0x0ffffffff; return (a << 32) | b; } public short readShort () throws IOException { int a = is.read(); int b = readUnsignedByte(); return (short)((a << 8) | b); } public String readUTF () throws IOException { int bytes = readUnsignedShort(); StringBuilder sb = new StringBuilder(); while (bytes > 0) { bytes -= readUtfChar(sb); } return sb.toString(); } private int readUtfChar (StringBuilder sb) throws IOException { int a = readUnsignedByte(); if ((a & 0x80) == 0) { sb.append((char)a); return 1; } - if ((a & 0xe0) == 0xb0) { + if ((a & 0xe0) == 0xc0) { int b = readUnsignedByte(); sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F))); return 2; } if ((a & 0xf0) == 0xe0) { - int b = is.read(); + int b = readUnsignedByte(); int c = readUnsignedByte(); sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); return 3; } throw new UTFDataFormatException(); } public int readUnsignedByte () throws IOException { int i = read(); if (i == -1) { throw new EOFException(); } return i; } public int readUnsignedShort () throws IOException { int a = is.read(); int b = readUnsignedByte(); return ((a << 8) | b); } public int skipBytes (int n) throws IOException { // note: This is actually a valid implementation of this method, rendering it quite useless... return 0; } @Override public int available () { return is.available(); } }
false
true
private int readUtfChar (StringBuilder sb) throws IOException { int a = readUnsignedByte(); if ((a & 0x80) == 0) { sb.append((char)a); return 1; } if ((a & 0xe0) == 0xb0) { int b = readUnsignedByte(); sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F))); return 2; } if ((a & 0xf0) == 0xe0) { int b = is.read(); int c = readUnsignedByte(); sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); return 3; } throw new UTFDataFormatException(); }
private int readUtfChar (StringBuilder sb) throws IOException { int a = readUnsignedByte(); if ((a & 0x80) == 0) { sb.append((char)a); return 1; } if ((a & 0xe0) == 0xc0) { int b = readUnsignedByte(); sb.append((char)(((a & 0x1F) << 6) | (b & 0x3F))); return 2; } if ((a & 0xf0) == 0xe0) { int b = readUnsignedByte(); int c = readUnsignedByte(); sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); return 3; } throw new UTFDataFormatException(); }
diff --git a/src/org/biojava/bio/alignment/SmithWaterman.java b/src/org/biojava/bio/alignment/SmithWaterman.java index 0ce2dd1d7..672f02c5f 100755 --- a/src/org/biojava/bio/alignment/SmithWaterman.java +++ b/src/org/biojava/bio/alignment/SmithWaterman.java @@ -1,411 +1,409 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.alignment; import java.util.HashMap; import java.util.Map; import org.biojava.bio.BioException; import org.biojava.bio.BioRuntimeException; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.impl.SimpleGappedSequence; import org.biojava.bio.seq.impl.SimpleSequence; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.symbol.SimpleAlignment; import org.biojava.bio.symbol.SimpleSymbolList; /* * Created on 05.09.2005 * */ /** Smith and Waterman developed an efficient dynamic programing algorithm * to perform local sequence alignments, which returns the most conserved * region of two sequences (longes common substring with modifications). * This algorithm is performed by the method <code>pairwiseAlignment</code> * of this class. It uses affine gap penalties if and only if the expenses * of a delete or insert operation are unequal to the expenses of gap extension. * This uses significantly more memory (four times as much) and increases * the runtime if swaping is performed. * * @author Andreas Dr&auml;ger * @author Gero Greiner * @since 1.5 */ public class SmithWaterman extends NeedlemanWunsch { private double match, replace, insert, delete, gapExt; private double[][] scoreMatrix; /** Constructs the new SmithWaterman alignment object. Alignments are only performed, * if the alphabet of the given <code>SubstitutionMatrix</code> equals the alpabet of * both the query and the target <code>Sequence</code>. The alignment parameters here * are expenses and not scores as they are in the <code>NeedlemanWunsch</code> object. * scores are just given by multipliing the expenses with <code>(-1)</code>. For example * you could use parameters like "-2, 5, 3, 3, 0". If the expenses for gap extension * are equal to the cost of starting a gap (delete or insert), no affine gap penalties * are used, which saves memory. * * @param match expenses for a match * @param replace expenses for a replace operation * @param insert expenses for a gap opening in the query sequence * @param delete expenses for a gap opening in the target sequence * @param gapExtend expenses for the extension of a gap which was started earlier. * @param matrix the <code>SubstitutionMatrix</code> object to use. */ public SmithWaterman(double match, double replace, double insert, double delete, double gapExtend, SubstitutionMatrix matrix) { super(insert, delete, gapExtend, match, replace, matrix); this.match = -match; this.replace = -replace; this.insert = -insert; this.delete = -delete; this.gapExt = -gapExtend; this.subMatrix = matrix; this.alignment = ""; } /** Overrides the method inherited from the NeedlemanWunsch and * sets the penalty for an insert operation to the specified value. * Reason: internaly scores are used instead of penalties so that * the value is muliplied with -1. * @param ins costs for a single insert operation */ public void setInsert(double ins) { this.insert = -ins; } /** Overrides the method inherited from the NeedlemanWunsch and * sets the penalty for a delete operation to the specified value. * Reason: internaly scores are used instead of penalties so that * the value is muliplied with -1. * @param del costs for a single deletion operation */ public void setDelete(double del) { this.delete = -del; } /** Overrides the method inherited from the NeedlemanWunsch and * sets the penalty for an extension of any gap (insert or delete) to the * specified value. * Reason: internaly scores are used instead of penalties so that * the value is muliplied with -1. * @param ge costs for any gap extension */ public void setGapExt(double ge) { this.gapExt = -ge; } /** Overrides the method inherited from the NeedlemanWunsch and * sets the penalty for a match operation to the specified value. * Reason: internaly scores are used instead of penalties so that * the value is muliplied with -1. * @param ma costs for a single match operation */ public void setMatch(double ma) { this.match = -ma; } /** Overrides the method inherited from the NeedlemanWunsch and * sets the penalty for a replace operation to the specified value. * Reason: internaly scores are used instead of penalties so that * the value is muliplied with -1. * @param rep costs for a single replace operation */ public void setReplace(double rep) { this.replace = -rep; } /** Overrides the method inherited from the NeedlemanWunsch and performs only a local alignment. * It finds only the longest common subsequence. This is good for the beginning, but it might * be better to have a system to find more than only one hit within the score matrix. Therfore * one should only define the k-th best hit, where k is somehow related to the number of hits. * * @see SequenceAlignment#pairwiseAlignment(org.biojava.bio.seq.Sequence, org.biojava.bio.seq.Sequence) */ public double pairwiseAlignment(Sequence query, Sequence subject) throws BioRuntimeException { if (query.getAlphabet().equals(subject.getAlphabet()) && query.getAlphabet().equals(subMatrix.getAlphabet())) { long time = System.currentTimeMillis(); int i, j, maxI = 0, maxJ = 0, queryStart = 0, targetStart = 0; this.scoreMatrix = new double[query.length()+1][subject.length()+1]; /* * Variables needed for traceback */ String[] align = new String[] {"", ""}; String path = ""; SymbolTokenization st; try { st = query.getAlphabet().getTokenization("default"); } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * Use affine gap panalties. */ if ((gapExt != delete) || (gapExt != insert)) { double[][] E = new double[query.length()+1][subject.length()+1]; // Inserts double[][] F = new double[query.length()+1][subject.length()+1]; // Deletes scoreMatrix[0][0] = 0; E[0][0] = F[0][0] = Double.NEGATIVE_INFINITY; for (i=1; i<=query.length(); i++) { scoreMatrix[i][0] = F[i][0] = 0; E[i][0] = Double.NEGATIVE_INFINITY; } for (j=1; j<=subject.length(); j++) { scoreMatrix[0][j] = E[0][j] = 0; F[0][j] = Double.NEGATIVE_INFINITY; } for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { E[i][j] = Math.max(E[i][j-1], scoreMatrix[i][j-1] + insert) + gapExt; F[i][j] = Math.max(F[i-1][j], scoreMatrix[i-1][j] + delete) + gapExt; scoreMatrix[i][j] = max(0.0, E[i][j], F[i][j], scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } //System.out.println(printCostMatrix(G, query.seqString().toCharArray(), subject.seqString().toCharArray())); /* * Here starts the traceback for affine gap penalities */ try { boolean[] gap_extend = {false, false}; j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if ((scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) && !(gap_extend[0] || gap_extend[1])) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert || finish gap if extended gap is opened } else if (scoreMatrix[i][j] == E[i][j] || gap_extend[0]) { //check if gap has been extended or freshly opened - //gap_extend[0] = (scoreMatrix[i][j] == E[i][j-1] + gapExt && gapExt != insert); gap_extend[0] = (E[i][j] != scoreMatrix[i][j-1] + insert + gapExt); align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete || finish gap if extended gap is opened } else { //check if gap has been extended or freshly opened - //gap_extend[1] = (scoreMatrix[i][j] == F[i-1][j] + gapExt && gapExt != delete); - gap_extend[1] = (F[i][j] != scoreMatrix[i][j-1] + delete + gapExt); + gap_extend[1] = (F[i][j] != scoreMatrix[i-1][j] + delete + gapExt); align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * No affine gap penalties to save memory. */ } else { for (i=0; i<=query.length(); i++) scoreMatrix[i][0] = 0; for (j=0; j<=subject.length(); j++) scoreMatrix[0][j] = 0; for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { scoreMatrix[i][j] = max( 0.0, scoreMatrix[i-1][j] + delete, scoreMatrix[i][j-1] + insert, scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j) ); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } /* * Here starts the traceback for non-affine gap penalities */ try{ j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if (scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert } else if (scoreMatrix[i][j] == scoreMatrix[i][j-1] + insert) { align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete } else { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } } /* * From here both cases are equal again. */ //System.out.println(printCostMatrix(scoreMatrix, query.seqString().toCharArray(), subject.seqString().toCharArray())); try { // this is necessary to have a value for the getEditDistance method. this.CostMatrix = new double[1][1]; CostMatrix[0][0] = -scoreMatrix[maxI][maxJ]; query = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(query.getAlphabet().getTokenization("token"), align[0]), query.getURN(), query.getName(), query.getAnnotation())); subject = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(subject.getAlphabet().getTokenization("token"), align[1]), subject.getURN(), subject.getName(), subject.getAnnotation())); Map m = new HashMap(); m.put(query.getName(), query); m.put(subject.getName(), subject); pairalign = new SimpleAlignment(m); /* * Construct the output with only 60 symbols in each line. */ this.alignment = formatOutput( query.getName(), // name of the query sequence subject.getName(), // name of the target sequence align, // the String representation of the alignment path, // String match/missmatch representation queryStart, // Start position of the alignment in the query sequence maxI, // End position of the alignment in the query sequence scoreMatrix.length-1, // length of the query sequence targetStart, // Start position of the alignment in the target sequence maxJ, // End position of the alignment in the target sequence scoreMatrix[0].length-1, // length of the target sequence getEditDistance(), System.currentTimeMillis() - time) + "\n"; // time consumption // Don't waste any memory. double value = scoreMatrix[maxI][maxJ]; scoreMatrix = null; Runtime.getRuntime().gc(); return value; } catch (BioException exc) { throw new BioRuntimeException(exc); } } else throw new BioRuntimeException( "The alphabets of the sequences and the substitution matrix have to be equal."); } /** This just computes the maximum of four doubles. * @param w * @param x * @param y * @param z * @return the maximum of four <code>double</code>s. */ private double max(double w, double x, double y, double z) { if ((w > x) && (w > y) && (w > z)) return w; if ((x > y) && (x > z)) return x; if ((y > z)) return y; return z; } /** This method computes the scores for the substution of the i-th symbol * of query by the j-th symbol of subject. * * @param query The query sequence * @param subject The target sequence * @param i The position of the symbol under consideration within the * query sequence (starting from one) * @param j The position of the symbol under consideration within the * target sequence * @return The score for the given substitution. */ private double matchReplace(Sequence query, Sequence subject, int i, int j) { try { return subMatrix.getValueAt(query.symbolAt(i), subject.symbolAt(j)); } catch (Exception exc) { if (query.symbolAt(i).getMatches().contains(subject.symbolAt(j)) || subject.symbolAt(j).getMatches().contains(query.symbolAt(i))) return match; return replace; } } }
false
true
public double pairwiseAlignment(Sequence query, Sequence subject) throws BioRuntimeException { if (query.getAlphabet().equals(subject.getAlphabet()) && query.getAlphabet().equals(subMatrix.getAlphabet())) { long time = System.currentTimeMillis(); int i, j, maxI = 0, maxJ = 0, queryStart = 0, targetStart = 0; this.scoreMatrix = new double[query.length()+1][subject.length()+1]; /* * Variables needed for traceback */ String[] align = new String[] {"", ""}; String path = ""; SymbolTokenization st; try { st = query.getAlphabet().getTokenization("default"); } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * Use affine gap panalties. */ if ((gapExt != delete) || (gapExt != insert)) { double[][] E = new double[query.length()+1][subject.length()+1]; // Inserts double[][] F = new double[query.length()+1][subject.length()+1]; // Deletes scoreMatrix[0][0] = 0; E[0][0] = F[0][0] = Double.NEGATIVE_INFINITY; for (i=1; i<=query.length(); i++) { scoreMatrix[i][0] = F[i][0] = 0; E[i][0] = Double.NEGATIVE_INFINITY; } for (j=1; j<=subject.length(); j++) { scoreMatrix[0][j] = E[0][j] = 0; F[0][j] = Double.NEGATIVE_INFINITY; } for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { E[i][j] = Math.max(E[i][j-1], scoreMatrix[i][j-1] + insert) + gapExt; F[i][j] = Math.max(F[i-1][j], scoreMatrix[i-1][j] + delete) + gapExt; scoreMatrix[i][j] = max(0.0, E[i][j], F[i][j], scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } //System.out.println(printCostMatrix(G, query.seqString().toCharArray(), subject.seqString().toCharArray())); /* * Here starts the traceback for affine gap penalities */ try { boolean[] gap_extend = {false, false}; j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if ((scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) && !(gap_extend[0] || gap_extend[1])) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert || finish gap if extended gap is opened } else if (scoreMatrix[i][j] == E[i][j] || gap_extend[0]) { //check if gap has been extended or freshly opened //gap_extend[0] = (scoreMatrix[i][j] == E[i][j-1] + gapExt && gapExt != insert); gap_extend[0] = (E[i][j] != scoreMatrix[i][j-1] + insert + gapExt); align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete || finish gap if extended gap is opened } else { //check if gap has been extended or freshly opened //gap_extend[1] = (scoreMatrix[i][j] == F[i-1][j] + gapExt && gapExt != delete); gap_extend[1] = (F[i][j] != scoreMatrix[i][j-1] + delete + gapExt); align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * No affine gap penalties to save memory. */ } else { for (i=0; i<=query.length(); i++) scoreMatrix[i][0] = 0; for (j=0; j<=subject.length(); j++) scoreMatrix[0][j] = 0; for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { scoreMatrix[i][j] = max( 0.0, scoreMatrix[i-1][j] + delete, scoreMatrix[i][j-1] + insert, scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j) ); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } /* * Here starts the traceback for non-affine gap penalities */ try{ j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if (scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert } else if (scoreMatrix[i][j] == scoreMatrix[i][j-1] + insert) { align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete } else { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } } /* * From here both cases are equal again. */ //System.out.println(printCostMatrix(scoreMatrix, query.seqString().toCharArray(), subject.seqString().toCharArray())); try { // this is necessary to have a value for the getEditDistance method. this.CostMatrix = new double[1][1]; CostMatrix[0][0] = -scoreMatrix[maxI][maxJ]; query = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(query.getAlphabet().getTokenization("token"), align[0]), query.getURN(), query.getName(), query.getAnnotation())); subject = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(subject.getAlphabet().getTokenization("token"), align[1]), subject.getURN(), subject.getName(), subject.getAnnotation())); Map m = new HashMap(); m.put(query.getName(), query); m.put(subject.getName(), subject); pairalign = new SimpleAlignment(m); /* * Construct the output with only 60 symbols in each line. */ this.alignment = formatOutput( query.getName(), // name of the query sequence subject.getName(), // name of the target sequence align, // the String representation of the alignment path, // String match/missmatch representation queryStart, // Start position of the alignment in the query sequence maxI, // End position of the alignment in the query sequence scoreMatrix.length-1, // length of the query sequence targetStart, // Start position of the alignment in the target sequence maxJ, // End position of the alignment in the target sequence scoreMatrix[0].length-1, // length of the target sequence getEditDistance(), System.currentTimeMillis() - time) + "\n"; // time consumption // Don't waste any memory. double value = scoreMatrix[maxI][maxJ]; scoreMatrix = null; Runtime.getRuntime().gc(); return value; } catch (BioException exc) { throw new BioRuntimeException(exc); } } else throw new BioRuntimeException( "The alphabets of the sequences and the substitution matrix have to be equal."); }
public double pairwiseAlignment(Sequence query, Sequence subject) throws BioRuntimeException { if (query.getAlphabet().equals(subject.getAlphabet()) && query.getAlphabet().equals(subMatrix.getAlphabet())) { long time = System.currentTimeMillis(); int i, j, maxI = 0, maxJ = 0, queryStart = 0, targetStart = 0; this.scoreMatrix = new double[query.length()+1][subject.length()+1]; /* * Variables needed for traceback */ String[] align = new String[] {"", ""}; String path = ""; SymbolTokenization st; try { st = query.getAlphabet().getTokenization("default"); } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * Use affine gap panalties. */ if ((gapExt != delete) || (gapExt != insert)) { double[][] E = new double[query.length()+1][subject.length()+1]; // Inserts double[][] F = new double[query.length()+1][subject.length()+1]; // Deletes scoreMatrix[0][0] = 0; E[0][0] = F[0][0] = Double.NEGATIVE_INFINITY; for (i=1; i<=query.length(); i++) { scoreMatrix[i][0] = F[i][0] = 0; E[i][0] = Double.NEGATIVE_INFINITY; } for (j=1; j<=subject.length(); j++) { scoreMatrix[0][j] = E[0][j] = 0; F[0][j] = Double.NEGATIVE_INFINITY; } for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { E[i][j] = Math.max(E[i][j-1], scoreMatrix[i][j-1] + insert) + gapExt; F[i][j] = Math.max(F[i-1][j], scoreMatrix[i-1][j] + delete) + gapExt; scoreMatrix[i][j] = max(0.0, E[i][j], F[i][j], scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } //System.out.println(printCostMatrix(G, query.seqString().toCharArray(), subject.seqString().toCharArray())); /* * Here starts the traceback for affine gap penalities */ try { boolean[] gap_extend = {false, false}; j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if ((scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) && !(gap_extend[0] || gap_extend[1])) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert || finish gap if extended gap is opened } else if (scoreMatrix[i][j] == E[i][j] || gap_extend[0]) { //check if gap has been extended or freshly opened gap_extend[0] = (E[i][j] != scoreMatrix[i][j-1] + insert + gapExt); align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete || finish gap if extended gap is opened } else { //check if gap has been extended or freshly opened gap_extend[1] = (F[i][j] != scoreMatrix[i-1][j] + delete + gapExt); align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } /* * No affine gap penalties to save memory. */ } else { for (i=0; i<=query.length(); i++) scoreMatrix[i][0] = 0; for (j=0; j<=subject.length(); j++) scoreMatrix[0][j] = 0; for (i=1; i<=query.length(); i++) for (j=1; j<=subject.length(); j++) { scoreMatrix[i][j] = max( 0.0, scoreMatrix[i-1][j] + delete, scoreMatrix[i][j-1] + insert, scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j) ); if (scoreMatrix[i][j] > scoreMatrix[maxI][maxJ]) { maxI = i; maxJ = j; } } /* * Here starts the traceback for non-affine gap penalities */ try{ j = maxJ; for (i=maxI; i>0; ) { do { // only Deletes or Inserts or Replaces possible. That's not what we want to have. if (scoreMatrix[i][j] == 0) { queryStart = i; targetStart = j; i = j = 0; // Match/Replace } else if (scoreMatrix[i][j] == scoreMatrix[i-1][j-1] + matchReplace(query, subject, i, j)) { if (query.symbolAt(i) == subject.symbolAt(j)) path = '|' + path; else path = ' ' + path; align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; // Insert } else if (scoreMatrix[i][j] == scoreMatrix[i][j-1] + insert) { align[0] = '-' + align[0]; align[1] = st.tokenizeSymbol(subject.symbolAt(j--)) + align[1]; path = ' ' + path; // Delete } else { align[0] = st.tokenizeSymbol(query.symbolAt(i--)) + align[0]; align[1] = '-' + align[1]; path = ' ' + path; } } while (j>0); } } catch (BioException exc) { throw new BioRuntimeException(exc); } } /* * From here both cases are equal again. */ //System.out.println(printCostMatrix(scoreMatrix, query.seqString().toCharArray(), subject.seqString().toCharArray())); try { // this is necessary to have a value for the getEditDistance method. this.CostMatrix = new double[1][1]; CostMatrix[0][0] = -scoreMatrix[maxI][maxJ]; query = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(query.getAlphabet().getTokenization("token"), align[0]), query.getURN(), query.getName(), query.getAnnotation())); subject = new SimpleGappedSequence( new SimpleSequence( new SimpleSymbolList(subject.getAlphabet().getTokenization("token"), align[1]), subject.getURN(), subject.getName(), subject.getAnnotation())); Map m = new HashMap(); m.put(query.getName(), query); m.put(subject.getName(), subject); pairalign = new SimpleAlignment(m); /* * Construct the output with only 60 symbols in each line. */ this.alignment = formatOutput( query.getName(), // name of the query sequence subject.getName(), // name of the target sequence align, // the String representation of the alignment path, // String match/missmatch representation queryStart, // Start position of the alignment in the query sequence maxI, // End position of the alignment in the query sequence scoreMatrix.length-1, // length of the query sequence targetStart, // Start position of the alignment in the target sequence maxJ, // End position of the alignment in the target sequence scoreMatrix[0].length-1, // length of the target sequence getEditDistance(), System.currentTimeMillis() - time) + "\n"; // time consumption // Don't waste any memory. double value = scoreMatrix[maxI][maxJ]; scoreMatrix = null; Runtime.getRuntime().gc(); return value; } catch (BioException exc) { throw new BioRuntimeException(exc); } } else throw new BioRuntimeException( "The alphabets of the sequences and the substitution matrix have to be equal."); }
diff --git a/domino/eclipse/plugins/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewGadgetHandler.java b/domino/eclipse/plugins/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewGadgetHandler.java index 06d96f502..3cc1cbead 100644 --- a/domino/eclipse/plugins/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewGadgetHandler.java +++ b/domino/eclipse/plugins/com.ibm.xsp.sbtsdk.playground/src/nsf/playground/playground/PreviewGadgetHandler.java @@ -1,113 +1,113 @@ package nsf.playground.playground; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringReader; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.commons.util.StringUtil; import com.ibm.commons.util.SystemCache; import com.ibm.commons.util.io.ByteStreamCache; import com.ibm.commons.util.io.ReaderInputStream; public class PreviewGadgetHandler extends PreviewHandler { static class RequestParams implements Serializable { private static final long serialVersionUID = 1L; String sOptions; String gadget; String html; String js; String css; String json; String properties; public RequestParams(String sOptions, String gadget, String html, String js, String css, String json, String properties) { this.sOptions = sOptions; this.gadget = gadget; this.html = html; this.js = js; this.css = css; this.json = json; this.properties = properties; } } private static SystemCache requestParamsMap = new SystemCache("gadgets", 50); @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sOptions = req.getParameter("fm_options"); String gadgetId = req.getParameter("fm_gadgetid"); String gadget = req.getParameter("fm_gadget"); String html = req.getParameter("fm_html"); String js = req.getParameter("fm_js"); String css = req.getParameter("fm_css"); String json = req.getParameter("fm_json"); String properties = req.getParameter("fm_properties"); RequestParams requestParams = new RequestParams(sOptions,gadget,html,js,css,json,properties); requestParamsMap.put(gadgetId, requestParams); resp.setStatus(200); } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String[] parts = StringUtil.splitString(pathInfo.substring(1), '/', false); if(parts.length==3) { RequestParams requestParams = (RequestParams)requestParamsMap.get(parts[1]); if(requestParams!=null) { String fileName = parts[2]; if(StringUtil.endsWithIgnoreCase(fileName,".xml")) { emit(resp,requestParams.gadget,"text/xml;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".html")) { emit(resp,requestParams.html,"text/html;charset=utf-8"); return; } - if(StringUtil.endsWithIgnoreCase(fileName,".xml")) { + if(StringUtil.endsWithIgnoreCase(fileName,".css")) { emit(resp,requestParams.css,"text/css;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".js")) { emit(resp,requestParams.js,"application/javascript;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".json")) { - emit(resp,requestParams.js,"application/json;charset=utf-8"); + emit(resp,requestParams.json,"application/json;charset=utf-8"); return; } } else { resp.setStatus(404); PrintWriter pw = resp.getWriter(); pw.println("In memory gadget cache has expired"); pw.flush(); } } PrintWriter pw = resp.getWriter(); pw.println("Social Business Tooolkit Playground - OpenSocial Gadget Snippet Preview Servlet"); pw.flush(); // Return the different parts of the gadget } private void emit(HttpServletResponse resp, String text, String contentType) throws IOException { resp.setStatus(200); resp.setContentType(contentType); ByteStreamCache bs = new ByteStreamCache(); InputStream is = new ReaderInputStream(new StringReader(text),"utf-8"); bs.copyFrom(is); resp.setContentLength((int)bs.getLength()); OutputStream os = resp.getOutputStream(); bs.copyTo(os); os.flush(); } }
false
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String[] parts = StringUtil.splitString(pathInfo.substring(1), '/', false); if(parts.length==3) { RequestParams requestParams = (RequestParams)requestParamsMap.get(parts[1]); if(requestParams!=null) { String fileName = parts[2]; if(StringUtil.endsWithIgnoreCase(fileName,".xml")) { emit(resp,requestParams.gadget,"text/xml;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".html")) { emit(resp,requestParams.html,"text/html;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".xml")) { emit(resp,requestParams.css,"text/css;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".js")) { emit(resp,requestParams.js,"application/javascript;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".json")) { emit(resp,requestParams.js,"application/json;charset=utf-8"); return; } } else { resp.setStatus(404); PrintWriter pw = resp.getWriter(); pw.println("In memory gadget cache has expired"); pw.flush(); } } PrintWriter pw = resp.getWriter(); pw.println("Social Business Tooolkit Playground - OpenSocial Gadget Snippet Preview Servlet"); pw.flush(); // Return the different parts of the gadget }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String[] parts = StringUtil.splitString(pathInfo.substring(1), '/', false); if(parts.length==3) { RequestParams requestParams = (RequestParams)requestParamsMap.get(parts[1]); if(requestParams!=null) { String fileName = parts[2]; if(StringUtil.endsWithIgnoreCase(fileName,".xml")) { emit(resp,requestParams.gadget,"text/xml;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".html")) { emit(resp,requestParams.html,"text/html;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".css")) { emit(resp,requestParams.css,"text/css;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".js")) { emit(resp,requestParams.js,"application/javascript;charset=utf-8"); return; } if(StringUtil.endsWithIgnoreCase(fileName,".json")) { emit(resp,requestParams.json,"application/json;charset=utf-8"); return; } } else { resp.setStatus(404); PrintWriter pw = resp.getWriter(); pw.println("In memory gadget cache has expired"); pw.flush(); } } PrintWriter pw = resp.getWriter(); pw.println("Social Business Tooolkit Playground - OpenSocial Gadget Snippet Preview Servlet"); pw.flush(); // Return the different parts of the gadget }
diff --git a/test/plugins/Freetalk/WoT/WoTMessageManagerTest.java b/test/plugins/Freetalk/WoT/WoTMessageManagerTest.java index 73053a23..93ae9828 100644 --- a/test/plugins/Freetalk/WoT/WoTMessageManagerTest.java +++ b/test/plugins/Freetalk/WoT/WoTMessageManagerTest.java @@ -1,447 +1,447 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.Freetalk.WoT; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.UUID; import plugins.Freetalk.Board; import plugins.Freetalk.DatabaseBasedTest; import plugins.Freetalk.FetchFailedMarker; import plugins.Freetalk.MessageList; import plugins.Freetalk.MessageManager; import plugins.Freetalk.SubscribedBoard; import plugins.Freetalk.MessageList.MessageListFetchFailedMarker; import plugins.Freetalk.SubscribedBoard.BoardThreadLink; import plugins.Freetalk.SubscribedBoard.MessageReference; import plugins.Freetalk.exceptions.InvalidParameterException; import plugins.Freetalk.exceptions.NoSuchIdentityException; import plugins.Freetalk.exceptions.NoSuchMessageException; import plugins.Freetalk.exceptions.NoSuchMessageListException; import com.db4o.ObjectSet; import com.db4o.query.Query; import freenet.keys.FreenetURI; import freenet.support.CurrentTimeUTC; public class WoTMessageManagerTest extends DatabaseBasedTest { private WoTIdentityManager mIdentityManager; private WoTMessageManager mMessageManager; private WoTOwnIdentity[] mOwnIdentities; private Set<Board> mBoards; private SubscribedBoard mBoard; private int mMessageListIndex = 0; /** * The threads which we stored in the database. The unit test should test whether board.getThreads() returns the threads in the order in which they are stored * in this list. It should of course also test whether no thread is missing, or no thread is returned even though it should * not be returned as a thread. */ private LinkedList<String> mThreads; /** * The replies to each message which we stored in the database. The unit test should test whether the replies show up, whether their order is correct, etc. */ private Hashtable<String, LinkedList<String>> mReplies; protected void setUp() throws Exception { super.setUp(); mIdentityManager = new WoTIdentityManager(db); mMessageManager = new WoTMessageManager(db, mIdentityManager); constructIdentities(); constructBoards(); mThreads = new LinkedList<String>(); mReplies = new Hashtable<String, LinkedList<String>>(); } private void constructIdentities() throws MalformedURLException { String[] requestSSKs = new String[] { "SSK@lY~N0Nk5NQpt6brGgtckFHPY11GzgkDn4VDszL6fwPg,GDQlSg9ncBBF8XIS-cXYb-LM9JxE3OiSydyOaZgCS4k,AQACAAE/WoT", "SSK@WcOyByjhHpYE-GeA4f0QTm8WxIMLeuTeHH0OvoIySLI,m2xhPKGLhq1yqpqdYp0Yvbs~qdnJU4PD0NmWga1cwRE,AQACAAE/WoT", "SSK@OHIaAMNpKIgdbkWPCOb9phCQoa015NAoiA0ud-9a4TM,5Jp16w6-yS~AiQweFljj-gJck0AYxzu-Nfs6BjKXPsk,AQACAAE/WoT", "SSK@VMFi2tyuli54KgLNmMHz4k-XHKlNhlDVGOCFdLL5VRU,00v-jVRVF8P5xrd3kuiAWXHN7RPDxb5kJP9Z8XUqe~A,AQACAAE/WoT", "SSK@HH~V2XmCbZp~738qtE67jUg1M5L5flVvQfc2bYpE1o4,c8H39jkp08cao-EJVTV~rISHlcMnlTlpNFICzL4gmZ4,AQACAAE/WoT" }; String[] insertSSKs = new String[] { "SSK@egaZBiTrPGsiLVBJGT91MOX5jtC6pFIDFDyjt3FcsRI,GDQlSg9ncBBF8XIS-cXYb-LM9JxE3OiSydyOaZgCS4k,AQECAAE/WoT", "SSK@Ze0-i5NRq60j549pck~Sb2zsyf98KNKczPsAGgT1lUE,m2xhPKGLhq1yqpqdYp0Yvbs~qdnJU4PD0NmWga1cwRE,AQECAAE/WoT", "SSK@RGNZ2LrmnS3DjX5DfpUfDpaqWnMmaLBVH9X8uB9CgRc,5Jp16w6-yS~AiQweFljj-gJck0AYxzu-Nfs6BjKXPsk,AQECAAE/WoT", "SSK@XjHet73nz3vIKRHc-Km8GtWCEMuzo6AEMIw16Pft6HA,00v-jVRVF8P5xrd3kuiAWXHN7RPDxb5kJP9Z8XUqe~A,AQECAAE/WoT", "SSK@ReQUmaBjHDrRd8Z8kOGMw9dVd5Q3RhhEAsYJQRLuXGY,c8H39jkp08cao-EJVTV~rISHlcMnlTlpNFICzL4gmZ4,AQECAAE/WoT" }; mOwnIdentities = new WoTOwnIdentity[requestSSKs.length]; for(int i = 0; i < requestSSKs.length; ++i) { FreenetURI requestURI = new FreenetURI(requestSSKs[i]); FreenetURI insertURI = new FreenetURI(insertSSKs[i]); mOwnIdentities[i] = new WoTOwnIdentity(WoTOwnIdentity.getIDFromURI(requestURI), requestURI, insertURI, "nickname" + i); mOwnIdentities[i].initializeTransient(db, mIdentityManager); mOwnIdentities[i].storeWithoutCommit(); } db.commit(); } private void constructBoards() throws Exception { mMessageManager.getOrCreateBoard("en.test"); mBoard = mMessageManager.subscribeToBoard(mOwnIdentities[0], "en.test"); mBoards = new HashSet<Board>(); mBoards.add(mBoard); } private WoTMessageList storeMessageList(WoTOwnIdentity author, FreenetURI uri, MessageList.MessageReference messageRef) throws InvalidParameterException, NoSuchIdentityException { List<MessageList.MessageReference> references = new ArrayList<MessageList.MessageReference>(2); references.add(messageRef); WoTMessageList list = new WoTMessageList(author, uri, references); list.initializeTransient(db, mMessageManager); list.storeWithoutCommit(); db.commit(); return list; } private WoTMessage createTestMessage(WoTOwnIdentity author, WoTMessage myParent, WoTMessageURI myThreadURI) throws MalformedURLException, InvalidParameterException, NoSuchIdentityException, NoSuchMessageException { FreenetURI myRealURI = new FreenetURI("CHK@"); UUID myUUID = UUID.randomUUID(); FreenetURI myListURI = WoTMessageList.assembleURI(author.getRequestURI(), mMessageListIndex++); WoTMessageURI myURI = new WoTMessageURI(myListURI + "#" + myUUID); MessageList.MessageReference ref = new MessageList.MessageReference(myURI.getMessageID(), myRealURI, mBoard); WoTMessageList myList = storeMessageList(author, myListURI, ref); WoTMessageURI myParentURI = myParent != null ? myParent.getURI() : null; WoTMessage message = WoTMessage.construct(myList, myRealURI, myURI.getMessageID(), myThreadURI, myParentURI, mBoards, mBoards.iterator().next(), author, "message " + myUUID, CurrentTimeUTC.get(), "message body " + myUUID, null); return message; } private void verifyStructure() { System.gc(); db.purge(); System.gc(); Iterator<String> expectedThreads = mThreads.iterator(); for(BoardThreadLink ref : mBoard.getThreads()) { // Verify that the thread exists assertTrue(expectedThreads.hasNext()); // ... and that it is in the correct position assertEquals(expectedThreads.next(), ref.getThreadID()); // Verify the replies of the thread LinkedList<String> expectedRepliesList= mReplies.get(ref.getThreadID()); if(expectedRepliesList == null) expectedRepliesList = new LinkedList<String>(); Iterator<String> expectedReplies = expectedRepliesList.iterator(); for(MessageReference replyRef : mBoard.getAllThreadReplies(ref.getThreadID(), true)) { assertTrue(expectedReplies.hasNext()); assertEquals(expectedReplies.next(), replyRef.getMessage().getID()); } assertFalse(expectedReplies.hasNext()); } assertFalse(expectedThreads.hasNext()); } /** * When you obtain a message object from the database, different kinds of other message objects can be queried from the message: * - The thread it belongs to * - The message it is a reply to * - The replies to the message * * Because messages are downloaded in random order, any of those referenced other messages can be unknown to Freetalk at a single point in time. * For example if the thread a message belongs to was not downloaded yet, the message object contains the FreenetURI of the thread (which is * sort of it's "primary key" in database-speech) but the reference to the actual message object which IS the thread will be null because the * thread was not downloaded yet. * * Therefore, it is the job of the MessageManager object and Board objects to <b>correctly</b> update associations of Message objects with * each others, for example: * - when a new message is downloaded, all it's already existent children should be linked to it * - when a new thread is downloaded, all messages whose parent messages have not been downloaded yet should be temporarily be set as children * of the thread, even though they are not. * - when a new message is downloaded, it should be ensured that any temporary parent&child associations mentioned in the previous line are * replaced with the real parent&child association with the new message. * - etc. * * There are many pitfalls in those tasks which might cause messages being permanently linked to wrong parents, children or threads or even * being lost. * Therefore, it is the job of this unit test to use a hardcoded image of an example thread tree with several messages for testing whether * the thread tree is properly reconstructed if the messages are fed in random order to the WoTMessageManager. * * This is accomplished by feeding the messages in ANY possible order to the WoTMessageManager (each time with a new blank database) and * verifying the thread tree after storing the messages. "Any possible order" means that all permutations of the ordering are covered. * * As a side effect, this test also ensures that no messages are invisible to the user when querying the WoTMessageManager for messages in a * certain board. This is done by not querying the database for the hardcoded message IDs directly but rather using the client-interface * functions for listing all threads, replies, etc. * */ public void testThreading() throws MalformedURLException, InvalidParameterException, NoSuchIdentityException, NoSuchMessageException { WoTMessage thread0 = createTestMessage(mOwnIdentities[0], null, null); mMessageManager.onMessageReceived(thread0); mThreads.addFirst(thread0.getID()); // Single empty thread verifyStructure(); { // Keep the variables in scope so we do not mix them up WoTMessage thread1 = createTestMessage(mOwnIdentities[1], null, null); mMessageManager.onMessageReceived(thread1); mThreads.addFirst(thread1.getID()); // Two empty threads, onMessageReceived called in chronological order verifyStructure(); } { WoTMessage thread0reply0 = createTestMessage(mOwnIdentities[2], thread0, thread0.getURI()); mMessageManager.onMessageReceived(thread0reply0); //First thread receives 1 reply, should be moved to top now mReplies.put(thread0.getID(), new LinkedList<String>()); mReplies.get(thread0.getID()).addLast(thread0reply0.getID()); mThreads.remove(thread0.getID()); mThreads.addFirst(thread0.getID()); verifyStructure(); } WoTMessage thread2reply1; // We'll use it later WoTMessage thread2; { thread2 = createTestMessage(mOwnIdentities[3], null, null); mMessageManager.onMessageReceived(thread2); // Third thread created, should be on top now mThreads.addFirst(thread2.getID()); verifyStructure(); WoTMessage thread2reply0 = createTestMessage(mOwnIdentities[0], thread2, thread2.getURI()); thread2reply1 = createTestMessage(mOwnIdentities[1], thread2reply0, thread2.getURI()); WoTMessage thread2reply2 = createTestMessage(mOwnIdentities[2], thread2, thread2.getURI()); mReplies.put(thread2.getID(), new LinkedList<String>()); // Three replies, onMessageReceived called in chronological order mMessageManager.onMessageReceived(thread2reply0); mReplies.get(thread2.getID()).addLast(thread2reply0.getID()); verifyStructure(); mMessageManager.onMessageReceived(thread2reply1); mReplies.get(thread2.getID()).addLast(thread2reply1.getID()); verifyStructure(); mMessageManager.onMessageReceived(thread2reply2); mReplies.get(thread2.getID()).addLast(thread2reply2.getID()); verifyStructure(); } { WoTMessage thread3 = createTestMessage(mOwnIdentities[4], null, null); mMessageManager.onMessageReceived(thread3); mThreads.addFirst(thread3.getID()); verifyStructure(); // Fourth thread created, should be on top now WoTMessage thread3reply0 = createTestMessage(mOwnIdentities[0], thread3, thread3.getURI()); WoTMessage thread3reply1 = createTestMessage(mOwnIdentities[1], thread3reply0, thread3.getURI()); WoTMessage thread3reply2 = createTestMessage(mOwnIdentities[2], thread3reply1, thread3.getURI()); WoTMessage thread3reply3 = createTestMessage(mOwnIdentities[3], thread3reply1, thread3.getURI()); // Four replies, onMessageReceived called in random order mReplies.put(thread3.getID(), new LinkedList<String>()); mReplies.get(thread3.getID()).addLast(thread3reply3.getID()); mMessageManager.onMessageReceived(thread3reply3); verifyStructure(); mReplies.get(thread3.getID()).addFirst(thread3reply2.getID()); mMessageManager.onMessageReceived(thread3reply2); verifyStructure(); mReplies.get(thread3.getID()).addFirst(thread3reply0.getID()); mMessageManager.onMessageReceived(thread3reply0); verifyStructure(); mReplies.get(thread3.getID()).add(1, thread3reply1.getID()); mMessageManager.onMessageReceived(thread3reply1); verifyStructure(); } { WoTMessage thread4 = thread2reply1; WoTMessage thread4reply0 = createTestMessage(mOwnIdentities[0], thread4, thread4.getURI()); // Fork a new thread off thread2reply1 WoTMessage thread4reply1 = createTestMessage(mOwnIdentities[1], thread4reply0, thread4.getURI()); // Reply to it WoTMessage thread4reply2 = createTestMessage(mOwnIdentities[2], null, thread4.getURI()); // Specify no parent, should be set to thread2reply1 FIXME verify this WoTMessage thread4reply3 = createTestMessage(mOwnIdentities[2], thread0, thread4.getURI()); // Specify different thread as parent mMessageManager.onMessageReceived(thread4reply0); mThreads.addFirst(thread4.getID()); mReplies.put(thread4.getID(), new LinkedList<String>()); mReplies.get(thread4.getID()).addFirst(thread4reply0.getID()); verifyStructure(); // Insert the replies in random order, TODO: Try all different orders mReplies.get(thread4.getID()).addLast(thread4reply2.getID()); mMessageManager.onMessageReceived(thread4reply2); verifyStructure(); mReplies.get(thread4.getID()).add(1, thread4reply1.getID()); mMessageManager.onMessageReceived(thread4reply1); verifyStructure(); mReplies.get(thread4.getID()).add(3, thread4reply3.getID()); mMessageManager.onMessageReceived(thread4reply3); verifyStructure(); } { WoTMessage thread2reply3 = createTestMessage(mOwnIdentities[0], thread2reply1, thread2.getURI()); // Replying to thread2reply1 within thread2 should still work even though someone forked a thread off it mMessageManager.onMessageReceived(thread2reply3); mReplies.get(thread2.getID()).addLast(thread2reply3.getID()); mThreads.remove(thread2.getID()); mThreads.addFirst(thread2.getID()); // thread2 should be on top verifyStructure(); } } /** * Tests whether deleting an own identity also deletes it's threads and message lists. * * TODO: Also test for non-own identities. * TODO: Also check whether deleting MessageFetchFailedReference and MessageListFetchFailedReference works. */ public void testOnIdentityDeletion() throws MalformedURLException, InvalidParameterException, NoSuchIdentityException, NoSuchMessageException { WoTMessage thread0 = createTestMessage(mOwnIdentities[1], null, null); mMessageManager.onMessageReceived(thread0); mThreads.addFirst(thread0.getID()); // Single empty thread WoTMessage thread0reply0 = createTestMessage(mOwnIdentities[1], thread0, thread0.getURI()); mMessageManager.onMessageReceived(thread0reply0); //First thread receives 1 reply, should be moved to top now mReplies.put(thread0.getID(), new LinkedList<String>()); mReplies.get(thread0.getID()).addLast(thread0reply0.getID()); mThreads.remove(thread0.getID()); mThreads.addFirst(thread0.getID()); verifyStructure(); // Fork a new thread off thread0 by creating a reply to it. The reply should not be deleted because it's from a different identity. // After deletion of the author of thread0reply0 thread1 should still be visible, as a ghost thread now. See Board.deleteMessage(). WoTMessage thread1 = thread0reply0; WoTMessage thread1reply0 = createTestMessage(mOwnIdentities[0], thread1, thread1.getURI()); mMessageManager.onMessageReceived(thread1reply0); mThreads.addFirst(thread1.getID()); mReplies.put(thread1.getID(), new LinkedList<String>()); mReplies.get(thread1.getID()).addFirst(thread1reply0.getID()); verifyStructure(); { // This thread should not be deleted because it's from a different identity. WoTMessage thread2 = createTestMessage(mOwnIdentities[0], null, null); mMessageManager.onMessageReceived(thread2); mThreads.addFirst(thread2.getID()); // Two empty threads, onMessageReceived called in chronological order verifyStructure(); } mMessageManager.onIdentityDeletion(mOwnIdentities[1]); mOwnIdentities[1].deleteWithoutCommit(); db.commit(); // onIdentityDeletion should have deleted that thread because it only contains messages from the deleted identity. mThreads.remove(thread0.getID()); // Thread 1 should still be visible even though it's message is from the deleted identity because it contains a reply from another identity. verifyStructure(); // Check whether Board.deleteMessage() worked. try { mMessageManager.getOwnMessage(thread0.getID()); fail("onIdentityDeletion() did not delete a Message object!"); } catch(NoSuchMessageException e) { } try { mMessageManager.getOwnMessageList(thread0.getMessageList().getID()); fail("onIdentityDeletion() did not delete a MessageLis objectt!"); } catch(NoSuchMessageListException e) { } } public void testOnMessageFetchFailed() { } @SuppressWarnings("unchecked") public void testOnMessageListFetchFailed() { WoTOwnIdentity author = mOwnIdentities[0]; Query q; ObjectSet<FetchFailedMarker> markers; ObjectSet<MessageList> messageLists; MessageListFetchFailedMarker marker; q = db.query(); q.constrain(FetchFailedMarker.class); assertEquals(0, q.execute().size()); q = db.query(); q.constrain(MessageList.class); assertEquals(0, q.execute().size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); marker = (MessageListFetchFailedMarker)markers.next(); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); assertEquals(marker.getDate().getTime() + MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY, marker.getDateOfNextRetry().getTime()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Now we simulate a retry of the message list fetch marker.setDateOfNextRetry(marker.getDate()); marker.storeWithoutCommit(); db.commit(); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(0, messageLists.size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); - assertEquals(marker.getDate().getTime() + Math.max(MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY*2, MessageManager.MAXIMAL_MESSAGELIST_FETCH_RETRY_DELAY), + assertEquals(marker.getDate().getTime() + Math.min(MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY*2, MessageManager.MAXIMAL_MESSAGELIST_FETCH_RETRY_DELAY), marker.getDateOfNextRetry().getTime()); assertEquals(1, marker.getNumberOfRetries()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Simulate failure with existing marker and existing ghost message list, i.e. the message list fetcher tried to fetch even though it shouldn't. mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); } }
true
true
public void testOnMessageListFetchFailed() { WoTOwnIdentity author = mOwnIdentities[0]; Query q; ObjectSet<FetchFailedMarker> markers; ObjectSet<MessageList> messageLists; MessageListFetchFailedMarker marker; q = db.query(); q.constrain(FetchFailedMarker.class); assertEquals(0, q.execute().size()); q = db.query(); q.constrain(MessageList.class); assertEquals(0, q.execute().size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); marker = (MessageListFetchFailedMarker)markers.next(); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); assertEquals(marker.getDate().getTime() + MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY, marker.getDateOfNextRetry().getTime()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Now we simulate a retry of the message list fetch marker.setDateOfNextRetry(marker.getDate()); marker.storeWithoutCommit(); db.commit(); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(0, messageLists.size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); assertEquals(marker.getDate().getTime() + Math.max(MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY*2, MessageManager.MAXIMAL_MESSAGELIST_FETCH_RETRY_DELAY), marker.getDateOfNextRetry().getTime()); assertEquals(1, marker.getNumberOfRetries()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Simulate failure with existing marker and existing ghost message list, i.e. the message list fetcher tried to fetch even though it shouldn't. mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); }
public void testOnMessageListFetchFailed() { WoTOwnIdentity author = mOwnIdentities[0]; Query q; ObjectSet<FetchFailedMarker> markers; ObjectSet<MessageList> messageLists; MessageListFetchFailedMarker marker; q = db.query(); q.constrain(FetchFailedMarker.class); assertEquals(0, q.execute().size()); q = db.query(); q.constrain(MessageList.class); assertEquals(0, q.execute().size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); marker = (MessageListFetchFailedMarker)markers.next(); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); assertEquals(marker.getDate().getTime() + MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY, marker.getDateOfNextRetry().getTime()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Now we simulate a retry of the message list fetch marker.setDateOfNextRetry(marker.getDate()); marker.storeWithoutCommit(); db.commit(); mMessageManager.clearExpiredFetchFailedMarkers(); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(0, messageLists.size()); mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); assertTrue((CurrentTimeUTC.getInMillis() - marker.getDate().getTime()) < 10 * 1000); assertEquals(marker.getDate().getTime() + Math.min(MessageManager.MINIMAL_MESSAGELIST_FETCH_RETRY_DELAY*2, MessageManager.MAXIMAL_MESSAGELIST_FETCH_RETRY_DELAY), marker.getDateOfNextRetry().getTime()); assertEquals(1, marker.getNumberOfRetries()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); // Simulate failure with existing marker and existing ghost message list, i.e. the message list fetcher tried to fetch even though it shouldn't. mMessageManager.onMessageListFetchFailed(author, WoTMessageList.assembleURI(author.getRequestURI(), 1), FetchFailedMarker.Reason.DataNotFound); q = db.query(); q.constrain(FetchFailedMarker.class); markers = q.execute(); assertEquals(1, markers.size()); assertEquals(marker, markers.next()); q = db.query(); q.constrain(MessageList.class); messageLists = q.execute(); assertEquals(1, messageLists.size()); assertEquals(messageLists.next().getID(), marker.getMessageListID()); }
diff --git a/deegree-client/deegree-mdeditor/src/main/java/org/deegree/client/mdeditor/gui/NavigationBean.java b/deegree-client/deegree-mdeditor/src/main/java/org/deegree/client/mdeditor/gui/NavigationBean.java index 848176c1d1..c7f806a57b 100644 --- a/deegree-client/deegree-mdeditor/src/main/java/org/deegree/client/mdeditor/gui/NavigationBean.java +++ b/deegree-client/deegree-mdeditor/src/main/java/org/deegree/client/mdeditor/gui/NavigationBean.java @@ -1,81 +1,81 @@ //$HeadURL: svn+ssh://[email protected]/deegree/base/trunk/resources/eclipse/files_template.xml $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.client.mdeditor.gui; import java.io.Serializable; import java.util.UUID; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import org.deegree.client.mdeditor.config.FormConfigurationParser; import org.deegree.client.mdeditor.controller.DatasetWriter; import org.deegree.client.mdeditor.model.FormFieldPath; /** * TODO add class documentation here * * @author <a href="mailto:[email protected]">Lyn Buesching</a> * @author last edited by: $Author: lyn $ * * @version $Revision: $, $Date: $ */ @ManagedBean @RequestScoped public class NavigationBean implements Serializable { private static final long serialVersionUID = 9025028665690108601L; public Object saveDataset() { FacesContext fc = FacesContext.getCurrentInstance(); fc.getELContext(); FormFieldBean formfields = (FormFieldBean) fc.getApplication().getELResolver().getValue( fc.getELContext(), null, "formFieldBean" ); FormFieldPath pathToIdentifier = FormConfigurationParser.getPathToIdentifier(); - Object value = formfields.getFormFields().get( pathToIdentifier ).getValue(); + Object value = formfields.getFormFields().get( pathToIdentifier.toString() ).getValue(); String id = String.valueOf( value ); if ( id == null && id.length() == 0 ) { id = UUID.randomUUID().toString(); } DatasetWriter.writeElements( id, formfields.getFormGroups() ); return null; } public Object loadDataset() { return null; } }
true
true
public Object saveDataset() { FacesContext fc = FacesContext.getCurrentInstance(); fc.getELContext(); FormFieldBean formfields = (FormFieldBean) fc.getApplication().getELResolver().getValue( fc.getELContext(), null, "formFieldBean" ); FormFieldPath pathToIdentifier = FormConfigurationParser.getPathToIdentifier(); Object value = formfields.getFormFields().get( pathToIdentifier ).getValue(); String id = String.valueOf( value ); if ( id == null && id.length() == 0 ) { id = UUID.randomUUID().toString(); } DatasetWriter.writeElements( id, formfields.getFormGroups() ); return null; }
public Object saveDataset() { FacesContext fc = FacesContext.getCurrentInstance(); fc.getELContext(); FormFieldBean formfields = (FormFieldBean) fc.getApplication().getELResolver().getValue( fc.getELContext(), null, "formFieldBean" ); FormFieldPath pathToIdentifier = FormConfigurationParser.getPathToIdentifier(); Object value = formfields.getFormFields().get( pathToIdentifier.toString() ).getValue(); String id = String.valueOf( value ); if ( id == null && id.length() == 0 ) { id = UUID.randomUUID().toString(); } DatasetWriter.writeElements( id, formfields.getFormGroups() ); return null; }
diff --git a/src/main/java/org/madogiwa/plaintable/util/ReflectionUtils.java b/src/main/java/org/madogiwa/plaintable/util/ReflectionUtils.java index 1287290..dc733a7 100644 --- a/src/main/java/org/madogiwa/plaintable/util/ReflectionUtils.java +++ b/src/main/java/org/madogiwa/plaintable/util/ReflectionUtils.java @@ -1,111 +1,111 @@ /* * Copyright (c) 2009 Hidenori Sugiyama * * 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.madogiwa.plaintable.util; import org.madogiwa.plaintable.schema.Schema; import java.lang.reflect.Field; import java.lang.reflect.Modifier; /** * @author Hidenori Sugiyama * */ public class ReflectionUtils { public static Schema findSchema(Class<?> clazz) { try { Schema schema = findSchemaFromStaticField(clazz); if (schema != null) { return schema; } Object instance = findInstance(clazz); if (instance == null) { - Class scalaObject = findScalaObject(clazz); - if (scalaObject == null) { + clazz = findScalaObject(clazz); + if (clazz == null) { return null; } - instance = findInstance(scalaObject); + instance = findInstance(clazz); if (instance == null) { return null; } } return findSchemaFromInstance(clazz, instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } private static Schema findSchemaFromStaticField(Class<?> clazz) throws IllegalAccessException { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); if (Modifier.isStatic(field.getModifiers()) && field.getType().equals(Schema.class)) { return (Schema) field.get(null); } } return null; } private static Schema findSchemaFromInstance(Class<?> clazz, Object instance) throws IllegalAccessException { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); if (!Modifier.isStatic(field.getModifiers()) && field.getType().equals(Schema.class)) { return (Schema) field.get(instance); } } return null; } public static Object findInstance(Class<?> clazz) throws IllegalAccessException { Field[] fields = clazz.getFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers()) && field.getType().equals(clazz)) { return field.get(null); } } return null; } public static Class<?> findClassByName(String className) { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { return null; } } public static Class<?> findScalaObject(Class<?> clazz) { try { return clazz.getClassLoader().loadClass(clazz.getCanonicalName() + "$"); } catch (ClassNotFoundException e) { return null; } } }
false
true
public static Schema findSchema(Class<?> clazz) { try { Schema schema = findSchemaFromStaticField(clazz); if (schema != null) { return schema; } Object instance = findInstance(clazz); if (instance == null) { Class scalaObject = findScalaObject(clazz); if (scalaObject == null) { return null; } instance = findInstance(scalaObject); if (instance == null) { return null; } } return findSchemaFromInstance(clazz, instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
public static Schema findSchema(Class<?> clazz) { try { Schema schema = findSchemaFromStaticField(clazz); if (schema != null) { return schema; } Object instance = findInstance(clazz); if (instance == null) { clazz = findScalaObject(clazz); if (clazz == null) { return null; } instance = findInstance(clazz); if (instance == null) { return null; } } return findSchemaFromInstance(clazz, instance); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
diff --git a/scheduleevent/scheduleevent-jar/src/main/java/com/silverpeas/scheduleevent/service/model/beans/DateOptionsComparator.java b/scheduleevent/scheduleevent-jar/src/main/java/com/silverpeas/scheduleevent/service/model/beans/DateOptionsComparator.java index ffad5fba2..17f2ee884 100644 --- a/scheduleevent/scheduleevent-jar/src/main/java/com/silverpeas/scheduleevent/service/model/beans/DateOptionsComparator.java +++ b/scheduleevent/scheduleevent-jar/src/main/java/com/silverpeas/scheduleevent/service/model/beans/DateOptionsComparator.java @@ -1,45 +1,45 @@ /** * Copyright (C) 2000 - 2009 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.scheduleevent.service.model.beans; import java.util.Comparator; public class DateOptionsComparator implements Comparator<DateOption> { public int compare(DateOption date1, DateOption date2) { if (date1.getDay().compareTo(date2.getDay()) == 0) { if (date1.getHour() == date2.getHour()) { return 0; - } else if (date1.getHour() > date2.getHour()) { + } + if (date1.getHour() > date2.getHour()) { return 1; - } else { - return -1; } + return -1; } else { return date1.getDay().compareTo(date2.getDay()); } } }
false
true
public int compare(DateOption date1, DateOption date2) { if (date1.getDay().compareTo(date2.getDay()) == 0) { if (date1.getHour() == date2.getHour()) { return 0; } else if (date1.getHour() > date2.getHour()) { return 1; } else { return -1; } } else { return date1.getDay().compareTo(date2.getDay()); } }
public int compare(DateOption date1, DateOption date2) { if (date1.getDay().compareTo(date2.getDay()) == 0) { if (date1.getHour() == date2.getHour()) { return 0; } if (date1.getHour() > date2.getHour()) { return 1; } return -1; } else { return date1.getDay().compareTo(date2.getDay()); } }
diff --git a/source/java/com/internetitem/sqshy/RunSqshy.java b/source/java/com/internetitem/sqshy/RunSqshy.java index 5a986c0..51ccd9b 100644 --- a/source/java/com/internetitem/sqshy/RunSqshy.java +++ b/source/java/com/internetitem/sqshy/RunSqshy.java @@ -1,143 +1,143 @@ package com.internetitem.sqshy; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jline.Terminal; import jline.TerminalFactory; import jline.console.ConsoleReader; import com.internetitem.sqshy.command.Commands; import com.internetitem.sqshy.command.ConnectCommand; import com.internetitem.sqshy.command.DisconnectCommand; import com.internetitem.sqshy.command.EchoCommand; import com.internetitem.sqshy.command.ReconnectCommand; import com.internetitem.sqshy.command.SetCommand; import com.internetitem.sqshy.config.Configuration; import com.internetitem.sqshy.config.DatabaseConnectionConfig; import com.internetitem.sqshy.config.DriverMatch; import com.internetitem.sqshy.config.args.CommandLineArgument.ArgumentType; import com.internetitem.sqshy.config.args.CommandLineParseException; import com.internetitem.sqshy.config.args.CommandLineParser; import com.internetitem.sqshy.config.args.ParsedCommandLine; import com.internetitem.sqshy.settings.Settings; public class RunSqshy { public static CommandLineParser buildCommandLineParser() { CommandLineParser parser = new CommandLineParser(); parser.addArg("help", "help", "h", ArgumentType.NoArg, "View help message"); parser.addArg("connect", "connect", "c", ArgumentType.RequiredArg, "Connect to saved alias\n(other connection settings override those in the alias"); parser.addArg("driver", "driver", "d", ArgumentType.RequiredArg, "JDBC Driver Class\nIf not specified, will be guessed based on URL"); parser.addArg("url", "url", "u", ArgumentType.RequiredArg, "JDBC URL"); parser.addArg("username", "username", "U", ArgumentType.RequiredArg, "Database Username"); parser.addArg("password", "password", "P", ArgumentType.RequiredArg, "Database Password\nIf the string @ is used, the user will be prompted"); parser.addArg("property", "property", "p", ArgumentType.List, "JDBC Properties (key=value)"); parser.addArg("settings", "settings", null, ArgumentType.RequiredArg, "Load saved settings from file (defaults to ~/.sqshyrc)\nMissing files are ignored"); parser.addArg("set", "set", "s", ArgumentType.List, "Set variables"); return parser; } public static void main(String[] args) throws Exception { CommandLineParser parser = buildCommandLineParser(); ParsedCommandLine cmdline; try { cmdline = parser.parse(args); } catch (CommandLineParseException e) { System.err.println("Error: " + e.getMessage()); System.err.println(); System.err.println(parser.getUsageString()); System.exit(1); return; } if (cmdline.getBoolValue("help")) { System.out.println(parser.getUsageString()); System.exit(0); return; } Settings settings = new Settings(); Configuration globalConfig = Configuration.loadFromResource("/defaults.json"); settings.getVariableManager().addVariables(globalConfig.getVariables()); String settingsFilename = cmdline.getStringValue("settings"); File settingsFile; if (settingsFilename != null) { settingsFile = new File(settingsFilename); } else { settingsFile = new File(System.getProperty("user.home"), ".sqshyrc"); } List<DriverMatch> driverInfos = new ArrayList<>(globalConfig.getDrivers()); List<DatabaseConnectionConfig> dcc = new ArrayList<>(); Configuration config = null; if (settingsFile.isFile()) { String filename = settingsFile.getAbsolutePath(); System.err.println("Loading settings file from " + filename); config = Configuration.loadFromFile(settingsFile); settings.getVariableManager().addVariables(config.getVariables()); if (config.getDrivers() != null) { driverInfos.addAll(config.getDrivers()); } List<DatabaseConnectionConfig> connections = config.getConnections(); if (connections != null) { dcc.addAll(connections); } } else { System.err.println("Warning: No settings file found in " + settingsFile.getAbsolutePath()); } String driverClass = cmdline.getStringValue("driver"); String url = cmdline.getStringValue("url"); String username = cmdline.getStringValue("username"); String password = cmdline.getStringValue("password"); if (password != null && password.equals("@")) { System.out.print("Password: "); password = new String(System.console().readPassword()); } List<String> properties = cmdline.getListValues("properties"); Map<String, String> connectionProperties = listToMap(properties); String alias = cmdline.getStringValue("connect"); settings.getVariableManager().addVariables(listToMap(cmdline.getListValues("set"))); Terminal terminal = TerminalFactory.create(); ConsoleReader reader = new ConsoleReader("sqshy", System.in, System.out, terminal); ConsoleLogger logger = new ConsoleLogger(settings, reader); ConnectionManager connectionManager = new ConnectionManager(settings, driverInfos, dcc); settings.init(logger, connectionManager); Commands commands = new Commands(settings); commands.addCommand("\\connect", ConnectCommand.class); commands.addCommand("\\disconnect", DisconnectCommand.class); commands.addCommand("\\reconnect", ReconnectCommand.class); commands.addCommand("\\set", SetCommand.class); commands.addCommand("\\echo", EchoCommand.class); - if (url != null) { + if (url != null || alias != null) { connectionManager.connect(alias, driverClass, url, username, password, connectionProperties); } SqshyRepl repl = new SqshyRepl(reader, settings, commands); repl.repl(); } private static Map<String, String> listToMap(List<String> properties) { if (properties == null || properties.isEmpty()) { return null; } Map<String, String> map = new HashMap<>(); for (String s : properties) { String[] parts = s.split("=", 2); if (parts.length == 2) { map.put(parts[0], parts[1]); } else { map.put(s, "true"); } } return map; } }
true
true
public static void main(String[] args) throws Exception { CommandLineParser parser = buildCommandLineParser(); ParsedCommandLine cmdline; try { cmdline = parser.parse(args); } catch (CommandLineParseException e) { System.err.println("Error: " + e.getMessage()); System.err.println(); System.err.println(parser.getUsageString()); System.exit(1); return; } if (cmdline.getBoolValue("help")) { System.out.println(parser.getUsageString()); System.exit(0); return; } Settings settings = new Settings(); Configuration globalConfig = Configuration.loadFromResource("/defaults.json"); settings.getVariableManager().addVariables(globalConfig.getVariables()); String settingsFilename = cmdline.getStringValue("settings"); File settingsFile; if (settingsFilename != null) { settingsFile = new File(settingsFilename); } else { settingsFile = new File(System.getProperty("user.home"), ".sqshyrc"); } List<DriverMatch> driverInfos = new ArrayList<>(globalConfig.getDrivers()); List<DatabaseConnectionConfig> dcc = new ArrayList<>(); Configuration config = null; if (settingsFile.isFile()) { String filename = settingsFile.getAbsolutePath(); System.err.println("Loading settings file from " + filename); config = Configuration.loadFromFile(settingsFile); settings.getVariableManager().addVariables(config.getVariables()); if (config.getDrivers() != null) { driverInfos.addAll(config.getDrivers()); } List<DatabaseConnectionConfig> connections = config.getConnections(); if (connections != null) { dcc.addAll(connections); } } else { System.err.println("Warning: No settings file found in " + settingsFile.getAbsolutePath()); } String driverClass = cmdline.getStringValue("driver"); String url = cmdline.getStringValue("url"); String username = cmdline.getStringValue("username"); String password = cmdline.getStringValue("password"); if (password != null && password.equals("@")) { System.out.print("Password: "); password = new String(System.console().readPassword()); } List<String> properties = cmdline.getListValues("properties"); Map<String, String> connectionProperties = listToMap(properties); String alias = cmdline.getStringValue("connect"); settings.getVariableManager().addVariables(listToMap(cmdline.getListValues("set"))); Terminal terminal = TerminalFactory.create(); ConsoleReader reader = new ConsoleReader("sqshy", System.in, System.out, terminal); ConsoleLogger logger = new ConsoleLogger(settings, reader); ConnectionManager connectionManager = new ConnectionManager(settings, driverInfos, dcc); settings.init(logger, connectionManager); Commands commands = new Commands(settings); commands.addCommand("\\connect", ConnectCommand.class); commands.addCommand("\\disconnect", DisconnectCommand.class); commands.addCommand("\\reconnect", ReconnectCommand.class); commands.addCommand("\\set", SetCommand.class); commands.addCommand("\\echo", EchoCommand.class); if (url != null) { connectionManager.connect(alias, driverClass, url, username, password, connectionProperties); } SqshyRepl repl = new SqshyRepl(reader, settings, commands); repl.repl(); }
public static void main(String[] args) throws Exception { CommandLineParser parser = buildCommandLineParser(); ParsedCommandLine cmdline; try { cmdline = parser.parse(args); } catch (CommandLineParseException e) { System.err.println("Error: " + e.getMessage()); System.err.println(); System.err.println(parser.getUsageString()); System.exit(1); return; } if (cmdline.getBoolValue("help")) { System.out.println(parser.getUsageString()); System.exit(0); return; } Settings settings = new Settings(); Configuration globalConfig = Configuration.loadFromResource("/defaults.json"); settings.getVariableManager().addVariables(globalConfig.getVariables()); String settingsFilename = cmdline.getStringValue("settings"); File settingsFile; if (settingsFilename != null) { settingsFile = new File(settingsFilename); } else { settingsFile = new File(System.getProperty("user.home"), ".sqshyrc"); } List<DriverMatch> driverInfos = new ArrayList<>(globalConfig.getDrivers()); List<DatabaseConnectionConfig> dcc = new ArrayList<>(); Configuration config = null; if (settingsFile.isFile()) { String filename = settingsFile.getAbsolutePath(); System.err.println("Loading settings file from " + filename); config = Configuration.loadFromFile(settingsFile); settings.getVariableManager().addVariables(config.getVariables()); if (config.getDrivers() != null) { driverInfos.addAll(config.getDrivers()); } List<DatabaseConnectionConfig> connections = config.getConnections(); if (connections != null) { dcc.addAll(connections); } } else { System.err.println("Warning: No settings file found in " + settingsFile.getAbsolutePath()); } String driverClass = cmdline.getStringValue("driver"); String url = cmdline.getStringValue("url"); String username = cmdline.getStringValue("username"); String password = cmdline.getStringValue("password"); if (password != null && password.equals("@")) { System.out.print("Password: "); password = new String(System.console().readPassword()); } List<String> properties = cmdline.getListValues("properties"); Map<String, String> connectionProperties = listToMap(properties); String alias = cmdline.getStringValue("connect"); settings.getVariableManager().addVariables(listToMap(cmdline.getListValues("set"))); Terminal terminal = TerminalFactory.create(); ConsoleReader reader = new ConsoleReader("sqshy", System.in, System.out, terminal); ConsoleLogger logger = new ConsoleLogger(settings, reader); ConnectionManager connectionManager = new ConnectionManager(settings, driverInfos, dcc); settings.init(logger, connectionManager); Commands commands = new Commands(settings); commands.addCommand("\\connect", ConnectCommand.class); commands.addCommand("\\disconnect", DisconnectCommand.class); commands.addCommand("\\reconnect", ReconnectCommand.class); commands.addCommand("\\set", SetCommand.class); commands.addCommand("\\echo", EchoCommand.class); if (url != null || alias != null) { connectionManager.connect(alias, driverClass, url, username, password, connectionProperties); } SqshyRepl repl = new SqshyRepl(reader, settings, commands); repl.repl(); }
diff --git a/src/main/java/pl/llp/aircasting/helper/GaugeHelper.java b/src/main/java/pl/llp/aircasting/helper/GaugeHelper.java index 15dabd9d..74c6cd68 100644 --- a/src/main/java/pl/llp/aircasting/helper/GaugeHelper.java +++ b/src/main/java/pl/llp/aircasting/helper/GaugeHelper.java @@ -1,93 +1,93 @@ package pl.llp.aircasting.helper; import pl.llp.aircasting.MarkerSize; import pl.llp.aircasting.R; import pl.llp.aircasting.model.Sensor; import pl.llp.aircasting.model.SessionManager; import android.util.TypedValue; import android.view.View; import android.widget.TextView; import com.google.inject.Inject; import com.google.inject.Singleton; import roboguice.inject.InjectResource; import static java.lang.String.valueOf; @Singleton public class GaugeHelper { @Inject ResourceHelper resourceHelper; @Inject SettingsHelper settingsHelper; @Inject SessionManager sessionManager; @InjectResource(R.string.avg_label_template) String avgLabel; @InjectResource(R.string.now_label_template) String nowLabel; @InjectResource(R.string.peak_label_template) String peakLabel; /** * Update a set of now/avg/peak gauges * * @param sensor The Sensor from which the readings are taken * @param view The view containing the three gauges */ public void updateGauges(Sensor sensor, View view) { updateVisibility(view); int now = (int) sessionManager.getNow(sensor); updateGauge(view.findViewById(R.id.now_gauge), sensor, MarkerSize.BIG, now); updateLabel(sensor, view.findViewById(R.id.now_label), nowLabel); boolean hasStats = sessionManager.isSessionStarted() || sessionManager.isSessionSaved(); - if (hasStats) + if (hasStats && sensor.isEnabled()) { int avg = (int) sessionManager.getAvg(sensor); int peak = (int) sessionManager.getPeak(sensor); updateGauge(view.findViewById(R.id.avg_gauge), sensor, MarkerSize.SMALL, avg); updateGauge(view.findViewById(R.id.peak_gauge), sensor, MarkerSize.SMALL, peak); updateLabel(sensor, view.findViewById(R.id.avg_label), avgLabel); updateLabel(sensor, view.findViewById(R.id.peak_label), peakLabel); } else { displayInactiveGauge(view.findViewById(R.id.avg_gauge), MarkerSize.SMALL); displayInactiveGauge(view.findViewById(R.id.peak_gauge), MarkerSize.SMALL); } } private void updateVisibility(View view) { View nowContainer = view.findViewById(R.id.now_container); nowContainer.setVisibility(sessionManager.isSessionSaved() ? View.GONE : View.VISIBLE); } private void updateLabel(Sensor sensor, View view, String label) { TextView textView = (TextView) view; String formatted = String.format(label, sensor.getShortType()); textView.setText(formatted); } private void updateGauge(View view, Sensor sensor, MarkerSize size, int value) { TextView textView = (TextView) view; textView.setText(valueOf(value)); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, resourceHelper.getTextSize(value, size)); textView.setBackgroundDrawable(resourceHelper.getGauge(sensor, size, value)); } private void displayInactiveGauge(View view, MarkerSize size) { TextView textView = (TextView) view; textView.setText("--"); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, ResourceHelper.SMALL_GAUGE_SMALL_TEXT); textView.setBackgroundDrawable(resourceHelper.getDisabledGauge(size)); } }
true
true
public void updateGauges(Sensor sensor, View view) { updateVisibility(view); int now = (int) sessionManager.getNow(sensor); updateGauge(view.findViewById(R.id.now_gauge), sensor, MarkerSize.BIG, now); updateLabel(sensor, view.findViewById(R.id.now_label), nowLabel); boolean hasStats = sessionManager.isSessionStarted() || sessionManager.isSessionSaved(); if (hasStats) { int avg = (int) sessionManager.getAvg(sensor); int peak = (int) sessionManager.getPeak(sensor); updateGauge(view.findViewById(R.id.avg_gauge), sensor, MarkerSize.SMALL, avg); updateGauge(view.findViewById(R.id.peak_gauge), sensor, MarkerSize.SMALL, peak); updateLabel(sensor, view.findViewById(R.id.avg_label), avgLabel); updateLabel(sensor, view.findViewById(R.id.peak_label), peakLabel); } else { displayInactiveGauge(view.findViewById(R.id.avg_gauge), MarkerSize.SMALL); displayInactiveGauge(view.findViewById(R.id.peak_gauge), MarkerSize.SMALL); } }
public void updateGauges(Sensor sensor, View view) { updateVisibility(view); int now = (int) sessionManager.getNow(sensor); updateGauge(view.findViewById(R.id.now_gauge), sensor, MarkerSize.BIG, now); updateLabel(sensor, view.findViewById(R.id.now_label), nowLabel); boolean hasStats = sessionManager.isSessionStarted() || sessionManager.isSessionSaved(); if (hasStats && sensor.isEnabled()) { int avg = (int) sessionManager.getAvg(sensor); int peak = (int) sessionManager.getPeak(sensor); updateGauge(view.findViewById(R.id.avg_gauge), sensor, MarkerSize.SMALL, avg); updateGauge(view.findViewById(R.id.peak_gauge), sensor, MarkerSize.SMALL, peak); updateLabel(sensor, view.findViewById(R.id.avg_label), avgLabel); updateLabel(sensor, view.findViewById(R.id.peak_label), peakLabel); } else { displayInactiveGauge(view.findViewById(R.id.avg_gauge), MarkerSize.SMALL); displayInactiveGauge(view.findViewById(R.id.peak_gauge), MarkerSize.SMALL); } }
diff --git a/src/main/java/hudson/plugins/yammer/YammerPublisher.java b/src/main/java/hudson/plugins/yammer/YammerPublisher.java index 61304ab..6b2f6a0 100644 --- a/src/main/java/hudson/plugins/yammer/YammerPublisher.java +++ b/src/main/java/hudson/plugins/yammer/YammerPublisher.java @@ -1,413 +1,414 @@ package hudson.plugins.yammer; import hudson.Extension; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.Result; import hudson.model.AbstractBuild; import hudson.model.Descriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.client.ClientProtocolException; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * <p> * When the user configures the project and enables this publisher, * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked and a new * {@link YammerPublisher} is created. The created instance is persisted to the * project configuration XML by using XStream, so this allows you to use * instance fields (like {@link #name}) to remember the configuration. * * <p> * When a build is performed, the * {@link #perform(Build, Launcher, BuildListener)} method will be invoked. * * @author Russell Hart */ public class YammerPublisher extends Publisher { protected static final Log LOGGER = LogFactory.getLog(YammerPublisher.class .getName()); /** * The name of the Yammer group to post the build result too. */ private String yammerGroup; /** * The id of the Yammer group to post the build result too. */ private String yammerGroupId; /** * A flag to indicate which build results should be posted to Yammer. */ private BuildResultPostOption buildResultPostOption; /** * People to notify */ private String peopleToNotify; /** * Get's called on saving the project specific config. * * @param yammerGroup */ @SuppressWarnings("deprecation") @DataBoundConstructor public YammerPublisher(String peopleToNotify, String yammerGroup, BuildResultPostOption buildResultPostOption) { this.peopleToNotify = peopleToNotify; this.yammerGroup = yammerGroup; this.buildResultPostOption = buildResultPostOption; if (this.yammerGroup != null & !this.yammerGroup.equals("")) { try { this.yammerGroupId = YammerUtils.getGroupId( ((DescriptorImpl) getDescriptor()).accessAuthToken, ((DescriptorImpl) getDescriptor()).accessAuthSecret, this.yammerGroup, ((DescriptorImpl) getDescriptor()).applicationKey, ((DescriptorImpl) getDescriptor()).applicationSecret); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage()); // throw new RuntimeException(e); } } } public String getPeopleToNotify() { return this.peopleToNotify; } public String getYammerGroup() { return this.yammerGroup; } public BuildResultPostOption getBuildResultPostOption() { return this.buildResultPostOption; } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#perform(hudson.model.AbstractBuild * , hudson.Launcher, hudson.model.BuildListener) */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException { DescriptorImpl descriptor = (DescriptorImpl) getDescriptor(); boolean sendMessage = false; switch (this.buildResultPostOption) { case ALL: sendMessage = true; break; case SUCCESS: if (build.getResult() == Result.SUCCESS) { sendMessage = true; } break; case FAILURES_ONLY: if (build.getResult() != Result.SUCCESS) { sendMessage = true; } break; case ABORTED_ONLY: if (build.getResult() == Result.ABORTED) { sendMessage = true; } break; case STATUS_CHANGE: - if (build.getResult() != build.getPreviousBuild().getResult()) { + if (build.getPreviousBuild() == null + || build.getResult() != build.getPreviousBuild().getResult()) { sendMessage = true; } break; } // if (!this.postOnlyFailures || (this.postOnlyFailures && // build.getResult() != Result.SUCCESS)) { if (sendMessage) { YammerUtils.sendMessage(descriptor.accessAuthToken, descriptor.accessAuthSecret, createBuildMessageFromResults(build), this.yammerGroupId, descriptor.applicationKey, descriptor.applicationSecret); listener.getLogger().println("YammerNofier: Send notification to " + this.yammerGroup); } return true; } /** * Create a message from the build results. * * @param build * @return */ private String createBuildMessageFromResults(AbstractBuild<?, ?> build) { String hudsonUrl = ((DescriptorImpl) getDescriptor()).hudsonUrl; String absoluteBuildURL = hudsonUrl.endsWith("/") ? hudsonUrl + build.getUrl() : hudsonUrl + "/" + build.getUrl(); StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("Hudson Build Results - "); messageBuilder.append(build.getFullDisplayName()); messageBuilder.append(" "); messageBuilder.append(build.getResult().toString()); messageBuilder.append(" "); messageBuilder.append(absoluteBuildURL); messageBuilder.append("\n"); messageBuilder.append(peopleToNotifyText()); return messageBuilder.toString(); } private String peopleToNotifyText() { if (StringUtils.isEmpty(getPeopleToNotify())) { return null; } String[] ppl = getPeopleToNotify().replaceAll("\\s", "").split(","); if (ppl.length == 0) { return null; } StringBuilder sb = new StringBuilder(); for (String p : ppl) { sb.append("@").append(p).append(", "); } sb.setLength(sb.length() - 2); return sb.toString(); } @Extension public static final class DescriptorImpl extends Descriptor<Publisher> { /** * The key of the application registered with Yammer. See * http://www.yammer.com/client_applications/new */ private String applicationKey; /** * The secret of the application registered with Yammer. See * http://www.yammer.com/client_applications/new */ private String applicationSecret; /** * The Yammer request auth token used in getting the access token and * access authentication. See http://www.yammer.com/api_oauth.html */ private String requestAuthToken; /** * The Yammer request auth secret used in getting the access * authentication. See http://www.yammer.com/api_oauth.html */ private String requestAuthSecret; /** * The Yammer access token used in getting the access authentication. * See http://www.yammer.com/api_oauth.html */ private String accessToken; /** * The Yammer access auth token, needed for using the Yammer API */ private String accessAuthToken = ""; /** * The Yammer access auth secret, needed for using the Yammer API */ private String accessAuthSecret = ""; /** * The HTTP address of the Hudson installation, such as * http://yourhost.yourdomain/hudson/. This value is used to put links * into messages generated by Hudson. */ private String hudsonUrl; @Override public String getDisplayName() { return "Publish results in Yammer"; } public String accessToken() { return accessToken; } public String hudsonUrl() { return hudsonUrl; } public String applicationKey() { return applicationKey; } public String applicationSecret() { return applicationSecret; } public Boolean showAccessToken() { return (this.applicationKey != null && this.applicationSecret != null); } public DescriptorImpl() { super(YammerPublisher.class); // Load the saved configuration load(); } /** * Gets new oauth request auth parameters from Yammer for this plugin. * * @throws IOException * @throws ClientProtocolException */ private void initialseRequestAuthParameters() throws ClientProtocolException, IOException { Map<String, String> parametersMap; parametersMap = YammerUtils.getRequestTokenParameters( this.applicationKey, this.applicationSecret); this.requestAuthToken = parametersMap.get(YammerUtils.OAUTH_TOKEN); this.requestAuthSecret = parametersMap .get(YammerUtils.OAUTH_SECRET); } /* * (non-Javadoc) * * @see * hudson.model.Descriptor#configure(org.kohsuke.stapler.StaplerRequest, * net.sf.json.JSONObject) */ @Override public boolean configure(StaplerRequest req, JSONObject o) throws FormException { // to persist global configuration information, set that to // properties and call save(). // String newAccessToken = o.getString("accessToken"); this.hudsonUrl = o.getString("hudsonUrl"); this.applicationKey = o.getString("applicationKey"); this.applicationSecret = o.getString("applicationSecret"); this.accessToken = o.getString("accessToken"); save(); return super.configure(req, o); } /** * Get the access auth parameters from Yammer. See * http://www.yammer.com/api_oauth.html * * @throws FormException */ private void setAccessAuthParameters() throws FormException { Map<String, String> parametersMap; try { parametersMap = YammerUtils.getAccessTokenParameters( this.requestAuthToken, this.requestAuthSecret, this.accessToken, this.applicationKey, this.applicationSecret); this.accessAuthToken = parametersMap .get(YammerUtils.OAUTH_TOKEN); this.accessAuthSecret = parametersMap .get(YammerUtils.OAUTH_SECRET); } catch (Exception e) { throw new FormException(e.getCause(), "accessToken"); } } public void doGenerateAccessTokenLink( StaplerRequest req, StaplerResponse rsp, @QueryParameter("applicationKey") final String applicationKey, @QueryParameter("applicationSecret") final String applicationSecret) throws IOException, ServletException { try { this.applicationKey = applicationKey; this.applicationSecret = applicationSecret; initialseRequestAuthParameters(); save(); rsp.getWriter() .write("<a href='https://www.yammer.com/oauth/authorize?oauth_token=" + this.requestAuthToken + "' target='_blank'>Click here to get a new access token</a>"); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage()); e.printStackTrace(); } } public void doGetAccessAuthParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter("accessToken") final String accessToken) throws IOException, ServletException { try { this.accessToken = accessToken; setAccessAuthParameters(); save(); rsp.getWriter().write("Success"); } catch (Exception e) { LOGGER.error(e.getLocalizedMessage()); e.printStackTrace(); rsp.getWriter().write("Failed: " + e.getLocalizedMessage()); } } } public enum BuildResultPostOption { ALL("Post all results"), SUCCESS("Post successes only"), FAILURES_ONLY("Post failures only"), ABORTED_ONLY("Post aborts only"), STATUS_CHANGE("Post on status change"); private final String description; BuildResultPostOption(String description) { this.description = description; } public String description() { return this.description; } } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } }
true
true
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException { DescriptorImpl descriptor = (DescriptorImpl) getDescriptor(); boolean sendMessage = false; switch (this.buildResultPostOption) { case ALL: sendMessage = true; break; case SUCCESS: if (build.getResult() == Result.SUCCESS) { sendMessage = true; } break; case FAILURES_ONLY: if (build.getResult() != Result.SUCCESS) { sendMessage = true; } break; case ABORTED_ONLY: if (build.getResult() == Result.ABORTED) { sendMessage = true; } break; case STATUS_CHANGE: if (build.getResult() != build.getPreviousBuild().getResult()) { sendMessage = true; } break; } // if (!this.postOnlyFailures || (this.postOnlyFailures && // build.getResult() != Result.SUCCESS)) { if (sendMessage) { YammerUtils.sendMessage(descriptor.accessAuthToken, descriptor.accessAuthSecret, createBuildMessageFromResults(build), this.yammerGroupId, descriptor.applicationKey, descriptor.applicationSecret); listener.getLogger().println("YammerNofier: Send notification to " + this.yammerGroup); } return true; }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException { DescriptorImpl descriptor = (DescriptorImpl) getDescriptor(); boolean sendMessage = false; switch (this.buildResultPostOption) { case ALL: sendMessage = true; break; case SUCCESS: if (build.getResult() == Result.SUCCESS) { sendMessage = true; } break; case FAILURES_ONLY: if (build.getResult() != Result.SUCCESS) { sendMessage = true; } break; case ABORTED_ONLY: if (build.getResult() == Result.ABORTED) { sendMessage = true; } break; case STATUS_CHANGE: if (build.getPreviousBuild() == null || build.getResult() != build.getPreviousBuild().getResult()) { sendMessage = true; } break; } // if (!this.postOnlyFailures || (this.postOnlyFailures && // build.getResult() != Result.SUCCESS)) { if (sendMessage) { YammerUtils.sendMessage(descriptor.accessAuthToken, descriptor.accessAuthSecret, createBuildMessageFromResults(build), this.yammerGroupId, descriptor.applicationKey, descriptor.applicationSecret); listener.getLogger().println("YammerNofier: Send notification to " + this.yammerGroup); } return true; }
diff --git a/tests/org/intellij/erlang/ErlangParserTest.java b/tests/org/intellij/erlang/ErlangParserTest.java index 150985fe..051b05dc 100644 --- a/tests/org/intellij/erlang/ErlangParserTest.java +++ b/tests/org/intellij/erlang/ErlangParserTest.java @@ -1,49 +1,49 @@ package org.intellij.erlang; import com.intellij.testFramework.ParsingTestCase; /** * @author ignatov */ public class ErlangParserTest extends ParsingTestCase { public ErlangParserTest() { super("parser", "erl", new ErlangParserDefinition()); } @Override protected void setUp() throws Exception { super.setUp(); // addExplicitExtension(LanguageBraceMatching.INSTANCE, myLanguage, new ErlangBraceMatcher()); // todo } @Override protected String getTestDataPath() { return "testData"; } @Override protected boolean skipSpaces() { return true; } public void testHelloWorld() { doTest(true); } public void testExport() { doTest(true); } public void testH() { doTest(true); } public void testMnesia() { doTest(true); } public void testIsDigits() { doTest(true); } public void testDialyzerDataflow() { doTest(true); } public void testTest() { doTest(true); } public void testRecords() { doTest(true); } @Override protected void doTest(boolean checkResult) { - OVERWRITE_TESTDATA = true; +// OVERWRITE_TESTDATA = true; super.doTest(checkResult); assertFalse( "PsiFile contains error elements", toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement") ); } }
true
true
protected void doTest(boolean checkResult) { OVERWRITE_TESTDATA = true; super.doTest(checkResult); assertFalse( "PsiFile contains error elements", toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement") ); }
protected void doTest(boolean checkResult) { // OVERWRITE_TESTDATA = true; super.doTest(checkResult); assertFalse( "PsiFile contains error elements", toParseTreeText(myFile, skipSpaces(), includeRanges()).contains("PsiErrorElement") ); }
diff --git a/src/org/jruby/evaluator/EvaluationState.java b/src/org/jruby/evaluator/EvaluationState.java index ffc80edae..bed1bc9d8 100644 --- a/src/org/jruby/evaluator/EvaluationState.java +++ b/src/org/jruby/evaluator/EvaluationState.java @@ -1,1972 +1,1981 @@ /******************************************************************************* * BEGIN LICENSE BLOCK *** Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public License Version * 1.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Copyright (C) 2006 Charles Oliver Nutter <[email protected]> * Copytight (C) 2006-2007 Thomas E Enebo <[email protected]> * Copyright (C) 2007 Miguel Covarrubias <[email protected]> * Copyright (C) 2007 Ola Bini <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in * which case the provisions of the GPL or the LGPL are applicable instead of * those above. If you wish to allow use of your version of this file only under * the terms of either the GPL or the LGPL, and not to allow others to use your * version of this file under the terms of the CPL, indicate your decision by * deleting the provisions above and replace them with the notice and other * provisions required by the GPL or the LGPL. If you do not delete the * provisions above, a recipient may use your version of this file under the * terms of any one of the CPL, the GPL or the LGPL. END LICENSE BLOCK **** ******************************************************************************/ package org.jruby.evaluator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.jruby.Ruby; import org.jruby.MetaClass; import org.jruby.RubyArray; import org.jruby.RubyBignum; import org.jruby.RubyClass; import org.jruby.RubyException; import org.jruby.RubyFloat; import org.jruby.RubyHash; import org.jruby.RubyKernel; import org.jruby.RubyModule; import org.jruby.RubyObject; import org.jruby.RubyProc; import org.jruby.RubyRange; import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.ast.AliasNode; import org.jruby.ast.ArgsCatNode; import org.jruby.ast.ArgsNode; import org.jruby.ast.ArgsPushNode; import org.jruby.ast.ArrayNode; import org.jruby.ast.AttrAssignNode; import org.jruby.ast.BackRefNode; import org.jruby.ast.BeginNode; import org.jruby.ast.BignumNode; import org.jruby.ast.BinaryOperatorNode; import org.jruby.ast.BlockNode; import org.jruby.ast.BlockPassNode; import org.jruby.ast.BreakNode; import org.jruby.ast.CallNode; import org.jruby.ast.CaseNode; import org.jruby.ast.ClassNode; import org.jruby.ast.ClassVarAsgnNode; import org.jruby.ast.ClassVarDeclNode; import org.jruby.ast.ClassVarNode; import org.jruby.ast.Colon2Node; import org.jruby.ast.Colon3Node; import org.jruby.ast.ConstDeclNode; import org.jruby.ast.ConstNode; import org.jruby.ast.DAsgnNode; import org.jruby.ast.DRegexpNode; import org.jruby.ast.DStrNode; import org.jruby.ast.DSymbolNode; import org.jruby.ast.DVarNode; import org.jruby.ast.DXStrNode; import org.jruby.ast.DefinedNode; import org.jruby.ast.DefnNode; import org.jruby.ast.DefsNode; import org.jruby.ast.DotNode; import org.jruby.ast.EnsureNode; import org.jruby.ast.EvStrNode; import org.jruby.ast.FCallNode; import org.jruby.ast.FixnumNode; import org.jruby.ast.FlipNode; import org.jruby.ast.FloatNode; import org.jruby.ast.ForNode; import org.jruby.ast.GlobalAsgnNode; import org.jruby.ast.GlobalVarNode; import org.jruby.ast.HashNode; import org.jruby.ast.IfNode; import org.jruby.ast.InstAsgnNode; import org.jruby.ast.InstVarNode; import org.jruby.ast.IterNode; import org.jruby.ast.ListNode; import org.jruby.ast.LocalAsgnNode; import org.jruby.ast.LocalVarNode; import org.jruby.ast.Match2Node; import org.jruby.ast.Match3Node; import org.jruby.ast.MatchNode; import org.jruby.ast.ModuleNode; import org.jruby.ast.MultipleAsgnNode; import org.jruby.ast.NewlineNode; import org.jruby.ast.NextNode; import org.jruby.ast.Node; import org.jruby.ast.NodeTypes; import org.jruby.ast.NotNode; import org.jruby.ast.NthRefNode; import org.jruby.ast.OpAsgnNode; import org.jruby.ast.OpAsgnOrNode; import org.jruby.ast.OpElementAsgnNode; import org.jruby.ast.OptNNode; import org.jruby.ast.OrNode; import org.jruby.ast.RegexpNode; import org.jruby.ast.RescueBodyNode; import org.jruby.ast.RescueNode; import org.jruby.ast.ReturnNode; import org.jruby.ast.RootNode; import org.jruby.ast.SClassNode; import org.jruby.ast.SValueNode; import org.jruby.ast.SplatNode; import org.jruby.ast.StrNode; import org.jruby.ast.SuperNode; import org.jruby.ast.SymbolNode; import org.jruby.ast.ToAryNode; import org.jruby.ast.UndefNode; import org.jruby.ast.UntilNode; import org.jruby.ast.VAliasNode; import org.jruby.ast.VCallNode; import org.jruby.ast.WhenNode; import org.jruby.ast.WhileNode; import org.jruby.ast.XStrNode; import org.jruby.ast.YieldNode; import org.jruby.ast.ZSuperNode; import org.jruby.ast.types.INameNode; import org.jruby.ast.util.ArgsUtil; import org.jruby.exceptions.JumpException; import org.jruby.exceptions.RaiseException; import org.jruby.exceptions.JumpException.JumpType; import org.jruby.internal.runtime.methods.DefaultMethod; import org.jruby.internal.runtime.methods.DynamicMethod; import org.jruby.internal.runtime.methods.WrapperMethod; import org.jruby.lexer.yacc.ISourcePosition; import org.jruby.parser.StaticScope; import org.jruby.runtime.Block; import org.jruby.runtime.CallType; import org.jruby.runtime.DynamicScope; import org.jruby.runtime.ForBlock; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; import org.jruby.util.KCode; import org.jruby.util.collections.SinglyLinkedList; public class EvaluationState { public static IRubyObject eval(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block block) { try { return evalInternal(runtime, context, node, self, block); } catch (StackOverflowError sfe) { throw runtime.newSystemStackError("stack level too deep"); } } /* Something like cvar_cbase() from eval.c, factored out for the benefit * of all the classvar-related node evaluations */ private static RubyModule getClassVariableBase(ThreadContext context, Ruby runtime) { SinglyLinkedList cref = context.peekCRef(); RubyModule rubyClass = (RubyModule) cref.getValue(); if (rubyClass.isSingleton()) { cref = cref.getNext(); rubyClass = (RubyModule) cref.getValue(); if (cref.getNext() == null) { runtime.getWarnings().warn("class variable access from toplevel singleton method"); } } return rubyClass; } private static IRubyObject evalInternal(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block aBlock) { bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); IRubyObject secondArgs = splatValue(runtime, evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock).dup(); return args.append(evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(runtime,context, next, self, aBlock); } return runtime.newArrayNoCopy(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(runtime,context, (Node) iter.next(), self, aBlock); } return result; } case NodeTypes.BLOCKPASSNODE: assert false: "Call nodes and friends deal with this"; case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setValue(result); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); RubyModule module = receiver.getMetaClass(); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { if (module.index != 0 && iVisited.index != 0) { return receiver.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.NORMAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, block); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(runtime,context, iVisited.getCaseNode(), self, aBlock); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(runtime,context, ((WhenNode) tag) .getExpressionNodes(), self, aBlock); for (int j = 0,k = expressions.getLength(); j < k; j++) { IRubyObject condition = expressions.eltInternal(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(runtime,context, tag, self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(runtime,context, whenNode.getExpressionNodes(), self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = null; if(superNode != null) { IRubyObject _super = evalInternal(runtime,context, superNode, self, aBlock); if(!(_super instanceof RubyClass)) { throw runtime.newTypeError("superclass must be a Class (" + RubyObject.trueFalseNil(_super) + ") given"); } superClass = superNode == null ? null : (RubyClass)_super; } Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(runtime, context, classNameNode, self, aBlock); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self, aBlock); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(runtime,context, iVisited.getLeftNode(), self, aBlock); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName(), aBlock); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; Node constNode = iVisited.getConstNode(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); IRubyObject module; if (constNode == null) { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } else if (constNode instanceof Colon2Node) { module = evalInternal(runtime,context, ((Colon2Node) iVisited.getConstNode()).getLeftNode(), self, aBlock); } else { // Colon3 module = runtime.getObject(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(runtime, context, iVisited.getExpressionNode(), self, aBlock); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction() || context.isTopLevel()) { visibility = Visibility.PRIVATE; } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { Object method = rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, string.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return string; } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return runtime.newSymbol(string.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return self.callMethod(context, "`", string); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); } finally { evalInternal(runtime,context, iVisited.getEnsureNode(), self, aBlock); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; return evalInternal(runtime,context, iVisited.getBody(), self, aBlock).objAsString(); } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.FUNCTIONAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), args, self, CallType.FUNCTIONAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { RubyModule module = self.getMetaClass(); IRubyObject result = self.callMethod(context, module, iVisited.getName(), args, CallType.FUNCTIONAL, block); if (result == null) { result = runtime.getNil(); } return result; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: // JRUBY-530, Kernel#loop case: if (je.isBreakInKernelLoop()) { // consume and rethrow or just keep rethrowing? if (block == je.getTarget()) je.setBreakInKernelLoop(false); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; Block block = ForBlock.createBlock(context, iVisited.getVarNode(), context.getCurrentScope(), iVisited.getCallable(), self); try { while (true) { try { ISourcePosition position = context.getPosition(); IRubyObject recv = null; try { recv = evalInternal(runtime,context, iVisited.getIterNode(), self, aBlock); } finally { context.setPosition(position); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (iVisited.getName().length() == 2) { switch (iVisited.getName().charAt(1)) { case '_': context.getCurrentScope().setLastLine(result); return result; case '~': context.getCurrentScope().setBackRef(result); return result; } } runtime.getGlobalVariables().set(iVisited.getName(), result); // FIXME: this should be encapsulated along with the set above if (iVisited.getName() == "$KCODE") { runtime.setKCode(KCode.create(runtime, result.toString())); } return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; if (iVisited.getName().length() == 2) { + IRubyObject value = null; switch (iVisited.getName().charAt(1)) { case '_': - return context.getCurrentScope().getLastLine(); + value = context.getCurrentScope().getLastLine(); + if (value == null) { + return runtime.getNil(); + } + return value; case '~': - return context.getCurrentScope().getBackRef(); + value = context.getCurrentScope().getBackRef(); + if (value == null) { + return runtime.getNil(); + } + return value; } } return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); IRubyObject value = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getCondition(), self, aBlock); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: assert false: "Call nodes deal with these directly"; case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(runtime,context, iVisited.getRegexpNode(), self, aBlock)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(runtime, context, classNameNode, self, aBlock); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), module, self, aBlock); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (!(value instanceof RubyArray)) { value = RubyArray.newArray(runtime, value); } return AssignmentVisitor.multiAssign(runtime, context, self, iVisited, (RubyArray) value, false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setTarget(iVisited); je.setValue(result); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(runtime, context, iVisited.getFirstNode(), self, aBlock); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); } if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited .getValueNode(), self, aBlock)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setValue(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(runtime,context, iVisited.getElseNode(), self, aBlock); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(runtime,context, exceptionNodes, self, aBlock); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(runtime, context, raisedException, exceptionNodesList, self)) { try { return evalInternal(runtime,context, rescueNode, self, aBlock); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setTarget(iVisited.getTarget()); je.setValue(result); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(runtime, context, iVisited.getBodyNode(), self, aBlock); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self, aBlock); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString((ByteList) iVisited.getValue().clone()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // If no explicit block passed to super, then use the one passed in. if (!block.isGiven()) block = aBlock; return context.callSuper(args, block); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530 until case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), IRubyObject.NULL_ARRAY, self, CallType.VARIABLE, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), IRubyObject.NULL_ARRAY, false, Block.NULL_BLOCK); } } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530, while case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString((ByteList) iVisited.getValue().clone())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getArgsNode(), self, aBlock); if (iVisited.getArgsNode() == null) { result = null; } Block block = context.getCurrentFrame().getBlock(); return block.yield(context, result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } Block block = getBlock(runtime, context, self, aBlock, ((ZSuperNode) node).getIterNode()); // Has the method that is calling super received a block argument if (!block.isGiven()) block = context.getCurrentFrame().getBlock(); return context.callSuper(context.getFrameArgs(), block); } default: throw new RuntimeException("Invalid node encountered in interpreter: \"" + node.getClass().getName() + "\", please report this at www.jruby.org"); } } while (true); } private static String getArgumentDefinition(Ruby runtime, ThreadContext context, Node node, String type, IRubyObject self, Block block) { if (node == null) return type; if (node instanceof ArrayNode) { for (Iterator iter = ((ArrayNode)node).iterator(); iter.hasNext(); ) { if (getDefinitionInner(runtime, context, (Node)iter.next(), self, block) == null) return null; } } else if (getDefinitionInner(runtime, context, node, self, block) == null) { return null; } return type; } private static String getDefinition(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block aBlock) { try { context.setWithinDefined(true); return getDefinitionInner(runtime, context, node, self, aBlock); } finally { context.setWithinDefined(false); } } private static String getDefinitionInner(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block aBlock) { if (node == null) return "expression"; switch(node.nodeId) { case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; if (getDefinitionInner(runtime, context, iVisited.getReceiverNode(), self, aBlock) != null) { try { IRubyObject receiver = eval(runtime, context, iVisited.getReceiverNode(), self, aBlock); RubyClass metaClass = receiver.getMetaClass(); DynamicMethod method = metaClass.searchMethod(iVisited.getName()); Visibility visibility = method.getVisibility(); if (!visibility.isPrivate() && (!visibility.isProtected() || self.isKindOf(metaClass.getRealClass()))) { if (metaClass.isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(runtime,context, iVisited.getArgsNode(), "assignment", self, aBlock); } } } catch (JumpException excptn) { } } return null; } case NodeTypes.BACKREFNODE: return "$" + ((BackRefNode) node).getType(); case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; if (getDefinitionInner(runtime, context, iVisited.getReceiverNode(), self, aBlock) != null) { try { IRubyObject receiver = eval(runtime, context, iVisited.getReceiverNode(), self, aBlock); RubyClass metaClass = receiver.getMetaClass(); DynamicMethod method = metaClass.searchMethod(iVisited.getName()); Visibility visibility = method.getVisibility(); if (!visibility.isPrivate() && (!visibility.isProtected() || self.isKindOf(metaClass.getRealClass()))) { if (metaClass.isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(runtime, context, iVisited.getArgsNode(), "method", self, aBlock); } } } catch (JumpException excptn) { } } return null; } case NodeTypes.CLASSVARASGNNODE: case NodeTypes.CLASSVARDECLNODE: case NodeTypes.CONSTDECLNODE: case NodeTypes.DASGNNODE: case NodeTypes.GLOBALASGNNODE: case NodeTypes.LOCALASGNNODE: case NodeTypes.MULTIPLEASGNNODE: case NodeTypes.OPASGNNODE: case NodeTypes.OPELEMENTASGNNODE: return "assignment"; case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; if (context.getRubyClass() == null && self.getMetaClass().isClassVarDefined(iVisited.getName())) { return "class_variable"; } else if (!context.getRubyClass().isSingleton() && context.getRubyClass().isClassVarDefined(iVisited.getName())) { return "class_variable"; } RubyModule module = (RubyModule) context.getRubyClass().getInstanceVariable("__attached__"); if (module != null && module.isClassVarDefined(iVisited.getName())) return "class_variable"; return null; } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; try { IRubyObject left = EvaluationState.eval(runtime, context, iVisited.getLeftNode(), self, aBlock); if (left instanceof RubyModule && ((RubyModule) left).getConstantAt(iVisited.getName()) != null) { return "constant"; } else if (left.getMetaClass().isMethodBound(iVisited.getName(), true)) { return "method"; } } catch (JumpException excptn) {} return null; } case NodeTypes.CONSTNODE: if (context.getConstantDefined(((ConstNode) node).getName())) { return "constant"; } return null; case NodeTypes.DVARNODE: return "local-variable(in-block)"; case NodeTypes.FALSENODE: return "false"; case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; if (self.getMetaClass().isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(runtime, context, iVisited.getArgsNode(), "method", self, aBlock); } return null; } case NodeTypes.GLOBALVARNODE: if (runtime.getGlobalVariables().isDefined(((GlobalVarNode) node).getName())) { return "global-variable"; } return null; case NodeTypes.INSTVARNODE: if (self.getInstanceVariable(((InstVarNode) node).getName()) != null) { return "instance-variable"; } return null; case NodeTypes.LOCALVARNODE: return "local-variable"; case NodeTypes.MATCH2NODE: case NodeTypes.MATCH3NODE: return "method"; case NodeTypes.NILNODE: return "nil"; case NodeTypes.NTHREFNODE: return "$" + ((NthRefNode) node).getMatchNumber(); case NodeTypes.SELFNODE: return "state.getSelf()"; case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; String name = context.getFrameName(); RubyModule klazz = context.getFrameKlazz(); if (name != null && klazz != null && klazz.getSuperClass().isMethodBound(name, false)) { return getArgumentDefinition(runtime, context, iVisited.getArgsNode(), "super", self, aBlock); } return null; } case NodeTypes.TRUENODE: return "true"; case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; if (self.getMetaClass().isMethodBound(iVisited.getName(), false)) { return "method"; } return null; } case NodeTypes.YIELDNODE: return aBlock.isGiven() ? "yield" : null; case NodeTypes.ZSUPERNODE: { String name = context.getFrameName(); RubyModule klazz = context.getFrameKlazz(); if (name != null && klazz != null && klazz.getSuperClass().isMethodBound(name, false)) { return "super"; } return null; } default: try { EvaluationState.eval(runtime, context, node, self, aBlock); return "expression"; } catch (JumpException jumpExcptn) {} } return null; } private static IRubyObject aryToAry(Ruby runtime, IRubyObject value) { if (value instanceof RubyArray) return value; if (value.respondsTo("to_ary")) { return value.convertToType("Array", "to_ary", false); } return runtime.newArray(value); } /** Evaluates the body in a class or module definition statement. * */ private static IRubyObject evalClassDefinitionBody(Ruby runtime, ThreadContext context, StaticScope scope, Node bodyNode, RubyModule type, IRubyObject self, Block block) { context.preClassEval(scope, type); try { if (isTrace(runtime)) { callTraceFunction(runtime, context, "class", type); } return evalInternal(runtime,context, bodyNode, type, block); } finally { context.postClassEval(); if (isTrace(runtime)) { callTraceFunction(runtime, context, "end", null); } } } /** * Helper method. * * test if a trace function is avaiable. * */ private static boolean isTrace(Ruby runtime) { return runtime.getTraceFunction() != null; } private static void callTraceFunction(Ruby runtime, ThreadContext context, String event, IRubyObject zelf) { String name = context.getFrameName(); RubyModule type = context.getFrameKlazz(); runtime.callTraceFunction(context, event, context.getPosition(), zelf, name, type); } public static IRubyObject splatValue(Ruby runtime, IRubyObject value) { if (value.isNil()) { return runtime.newArray(value); } return arrayValue(runtime, value); } public static IRubyObject aValueSplat(Ruby runtime, IRubyObject value) { if (!(value instanceof RubyArray) || ((RubyArray) value).length().getLongValue() == 0) { return runtime.getNil(); } RubyArray array = (RubyArray) value; return array.getLength() == 1 ? array.first(IRubyObject.NULL_ARRAY) : array; } public static RubyArray arrayValue(Ruby runtime, IRubyObject value) { IRubyObject newValue = value.convertToType("Array", "to_ary", false); if (newValue.isNil()) { // Object#to_a is obsolete. We match Ruby's hack until to_a goes away. Then we can // remove this hack too. if (value.getMetaClass().searchMethod("to_a").getImplementationClass() != runtime .getKernel()) { newValue = value.convertToType("Array", "to_a", false); if (newValue.getType() != runtime.getClass("Array")) { throw runtime.newTypeError("`to_a' did not return Array"); } } else { newValue = runtime.newArray(value); } } return (RubyArray) newValue; } private static IRubyObject[] setupArgs(Ruby runtime, ThreadContext context, Node node, IRubyObject self) { if (node == null) return IRubyObject.NULL_ARRAY; if (node instanceof ArrayNode) { ArrayNode argsArrayNode = (ArrayNode) node; ISourcePosition position = context.getPosition(); int size = argsArrayNode.size(); IRubyObject[] argsArray = new IRubyObject[size]; for (int i = 0; i < size; i++) { argsArray[i] = evalInternal(runtime,context, argsArrayNode.get(i), self, Block.NULL_BLOCK); } context.setPosition(position); return argsArray; } return ArgsUtil.convertToJavaArray(evalInternal(runtime,context, node, self, Block.NULL_BLOCK)); } private static RubyModule getEnclosingModule(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block block) { RubyModule enclosingModule = null; if (node instanceof Colon2Node) { IRubyObject result = evalInternal(runtime,context, ((Colon2Node) node).getLeftNode(), self, block); if (result != null && !result.isNil()) { enclosingModule = (RubyModule) result; } } else if (node instanceof Colon3Node) { enclosingModule = runtime.getObject(); } if (enclosingModule == null) { enclosingModule = (RubyModule) context.peekCRef().getValue(); } return enclosingModule; } private static boolean isRescueHandled(Ruby runtime, ThreadContext context, RubyException currentException, ListNode exceptionNodes, IRubyObject self) { if (exceptionNodes == null) { return currentException.isKindOf(runtime.getClass("StandardError")); } IRubyObject[] args = setupArgs(runtime, context, exceptionNodes, self); for (int i = 0; i < args.length; i++) { if (!args[i].isKindOf(runtime.getClass("Module"))) { throw runtime.newTypeError("class or module required for rescue clause"); } if (args[i].callMethod(context, "===", currentException).isTrue()) return true; } return false; } public static Block getBlock(Ruby runtime, ThreadContext context, IRubyObject self, Block currentBlock, Node blockNode) { if (blockNode == null) return Block.NULL_BLOCK; if (blockNode instanceof IterNode) { IterNode iterNode = (IterNode) blockNode; // Create block for this iter node return Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self); } else if (blockNode instanceof BlockPassNode) { BlockPassNode blockPassNode = (BlockPassNode) blockNode; IRubyObject proc = evalInternal(runtime,context, blockPassNode.getBodyNode(), self, currentBlock); // No block from a nil proc if (proc.isNil()) return Block.NULL_BLOCK; // If not already a proc then we should try and make it one. if (!(proc instanceof RubyProc)) { proc = proc.convertToType("Proc", "to_proc", false); if (!(proc instanceof RubyProc)) { throw runtime.newTypeError("wrong argument type " + proc.getMetaClass().getName() + " (expected Proc)"); } } // TODO: Add safety check for taintedness if (currentBlock.isGiven()) { RubyProc procObject = currentBlock.getProcObject(); // The current block is already associated with proc. No need to create a new one if (procObject != null && procObject == proc) return currentBlock; } return ((RubyProc) proc).getBlock(); } assert false: "Trying to get block from something which cannot deliver"; return null; } }
false
true
private static IRubyObject evalInternal(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block aBlock) { bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); IRubyObject secondArgs = splatValue(runtime, evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock).dup(); return args.append(evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(runtime,context, next, self, aBlock); } return runtime.newArrayNoCopy(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(runtime,context, (Node) iter.next(), self, aBlock); } return result; } case NodeTypes.BLOCKPASSNODE: assert false: "Call nodes and friends deal with this"; case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setValue(result); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); RubyModule module = receiver.getMetaClass(); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { if (module.index != 0 && iVisited.index != 0) { return receiver.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.NORMAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, block); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(runtime,context, iVisited.getCaseNode(), self, aBlock); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(runtime,context, ((WhenNode) tag) .getExpressionNodes(), self, aBlock); for (int j = 0,k = expressions.getLength(); j < k; j++) { IRubyObject condition = expressions.eltInternal(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(runtime,context, tag, self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(runtime,context, whenNode.getExpressionNodes(), self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = null; if(superNode != null) { IRubyObject _super = evalInternal(runtime,context, superNode, self, aBlock); if(!(_super instanceof RubyClass)) { throw runtime.newTypeError("superclass must be a Class (" + RubyObject.trueFalseNil(_super) + ") given"); } superClass = superNode == null ? null : (RubyClass)_super; } Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(runtime, context, classNameNode, self, aBlock); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self, aBlock); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(runtime,context, iVisited.getLeftNode(), self, aBlock); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName(), aBlock); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; Node constNode = iVisited.getConstNode(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); IRubyObject module; if (constNode == null) { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } else if (constNode instanceof Colon2Node) { module = evalInternal(runtime,context, ((Colon2Node) iVisited.getConstNode()).getLeftNode(), self, aBlock); } else { // Colon3 module = runtime.getObject(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(runtime, context, iVisited.getExpressionNode(), self, aBlock); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction() || context.isTopLevel()) { visibility = Visibility.PRIVATE; } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { Object method = rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, string.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return string; } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return runtime.newSymbol(string.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return self.callMethod(context, "`", string); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); } finally { evalInternal(runtime,context, iVisited.getEnsureNode(), self, aBlock); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; return evalInternal(runtime,context, iVisited.getBody(), self, aBlock).objAsString(); } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.FUNCTIONAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), args, self, CallType.FUNCTIONAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { RubyModule module = self.getMetaClass(); IRubyObject result = self.callMethod(context, module, iVisited.getName(), args, CallType.FUNCTIONAL, block); if (result == null) { result = runtime.getNil(); } return result; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: // JRUBY-530, Kernel#loop case: if (je.isBreakInKernelLoop()) { // consume and rethrow or just keep rethrowing? if (block == je.getTarget()) je.setBreakInKernelLoop(false); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; Block block = ForBlock.createBlock(context, iVisited.getVarNode(), context.getCurrentScope(), iVisited.getCallable(), self); try { while (true) { try { ISourcePosition position = context.getPosition(); IRubyObject recv = null; try { recv = evalInternal(runtime,context, iVisited.getIterNode(), self, aBlock); } finally { context.setPosition(position); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (iVisited.getName().length() == 2) { switch (iVisited.getName().charAt(1)) { case '_': context.getCurrentScope().setLastLine(result); return result; case '~': context.getCurrentScope().setBackRef(result); return result; } } runtime.getGlobalVariables().set(iVisited.getName(), result); // FIXME: this should be encapsulated along with the set above if (iVisited.getName() == "$KCODE") { runtime.setKCode(KCode.create(runtime, result.toString())); } return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; if (iVisited.getName().length() == 2) { switch (iVisited.getName().charAt(1)) { case '_': return context.getCurrentScope().getLastLine(); case '~': return context.getCurrentScope().getBackRef(); } } return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); IRubyObject value = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getCondition(), self, aBlock); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: assert false: "Call nodes deal with these directly"; case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(runtime,context, iVisited.getRegexpNode(), self, aBlock)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(runtime, context, classNameNode, self, aBlock); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), module, self, aBlock); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (!(value instanceof RubyArray)) { value = RubyArray.newArray(runtime, value); } return AssignmentVisitor.multiAssign(runtime, context, self, iVisited, (RubyArray) value, false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setTarget(iVisited); je.setValue(result); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(runtime, context, iVisited.getFirstNode(), self, aBlock); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); } if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited .getValueNode(), self, aBlock)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setValue(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(runtime,context, iVisited.getElseNode(), self, aBlock); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(runtime,context, exceptionNodes, self, aBlock); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(runtime, context, raisedException, exceptionNodesList, self)) { try { return evalInternal(runtime,context, rescueNode, self, aBlock); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setTarget(iVisited.getTarget()); je.setValue(result); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(runtime, context, iVisited.getBodyNode(), self, aBlock); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self, aBlock); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString((ByteList) iVisited.getValue().clone()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // If no explicit block passed to super, then use the one passed in. if (!block.isGiven()) block = aBlock; return context.callSuper(args, block); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530 until case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), IRubyObject.NULL_ARRAY, self, CallType.VARIABLE, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), IRubyObject.NULL_ARRAY, false, Block.NULL_BLOCK); } } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530, while case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString((ByteList) iVisited.getValue().clone())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getArgsNode(), self, aBlock); if (iVisited.getArgsNode() == null) { result = null; } Block block = context.getCurrentFrame().getBlock(); return block.yield(context, result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } Block block = getBlock(runtime, context, self, aBlock, ((ZSuperNode) node).getIterNode()); // Has the method that is calling super received a block argument if (!block.isGiven()) block = context.getCurrentFrame().getBlock(); return context.callSuper(context.getFrameArgs(), block); } default: throw new RuntimeException("Invalid node encountered in interpreter: \"" + node.getClass().getName() + "\", please report this at www.jruby.org"); } } while (true); }
private static IRubyObject evalInternal(Ruby runtime, ThreadContext context, Node node, IRubyObject self, Block aBlock) { bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); IRubyObject secondArgs = splatValue(runtime, evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock).dup(); return args.append(evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(runtime,context, next, self, aBlock); } return runtime.newArrayNoCopy(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(runtime,context, (Node) iter.next(), self, aBlock); } return result; } case NodeTypes.BLOCKPASSNODE: assert false: "Call nodes and friends deal with this"; case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setValue(result); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); RubyModule module = receiver.getMetaClass(); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { if (module.index != 0 && iVisited.index != 0) { return receiver.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.NORMAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, receiver, method, iVisited.getName(), args, self, CallType.NORMAL, block); if (mmResult != null) { return mmResult; } return method.call(context, receiver, module, iVisited.getName(), args, false, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(runtime,context, iVisited.getCaseNode(), self, aBlock); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(runtime,context, ((WhenNode) tag) .getExpressionNodes(), self, aBlock); for (int j = 0,k = expressions.getLength(); j < k; j++) { IRubyObject condition = expressions.eltInternal(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(runtime,context, tag, self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(runtime,context, whenNode.getExpressionNodes(), self, aBlock); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = null; if(superNode != null) { IRubyObject _super = evalInternal(runtime,context, superNode, self, aBlock); if(!(_super instanceof RubyClass)) { throw runtime.newTypeError("superclass must be a Class (" + RubyObject.trueFalseNil(_super) + ") given"); } superClass = superNode == null ? null : (RubyClass)_super; } Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(runtime, context, classNameNode, self, aBlock); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self, aBlock); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = getClassVariableBase(context, runtime); if (rubyClass == null) { rubyClass = self.getMetaClass(); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(runtime,context, iVisited.getLeftNode(), self, aBlock); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName(), aBlock); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; Node constNode = iVisited.getConstNode(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); IRubyObject module; if (constNode == null) { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } else if (constNode instanceof Colon2Node) { module = evalInternal(runtime,context, ((Colon2Node) iVisited.getConstNode()).getLeftNode(), self, aBlock); } else { // Colon3 module = runtime.getObject(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(runtime, context, iVisited.getExpressionNode(), self, aBlock); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction() || context.isTopLevel()) { visibility = Visibility.PRIVATE; } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { Object method = rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, string.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return string; } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return runtime.newSymbol(string.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; RubyString string = runtime.newString(new ByteList()); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); if (iterNode instanceof StrNode) { string.getByteList().append(((StrNode) iterNode).getValue()); } else { string.append(evalInternal(runtime,context, iterNode, self, aBlock)); } } return self.callMethod(context, "`", string); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); } finally { evalInternal(runtime,context, iVisited.getEnsureNode(), self, aBlock); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; return evalInternal(runtime,context, iVisited.getBody(), self, aBlock).objAsString(); } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // No block provided lets look at fast path for STI dispatch. if (!block.isGiven()) { RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), args, CallType.FUNCTIONAL, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), args, self, CallType.FUNCTIONAL, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), args, false, Block.NULL_BLOCK); } } try { while (true) { try { RubyModule module = self.getMetaClass(); IRubyObject result = self.callMethod(context, module, iVisited.getName(), args, CallType.FUNCTIONAL, block); if (result == null) { result = runtime.getNil(); } return result; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: // JRUBY-530, Kernel#loop case: if (je.isBreakInKernelLoop()) { // consume and rethrow or just keep rethrowing? if (block == je.getTarget()) je.setBreakInKernelLoop(false); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(runtime,context, iVisited.getBeginNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(runtime,context, iVisited.getEndNode(), self, aBlock).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; Block block = ForBlock.createBlock(context, iVisited.getVarNode(), context.getCurrentScope(), iVisited.getCallable(), self); try { while (true) { try { ISourcePosition position = context.getPosition(); IRubyObject recv = null; try { recv = evalInternal(runtime,context, iVisited.getIterNode(), self, aBlock); } finally { context.setPosition(position); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL, block); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: return (IRubyObject) je.getValue(); default: throw je; } } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (iVisited.getName().length() == 2) { switch (iVisited.getName().charAt(1)) { case '_': context.getCurrentScope().setLastLine(result); return result; case '~': context.getCurrentScope().setBackRef(result); return result; } } runtime.getGlobalVariables().set(iVisited.getName(), result); // FIXME: this should be encapsulated along with the set above if (iVisited.getName() == "$KCODE") { runtime.setKCode(KCode.create(runtime, result.toString())); } return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; if (iVisited.getName().length() == 2) { IRubyObject value = null; switch (iVisited.getName().charAt(1)) { case '_': value = context.getCurrentScope().getLastLine(); if (value == null) { return runtime.getNil(); } return value; case '~': value = context.getCurrentScope().getBackRef(); if (value == null) { return runtime.getNil(); } return value; } } return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); IRubyObject value = evalInternal(runtime,context, (Node) iterator.next(), self, aBlock); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getCondition(), self, aBlock); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: assert false: "Call nodes deal with these directly"; case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(runtime,context, iVisited.getRegexpNode(), self, aBlock)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(runtime, context, classNameNode, self, aBlock); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), module, self, aBlock); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; IRubyObject value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); if (!(value instanceof RubyArray)) { value = RubyArray.newArray(runtime, value); } return AssignmentVisitor.multiAssign(runtime, context, self, iVisited, (RubyArray) value, false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(runtime, context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setTarget(iVisited); je.setValue(result); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(runtime, context, iVisited.getFirstNode(), self, aBlock); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); } if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(runtime,context, iVisited .getValueNode(), self, aBlock)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getFirstNode(), self, aBlock); if (!result.isTrue()) { result = evalInternal(runtime,context, iVisited.getSecondNode(), self, aBlock); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setValue(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(runtime,context, iVisited.getElseNode(), self, aBlock); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(runtime,context, exceptionNodes, self, aBlock); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(runtime, context, raisedException, exceptionNodesList, self)) { try { return evalInternal(runtime,context, rescueNode, self, aBlock); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getValueNode(), self, aBlock); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setTarget(iVisited.getTarget()); je.setValue(result); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(runtime, context, iVisited.getBodyNode(), self, aBlock); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(runtime,context, iVisited.getReceiverNode(), self, aBlock); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(runtime, context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self, aBlock); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString((ByteList) iVisited.getValue().clone()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } IRubyObject[] args = setupArgs(runtime, context, iVisited.getArgsNode(), self); Block block = getBlock(runtime, context, self, aBlock, iVisited.getIterNode()); // If no explicit block passed to super, then use the one passed in. if (!block.isGiven()) block = aBlock; return context.callSuper(args, block); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(runtime, evalInternal(runtime,context, iVisited.getValue(), self, aBlock)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530 until case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return (IRubyObject) je.getValue(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; RubyModule module = self.getMetaClass(); if (module.index != 0 && iVisited.index != 0) { return self.callMethod(context, module, runtime.getSelectorTable().table[module.index][iVisited.index], iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE, Block.NULL_BLOCK); } else { DynamicMethod method = module.searchMethod(iVisited.getName()); IRubyObject mmResult = RubyObject.callMethodMissingIfNecessary(context, self, method, iVisited.getName(), IRubyObject.NULL_ARRAY, self, CallType.VARIABLE, Block.NULL_BLOCK); if (mmResult != null) { return mmResult; } return method.call(context, self, module, iVisited.getName(), IRubyObject.NULL_ARRAY, false, Block.NULL_BLOCK); } } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(runtime,context, iVisited.getConditionNode(), self, aBlock)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(runtime,context, iVisited.getBodyNode(), self, aBlock); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: // JRUBY-530, while case if (je.getTarget() == aBlock) { je.setTarget(null); throw je; } return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString((ByteList) iVisited.getValue().clone())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(runtime,context, iVisited.getArgsNode(), self, aBlock); if (iVisited.getArgsNode() == null) { result = null; } Block block = context.getCurrentFrame().getBlock(); return block.yield(context, result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameKlazz() == null) { String name = context.getFrameName(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } Block block = getBlock(runtime, context, self, aBlock, ((ZSuperNode) node).getIterNode()); // Has the method that is calling super received a block argument if (!block.isGiven()) block = context.getCurrentFrame().getBlock(); return context.callSuper(context.getFrameArgs(), block); } default: throw new RuntimeException("Invalid node encountered in interpreter: \"" + node.getClass().getName() + "\", please report this at www.jruby.org"); } } while (true); }
diff --git a/src/com/modcrafting/ultrabans/commands/Jail.java b/src/com/modcrafting/ultrabans/commands/Jail.java index fe0f906..85bb4bd 100644 --- a/src/com/modcrafting/ultrabans/commands/Jail.java +++ b/src/com/modcrafting/ultrabans/commands/Jail.java @@ -1,132 +1,134 @@ /* COPYRIGHT (c) 2012 Joshua McCurry * This work is licensed under the * Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License * and use of this software or its code is an agreement to this license. * A full copy of this license can be found at * http://creativecommons.org/licenses/by-nc-sa/3.0/. */ package com.modcrafting.ultrabans.commands; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.modcrafting.ultrabans.Ultrabans; import com.modcrafting.ultrabans.tracker.Track; public class Jail implements CommandExecutor{ Ultrabans plugin; public Jail(Ultrabans ultraBan) { this.plugin = ultraBan; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Track.track(command.getName()); if(!sender.hasPermission(command.getPermission())){ sender.sendMessage(ChatColor.RED+plugin.perms); return true; } YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean broadcast = true; Player player = null; String admin = plugin.admin; String reason = plugin.reason; if (sender instanceof Player){ player = (Player)sender; admin = player.getName(); } if (args.length < 1) return false; if(args[0].equalsIgnoreCase("setjail")){ + if(player==null) return true; plugin.jail.setJail(player.getLocation(), "jail"); String msg = config.getString("Messages.Jail.SetJail","Jail has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } if(args[0].equalsIgnoreCase("setrelease")){ + if(player==null) return true; plugin.jail.setJail(player.getLocation(), "release"); String msg = config.getString("Messages.Jail.SetRelease","Release has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } String p = args[0]; p = plugin.util.expandName(p); if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = plugin.admin; reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } Player victim = plugin.getServer().getPlayer(p); if(victim == null){ if(plugin.jailed.contains(p)){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msg = config.getString("Messages.Jail.Online","%victim% must be online to be jailed."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; }else{ if(victim.getName().equalsIgnoreCase(admin)){ String bcmsg = config.getString("Messages.Jail.Emo","You cannot jail yourself!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(victim.hasPermission( "ultraban.override.jail")&&!admin.equalsIgnoreCase(plugin.admin)){ String bcmsg = config.getString("Messages.Jail.Denied","Your jail attempt has been denied!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(plugin.jailed.contains(victim.getName().toLowerCase())){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, victim.getName()); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msgvic = config.getString("Messages.Jail.MsgToVictim", "You have been jailed by %admin%. Reason: %reason%"); if(msgvic.contains(plugin.regexAdmin)) msgvic = msgvic.replaceAll(plugin.regexAdmin, admin); if(msgvic.contains(plugin.regexReason)) msgvic = msgvic.replaceAll(plugin.regexReason, reason); msgvic=plugin.util.formatMessage(msgvic); victim.sendMessage(msgvic); String bcmsg = config.getString("Messages.Jail.MsgToBroadcast","%victim% was jailed by %admin%. Reason: %reason%!"); if(bcmsg.contains(plugin.regexAdmin)) bcmsg = bcmsg.replaceAll(plugin.regexAdmin, admin); if(bcmsg.contains(plugin.regexReason)) bcmsg = bcmsg.replaceAll(plugin.regexReason, reason); if(bcmsg.contains(plugin.regexVictim)) bcmsg = bcmsg.replaceAll(plugin.regexVictim, victim.getName()); bcmsg=plugin.util.formatMessage(bcmsg); if(broadcast){ plugin.getServer().broadcastMessage(bcmsg); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + bcmsg); } plugin.db.addPlayer(p, reason, admin, 0, 6); plugin.jailed.add(p.toLowerCase()); Location stlp = plugin.jail.getJail("jail"); victim.teleport(stlp); } return true; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Track.track(command.getName()); if(!sender.hasPermission(command.getPermission())){ sender.sendMessage(ChatColor.RED+plugin.perms); return true; } YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean broadcast = true; Player player = null; String admin = plugin.admin; String reason = plugin.reason; if (sender instanceof Player){ player = (Player)sender; admin = player.getName(); } if (args.length < 1) return false; if(args[0].equalsIgnoreCase("setjail")){ plugin.jail.setJail(player.getLocation(), "jail"); String msg = config.getString("Messages.Jail.SetJail","Jail has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } if(args[0].equalsIgnoreCase("setrelease")){ plugin.jail.setJail(player.getLocation(), "release"); String msg = config.getString("Messages.Jail.SetRelease","Release has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } String p = args[0]; p = plugin.util.expandName(p); if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = plugin.admin; reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } Player victim = plugin.getServer().getPlayer(p); if(victim == null){ if(plugin.jailed.contains(p)){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msg = config.getString("Messages.Jail.Online","%victim% must be online to be jailed."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; }else{ if(victim.getName().equalsIgnoreCase(admin)){ String bcmsg = config.getString("Messages.Jail.Emo","You cannot jail yourself!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(victim.hasPermission( "ultraban.override.jail")&&!admin.equalsIgnoreCase(plugin.admin)){ String bcmsg = config.getString("Messages.Jail.Denied","Your jail attempt has been denied!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(plugin.jailed.contains(victim.getName().toLowerCase())){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, victim.getName()); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msgvic = config.getString("Messages.Jail.MsgToVictim", "You have been jailed by %admin%. Reason: %reason%"); if(msgvic.contains(plugin.regexAdmin)) msgvic = msgvic.replaceAll(plugin.regexAdmin, admin); if(msgvic.contains(plugin.regexReason)) msgvic = msgvic.replaceAll(plugin.regexReason, reason); msgvic=plugin.util.formatMessage(msgvic); victim.sendMessage(msgvic); String bcmsg = config.getString("Messages.Jail.MsgToBroadcast","%victim% was jailed by %admin%. Reason: %reason%!"); if(bcmsg.contains(plugin.regexAdmin)) bcmsg = bcmsg.replaceAll(plugin.regexAdmin, admin); if(bcmsg.contains(plugin.regexReason)) bcmsg = bcmsg.replaceAll(plugin.regexReason, reason); if(bcmsg.contains(plugin.regexVictim)) bcmsg = bcmsg.replaceAll(plugin.regexVictim, victim.getName()); bcmsg=plugin.util.formatMessage(bcmsg); if(broadcast){ plugin.getServer().broadcastMessage(bcmsg); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + bcmsg); } plugin.db.addPlayer(p, reason, admin, 0, 6); plugin.jailed.add(p.toLowerCase()); Location stlp = plugin.jail.getJail("jail"); victim.teleport(stlp); } return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Track.track(command.getName()); if(!sender.hasPermission(command.getPermission())){ sender.sendMessage(ChatColor.RED+plugin.perms); return true; } YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); boolean broadcast = true; Player player = null; String admin = plugin.admin; String reason = plugin.reason; if (sender instanceof Player){ player = (Player)sender; admin = player.getName(); } if (args.length < 1) return false; if(args[0].equalsIgnoreCase("setjail")){ if(player==null) return true; plugin.jail.setJail(player.getLocation(), "jail"); String msg = config.getString("Messages.Jail.SetJail","Jail has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } if(args[0].equalsIgnoreCase("setrelease")){ if(player==null) return true; plugin.jail.setJail(player.getLocation(), "release"); String msg = config.getString("Messages.Jail.SetRelease","Release has been set!"); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY + msg); return true; } String p = args[0]; p = plugin.util.expandName(p); if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; reason = plugin.util.combineSplit(2, args, " "); }else{ if(args[1].equalsIgnoreCase("-a")){ admin = plugin.admin; reason = plugin.util.combineSplit(2, args, " "); }else{ reason = plugin.util.combineSplit(1, args, " "); } } } Player victim = plugin.getServer().getPlayer(p); if(victim == null){ if(plugin.jailed.contains(p)){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msg = config.getString("Messages.Jail.Online","%victim% must be online to be jailed."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, p); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; }else{ if(victim.getName().equalsIgnoreCase(admin)){ String bcmsg = config.getString("Messages.Jail.Emo","You cannot jail yourself!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(victim.hasPermission( "ultraban.override.jail")&&!admin.equalsIgnoreCase(plugin.admin)){ String bcmsg = config.getString("Messages.Jail.Denied","Your jail attempt has been denied!"); bcmsg = plugin.util.formatMessage(bcmsg); sender.sendMessage(bcmsg); return true; } if(plugin.jailed.contains(victim.getName().toLowerCase())){ String msg = config.getString("Messages.Jail.Failed","%victim% is already in jail."); if(msg.contains(plugin.regexVictim)) msg = msg.replaceAll(plugin.regexVictim, victim.getName()); msg=plugin.util.formatMessage(msg); sender.sendMessage(ChatColor.GRAY+msg); return true; } String msgvic = config.getString("Messages.Jail.MsgToVictim", "You have been jailed by %admin%. Reason: %reason%"); if(msgvic.contains(plugin.regexAdmin)) msgvic = msgvic.replaceAll(plugin.regexAdmin, admin); if(msgvic.contains(plugin.regexReason)) msgvic = msgvic.replaceAll(plugin.regexReason, reason); msgvic=plugin.util.formatMessage(msgvic); victim.sendMessage(msgvic); String bcmsg = config.getString("Messages.Jail.MsgToBroadcast","%victim% was jailed by %admin%. Reason: %reason%!"); if(bcmsg.contains(plugin.regexAdmin)) bcmsg = bcmsg.replaceAll(plugin.regexAdmin, admin); if(bcmsg.contains(plugin.regexReason)) bcmsg = bcmsg.replaceAll(plugin.regexReason, reason); if(bcmsg.contains(plugin.regexVictim)) bcmsg = bcmsg.replaceAll(plugin.regexVictim, victim.getName()); bcmsg=plugin.util.formatMessage(bcmsg); if(broadcast){ plugin.getServer().broadcastMessage(bcmsg); }else{ sender.sendMessage(ChatColor.ITALIC + "Silent: " + bcmsg); } plugin.db.addPlayer(p, reason, admin, 0, 6); plugin.jailed.add(p.toLowerCase()); Location stlp = plugin.jail.getJail("jail"); victim.teleport(stlp); } return true; }
diff --git a/framework/src/play/libs/OpenID.java b/framework/src/play/libs/OpenID.java index 4d8fe67a..c29e2c81 100644 --- a/framework/src/play/libs/OpenID.java +++ b/framework/src/play/libs/OpenID.java @@ -1,346 +1,346 @@ package play.libs; import java.net.URI; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import play.Logger; import play.exceptions.PlayException; import play.libs.WS.HttpResponse; import play.mvc.Router; import play.mvc.Http.Request; import play.mvc.Scope.Params; import play.mvc.results.Redirect; public class OpenID { private OpenID(String id) { this.id = id; this.returnAction = this.realmAction = Request.current().action; } // ~~~ API String id; String returnAction; String realmAction; List<String> sregRequired = new ArrayList<String>(); List<String> sregOptional = new ArrayList<String>(); Map<String, String> axRequired = new HashMap<String, String>(); Map<String, String> axOptional = new HashMap<String, String>(); public OpenID returnTo(String action) { this.returnAction = action; return this; } public OpenID forRealm(String action) { this.realmAction = action; return this; } public OpenID required(String alias) { this.sregRequired.add(alias); return this; } public OpenID required(String alias, String schema) { this.axRequired.put(alias, schema); return this; } public OpenID optional(String alias) { this.sregOptional.add(alias); return this; } public OpenID optional(String alias, String schema) { this.axOptional.put(alias, schema); return this; } public boolean verify() { try { // Normalize String claimedId = normalize(id); String server = null; String delegate = null; // Discover HttpResponse response = WS.url(claimedId).get(); // Try HTML (I know it's bad) String html = response.getString(); server = discoverServer(html); if (server == null) { // Try YADIS Document xrds = null; if (response.getContentType().contains("application/xrds+xml")) { xrds = response.getXml(); } else if (response.getHeader("X-XRDS-Location") != null) { xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml(); } else { return false; } // Ok we have the XRDS file server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()", xrds); claimedId = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()", xrds); if (claimedId == null) { claimedId = "http://specs.openid.net/auth/2.0/identifier_select"; } else { server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()", xrds); } if (server == null) { return false; } } else { // Delegate Matcher openid2Localid = Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); Matcher openidDelegate = Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); if (openid2Localid.find()) { delegate = extractHref(openid2Localid.group()); } else if (openidDelegate.find()) { delegate = extractHref(openidDelegate.group()); } } // Redirect String url = server; if (!server.contains("?")) { url += "?"; } if (!url.endsWith("?") && !url.endsWith("&")) { url += "&"; } url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8"); url += "&openid.mode=checkid_setup"; url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8"); url += "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8"); - if (returnAction != null && returnAction.startsWith("http://")) { + if (returnAction != null && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) { url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8"); } else { url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), "utf8"); } - if (realmAction != null && realmAction.startsWith("http://")) { + if (realmAction != null && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) { url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8"); } else { url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), "utf8"); } if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) { url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8"); } String sregO = ""; for (String a : sregOptional) { sregO += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregO)) { url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1); } String sregR = ""; for (String a : sregRequired) { sregR += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregR)) { url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1); } if (!axRequired.isEmpty() || !axOptional.isEmpty()) { url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0"; url += "&openid.ax.mode=fetch_request"; for (String a : axOptional.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8"); } for (String a : axRequired.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8"); } if (!axRequired.isEmpty()) { String r = ""; for (String a : axRequired.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.required=" + r; } if (!axOptional.isEmpty()) { String r = ""; for (String a : axOptional.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.if_available=" + r; } } if (Logger.isTraceEnabled()) { // Debug Logger.trace("Send request %s", url); } throw new Redirect(url); } catch (Redirect e) { throw e; } catch (PlayException e) { throw e; } catch (Exception e) { return false; } } // ~~~~ Main API public static OpenID id(String id) { return new OpenID(id); } /** * Normalize the given openid as a standard openid */ public static String normalize(String openID) { openID = openID.trim(); if (!openID.startsWith("http://") && !openID.startsWith("https://")) { openID = "http://" + openID; } try { URI url = new URI(openID); String frag = url.getRawFragment(); if (frag != null && frag.length() > 0) { openID = openID.replace("#" + frag, ""); } if (url.getPath().equals("")) { openID += "/"; } openID = new URI(openID).toString(); } catch (Exception e) { throw new RuntimeException(openID + " is not a valid URL"); } return openID; } /** * Is the current request an authentication response from the OP ? */ public static boolean isAuthenticationResponse() { return Params.current().get("openid.mode") != null; } /** * Retrieve the verified OpenID * @return A UserInfo object */ public static UserInfo getVerifiedID() { try { String mode = Params.current().get("openid.mode"); // Check authentication if (mode != null && mode.equals("id_res")) { // id String id = Params.current().get("openid.claimed_id"); if (id == null) { id = Params.current().get("openid.identity"); } id = normalize(id); // server String server = Params.current().get("openid.op_endpoint"); if (server == null) { server = discoverServer(id); } String fields = Request.current().querystring.replace("openid.mode=id_res", "openid.mode=check_authentication"); WS.HttpResponse response = WS.url(server).mimeType("application/x-www-form-urlencoded").body(fields).post(); if (response.getStatus() == 200 && response.getString().contains("is_valid:true")) { UserInfo userInfo = new UserInfo(); userInfo.id = id; Pattern patternAX = Pattern.compile("^openid[.].+[.]value[.]([^.]+)([.]\\d+)?$"); Pattern patternSREG = Pattern.compile("^openid[.]sreg[.]([^.]+)$"); for (String p : Params.current().allSimple().keySet()) { Matcher m = patternAX.matcher(p); if (m.matches()) { String alias = m.group(1); userInfo.extensions.put(alias, Params.current().get(p)); } m = patternSREG.matcher(p); if (m.matches()) { String alias = m.group(1); userInfo.extensions.put(alias, Params.current().get(p)); } } return userInfo; } else { return null; } } } catch (Exception e) { throw new RuntimeException(e); } return null; } // ~~~~ Utils static String extractHref(String link) { Matcher m = Pattern.compile("href=\"([^\"]*)\"").matcher(link); if (m.find()) { return m.group(1).trim(); } m = Pattern.compile("href=\'([^\']*)\'").matcher(link); if (m.find()) { return m.group(1).trim(); } return null; } public static String discoverServer(String openid) { if (openid.startsWith("http")) { openid = WS.url(openid).get().getString(); } Matcher openid2Provider = Pattern.compile("<link[^>]+openid2[.]provider[^>]+>", Pattern.CASE_INSENSITIVE).matcher(openid); Matcher openidServer = Pattern.compile("<link[^>]+openid[.]server[^>]+>", Pattern.CASE_INSENSITIVE).matcher(openid); String server = null; if (openid2Provider.find()) { server = extractHref(openid2Provider.group()); } else if (openidServer.find()) { server = extractHref(openidServer.group()); } return server; } // ~~~~ Result class public static class UserInfo { /** * OpenID */ public String id; /** * Extensions values */ public Map<String, String> extensions = new HashMap<String, String>(); @Override public String toString() { return id + " " + extensions; } } }
false
true
public boolean verify() { try { // Normalize String claimedId = normalize(id); String server = null; String delegate = null; // Discover HttpResponse response = WS.url(claimedId).get(); // Try HTML (I know it's bad) String html = response.getString(); server = discoverServer(html); if (server == null) { // Try YADIS Document xrds = null; if (response.getContentType().contains("application/xrds+xml")) { xrds = response.getXml(); } else if (response.getHeader("X-XRDS-Location") != null) { xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml(); } else { return false; } // Ok we have the XRDS file server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()", xrds); claimedId = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()", xrds); if (claimedId == null) { claimedId = "http://specs.openid.net/auth/2.0/identifier_select"; } else { server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()", xrds); } if (server == null) { return false; } } else { // Delegate Matcher openid2Localid = Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); Matcher openidDelegate = Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); if (openid2Localid.find()) { delegate = extractHref(openid2Localid.group()); } else if (openidDelegate.find()) { delegate = extractHref(openidDelegate.group()); } } // Redirect String url = server; if (!server.contains("?")) { url += "?"; } if (!url.endsWith("?") && !url.endsWith("&")) { url += "&"; } url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8"); url += "&openid.mode=checkid_setup"; url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8"); url += "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8"); if (returnAction != null && returnAction.startsWith("http://")) { url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8"); } else { url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), "utf8"); } if (realmAction != null && realmAction.startsWith("http://")) { url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8"); } else { url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), "utf8"); } if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) { url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8"); } String sregO = ""; for (String a : sregOptional) { sregO += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregO)) { url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1); } String sregR = ""; for (String a : sregRequired) { sregR += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregR)) { url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1); } if (!axRequired.isEmpty() || !axOptional.isEmpty()) { url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0"; url += "&openid.ax.mode=fetch_request"; for (String a : axOptional.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8"); } for (String a : axRequired.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8"); } if (!axRequired.isEmpty()) { String r = ""; for (String a : axRequired.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.required=" + r; } if (!axOptional.isEmpty()) { String r = ""; for (String a : axOptional.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.if_available=" + r; } } if (Logger.isTraceEnabled()) { // Debug Logger.trace("Send request %s", url); } throw new Redirect(url); } catch (Redirect e) { throw e; } catch (PlayException e) { throw e; } catch (Exception e) { return false; } }
public boolean verify() { try { // Normalize String claimedId = normalize(id); String server = null; String delegate = null; // Discover HttpResponse response = WS.url(claimedId).get(); // Try HTML (I know it's bad) String html = response.getString(); server = discoverServer(html); if (server == null) { // Try YADIS Document xrds = null; if (response.getContentType().contains("application/xrds+xml")) { xrds = response.getXml(); } else if (response.getHeader("X-XRDS-Location") != null) { xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml(); } else { return false; } // Ok we have the XRDS file server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()", xrds); claimedId = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()", xrds); if (claimedId == null) { claimedId = "http://specs.openid.net/auth/2.0/identifier_select"; } else { server = XPath.selectText("//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()", xrds); } if (server == null) { return false; } } else { // Delegate Matcher openid2Localid = Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); Matcher openidDelegate = Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE).matcher(html); if (openid2Localid.find()) { delegate = extractHref(openid2Localid.group()); } else if (openidDelegate.find()) { delegate = extractHref(openidDelegate.group()); } } // Redirect String url = server; if (!server.contains("?")) { url += "?"; } if (!url.endsWith("?") && !url.endsWith("&")) { url += "&"; } url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8"); url += "&openid.mode=checkid_setup"; url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8"); url += "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8"); if (returnAction != null && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) { url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8"); } else { url += "&openid.return_to=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(returnAction), "utf8"); } if (realmAction != null && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) { url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8"); } else { url += "&openid.realm=" + URLEncoder.encode(Request.current().getBase() + Router.reverse(realmAction), "utf8"); } if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) { url += "&openid.ns.sreg=" + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8"); } String sregO = ""; for (String a : sregOptional) { sregO += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregO)) { url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1); } String sregR = ""; for (String a : sregRequired) { sregR += URLEncoder.encode(a, "UTF-8") + ","; } if (!StringUtils.isEmpty(sregR)) { url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1); } if (!axRequired.isEmpty() || !axOptional.isEmpty()) { url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0"; url += "&openid.ax.mode=fetch_request"; for (String a : axOptional.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8"); } for (String a : axRequired.keySet()) { url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8"); } if (!axRequired.isEmpty()) { String r = ""; for (String a : axRequired.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.required=" + r; } if (!axOptional.isEmpty()) { String r = ""; for (String a : axOptional.keySet()) { r += "," + a; } r = r.substring(1); url += "&openid.ax.if_available=" + r; } } if (Logger.isTraceEnabled()) { // Debug Logger.trace("Send request %s", url); } throw new Redirect(url); } catch (Redirect e) { throw e; } catch (PlayException e) { throw e; } catch (Exception e) { return false; } }
diff --git a/api/src/main/java/org/xnio/streams/BufferPipeOutputStream.java b/api/src/main/java/org/xnio/streams/BufferPipeOutputStream.java index 17766f45..4a286c05 100644 --- a/api/src/main/java/org/xnio/streams/BufferPipeOutputStream.java +++ b/api/src/main/java/org/xnio/streams/BufferPipeOutputStream.java @@ -1,182 +1,182 @@ /* * JBoss, Home of Professional Open Source * Copyright 2010, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xnio.streams; import java.io.Flushable; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import org.xnio.Pooled; /** * An {@code OutputStream} implementation which writes out {@code ByteBuffer}s to a consumer. */ public class BufferPipeOutputStream extends OutputStream { private final Object lock = new Object(); private Pooled<ByteBuffer> buffer; private boolean eof; private final BufferWriter bufferWriterTask; /** * Construct a new instance. The internal buffers will have a capacity of {@code bufferSize}. The * given {@code bufferWriterTask} will be called to send buffers, flush the output stream, and handle the * end-of-file condition. * * @param bufferWriterTask the writer task */ public BufferPipeOutputStream(final BufferWriter bufferWriterTask) throws IOException { this.bufferWriterTask = bufferWriterTask; synchronized (lock) { buffer = bufferWriterTask.getBuffer(); } } private static IOException closed() { return new IOException("Stream is closed"); } private void checkClosed() throws IOException { if (eof) { throw closed(); } } private Pooled<ByteBuffer> getBuffer() throws IOException { final Pooled<ByteBuffer> buffer = this.buffer; if (buffer != null && buffer.getResource().hasRemaining()) { return buffer; } else { if (buffer != null) send(); return this.buffer = bufferWriterTask.getBuffer(); } } /** {@inheritDoc} */ public void write(final int b) throws IOException { synchronized (this) { checkClosed(); getBuffer().getResource().put((byte) b); } } /** {@inheritDoc} */ public void write(final byte[] b, int off, int len) throws IOException { synchronized (this) { checkClosed(); while (len > 0) { final ByteBuffer buffer = getBuffer().getResource(); final int cnt = Math.min(len, buffer.remaining()); buffer.put(b, off, cnt); len -= cnt; off += cnt; } } } // call with lock held private void send() throws IOException { final Pooled<ByteBuffer> pooledBuffer = buffer; - final ByteBuffer buffer = pooledBuffer.getResource(); + final ByteBuffer buffer = pooledBuffer == null ? null : pooledBuffer.getResource(); this.buffer = null; final boolean eof = this.eof; if (buffer != null && buffer.position() > 0) { buffer.flip(); send(pooledBuffer, eof); } else if (eof) { Pooled<ByteBuffer> pooledBuffer1 = getBuffer(); final ByteBuffer buffer1 = pooledBuffer1.getResource(); buffer1.flip(); send(pooledBuffer1, eof); } } private void send(Pooled<ByteBuffer> buffer, boolean eof) throws IOException { try { bufferWriterTask.accept(buffer, eof); } catch (IOException e) { this.eof = true; throw e; } } /** {@inheritDoc} */ public void flush() throws IOException { synchronized (this) { send(); try { bufferWriterTask.flush(); } catch (IOException e) { eof = true; buffer = null; throw e; } } } /** {@inheritDoc} */ public void close() throws IOException { synchronized (this) { if (eof) { return; } eof = true; flush(); } } /** * A buffer writer for an {@link BufferPipeOutputStream}. */ public interface BufferWriter extends Flushable { /** * Get a new buffer to be filled. The new buffer may, for example, include a prepended header. This method * may block until a buffer is available or until some other condition, such as flow control, is met. * * @return the new buffer * @throws IOException if an I/O error occurs */ Pooled<ByteBuffer> getBuffer() throws IOException; /** * Accept a buffer. If this is the last buffer that will be sent, the {@code eof} flag will be set to {@code true}. * This method should block until the entire buffer is consumed, or an error occurs. This method may also block * until some other condition, such as flow control, is met. * * @param pooledBuffer the buffer to send * @param eof {@code true} if this is the last buffer which will be sent * @throws IOException if an I/O error occurs */ void accept(Pooled<ByteBuffer> pooledBuffer, boolean eof) throws IOException; /** * Flushes this stream by writing any buffered output to the underlying stream. This method should block until * the data is fully flushed. This method may also block until some other condition, such as flow control, is * met. * * @throws IOException If an I/O error occurs */ void flush() throws IOException; } }
true
true
private void send() throws IOException { final Pooled<ByteBuffer> pooledBuffer = buffer; final ByteBuffer buffer = pooledBuffer.getResource(); this.buffer = null; final boolean eof = this.eof; if (buffer != null && buffer.position() > 0) { buffer.flip(); send(pooledBuffer, eof); } else if (eof) { Pooled<ByteBuffer> pooledBuffer1 = getBuffer(); final ByteBuffer buffer1 = pooledBuffer1.getResource(); buffer1.flip(); send(pooledBuffer1, eof); } }
private void send() throws IOException { final Pooled<ByteBuffer> pooledBuffer = buffer; final ByteBuffer buffer = pooledBuffer == null ? null : pooledBuffer.getResource(); this.buffer = null; final boolean eof = this.eof; if (buffer != null && buffer.position() > 0) { buffer.flip(); send(pooledBuffer, eof); } else if (eof) { Pooled<ByteBuffer> pooledBuffer1 = getBuffer(); final ByteBuffer buffer1 = pooledBuffer1.getResource(); buffer1.flip(); send(pooledBuffer1, eof); } }
diff --git a/src/test/java/pl/psnc/dl/wf4ever/darceo/client/TestDArceoClient.java b/src/test/java/pl/psnc/dl/wf4ever/darceo/client/TestDArceoClient.java index 76d8d96..9b9641f 100644 --- a/src/test/java/pl/psnc/dl/wf4ever/darceo/client/TestDArceoClient.java +++ b/src/test/java/pl/psnc/dl/wf4ever/darceo/client/TestDArceoClient.java @@ -1,123 +1,123 @@ package pl.psnc.dl.wf4ever.darceo.client; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.UUID; import junit.framework.Assert; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.Test; import pl.psnc.dl.wf4ever.darceo.model.mock.ResearchObjectSerializableMock; import pl.psnc.dl.wf4ever.preservation.model.ResearchObjectSerializable; import com.sun.jersey.api.client.Client; public class TestDArceoClient { private static Client client = Client.create(); @BeforeClass public static void setUpClass() { client = Client.create(); client.setFollowRedirects(false); } @Test public void testSingleton() throws DArceoException, IOException { Assert.assertNotNull(DArceoClient.getInstance()); } @Test public void testCRUDRO() throws IOException, DArceoException, InterruptedException { List<String> roContent = new ArrayList<String>(); String path1 = "mock/simple/content/simple/1.txt"; String path2 = "mock/simple/content/simple/2.txt"; String path3 = "mock/simple/content/simple/.ro/manifest.rdf"; String path4 = "mock/simple/content/simple/.ro/evo_info.ttl"; roContent.add(path1); roContent.add(path2); roContent.add(path3); roContent.add(path4); List<String> expectedResources = new ArrayList<String>(); expectedResources.add(path1); expectedResources.add(path2); expectedResources.add(path3); expectedResources.add(path4); ResearchObjectSerializable ro = new ResearchObjectSerializableMock(roContent, "mock/simple/content/simple/", URI.create("http://www.example.com/ROs/ro" + UUID.randomUUID().toString() + "/")); crud(ro, expectedResources); } //TODO write more tests with the strange URIs to define expected exceptions in case of mistakes in URIs parameters. OK ;) ? private void crud(ResearchObjectSerializable ro, List<String> expectedResources) throws IOException, DArceoException, InterruptedException { //POST URI statusURI = DArceoClient.getInstance().post(ro); Assert.assertNotNull(statusURI); URI id = DArceoClient.getInstance().postORUpdateBlocking(statusURI); Assert.assertNotNull(id); - Thread.sleep(1000); + Thread.sleep(2500); //GET ResearchObjectSerializable returnedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNotNull("RO couldn't be reterived", returnedRO); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/manifest.rdf"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/evo_info.ttl"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("2.txt"))); String txt1content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/1.txt")); String txt2content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/2.txt")); String txt3content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/3.txt")); String txtSerialziation1content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("1.txt")).getSerialization()); String txtSerialziation2content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("2.txt")).getSerialization()); Assert.assertEquals(txt1content, txtSerialziation1content); Assert.assertEquals(txt2content, txtSerialziation2content); //GET Test Assert.assertNull(DArceoClient.getInstance().getBlocking(id.resolve("wrong-id"))); //UPDATE List<String> roContent = new ArrayList<String>(); String path2 = "mock/simple/content/simple_update/.ro/manifest.rdf"; String path1 = "mock/simple/content/simple_update/.ro/evo_info.ttl"; String path3 = "mock/simple/content/simple_update/2.txt"; String path = "mock/simple/content/simple_update/3.txt"; roContent.add(path); roContent.add(path1); roContent.add(path2); roContent.add(path3); ResearchObjectSerializable roToUpdate = new ResearchObjectSerializableMock(roContent, "mock/simple/content/simple_update/", id); URI updateStatus = DArceoClient.getInstance().update(roToUpdate); URI updateId = DArceoClient.getInstance().postORUpdateBlocking(updateStatus); Assert.assertNotNull(id); Assert.assertEquals(URI.create("2"), updateId); - Thread.sleep(1000); + Thread.sleep(2500); ResearchObjectSerializable updatedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("3.txt"))); String txtSerialziation3content = IOUtils.toString(updatedRO.getSerializables() .get(returnedRO.getUri().resolve("3.txt")).getSerialization()); Assert.assertEquals(txt3content, txtSerialziation3content); ///DELETE //DELETE Test Assert.assertNull(DArceoClient.getInstance().delete(id.resolve("wrong-id"))); Assert.assertTrue(DArceoClient.getInstance().deleteBlocking(DArceoClient.getInstance().delete(id))); } }
false
true
private void crud(ResearchObjectSerializable ro, List<String> expectedResources) throws IOException, DArceoException, InterruptedException { //POST URI statusURI = DArceoClient.getInstance().post(ro); Assert.assertNotNull(statusURI); URI id = DArceoClient.getInstance().postORUpdateBlocking(statusURI); Assert.assertNotNull(id); Thread.sleep(1000); //GET ResearchObjectSerializable returnedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNotNull("RO couldn't be reterived", returnedRO); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/manifest.rdf"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/evo_info.ttl"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("2.txt"))); String txt1content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/1.txt")); String txt2content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/2.txt")); String txt3content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/3.txt")); String txtSerialziation1content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("1.txt")).getSerialization()); String txtSerialziation2content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("2.txt")).getSerialization()); Assert.assertEquals(txt1content, txtSerialziation1content); Assert.assertEquals(txt2content, txtSerialziation2content); //GET Test Assert.assertNull(DArceoClient.getInstance().getBlocking(id.resolve("wrong-id"))); //UPDATE List<String> roContent = new ArrayList<String>(); String path2 = "mock/simple/content/simple_update/.ro/manifest.rdf"; String path1 = "mock/simple/content/simple_update/.ro/evo_info.ttl"; String path3 = "mock/simple/content/simple_update/2.txt"; String path = "mock/simple/content/simple_update/3.txt"; roContent.add(path); roContent.add(path1); roContent.add(path2); roContent.add(path3); ResearchObjectSerializable roToUpdate = new ResearchObjectSerializableMock(roContent, "mock/simple/content/simple_update/", id); URI updateStatus = DArceoClient.getInstance().update(roToUpdate); URI updateId = DArceoClient.getInstance().postORUpdateBlocking(updateStatus); Assert.assertNotNull(id); Assert.assertEquals(URI.create("2"), updateId); Thread.sleep(1000); ResearchObjectSerializable updatedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("3.txt"))); String txtSerialziation3content = IOUtils.toString(updatedRO.getSerializables() .get(returnedRO.getUri().resolve("3.txt")).getSerialization()); Assert.assertEquals(txt3content, txtSerialziation3content); ///DELETE //DELETE Test Assert.assertNull(DArceoClient.getInstance().delete(id.resolve("wrong-id"))); Assert.assertTrue(DArceoClient.getInstance().deleteBlocking(DArceoClient.getInstance().delete(id))); }
private void crud(ResearchObjectSerializable ro, List<String> expectedResources) throws IOException, DArceoException, InterruptedException { //POST URI statusURI = DArceoClient.getInstance().post(ro); Assert.assertNotNull(statusURI); URI id = DArceoClient.getInstance().postORUpdateBlocking(statusURI); Assert.assertNotNull(id); Thread.sleep(2500); //GET ResearchObjectSerializable returnedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNotNull("RO couldn't be reterived", returnedRO); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/manifest.rdf"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve(".ro/evo_info.ttl"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(returnedRO.getSerializables().get(returnedRO.getUri().resolve("2.txt"))); String txt1content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/1.txt")); String txt2content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/2.txt")); String txt3content = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("mock/3.txt")); String txtSerialziation1content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("1.txt")).getSerialization()); String txtSerialziation2content = IOUtils.toString(returnedRO.getSerializables() .get(returnedRO.getUri().resolve("2.txt")).getSerialization()); Assert.assertEquals(txt1content, txtSerialziation1content); Assert.assertEquals(txt2content, txtSerialziation2content); //GET Test Assert.assertNull(DArceoClient.getInstance().getBlocking(id.resolve("wrong-id"))); //UPDATE List<String> roContent = new ArrayList<String>(); String path2 = "mock/simple/content/simple_update/.ro/manifest.rdf"; String path1 = "mock/simple/content/simple_update/.ro/evo_info.ttl"; String path3 = "mock/simple/content/simple_update/2.txt"; String path = "mock/simple/content/simple_update/3.txt"; roContent.add(path); roContent.add(path1); roContent.add(path2); roContent.add(path3); ResearchObjectSerializable roToUpdate = new ResearchObjectSerializableMock(roContent, "mock/simple/content/simple_update/", id); URI updateStatus = DArceoClient.getInstance().update(roToUpdate); URI updateId = DArceoClient.getInstance().postORUpdateBlocking(updateStatus); Assert.assertNotNull(id); Assert.assertEquals(URI.create("2"), updateId); Thread.sleep(2500); ResearchObjectSerializable updatedRO = DArceoClient.getInstance().getBlocking(id); Assert.assertNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("1.txt"))); Assert.assertNotNull(updatedRO.getSerializables().get(updatedRO.getUri().resolve("3.txt"))); String txtSerialziation3content = IOUtils.toString(updatedRO.getSerializables() .get(returnedRO.getUri().resolve("3.txt")).getSerialization()); Assert.assertEquals(txt3content, txtSerialziation3content); ///DELETE //DELETE Test Assert.assertNull(DArceoClient.getInstance().delete(id.resolve("wrong-id"))); Assert.assertTrue(DArceoClient.getInstance().deleteBlocking(DArceoClient.getInstance().delete(id))); }
diff --git a/src/main/java/ru/urbancamper/audiobookmarker/AudioBookMarkerUtil.java b/src/main/java/ru/urbancamper/audiobookmarker/AudioBookMarkerUtil.java index 8f2e6b3..a1e59aa 100644 --- a/src/main/java/ru/urbancamper/audiobookmarker/AudioBookMarkerUtil.java +++ b/src/main/java/ru/urbancamper/audiobookmarker/AudioBookMarkerUtil.java @@ -1,52 +1,52 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ru.urbancamper.audiobookmarker; import java.io.File; import java.util.HashMap; import ru.urbancamper.audiobookmarker.audio.AudioFileRecognizerInterface; import ru.urbancamper.audiobookmarker.document.MarkedDocument; import ru.urbancamper.audiobookmarker.text.BookText; import ru.urbancamper.audiobookmarker.text.RecognizedTextOfSingleAudiofile; /** * * @author pozpl */ public class AudioBookMarkerUtil { private BookText bookTextAggregator; private AudioFileRecognizerInterface audioRecognizer; public AudioBookMarkerUtil(BookText bookText, AudioFileRecognizerInterface audioRecognizer){ this.bookTextAggregator = bookText; this.audioRecognizer = audioRecognizer; } public MarkedDocument makeMarkers(String[] audioBookFilesPaths, String fullText){ this.bookTextAggregator.setFullText(fullText); HashMap<String, String> audioFilesIdentificatorMap = new HashMap<String, String>(); String audioFilePath; String fileName; for(Integer fileCounter = 0; fileCounter < audioBookFilesPaths.length; fileCounter++){ audioFilePath = audioBookFilesPaths[fileCounter]; fileName = this.getAudioFileName(audioFilePath); audioFilesIdentificatorMap.put(fileName, fileCounter.toString()); - RecognizedTextOfSingleAudiofile recognizedFile = this.audioRecognizer.recognize(audioFilePath, audioFilePath); + RecognizedTextOfSingleAudiofile recognizedFile = this.audioRecognizer.recognize(audioFilePath, fileCounter.toString()); this.bookTextAggregator.registerRecognizedTextPiece(recognizedFile); } String markedText = this.bookTextAggregator.buildTextWithAudioMarks(); MarkedDocument markedDokument = new MarkedDocument(markedText, audioFilesIdentificatorMap); return markedDokument; } private String getAudioFileName(String audioFilePath){ String fileName; fileName = new File(audioFilePath).getName(); return fileName; } }
true
true
public MarkedDocument makeMarkers(String[] audioBookFilesPaths, String fullText){ this.bookTextAggregator.setFullText(fullText); HashMap<String, String> audioFilesIdentificatorMap = new HashMap<String, String>(); String audioFilePath; String fileName; for(Integer fileCounter = 0; fileCounter < audioBookFilesPaths.length; fileCounter++){ audioFilePath = audioBookFilesPaths[fileCounter]; fileName = this.getAudioFileName(audioFilePath); audioFilesIdentificatorMap.put(fileName, fileCounter.toString()); RecognizedTextOfSingleAudiofile recognizedFile = this.audioRecognizer.recognize(audioFilePath, audioFilePath); this.bookTextAggregator.registerRecognizedTextPiece(recognizedFile); } String markedText = this.bookTextAggregator.buildTextWithAudioMarks(); MarkedDocument markedDokument = new MarkedDocument(markedText, audioFilesIdentificatorMap); return markedDokument; }
public MarkedDocument makeMarkers(String[] audioBookFilesPaths, String fullText){ this.bookTextAggregator.setFullText(fullText); HashMap<String, String> audioFilesIdentificatorMap = new HashMap<String, String>(); String audioFilePath; String fileName; for(Integer fileCounter = 0; fileCounter < audioBookFilesPaths.length; fileCounter++){ audioFilePath = audioBookFilesPaths[fileCounter]; fileName = this.getAudioFileName(audioFilePath); audioFilesIdentificatorMap.put(fileName, fileCounter.toString()); RecognizedTextOfSingleAudiofile recognizedFile = this.audioRecognizer.recognize(audioFilePath, fileCounter.toString()); this.bookTextAggregator.registerRecognizedTextPiece(recognizedFile); } String markedText = this.bookTextAggregator.buildTextWithAudioMarks(); MarkedDocument markedDokument = new MarkedDocument(markedText, audioFilesIdentificatorMap); return markedDokument; }
diff --git a/src/info/eigenein/openwifi/activities/MainActivity.java b/src/info/eigenein/openwifi/activities/MainActivity.java index 273bc0f..f53a583 100644 --- a/src/info/eigenein/openwifi/activities/MainActivity.java +++ b/src/info/eigenein/openwifi/activities/MainActivity.java @@ -1,443 +1,443 @@ package info.eigenein.openwifi.activities; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.location.*; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.maps.*; import info.eigenein.openwifi.R; import info.eigenein.openwifi.helpers.entities.Area; import info.eigenein.openwifi.helpers.entities.Cluster; import info.eigenein.openwifi.helpers.entities.ClusterList; import info.eigenein.openwifi.helpers.entities.Network; import info.eigenein.openwifi.helpers.location.L; import info.eigenein.openwifi.helpers.location.LocationProcessor; import info.eigenein.openwifi.helpers.location.LocationTracker; import info.eigenein.openwifi.helpers.map.*; import info.eigenein.openwifi.helpers.scan.ScanResultTracker; import info.eigenein.openwifi.helpers.scan.ScanServiceManager; import info.eigenein.openwifi.persistency.MyScanResult; import org.apache.commons.collections.map.MultiKeyMap; import java.util.*; /** * Main application activity with the map. */ public class MainActivity extends MapActivity { private static final String LOG_TAG = MainActivity.class.getCanonicalName(); private final static int DEFAULT_ZOOM = 17; private TrackableMapView mapView = null; private MyLocationOverlay myLocationOverlay = null; private ClusterListOverlay clusterListOverlay = null; private RefreshScanResultsAsyncTask refreshScanResultsAsyncTask = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup default values for the settings. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Setup view. setContentView(R.layout.main); // Setup action bar. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayShowTitleEnabled(false); } // Setup map. mapView = (TrackableMapView)findViewById(R.id.map_view); mapView.setBuiltInZoomControls(false); mapView.addMovedOrZoomedObserver(new MapViewListener() { @Override public void onMovedOrZoomed() { Log.d(LOG_TAG + ".onCreate", "onMovedOrZoomed"); updateZoomButtonsState(); startRefreshingScanResultsOnMap(); } }); mapView.invalidateMovedOrZoomed(); // Setup map controller. final MapController mapController = mapView.getController(); // Setup current location. myLocationOverlay = new TrackableMyLocationOverlay(this, mapView); myLocationOverlay.runOnFirstFix(new Runnable() { public void run() { Log.d(LOG_TAG + ".onCreate", "runOnFirstFix"); // Zoom in to current location mapController.setZoom(DEFAULT_ZOOM); mapController.animateTo(myLocationOverlay.getMyLocation()); mapView.invalidateMovedOrZoomed(); } }); // Setup my location button. findViewById(R.id.button_my_location).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GeoPoint myLocation = myLocationOverlay.getMyLocation(); if (myLocation == null) { // Try to obtain current location from the location tracker. final Location location = LocationTracker.getInstance().getLocation(MainActivity.this); if (location != null) { myLocation = L.toGeoPoint(location.getLatitude(), location.getLongitude()); } } if (myLocation != null) { mapController.animateTo(myLocation); mapView.invalidateMovedOrZoomed(); } else { Toast.makeText(MainActivity.this, R.string.my_location_is_unavailable, Toast.LENGTH_SHORT).show(); } } }); // Setup zoom buttons. findViewById(R.id.button_zoom_out).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomOut(); mapView.invalidateMovedOrZoomed(); } }); findViewById(R.id.button_zoom_in).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomIn(); mapView.invalidateMovedOrZoomed(); } }); // Setup overlays. final List<Overlay> overlays = mapView.getOverlays(); - overlays.add(myLocationOverlay); clusterListOverlay = new ClusterListOverlay(); overlays.add(clusterListOverlay); + overlays.add(myLocationOverlay); } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); boolean isServiceStarted = ScanServiceManager.isStarted(this); menu.findItem(R.id.start_scan_menuitem).setVisible(!isServiceStarted); menu.findItem(R.id.pause_scan_menuitem).setVisible(isServiceStarted); return true; } @Override public void onStart() { super.onStart(); // Initialize my location. if (myLocationOverlay != null) { // Enable my location. myLocationOverlay.enableMyLocation(); myLocationOverlay.enableCompass(); } // Update overlays. startRefreshingScanResultsOnMap(); EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); if (myLocationOverlay != null) { // Disable my location to avoid using of location services. myLocationOverlay.disableCompass(); myLocationOverlay.disableMyLocation(); } EasyTracker.getInstance().activityStop(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings_menuitem: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.start_scan_menuitem: ScanServiceManager.restart(this); Toast.makeText(this, R.string.scan_started, Toast.LENGTH_LONG).show(); invalidateOptionsMenu(); return true; case R.id.pause_scan_menuitem: ScanServiceManager.stop(this); Toast.makeText(this, R.string.scan_paused, Toast.LENGTH_SHORT).show(); invalidateOptionsMenu(); return true; case R.id.map_view_menuitem: final CharSequence[] items = getResources().getTextArray(R.array.map_views); new AlertDialog.Builder(this) .setTitle(getString(R.string.map_view)) .setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: mapView.setSatellite(false); break; case 1: mapView.setSatellite(true); break; } } }) .show(); return true; case R.id.about_menuitem: startActivity(new Intent(this, AboutActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override public void invalidateOptionsMenu() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Added in API level 11 super.invalidateOptionsMenu(); } } @Override protected boolean isRouteDisplayed() { return false; } /** * Updates zoom buttons enabled/disabled state for the current zoom level. */ private void updateZoomButtonsState() { final ImageButton zoomOutButton = (ImageButton)findViewById(R.id.button_zoom_out); zoomOutButton.setEnabled(mapView.getZoomLevel() != 1); final ImageButton zoomInButton = (ImageButton)findViewById(R.id.button_zoom_in); zoomInButton.setEnabled(mapView.getZoomLevel() != mapView.getMaxZoomLevel()); } /** * Refreshes the scan results on the map. */ private void startRefreshingScanResultsOnMap() { Log.d(LOG_TAG, "startRefreshingScanResultsOnMap"); // Check if the task is already running. cancelRefreshScanResultsAsyncTask(); // Check map bounds. if (mapView.getLatitudeSpan() == 0 || mapView.getLongitudeSpan() == 0) { Log.w(LOG_TAG, "Zero mapView span."); return; } // Get map bounds. final Projection mapViewProjection = mapView.getProjection(); GeoPoint nwGeoPoint = mapViewProjection.fromPixels(0, 0); GeoPoint seGeoPoint = mapViewProjection.fromPixels(mapView.getWidth(), mapView.getHeight()); // Run task to retrieve the scan results and process them into a cluster list. refreshScanResultsAsyncTask = new RefreshScanResultsAsyncTask( L.fromE6(seGeoPoint.getLatitudeE6()), L.fromE6(nwGeoPoint.getLongitudeE6()), L.fromE6(nwGeoPoint.getLatitudeE6()), L.fromE6(seGeoPoint.getLongitudeE6()), 0.0005 * Math.pow(2.0, 20.0 - mapView.getZoomLevel()) ); refreshScanResultsAsyncTask.execute(); } private synchronized void cancelRefreshScanResultsAsyncTask() { if (refreshScanResultsAsyncTask != null) { // Cancel old task. refreshScanResultsAsyncTask.cancel(true); refreshScanResultsAsyncTask = null; } } /** * Used to aggregate the scan results from the application database. */ public class RefreshScanResultsAsyncTask extends AsyncTask<Void, Void, ClusterList> { private final String LOG_TAG = RefreshScanResultsAsyncTask.class.getCanonicalName(); /** * Defines a "border" for selecting scan results within the specified area. * Without this border a cluster "jumps" when one of its scan results * goes off the visible area. */ private static final double BORDER_WIDTH = 0.002; private final double minLatitude; private final double minLongitude; private final double maxLatitude; private final double maxLongitude; private final double gridSize; /** * Groups scan results into the grid by their location. * (int, int) -> StoredScanResult */ private final MultiKeyMap cellToScanResultCache = new MultiKeyMap(); public RefreshScanResultsAsyncTask( final double minLatitude, final double minLongitude, final double maxLatitude, final double maxLongitude, final double gridSize) { Log.d(LOG_TAG, String.format( "RefreshScanResultsAsyncTask[minLat=%s, minLon=%s, maxLat=%s, maxLon=%s, gridSize=%s]", minLatitude, minLongitude, maxLatitude, maxLongitude, gridSize)); this.minLatitude = minLatitude; this.minLongitude = minLongitude; this.maxLatitude = maxLatitude; this.maxLongitude = maxLongitude; this.gridSize = gridSize; } @Override protected ClusterList doInBackground(Void... params) { // Retrieve scan results. final long getScanResultsStartTime = System.currentTimeMillis(); final List<MyScanResult> scanResults = ScanResultTracker.getScanResults( MainActivity.this, minLatitude - BORDER_WIDTH, minLongitude - BORDER_WIDTH, maxLatitude + BORDER_WIDTH, maxLongitude + BORDER_WIDTH ); Log.d(LOG_TAG + ".doInBackground", String.format( "fetched %d results in %sms.", scanResults.size(), System.currentTimeMillis() - getScanResultsStartTime )); // Process them if we're still not cancelled. if (isCancelled()) { return null; } for (final MyScanResult scanResult : scanResults) { // Check if we're cancelled. if (isCancelled()) { return null; } addScanResult(scanResult); } return buildClusterList(); } @Override protected synchronized void onPostExecute(final ClusterList clusterList) { Log.d(LOG_TAG + ".onPostExecute", clusterList.toString()); clusterListOverlay.clearClusterOverlays(); for (final Cluster cluster : clusterList) { ClusterOverlay clusterOverlay = new ClusterOverlay( MainActivity.this, cluster ); clusterListOverlay.addClusterOverlay(clusterOverlay); } mapView.invalidate(); } @Override protected void onCancelled(final ClusterList result) { Log.d(LOG_TAG + ".onCancelled", "cancelled"); } private void addScanResult(final MyScanResult scanResult) { final int key1 = (int)Math.floor(scanResult.getLatitude() / gridSize); final int key2 = (int)Math.floor(scanResult.getLongitude() / gridSize); List<MyScanResult> subCache = (List<MyScanResult>)cellToScanResultCache.get(key1, key2); if (subCache == null) { subCache = new ArrayList<MyScanResult>(); cellToScanResultCache.put(key1, key2, subCache); } subCache.add(scanResult); } private ClusterList buildClusterList() { final ClusterList clusterList = new ClusterList(); // Iterate through grid cells. for (final Object o : cellToScanResultCache.values()) { // Check if we're cancelled. if (isCancelled()) { return null; } final List<MyScanResult> subCache = (List<MyScanResult>)o; final HashMap<String, HashSet<String>> ssidToBssidCache = new HashMap<String, HashSet<String>>(); LocationProcessor locationProcessor = new LocationProcessor(); for (final MyScanResult scanResult : subCache) { // Check if we're cancelled. if (isCancelled()) { return null; } // Combine BSSIDs from the same SSIDs. HashSet<String> bssids = ssidToBssidCache.get(scanResult.getSsid()); if (bssids == null) { bssids = new HashSet<String>(); ssidToBssidCache.put(scanResult.getSsid(), bssids); } bssids.add(scanResult.getBssid()); // Track the location. locationProcessor.add(scanResult); } // Initialize a cluster. final Area area = locationProcessor.getArea(); final Cluster cluster = new Cluster(area); // And fill it with networks. for (final Map.Entry<String, HashSet<String>> entry : ssidToBssidCache.entrySet()) { // Check if we're cancelled. if (isCancelled()) { return null; } cluster.add(new Network(entry.getKey(), entry.getValue())); } // Finally, add the cluster to the cluster list. clusterList.add(cluster); Log.d(LOG_TAG, "clusterList.add " + cluster); } return clusterList; } } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup default values for the settings. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Setup view. setContentView(R.layout.main); // Setup action bar. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayShowTitleEnabled(false); } // Setup map. mapView = (TrackableMapView)findViewById(R.id.map_view); mapView.setBuiltInZoomControls(false); mapView.addMovedOrZoomedObserver(new MapViewListener() { @Override public void onMovedOrZoomed() { Log.d(LOG_TAG + ".onCreate", "onMovedOrZoomed"); updateZoomButtonsState(); startRefreshingScanResultsOnMap(); } }); mapView.invalidateMovedOrZoomed(); // Setup map controller. final MapController mapController = mapView.getController(); // Setup current location. myLocationOverlay = new TrackableMyLocationOverlay(this, mapView); myLocationOverlay.runOnFirstFix(new Runnable() { public void run() { Log.d(LOG_TAG + ".onCreate", "runOnFirstFix"); // Zoom in to current location mapController.setZoom(DEFAULT_ZOOM); mapController.animateTo(myLocationOverlay.getMyLocation()); mapView.invalidateMovedOrZoomed(); } }); // Setup my location button. findViewById(R.id.button_my_location).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GeoPoint myLocation = myLocationOverlay.getMyLocation(); if (myLocation == null) { // Try to obtain current location from the location tracker. final Location location = LocationTracker.getInstance().getLocation(MainActivity.this); if (location != null) { myLocation = L.toGeoPoint(location.getLatitude(), location.getLongitude()); } } if (myLocation != null) { mapController.animateTo(myLocation); mapView.invalidateMovedOrZoomed(); } else { Toast.makeText(MainActivity.this, R.string.my_location_is_unavailable, Toast.LENGTH_SHORT).show(); } } }); // Setup zoom buttons. findViewById(R.id.button_zoom_out).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomOut(); mapView.invalidateMovedOrZoomed(); } }); findViewById(R.id.button_zoom_in).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomIn(); mapView.invalidateMovedOrZoomed(); } }); // Setup overlays. final List<Overlay> overlays = mapView.getOverlays(); overlays.add(myLocationOverlay); clusterListOverlay = new ClusterListOverlay(); overlays.add(clusterListOverlay); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Setup default values for the settings. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Setup view. setContentView(R.layout.main); // Setup action bar. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayShowTitleEnabled(false); } // Setup map. mapView = (TrackableMapView)findViewById(R.id.map_view); mapView.setBuiltInZoomControls(false); mapView.addMovedOrZoomedObserver(new MapViewListener() { @Override public void onMovedOrZoomed() { Log.d(LOG_TAG + ".onCreate", "onMovedOrZoomed"); updateZoomButtonsState(); startRefreshingScanResultsOnMap(); } }); mapView.invalidateMovedOrZoomed(); // Setup map controller. final MapController mapController = mapView.getController(); // Setup current location. myLocationOverlay = new TrackableMyLocationOverlay(this, mapView); myLocationOverlay.runOnFirstFix(new Runnable() { public void run() { Log.d(LOG_TAG + ".onCreate", "runOnFirstFix"); // Zoom in to current location mapController.setZoom(DEFAULT_ZOOM); mapController.animateTo(myLocationOverlay.getMyLocation()); mapView.invalidateMovedOrZoomed(); } }); // Setup my location button. findViewById(R.id.button_my_location).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GeoPoint myLocation = myLocationOverlay.getMyLocation(); if (myLocation == null) { // Try to obtain current location from the location tracker. final Location location = LocationTracker.getInstance().getLocation(MainActivity.this); if (location != null) { myLocation = L.toGeoPoint(location.getLatitude(), location.getLongitude()); } } if (myLocation != null) { mapController.animateTo(myLocation); mapView.invalidateMovedOrZoomed(); } else { Toast.makeText(MainActivity.this, R.string.my_location_is_unavailable, Toast.LENGTH_SHORT).show(); } } }); // Setup zoom buttons. findViewById(R.id.button_zoom_out).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomOut(); mapView.invalidateMovedOrZoomed(); } }); findViewById(R.id.button_zoom_in).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mapController.zoomIn(); mapView.invalidateMovedOrZoomed(); } }); // Setup overlays. final List<Overlay> overlays = mapView.getOverlays(); clusterListOverlay = new ClusterListOverlay(); overlays.add(clusterListOverlay); overlays.add(myLocationOverlay); }
diff --git a/src/main/java/hudson/plugins/cppncss/parser/Statistic.java b/src/main/java/hudson/plugins/cppncss/parser/Statistic.java index f6ed1a9..ca0f06d 100644 --- a/src/main/java/hudson/plugins/cppncss/parser/Statistic.java +++ b/src/main/java/hudson/plugins/cppncss/parser/Statistic.java @@ -1,380 +1,380 @@ package hudson.plugins.cppncss.parser; import hudson.model.AbstractBuild; import hudson.util.IOException2; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.*; import java.util.*; /** * TODO javadoc. * * @author Stephen Connolly * @author Shaohua Wen * @since 25-Feb-2008 21:33:40 */ public class Statistic implements Serializable { // ------------------------------ FIELDS ------------------------------ private AbstractBuild<?, ?> owner; private String name; private long functions; private long ncss; private long ccn; private String parentElement; // -------------------------- STATIC METHODS -------------------------- public static StatisticsResult parse(File inFile) throws IOException, XmlPullParserException { StatisticsResult result = new StatisticsResult(); Collection<Statistic> fileResults = new ArrayList<Statistic>(); Collection<Statistic> functionResults = new ArrayList<Statistic>(); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); XmlPullParser parser = factory.newPullParser(); parser.setInput(bis, null); // check that the first tag is <cppncss> expectNextTag(parser, "cppncss"); // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } int depth = parser.getDepth(); //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String functionName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", functionName); String[] functionValueNames = {"Nr.","NCSS","CCN"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(functionValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); if(data.get("name").indexOf(" at ") > 0){ String fileStr = data.get("name").substring(data.get("name").indexOf(" at ")+4); String file = fileStr.substring(0,fileStr.lastIndexOf(":")); s.setParentElement(file); } - s.setNcss(Long.valueOf(data.get(functionValueNames[1]))); - s.setCcn(Long.valueOf(data.get(functionValueNames[2]))); + s.setNcss(Long.valueOf(data.get(functionValueNames[1]).trim())); + s.setCcn(Long.valueOf(data.get(functionValueNames[2]).trim())); functionResults.add(s); } parser.next(); } // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } depth = parser.getDepth(); while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String fileName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", fileName); String[] fileValueNames = {"Nr.","NCSS","CCN","Functions"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(fileValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); - s.setNcss(Long.valueOf(data.get(fileValueNames[1]))); - s.setCcn(Long.valueOf(data.get(fileValueNames[2]))); - s.setFunctions(Long.valueOf(data.get(fileValueNames[3]))); + s.setNcss(Long.valueOf(data.get(fileValueNames[1]).trim())); + s.setCcn(Long.valueOf(data.get(fileValueNames[2]).trim())); + s.setFunctions(Long.valueOf(data.get(fileValueNames[3]).trim())); fileResults.add(s); } parser.next(); } } catch (XmlPullParserException e) { throw new IOException2(e); } finally { if (bis != null) { bis.close(); } if (fis != null) { fis.close(); } } result.setFunctionResults(functionResults); result.setFileResults(fileResults); return result; } private static boolean skipToTag(XmlPullParser parser, String tagName) throws IOException, XmlPullParserException { while (true) { if (parser.getEventType() == XmlPullParser.END_TAG) { return false; } if (parser.getEventType() != XmlPullParser.START_TAG) { parser.next(); continue; } if (parser.getName().equals(tagName)) { return true; } skipTag(parser); } } private static void skipTag(XmlPullParser parser) throws IOException, XmlPullParserException { parser.next(); endElement(parser); } private static void expectNextTag(XmlPullParser parser, String tag) throws IOException, XmlPullParserException { while (true) { if (parser.getEventType() != XmlPullParser.START_TAG) { parser.next(); continue; } if (parser.getName().equals(tag)) { return; } throw new IOException("Expecting tag " + tag); } } private static void endElement(XmlPullParser parser) throws IOException, XmlPullParserException { int depth = parser.getDepth(); while (parser.getDepth() >= depth) { parser.next(); } } public static Statistic total(Collection<Statistic>... results) { Collection<Statistic> merged = merge(results); Statistic total = new Statistic(""); for (Statistic individual : merged) { total.add(individual); } return total; } public void add(Statistic r) { functions += r.functions; ncss += r.ncss; ccn += r.ccn; } public static Collection<Statistic> merge(Collection<Statistic>... results) { Collection<Statistic> newResults = new ArrayList<Statistic>(); if (results.length == 0) { return Collections.emptySet(); } else if (results.length == 1) { return results[0]; } else { List<String> indivNames = new ArrayList<String>(); for (Collection<Statistic> result : results) { for (Statistic individual : result) { if (!indivNames.contains(individual.name)) { indivNames.add(individual.name); } } } for (String indivName : indivNames) { Statistic indivStat = new Statistic(indivName); for (Collection<Statistic> result : results) { for (Statistic individual : result) { if (indivName.equals(individual.name)) { indivStat.add(individual); } } } newResults.add(indivStat); } return newResults; } } // --------------------------- CONSTRUCTORS --------------------------- public Statistic(String name) { this.name = name; } // --------------------- GETTER / SETTER METHODS --------------------- public void setCcn(long ccn) { this.ccn = ccn; } public long getCcn() { return ccn; } public long getFunctions() { return functions; } public void setFunctions(long functions) { this.functions = functions; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getNcss() { return ncss; } public void setNcss(long ncss) { this.ncss = ncss; } public AbstractBuild<?, ?> getOwner() { return owner; } public void setOwner(AbstractBuild<?, ?> owner) { this.owner = owner; } public void setParentElement(String parentElement) { this.parentElement = parentElement; } public String getParentElement(){ return parentElement; } // ------------------------ CANONICAL METHODS ------------------------ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Statistic statistic = (Statistic) o; if (ccn != statistic.ccn) return false; if (functions != statistic.functions) return false; if (ncss != statistic.ncss) return false; if (!name.equals(statistic.name)) return false; if (owner != null ? !owner.equals(statistic.owner) : statistic.owner != null) return false; return true; } public int hashCode() { int result; result = (owner != null ? owner.hashCode() : 0); result = 31 * result + name.hashCode(); return result; } public String toString() { return "Statistic{" + "name='" + name + '\'' + ", ccn=" + ccn + ", functions=" + functions + ", ncss=" + ncss + '}'; } public String toSummary() { return "<ul>" + diff(0, ccn, "ccn") + diff(0, functions, "functions") + diff(0, ncss, "ncss") + "</ul>"; } private static String diff(long a, long b, String name) { if (a == b) { return ""; } else if (a < b) { return "<li>" + name + " (+" + (b - a) + ")</li>"; } else { // if (a < b) return "<li>" + name + " (-" + (a - b) + ")</li>"; } } public String toSummary(Statistic totals) { return "<ul>" + diff(totals.ccn, ccn, "ccn") + diff(totals.functions, functions, "functions") + diff(totals.ncss, ncss, "ncss") + "</ul>"; } public void set(Statistic that) { this.name = that.name; this.ccn = that.ccn; this.functions = that.functions; this.ncss = that.ncss; } }
false
true
public static StatisticsResult parse(File inFile) throws IOException, XmlPullParserException { StatisticsResult result = new StatisticsResult(); Collection<Statistic> fileResults = new ArrayList<Statistic>(); Collection<Statistic> functionResults = new ArrayList<Statistic>(); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); XmlPullParser parser = factory.newPullParser(); parser.setInput(bis, null); // check that the first tag is <cppncss> expectNextTag(parser, "cppncss"); // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } int depth = parser.getDepth(); //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String functionName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", functionName); String[] functionValueNames = {"Nr.","NCSS","CCN"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(functionValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); if(data.get("name").indexOf(" at ") > 0){ String fileStr = data.get("name").substring(data.get("name").indexOf(" at ")+4); String file = fileStr.substring(0,fileStr.lastIndexOf(":")); s.setParentElement(file); } s.setNcss(Long.valueOf(data.get(functionValueNames[1]))); s.setCcn(Long.valueOf(data.get(functionValueNames[2]))); functionResults.add(s); } parser.next(); } // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } depth = parser.getDepth(); while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String fileName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", fileName); String[] fileValueNames = {"Nr.","NCSS","CCN","Functions"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(fileValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); s.setNcss(Long.valueOf(data.get(fileValueNames[1]))); s.setCcn(Long.valueOf(data.get(fileValueNames[2]))); s.setFunctions(Long.valueOf(data.get(fileValueNames[3]))); fileResults.add(s); } parser.next(); } } catch (XmlPullParserException e) { throw new IOException2(e); } finally { if (bis != null) { bis.close(); } if (fis != null) { fis.close(); } } result.setFunctionResults(functionResults); result.setFileResults(fileResults); return result; }
public static StatisticsResult parse(File inFile) throws IOException, XmlPullParserException { StatisticsResult result = new StatisticsResult(); Collection<Statistic> fileResults = new ArrayList<Statistic>(); Collection<Statistic> functionResults = new ArrayList<Statistic>(); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); XmlPullParser parser = factory.newPullParser(); parser.setInput(bis, null); // check that the first tag is <cppncss> expectNextTag(parser, "cppncss"); // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } int depth = parser.getDepth(); //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String functionName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", functionName); String[] functionValueNames = {"Nr.","NCSS","CCN"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(functionValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); if(data.get("name").indexOf(" at ") > 0){ String fileStr = data.get("name").substring(data.get("name").indexOf(" at ")+4); String file = fileStr.substring(0,fileStr.lastIndexOf(":")); s.setParentElement(file); } s.setNcss(Long.valueOf(data.get(functionValueNames[1]).trim())); s.setCcn(Long.valueOf(data.get(functionValueNames[2]).trim())); functionResults.add(s); } parser.next(); } // skip until we get to the <measure> tag while (parser.getDepth() > 0 && (parser.getEventType() != XmlPullParser.START_TAG || !"measure".equals(parser.getName()))) { parser.next(); } //skip until we get to <item> tag while(parser.getDepth() > 1 && (parser.getEventType() != XmlPullParser.START_TAG || !"item".equals(parser.getName()))) { parser.next(); } depth = parser.getDepth(); while(parser.getDepth() >= depth) { if(parser.getDepth() == 3 && parser.getEventType() == XmlPullParser.START_TAG && "item".equals(parser.getName())){ String fileName = parser.getAttributeValue(0); Map<String, String> data = new HashMap<String, String>(); data.put("name", fileName); String[] fileValueNames = {"Nr.","NCSS","CCN","Functions"}; int subIndex = 0; String lastTag = null; String lastText = null; while (parser.getDepth() >= 3) { parser.next(); switch (parser.getEventType()) { case XmlPullParser.START_TAG: lastTag = parser.getName(); break; case XmlPullParser.TEXT: lastText = parser.getText(); break; case XmlPullParser.END_TAG: subIndex ++; if (parser.getDepth() == 4 && lastTag != null && lastText != null) { data.put(fileValueNames[subIndex - 1 ], lastText); } lastTag = null; lastText = null; break; } } Statistic s = new Statistic(data.get("name")); s.setNcss(Long.valueOf(data.get(fileValueNames[1]).trim())); s.setCcn(Long.valueOf(data.get(fileValueNames[2]).trim())); s.setFunctions(Long.valueOf(data.get(fileValueNames[3]).trim())); fileResults.add(s); } parser.next(); } } catch (XmlPullParserException e) { throw new IOException2(e); } finally { if (bis != null) { bis.close(); } if (fis != null) { fis.close(); } } result.setFunctionResults(functionResults); result.setFileResults(fileResults); return result; }
diff --git a/src/org/andengine/extension/rubeloader/factory/PhysicsWorldFactoryFixedStep.java b/src/org/andengine/extension/rubeloader/factory/PhysicsWorldFactoryFixedStep.java index a78851a..045a76d 100644 --- a/src/org/andengine/extension/rubeloader/factory/PhysicsWorldFactoryFixedStep.java +++ b/src/org/andengine/extension/rubeloader/factory/PhysicsWorldFactoryFixedStep.java @@ -1,21 +1,21 @@ package org.andengine.extension.rubeloader.factory; import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.extension.rubeloader.def.WorldDef; public class PhysicsWorldFactoryFixedStep extends PhysicsWorldFactory { private final int mStepsPerSecond; public PhysicsWorldFactoryFixedStep(int pStepsPerSecond) { super(); this.mStepsPerSecond = pStepsPerSecond; } @Override public PhysicsWorld populate(WorldDef pWorldDef) { - PhysicsWorld ret = new FixedStepPhysicsWorld(mStepsPerSecond, pWorldDef.gravity, pWorldDef.allowSleep, pWorldDef.positionIterations, pWorldDef.velocityIterations); + PhysicsWorld ret = new FixedStepPhysicsWorld(mStepsPerSecond, pWorldDef.gravity, pWorldDef.allowSleep, pWorldDef.velocityIterations, pWorldDef.positionIterations); tuneParams(pWorldDef, ret); return ret; } }
true
true
public PhysicsWorld populate(WorldDef pWorldDef) { PhysicsWorld ret = new FixedStepPhysicsWorld(mStepsPerSecond, pWorldDef.gravity, pWorldDef.allowSleep, pWorldDef.positionIterations, pWorldDef.velocityIterations); tuneParams(pWorldDef, ret); return ret; }
public PhysicsWorld populate(WorldDef pWorldDef) { PhysicsWorld ret = new FixedStepPhysicsWorld(mStepsPerSecond, pWorldDef.gravity, pWorldDef.allowSleep, pWorldDef.velocityIterations, pWorldDef.positionIterations); tuneParams(pWorldDef, ret); return ret; }
diff --git a/melati/src/main/java/org/melati/servlet/DefaultFileDataAdaptor.java b/melati/src/main/java/org/melati/servlet/DefaultFileDataAdaptor.java index f904b9170..932238f1c 100644 --- a/melati/src/main/java/org/melati/servlet/DefaultFileDataAdaptor.java +++ b/melati/src/main/java/org/melati/servlet/DefaultFileDataAdaptor.java @@ -1,112 +1,113 @@ /* * $Source$ * $Revision$ * * Copyright (C) 2000 Myles Chippendale * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * Melati is free software; Permission is granted to copy, distribute * and/or modify this software under the terms either: * * a) 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, * * or * * b) any version of the Melati Software License, as published * at http://melati.org * * You should have received a copy of the GNU General Public License and * the Melati Software License along with this program; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the * GNU General Public License and visit http://melati.org to obtain the * Melati Software License. * * Feel free to contact the Developers of Melati (http://melati.org), * if you would like to work out a different arrangement than the options * outlined here. It is our intention to allow Melati to be used by as * wide an audience as possible. * * 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. * * Contact details for copyright holder: * * Mylesc Chippendale <mylesc At paneris.org> * http://paneris.org/ * 29 Stanley Road, Oxford, OX4 1QY, UK */ package org.melati.servlet; import java.io.File; import org.melati.Melati; import org.melati.util.UTF8URLEncoder; import org.melati.util.FileUtils; /** * The default way to save an uploaded file to disk. * * We tell it what directory to save it in and the base URL * to that directory. */ public class DefaultFileDataAdaptor extends BaseFileDataAdaptor { protected Melati melati; protected String uploadDir = null; protected String uploadURL = null; protected boolean makeUnique = true; /** * Constructor. * * @param melatiP The current melati * @param uploadDirP The directory to save this file in * @param uploadUrlP A URL pointing to this directory (null if there * isn't an appropriate URL) */ public DefaultFileDataAdaptor(Melati melatiP, String uploadDirP, String uploadUrlP) { this.melati = melatiP; this.uploadDir = uploadDirP; this.uploadURL = uploadUrlP; } /** * Constructor. * * @param melatiP The current melati * @param uploadDir The directory to save this file in * @param uploadURL A URL pointing to this directory (null if there * isn't an appropriate URL) * @param makeUnique Whether we should make sure the new file has a unique * name within the <code>uploadDir</code> directory */ public DefaultFileDataAdaptor(Melati melatiP, String uploadDir, String uploadURL, boolean makeUnique) { + this.melati = melatiP; this.uploadDir = uploadDir; this.uploadURL = uploadURL; this.makeUnique = makeUnique; } protected File calculateLocalFile() { // FIXME decode surely? File f = new File(uploadDir, UTF8URLEncoder.encode(field.getUploadedFileName(), melati.getEncoding())); return makeUnique ? FileUtils.withUniqueName(f) : f; } protected String calculateURL() { return (uploadURL != null && getFile() != null) ? uploadURL + File.separatorChar + file.getName() : null; } }
true
true
public DefaultFileDataAdaptor(Melati melatiP, String uploadDir, String uploadURL, boolean makeUnique) { this.uploadDir = uploadDir; this.uploadURL = uploadURL; this.makeUnique = makeUnique; }
public DefaultFileDataAdaptor(Melati melatiP, String uploadDir, String uploadURL, boolean makeUnique) { this.melati = melatiP; this.uploadDir = uploadDir; this.uploadURL = uploadURL; this.makeUnique = makeUnique; }
diff --git a/src/main/java/org/concord/energy3d/logger/PostProcessor.java b/src/main/java/org/concord/energy3d/logger/PostProcessor.java index f9ac4aae..fb8edc26 100644 --- a/src/main/java/org/concord/energy3d/logger/PostProcessor.java +++ b/src/main/java/org/concord/energy3d/logger/PostProcessor.java @@ -1,150 +1,157 @@ package org.concord.energy3d.logger; import java.io.File; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import org.concord.energy3d.model.Floor; import org.concord.energy3d.model.Foundation; import org.concord.energy3d.model.HousePart; import org.concord.energy3d.model.Roof; import org.concord.energy3d.model.Wall; import org.concord.energy3d.model.Window; import org.concord.energy3d.scene.Scene; /** * @author Charles Xie * */ public class PostProcessor { public static boolean replaying = true; public static boolean backward, forward; private final static int SLEEP = 200; private final static DecimalFormat FORMAT_TIME_COUNT = new DecimalFormat("000000000"); private final static DecimalFormat FORMAT_PART_COUNT = new DecimalFormat("000"); private PostProcessor() { } public static void process(final File[] files, final File output, final Runnable update) { new Thread() { public void run() { final int n = files.length; PrintWriter logWriter = null; try { logWriter = new PrintWriter(output); } catch (final Exception ex) { ex.printStackTrace(); } final PrintWriter pw = logWriter; int i = -1; - Date date0 = null; int total0 = -1; int wallCount0 = -1; int windowCount0 = -1; int foundationCount0 = -1; int roofCount0 = -1; int floorCount0 = -1; long timestamp = -1; + Date date0 = null; while (i < n - 1) { if (replaying) { i++; - // if (i == n) i = 0; int slash = files[i].toString().lastIndexOf(System.getProperty("file.separator")); String fileName = files[i].toString().substring(slash + 1).trim(); String[] ss = fileName.substring(0, fileName.length() - 4).split("[\\s]+"); // get time stamp - String[] day = ss[0].split("-"); - String[] time = ss[1].split("-"); - Calendar c = Calendar.getInstance(); - c.set(Integer.parseInt(day[0]), Integer.parseInt(day[1]) - 1, Integer.parseInt(day[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2])); - if (date0 == null) - date0 = c.getTime(); - timestamp = Math.round((c.getTime().getTime() - date0.getTime()) * 0.001); + if (ss.length >= 2) { + String[] day = ss[0].split("-"); + String[] time = ss[1].split("-"); + Calendar c = Calendar.getInstance(); + c.set(Integer.parseInt(day[0]), Integer.parseInt(day[1]) - 1, Integer.parseInt(day[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2])); + if (date0 == null) + date0 = c.getTime(); + timestamp = Math.round((c.getTime().getTime() - date0.getTime()) * 0.001); + } else { + System.err.println("File timestamp error"); + timestamp = 0; + } System.out.println("Play back " + i + " of " + n + ": " + fileName); try { Scene.open(files[i].toURI().toURL()); update.run(); sleep(SLEEP); } catch (final Exception e) { e.printStackTrace(); } final ArrayList<HousePart> parts = Scene.getInstance().getParts(); int wallCount = 0; int windowCount = 0; int foundationCount = 0; int roofCount = 0; int floorCount = 0; for (HousePart x : parts) { if (x instanceof Wall) wallCount++; else if (x instanceof Window) windowCount++; else if (x instanceof Foundation) foundationCount++; else if (x instanceof Roof) roofCount++; else if (x instanceof Floor) floorCount++; } if (total0 == -1) total0 = parts.size(); if (wallCount0 == -1) wallCount0 = wallCount; if (windowCount0 == -1) windowCount0 = windowCount; if (foundationCount0 == -1) foundationCount0 = foundationCount; if (roofCount0 == -1) roofCount0 = roofCount; if (floorCount0 == -1) floorCount0 = floorCount; pw.print(fileName); pw.print(" Timestamp=" + FORMAT_TIME_COUNT.format(timestamp)); pw.print(" Total=" + FORMAT_PART_COUNT.format(parts.size() - total0)); pw.print(" Wall=" + FORMAT_PART_COUNT.format(wallCount - wallCount0)); pw.print(" Window=" + FORMAT_PART_COUNT.format(windowCount - windowCount0)); pw.print(" Foundation=" + FORMAT_PART_COUNT.format(foundationCount - foundationCount0)); pw.print(" Roof=" + FORMAT_PART_COUNT.format(roofCount - roofCount0)); pw.print(" Floor=" + FORMAT_PART_COUNT.format(floorCount - floorCount0)); pw.println(""); + // if (i == n - 1) i = 0; } else { if (backward) { if (i > 0) { i--; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } backward = false; } else if (forward) { if (i < n - 1) { i++; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } forward = false; + if (i == n - 1) + i = n - 2; } } } pw.close(); } }.start(); } }
false
true
public static void process(final File[] files, final File output, final Runnable update) { new Thread() { public void run() { final int n = files.length; PrintWriter logWriter = null; try { logWriter = new PrintWriter(output); } catch (final Exception ex) { ex.printStackTrace(); } final PrintWriter pw = logWriter; int i = -1; Date date0 = null; int total0 = -1; int wallCount0 = -1; int windowCount0 = -1; int foundationCount0 = -1; int roofCount0 = -1; int floorCount0 = -1; long timestamp = -1; while (i < n - 1) { if (replaying) { i++; // if (i == n) i = 0; int slash = files[i].toString().lastIndexOf(System.getProperty("file.separator")); String fileName = files[i].toString().substring(slash + 1).trim(); String[] ss = fileName.substring(0, fileName.length() - 4).split("[\\s]+"); // get time stamp String[] day = ss[0].split("-"); String[] time = ss[1].split("-"); Calendar c = Calendar.getInstance(); c.set(Integer.parseInt(day[0]), Integer.parseInt(day[1]) - 1, Integer.parseInt(day[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2])); if (date0 == null) date0 = c.getTime(); timestamp = Math.round((c.getTime().getTime() - date0.getTime()) * 0.001); System.out.println("Play back " + i + " of " + n + ": " + fileName); try { Scene.open(files[i].toURI().toURL()); update.run(); sleep(SLEEP); } catch (final Exception e) { e.printStackTrace(); } final ArrayList<HousePart> parts = Scene.getInstance().getParts(); int wallCount = 0; int windowCount = 0; int foundationCount = 0; int roofCount = 0; int floorCount = 0; for (HousePart x : parts) { if (x instanceof Wall) wallCount++; else if (x instanceof Window) windowCount++; else if (x instanceof Foundation) foundationCount++; else if (x instanceof Roof) roofCount++; else if (x instanceof Floor) floorCount++; } if (total0 == -1) total0 = parts.size(); if (wallCount0 == -1) wallCount0 = wallCount; if (windowCount0 == -1) windowCount0 = windowCount; if (foundationCount0 == -1) foundationCount0 = foundationCount; if (roofCount0 == -1) roofCount0 = roofCount; if (floorCount0 == -1) floorCount0 = floorCount; pw.print(fileName); pw.print(" Timestamp=" + FORMAT_TIME_COUNT.format(timestamp)); pw.print(" Total=" + FORMAT_PART_COUNT.format(parts.size() - total0)); pw.print(" Wall=" + FORMAT_PART_COUNT.format(wallCount - wallCount0)); pw.print(" Window=" + FORMAT_PART_COUNT.format(windowCount - windowCount0)); pw.print(" Foundation=" + FORMAT_PART_COUNT.format(foundationCount - foundationCount0)); pw.print(" Roof=" + FORMAT_PART_COUNT.format(roofCount - roofCount0)); pw.print(" Floor=" + FORMAT_PART_COUNT.format(floorCount - floorCount0)); pw.println(""); } else { if (backward) { if (i > 0) { i--; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } backward = false; } else if (forward) { if (i < n - 1) { i++; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } forward = false; } } } pw.close(); } }.start(); }
public static void process(final File[] files, final File output, final Runnable update) { new Thread() { public void run() { final int n = files.length; PrintWriter logWriter = null; try { logWriter = new PrintWriter(output); } catch (final Exception ex) { ex.printStackTrace(); } final PrintWriter pw = logWriter; int i = -1; int total0 = -1; int wallCount0 = -1; int windowCount0 = -1; int foundationCount0 = -1; int roofCount0 = -1; int floorCount0 = -1; long timestamp = -1; Date date0 = null; while (i < n - 1) { if (replaying) { i++; int slash = files[i].toString().lastIndexOf(System.getProperty("file.separator")); String fileName = files[i].toString().substring(slash + 1).trim(); String[] ss = fileName.substring(0, fileName.length() - 4).split("[\\s]+"); // get time stamp if (ss.length >= 2) { String[] day = ss[0].split("-"); String[] time = ss[1].split("-"); Calendar c = Calendar.getInstance(); c.set(Integer.parseInt(day[0]), Integer.parseInt(day[1]) - 1, Integer.parseInt(day[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2])); if (date0 == null) date0 = c.getTime(); timestamp = Math.round((c.getTime().getTime() - date0.getTime()) * 0.001); } else { System.err.println("File timestamp error"); timestamp = 0; } System.out.println("Play back " + i + " of " + n + ": " + fileName); try { Scene.open(files[i].toURI().toURL()); update.run(); sleep(SLEEP); } catch (final Exception e) { e.printStackTrace(); } final ArrayList<HousePart> parts = Scene.getInstance().getParts(); int wallCount = 0; int windowCount = 0; int foundationCount = 0; int roofCount = 0; int floorCount = 0; for (HousePart x : parts) { if (x instanceof Wall) wallCount++; else if (x instanceof Window) windowCount++; else if (x instanceof Foundation) foundationCount++; else if (x instanceof Roof) roofCount++; else if (x instanceof Floor) floorCount++; } if (total0 == -1) total0 = parts.size(); if (wallCount0 == -1) wallCount0 = wallCount; if (windowCount0 == -1) windowCount0 = windowCount; if (foundationCount0 == -1) foundationCount0 = foundationCount; if (roofCount0 == -1) roofCount0 = roofCount; if (floorCount0 == -1) floorCount0 = floorCount; pw.print(fileName); pw.print(" Timestamp=" + FORMAT_TIME_COUNT.format(timestamp)); pw.print(" Total=" + FORMAT_PART_COUNT.format(parts.size() - total0)); pw.print(" Wall=" + FORMAT_PART_COUNT.format(wallCount - wallCount0)); pw.print(" Window=" + FORMAT_PART_COUNT.format(windowCount - windowCount0)); pw.print(" Foundation=" + FORMAT_PART_COUNT.format(foundationCount - foundationCount0)); pw.print(" Roof=" + FORMAT_PART_COUNT.format(roofCount - roofCount0)); pw.print(" Floor=" + FORMAT_PART_COUNT.format(floorCount - floorCount0)); pw.println(""); // if (i == n - 1) i = 0; } else { if (backward) { if (i > 0) { i--; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } backward = false; } else if (forward) { if (i < n - 1) { i++; System.out.println("Play back " + i + " of " + n); try { Scene.open(files[i].toURI().toURL()); update.run(); } catch (final Exception e) { e.printStackTrace(); } } forward = false; if (i == n - 1) i = n - 2; } } } pw.close(); } }.start(); }
diff --git a/aQute.libg/src/aQute/libg/cafs/CAFS.java b/aQute.libg/src/aQute/libg/cafs/CAFS.java index d7473918d..61233969d 100644 --- a/aQute.libg/src/aQute/libg/cafs/CAFS.java +++ b/aQute.libg/src/aQute/libg/cafs/CAFS.java @@ -1,414 +1,414 @@ package aQute.libg.cafs; import static aQute.lib.io.IO.*; import java.io.*; import java.nio.channels.*; import java.security.*; import java.util.*; import java.util.concurrent.atomic.*; import java.util.zip.*; import aQute.lib.index.*; import aQute.libg.cryptography.*; /** * CAFS implements a SHA-1 based file store. The basic idea is that every file * in the universe has a unique SHA-1. Hard to believe but people smarter than * me have come to that conclusion. This class maintains a compressed store of * SHA-1 identified files. So if you have the SHA-1, you can get the contents. * * This makes it easy to store a SHA-1 instead of the whole file or maintain a * naming scheme. An added advantage is that it is always easy to verify you get * the right stuff. The SHA-1 Content Addressable File Store is the core * underlying idea in Git. */ public class CAFS implements Closeable, Iterable<SHA1> { final static byte[] CAFS = "CAFS".getBytes(); final static byte[] CAFE = "CAFE".getBytes(); final static String INDEXFILE = "index.idx"; final static String STOREFILE = "store.cafs"; final static String ALGORITHM = "SHA-1"; final static int KEYLENGTH = 20; final static int HEADERLENGTH = 4 // CAFS + 4 // flags + 4 // compressed length + 4 // uncompressed length + KEYLENGTH // key + 2 // header checksum ; final File home; Index index; RandomAccessFile store; FileChannel channel; /** * Constructor for a Content Addressable File Store * * @param home * @param create * @throws Exception */ public CAFS(File home, boolean create) throws Exception { this.home = home; if (!home.isDirectory()) { if (create) { home.mkdirs(); } else throw new IllegalArgumentException("CAFS requires a directory with create=false"); } index = new Index(new File(home, INDEXFILE), KEYLENGTH); store = new RandomAccessFile(new File(home, STOREFILE), "rw"); channel = store.getChannel(); if (store.length() < 0x100) { if (create) { store.write(CAFS); for (int i = 1; i < 64; i++) store.writeInt(0); channel.force(true); } else throw new IllegalArgumentException("Invalid store file, length is too short " + store); System.out.println(store.length()); } store.seek(0); if (!verifySignature(store, CAFS)) throw new IllegalArgumentException("Not a valid signature: CAFS at start of file"); } /** * Store an input stream in the CAFS while calculating and returning the * SHA-1 code. * * @param in * The input stream to store. * @return The SHA-1 code. * @throws Exception * if anything goes wrong */ public SHA1 write(InputStream in) throws Exception { Deflater deflater = new Deflater(); MessageDigest md = MessageDigest.getInstance(ALGORITHM); DigestInputStream din = new DigestInputStream(in, md); - DeflaterInputStream dfl = new DeflaterInputStream(din, deflater); ByteArrayOutputStream bout = new ByteArrayOutputStream(); - copy(dfl, bout); + DeflaterOutputStream dout = new DeflaterOutputStream(bout, deflater); + copy(din, dout); synchronized (store) { // First check if it already exists SHA1 sha1 = new SHA1(md.digest()); long search = index.search(sha1.digest()); if (search > 0) return sha1; byte[] compressed = bout.toByteArray(); // we need to append this file to our store, // which requires a lock. However, we are in a race // so others can get the lock between us getting // the length and someone else getting the lock. // So we must verify after we get the lock that the // length was unchanged. FileLock lock = null; try { long insertPoint; int recordLength = compressed.length + HEADERLENGTH; while (true) { insertPoint = store.length(); lock = channel.lock(insertPoint, recordLength, false); if (store.length() == insertPoint) break; // We got the wrong lock, someone else // got in between reading the length // and locking lock.release(); } int totalLength = deflater.getTotalIn(); store.seek(insertPoint); update(sha1.digest(), compressed, totalLength); index.insert(sha1.digest(), insertPoint); return sha1; } finally { if (lock != null) lock.release(); } } } /** * Read the contents of a sha 1 key. * * @param sha1 * The key * @return An Input Stream on the content or null of key not found * @throws Exception */ public InputStream read(final SHA1 sha1) throws Exception { synchronized (store) { long offset = index.search(sha1.digest()); if (offset < 0) return null; byte[] readSha1; byte[] buffer; store.seek(offset); if (!verifySignature(store, CAFE)) throw new IllegalArgumentException("No signature"); int flags =store.readInt(); int compressedLength = store.readInt(); int uncompressedLength = store.readInt(); readSha1 = new byte[KEYLENGTH]; store.read(readSha1); SHA1 rsha1 = new SHA1(readSha1); if (!sha1.equals(rsha1)) throw new IOException("SHA1 read and asked mismatch: " + sha1 + " " + rsha1); short crc = store.readShort(); // Read CRC if ( crc != checksum(flags,compressedLength, uncompressedLength, readSha1)) throw new IllegalArgumentException("Invalid header checksum: " + sha1); buffer = new byte[compressedLength]; store.readFully(buffer); return getSha1Stream(sha1, buffer, uncompressedLength); } } public boolean exists(byte[] sha1) throws Exception { return index.search(sha1) >= 0; } public void reindex() throws Exception { long length; synchronized (store) { length = store.length(); if (length < 0x100) throw new IllegalArgumentException( "Store file is too small, need to be at least 256 bytes: " + store); } RandomAccessFile in = new RandomAccessFile(new File(home, STOREFILE), "r"); try { byte[] signature = new byte[4]; in.readFully(signature); if (!Arrays.equals(CAFS, signature)) throw new IllegalArgumentException("Store file does not start with CAFS: " + in); in.seek(0x100); File ixf = new File(home, "index.new"); Index index = new Index(ixf, KEYLENGTH); while (in.getFilePointer() < length) { long entry = in.getFilePointer(); SHA1 sha1 = verifyEntry(in); index.insert(sha1.digest(), entry); } synchronized (store) { index.close(); File indexFile = new File(home, INDEXFILE); ixf.renameTo(indexFile); index = new Index(indexFile, KEYLENGTH); } } finally { in.close(); } } public void close() throws IOException { synchronized (store) { try { store.close(); } finally { index.close(); } } } private SHA1 verifyEntry(RandomAccessFile in) throws IOException, NoSuchAlgorithmException { byte[] signature = new byte[4]; in.readFully(signature); if (!Arrays.equals(CAFE, signature)) throw new IllegalArgumentException("File is corrupted: " + in); /* int flags = */in.readInt(); int compressedSize = in.readInt(); int uncompressedSize = in.readInt(); byte[] key = new byte[KEYLENGTH]; in.readFully(key); SHA1 sha1 = new SHA1(key); byte[] buffer = new byte[compressedSize]; in.readFully(buffer); InputStream xin = getSha1Stream(sha1, buffer, uncompressedSize); xin.skip(uncompressedSize); xin.close(); return sha1; } private boolean verifySignature(DataInput din, byte[] org) throws IOException { byte[] read = new byte[org.length]; din.readFully(read); return Arrays.equals(read, org); } private InputStream getSha1Stream(final SHA1 sha1, byte[] buffer, final int total) throws NoSuchAlgorithmException { ByteArrayInputStream in = new ByteArrayInputStream(buffer); InflaterInputStream iin = new InflaterInputStream(in) { int count = 0; final MessageDigest digestx = MessageDigest.getInstance(ALGORITHM); final AtomicBoolean calculated = new AtomicBoolean(); @Override public int read(byte[] data, int offset, int length) throws IOException { int size = super.read(data, offset, length); if (size <= 0) eof(); else { count+=size; this.digestx.update(data, offset, size); } return size; } public int read() throws IOException { int c = super.read(); if (c < 0) eof(); else { count++; this.digestx.update((byte) c); } return c; } void eof() throws IOException { if ( calculated.getAndSet(true)) return; if ( count != total ) throw new IOException("Counts do not match. Expected to read: " + total + " Actually read: " + count); SHA1 calculatedSha1 = new SHA1(digestx.digest()); if (!sha1.equals(calculatedSha1)) throw ( new IOException("SHA1 caclulated and asked mismatch, asked: " + sha1 + ", \nfound: " +calculatedSha1)); } public void close() throws IOException { eof(); super.close(); } }; return iin; } /** * Update a record in the store, assuming the store is at the right * position. * * @param sha1 * The checksum * @param compressed * The compressed length * @param totalLength * The uncompressed length * @throws IOException * The exception */ private void update(byte[] sha1, byte[] compressed, int totalLength) throws IOException { System.out.println("pos: " + store.getFilePointer()); store.write(CAFE); // 00-03 Signature store.writeInt(0); // 04-07 Flags for the future store.writeInt(compressed.length); // 08-11 Length deflated data store.writeInt(totalLength); // 12-15 Length store.write(sha1); // 16-35 store.writeShort( checksum(0,compressed.length, totalLength, sha1)); store.write(compressed); channel.force(false); } private short checksum(int flags, int compressedLength, int totalLength, byte[] sha1) { CRC32 crc = new CRC32(); crc.update(flags); crc.update(flags>>8); crc.update(flags>>16); crc.update(flags>>24); crc.update(compressedLength); crc.update(compressedLength>>8); crc.update(compressedLength>>16); crc.update(compressedLength>>24); crc.update(totalLength); crc.update(totalLength>>8); crc.update(totalLength>>16); crc.update(totalLength>>24); crc.update(sha1); return (short) crc.getValue(); } public Iterator<SHA1> iterator() { return new Iterator<SHA1>() { long position = 0x100; public boolean hasNext() { synchronized(store) { try { return position < store.length(); } catch (IOException e) { throw new RuntimeException(e); } } } public SHA1 next() { synchronized(store) { try { store.seek(position); byte [] signature = new byte[4]; store.readFully(signature); if ( !Arrays.equals(CAFE, signature)) throw new IllegalArgumentException("No signature"); int flags = store.readInt(); int compressedLength = store.readInt(); int totalLength = store.readInt(); byte []sha1 = new byte[KEYLENGTH]; store.readFully(sha1); short crc = store.readShort(); if ( crc != checksum(flags,compressedLength, totalLength, sha1)) throw new IllegalArgumentException("Header checksum fails"); position += HEADERLENGTH + compressedLength; return new SHA1(sha1); } catch (IOException e) { throw new RuntimeException(e); } } } public void remove() { throw new UnsupportedOperationException("Remvoe not supported, CAFS is write once"); } }; } public boolean isEmpty() throws IOException { synchronized(store) { return store.getFilePointer() <= 256; } } }
false
true
public SHA1 write(InputStream in) throws Exception { Deflater deflater = new Deflater(); MessageDigest md = MessageDigest.getInstance(ALGORITHM); DigestInputStream din = new DigestInputStream(in, md); DeflaterInputStream dfl = new DeflaterInputStream(din, deflater); ByteArrayOutputStream bout = new ByteArrayOutputStream(); copy(dfl, bout); synchronized (store) { // First check if it already exists SHA1 sha1 = new SHA1(md.digest()); long search = index.search(sha1.digest()); if (search > 0) return sha1; byte[] compressed = bout.toByteArray(); // we need to append this file to our store, // which requires a lock. However, we are in a race // so others can get the lock between us getting // the length and someone else getting the lock. // So we must verify after we get the lock that the // length was unchanged. FileLock lock = null; try { long insertPoint; int recordLength = compressed.length + HEADERLENGTH; while (true) { insertPoint = store.length(); lock = channel.lock(insertPoint, recordLength, false); if (store.length() == insertPoint) break; // We got the wrong lock, someone else // got in between reading the length // and locking lock.release(); } int totalLength = deflater.getTotalIn(); store.seek(insertPoint); update(sha1.digest(), compressed, totalLength); index.insert(sha1.digest(), insertPoint); return sha1; } finally { if (lock != null) lock.release(); } } }
public SHA1 write(InputStream in) throws Exception { Deflater deflater = new Deflater(); MessageDigest md = MessageDigest.getInstance(ALGORITHM); DigestInputStream din = new DigestInputStream(in, md); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DeflaterOutputStream dout = new DeflaterOutputStream(bout, deflater); copy(din, dout); synchronized (store) { // First check if it already exists SHA1 sha1 = new SHA1(md.digest()); long search = index.search(sha1.digest()); if (search > 0) return sha1; byte[] compressed = bout.toByteArray(); // we need to append this file to our store, // which requires a lock. However, we are in a race // so others can get the lock between us getting // the length and someone else getting the lock. // So we must verify after we get the lock that the // length was unchanged. FileLock lock = null; try { long insertPoint; int recordLength = compressed.length + HEADERLENGTH; while (true) { insertPoint = store.length(); lock = channel.lock(insertPoint, recordLength, false); if (store.length() == insertPoint) break; // We got the wrong lock, someone else // got in between reading the length // and locking lock.release(); } int totalLength = deflater.getTotalIn(); store.seek(insertPoint); update(sha1.digest(), compressed, totalLength); index.insert(sha1.digest(), insertPoint); return sha1; } finally { if (lock != null) lock.release(); } } }
diff --git a/app/src/jiunling/pass/wifi/RegexNetwork.java b/app/src/jiunling/pass/wifi/RegexNetwork.java index dad90ac..1762cc4 100644 --- a/app/src/jiunling/pass/wifi/RegexNetwork.java +++ b/app/src/jiunling/pass/wifi/RegexNetwork.java @@ -1,75 +1,75 @@ package jiunling.pass.wifi; import java.util.regex.Matcher; import java.util.regex.Pattern; import jiunling.pass.root.SuperUser; import org.json.JSONException; import org.json.JSONObject; public class RegexNetwork { /*** Debugging ***/ // private static final String TAG = "RegexNetwork"; // private static final boolean D = true; private static final String GetNetWorkShell = "cat /data/misc/wifi/wpa_supplicant.conf;"; private SuperUser mSuperUser = null; private String psk = null; private boolean verify = true; public RegexNetwork() { if( mSuperUser == null) mSuperUser = new SuperUser(); } public void getNetwork(String SSID) { if(mSuperUser.runShell(GetNetWorkShell)) { String command = mSuperUser.getResult(); try { JSONObject json = findSpecified(command, SSID); if(json != null) { if(!json.isNull("psk")) psk = json.getString("psk"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private JSONObject findSpecified(String command, String SSID) { Pattern mPattern = Pattern.compile("network=[{][^}]+[}]", Pattern.DOTALL | Pattern.MULTILINE); Matcher mMatcher = mPattern.matcher(command); while (mMatcher.find()) { String group = mMatcher.group(); group = group.replace("network=","").replace("\n",",").replace(",}","}").replaceFirst(",",""); try { JSONObject json = new JSONObject(group); if(SSID.equals(json.getString("ssid"))) { return json; } else { continue; } } catch (JSONException e) { // TODO Auto-generated catch block - e.printStackTrace(); +// e.printStackTrace(); verify = false; } } return null; } public boolean verify() { return verify; } public String getPSk() { return psk; } }
true
true
private JSONObject findSpecified(String command, String SSID) { Pattern mPattern = Pattern.compile("network=[{][^}]+[}]", Pattern.DOTALL | Pattern.MULTILINE); Matcher mMatcher = mPattern.matcher(command); while (mMatcher.find()) { String group = mMatcher.group(); group = group.replace("network=","").replace("\n",",").replace(",}","}").replaceFirst(",",""); try { JSONObject json = new JSONObject(group); if(SSID.equals(json.getString("ssid"))) { return json; } else { continue; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); verify = false; } } return null; }
private JSONObject findSpecified(String command, String SSID) { Pattern mPattern = Pattern.compile("network=[{][^}]+[}]", Pattern.DOTALL | Pattern.MULTILINE); Matcher mMatcher = mPattern.matcher(command); while (mMatcher.find()) { String group = mMatcher.group(); group = group.replace("network=","").replace("\n",",").replace(",}","}").replaceFirst(",",""); try { JSONObject json = new JSONObject(group); if(SSID.equals(json.getString("ssid"))) { return json; } else { continue; } } catch (JSONException e) { // TODO Auto-generated catch block // e.printStackTrace(); verify = false; } } return null; }
diff --git a/src/biz/bokhorst/xprivacy/PrivacyManager.java b/src/biz/bokhorst/xprivacy/PrivacyManager.java index 41b1296d..f8a410c1 100644 --- a/src/biz/bokhorst/xprivacy/PrivacyManager.java +++ b/src/biz/bokhorst/xprivacy/PrivacyManager.java @@ -1,842 +1,843 @@ package biz.bokhorst.xprivacy; import java.lang.reflect.Field; import java.net.Inet4Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import android.annotation.SuppressLint; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.location.Location; import android.nfc.NfcAdapter; import android.os.Build; import android.provider.MediaStore; import android.telephony.TelephonyManager; import android.util.Log; public class PrivacyManager { // This should correspond with restrict_<name> in strings.xml public static final String cAccounts = "accounts"; public static final String cBoot = "boot"; public static final String cBrowser = "browser"; public static final String cCalendar = "calendar"; public static final String cCalling = "calling"; public static final String cContacts = "contacts"; public static final String cDictionary = "dictionary"; public static final String cIdentification = "identification"; public static final String cInternet = "internet"; public static final String cLocation = "location"; public static final String cMedia = "media"; public static final String cMessages = "messages"; public static final String cNetwork = "network"; public static final String cNfc = "nfc"; public static final String cPhone = "phone"; public static final String cStorage = "storage"; public static final String cShell = "shell"; public static final String cSystem = "system"; public static final String cView = "view"; private static final String cRestrictionNames[] = new String[] { cAccounts, cBoot, cBrowser, cCalendar, cCalling, cContacts, cDictionary, cIdentification, cInternet, cLocation, cMedia, cMessages, cNetwork, cNfc, cPhone, cStorage, cShell, cSystem, cView }; public final static int cXposedMinVersion = 34; public final static boolean cExperimental = false; public final static int cUidAndroid = 1000; public final static String cSettingExpert = "Expert"; public final static String cSettingLatitude = "Latitude"; public final static String cSettingLongitude = "Longitude"; public final static String cSettingMac = "Mac"; public final static String cSettingImei = "IMEI"; public final static String cSettingPhone = "Phone"; public final static String cSettingId = "ID"; public final static String cSettingTheme = "Theme"; private final static String cDeface = "DEFACE"; private final static int cCacheTimeoutMs = 15 * 1000; private static Map<String, List<String>> mPermissions = new LinkedHashMap<String, List<String>>(); private static Map<String, List<String>> mMethods = new LinkedHashMap<String, List<String>>(); private static Map<String, CRestriction> mRestrictionCache = new HashMap<String, CRestriction>(); private static Map<String, CSetting> mSettingsCache = new HashMap<String, CSetting>(); private static Map<UsageData, UsageData> mUsageQueue = new LinkedHashMap<UsageData, UsageData>(); static { // This is a workaround, the idea was to use registerMethod // Static data is not shared across VM's // If you know a better solution, please let me know // Restrictions for (String restrictionName : cRestrictionNames) { mPermissions.put(restrictionName, new ArrayList<String>()); mMethods.put(restrictionName, new ArrayList<String>()); } // Permissions mPermissions.get(cAccounts).add("GET_ACCOUNTS"); mPermissions.get(cAccounts).add("USE_CREDENTIALS"); mPermissions.get(cAccounts).add("MANAGE_ACCOUNTS"); mPermissions.get(cBoot).add("RECEIVE_BOOT_COMPLETED"); mPermissions.get(cBrowser).add("READ_HISTORY_BOOKMARKS"); mPermissions.get(cBrowser).add("GLOBAL_SEARCH"); mPermissions.get(cCalendar).add("READ_CALENDAR"); mPermissions.get(cCalling).add("SEND_SMS"); mPermissions.get(cCalling).add("CALL_PHONE"); mPermissions.get(cContacts).add("READ_CONTACTS"); mPermissions.get(cDictionary).add("READ_USER_DICTIONARY"); mPermissions.get(cInternet).add("INTERNET"); mPermissions.get(cLocation).add("ACCESS_COARSE_LOCATION"); mPermissions.get(cLocation).add("ACCESS_FINE_LOCATION"); mPermissions.get(cLocation).add("ACCESS_COARSE_UPDATES"); mPermissions.get(cLocation).add("CONTROL_LOCATION_UPDATES"); mPermissions.get(cMedia).add("CAMERA"); mPermissions.get(cMedia).add("RECORD_AUDIO"); mPermissions.get(cMedia).add("RECORD_VIDEO"); mPermissions.get(cMessages).add("READ_WRITE_ALL_VOICEMAIL"); mPermissions.get(cMessages).add("READ_SMS"); mPermissions.get(cMessages).add("RECEIVE_SMS"); mPermissions.get(cNetwork).add("ACCESS_NETWORK_STATE"); mPermissions.get(cNetwork).add("ACCESS_WIFI_STATE"); mPermissions.get(cNetwork).add("BLUETOOTH"); mPermissions.get(cNfc).add("NFC"); mPermissions.get(cPhone).add("READ_PHONE_STATE"); mPermissions.get(cPhone).add("PROCESS_OUTGOING_CALLS"); mPermissions.get(cPhone).add("READ_CALL_LOG"); mPermissions.get(cPhone).add("WRITE_APN_SETTINGS"); mPermissions.get(cStorage).add("READ_EXTERNAL_STORAGE"); mPermissions.get(cStorage).add("WRITE_EXTERNAL_STORAGE"); mPermissions.get(cStorage).add("WRITE_MEDIA_STORAGE"); // Methods // Account manager String[] accs = new String[] { "addOnAccountsUpdatedListener", "blockingGetAuthToken", "getAccounts", "getAccountsByType", "getAccountsByTypeAndFeatures", "getAuthToken", "getAuthTokenByFeatures", "hasFeatures", "removeOnAccountsUpdatedListener" }; for (String acc : accs) mMethods.get(cAccounts).add(acc); // Application package manager String[] ams = new String[] { "getInstalledApplications", "getInstalledPackages", "getInstalledThemePackages", "getPreferredPackages" }; for (String am : ams) mMethods.get(cSystem).add(am); // Audio record mMethods.get(PrivacyManager.cMedia).add("startRecording"); // Bluetooth adapter mMethods.get(PrivacyManager.cNetwork).add("getAddress"); mMethods.get(PrivacyManager.cNetwork).add("getBondedDevices"); // Camera String[] cams = new String[] { "setPreviewCallback", "setPreviewCallbackWithBuffer", "setOneShotPreviewCallback", "takePicture" }; for (String cam : cams) mMethods.get(cMedia).add(cam); // Identification mMethods.get(PrivacyManager.cIdentification).add("SERIAL"); // Location manager String[] locs = new String[] { "addNmeaListener", "addProximityAlert", "getLastKnownLocation", "removeUpdates", "requestLocationUpdates", "requestSingleUpdate", "sendExtraCommand" }; for (String loc : locs) mMethods.get(cLocation).add(loc); // Media recorder mMethods.get(cMedia).add("setOutputFile"); // Network interface String[] nets = new String[] { "getHardwareAddress", "getInetAddresses", "getInterfaceAddresses" }; for (String net : nets) mMethods.get(cNetwork).add(net); // Package manager service mMethods.get(cInternet).add("getPackageGids"); mMethods.get(cStorage).add("getPackageGids"); // Runtime mMethods.get(cShell).add("sh"); mMethods.get(cShell).add("su"); mMethods.get(cShell).add("exec"); mMethods.get(cShell).add("load"); mMethods.get(cShell).add("loadLibrary"); mMethods.get(cShell).add("start"); // Settings secure mMethods.get(cIdentification).add("getString"); // SMS manager mMethods.get(cMessages).add("getAllMessagesFromIcc"); String[] smses = new String[] { "sendDataMessage", "sendMultipartTextMessage", "sendTextMessage" }; for (String sms : smses) mMethods.get(cCalling).add(sms); // System properties String[] props = new String[] { "ro.gsm.imei", "net.hostname", "ro.serialno", "ro.boot.serialno", "ro.boot.wifimacaddr", "ro.boot.btmacaddr" }; for (String prop : props) mMethods.get(cIdentification).add(prop); // Telephony String[] tlocs = new String[] { "disableLocationUpdates", "enableLocationUpdates", "getAllCellInfo", "getCellLocation", "getNeighboringCellInfo" }; for (String tloc : tlocs) mMethods.get(cLocation).add(tloc); String[] phones = new String[] { "getDeviceId", "getIsimDomain", "getIsimImpi", "getIsimImpu", "getLine1AlphaTag", "getLine1Number", "getMsisdn", "getNetworkCountryIso", "getNetworkOperator", "getNetworkOperatorName", "getSimCountryIso", "getSimOperator", "getSimOperatorName", "getSimSerialNumber", "getSubscriberId", "getVoiceMailAlphaTag", "getVoiceMailNumber", "listen" }; for (String phone : phones) mMethods.get(cPhone).add(phone); // Wi-Fi manager String[] wifis = new String[] { "getConfiguredNetworks", "getConnectionInfo", "getDhcpInfo", "getScanResults" }; for (String wifi : wifis) mMethods.get(cNetwork).add(wifi); // Intent receive: boot mMethods.get(cBoot).add(Intent.ACTION_BOOT_COMPLETED); if (PrivacyManager.cExperimental) mMethods.get(cBoot).add("installContentProviders"); // Intent receive: calling mMethods.get(cPhone).add(Intent.ACTION_NEW_OUTGOING_CALL); mMethods.get(cPhone).add(TelephonyManager.ACTION_PHONE_STATE_CHANGED); // Intent receive: NFC mMethods.get(cNfc).add(NfcAdapter.ACTION_NDEF_DISCOVERED); mMethods.get(cNfc).add(NfcAdapter.ACTION_TAG_DISCOVERED); mMethods.get(cNfc).add(NfcAdapter.ACTION_TECH_DISCOVERED); // Intent send: browser mMethods.get(cView).add(Intent.ACTION_VIEW); // Intent send: call mMethods.get(cCalling).add(Intent.ACTION_CALL); // Intent send: media mMethods.get(cMedia).add(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT >= 17) mMethods.get(cMedia).add("android.media.action.IMAGE_CAPTURE_SECURE"); mMethods.get(cMedia).add(MediaStore.ACTION_VIDEO_CAPTURE); // Content providers mMethods.get(cBrowser).add("BrowserProvider"); mMethods.get(cBrowser).add("BrowserProvider2"); mMethods.get(cCalendar).add("CalendarProvider2"); mMethods.get(cContacts).add("ContactsProvider2"); mMethods.get(cDictionary).add("UserDictionary"); mMethods.get(cPhone).add("CallLogProvider"); mMethods.get(cMessages).add("VoicemailContentProvider"); mMethods.get(cMessages).add("SmsProvider"); mMethods.get(cMessages).add("MmsProvider"); mMethods.get(cMessages).add("MmsSmsProvider"); mMethods.get(cPhone).add("TelephonyProvider"); } // Data public static void registerMethod(String methodName, String restrictionName, String[] permissions) { if (restrictionName != null && !mPermissions.containsKey(restrictionName)) Util.log(null, Log.WARN, "Missing restriction " + restrictionName); for (String permission : permissions) if (!mPermissions.get(restrictionName).contains(permission)) Util.log(null, Log.WARN, "Missing permission " + permission); if (!mMethods.containsKey(restrictionName) || !mMethods.get(restrictionName).contains(methodName)) Util.log(null, Log.WARN, "Missing method " + methodName); } public static List<String> getRestrictions() { List<String> listRestriction = new ArrayList<String>(Arrays.asList(cRestrictionNames)); if (!Boolean.parseBoolean(PrivacyManager.getSetting(null, null, PrivacyManager.cSettingExpert, Boolean.FALSE.toString(), false))) { listRestriction.remove(cBoot); listRestriction.remove(cShell); } return listRestriction; } public static List<String> getMethodNames(String restrictionName) { return mMethods.get(restrictionName); } public static List<String> getPermissions(String restrictionName) { return mPermissions.get(restrictionName); } public static List<String> getMethods(String restrictionName) { return mMethods.get(restrictionName); } public static String getLocalizedName(Context context, String restrictionName) { String packageName = PrivacyManager.class.getPackage().getName(); int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string", packageName); return (stringId == 0 ? null : context.getString(stringId)); } // Restrictions @SuppressLint("DefaultLocale") public static boolean getRestricted(XHook hook, Context context, int uid, String restrictionName, String methodName, boolean usage, boolean useCache) { try { long start = System.currentTimeMillis(); // Check uid if (uid <= 0) { Util.log(hook, Log.WARN, "uid <= 0"); Util.logStack(hook); return false; } // Check restriction if (restrictionName == null || restrictionName.equals("")) { Util.log(hook, Log.WARN, "restriction empty"); Util.logStack(hook); return false; } - if (methodName == null || methodName.equals("")) { - Util.log(hook, Log.WARN, "method empty"); - Util.logStack(hook); - } + if (usage) + if (methodName == null || methodName.equals("")) { + Util.log(hook, Log.WARN, "method empty"); + Util.logStack(hook); + } // Check cache String keyCache = String.format("%d.%s.%s", uid, restrictionName, methodName); if (useCache) synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) { CRestriction entry = mRestrictionCache.get(keyCache); if (entry.isExpired()) mRestrictionCache.remove(keyCache); else { long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, entry.isRestricted(), true, delta); return entry.isRestricted(); } } } // Check if restricted boolean fallback = true; boolean restricted = false; if (context != null && uid != PrivacyManager.cUidAndroid) try { // Get content resolver ContentResolver contentResolver = context.getContentResolver(); if (contentResolver == null) { Util.log(hook, Log.WARN, "contentResolver is null"); Util.logStack(hook); } else { // Query restriction Cursor cursor = contentResolver.query(PrivacyProvider.URI_RESTRICTION, null, restrictionName, new String[] { Integer.toString(uid), Boolean.toString(usage), methodName }, null); if (cursor == null) { // Can happen if memory low Util.log(hook, Log.WARN, "cursor is null"); Util.logStack(null); } else { // Get restriction if (cursor.moveToNext()) { restricted = Boolean.parseBoolean(cursor.getString(cursor .getColumnIndex(PrivacyProvider.COL_RESTRICTED))); fallback = false; } else { Util.log(hook, Log.WARN, "cursor is empty"); Util.logStack(null); } cursor.close(); } // Send usage data UsageData data = null; do { int size = 0; synchronized (mUsageQueue) { if (mUsageQueue.size() > 0) { data = mUsageQueue.keySet().iterator().next(); mUsageQueue.remove(data); size = mUsageQueue.size(); } else data = null; } if (data != null) { try { Util.log(hook, Log.INFO, "Sending usage data=" + data + " size=" + size); ContentValues values = new ContentValues(); values.put(PrivacyProvider.COL_UID, data.getUid()); values.put(PrivacyProvider.COL_RESTRICTION, data.getRestrictionName()); values.put(PrivacyProvider.COL_METHOD, data.getMethodName()); values.put(PrivacyProvider.COL_USED, data.getTimeStamp()); if (contentResolver.update(PrivacyProvider.URI_USAGE, values, null, null) <= 0) Util.log(hook, Log.INFO, "Error updating usage data=" + data); } catch (Throwable ex) { Util.bug(hook, ex); } } } while (data != null); } } catch (Throwable ex) { Util.bug(hook, ex); } // Use fallback if (fallback) { // Queue usage data if (usage && uid != PrivacyManager.cUidAndroid) { UsageData usageData = new UsageData(uid, restrictionName, methodName); synchronized (mUsageQueue) { if (mUsageQueue.containsKey(usageData)) mUsageQueue.remove(usageData); mUsageQueue.put(usageData, usageData); Util.log(hook, Log.INFO, "Queue usage data=" + usageData + " size=" + mUsageQueue.size()); } } // Fallback restricted = PrivacyProvider.getRestrictedFallback(hook, uid, restrictionName, methodName); } // Add to cache synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) mRestrictionCache.remove(keyCache); mRestrictionCache.put(keyCache, new CRestriction(restricted)); } // Result long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, restricted, false, delta); return restricted; } catch (Throwable ex) { // Failsafe Util.bug(hook, ex); return false; } } public static void setRestricted(XHook hook, Context context, int uid, String restrictionName, String methodName, boolean restricted) { // Check context if (context == null) { Util.log(hook, Log.WARN, "context is null"); return; } // Check uid if (uid == 0) { Util.log(hook, Log.WARN, "uid=0"); return; } // Get content resolver ContentResolver contentResolver = context.getContentResolver(); if (contentResolver == null) { Util.log(hook, Log.WARN, "contentResolver is null"); return; } // Set restrictions ContentValues values = new ContentValues(); values.put(PrivacyProvider.COL_UID, uid); values.put(PrivacyProvider.COL_METHOD, methodName); values.put(PrivacyProvider.COL_RESTRICTED, Boolean.toString(restricted)); if (contentResolver.update(PrivacyProvider.URI_RESTRICTION, values, restrictionName, null) <= 0) Util.log(hook, Log.INFO, "Error updating restriction=" + restrictionName); // Result logRestriction(hook, context, uid, "set", restrictionName, methodName, restricted, false, 0); } public static class RestrictionDesc { public int uid; public boolean restricted; public String restrictionName; public String methodName; } public static List<RestrictionDesc> getRestrictions(Context context) { List<RestrictionDesc> result = new ArrayList<RestrictionDesc>(); Cursor rCursor = context.getContentResolver().query(PrivacyProvider.URI_RESTRICTION, null, null, new String[] { Integer.toString(0), Boolean.toString(false) }, null); while (rCursor.moveToNext()) { RestrictionDesc restriction = new RestrictionDesc(); restriction.uid = rCursor.getInt(rCursor.getColumnIndex(PrivacyProvider.COL_UID)); restriction.restricted = Boolean.parseBoolean(rCursor.getString(rCursor .getColumnIndex(PrivacyProvider.COL_RESTRICTED))); restriction.restrictionName = rCursor.getString(rCursor.getColumnIndex(PrivacyProvider.COL_RESTRICTION)); restriction.methodName = rCursor.getString(rCursor.getColumnIndex(PrivacyProvider.COL_METHOD)); result.add(restriction); } rCursor.close(); return result; } public static void deleteRestrictions(Context context, int uid) { context.getContentResolver().delete(PrivacyProvider.URI_RESTRICTION, null, new String[] { Integer.toString(uid) }); Util.log(null, Log.INFO, "Delete restrictions uid=" + uid); } // Usage public static boolean isUsed(Context context, int uid, String restrictionName, String methodName) { return (getUsed(context, uid, restrictionName, methodName) != 0); } public static long getUsed(Context context, int uid, String restrictionName, String methodName) { long lastUsage = 0; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(PrivacyProvider.URI_USAGE, null, restrictionName, new String[] { Integer.toString(uid), methodName }, null); if (cursor.moveToNext()) lastUsage = cursor.getLong(cursor.getColumnIndex(PrivacyProvider.COL_USED)); cursor.close(); boolean used = (lastUsage != 0); logRestriction(null, context, uid, "used", restrictionName, methodName, used, false, 0); return lastUsage; } public static void deleteUsageData(Context context, int uid) { for (String restrictionName : PrivacyManager.getRestrictions()) context.getContentResolver().delete(PrivacyProvider.URI_USAGE, restrictionName, new String[] { Integer.toString(uid) }); Util.log(null, Log.INFO, "Delete usage uid=" + uid); } // Settings public static String getSetting(XHook hook, Context context, String settingName, String defaultValue, boolean useCache) { // Check cache if (useCache) synchronized (mSettingsCache) { if (mSettingsCache.containsKey(settingName)) { CSetting entry = mSettingsCache.get(settingName); if (entry.isExpired()) mSettingsCache.remove(settingName); else { String value = mSettingsCache.get(settingName).getSettingsValue(); Util.log(hook, Log.INFO, String.format("get setting %s=%s *", settingName, value)); return value; } } } // Get setting boolean fallback = true; String value = defaultValue; if (context != null) { try { ContentResolver contentResolver = context.getContentResolver(); if (contentResolver == null) { Util.log(hook, Log.WARN, "contentResolver is null"); Util.logStack(hook); } else { Cursor cursor = contentResolver.query(PrivacyProvider.URI_SETTING, null, settingName, null, null); if (cursor == null) { // Can happen if memory low Util.log(hook, Log.WARN, "cursor is null"); Util.logStack(null); } else { if (cursor.moveToNext()) { value = cursor.getString(cursor.getColumnIndex(PrivacyProvider.COL_VALUE)); if (value == null) value = defaultValue; fallback = false; } else { Util.log(hook, Log.WARN, "cursor is empty"); } cursor.close(); } } } catch (Throwable ex) { Util.bug(hook, ex); Util.logStack(hook); } } // Use fallback if (fallback) value = PrivacyProvider.getSettingFallback(settingName, defaultValue); // Add to cache synchronized (mSettingsCache) { if (mSettingsCache.containsKey(settingName)) mSettingsCache.remove(settingName); mSettingsCache.put(settingName, new CSetting(value)); } Util.log(hook, Log.INFO, String.format("get setting %s=%s%s", settingName, value, (fallback ? " #" : ""))); return value; } public static void setSetting(XHook hook, Context context, String settingName, String value) { ContentResolver contentResolver = context.getContentResolver(); ContentValues values = new ContentValues(); values.put(PrivacyProvider.COL_VALUE, value); if (contentResolver.update(PrivacyProvider.URI_SETTING, values, settingName, null) <= 0) Util.log(hook, Log.INFO, "Error updating setting=" + settingName); Util.log(hook, Log.INFO, String.format("set setting %s=%s", settingName, value)); } public static Map<String, String> getSettings(Context context) { Map<String, String> result = new HashMap<String, String>(); Cursor sCursor = context.getContentResolver().query(PrivacyProvider.URI_SETTING, null, null, null, null); while (sCursor.moveToNext()) { // Get setting String setting = sCursor.getString(sCursor.getColumnIndex(PrivacyProvider.COL_SETTING)); String value = sCursor.getString(sCursor.getColumnIndex(PrivacyProvider.COL_VALUE)); result.put(setting, value); } sCursor.close(); return result; } // Defacing public static String getDefacedProp(String name) { // Serial number if (name.equals("SERIAL") || name.equals("ro.serialno") || name.equals("ro.boot.serialno")) return cDeface; // MAC addresses if (name.equals("MAC") || name.equals("ro.boot.btmacaddr") || name.equals("ro.boot.wifimacaddr")) return getSetting(null, null, cSettingMac, "de:fa:ce:de:fa:ce", true); // IMEI if (name.equals("getDeviceId") || name.equals("ro.gsm.imei")) return getSetting(null, null, cSettingImei, cDeface, true); // Phone if (name.equals("PhoneNumber") || name.equals("getLine1AlphaTag") || name.equals("getLine1Number") || name.equals("getVoiceMailAlphaTag") || name.equals("getVoiceMailNumber")) return getSetting(null, null, cSettingPhone, cDeface, true); // Android ID if (name.equals("ANDROID_ID")) return getSetting(null, null, cSettingId, cDeface, true); // XSystemProperties: "net.hostname" // XTelephonyManager: // - public String getIsimDomain() // - public String getIsimImpi() // - public String[] getIsimImpu() // - public String getMsisdn() // - public String getNetworkCountryIso() // - public String getNetworkOperator() // - public String getNetworkOperatorName() // - public String getSimCountryIso() // - public String getSimOperator() // - public String getSimOperatorName() // - public String getSimSerialNumber() // - public String getSubscriberId() // XWifiManager: SSID return cDeface; } public static InetAddress getDefacedInetAddress() { try { Field unspecified = Inet4Address.class.getDeclaredField("ALL"); unspecified.setAccessible(true); return (InetAddress) unspecified.get(Inet4Address.class); } catch (Throwable ex) { Util.bug(null, ex); return null; } } public static int getDefacedIPInt() { return 127 + (0 << 8) + (0 << 16) + (1 << 24); } public static byte[] getDefacedIPBytes() { return new byte[] { 10, 1, 1, 1 }; } public static byte[] getDefacedBytes() { return new byte[] { (byte) 0xDE, (byte) 0xFA, (byte) 0xCE }; } public static Location getDefacedLocation(Location location) { String sLat = getSetting(null, null, PrivacyManager.cSettingLatitude, "", true); String sLon = getSetting(null, null, PrivacyManager.cSettingLongitude, "", true); if (sLat.equals("") || sLon.equals("")) { // Christmas Island location.setLatitude(-10.5); location.setLongitude(105.667); } else { // 1 degree ~ 111111 m // 1 m ~ 0,000009 degrees = 9e-6 location.setLatitude(Float.parseFloat(sLat) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6); location.setLongitude(Float.parseFloat(sLon) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6); } return location; } // Helper methods private static void logRestriction(XHook hook, Context context, int uid, String prefix, String restrictionName, String methodName, boolean restricted, boolean cached, long ms) { Util.log(hook, Log.INFO, String.format("%s %s/%s %s=%b%s%s", prefix, getPackageName(context, uid), methodName, restrictionName, restricted, (cached ? " *" : (context == null ? " #" : "")), (ms > 1 ? " " + ms + " ms" : ""))); } private static String getPackageName(Context context, int uid) { if (context != null) { String[] packages = context.getPackageManager().getPackagesForUid(uid); if (packages != null && packages.length == 1) return packages[0]; } return Integer.toString(uid); } public static boolean hasInternet(Context context, String packageName) { // TODO: check if internet permission restricted PackageManager pm = context.getPackageManager(); return (pm.checkPermission("android.permission.INTERNET", packageName) == PackageManager.PERMISSION_GRANTED); } @SuppressLint("DefaultLocale") public static boolean hasPermission(Context context, String packageName, String restrictionName) { List<String> listPermission = mPermissions.get(restrictionName); if (listPermission == null || listPermission.size() == 0) return true; try { PackageManager pm = context.getPackageManager(); PackageInfo pInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); if (pInfo != null && pInfo.requestedPermissions != null) for (String rPermission : pInfo.requestedPermissions) for (String permission : listPermission) if (rPermission.toLowerCase().contains(permission.toLowerCase())) return true; } catch (Throwable ex) { Util.bug(null, ex); return false; } return false; } // Helper classes private static class CRestriction { private long mTimestamp; private boolean mRestricted; public CRestriction(boolean restricted) { mTimestamp = new Date().getTime(); mRestricted = restricted; } public boolean isExpired() { return (mTimestamp + cCacheTimeoutMs < new Date().getTime()); } public boolean isRestricted() { return mRestricted; } } private static class CSetting { private long mTimestamp; private String mValue; public CSetting(String settingValue) { mTimestamp = new Date().getTime(); mValue = settingValue; } public boolean isExpired() { return (mTimestamp + cCacheTimeoutMs < new Date().getTime()); } public String getSettingsValue() { return mValue; } } private static class UsageData { private Integer mUid; private String mRestriction; private String mMethodName; private long mTimeStamp; private int mHash; public UsageData(int uid, String restrictionName, String methodName) { mUid = uid; mRestriction = restrictionName; mMethodName = methodName; mTimeStamp = new Date().getTime(); mHash = mUid.hashCode(); if (mRestriction != null) mHash = mHash ^ mRestriction.hashCode(); if (mMethodName != null) mHash = mHash ^ mMethodName.hashCode(); } public int getUid() { return mUid; } public String getRestrictionName() { return mRestriction; } public String getMethodName() { return mMethodName; } public long getTimeStamp() { return mTimeStamp; } @Override public int hashCode() { return mHash; } @Override public boolean equals(Object obj) { UsageData other = (UsageData) obj; // @formatter:off return (mUid.equals(other.mUid) && (mRestriction == null ? other.mRestriction == null : mRestriction.equals(other.mRestriction)) && (mMethodName == null ? other.mMethodName == null : mMethodName.equals(other.mMethodName))); // @formatter:on } @Override @SuppressLint("DefaultLocale") public String toString() { return String.format("%d/%s/%s", mUid, mRestriction, mMethodName); } } }
true
true
public static boolean getRestricted(XHook hook, Context context, int uid, String restrictionName, String methodName, boolean usage, boolean useCache) { try { long start = System.currentTimeMillis(); // Check uid if (uid <= 0) { Util.log(hook, Log.WARN, "uid <= 0"); Util.logStack(hook); return false; } // Check restriction if (restrictionName == null || restrictionName.equals("")) { Util.log(hook, Log.WARN, "restriction empty"); Util.logStack(hook); return false; } if (methodName == null || methodName.equals("")) { Util.log(hook, Log.WARN, "method empty"); Util.logStack(hook); } // Check cache String keyCache = String.format("%d.%s.%s", uid, restrictionName, methodName); if (useCache) synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) { CRestriction entry = mRestrictionCache.get(keyCache); if (entry.isExpired()) mRestrictionCache.remove(keyCache); else { long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, entry.isRestricted(), true, delta); return entry.isRestricted(); } } } // Check if restricted boolean fallback = true; boolean restricted = false; if (context != null && uid != PrivacyManager.cUidAndroid) try { // Get content resolver ContentResolver contentResolver = context.getContentResolver(); if (contentResolver == null) { Util.log(hook, Log.WARN, "contentResolver is null"); Util.logStack(hook); } else { // Query restriction Cursor cursor = contentResolver.query(PrivacyProvider.URI_RESTRICTION, null, restrictionName, new String[] { Integer.toString(uid), Boolean.toString(usage), methodName }, null); if (cursor == null) { // Can happen if memory low Util.log(hook, Log.WARN, "cursor is null"); Util.logStack(null); } else { // Get restriction if (cursor.moveToNext()) { restricted = Boolean.parseBoolean(cursor.getString(cursor .getColumnIndex(PrivacyProvider.COL_RESTRICTED))); fallback = false; } else { Util.log(hook, Log.WARN, "cursor is empty"); Util.logStack(null); } cursor.close(); } // Send usage data UsageData data = null; do { int size = 0; synchronized (mUsageQueue) { if (mUsageQueue.size() > 0) { data = mUsageQueue.keySet().iterator().next(); mUsageQueue.remove(data); size = mUsageQueue.size(); } else data = null; } if (data != null) { try { Util.log(hook, Log.INFO, "Sending usage data=" + data + " size=" + size); ContentValues values = new ContentValues(); values.put(PrivacyProvider.COL_UID, data.getUid()); values.put(PrivacyProvider.COL_RESTRICTION, data.getRestrictionName()); values.put(PrivacyProvider.COL_METHOD, data.getMethodName()); values.put(PrivacyProvider.COL_USED, data.getTimeStamp()); if (contentResolver.update(PrivacyProvider.URI_USAGE, values, null, null) <= 0) Util.log(hook, Log.INFO, "Error updating usage data=" + data); } catch (Throwable ex) { Util.bug(hook, ex); } } } while (data != null); } } catch (Throwable ex) { Util.bug(hook, ex); } // Use fallback if (fallback) { // Queue usage data if (usage && uid != PrivacyManager.cUidAndroid) { UsageData usageData = new UsageData(uid, restrictionName, methodName); synchronized (mUsageQueue) { if (mUsageQueue.containsKey(usageData)) mUsageQueue.remove(usageData); mUsageQueue.put(usageData, usageData); Util.log(hook, Log.INFO, "Queue usage data=" + usageData + " size=" + mUsageQueue.size()); } } // Fallback restricted = PrivacyProvider.getRestrictedFallback(hook, uid, restrictionName, methodName); } // Add to cache synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) mRestrictionCache.remove(keyCache); mRestrictionCache.put(keyCache, new CRestriction(restricted)); } // Result long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, restricted, false, delta); return restricted; } catch (Throwable ex) { // Failsafe Util.bug(hook, ex); return false; } }
public static boolean getRestricted(XHook hook, Context context, int uid, String restrictionName, String methodName, boolean usage, boolean useCache) { try { long start = System.currentTimeMillis(); // Check uid if (uid <= 0) { Util.log(hook, Log.WARN, "uid <= 0"); Util.logStack(hook); return false; } // Check restriction if (restrictionName == null || restrictionName.equals("")) { Util.log(hook, Log.WARN, "restriction empty"); Util.logStack(hook); return false; } if (usage) if (methodName == null || methodName.equals("")) { Util.log(hook, Log.WARN, "method empty"); Util.logStack(hook); } // Check cache String keyCache = String.format("%d.%s.%s", uid, restrictionName, methodName); if (useCache) synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) { CRestriction entry = mRestrictionCache.get(keyCache); if (entry.isExpired()) mRestrictionCache.remove(keyCache); else { long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, entry.isRestricted(), true, delta); return entry.isRestricted(); } } } // Check if restricted boolean fallback = true; boolean restricted = false; if (context != null && uid != PrivacyManager.cUidAndroid) try { // Get content resolver ContentResolver contentResolver = context.getContentResolver(); if (contentResolver == null) { Util.log(hook, Log.WARN, "contentResolver is null"); Util.logStack(hook); } else { // Query restriction Cursor cursor = contentResolver.query(PrivacyProvider.URI_RESTRICTION, null, restrictionName, new String[] { Integer.toString(uid), Boolean.toString(usage), methodName }, null); if (cursor == null) { // Can happen if memory low Util.log(hook, Log.WARN, "cursor is null"); Util.logStack(null); } else { // Get restriction if (cursor.moveToNext()) { restricted = Boolean.parseBoolean(cursor.getString(cursor .getColumnIndex(PrivacyProvider.COL_RESTRICTED))); fallback = false; } else { Util.log(hook, Log.WARN, "cursor is empty"); Util.logStack(null); } cursor.close(); } // Send usage data UsageData data = null; do { int size = 0; synchronized (mUsageQueue) { if (mUsageQueue.size() > 0) { data = mUsageQueue.keySet().iterator().next(); mUsageQueue.remove(data); size = mUsageQueue.size(); } else data = null; } if (data != null) { try { Util.log(hook, Log.INFO, "Sending usage data=" + data + " size=" + size); ContentValues values = new ContentValues(); values.put(PrivacyProvider.COL_UID, data.getUid()); values.put(PrivacyProvider.COL_RESTRICTION, data.getRestrictionName()); values.put(PrivacyProvider.COL_METHOD, data.getMethodName()); values.put(PrivacyProvider.COL_USED, data.getTimeStamp()); if (contentResolver.update(PrivacyProvider.URI_USAGE, values, null, null) <= 0) Util.log(hook, Log.INFO, "Error updating usage data=" + data); } catch (Throwable ex) { Util.bug(hook, ex); } } } while (data != null); } } catch (Throwable ex) { Util.bug(hook, ex); } // Use fallback if (fallback) { // Queue usage data if (usage && uid != PrivacyManager.cUidAndroid) { UsageData usageData = new UsageData(uid, restrictionName, methodName); synchronized (mUsageQueue) { if (mUsageQueue.containsKey(usageData)) mUsageQueue.remove(usageData); mUsageQueue.put(usageData, usageData); Util.log(hook, Log.INFO, "Queue usage data=" + usageData + " size=" + mUsageQueue.size()); } } // Fallback restricted = PrivacyProvider.getRestrictedFallback(hook, uid, restrictionName, methodName); } // Add to cache synchronized (mRestrictionCache) { if (mRestrictionCache.containsKey(keyCache)) mRestrictionCache.remove(keyCache); mRestrictionCache.put(keyCache, new CRestriction(restricted)); } // Result long delta = System.currentTimeMillis() - start; logRestriction(hook, context, uid, "get", restrictionName, methodName, restricted, false, delta); return restricted; } catch (Throwable ex) { // Failsafe Util.bug(hook, ex); return false; } }
diff --git a/util/src/main/java/com/psddev/dari/util/CodeUtils.java b/util/src/main/java/com/psddev/dari/util/CodeUtils.java index dafe8202..ce92b63a 100644 --- a/util/src/main/java/com/psddev/dari/util/CodeUtils.java +++ b/util/src/main/java/com/psddev/dari/util/CodeUtils.java @@ -1,817 +1,813 @@ package com.psddev.dari.util; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.lang.instrument.ClassDefinition; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletContext; import javax.tools.DiagnosticCollector; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileManager; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardLocation; import javax.tools.ToolProvider; import org.objectweb.asm.ClassAdapter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CodeUtils { public static final String JAVA_SOURCE_DIRECTORY_PROPERTY = "javaSourceDirectory"; public static final String RESOURCE_DIRECTORY_PROPERTY = "resourceDirectory"; private static final String BUILD_PROPERTIES_PATH = "build.properties"; private static final JavaCompiler COMPILER = ToolProvider.getSystemJavaCompiler(); private static final Logger LOGGER = LoggerFactory.getLogger(CodeUtils.class); private static final URI DEFAULT_URI; static { try { DEFAULT_URI = new URI("mem:/"); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); } } private static final String ATTRIBUTE_PREFIX = CodeUtils.class.getName() + "."; private static final String WEBAPP_SOURCE_DIRECTORIES_ATTRIBUTE = ATTRIBUTE_PREFIX + "webappSourceDirectories"; private static final Set<File> SOURCE_DIRECTORIES; private static final Set<File> RESOURCE_DIRECTORIES; private static final Map<File, Long> JAR_LAST_MODIFIED_MAP; // Scan all build property files to find source directories. static { Set<File> sources = new HashSet<File>(); Set<File> resources = new HashSet<File>(); Map<File, Long> jars = new HashMap<File, Long>(); try { for (Enumeration<URL> i = ObjectUtils.getCurrentClassLoader().getResources(BUILD_PROPERTIES_PATH); i.hasMoreElements(); ) { try { URLConnection buildConnection = i.nextElement().openConnection(); InputStream buildInput = buildConnection.getInputStream(); try { Properties build = new Properties(); build.load(buildInput); Set<File> directories = new HashSet<File>(); String sourceString = build.getProperty(JAVA_SOURCE_DIRECTORY_PROPERTY); if (sourceString != null) { File source = new File(sourceString); if (source.exists()) { sources.add(source); directories.add(source); } } String resourceString = build.getProperty(RESOURCE_DIRECTORY_PROPERTY); if (resourceString != null) { File resource = new File(resourceString); if (resource.exists()) { resources.add(resource); directories.add(resource); } } if (buildConnection instanceof JarURLConnection) { URL jarUrl = ((JarURLConnection) buildConnection).getJarFileURL(); URLConnection jarConnection = jarUrl.openConnection(); InputStream jarInput = jarConnection.getInputStream(); try { long lastModified = jarConnection.getLastModified(); for (File directory : directories) { LOGGER.info("Found sources in [{}] originally packaged in [{}]", directory, jarUrl); jars.put(directory, lastModified); } } finally { jarInput.close(); } } } finally { buildInput.close(); } } catch (IOException ex) { } } } catch (IOException ex) { } SOURCE_DIRECTORIES = Collections.unmodifiableSet(sources); RESOURCE_DIRECTORIES = Collections.unmodifiableSet(resources); JAR_LAST_MODIFIED_MAP = Collections.unmodifiableMap(jars); } public static Set<File> getSourceDirectories() { return SOURCE_DIRECTORIES; } public static Set<File> getResourceDirectories() { return RESOURCE_DIRECTORIES; } public static Long getJarLastModified(File directory) { return JAR_LAST_MODIFIED_MAP.get(directory); } /** * Returns an immuntable map of all web application source directories * keyed by their context paths. */ public static Map<String, File> getWebappSourceDirectories(ServletContext context) { @SuppressWarnings("unchecked") Map<String, File> sourceDirectories = (Map<String, File>) context.getAttribute(WEBAPP_SOURCE_DIRECTORIES_ATTRIBUTE); if (sourceDirectories != null) { return sourceDirectories; } Map<String, File> unsorted = new HashMap<String, File>(); try { addWebappSourceDirectories(context, unsorted, "/"); } catch (IOException error) { return Collections.emptyMap(); } List<String> prefixes = new ArrayList<String>(unsorted.keySet()); Collections.sort(prefixes); Collections.reverse(prefixes); sourceDirectories = new LinkedHashMap<String, File>(); for (String prefix : prefixes) { sourceDirectories.put(prefix, unsorted.get(prefix)); } sourceDirectories = Collections.unmodifiableMap(sourceDirectories); context.setAttribute(WEBAPP_SOURCE_DIRECTORIES_ATTRIBUTE, sourceDirectories); return sourceDirectories; } private static void addWebappSourceDirectories(ServletContext context, Map<String, File> sourceDirectories, String path) throws IOException { @SuppressWarnings("unchecked") Set<String> children = (Set<String>) context.getResourcePaths(path); if (children != null) { for (String child : children) { if (child.endsWith("/build.properties")) { int webInfAt = child.indexOf("/WEB-INF/"); if (webInfAt > -1) { InputStream buildInput = context.getResourceAsStream(child); Properties buildProperties = new Properties(); try { buildProperties.load(buildInput); } finally { buildInput.close(); } File sourceDirectory = ObjectUtils.to(File.class, buildProperties.get(SourceFilter.WEBAPP_SOURCES_PROPERTY)); if (sourceDirectory.exists()) { sourceDirectories.put( StringUtils.ensureEnd(child.substring(0, webInfAt), "/"), sourceDirectory); } } } else if (child.endsWith("/")) { addWebappSourceDirectories(context, sourceDirectories, child); } } } } /** * Returns the original source file associated with the given {@code path} * in the given {@code context}. */ public static File getWebappSource(ServletContext context, String path) { for (Map.Entry<String, File> entry : getWebappSourceDirectories(context).entrySet()) { String prefix = entry.getKey(); if (path.startsWith(prefix)) { return new File(entry.getValue(), path.substring(prefix.length())); } } return null; } /** * Returns all original source paths that begin with the given {@code path} * in the same format as {@link ServletContext#getResourcePaths}. */ @SuppressWarnings("unchecked") public static Set<String> getResourcePaths(ServletContext context, String path) { File source = getWebappSource(context, path); if (source != null && source.exists()) { Set<String> paths = new LinkedHashSet<String>(); String[] children = source.list(); if (children != null) { for (String child : children) { String childPath = path + child; if (new File(source, child).isDirectory()) { childPath += "/"; } paths.add(childPath); } } return paths; } else { return (Set<String>) context.getResourcePaths(path); } } /** * Returns the original source as a URL associated with the given * {@code path} in the given {@code context}. */ public static URL getResource(ServletContext context, String path) throws MalformedURLException { File source = getWebappSource(context, path); return source != null ? source.toURI().toURL() : context.getResource(path); } /** * Returns the original source as an input stream associated with the * given {@code path} in the given {@code context}. */ public static InputStream getResourceAsStream(ServletContext context, String path) { File source = getWebappSource(context, path); if (source != null) { try { return new FileInputStream(source); } catch (FileNotFoundException error) { } } return context.getResourceAsStream(path); } /** * Returns the source file associated with the given * {@code className}. * * @return May be {@code null} if there's no such file or if * the source directory information isn't available. */ public static File getSource(String className) { int dollarAt = className.indexOf('$'); if (dollarAt > -1) { className = className.substring(0, dollarAt); } className = className.replace('.', File.separatorChar); for (File sourceDirectory : getSourceDirectories()) { File source = new File(sourceDirectory, className + ".java"); if (source.exists()) { return source; } } return null; } public static Object compileJava(String code) throws Exception { StringBuilder classPathsBuilder = new StringBuilder(); for (ClassLoader loader = ObjectUtils.getCurrentClassLoader(); loader != null; loader = loader.getParent()) { if (loader instanceof URLClassLoader) { for (URL url : ((URLClassLoader) loader).getURLs()) { classPathsBuilder.append(IoUtils.toFile(url, StringUtils.UTF_8).getPath()); classPathsBuilder.append(File.pathSeparator); } } } MemoryFileManager fileManager = new MemoryFileManager(COMPILER.getStandardFileManager(null, null, null)); try { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); List<String> options = new ArrayList<String>(); options.add("-classpath"); options.add(classPathsBuilder.toString()); JavaFileObject source = new StringSource(code); JavaCompiler.CompilationTask task = COMPILER.getTask(null, fileManager, diagnostics, options, null, Arrays.asList(source)); synchronized (COMPILER) { if (task.call()) { Set<Class<?>> classes = new HashSet<Class<?>>(); ClassLoader classLoader = fileManager.getClassLoader(StandardLocation.CLASS_OUTPUT); for (String className : fileManager.classes.keySet()) { classes.add(classLoader.loadClass(className)); } return classes; } } if (!diagnostics.getDiagnostics().isEmpty()) { return diagnostics; } else { throw new IllegalArgumentException( "Can't find a static method without any parameters!"); } } finally { fileManager.close(); } } @SuppressWarnings("unchecked") public static Object evaluateJava(String code) throws Exception { Object result = compileJava(code); if (result instanceof Set) { for (Class<?> c : (Set<Class<?>>) result) { for (Method method : c.getDeclaredMethods()) { if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class && method.getParameterTypes().length == 0) { method.setAccessible(true); try { return method.invoke(null); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); throw cause instanceof Exception ? (Exception) cause : ex; } } } } } return result; } // --- private static class MemoryFileManager extends ForwardingJavaFileManager<JavaFileManager> { private final Map<String, byte[]> classes = new LinkedHashMap<String, byte[]>(); public MemoryFileManager(JavaFileManager fileManager) { super(fileManager); } @Override public ClassLoader getClassLoader(Location location) { return new ByteArrayClassLoader(ObjectUtils.getCurrentClassLoader(), classes); } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) { return new ByteArrayClass(); } @Override public boolean hasLocation(Location location) { return location == StandardLocation.CLASS_OUTPUT || location == StandardLocation.CLASS_PATH; } private class ByteArrayClass extends SimpleJavaFileObject { public ByteArrayClass() { super(DEFAULT_URI, JavaFileObject.Kind.CLASS); } public OutputStream openOutputStream() { return new FilterOutputStream(new ByteArrayOutputStream()) { @Override public void close() throws IOException { byte[] bytecode = ((ByteArrayOutputStream) out).toByteArray(); String className = new ClassReader(bytecode).getClassName().replace('/', '.'); classes.put(className, bytecode); } }; } } } public static class ByteArrayClassLoader extends ClassLoader { private final Map<String, byte[]> classes; public ByteArrayClassLoader(ClassLoader parent, Map<String, byte[]> classes) { super(parent); this.classes = classes; } @Override public Class<?> loadClass(String className) throws ClassNotFoundException { byte[] bytecode = classes.get(className); if (bytecode != null) { return defineClass(className, bytecode, 0, bytecode.length); } else { return super.loadClass(className); } } } private static class StringSource extends SimpleJavaFileObject { private static final Pattern CLASS_NAME_PATTERN = Pattern.compile( "(?m)^[\\s\\p{javaJavaIdentifierPart}]*(?:class|interface)\\s+" + "(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)"); private final String code; public StringSource(String code) { super(guessClassName(code), JavaFileObject.Kind.SOURCE); this.code = code; } private static URI guessClassName(String code) { Matcher classNameMatcher = CLASS_NAME_PATTERN.matcher(code); if (classNameMatcher.find()) { return DEFAULT_URI.resolve(classNameMatcher.group(1) + JavaFileObject.Kind.SOURCE.extension); } else { return DEFAULT_URI; } } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } // --- private static Class<?> AGENT_CLASS; private static final Instrumentation INSTRUMENTATION; private static final Map<String, String> JSP_SERVLET_PATHS_MAP = new HashMap<String, String>(); private static final Map<String, String> JSP_LINE_NUMBERS_MAP = new HashMap<String, String>(); private static final ClassFileTransformer JSP_CLASS_RECORDER = new ClassFileTransformer() { @Override public byte[] transform( ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] bytecode) { ClassReader reader = new ClassReader(bytecode); String superName = reader.getSuperName(); if ("org/apache/jasper/runtime/HttpJspBase".equals(superName)) { ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_FRAMES); reader.accept(new SmapAdapter(writer, className), ClassReader.SKIP_FRAMES); } return null; } }; private static class SmapAdapter extends ClassAdapter { private static final Pattern LINE_SECTION_PATTERN = Pattern.compile("(?s)(\\S+)\\s+\\*L\\s+(.*?)\\s*\\*E"); private final String className; public SmapAdapter(ClassVisitor delegate, String initialClassName) { super(delegate); className = initialClassName; } @Override public void visitSource(String source, String debug) { if (!debug.startsWith("SMAP")) { return; } Matcher lineSectionMatcher = LINE_SECTION_PATTERN.matcher(debug); if (lineSectionMatcher.find()) { String name = className.replace('/', '.'); JSP_SERVLET_PATHS_MAP.put(name, lineSectionMatcher.group(1)); JSP_LINE_NUMBERS_MAP.put(name, lineSectionMatcher.group(2)); } } } static { Class<?> agentClass = getAgentClass(); Instrumentation instrumentation = null; if (agentClass != null) { try { instrumentation = (Instrumentation) agentClass.getField("INSTRUMENTATION").get(null); instrumentation.addTransformer(JSP_CLASS_RECORDER, true); } catch (Exception ex) { } } INSTRUMENTATION = instrumentation; } /** * Returns the agent class that provides the instrumentation * instance. * * @return May be {@code null}. */ private static synchronized Class<?> getAgentClass() { try { AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); return AGENT_CLASS; } catch (ClassNotFoundException ex) { } Class<?> vmClass = ObjectUtils.getClassByName("com.sun.tools.attach.VirtualMachine"); if (vmClass == null) { return null; } // Hack to guess this app's PID. RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pid = runtime.getName(); int atAt = pid.indexOf('@'); if (atAt < 0) { LOGGER.info("Can't guess the VM PID!"); return null; } else { pid = pid.substring(0, atAt); } Object vm = null; try { try { // Hack around Mac OS X not using the correct // temporary directory. String newTmpdir = System.getenv("TMPDIR"); if (newTmpdir != null) { String oldTmpdir = System.getProperty("java.io.tmpdir"); if (oldTmpdir != null) { try { System.setProperty("java.io.tmpdir", newTmpdir); vm = vmClass.getMethod("attach", String.class).invoke(null, pid); } finally { System.setProperty("java.io.tmpdir", oldTmpdir); } } - } else { - vm = vmClass.getMethod("attach", String.class).invoke(null, pid); } // Create a temporary instrumentation agent JAR. String agentName = Agent.class.getName(); File file = File.createTempFile(agentName, ".jar"); try { Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attributes.putValue("Agent-Class", Agent.class.getName()); attributes.putValue("Can-Redefine-Classes", "true"); attributes.putValue("Can-Retransform-Classes", "true"); JarOutputStream jar = new JarOutputStream(new FileOutputStream(file), manifest); try { String entryName = agentName.replace('.', '/') + ".class"; jar.putNextEntry(new JarEntry(entryName)); InputStream originalInput = CodeUtils.class.getResourceAsStream("/" + entryName); try { IoUtils.copy(originalInput, jar); } finally { originalInput.close(); } jar.closeEntry(); } finally { jar.close(); } - if (vm != null) { - vmClass.getMethod("loadAgent", String.class).invoke(vm, file.getAbsolutePath()); - } + vmClass.getMethod("loadAgent", String.class).invoke(vm, file.getAbsolutePath()); AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); } finally { if (!file.delete()) { file.deleteOnExit(); } } } finally { if (vm != null) { vmClass.getMethod("detach").invoke(vm); } } } catch (Exception ex) { LOGGER.info("Can't create an instrumentation instance!", ex); } return AGENT_CLASS; } /** * Exposes an instrumentation instance. While this class is technically * public, it shouldn't be accessed directly. * Use {@link CodeUtils#getInstrumentation} instead. */ public static final class Agent { public static Instrumentation INSTRUMENTATION; public static void agentmain(String agentArguments, Instrumentation instrumentation) { INSTRUMENTATION = instrumentation; } } /** * Returns an instrumentation instance for redefining classes on the fly. * * @return May be {@code null}. */ public static Instrumentation getInstrumentation() { return INSTRUMENTATION; } /** * For receiving notifications when classes are redefined through * {@link #redefineClasses}. */ public static interface RedefineClassesListener { public void redefined(Set<Class<?>> classes); } private static final Set<RedefineClassesListener> REDEFINE_CLASSES_LISTENERS = new HashSet<RedefineClassesListener>(); /** * Adds the given {@code listener} to be notified when classes * are redefined through {@link #redefineClasses}. * * @param listener If {@code null}, does nothing. */ public static void addRedefineClassesListener(RedefineClassesListener listener) { if (listener != null) { REDEFINE_CLASSES_LISTENERS.add(listener); } } /** * Removes the given {@code listener} so that it's no longer notified * when classes are redefined through {@link #redefineClasses}. * * @param listener If {@code null}, does nothing. */ public static void removeRedefineClassesListener(RedefineClassesListener listener) { if (listener != null) { REDEFINE_CLASSES_LISTENERS.remove(listener); } } /** * Redefines all classes according to the given {@code definitions}. * * @return Definitions that failed to redefine the class. * @see Instrumentation#redefineClasses */ public static List<ClassDefinition> redefineClasses(List<ClassDefinition> definitions) { Set<Class<?>> successes = new HashSet<Class<?>>(); List<ClassDefinition> failures = new ArrayList<ClassDefinition>(); Instrumentation instrumentation = getInstrumentation(); if (instrumentation == null) { failures.addAll(definitions); } else { for (ClassDefinition definition : definitions) { try { instrumentation.redefineClasses(definition); Class<?> c = definition.getDefinitionClass(); successes.add(c); } catch (Exception error) { failures.add(definition); } } } if (!successes.isEmpty()) { LOGGER.info("Redefined {}", successes); for (RedefineClassesListener listener : REDEFINE_CLASSES_LISTENERS) { listener.redefined(successes); } } return failures; } public static String getJspServletPath(String className) { return JSP_SERVLET_PATHS_MAP.get(className); } public static int getJspLineNumber(String className, int javaLineNumber) { String jspLineNumbers = JSP_LINE_NUMBERS_MAP.get(className); if (jspLineNumbers == null) { return -1; } BufferedReader reader = new BufferedReader(new StringReader(jspLineNumbers)); try { int at, inputStart, inputRepeat, outputStart, outputIncrement, offset; String input, output; for (String line; (line = reader.readLine()) != null; ) { at = line.indexOf('#'); if (at > -1) { line = line.substring(at + 1); } at = line.indexOf(':'); if (at < 0) { continue; } input = line.substring(0, at); output = line.substring(at + 1); at = input.indexOf(','); if (at < 0) { inputStart = ObjectUtils.to(int.class, input); inputRepeat = 1; } else { inputStart = ObjectUtils.to(int.class, input.substring(0, at)); inputRepeat = ObjectUtils.to(int.class, input.substring(at + 1)); } at = output.indexOf(','); if (at < 0) { outputStart = ObjectUtils.to(int.class, output); outputIncrement = 1; } else { outputStart = ObjectUtils.to(int.class, output.substring(0, at)); outputIncrement = ObjectUtils.to(int.class, output.substring(at + 1)); } offset = javaLineNumber - outputStart; if (offset >= 0 && offset < inputRepeat * outputIncrement) { return inputStart + offset / outputIncrement; } } } catch (IOException ex) { } return -1; } }
false
true
private static synchronized Class<?> getAgentClass() { try { AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); return AGENT_CLASS; } catch (ClassNotFoundException ex) { } Class<?> vmClass = ObjectUtils.getClassByName("com.sun.tools.attach.VirtualMachine"); if (vmClass == null) { return null; } // Hack to guess this app's PID. RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pid = runtime.getName(); int atAt = pid.indexOf('@'); if (atAt < 0) { LOGGER.info("Can't guess the VM PID!"); return null; } else { pid = pid.substring(0, atAt); } Object vm = null; try { try { // Hack around Mac OS X not using the correct // temporary directory. String newTmpdir = System.getenv("TMPDIR"); if (newTmpdir != null) { String oldTmpdir = System.getProperty("java.io.tmpdir"); if (oldTmpdir != null) { try { System.setProperty("java.io.tmpdir", newTmpdir); vm = vmClass.getMethod("attach", String.class).invoke(null, pid); } finally { System.setProperty("java.io.tmpdir", oldTmpdir); } } } else { vm = vmClass.getMethod("attach", String.class).invoke(null, pid); } // Create a temporary instrumentation agent JAR. String agentName = Agent.class.getName(); File file = File.createTempFile(agentName, ".jar"); try { Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attributes.putValue("Agent-Class", Agent.class.getName()); attributes.putValue("Can-Redefine-Classes", "true"); attributes.putValue("Can-Retransform-Classes", "true"); JarOutputStream jar = new JarOutputStream(new FileOutputStream(file), manifest); try { String entryName = agentName.replace('.', '/') + ".class"; jar.putNextEntry(new JarEntry(entryName)); InputStream originalInput = CodeUtils.class.getResourceAsStream("/" + entryName); try { IoUtils.copy(originalInput, jar); } finally { originalInput.close(); } jar.closeEntry(); } finally { jar.close(); } if (vm != null) { vmClass.getMethod("loadAgent", String.class).invoke(vm, file.getAbsolutePath()); } AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); } finally { if (!file.delete()) { file.deleteOnExit(); } } } finally { if (vm != null) { vmClass.getMethod("detach").invoke(vm); } } } catch (Exception ex) { LOGGER.info("Can't create an instrumentation instance!", ex); } return AGENT_CLASS; }
private static synchronized Class<?> getAgentClass() { try { AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); return AGENT_CLASS; } catch (ClassNotFoundException ex) { } Class<?> vmClass = ObjectUtils.getClassByName("com.sun.tools.attach.VirtualMachine"); if (vmClass == null) { return null; } // Hack to guess this app's PID. RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String pid = runtime.getName(); int atAt = pid.indexOf('@'); if (atAt < 0) { LOGGER.info("Can't guess the VM PID!"); return null; } else { pid = pid.substring(0, atAt); } Object vm = null; try { try { // Hack around Mac OS X not using the correct // temporary directory. String newTmpdir = System.getenv("TMPDIR"); if (newTmpdir != null) { String oldTmpdir = System.getProperty("java.io.tmpdir"); if (oldTmpdir != null) { try { System.setProperty("java.io.tmpdir", newTmpdir); vm = vmClass.getMethod("attach", String.class).invoke(null, pid); } finally { System.setProperty("java.io.tmpdir", oldTmpdir); } } } // Create a temporary instrumentation agent JAR. String agentName = Agent.class.getName(); File file = File.createTempFile(agentName, ".jar"); try { Manifest manifest = new Manifest(); Attributes attributes = manifest.getMainAttributes(); attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attributes.putValue("Agent-Class", Agent.class.getName()); attributes.putValue("Can-Redefine-Classes", "true"); attributes.putValue("Can-Retransform-Classes", "true"); JarOutputStream jar = new JarOutputStream(new FileOutputStream(file), manifest); try { String entryName = agentName.replace('.', '/') + ".class"; jar.putNextEntry(new JarEntry(entryName)); InputStream originalInput = CodeUtils.class.getResourceAsStream("/" + entryName); try { IoUtils.copy(originalInput, jar); } finally { originalInput.close(); } jar.closeEntry(); } finally { jar.close(); } vmClass.getMethod("loadAgent", String.class).invoke(vm, file.getAbsolutePath()); AGENT_CLASS = ClassLoader.getSystemClassLoader().loadClass(Agent.class.getName()); } finally { if (!file.delete()) { file.deleteOnExit(); } } } finally { if (vm != null) { vmClass.getMethod("detach").invoke(vm); } } } catch (Exception ex) { LOGGER.info("Can't create an instrumentation instance!", ex); } return AGENT_CLASS; }
diff --git a/src/hello/FizzBuzz.java b/src/hello/FizzBuzz.java index b7e54ee..7892fb6 100644 --- a/src/hello/FizzBuzz.java +++ b/src/hello/FizzBuzz.java @@ -1,11 +1,11 @@ package hello; public class FizzBuzz { public String fizzbuzz(int i) { if (i % 3 == 0) return "Fizz"; - if (i == 5) return "Buzz"; + if (i % 5 == 0) return "Buzz"; return null; } }
true
true
public String fizzbuzz(int i) { if (i % 3 == 0) return "Fizz"; if (i == 5) return "Buzz"; return null; }
public String fizzbuzz(int i) { if (i % 3 == 0) return "Fizz"; if (i % 5 == 0) return "Buzz"; return null; }
diff --git a/src/net/colar/netbeans/fan/FanParserTask.java b/src/net/colar/netbeans/fan/FanParserTask.java index c2d5ce1..3763c1f 100644 --- a/src/net/colar/netbeans/fan/FanParserTask.java +++ b/src/net/colar/netbeans/fan/FanParserTask.java @@ -1,1501 +1,1507 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan; import java.io.File; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.swing.text.Document; import net.colar.netbeans.fan.indexer.FanIndexerFactory; import net.colar.netbeans.fan.indexer.model.FanMethodParam; import net.colar.netbeans.fan.indexer.model.FanSlot; import net.colar.netbeans.fan.parboiled.FanLexAstUtils; import net.colar.netbeans.fan.indexer.model.FanType; import net.colar.netbeans.fan.parboiled.AstKind; import net.colar.netbeans.fan.parboiled.AstNode; import net.colar.netbeans.fan.parboiled.CancellableRecoveringParserRunner; import net.colar.netbeans.fan.parboiled.FantomParser; import net.colar.netbeans.fan.parboiled.FantomLexerTokens.TokenName; import net.colar.netbeans.fan.parboiled.FantomParserAstActions; import net.colar.netbeans.fan.parboiled.ParserCancelledError; import net.colar.netbeans.fan.parboiled.pred.NodeKindPredicate; import net.colar.netbeans.fan.project.FanBuildFileHelper; import net.colar.netbeans.fan.scope.FanAstScopeVarBase; import net.colar.netbeans.fan.scope.FanAstScopeVarBase.VarKind; import net.colar.netbeans.fan.scope.FanLocalScopeVar; import net.colar.netbeans.fan.scope.FanMethodScopeVar; import net.colar.netbeans.fan.scope.FanTypeScopeVar; import net.colar.netbeans.fan.types.FanResolvedFuncType; import net.colar.netbeans.fan.types.FanResolvedListType; import net.colar.netbeans.fan.types.FanResolvedMapType; import net.colar.netbeans.fan.types.FanResolvedNullType; import net.colar.netbeans.fan.types.FanResolvedType; import net.colar.netbeans.fan.types.FanUnknownType; import net.colar.netbeans.fan.utils.GenericPair; import org.netbeans.modules.csl.api.Error; import org.netbeans.modules.csl.api.OffsetRange; import org.netbeans.modules.csl.api.Severity; import org.netbeans.modules.csl.spi.DefaultError; import org.netbeans.modules.csl.spi.ParserResult; import org.netbeans.modules.parsing.api.Snapshot; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.parboiled.Node; import org.parboiled.Parboiled; import org.parboiled.errors.ErrorUtils; import org.parboiled.errors.ParseError; import org.parboiled.support.ParseTreeUtils; import org.parboiled.support.ParsingResult; /** * Parse a fan file and holds the results * parse() parses the file * parseScope() adds to the tree scope variables etc... * @author tcolar */ public class FanParserTask extends ParserResult { boolean invalidated = false; public boolean dumpTree = false; // debug List<Error> errors = new Vector<Error>(); // -> use parsingResult.errors ? // full path of the source file private final FileObject sourceFile; // simple name of the source file private final String sourceName; // pod name private final String pod; // once parse() is called, will contain the parboiled parsing result private ParsingResult<AstNode> parsingResult; private AstNode astRoot; // Cache types resolution, for performance private HashMap<String, FanType> typeCache = new HashMap<String, FanType>(); // Cache slots resolution, for performance private HashMap<String, List<FanSlot>> typeSlotsCache = new HashMap<String, List<FanSlot>>(); private FantomParser parser; private boolean localScopeDone; boolean hasGlobalError = false; Future<ParsingResult> parsingTask; CancellableRecoveringParserRunner runner; public FanParserTask(Snapshot snapshot) { super(snapshot); invalidated = false; sourceName = (snapshot == null || snapshot.getSource().getFileObject() == null) ? null : snapshot.getSource().getFileObject().getName(); sourceFile = (snapshot == null || snapshot.getSource().getFileObject() == null) ? null : FileUtil.toFileObject(FileUtil.normalizeFile(new File(snapshot.getSource().getFileObject().getPath()))); pod = (sourceFile == null) ? null : FanBuildFileHelper.getPodForPath(sourceFile.getPath()); parser = Parboiled.createParser(FantomParser.class, this); } @Override public List<? extends Error> getDiagnostics() { return errors; } /** * Return AST tree generated by this parsing * @return */ public Node<AstNode> getParseNodeTree() { if (parsingResult != null) { return parsingResult.parseTreeRoot; } return null; } public AstNode getAstTree() { Node<AstNode> nd = getParseNodeTree(); return nd == null ? null : nd.getValue(); } /** * Dump AST tree */ public void dumpTree() { FanUtilities.GENERIC_LOGGER.trace("-------------------Start AST Tree dump-----------------------"); ParseTreeUtils.printNodeTree(parsingResult); FanUtilities.GENERIC_LOGGER.trace("-------------------End AST Tree dump-----------------------"); } /** * Shotcut method for getSnapshot().getSource().getDocument(true); * @return */ public Document getDocument() { return getSnapshot().getSource().getDocument(true); } public void addGlobalError(String title, Throwable t) { // "High level error" Error error = DefaultError.createDefaultError(FanParserErrorKey.GLOBAL_ERROR.name(), title, title, null, 0, 0, true, Severity.ERROR); errors.add(error); } /** * The root scope * @return */ public AstNode getRootScope() { return astRoot; } public FileObject getSourceFile() { return sourceFile; } /** * Add an error (not the parser errors, but others like semantic etc..) * @param info * @param node */ public void addError(FanParserErrorKey key, String info, AstNode node) { if (node == null) { return; } String k = key.name(); OffsetRange range = node.getRelevantTextRange(); int start = range.getStart(); int end = range.getEnd(); //System.out.println("Start: "+start+"End:"+end); Error error = DefaultError.createDefaultError(k, info, "Syntax Error", sourceFile, start, end, true, Severity.ERROR); errors.add(error); } /** * Parse the file (using parboiled FantomParser) */ @SuppressWarnings(value = "unchecked") public void parse() { long start = new Date().getTime(); System.out.println("Starting parsing of: " + sourceName); try { try { runner = new CancellableRecoveringParserRunner(parser.compilationUnit(), getSnapshot().getText().toString()); parsingTask = runner.start(); parsingResult = parsingTask.get(); } catch (ParserCancelledError e) { cleanup(); return; } catch (CancellationException e) { cleanup(); return; } catch (ExecutionException e) { cleanup(); return; } catch (InterruptedException e) { cleanup(); return; } catch (Throwable e) { System.out.print("Error while parsing !!"); e.printStackTrace(); cleanup(); Runtime.getRuntime().gc(); return; } // Copy parboiled parse error into a CSL errrors for (ParseError err : parsingResult.parseErrors) { // key, displayName, description, file, start, end, lineError?, severity String msg = ErrorUtils.printParseError(err, parsingResult.inputBuffer); Error error = DefaultError.createDefaultError(FanParserErrorKey.PARSER_ERROR.name(), msg, msg, sourceFile, err.getErrorLocation().getIndex(), err.getErrorLocation().getIndex() + err.getErrorCharCount(), false, Severity.ERROR); errors.add(error); } if (parsingResult.parseTreeRoot != null) { astRoot = parsingResult.parseTreeRoot.getValue(); // link ast nodes together FantomParserAstActions.linkNodes(parsingResult.parseTreeRoot, astRoot); //String parseTreePrintOut = ParseTreeUtils.printNodeTree(parsingResult); //System.out.println(parseTreePrintOut); } } catch (Exception e) { addGlobalError("Parser error", e); e.printStackTrace(); hasGlobalError = true; } FanUtilities.GENERIC_LOGGER.info("Parsing completed in " + (new Date().getTime() - start) + " for : " + sourceName); } private void cleanup() { System.out.print("Cleaning up failed / 1cancelled parser task."); if (parsingTask != null) { parsingTask.cancel(true); } } /** * Call after parsing to add scope variables / type resolution to the AST tree * This does the "global" items - as needed by the indexer * such as types, slots & their params */ @SuppressWarnings("unchecked") public void parseGlobalScope() { long start = new Date().getTime(); FanUtilities.GENERIC_LOGGER.debug("Starting parsing scope of: " + sourceName); if (astRoot == null) { return; } // First run : lookup using statements for (AstNode node : astRoot.getChildren()) { if (invalidated) { return; // bailing out if task cancelled } switch (node.getKind()) { case AST_INC_USING: addError(FanParserErrorKey.INC_IMPORT, "Incomplete import statement", node); break; case AST_USING: addUsing(node); break; } } // Second pass, lookup types and slots for (AstNode node : astRoot.getChildren()) { if (invalidated) { return; // bailing out if task cancelled } switch (node.getKind()) { case AST_TYPE_DEF: String name = FanLexAstUtils.getFirstChildText(node, new NodeKindPredicate(AstKind.AST_ID)); if (name == null) { break; } FanTypeScopeVar var = new FanTypeScopeVar(node, name); AstNode scopeNode = FanLexAstUtils.getScopeNode(node.getRoot()); // We parse the type base first and add it to scope right away // So that parseSlots() can later resolve this & super. System.out.print(name); var.parse(); Hashtable<String, FanAstScopeVarBase> vars = scopeNode.getAllScopeVars(); if (vars.containsKey(name) && // If we have a "using" with the same name, we take precedence vars.get(name).getKind() != VarKind.IMPORT && vars.get(name).getKind() != VarKind.IMPORT_JAVA) { addError(FanParserErrorKey.DUPLICATED_VAR, "Duplicated type name", node); } else { scopeNode.getLocalScopeVars().put(name, var); } // Parse the slot definitions var.parseSlots(this); break; } } if (dumpTree) { FanLexAstUtils.dumpTree(astRoot, 0); } FanUtilities.GENERIC_LOGGER.info("Parsing of scope completed in " + (new Date().getTime() - start) + " for : " + sourceName); } //TODO: don't show the whole stack of errors, but just the base. // esp. for expressions, calls etc... /** * This parses the local scopes (inside slots) * This is not needed by the indexer, so we don't do it when called * from the indexer (see NBFanParser) * It highlights errors as well */ @SuppressWarnings("unchecked") public void parseLocalScopes() { // don't allow multiple calls synchronized (this) { if (localScopeDone) { return; } localScopeDone = true; } // Now do all the local scopes / variables for (AstNode node : astRoot.getChildren()) { if (node.getKind() == AstKind.AST_TYPE_DEF) { for (FanAstScopeVarBase var : node.getLocalScopeVars().values()) { if (var.getKind() == VarKind.CTOR || var.getKind() == VarKind.METHOD && !(var instanceof FanLocalScopeVar)) // those are "generated" - no node to parse { if (invalidated) { return; // bailing out if task cancelled } AstNode bkNode = var.getNode(); AstNode blockNode = FanLexAstUtils.getFirstChild(bkNode, new NodeKindPredicate(AstKind.AST_BLOCK)); if (blockNode != null) { try { parseVars(blockNode, null); } catch (IllegalStateException e) { return; // task cancelled } } } } } } } /** * Recursive - called by parseLocalScope * Parse the blocks / expressions * @param node * @param type */ @SuppressWarnings("unchecked") public void parseVars(AstNode node, FanResolvedType type) { if (invalidated) { throw new IllegalStateException("Parser task was invalidated"); } if (node == null) { return; } // If base type is unknown ... so are child if (type instanceof FanUnknownType) { node.setType(type); // Note: all children(if any) will be "unknown" as well. for (AstNode nd : node.getChildren()) { parseVars(nd, type); } return; } String text = node.getNodeText(true); try { switch (node.getKind()) { /*case TODO: AST_FIELD_ACCESSOR: AstNode fNode = FanLexAstUtils.findParentNode(node, AstKind.AST_FIELD_DEF); if (fNode != null) { AstNode fieldType = FanLexAstUtils.getFirstChild(fNode, new NodeKindPredicate(AstKind.AST_TYPE)); // introduce "it" to scope FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", fieldType.getType()); node.addScopeVar(itVar, true); } parseChildren(node); break;*/ case AST_EXPR_INDEX: AstNode indexEpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); type = doIndexExpr(indexEpr, type); break; case AST_LIST: // Index expressions, sometimes get parsed as Lists because the parser doesn't know a Type vs a variable // so str[0] gets parsed as a list (like Str[0] would be) rather than an index expr // so dolist takes care of that issue. type = doList(node, type); break; case AST_MAP: type = doMap(node, type); break; case AST_EXPR: case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression) case AST_EXPR_MULT: case AST_EXPR_ADD: type = doExpr(node, type); break; case AST_CALL_EXPR: // there is also an operator node, but we ignore it - will be used in doCall() AstNode callNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CALL)); parseVars(callNode, type); type = callNode.getType(); + if(type==null || ! type.isResolved()) + { + // we need to exit now, because we already added an error in parseVars (don't want 2) + node.setType(type); + return; + } break; case AST_CLOSURE: // standalone closure -> closure definition // closure calls are dealt with in doExpr type = doClosureDef(node, null); break; case AST_IT_BLOCK: // itBlocks that are not following a call or callExpr are in fact constructor block // the ones following call or callExpr are dealt with in doExpr as a closure // NO BREAK case AST_CTOR_BLOCK: if (type == null) { addError(FanParserErrorKey.UNEXPECTED_CTOR, "Unexpected constructor block", node); } doClosureCall(node, type, "with", 0); type = type.asStaticContext(false); break; case AST_CALL: type = doCall(node, type, null); break; case AST_ARG: // arg contains one expression - parse it to check for errors AstNode argExprNode = node.getChildren().get(0); parseVars(argExprNode, null); type = argExprNode.getType(); break; case AST_CHILD: // a wrapper node (takes type from wrapped node) parseChildren(node); if (node.getChildren().size() != 1) { throw new RuntimeException("AST_CHILD should have only one child node"); } type = node.getChildren().get(0).getType(); break; case AST_EXR_CAST: // take the cast type AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(castTypeNode, null); type = castTypeNode.getType(); // then parse the expression separately AstNode castExpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); parseVars(castExpr, null); //TODO: check if cast is valid break; case AST_EXPR_TYPE_CHECK: type = doTypeCheckExpr(node, type); break; case AST_EXPR_RANGE: // if only one child, then it's really not a rangeExpr, but an addExpr if (node.getChildren().size() == 1) { parseVars(node.getChildren().get(0), type); type = node.getChildren().get(0).getType(); } else { type = doRangeExpr(node, type); } break; case AST_CATCH_BLOCK: type = doCatchBlock(node, type); break; case AST_EXPR_LIT_BASE: Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf type = resolveLitteral(node, parseNode); break; case AST_ID: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_TYPE: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_LOCAL_DEF: // special case, since it introduces scope vars type = doLocalDef(node, type); break; case AST_TYPE_LITTERAL: // 'Type#' or '#slot' or 'Type#slot' type = doTypeLitteral(node, type); break; case AST_ENUM_DEFS: // already dealt with in type/slot parsing break; case AST_DSL: AstNode dslType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(dslType, null); type = dslType.getType(); break; case DUMMY_ROOT_NODE: // have dummy_root_node (for testing) carry it's child type AstNode dummyChild = node.getChildren().get(0); parseVars(dummyChild, type); type = dummyChild.getType(); break; default: // recurse into children parseChildren(node); } } catch (Exception e) { // We don't want exception to be propagated to user as an exception (prevents fixing it in IDE) // Do mark a global parsing error however type = FanResolvedType.makeUnresolved(node); addError(FanParserErrorKey.PARSING_ERR, "Unexpected Parsing error: " + e.toString(), node); FanUtilities.GENERIC_LOGGER.exception("Error parsing node: " + text, e); } node.setType(type); if (type != null && !type.isResolved()) { addError(FanParserErrorKey.UNKNOWN_ITEM, "Could not resolve item -> " + text, node); //FanUtilities.GENERIC_LOGGER.info(">Unresolved node"); //FanLexAstUtils.dumpTree(node, 0); //FanLexAstUtils.dumpTree(astRoot, 0); //FanUtilities.GENERIC_LOGGER.info("<Unresolved node"); } } private void parseChildren(AstNode node) { for (AstNode child : node.getChildren()) { parseVars(child, null); } } public FanResolvedType resolveLitteral(AstNode astNode, Node<AstNode> parseNode) { FanResolvedType type = FanResolvedType.makeUnresolved(astNode); String lbl = parseNode.getLabel(); String txt = astNode.getNodeText(true); if (lbl.equalsIgnoreCase(TokenName.ID.name())) { type = FanResolvedType.makeFromTypeSig(astNode, txt); } else if (lbl.equalsIgnoreCase(TokenName.CHAR_.name())) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Int"); } else if (lbl.equalsIgnoreCase(TokenName.NUMBER.name())) { char lastChar = (txt == null || txt.length() == 0) ? null : txt.charAt(txt.length() - 1); if (txt.toLowerCase().startsWith("0x")) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Int"); } else if (lastChar == 'f' || lastChar == 'F') { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Float"); } else if (lastChar == 'd' || lastChar == 'D') { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Decimal"); } else if (txt.endsWith("day") || txt.endsWith("hr") || txt.endsWith("min") || txt.endsWith("sec") || txt.endsWith("ms") || txt.endsWith("ns")) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Duration"); } else if (txt.indexOf(".") != -1) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Float"); } else { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Int"); // Default } } else if (lbl.equalsIgnoreCase(TokenName.STRS.name())) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Str"); } else if (lbl.equalsIgnoreCase(TokenName.URI.name())) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Uri"); } else if (lbl.equals("true") || lbl.equals("false")) { type = FanResolvedType.makeFromTypeSig(astNode, "sys::Bool"); } else if (lbl.equals("null")) { type = new FanResolvedNullType(astNode); // null is always nullable :) type = type.asNullableContext(true); } else if (lbl.equals("it")) { FanAstScopeVarBase var = astNode.getAllScopeVars().get("it"); if (var != null) { type = var.getType(); } } else if (lbl.equals("this")) { type = FanResolvedType.resolveThisType(astNode); } else if (lbl.equals("super")) { type = FanResolvedType.resolveSuper(astNode); } // Literal are never static context return type.asStaticContext(false); } @SuppressWarnings("unchecked") private void addUsing(AstNode usingNode) { String type = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_ID)); String as = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_USING_AS)); String ffi = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_USING_FFI)); String name = as != null ? as : type; if (name.indexOf("::") > -1) { name = name.substring(name.indexOf("::") + 2); } if (ffi != null && ffi.toLowerCase().equals("java")) { if (type.indexOf("::") != -1) { // Individual Item String qname = type.replaceAll("::", "\\."); if (findCachedQualifiedType(qname) == null) { addError(FanParserErrorKey.UNRESOLVED_USING, "Unresolved Java Item: " + qname, usingNode); } else { addUsingToNode(name, qname, usingNode, VarKind.IMPORT_JAVA); } } else { // whole package if (!FanType.hasPod(name)) { addError(FanParserErrorKey.UNRESOLVED_USING,"Unresolved Java package: " + name, usingNode); } else { Vector<FanType> items = FanType.findPodTypes(name, ""); for (FanType t : items) { addUsingToNode(t.getSimpleName(), t.getQualifiedName(), usingNode, VarKind.IMPORT_JAVA); } } } } else { if (type.indexOf("::") > 0) { // Adding a specific type String[] data = type.split("::"); if (!FanType.hasPod(data[0])) { addError(FanParserErrorKey.UNRESOLVED_USING, "Unresolved Pod: " + data[0], usingNode); } else if (findCachedQualifiedType(type) == null) { addError(FanParserErrorKey.UNRESOLVED_USING, "Unresolved Type: " + type, usingNode); } //Type t = FanPodIndexer.getInstance().getPodType(data[0], data[1]); addUsingToNode(name, type, usingNode, VarKind.IMPORT); } else { // Adding all the types of a Pod if (name.equalsIgnoreCase("sys")) // sys is always avail. { return; } if (!FanType.hasPod(name)) { addError(FanParserErrorKey.UNRESOLVED_USING, "Unresolved Pod: " + name, usingNode); } else { Vector<FanType> items = FanType.findPodTypes(name, ""); for (FanType t : items) { addUsingToNode(t.getSimpleName(), t.getQualifiedName(), usingNode, VarKind.IMPORT); } } } } } public static void addUsingToNode(String name, String qType, AstNode node, VarKind importKind) { AstNode scopeNode = FanLexAstUtils.getScopeNode(node); if (scopeNode == null) { return; } if (scopeNode.getLocalScopeVars().containsKey(name)) { // This is 'legal' ... maybe show a warning later ? //addError("Duplicated using: " + qType + " / " + scopeNode.getLocalScopeVars().get(name), node); System.out.println("Already have a using called: " + qType + " (" + scopeNode.getLocalScopeVars().get(name) + ")"); // Note: only keeping the 'last' definition (ie: override) } FanResolvedType rType = FanResolvedType.makeFromDbType(node, qType); rType = rType.asStaticContext(true); scopeNode.addScopeVar(name, importKind, rType, true); } public ParsingResult<AstNode> getParsingResult() { return parsingResult; } public String getPod() { return pod; } /** * TODO: this whole prunning stuff is a bit ugly * Should try to buod the AST properly using technizues here: * http://parboiled.hostingdelivered.com/viewtopic.php?f=3&t=9 * * During ParseNode construction, some astNodes that migth have been constructed from * some parseNode that where then "backtracked" (not the whoel sequence matched) * This looks for and remove those unwanted nodes. * @param node */ /*public void prune(AstNode node, String rootLabel) { List<AstNode> children = node.getChildren(); List<AstNode> toBepruned = new ArrayList<AstNode>(); for (AstNode child : children) { Node<AstNode> parseNode = child.getParseNode(); // If the node is orphaned (no link back to the root), that means it was backtracked out of. String label = "N/A"; while (parseNode != null) { label = parseNode.getLabel(); parseNode = parseNode.getParent(); } if (!rootLabel.equals(label)) { toBepruned.add(child); } else { // recurse into children prune(child, rootLabel); } } // Drop the orphaned nodes for (AstNode nd : toBepruned) { children.remove(nd); } } public String getRootLabel(AstNode rootNode) { Node<AstNode> parseNode = rootNode.getParseNode(); String rootLabel = "n/a"; while (parseNode != null) { rootLabel = parseNode.getLabel(); parseNode = parseNode.getParent(); } return rootLabel; }*/ @SuppressWarnings("unchecked") private FanResolvedType doExpr(AstNode node, FanResolvedType type) { // TODO: validate assignment type is compatible. boolean first = true; type = null; List<AstNode> children = node.getChildren(); for (int i = 0; i != children.size(); i++) { FanResolvedType baseType = type != null ? type : FanResolvedType.resolveItType(node); // when a itBlock follows a call, it's actually a sort of closure call (with block) AstNode child = children.get(i); if (child.getKind() == AstKind.AST_CALL || child.getKind() == AstKind.AST_CALL_EXPR) { if (i + 1 < children.size()) { AstNode nextChild = children.get(i + 1); if (nextChild.getKind() == AstKind.AST_IT_BLOCK) { AstNode callChild = child.getKind() == AstKind.AST_CALL ? child : FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_CALL)); // call expr // parse the whole thing as a closure call type = doCall(callChild, type, nextChild); // skip next child since we juts did it i++; continue; } } } // Normal procedure parseVars(child, type); // we take type of right hand side if first in expression // and not one of the special type we don't want the rhs for if (first || (child.getKind() != AstKind.AST_EXPR_ADD // add/mult operation cannot change the type && child.getKind() != AstKind.AST_EXPR_MULT //same /*&& child.getKind() != AstKind.AST_EXPR*/)) // new/sub expression { type = child.getType(); if (type != null && type.isResolved()) { type = type.parameterize(baseType, child); } // If part of the expr chain is unresolved (error), mark it unresolved // This avoids getting errors for the whole expression chain if (type != null && !type.isResolved()) { type = new FanUnknownType(node, child.getNodeText(true)); } } first = false; } return type; } /** * * @param node * @param type * @param forcedClosure : when we have an itBlock, we need to send it as if it was a closure * @return */ @SuppressWarnings("unchecked") private FanResolvedType doCall(AstNode node, FanResolvedType type, AstNode forcedClosure) { // saving the base type, because we need it for closures FanResolvedType baseType = type; if (type != null && type.isResolved() && node.getNodeText(true).equals("super")) { // named super. if (!type.isStaticContext() || !FanResolvedType.resolveThisType(node).isTypeCompatible(type)) { addError(FanParserErrorKey.INAVALID_SUPER, "Invalid named super call", node); type = FanResolvedType.makeUnresolved(node); } else { type = type.asStaticContext(false); } return type; } AstNode callChild = node.getChildren().get(0); String name = callChild.getNodeText(true); //if a direct call like doThis(), then search scope for type/slot // or if the type is actulaly the current type we are in (that happens when using 'this.') if (type == null || type.getQualifiedType().equals(FanResolvedType.resolveThisType(node).getQualifiedType())) { baseType = FanResolvedType.resolveItType(callChild); // constructor call or local slot type = FanResolvedType.makeFromTypeSig(callChild, name); type = type.parameterize(baseType, callChild).asStaticContext(false); // call is always not staticContext FanAstScopeVarBase childVar = callChild.getAllScopeVars().get(callChild.getNodeText(true)); // If not in scope, then not a local slot. if (childVar == null || (childVar.getKind() != VarKind.FIELD && childVar.getKind() != VarKind.METHOD)) { // It was a constructor call // once we make the call to make, it's not staticContext anymore baseType = type.asStaticContext(false); name = "make"; } } else // otherwise a slot of the base type like var.toStr() { // checking what call op we are dealing with String op = "."; AstNode callExpr = FanLexAstUtils.findParentNode(node, AstKind.AST_CALL_EXPR); if (callExpr != null) { AstNode operator = FanLexAstUtils.getFirstChild(callExpr, new NodeKindPredicate(AstKind.LBL_OP)); if (operator != null) { op = operator.getNodeText(true); } } // Can't resolve dynamic calls -> unknow type if (op.endsWith("->")) { return new FanUnknownType(node, sourceName); } // If using null check call on non nullable object, show an error, but continue resolution if (!type.isNullable() && op.startsWith("?")) { addError(FanParserErrorKey.NULL_CHECK, "Null check call on non-nullable: " + type.toString(), node); } type = type.resolveSlotType(name, this); type = type.parameterize(baseType, node); type = type.asStaticContext(false); // result of call never staticContext // The result of a null check call is always a nullable. // Note call like doc?.do comes as doc? . do if (op.startsWith("?")) { type = type.asNullableContext(true); } } // parse args List<AstNode> args = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_ARG)); int argIndex = 0; for (AstNode arg : args) { if (FanLexAstUtils.isWrappingNode(arg, new NodeKindPredicate(AstKind.AST_CLOSURE))) { // If the argument is a closure, we need to call doClosure directly AstNode closure = FanLexAstUtils.getFirstChildRecursive(arg, new NodeKindPredicate(AstKind.AST_CLOSURE)); doClosureCall(closure, baseType, name, argIndex); } else { // otherwise, do normal parsing parseVars(arg, null); } argIndex++; } // deal with the special trailing closure argument (if any) // TODO: Check that param types matches slot declaration AstNode closure = forcedClosure != null ? forcedClosure : FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CLOSURE)); if (closure != null) { doClosureCall(closure, baseType, name, argIndex); } // we need to parameterize the result // if baseType is null, then it probably couldn't return generics and if it did, then it would be "this", so leave it alone either way if (baseType != null) { type = type.parameterize(baseType, node); } return type.asStaticContext(false); } private void doClosureCall(AstNode closureNode, FanResolvedType baseType, String slotName, int argIndex) { //TODO: Check that param types matches slot declaration FanResolvedType slotBase = baseType.resolveSlotBaseType(slotName, this); FanSlot slot = FanSlot.findByTypeAndName(slotBase.getQualifiedType(), slotName); if (slot == null) { addError(FanParserErrorKey.CLOSURE_CALL, "Can't find closure call slot: " + slotBase.getQualifiedType() + "." + slotName, closureNode); } else { List<FanMethodParam> params = slot.getAllParameters(); if (argIndex > params.size()) { addError(FanParserErrorKey.CLOSURE_CALL, "Too many parameters in closure call.", closureNode); } else { if (argIndex == params.size()) { // One extra parameter VS expected -> trying 'with' call slotBase = baseType.resolveSlotBaseType("with", this); slot = FanSlot.findByTypeAndName(slotBase.getQualifiedType(), "with"); params = slot.getAllParameters(); argIndex = 0; } FanResolvedType func = FanResolvedType.makeFromTypeSig(closureNode, params.get(argIndex).getQualifiedType()); if (func == null || !(func instanceof FanResolvedFuncType)) { // This could happen, because of defaulted parameters, try a 'with' as well then .. probably too loose slotBase = baseType.resolveSlotBaseType("with", this); slot = FanSlot.findByTypeAndName(slotBase.getQualifiedType(), "with"); params = slot.getAllParameters(); argIndex = 0; func = FanResolvedType.makeFromTypeSig(closureNode, params.get(argIndex).getQualifiedType()); } // build lits of expected params for doClosure to use for inferrence resolution List<FanResolvedType> infTypes = new ArrayList<FanResolvedType>(); if (func instanceof FanResolvedFuncType) { // Otherwise it's a generic sys::Func -> no inference possible for (FanResolvedType t : ((FanResolvedFuncType) func).getTypes()) { // might be a generic type t = t.parameterize(baseType, closureNode); infTypes.add(t); } } FanResolvedFuncType closureFunc = closureNode.getKind() == AstKind.AST_CLOSURE ? doClosureDef(closureNode, infTypes) : (FanResolvedFuncType) func; AstNode closureBlock = closureNode.getKind() == AstKind.AST_CLOSURE ? FanLexAstUtils.getFirstChild(closureNode, new NodeKindPredicate(AstKind.AST_BLOCK)) : closureNode; // introduce the function variables boolean anyVars = false; if (closureFunc.getTypeNames() != null) { for (int i = 0; i != closureFunc.getTypeNames().size(); i++) { String name = closureFunc.getTypeNames().get(i); FanResolvedType type = closureFunc.getTypes().get(i); if (name != null) { closureBlock.addScopeVar(name, VarKind.LOCAL, type, false); anyVars = true; } } } if (anyVars == false) { FanResolvedType varType = closureFunc.getTypes().size() > 0 ? closureFunc.getTypes().get(0).parameterize(baseType, closureNode) : baseType; introduceItVariables(closureBlock, varType); // parse the block } parseChildren(closureBlock); } } } /** * * @param closureDefNode, can be null if not a closure defintion (itBlock / ctorblock) * @param blockNode * @param paramTypes * @return */ @SuppressWarnings("unchecked") private FanResolvedFuncType doClosureDef(AstNode closureDefNode, List<FanResolvedType> paramTypes) { FanResolvedType retType = FanResolvedType.makeFromDbType(closureDefNode, "sys::Void").asStaticContext(false); FanResolvedFuncType result = null; // Will store resolved types List<FanResolvedType> formalTypes = new ArrayList<FanResolvedType>(); int index = 0; List<String> formalNames = new ArrayList<String>(); if (closureDefNode != null) { // fully qualified closure (with parameters) for (AstNode child : closureDefNode.getChildren()) { if (child.getKind() == AstKind.AST_FORMAL) { GenericPair<String, FanResolvedType> pair = doFormal(child, paramTypes, index); FanResolvedType t = pair.getSecond(); if (t != null && !t.isResolved()) { addError(FanParserErrorKey.FORMAL_DEF, "Couldn't resolve formal definition: " + child.getNodeText(true), child); } String name = pair.getFirst(); formalTypes.add(t); formalNames.add(name); } else if (child.getKind() == AstKind.AST_TYPE) { // save the returned type parseVars(child, null); retType = child.getType(); } index++; } result = new FanResolvedFuncType(closureDefNode, formalTypes, retType); result.setTypeNames(formalNames); } else { formalTypes.add(FanResolvedType.makeFromDbType(null, "sys::This")); result = new FanResolvedFuncType(null, formalTypes, FanResolvedType.makeFromDbType(null, "sys::Void")); } return result; } /** * Deal with a formal (as used in a call) * @param node * @param baseType * @param closureBlock * @param formalTypes * @param index * @return */ @SuppressWarnings("unchecked") private GenericPair<String, FanResolvedType> doFormal(AstNode node, List<FanResolvedType> inferredTypes, int index) { AstNode formalName = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID)); AstNode formalTypeAndId = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID)); FanResolvedType fType = FanResolvedType.makeFromDbType(node, "sys::Void").asStaticContext(false); if (formalTypeAndId != null) { // typed formal formalName = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_ID)); AstNode formalType = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(formalType, null); fType = formalType.getType().asStaticContext(false); // TODO: check that it matches callParams } else { if (inferredTypes == null) { //addError("Can't have inferred formals in closure definition.", node); // actually that's allowed, just uses sys::Obj? fType = FanResolvedType.makeFromTypeSig(node, "sys::Obj?"); } else if (index >= inferredTypes.size()) { addError(FanParserErrorKey.FORMAL_DEF, "More inferred formals than expected.", node); fType = FanResolvedType.makeUnresolved(node); } else { fType = inferredTypes.get(index); } } return new GenericPair(formalName == null ? null : formalName.getNodeText(true), fType); } /** * Index expressions, sometimes get parsed as Lists because the parser doesn't know a Type vs a variable * so str[0] gets parsed as a list (like Str[0] would be) rather than an index expr * So we deal with this here. * @param node * @param type * @return */ @SuppressWarnings("unchecked") private FanResolvedType doList(AstNode node, FanResolvedType type) { AstNode listTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); List<AstNode> listExprNodes = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_EXPR)); List<FanResolvedType> listTypes = new ArrayList(); if (listTypeNode != null) { // if it's a typed list, use that as the type parseVars(listTypeNode, null); if (!listTypeNode.getType().isStaticContext() && listExprNodes.size() > 0) { // It's NOT a List at all after all, but an index expression (called on a var, not a Static type)! return doIndexExpr(listExprNodes.get(0), listTypeNode.getType()); } type = new FanResolvedListType(node, listTypeNode.getType()); } for (AstNode listExpr : listExprNodes) { parseVars(listExpr, null); listTypes.add(listExpr.getType()); } if (listTypeNode == null) { // try to infer it from the expr Nodes type = new FanResolvedListType(node, FanResolvedType.makeFromItemList(node, listTypes)); } return type; } @SuppressWarnings("unchecked") private FanResolvedType doMap(AstNode node, FanResolvedType type) { AstNode mapTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); List<AstNode> mapPairNodes = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_MAP_PAIR)); List<FanResolvedType> mapKeyTypes = new ArrayList(); List<FanResolvedType> mapValTypes = new ArrayList(); for (AstNode mapPair : mapPairNodes) { AstNode mapKey = mapPair.getChildren().get(0); AstNode mapVal = mapPair.getChildren().get(1); parseVars(mapKey, null); parseVars(mapVal, null); mapKeyTypes.add(mapKey.getType()); mapValTypes.add(mapVal.getType()); } if (mapTypeNode != null) { // if it's a typed list, use that as the type parseVars(mapTypeNode, null); type = mapTypeNode.getType(); } else { // otherwise try to infer it from the expr Nodes type = new FanResolvedMapType(node, FanResolvedType.makeFromItemList(node, mapKeyTypes), FanResolvedType.makeFromItemList(node, mapValTypes)); } return type; } /** * Note that we get the content of the index expression (exprNode) * @param exprNode * @param type * @return */ @SuppressWarnings("unchecked") private FanResolvedType doIndexExpr(AstNode exprNode, FanResolvedType type) { FanResolvedType baseType = type; parseVars(exprNode, null); AstNode range = FanLexAstUtils.getFirstChildRecursive(exprNode, new NodeKindPredicate(AstKind.AST_EXPR_RANGE)); // It's kinda twisted, but the expr will have a range ast node either way // however in the case of a "real" range it has 2 children expr (otherwise just 1 expr) if (range != null && range.getChildren().size() == 2) { // in case of a range, it's a call to slice() type = type.resolveSlotType("slice", this); if (!type.isResolved()) { addError(FanParserErrorKey.RANGE, "Range expression only valid on types with a 'slice' method." + exprNode.getNodeText(true), exprNode); } } else { // otherwise to get() (including list/maps) type = type.resolveSlotType("get", this); if (!type.isResolved()) { addError(FanParserErrorKey.INDEX, "Index expression only valid on types with 'get' method-> " + exprNode.getNodeText(true), exprNode); } } // TODO: check if list/map index key type is valid ? return type.parameterize(baseType, exprNode).asStaticContext(false); } @SuppressWarnings("unchecked") private FanResolvedType doTypeCheckExpr(AstNode node, FanResolvedType type) { String text = node.getNodeText(true); parseChildren(node); AstNode checkType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); if (text.startsWith("as")) // (cast) { type = checkType.getType(); } else if (text.startsWith("is")) // is or isnot -> boolean { type = FanResolvedType.makeFromDbType(node, "sys::Bool"); } else { type = null; // shouldn't happen } return type.asStaticContext(false); } private void introduceItVariables(AstNode node, FanResolvedType itType) { if (itType != null && itType.getDbType() != null) { itType = itType.asStaticContext(false); List<FanSlot> itSlots = FanSlot.getAllSlotsForType(itType.getDbType().getQualifiedName(), true, this); Hashtable<String, FanAstScopeVarBase> curvars = node.getAllScopeVars(); for (FanSlot itSlot : itSlots) { // itVar cannot "take over" existing variables if (!curvars.containsKey(itSlot.getName())) { FanAstScopeVarBase newVar = new FanLocalScopeVar(node, itType, itSlot, itSlot.getName()); node.addScopeVar(newVar, false); } } // add "it" to scope FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", itType); node.addScopeVar(itVar, true); } } @SuppressWarnings("unchecked") private FanResolvedType doLocalDef(AstNode node, FanResolvedType type) { AstNode typeAndIdNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID)); AstNode idNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID)); AstNode exprNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); if (typeAndIdNode != null) { idNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_ID)); AstNode typeNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(typeNode, null); type = typeNode.getType(); } String name = idNode.getNodeText(true); if (exprNode != null) { parseVars(exprNode, null); if (type == null) // Prefer the type in TypeNode if specified { type = exprNode.getType(); //TODO: check types are compatible } } if (type != null) { type = type.asStaticContext(false); } node.addScopeVar(new FanLocalScopeVar(node, VarKind.LOCAL, name, type), false); return type; } private FanResolvedType doRangeExpr(AstNode node, FanResolvedType type) { parseChildren(node); if (type == null) { // a range like (0..5) - always a range of Int type = FanResolvedType.makeFromDbType(node, "sys::Range"); } else if (type instanceof FanResolvedListType) { // a range like list[0..5] type = ((FanResolvedListType) type).getItemType().asStaticContext(false); } else if (type instanceof FanResolvedMapType) { // a range like map[0..5] type = ((FanResolvedMapType) type).getValType().asStaticContext(false); } else { // a range like "mystring"[0..5] type = type.resolveSlotType("slice", this); } return type; } @SuppressWarnings("unchecked") private FanResolvedType doCatchBlock(AstNode node, FanResolvedType type) { AstNode typeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); AstNode idNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID)); AstNode blockNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_BLOCK)); if (typeNode != null && idNode != null && blockNode != null) { parseVars(typeNode, null); // add exception variable to block scope FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.LOCAL, idNode.getNodeText(true), typeNode.getType().asStaticContext(false)); blockNode.addScopeVar(itVar, true); // Now parse the block parseVars(blockNode, null); } return type; } /** * Resolves fanType for a qualified name * Uses a cache for performance reason (heavy DB actions). * Calls FanType.findByQualifiedName(qName) * @param qName * @return */ public FanType findCachedQualifiedType(String qName) { if (!typeCache.containsKey(qName)) { typeCache.put(qName, FanType.findByQualifiedName(qName)); } return typeCache.get(qName); } public HashMap<String, List<FanSlot>> getTypeSlotCache() { return typeSlotsCache; } private FanResolvedType doTypeLitteral(AstNode node, FanResolvedType type) { FanResolvedType baseType = type; String slotId = node.getNodeText(true).substring(1); // always starts with # boolean isTypeLit = type != null && slotId.length() == 0; // otherwise a slot type = FanResolvedType.makeUnresolved(node); if (isTypeLit) { type = FanResolvedType.makeFromDbType(node, "sys::Type"); } else {// slot litteral if (baseType != null && baseType.getDbType().isJava()) { // Not even sure if this is suppose to work for java types, but covering it anyway List<Member> members = FanIndexerFactory.getJavaIndexer().findTypeSlots(baseType.getQualifiedType()); for (Member m : members) { if (m.getName().equalsIgnoreCase(slotId)) { if (m instanceof Field) { type = FanResolvedType.makeFromDbType(node, "sys::Field"); } else { type = FanResolvedType.makeFromDbType(node, "sys::Method"); } } } } else { // Fantom types if (baseType == null) { // local slot FanAstScopeVarBase var = node.getAllScopeVars().get(slotId); if (var instanceof FanMethodScopeVar) // note: method inherits from field { type = FanResolvedType.makeFromDbType(node, "sys::Method"); } else { type = FanResolvedType.makeFromDbType(node, "sys::Field"); } } else { // Type specified slots FanSlot slot = FanSlot.findByTypeAndName(baseType.getQualifiedType(), slotId); if (slot != null) { if (slot.isField()) { type = FanResolvedType.makeFromDbType(node, "sys::Field"); } else { type = FanResolvedType.makeFromDbType(node, "sys::Method"); } } } } } // we want an instance of the type type = type.asStaticContext(false); return type; } @Override protected void invalidate() { cancel(); } void cancel() { //System.out.println("Parser cancel called"); if (runner != null) { runner.cancel(); } if (parsingTask != null) { parsingTask.cancel(true); } if (parser != null) { // TODO: this seem to cause crashes/deadlock parser.cancel(); parser = null; } } public boolean hasGlobalError() { return hasGlobalError; } }
true
true
public void parseVars(AstNode node, FanResolvedType type) { if (invalidated) { throw new IllegalStateException("Parser task was invalidated"); } if (node == null) { return; } // If base type is unknown ... so are child if (type instanceof FanUnknownType) { node.setType(type); // Note: all children(if any) will be "unknown" as well. for (AstNode nd : node.getChildren()) { parseVars(nd, type); } return; } String text = node.getNodeText(true); try { switch (node.getKind()) { /*case TODO: AST_FIELD_ACCESSOR: AstNode fNode = FanLexAstUtils.findParentNode(node, AstKind.AST_FIELD_DEF); if (fNode != null) { AstNode fieldType = FanLexAstUtils.getFirstChild(fNode, new NodeKindPredicate(AstKind.AST_TYPE)); // introduce "it" to scope FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", fieldType.getType()); node.addScopeVar(itVar, true); } parseChildren(node); break;*/ case AST_EXPR_INDEX: AstNode indexEpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); type = doIndexExpr(indexEpr, type); break; case AST_LIST: // Index expressions, sometimes get parsed as Lists because the parser doesn't know a Type vs a variable // so str[0] gets parsed as a list (like Str[0] would be) rather than an index expr // so dolist takes care of that issue. type = doList(node, type); break; case AST_MAP: type = doMap(node, type); break; case AST_EXPR: case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression) case AST_EXPR_MULT: case AST_EXPR_ADD: type = doExpr(node, type); break; case AST_CALL_EXPR: // there is also an operator node, but we ignore it - will be used in doCall() AstNode callNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CALL)); parseVars(callNode, type); type = callNode.getType(); break; case AST_CLOSURE: // standalone closure -> closure definition // closure calls are dealt with in doExpr type = doClosureDef(node, null); break; case AST_IT_BLOCK: // itBlocks that are not following a call or callExpr are in fact constructor block // the ones following call or callExpr are dealt with in doExpr as a closure // NO BREAK case AST_CTOR_BLOCK: if (type == null) { addError(FanParserErrorKey.UNEXPECTED_CTOR, "Unexpected constructor block", node); } doClosureCall(node, type, "with", 0); type = type.asStaticContext(false); break; case AST_CALL: type = doCall(node, type, null); break; case AST_ARG: // arg contains one expression - parse it to check for errors AstNode argExprNode = node.getChildren().get(0); parseVars(argExprNode, null); type = argExprNode.getType(); break; case AST_CHILD: // a wrapper node (takes type from wrapped node) parseChildren(node); if (node.getChildren().size() != 1) { throw new RuntimeException("AST_CHILD should have only one child node"); } type = node.getChildren().get(0).getType(); break; case AST_EXR_CAST: // take the cast type AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(castTypeNode, null); type = castTypeNode.getType(); // then parse the expression separately AstNode castExpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); parseVars(castExpr, null); //TODO: check if cast is valid break; case AST_EXPR_TYPE_CHECK: type = doTypeCheckExpr(node, type); break; case AST_EXPR_RANGE: // if only one child, then it's really not a rangeExpr, but an addExpr if (node.getChildren().size() == 1) { parseVars(node.getChildren().get(0), type); type = node.getChildren().get(0).getType(); } else { type = doRangeExpr(node, type); } break; case AST_CATCH_BLOCK: type = doCatchBlock(node, type); break; case AST_EXPR_LIT_BASE: Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf type = resolveLitteral(node, parseNode); break; case AST_ID: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_TYPE: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_LOCAL_DEF: // special case, since it introduces scope vars type = doLocalDef(node, type); break; case AST_TYPE_LITTERAL: // 'Type#' or '#slot' or 'Type#slot' type = doTypeLitteral(node, type); break; case AST_ENUM_DEFS: // already dealt with in type/slot parsing break; case AST_DSL: AstNode dslType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(dslType, null); type = dslType.getType(); break; case DUMMY_ROOT_NODE: // have dummy_root_node (for testing) carry it's child type AstNode dummyChild = node.getChildren().get(0); parseVars(dummyChild, type); type = dummyChild.getType(); break; default: // recurse into children parseChildren(node); } } catch (Exception e) { // We don't want exception to be propagated to user as an exception (prevents fixing it in IDE) // Do mark a global parsing error however type = FanResolvedType.makeUnresolved(node); addError(FanParserErrorKey.PARSING_ERR, "Unexpected Parsing error: " + e.toString(), node); FanUtilities.GENERIC_LOGGER.exception("Error parsing node: " + text, e); } node.setType(type); if (type != null && !type.isResolved()) { addError(FanParserErrorKey.UNKNOWN_ITEM, "Could not resolve item -> " + text, node); //FanUtilities.GENERIC_LOGGER.info(">Unresolved node"); //FanLexAstUtils.dumpTree(node, 0); //FanLexAstUtils.dumpTree(astRoot, 0); //FanUtilities.GENERIC_LOGGER.info("<Unresolved node"); } }
public void parseVars(AstNode node, FanResolvedType type) { if (invalidated) { throw new IllegalStateException("Parser task was invalidated"); } if (node == null) { return; } // If base type is unknown ... so are child if (type instanceof FanUnknownType) { node.setType(type); // Note: all children(if any) will be "unknown" as well. for (AstNode nd : node.getChildren()) { parseVars(nd, type); } return; } String text = node.getNodeText(true); try { switch (node.getKind()) { /*case TODO: AST_FIELD_ACCESSOR: AstNode fNode = FanLexAstUtils.findParentNode(node, AstKind.AST_FIELD_DEF); if (fNode != null) { AstNode fieldType = FanLexAstUtils.getFirstChild(fNode, new NodeKindPredicate(AstKind.AST_TYPE)); // introduce "it" to scope FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", fieldType.getType()); node.addScopeVar(itVar, true); } parseChildren(node); break;*/ case AST_EXPR_INDEX: AstNode indexEpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); type = doIndexExpr(indexEpr, type); break; case AST_LIST: // Index expressions, sometimes get parsed as Lists because the parser doesn't know a Type vs a variable // so str[0] gets parsed as a list (like Str[0] would be) rather than an index expr // so dolist takes care of that issue. type = doList(node, type); break; case AST_MAP: type = doMap(node, type); break; case AST_EXPR: case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression) case AST_EXPR_MULT: case AST_EXPR_ADD: type = doExpr(node, type); break; case AST_CALL_EXPR: // there is also an operator node, but we ignore it - will be used in doCall() AstNode callNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CALL)); parseVars(callNode, type); type = callNode.getType(); if(type==null || ! type.isResolved()) { // we need to exit now, because we already added an error in parseVars (don't want 2) node.setType(type); return; } break; case AST_CLOSURE: // standalone closure -> closure definition // closure calls are dealt with in doExpr type = doClosureDef(node, null); break; case AST_IT_BLOCK: // itBlocks that are not following a call or callExpr are in fact constructor block // the ones following call or callExpr are dealt with in doExpr as a closure // NO BREAK case AST_CTOR_BLOCK: if (type == null) { addError(FanParserErrorKey.UNEXPECTED_CTOR, "Unexpected constructor block", node); } doClosureCall(node, type, "with", 0); type = type.asStaticContext(false); break; case AST_CALL: type = doCall(node, type, null); break; case AST_ARG: // arg contains one expression - parse it to check for errors AstNode argExprNode = node.getChildren().get(0); parseVars(argExprNode, null); type = argExprNode.getType(); break; case AST_CHILD: // a wrapper node (takes type from wrapped node) parseChildren(node); if (node.getChildren().size() != 1) { throw new RuntimeException("AST_CHILD should have only one child node"); } type = node.getChildren().get(0).getType(); break; case AST_EXR_CAST: // take the cast type AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(castTypeNode, null); type = castTypeNode.getType(); // then parse the expression separately AstNode castExpr = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR)); parseVars(castExpr, null); //TODO: check if cast is valid break; case AST_EXPR_TYPE_CHECK: type = doTypeCheckExpr(node, type); break; case AST_EXPR_RANGE: // if only one child, then it's really not a rangeExpr, but an addExpr if (node.getChildren().size() == 1) { parseVars(node.getChildren().get(0), type); type = node.getChildren().get(0).getType(); } else { type = doRangeExpr(node, type); } break; case AST_CATCH_BLOCK: type = doCatchBlock(node, type); break; case AST_EXPR_LIT_BASE: Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf type = resolveLitteral(node, parseNode); break; case AST_ID: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_TYPE: type = FanResolvedType.makeFromTypeSig(node, text); break; case AST_LOCAL_DEF: // special case, since it introduces scope vars type = doLocalDef(node, type); break; case AST_TYPE_LITTERAL: // 'Type#' or '#slot' or 'Type#slot' type = doTypeLitteral(node, type); break; case AST_ENUM_DEFS: // already dealt with in type/slot parsing break; case AST_DSL: AstNode dslType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE)); parseVars(dslType, null); type = dslType.getType(); break; case DUMMY_ROOT_NODE: // have dummy_root_node (for testing) carry it's child type AstNode dummyChild = node.getChildren().get(0); parseVars(dummyChild, type); type = dummyChild.getType(); break; default: // recurse into children parseChildren(node); } } catch (Exception e) { // We don't want exception to be propagated to user as an exception (prevents fixing it in IDE) // Do mark a global parsing error however type = FanResolvedType.makeUnresolved(node); addError(FanParserErrorKey.PARSING_ERR, "Unexpected Parsing error: " + e.toString(), node); FanUtilities.GENERIC_LOGGER.exception("Error parsing node: " + text, e); } node.setType(type); if (type != null && !type.isResolved()) { addError(FanParserErrorKey.UNKNOWN_ITEM, "Could not resolve item -> " + text, node); //FanUtilities.GENERIC_LOGGER.info(">Unresolved node"); //FanLexAstUtils.dumpTree(node, 0); //FanLexAstUtils.dumpTree(astRoot, 0); //FanUtilities.GENERIC_LOGGER.info("<Unresolved node"); } }
diff --git a/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java b/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java index a87af596..b7e867c2 100644 --- a/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java +++ b/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java @@ -1,154 +1,152 @@ package org.red5.server.jetty; /* * RED5 Open Source Flash Server - http://www.osflash.org/red5 * * Copyright (c) 2006 by respective authors (see below). All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.util.EventListener; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mortbay.jetty.handler.ContextHandler; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.resource.Resource; import org.red5.server.Context; import org.red5.server.ContextLoader; import org.red5.server.JettyLoader; import org.red5.server.WebScope; import org.red5.server.adapter.ApplicationAdapter; import org.red5.server.api.IClientRegistry; import org.red5.server.api.IMappingStrategy; import org.red5.server.api.IScopeResolver; import org.red5.server.api.IServer; import org.red5.server.api.service.IServiceInvoker; import org.springframework.beans.factory.access.BeanFactoryLocator; import org.springframework.beans.factory.access.BeanFactoryReference; import org.springframework.context.ApplicationContext; import org.springframework.context.access.ContextSingletonBeanFactoryLocator; import org.springframework.web.context.support.GenericWebApplicationContext; public class Red5WebPropertiesConfiguration implements Configuration, EventListener { // Initialize Logging protected static Log log = LogFactory.getLog(Red5WebPropertiesConfiguration.class.getName()); protected static WebAppContext _context; public void setWebAppContext(WebAppContext context) { _context = context; } public WebAppContext getWebAppContext() { return _context; } public void configureClassLoader() throws Exception { // TODO Auto-generated method stub } public void configureDefaults() throws Exception { // TODO Auto-generated method stub } public void configureWebApp () throws Exception{ WebAppContext context = getWebAppContext(); if (context.isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf = context.getWebInf(); if(webInf != null && webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if(hostnames[i].equals("*")) { // A virtual host "null" must be used so requests for any host // will be served. hostnames = null; break; } } context.setVirtualHosts(hostnames); - if(contextPath.equals("/")) - context.setContextPath("/defaultApp"); - else context.setContextPath(contextPath); + context.setContextPath(contextPath); } } else if (webInf == null) { // No WEB-INF directory found, register as default application log.info("No WEB-INF directory found for " + context.getContextPath() + ", creating default application."); BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("red5.xml"); BeanFactoryReference bfr = bfl.useBeanFactory("red5.common"); // Create WebScope dynamically WebScope scope = new WebScope(); IServer server = (IServer) bfr.getFactory().getBean(IServer.ID); scope.setServer(server); scope.setGlobalScope(server.getGlobal("default")); // Get default Red5 context ApplicationContext appCtx = JettyLoader.getApplicationContext(); ContextLoader loader = (ContextLoader) appCtx.getBean("context.loader"); appCtx = loader.getContext("default.context"); // Create context for the WebScope and initialize Context scopeContext = new Context(); scopeContext.setContextPath("/"); scopeContext.setClientRegistry((IClientRegistry) appCtx.getBean("global.clientRegistry")); scopeContext.setMappingStrategy((IMappingStrategy) appCtx.getBean("global.mappingStrategy")); scopeContext.setServiceInvoker((IServiceInvoker) appCtx.getBean("global.serviceInvoker")); scopeContext.setScopeResolver((IScopeResolver) appCtx.getBean("red5.scopeResolver")); // The context needs an ApplicationContext so resources can be resolved GenericWebApplicationContext webCtx = new GenericWebApplicationContext(); webCtx.setDisplayName("Automatic generated WebAppContext"); webCtx.setParent(appCtx); webCtx.setServletContext(ContextHandler.getCurrentContext()); scopeContext.setApplicationContext(webCtx); // Store context in scope scope.setContext(scopeContext); // Use default ApplicationAdapter as handler scope.setHandler(new ApplicationAdapter()); // Make available as "/<directoryName>" and allow access from all hosts scope.setContextPath(context.getContextPath()); scope.setVirtualHosts("*"); // Register WebScope in server scope.register(); } } public void deconfigureWebApp() throws Exception { // TODO Auto-generated method stub } }
true
true
public void configureWebApp () throws Exception{ WebAppContext context = getWebAppContext(); if (context.isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf = context.getWebInf(); if(webInf != null && webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if(hostnames[i].equals("*")) { // A virtual host "null" must be used so requests for any host // will be served. hostnames = null; break; } } context.setVirtualHosts(hostnames); if(contextPath.equals("/")) context.setContextPath("/defaultApp"); else context.setContextPath(contextPath); } } else if (webInf == null) { // No WEB-INF directory found, register as default application log.info("No WEB-INF directory found for " + context.getContextPath() + ", creating default application."); BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("red5.xml"); BeanFactoryReference bfr = bfl.useBeanFactory("red5.common"); // Create WebScope dynamically WebScope scope = new WebScope(); IServer server = (IServer) bfr.getFactory().getBean(IServer.ID); scope.setServer(server); scope.setGlobalScope(server.getGlobal("default")); // Get default Red5 context ApplicationContext appCtx = JettyLoader.getApplicationContext(); ContextLoader loader = (ContextLoader) appCtx.getBean("context.loader"); appCtx = loader.getContext("default.context"); // Create context for the WebScope and initialize Context scopeContext = new Context(); scopeContext.setContextPath("/"); scopeContext.setClientRegistry((IClientRegistry) appCtx.getBean("global.clientRegistry")); scopeContext.setMappingStrategy((IMappingStrategy) appCtx.getBean("global.mappingStrategy")); scopeContext.setServiceInvoker((IServiceInvoker) appCtx.getBean("global.serviceInvoker")); scopeContext.setScopeResolver((IScopeResolver) appCtx.getBean("red5.scopeResolver")); // The context needs an ApplicationContext so resources can be resolved GenericWebApplicationContext webCtx = new GenericWebApplicationContext(); webCtx.setDisplayName("Automatic generated WebAppContext"); webCtx.setParent(appCtx); webCtx.setServletContext(ContextHandler.getCurrentContext()); scopeContext.setApplicationContext(webCtx); // Store context in scope scope.setContext(scopeContext); // Use default ApplicationAdapter as handler scope.setHandler(new ApplicationAdapter()); // Make available as "/<directoryName>" and allow access from all hosts scope.setContextPath(context.getContextPath()); scope.setVirtualHosts("*"); // Register WebScope in server scope.register(); } }
public void configureWebApp () throws Exception{ WebAppContext context = getWebAppContext(); if (context.isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf = context.getWebInf(); if(webInf != null && webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if(hostnames[i].equals("*")) { // A virtual host "null" must be used so requests for any host // will be served. hostnames = null; break; } } context.setVirtualHosts(hostnames); context.setContextPath(contextPath); } } else if (webInf == null) { // No WEB-INF directory found, register as default application log.info("No WEB-INF directory found for " + context.getContextPath() + ", creating default application."); BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance("red5.xml"); BeanFactoryReference bfr = bfl.useBeanFactory("red5.common"); // Create WebScope dynamically WebScope scope = new WebScope(); IServer server = (IServer) bfr.getFactory().getBean(IServer.ID); scope.setServer(server); scope.setGlobalScope(server.getGlobal("default")); // Get default Red5 context ApplicationContext appCtx = JettyLoader.getApplicationContext(); ContextLoader loader = (ContextLoader) appCtx.getBean("context.loader"); appCtx = loader.getContext("default.context"); // Create context for the WebScope and initialize Context scopeContext = new Context(); scopeContext.setContextPath("/"); scopeContext.setClientRegistry((IClientRegistry) appCtx.getBean("global.clientRegistry")); scopeContext.setMappingStrategy((IMappingStrategy) appCtx.getBean("global.mappingStrategy")); scopeContext.setServiceInvoker((IServiceInvoker) appCtx.getBean("global.serviceInvoker")); scopeContext.setScopeResolver((IScopeResolver) appCtx.getBean("red5.scopeResolver")); // The context needs an ApplicationContext so resources can be resolved GenericWebApplicationContext webCtx = new GenericWebApplicationContext(); webCtx.setDisplayName("Automatic generated WebAppContext"); webCtx.setParent(appCtx); webCtx.setServletContext(ContextHandler.getCurrentContext()); scopeContext.setApplicationContext(webCtx); // Store context in scope scope.setContext(scopeContext); // Use default ApplicationAdapter as handler scope.setHandler(new ApplicationAdapter()); // Make available as "/<directoryName>" and allow access from all hosts scope.setContextPath(context.getContextPath()); scope.setVirtualHosts("*"); // Register WebScope in server scope.register(); } }
diff --git a/contentconnector-http/src/main/java/com/gentics/cr/http/HTTPClientRequestProcessor.java b/contentconnector-http/src/main/java/com/gentics/cr/http/HTTPClientRequestProcessor.java index bbf8f4b1..1a04d501 100644 --- a/contentconnector-http/src/main/java/com/gentics/cr/http/HTTPClientRequestProcessor.java +++ b/contentconnector-http/src/main/java/com/gentics/cr/http/HTTPClientRequestProcessor.java @@ -1,207 +1,207 @@ package com.gentics.cr.http; import java.io.IOException; import java.io.ObjectInputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; import java.util.Vector; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.HttpVersion; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.log4j.Logger; import com.gentics.cr.CRConfig; import com.gentics.cr.CRError; import com.gentics.cr.CRRequest; import com.gentics.cr.CRResolvableBean; import com.gentics.cr.RequestProcessor; import com.gentics.cr.exceptions.CRException; /** * * Last changed: $Date: 2010-04-01 15:25:54 +0200 (Do, 01 Apr 2010) $ * @version $Revision: 545 $ * @author $Author: [email protected] $ * */ public class HTTPClientRequestProcessor extends RequestProcessor { private static Logger log = Logger.getLogger(HTTPClientRequestProcessor.class); protected String name=null; private static final String URL_KEY = "URL"; private String path=""; protected HttpClient client; /** * Create new instance of HTTPClientRequestProcessor * @param config * @throws CRException */ public HTTPClientRequestProcessor(CRConfig config) throws CRException { super(config); this.name=config.getName(); //LOAD ADDITIONAL CONFIG client = new HttpClient(); this.path = (String)config.get(URL_KEY); if(this.path==null)log.error("COULD NOT GET URL FROM CONFIG (add RP.<rpnumber>.url=<url> to config). OVERTHINK YOUR CONFIG!"); } private String encode(String str) { if(str!=null) { try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e2) { log.error(e2.getMessage()); e2.printStackTrace(); } } return null; } /** * Requests Objects from a remote ContentConnector Servlet using type JavaXML * @param request * @param doNavigation * @return Collection of CRResolvableBean * @throws CRException */ public Collection<CRResolvableBean> getObjects(CRRequest request, boolean doNavigation) throws CRException { ArrayList<CRResolvableBean> resultlist = new ArrayList<CRResolvableBean>(); String additional = null; String filter = "filter="+encode(request.getRequestFilter()); String attributesstring = ""; for(String att:request.getAttributeArray()) { attributesstring+="&attributes="+encode(att); } String countstring=""; if(request.getCountString()!=null && !request.getCountString().equals("")) { countstring="&count="+encode(request.getCountString()); } String startstring=""; if(request.getStartString()!=null && !request.getStartString().equals("")) { startstring="&start="+encode(request.getStartString()); } String sortstring=""; if(request.getSortArray()!=null && request.getSortArray().length>0) { for(String sort:request.getSortArray()){ sortstring+="&sorting="+encode(sort); } } if(request.get(RequestProcessor.META_RESOLVABLE_KEY)!=null && (Boolean)request.get(RequestProcessor.META_RESOLVABLE_KEY)) { if(additional==null) additional=""; additional+="&"+RequestProcessor.META_RESOLVABLE_KEY+"=true"; } String highlightquery = (String)request.get(RequestProcessor.HIGHLIGHT_QUERY_KEY); if(highlightquery!=null) { if(additional==null) additional=""; additional+="&"+RequestProcessor.HIGHLIGHT_QUERY_KEY+"="+encode(highlightquery); } //TODO REQUEST ERWEITERN String reqUrl = filter+attributesstring+startstring+countstring+sortstring+"&type=JavaBIN"; if(additional!=null) reqUrl +=additional; GetMethod method = new GetMethod(this.path+"?"+reqUrl); // Provide custom retry handler is necessary method.getParams().setVersion(HttpVersion.HTTP_1_0); //Set request charset method.setRequestHeader("Content-type","text/xml; charset=UTF-8"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { HTTPClientRequestProcessor.log.error("Request failed: " + method.getStatusLine()); } Collection<CRResolvableBean> result = new Vector<CRResolvableBean>(); ObjectInputStream objstream = new ObjectInputStream(method.getResponseBodyAsStream()); Object responseObject; try { responseObject = objstream.readObject(); objstream.close(); if(responseObject instanceof Collection<?>) { result = this.toCRResolvableBeanCollection(responseObject); } else if(responseObject instanceof CRError) { CRError ex = (CRError)responseObject; throw new CRException(ex); } else { HTTPClientRequestProcessor.log.error("COULD NOT CAST RESULT. Perhaps remote agent does not work properly"); } } catch (ClassNotFoundException e) { - HTTPClientRequestProcessor.log.error("Coult not load object from http response: "+e.getMessage()); - e.printStackTrace(); + log.error("Coult not load object from http response",e); + throw new CRException(e); } if(result!=null) { for(CRResolvableBean crBean:result) { resultlist.add(crBean); } } } catch (HttpException e) { - System.err.println("Fatal protocol violation: " + e.getMessage()); - e.printStackTrace(); + log.error("Fatal protocol violation",e); + throw new CRException(e); } catch (IOException e) { - System.err.println("Fatal transport error: " + e.getMessage()); - e.printStackTrace(); + log.error("Fatal transport error",e); + throw new CRException(e); } finally { // Release the connection. method.releaseConnection(); } return resultlist; } @Override public void finalize() { } }
false
true
public Collection<CRResolvableBean> getObjects(CRRequest request, boolean doNavigation) throws CRException { ArrayList<CRResolvableBean> resultlist = new ArrayList<CRResolvableBean>(); String additional = null; String filter = "filter="+encode(request.getRequestFilter()); String attributesstring = ""; for(String att:request.getAttributeArray()) { attributesstring+="&attributes="+encode(att); } String countstring=""; if(request.getCountString()!=null && !request.getCountString().equals("")) { countstring="&count="+encode(request.getCountString()); } String startstring=""; if(request.getStartString()!=null && !request.getStartString().equals("")) { startstring="&start="+encode(request.getStartString()); } String sortstring=""; if(request.getSortArray()!=null && request.getSortArray().length>0) { for(String sort:request.getSortArray()){ sortstring+="&sorting="+encode(sort); } } if(request.get(RequestProcessor.META_RESOLVABLE_KEY)!=null && (Boolean)request.get(RequestProcessor.META_RESOLVABLE_KEY)) { if(additional==null) additional=""; additional+="&"+RequestProcessor.META_RESOLVABLE_KEY+"=true"; } String highlightquery = (String)request.get(RequestProcessor.HIGHLIGHT_QUERY_KEY); if(highlightquery!=null) { if(additional==null) additional=""; additional+="&"+RequestProcessor.HIGHLIGHT_QUERY_KEY+"="+encode(highlightquery); } //TODO REQUEST ERWEITERN String reqUrl = filter+attributesstring+startstring+countstring+sortstring+"&type=JavaBIN"; if(additional!=null) reqUrl +=additional; GetMethod method = new GetMethod(this.path+"?"+reqUrl); // Provide custom retry handler is necessary method.getParams().setVersion(HttpVersion.HTTP_1_0); //Set request charset method.setRequestHeader("Content-type","text/xml; charset=UTF-8"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { HTTPClientRequestProcessor.log.error("Request failed: " + method.getStatusLine()); } Collection<CRResolvableBean> result = new Vector<CRResolvableBean>(); ObjectInputStream objstream = new ObjectInputStream(method.getResponseBodyAsStream()); Object responseObject; try { responseObject = objstream.readObject(); objstream.close(); if(responseObject instanceof Collection<?>) { result = this.toCRResolvableBeanCollection(responseObject); } else if(responseObject instanceof CRError) { CRError ex = (CRError)responseObject; throw new CRException(ex); } else { HTTPClientRequestProcessor.log.error("COULD NOT CAST RESULT. Perhaps remote agent does not work properly"); } } catch (ClassNotFoundException e) { HTTPClientRequestProcessor.log.error("Coult not load object from http response: "+e.getMessage()); e.printStackTrace(); } if(result!=null) { for(CRResolvableBean crBean:result) { resultlist.add(crBean); } } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return resultlist; }
public Collection<CRResolvableBean> getObjects(CRRequest request, boolean doNavigation) throws CRException { ArrayList<CRResolvableBean> resultlist = new ArrayList<CRResolvableBean>(); String additional = null; String filter = "filter="+encode(request.getRequestFilter()); String attributesstring = ""; for(String att:request.getAttributeArray()) { attributesstring+="&attributes="+encode(att); } String countstring=""; if(request.getCountString()!=null && !request.getCountString().equals("")) { countstring="&count="+encode(request.getCountString()); } String startstring=""; if(request.getStartString()!=null && !request.getStartString().equals("")) { startstring="&start="+encode(request.getStartString()); } String sortstring=""; if(request.getSortArray()!=null && request.getSortArray().length>0) { for(String sort:request.getSortArray()){ sortstring+="&sorting="+encode(sort); } } if(request.get(RequestProcessor.META_RESOLVABLE_KEY)!=null && (Boolean)request.get(RequestProcessor.META_RESOLVABLE_KEY)) { if(additional==null) additional=""; additional+="&"+RequestProcessor.META_RESOLVABLE_KEY+"=true"; } String highlightquery = (String)request.get(RequestProcessor.HIGHLIGHT_QUERY_KEY); if(highlightquery!=null) { if(additional==null) additional=""; additional+="&"+RequestProcessor.HIGHLIGHT_QUERY_KEY+"="+encode(highlightquery); } //TODO REQUEST ERWEITERN String reqUrl = filter+attributesstring+startstring+countstring+sortstring+"&type=JavaBIN"; if(additional!=null) reqUrl +=additional; GetMethod method = new GetMethod(this.path+"?"+reqUrl); // Provide custom retry handler is necessary method.getParams().setVersion(HttpVersion.HTTP_1_0); //Set request charset method.setRequestHeader("Content-type","text/xml; charset=UTF-8"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { HTTPClientRequestProcessor.log.error("Request failed: " + method.getStatusLine()); } Collection<CRResolvableBean> result = new Vector<CRResolvableBean>(); ObjectInputStream objstream = new ObjectInputStream(method.getResponseBodyAsStream()); Object responseObject; try { responseObject = objstream.readObject(); objstream.close(); if(responseObject instanceof Collection<?>) { result = this.toCRResolvableBeanCollection(responseObject); } else if(responseObject instanceof CRError) { CRError ex = (CRError)responseObject; throw new CRException(ex); } else { HTTPClientRequestProcessor.log.error("COULD NOT CAST RESULT. Perhaps remote agent does not work properly"); } } catch (ClassNotFoundException e) { log.error("Coult not load object from http response",e); throw new CRException(e); } if(result!=null) { for(CRResolvableBean crBean:result) { resultlist.add(crBean); } } } catch (HttpException e) { log.error("Fatal protocol violation",e); throw new CRException(e); } catch (IOException e) { log.error("Fatal transport error",e); throw new CRException(e); } finally { // Release the connection. method.releaseConnection(); } return resultlist; }
diff --git a/src/com/android/exchange/adapter/EmailSyncAdapter.java b/src/com/android/exchange/adapter/EmailSyncAdapter.java index 2cd43c2a..18324ff4 100644 --- a/src/com/android/exchange/adapter/EmailSyncAdapter.java +++ b/src/com/android/exchange/adapter/EmailSyncAdapter.java @@ -1,698 +1,699 @@ /* * 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.adapter; import com.android.email.mail.Address; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailProvider; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.AccountColumns; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.Message; import com.android.email.provider.EmailContent.MessageColumns; import com.android.email.provider.EmailContent.SyncColumns; import com.android.email.service.MailService; import com.android.exchange.Eas; import com.android.exchange.EasSyncService; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.webkit.MimeTypeMap; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; /** * Sync adapter for EAS email * */ public class EmailSyncAdapter extends AbstractSyncAdapter { private static final int UPDATES_READ_COLUMN = 0; private static final int UPDATES_MAILBOX_KEY_COLUMN = 1; private static final int UPDATES_SERVER_ID_COLUMN = 2; private static final int UPDATES_FLAG_COLUMN = 3; private static final String[] UPDATES_PROJECTION = {MessageColumns.FLAG_READ, MessageColumns.MAILBOX_KEY, SyncColumns.SERVER_ID, MessageColumns.FLAG_FAVORITE}; String[] bindArguments = new String[2]; ArrayList<Long> mDeletedIdList = new ArrayList<Long>(); ArrayList<Long> mUpdatedIdList = new ArrayList<Long>(); public EmailSyncAdapter(Mailbox mailbox, EasSyncService service) { super(mailbox, service); } @Override public boolean parse(InputStream is) throws IOException { EasEmailSyncParser p = new EasEmailSyncParser(is, this); return p.parse(); } public class EasEmailSyncParser extends AbstractSyncParser { private static final String WHERE_SERVER_ID_AND_MAILBOX_KEY = SyncColumns.SERVER_ID + "=? and " + MessageColumns.MAILBOX_KEY + "=?"; private String mMailboxIdAsString; ArrayList<Message> newEmails = new ArrayList<Message>(); ArrayList<Long> deletedEmails = new ArrayList<Long>(); ArrayList<ServerChange> changedEmails = new ArrayList<ServerChange>(); public EasEmailSyncParser(InputStream in, EmailSyncAdapter adapter) throws IOException { super(in, adapter); mMailboxIdAsString = Long.toString(mMailbox.mId); } @Override public void wipe() { mContentResolver.delete(Message.CONTENT_URI, Message.MAILBOX_KEY + "=" + mMailbox.mId, null); mContentResolver.delete(Message.DELETED_CONTENT_URI, Message.MAILBOX_KEY + "=" + mMailbox.mId, null); mContentResolver.delete(Message.UPDATED_CONTENT_URI, Message.MAILBOX_KEY + "=" + mMailbox.mId, null); } public void addData (Message msg) throws IOException { ArrayList<Attachment> atts = new ArrayList<Attachment>(); while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) { switch (tag) { case Tags.EMAIL_ATTACHMENTS: case Tags.BASE_ATTACHMENTS: // BASE_ATTACHMENTS is used in EAS 12.0 and up attachmentsParser(atts, msg); break; case Tags.EMAIL_TO: msg.mTo = Address.pack(Address.parse(getValue())); break; case Tags.EMAIL_FROM: String from = getValue(); String sender = from; int q = from.indexOf('\"'); if (q >= 0) { int qq = from.indexOf('\"', q + 1); if (qq > 0) { sender = from.substring(q + 1, qq); } } msg.mDisplayName = sender; msg.mFrom = Address.pack(Address.parse(from)); break; case Tags.EMAIL_CC: msg.mCc = Address.pack(Address.parse(getValue())); break; case Tags.EMAIL_REPLY_TO: msg.mReplyTo = Address.pack(Address.parse(getValue())); break; case Tags.EMAIL_DATE_RECEIVED: String date = getValue(); // 2009-02-11T18:03:03.627Z GregorianCalendar cal = new GregorianCalendar(); cal.set(Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date .substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10)), Integer.parseInt(date.substring(11, 13)), Integer.parseInt(date .substring(14, 16)), Integer.parseInt(date .substring(17, 19))); cal.setTimeZone(TimeZone.getTimeZone("GMT")); msg.mTimeStamp = cal.getTimeInMillis(); break; case Tags.EMAIL_SUBJECT: msg.mSubject = getValue(); break; case Tags.EMAIL_READ: msg.mFlagRead = getValueInt() == 1; break; case Tags.BASE_BODY: bodyParser(msg); break; case Tags.EMAIL_FLAG: msg.mFlagFavorite = flagParser(); break; case Tags.EMAIL_BODY: String text = getValue(); msg.mText = text; msg.mTextInfo = "X;X;8;" + text.length(); // location;encoding;charset;size break; default: skipTag(); } } if (atts.size() > 0) { msg.mAttachments = atts; } } private void addParser(ArrayList<Message> emails) throws IOException { Message msg = new Message(); msg.mAccountKey = mAccount.mId; msg.mMailboxKey = mMailbox.mId; msg.mFlagLoaded = Message.LOADED; while (nextTag(Tags.SYNC_ADD) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: msg.mServerId = getValue(); break; case Tags.SYNC_APPLICATION_DATA: addData(msg); break; default: skipTag(); } } // Tell the provider that this is synced back msg.mServerVersion = mMailbox.mSyncKey; emails.add(msg); } // For now, we only care about the "active" state private Boolean flagParser() throws IOException { Boolean state = false; while (nextTag(Tags.EMAIL_FLAG) != END) { switch (tag) { case Tags.EMAIL_FLAG_STATUS: state = getValueInt() == 2; break; default: skipTag(); } } return state; } private void bodyParser(Message msg) throws IOException { String bodyType = Eas.BODY_PREFERENCE_TEXT; String body = ""; while (nextTag(Tags.EMAIL_BODY) != END) { switch (tag) { case Tags.BASE_TYPE: bodyType = getValue(); break; case Tags.BASE_DATA: body = getValue(); break; default: skipTag(); } } // We always ask for TEXT or HTML; there's no third option String info = "X;X;8;" + body.length(); if (bodyType.equals(Eas.BODY_PREFERENCE_HTML)) { msg.mHtmlInfo = info; msg.mHtml = body; } else { msg.mTextInfo = info; msg.mText = body; } } private void attachmentsParser(ArrayList<Attachment> atts, Message msg) throws IOException { while (nextTag(Tags.EMAIL_ATTACHMENTS) != END) { switch (tag) { case Tags.EMAIL_ATTACHMENT: case Tags.BASE_ATTACHMENT: // BASE_ATTACHMENT is used in EAS 12.0 and up attachmentParser(atts, msg); break; default: skipTag(); } } } private void attachmentParser(ArrayList<Attachment> atts, Message msg) throws IOException { String fileName = null; String length = null; String location = null; while (nextTag(Tags.EMAIL_ATTACHMENT) != END) { switch (tag) { // We handle both EAS 2.5 and 12.0+ attachments here case Tags.EMAIL_DISPLAY_NAME: case Tags.BASE_DISPLAY_NAME: fileName = getValue(); break; case Tags.EMAIL_ATT_NAME: case Tags.BASE_FILE_REFERENCE: location = getValue(); break; case Tags.EMAIL_ATT_SIZE: case Tags.BASE_ESTIMATED_DATA_SIZE: length = getValue(); break; default: skipTag(); } } if ((fileName != null) && (length != null) && (location != null)) { Attachment att = new Attachment(); att.mEncoding = "base64"; att.mSize = Long.parseLong(length); att.mFileName = fileName; att.mLocation = location; att.mMimeType = getMimeTypeFromFileName(fileName); atts.add(att); msg.mFlagAttachment = true; } } /** * Try to determine a mime type from a file name, defaulting to application/x, where x * is either the extension or (if none) octet-stream * At the moment, this is somewhat lame, since many file types aren't recognized * @param fileName the file name to ponder * @return */ // Note: The MimeTypeMap method currently uses a very limited set of mime types // A bug has been filed against this issue. public String getMimeTypeFromFileName(String fileName) { String mimeType; int lastDot = fileName.lastIndexOf('.'); String extension = null; if ((lastDot > 0) && (lastDot < fileName.length() - 1)) { extension = fileName.substring(lastDot + 1); } if (extension == null) { // A reasonable default for now. mimeType = "application/octet-stream"; } else { mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mimeType == null) { mimeType = "application/" + extension; } } return mimeType; } private Cursor getServerIdCursor(String serverId, String[] projection) { bindArguments[0] = serverId; bindArguments[1] = mMailboxIdAsString; return mContentResolver.query(Message.CONTENT_URI, projection, WHERE_SERVER_ID_AND_MAILBOX_KEY, bindArguments, null); } private void deleteParser(ArrayList<Long> deletes) throws IOException { while (nextTag(Tags.SYNC_DELETE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: String serverId = getValue(); // Find the message in this mailbox with the given serverId Cursor c = getServerIdCursor(serverId, Message.ID_COLUMN_PROJECTION); try { if (c.moveToFirst()) { userLog("Deleting ", serverId); deletes.add(c.getLong(Message.ID_COLUMNS_ID_COLUMN)); } } finally { c.close(); } break; default: skipTag(); } } } class ServerChange { long id; Boolean read; Boolean flag; ServerChange(long _id, Boolean _read, Boolean _flag) { id = _id; read = _read; flag = _flag; } } private void changeParser(ArrayList<ServerChange> changes) throws IOException { String serverId = null; Boolean oldRead = false; Boolean read = null; Boolean oldFlag = false; Boolean flag = null; long id = 0; while (nextTag(Tags.SYNC_CHANGE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); Cursor c = getServerIdCursor(serverId, Message.LIST_PROJECTION); try { if (c.moveToFirst()) { userLog("Changing ", serverId); oldRead = c.getInt(Message.LIST_READ_COLUMN) == Message.READ; oldFlag = c.getInt(Message.LIST_FAVORITE_COLUMN) == 1; id = c.getLong(Message.LIST_ID_COLUMN); } } finally { c.close(); } break; case Tags.EMAIL_READ: read = getValueInt() == 1; break; case Tags.EMAIL_FLAG: flag = flagParser(); break; case Tags.SYNC_APPLICATION_DATA: break; default: skipTag(); } } if (((read != null) && !oldRead.equals(read)) || ((flag != null) && !oldFlag.equals(flag))) { changes.add(new ServerChange(id, read, flag)); } } /* (non-Javadoc) * @see com.android.exchange.adapter.EasContentParser#commandsParser() */ @Override public void commandsParser() throws IOException { while (nextTag(Tags.SYNC_COMMANDS) != END) { if (tag == Tags.SYNC_ADD) { addParser(newEmails); incrementChangeCount(); } else if (tag == Tags.SYNC_DELETE) { deleteParser(deletedEmails); incrementChangeCount(); } else if (tag == Tags.SYNC_CHANGE) { changeParser(changedEmails); incrementChangeCount(); } else skipTag(); } } @Override public void responsesParser() throws IOException { } @Override public void commit() throws IOException { int notifyCount = 0; // Use a batch operation to handle the changes // TODO New mail notifications? Who looks for these? ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (Message msg: newEmails) { if (!msg.mFlagRead) { notifyCount++; } msg.addSaveOps(ops); } for (Long id : deletedEmails) { ops.add(ContentProviderOperation.newDelete( ContentUris.withAppendedId(Message.CONTENT_URI, id)).build()); } if (!changedEmails.isEmpty()) { // Server wins in a conflict... for (ServerChange change : changedEmails) { ContentValues cv = new ContentValues(); if (change.read != null) { cv.put(MessageColumns.FLAG_READ, change.read); } if (change.flag != null) { cv.put(MessageColumns.FLAG_FAVORITE, change.flag); } ops.add(ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Message.CONTENT_URI, change.id)) .withValues(cv) .build()); } } ops.add(ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId)).withValues( mMailbox.toContentValues()).build()); addCleanupOps(ops); // No commits if we're stopped synchronized (mService.getSynchronizer()) { if (mService.isStopped()) return; try { mContentResolver.applyBatch(EmailProvider.EMAIL_AUTHORITY, ops); userLog(mMailbox.mDisplayName, " SyncKey saved as: ", mMailbox.mSyncKey); } catch (RemoteException e) { // There is nothing to be done here; fail by returning null } catch (OperationApplicationException e) { // There is nothing to be done here; fail by returning null } } if (notifyCount > 0) { // Use the new atomic add URI in EmailProvider // We could add this to the operations being done, but it's not strictly // speaking necessary, as the previous batch preserves the integrity of the // database, whereas this is purely for notification purposes, and is itself atomic ContentValues cv = new ContentValues(); cv.put(EmailContent.FIELD_COLUMN_NAME, AccountColumns.NEW_MESSAGE_COUNT); cv.put(EmailContent.ADD_COLUMN_NAME, notifyCount); Uri uri = ContentUris.withAppendedId(Account.ADD_TO_FIELD_URI, mAccount.mId); mContentResolver.update(uri, cv, null, null); MailService.actionNotifyNewMessages(mContext, mAccount.mId); } } } @Override public String getCollectionName() { return "Email"; } private void addCleanupOps(ArrayList<ContentProviderOperation> ops) { // If we've sent local deletions, clear out the deleted table for (Long id: mDeletedIdList) { ops.add(ContentProviderOperation.newDelete( ContentUris.withAppendedId(Message.DELETED_CONTENT_URI, id)).build()); } // And same with the updates for (Long id: mUpdatedIdList) { ops.add(ContentProviderOperation.newDelete( ContentUris.withAppendedId(Message.UPDATED_CONTENT_URI, id)).build()); } } @Override public void cleanup() { if (!mDeletedIdList.isEmpty() || !mUpdatedIdList.isEmpty()) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); addCleanupOps(ops); try { mContext.getContentResolver() .applyBatch(EmailProvider.EMAIL_AUTHORITY, ops); } catch (RemoteException e) { // There is nothing to be done here; fail by returning null } catch (OperationApplicationException e) { // There is nothing to be done here; fail by returning null } } } private String formatTwo(int num) { if (num < 10) { return "0" + (char)('0' + num); } else return Integer.toString(num); } /** * Create date/time in RFC8601 format. Oddly enough, for calendar date/time, Microsoft uses * a different format that excludes the punctuation (this is why I'm not putting this in a * parent class) */ public String formatDateTime(Calendar calendar) { StringBuilder sb = new StringBuilder(); //YYYY-MM-DDTHH:MM:SS.MSSZ sb.append(calendar.get(Calendar.YEAR)); sb.append('-'); sb.append(formatTwo(calendar.get(Calendar.MONTH) + 1)); sb.append('-'); sb.append(formatTwo(calendar.get(Calendar.DAY_OF_MONTH))); sb.append('T'); sb.append(formatTwo(calendar.get(Calendar.HOUR_OF_DAY))); sb.append(':'); sb.append(formatTwo(calendar.get(Calendar.MINUTE))); sb.append(':'); sb.append(formatTwo(calendar.get(Calendar.SECOND))); sb.append(".000Z"); return sb.toString(); } @Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); // Find any of our deleted items Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); boolean first = true; // We keep track of the list of deleted item id's so that we can remove them from the // deleted table after the server receives our command mDeletedIdList.clear(); try { while (c.moveToNext()) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE mDeletedIdList.add(c.getLong(Message.LIST_ID_COLUMN)); } } finally { c.close(); } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // If the message is now in the trash folder, it has been deleted by the user if (currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN) == trashMailboxId) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) - .data(Tags.SYNC_SERVER_ID, currentCursor.getString(UPDATES_SERVER_ID_COLUMN)) + .data(Tags.SYNC_SERVER_ID, + currentCursor.getString(UPDATES_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE continue; } boolean flagChange = false; boolean readChange = false; int flag = 0; // We can only send flag changes to the server in 12.0 or later if (mService.mProtocolVersionDouble >= 12.0) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); - if (read == c.getInt(Message.LIST_READ_COLUMN)) { + if (read != c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1*WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!first) { s.end(); // SYNC_COMMANDS } return false; } }
false
true
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); // Find any of our deleted items Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); boolean first = true; // We keep track of the list of deleted item id's so that we can remove them from the // deleted table after the server receives our command mDeletedIdList.clear(); try { while (c.moveToNext()) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE mDeletedIdList.add(c.getLong(Message.LIST_ID_COLUMN)); } } finally { c.close(); } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // If the message is now in the trash folder, it has been deleted by the user if (currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN) == trashMailboxId) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) .data(Tags.SYNC_SERVER_ID, currentCursor.getString(UPDATES_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE continue; } boolean flagChange = false; boolean readChange = false; int flag = 0; // We can only send flag changes to the server in 12.0 or later if (mService.mProtocolVersionDouble >= 12.0) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); if (read == c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1*WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!first) { s.end(); // SYNC_COMMANDS } return false; }
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mContext.getContentResolver(); // Find any of our deleted items Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); boolean first = true; // We keep track of the list of deleted item id's so that we can remove them from the // deleted table after the server receives our command mDeletedIdList.clear(); try { while (c.moveToNext()) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE mDeletedIdList.add(c.getLong(Message.LIST_ID_COLUMN)); } } finally { c.close(); } // Find our trash mailbox, since deletions will have been moved there... long trashMailboxId = Mailbox.findMailboxOfType(mContext, mMailbox.mAccountKey, Mailbox.TYPE_TRASH); // Do the same now for updated items c = cr.query(Message.UPDATED_CONTENT_URI, Message.LIST_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); // We keep track of the list of updated item id's as we did above with deleted items mUpdatedIdList.clear(); try { while (c.moveToNext()) { long id = c.getLong(Message.LIST_ID_COLUMN); // Say we've handled this update mUpdatedIdList.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = cr.query(ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATES_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } // If the message is now in the trash folder, it has been deleted by the user if (currentCursor.getLong(UPDATES_MAILBOX_KEY_COLUMN) == trashMailboxId) { if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the command to delete this message s.start(Tags.SYNC_DELETE) .data(Tags.SYNC_SERVER_ID, currentCursor.getString(UPDATES_SERVER_ID_COLUMN)) .end(); // SYNC_DELETE continue; } boolean flagChange = false; boolean readChange = false; int flag = 0; // We can only send flag changes to the server in 12.0 or later if (mService.mProtocolVersionDouble >= 12.0) { flag = currentCursor.getInt(UPDATES_FLAG_COLUMN); if (flag != c.getInt(Message.LIST_FAVORITE_COLUMN)) { flagChange = true; } } int read = currentCursor.getInt(UPDATES_READ_COLUMN); if (read != c.getInt(Message.LIST_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } if (first) { s.start(Tags.SYNC_COMMANDS); first = false; } // Send the change to "read" and "favorite" (flagged) s.start(Tags.SYNC_CHANGE) .data(Tags.SYNC_SERVER_ID, c.getString(Message.LIST_SERVER_ID_COLUMN)) .start(Tags.SYNC_APPLICATION_DATA); if (readChange) { s.data(Tags.EMAIL_READ, Integer.toString(read)); } // "Flag" is a relatively complex concept in EAS 12.0 and above. It is not only // the boolean "favorite" that we think of in Gmail, but it also represents a // follow up action, which can include a subject, start and due dates, and even // recurrences. We don't support any of this as yet, but EAS 12.0 and higher // require that a flag contain a status, a type, and four date fields, two each // for start date and end (due) date. if (flagChange) { if (flag != 0) { // Status 2 = set flag s.start(Tags.EMAIL_FLAG).data(Tags.EMAIL_FLAG_STATUS, "2"); // "FollowUp" is the standard type s.data(Tags.EMAIL_FLAG_TYPE, "FollowUp"); long now = System.currentTimeMillis(); Calendar calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTimeInMillis(now); // Flags are required to have a start date and end date (duplicated) // First, we'll set the current date/time in GMT as the start time String utc = formatDateTime(calendar); s.data(Tags.TASK_START_DATE, utc).data(Tags.TASK_UTC_START_DATE, utc); // And then we'll use one week from today for completion date calendar.setTimeInMillis(now + 1*WEEKS); utc = formatDateTime(calendar); s.data(Tags.TASK_DUE_DATE, utc).data(Tags.TASK_UTC_DUE_DATE, utc); s.end(); } else { s.tag(Tags.EMAIL_FLAG); } } s.end().end(); // SYNC_APPLICATION_DATA, SYNC_CHANGE } finally { currentCursor.close(); } } } finally { c.close(); } if (!first) { s.end(); // SYNC_COMMANDS } return false; }
diff --git a/core/src/com/google/zxing/oned/AbstractOneDReader.java b/core/src/com/google/zxing/oned/AbstractOneDReader.java index cca98784..a818cbb8 100644 --- a/core/src/com/google/zxing/oned/AbstractOneDReader.java +++ b/core/src/com/google/zxing/oned/AbstractOneDReader.java @@ -1,229 +1,246 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.oned; import com.google.zxing.BlackPointEstimationMethod; import com.google.zxing.DecodeHintType; import com.google.zxing.MonochromeBitmapSource; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.common.BitArray; import java.util.Hashtable; /** * <p>Encapsulates functionality and implementation that is common to all families * of one-dimensional barcodes.</p> * * @author [email protected] (Daniel Switkin) * @author [email protected] (Sean Owen) */ public abstract class AbstractOneDReader implements OneDReader { public final Result decode(MonochromeBitmapSource image) throws ReaderException { return decode(image, null); } public final Result decode(MonochromeBitmapSource image, Hashtable hints) throws ReaderException { boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); try { return doDecode(image, hints, tryHarder); } catch (ReaderException re) { if (tryHarder && image.isRotateSupported()) { MonochromeBitmapSource rotatedImage = image.rotateCounterClockwise(); Result result = doDecode(rotatedImage, hints, tryHarder); // Record that we found it rotated 90 degrees CCW / 270 degrees CW Hashtable metadata = result.getResultMetadata(); int orientation = 270; if (metadata != null && metadata.containsKey(ResultMetadataType.ORIENTATION)) { // But if we found it reversed in doDecode(), add in that result here: orientation = (orientation + ((Integer) metadata.get(ResultMetadataType.ORIENTATION)).intValue()) % 360; } result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(orientation)); return result; } else { throw re; } } } private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException { int width = image.getWidth(); int height = image.getHeight(); BitArray row = new BitArray(width); // We're going to examine rows from the middle outward, searching alternately above and below the middle, // and farther out each time. rowStep is the number of rows between each successive attempt above and below // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep, // then middle - 2*rowStep, etc. // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided // that moving up and down by about 1/16 of the image is pretty good; we try more of the image if // "trying harder" int middle = height >> 1; int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4)); int maxLines; //if (tryHarder || barcodesToSkip > 0) { if (tryHarder) { maxLines = height; // Look at the whole image; looking for more than one barcode } else { maxLines = 7; } - Hashtable lastResults = null; + // Remember last barcode to avoid thinking we've found a new barcode when + // we just rescanned the last one. Actually remember two, the last one + // found above and below. + String lastResultAboveText = null; + String lastResultBelowText = null; boolean skippingSomeBarcodes = hints != null && hints.containsKey(DecodeHintType.SKIP_N_BARCODES) && ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue() > 0; for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; boolean isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: try { image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber); } catch (ReaderException re) { continue; } image.getBlackRow(rowNumber, row, 0, width); // We may try twice for each row, if "trying harder": for (int attempt = 0; attempt < 2; attempt++) { if (attempt == 1) { // trying again? if (tryHarder) { // only if "trying harder" row.reverse(); // reverse the row and continue } else { break; } } try { // Look for a barcode Result result = decodeRow(rowNumber, row, hints); + String resultText = result.getText(); - if (lastResults != null && lastResults.containsKey(result.getText())) { + // make sure we terminate inner loop after this because we found something + attempt = 1; + // See if we should skip and keep looking + if (( isAbove && resultText.equals(lastResultAboveText)) || + (!isAbove && resultText.equals(lastResultBelowText))) { // Just saw the last barcode again, proceed continue; } - if (skippingSomeBarcodes) { // See if we should skip and keep looking + if (skippingSomeBarcodes) { int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue(); if (oldValue > 1) { hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1)); } else { hints.remove(DecodeHintType.SKIP_N_BARCODES); skippingSomeBarcodes = false; } - if (lastResults == null) { - lastResults = new Hashtable(3); + if (isAbove) { + lastResultAboveText = resultText; + } else { + lastResultBelowText = resultText; } - lastResults.put(result.getText(), Boolean.TRUE); // Remember what we just saw } else { // We found our barcode if (attempt == 1) { // But it was upside down, so note that result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180)); } return result; } } catch (ReaderException re) { // continue -- just couldn't decode this row + if (skippingSomeBarcodes) { + if (isAbove) { + lastResultAboveText = null; + } else { + lastResultBelowText = null; + } + } } } } throw new ReaderException("No barcode found"); } static void recordPattern(BitArray row, int start, int[] counters) throws ReaderException { int numCounters = counters.length; for (int i = 0; i < numCounters; i++) { counters[i] = 0; } int end = row.getSize(); if (start >= end) { throw new ReaderException("Couldn't fully read a pattern"); } boolean isWhite = !row.get(start); int counterPosition = 0; int i = start; while (i < end) { boolean pixel = row.get(i); if ((!pixel && isWhite) || (pixel && !isWhite)) { counters[counterPosition]++; } else { counterPosition++; if (counterPosition == numCounters) { break; } else { counters[counterPosition] = 1; isWhite = !isWhite; } } i++; } // If we read fully the last section of pixels and filled up our counters -- or filled // the last counter but ran off the side of the image, OK. Otherwise, a problem. if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end))) { throw new ReaderException("Couldn't fully read a pattern"); } } /** * Determines how closely a set of observed counts of runs of black/white values matches a given * target pattern. This is reported as the ratio of the total variance from the expected pattern proportions * across all pattern elements, to the length of the pattern. * * @param counters observed counters * @param pattern expected pattern * @return average variance between counters and pattern */ static float patternMatchVariance(int[] counters, int[] pattern) { int total = 0; int numCounters = counters.length; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } float unitBarWidth = (float) total / (float) patternLength; float totalVariance = 0.0f; for (int x = 0; x < numCounters; x++) { float scaledCounter = (float) counters[x] / unitBarWidth; float width = pattern[x]; float abs = scaledCounter > width ? scaledCounter - width : width - scaledCounter; totalVariance += abs; } return totalVariance / (float) patternLength; } }
false
true
private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException { int width = image.getWidth(); int height = image.getHeight(); BitArray row = new BitArray(width); // We're going to examine rows from the middle outward, searching alternately above and below the middle, // and farther out each time. rowStep is the number of rows between each successive attempt above and below // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep, // then middle - 2*rowStep, etc. // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided // that moving up and down by about 1/16 of the image is pretty good; we try more of the image if // "trying harder" int middle = height >> 1; int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4)); int maxLines; //if (tryHarder || barcodesToSkip > 0) { if (tryHarder) { maxLines = height; // Look at the whole image; looking for more than one barcode } else { maxLines = 7; } Hashtable lastResults = null; boolean skippingSomeBarcodes = hints != null && hints.containsKey(DecodeHintType.SKIP_N_BARCODES) && ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue() > 0; for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; boolean isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: try { image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber); } catch (ReaderException re) { continue; } image.getBlackRow(rowNumber, row, 0, width); // We may try twice for each row, if "trying harder": for (int attempt = 0; attempt < 2; attempt++) { if (attempt == 1) { // trying again? if (tryHarder) { // only if "trying harder" row.reverse(); // reverse the row and continue } else { break; } } try { // Look for a barcode Result result = decodeRow(rowNumber, row, hints); if (lastResults != null && lastResults.containsKey(result.getText())) { // Just saw the last barcode again, proceed continue; } if (skippingSomeBarcodes) { // See if we should skip and keep looking int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue(); if (oldValue > 1) { hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1)); } else { hints.remove(DecodeHintType.SKIP_N_BARCODES); skippingSomeBarcodes = false; } if (lastResults == null) { lastResults = new Hashtable(3); } lastResults.put(result.getText(), Boolean.TRUE); // Remember what we just saw } else { // We found our barcode if (attempt == 1) { // But it was upside down, so note that result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180)); } return result; } } catch (ReaderException re) { // continue -- just couldn't decode this row } } } throw new ReaderException("No barcode found"); }
private Result doDecode(MonochromeBitmapSource image, Hashtable hints, boolean tryHarder) throws ReaderException { int width = image.getWidth(); int height = image.getHeight(); BitArray row = new BitArray(width); // We're going to examine rows from the middle outward, searching alternately above and below the middle, // and farther out each time. rowStep is the number of rows between each successive attempt above and below // the middle. So we'd scan row middle, then middle - rowStep, then middle + rowStep, // then middle - 2*rowStep, etc. // rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily decided // that moving up and down by about 1/16 of the image is pretty good; we try more of the image if // "trying harder" int middle = height >> 1; int rowStep = Math.max(1, height >> (tryHarder ? 7 : 4)); int maxLines; //if (tryHarder || barcodesToSkip > 0) { if (tryHarder) { maxLines = height; // Look at the whole image; looking for more than one barcode } else { maxLines = 7; } // Remember last barcode to avoid thinking we've found a new barcode when // we just rescanned the last one. Actually remember two, the last one // found above and below. String lastResultAboveText = null; String lastResultBelowText = null; boolean skippingSomeBarcodes = hints != null && hints.containsKey(DecodeHintType.SKIP_N_BARCODES) && ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue() > 0; for (int x = 0; x < maxLines; x++) { // Scanning from the middle out. Determine which row we're looking at next: int rowStepsAboveOrBelow = (x + 1) >> 1; boolean isAbove = (x & 0x01) == 0; // i.e. is x even? int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow); if (rowNumber < 0 || rowNumber >= height) { // Oops, if we run off the top or bottom, stop break; } // Estimate black point for this row and load it: try { image.estimateBlackPoint(BlackPointEstimationMethod.ROW_SAMPLING, rowNumber); } catch (ReaderException re) { continue; } image.getBlackRow(rowNumber, row, 0, width); // We may try twice for each row, if "trying harder": for (int attempt = 0; attempt < 2; attempt++) { if (attempt == 1) { // trying again? if (tryHarder) { // only if "trying harder" row.reverse(); // reverse the row and continue } else { break; } } try { // Look for a barcode Result result = decodeRow(rowNumber, row, hints); String resultText = result.getText(); // make sure we terminate inner loop after this because we found something attempt = 1; // See if we should skip and keep looking if (( isAbove && resultText.equals(lastResultAboveText)) || (!isAbove && resultText.equals(lastResultBelowText))) { // Just saw the last barcode again, proceed continue; } if (skippingSomeBarcodes) { int oldValue = ((Integer) hints.get(DecodeHintType.SKIP_N_BARCODES)).intValue(); if (oldValue > 1) { hints.put(DecodeHintType.SKIP_N_BARCODES, new Integer(oldValue - 1)); } else { hints.remove(DecodeHintType.SKIP_N_BARCODES); skippingSomeBarcodes = false; } if (isAbove) { lastResultAboveText = resultText; } else { lastResultBelowText = resultText; } } else { // We found our barcode if (attempt == 1) { // But it was upside down, so note that result.putMetadata(ResultMetadataType.ORIENTATION, new Integer(180)); } return result; } } catch (ReaderException re) { // continue -- just couldn't decode this row if (skippingSomeBarcodes) { if (isAbove) { lastResultAboveText = null; } else { lastResultBelowText = null; } } } } } throw new ReaderException("No barcode found"); }
diff --git a/components/bio-formats/src/loci/formats/in/MinimalTiffReader.java b/components/bio-formats/src/loci/formats/in/MinimalTiffReader.java index ae517fd9a..5088af9cc 100644 --- a/components/bio-formats/src/loci/formats/in/MinimalTiffReader.java +++ b/components/bio-formats/src/loci/formats/in/MinimalTiffReader.java @@ -1,462 +1,464 @@ // // MinimalTiffReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.codec.JPEG2000CodecOptions; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffCompression; import loci.formats.tiff.TiffParser; /** * MinimalTiffReader is the superclass for file format readers compatible with * or derived from the TIFF 6.0 file format. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/MinimalTiffReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/MinimalTiffReader.java;hb=HEAD">Gitweb</a></dd></dl> * * @author Melissa Linkert melissa at glencoesoftware.com */ public class MinimalTiffReader extends FormatReader { // -- Constants -- /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(MinimalTiffReader.class); // -- Fields -- /** List of IFDs for the current TIFF. */ protected IFDList ifds; /** List of thumbnail IFDs for the current TIFF. */ protected IFDList thumbnailIFDs; protected TiffParser tiffParser; private int lastPlane; /** Number of JPEG 2000 resolution levels. */ private Integer resolutionLevels; /** What a given series resolution level is. */ private Map<Integer, Integer> resolutionLevel; /** Codec options to use when decoding JPEG 2000 data. */ private JPEG2000CodecOptions j2kCodecOptions; // -- Constructors -- /** Constructs a new MinimalTiffReader. */ public MinimalTiffReader() { this("Minimal TIFF", new String[] {"tif", "tiff"}); } /** Constructs a new MinimalTiffReader. */ public MinimalTiffReader(String name, String suffix) { this(name, new String[] {suffix}); } /** Constructs a new MinimalTiffReader. */ public MinimalTiffReader(String name, String[] suffixes) { super(name, suffixes); domains = new String[] {FormatTools.GRAPHICS_DOMAIN}; suffixNecessary = false; } // -- MinimalTiffReader API methods -- /** Gets the list of IFDs associated with the current TIFF's image planes. */ public IFDList getIFDs() { return ifds; } /** Gets the list of IFDs associated with the current TIFF's thumbnails. */ public IFDList getThumbnailIFDs() { return thumbnailIFDs; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { return new TiffParser(stream).isValidHeader(); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (ifds == null || lastPlane < 0 || lastPlane > ifds.size()) return null; IFD lastIFD = ifds.get(lastPlane); int[] bits = lastIFD.getBitsPerSample(); if (bits[0] <= 8) { int[] colorMap = lastIFD.getIFDIntArray(IFD.COLOR_MAP); if (colorMap == null) { // it's possible that the LUT is only present in the first IFD if (lastPlane != 0) { lastIFD = ifds.get(0); colorMap = lastIFD.getIFDIntArray(IFD.COLOR_MAP); if (colorMap == null) return null; } else return null; } byte[][] table = new byte[3][colorMap.length / 3]; int next = 0; for (int j=0; j<table.length; j++) { for (int i=0; i<table[0].length; i++) { table[j][i] = (byte) ((colorMap[next++] >> 8) & 0xff); } } return table; } return null; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (ifds == null || lastPlane < 0 || lastPlane > ifds.size()) return null; IFD lastIFD = ifds.get(lastPlane); int[] bits = lastIFD.getBitsPerSample(); if (bits[0] <= 16 && bits[0] > 8) { int[] colorMap = lastIFD.getIFDIntArray(IFD.COLOR_MAP); if (colorMap == null || colorMap.length < 65536 * 3) { // it's possible that the LUT is only present in the first IFD if (lastPlane != 0) { lastIFD = ifds.get(0); colorMap = lastIFD.getIFDIntArray(IFD.COLOR_MAP); if (colorMap == null || colorMap.length < 65536 * 3) return null; } else return null; } short[][] table = new short[3][colorMap.length / 3]; int next = 0; for (int i=0; i<table.length; i++) { for (int j=0; j<table[0].length; j++) { table[i][j] = (short) (colorMap[next++] & 0xffff); } } return table; } return null; } /* @see loci.formats.FormatReader#getThumbSizeX() */ public int getThumbSizeX() { if (thumbnailIFDs != null && thumbnailIFDs.size() > 0) { try { return (int) thumbnailIFDs.get(0).getImageWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve thumbnail width", e); } } return super.getThumbSizeX(); } /* @see loci.formats.FormatReader#getThumbSizeY() */ public int getThumbSizeY() { if (thumbnailIFDs != null && thumbnailIFDs.size() > 0) { try { return (int) thumbnailIFDs.get(0).getImageLength(); } catch (FormatException e) { LOGGER.debug("Could not retrieve thumbnail height", e); } } return super.getThumbSizeY(); } /* @see loci.formats.FormatReader#openThumbBytes(int) */ public byte[] openThumbBytes(int no) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (thumbnailIFDs == null || thumbnailIFDs.size() <= no) { return super.openThumbBytes(no); } int[] bps = null; try { bps = thumbnailIFDs.get(no).getBitsPerSample(); } catch (FormatException e) { } if (bps == null) { return super.openThumbBytes(no); } int b = bps[0]; while ((b % 8) != 0) b++; b /= 8; if (b != FormatTools.getBytesPerPixel(getPixelType()) || bps.length != getRGBChannelCount()) { return super.openThumbBytes(no); } byte[] buf = new byte[getThumbSizeX() * getThumbSizeY() * getRGBChannelCount() * FormatTools.getBytesPerPixel(getPixelType())]; return tiffParser.getSamples(thumbnailIFDs.get(no), buf); } /** * @see loci.formats.FormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); IFD firstIFD = ifds.get(0); lastPlane = no; if (firstIFD.getCompression() == TiffCompression.JPEG_2000 || firstIFD.getCompression() == TiffCompression.JPEG_2000_LOSSY) { j2kCodecOptions.resolution = resolutionLevel.get(series); LOGGER.info("Using JPEG 2000 resolution level {}", j2kCodecOptions.resolution); tiffParser.setCodecOptions(j2kCodecOptions); } tiffParser.getSamples(ifds.get(no), buf, x, y, w, h); boolean float16 = getPixelType() == FormatTools.FLOAT && ifds.get(0).getBitsPerSample()[0] == 16; boolean float24 = getPixelType() == FormatTools.FLOAT && ifds.get(0).getBitsPerSample()[0] == 24; if (float16 || float24) { int nPixels = w * h * getRGBChannelCount(); int nBytes = float16 ? 2 : 3; int mantissaBits = float16 ? 10 : 16; int exponentBits = float16 ? 5 : 7; int maxExponent = (int) Math.pow(2, exponentBits) - 1; int bits = (nBytes * 8) - 1; byte[] newBuf = new byte[buf.length]; for (int i=0; i<nPixels; i++) { int v = DataTools.bytesToInt(buf, i * nBytes, nBytes, isLittleEndian()); int sign = v >> bits; int exponent = (v >> mantissaBits) & (int) (Math.pow(2, exponentBits) - 1); int mantissa = v & (int) (Math.pow(2, mantissaBits) - 1); if (exponent == 0) { if (mantissa != 0) { while ((mantissa & (int) Math.pow(2, mantissaBits)) == 0) { mantissa <<= 1; exponent--; } exponent++; mantissa &= (int) (Math.pow(2, mantissaBits) - 1); exponent += 127 - (Math.pow(2, exponentBits - 1) - 1); } } else if (exponent == maxExponent) { exponent = 255; } else { exponent += 127 - (Math.pow(2, exponentBits - 1) - 1); } mantissa <<= (23 - mantissaBits); int value = (sign << 31) | (exponent << 23) | mantissa; DataTools.unpackBytes(value, newBuf, i * 4, 4, isLittleEndian()); } System.arraycopy(newBuf, 0, buf, 0, newBuf.length); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { ifds = null; thumbnailIFDs = null; lastPlane = 0; tiffParser = null; resolutionLevels = null; resolutionLevel = new HashMap<Integer, Integer>(); j2kCodecOptions = JPEG2000CodecOptions.getDefaultOptions(); } } /* @see loci.formats.IFormatReader#getOptimalTileWidth() */ public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); try { return (int) ifds.get(0).getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); } /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); try { return (int) ifds.get(0).getTileLength(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile height", e); } return super.getOptimalTileHeight(); } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); tiffParser = new TiffParser(in); tiffParser.setDoCaching(false); Boolean littleEndian = tiffParser.checkHeader(); if (littleEndian == null) { throw new FormatException("Invalid TIFF file"); } boolean little = littleEndian.booleanValue(); in.order(little); LOGGER.info("Reading IFDs"); ifds = tiffParser.getNonThumbnailIFDs(); if (ifds == null || ifds.size() == 0) { throw new FormatException("No IFDs found"); } thumbnailIFDs = tiffParser.getThumbnailIFDs(); LOGGER.info("Populating metadata"); core[0].imageCount = ifds.size(); IFDList subResolutionIFDs = new IFDList(); for (IFD ifd : ifds) { tiffParser.fillInIFD(ifd); if (ifd.getCompression() == TiffCompression.JPEG_2000 || ifd.getCompression() == TiffCompression.JPEG_2000_LOSSY) { LOGGER.debug("Found IFD with JPEG 2000 compression"); long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); if (stripOffsets.length > 0) { long stripOffset = stripOffsets[0]; in.seek(stripOffset); JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in, stripOffset + stripByteCounts[0]); resolutionLevels = metadataParser.getResolutionLevels(); - LOGGER.debug("JPEG 2000 resolution levels: {}", resolutionLevels); - for (int level = 1; level <= resolutionLevels; level++) { - IFD newIFD = new IFD(ifd); - long factor = (long) Math.pow(2, level); - long newImageWidth = ifd.getImageWidth() / factor; - long newImageLength = ifd.getImageLength() / factor; - int resolutionLevel = Math.abs(level - resolutionLevels); - newIFD.put(IFD.RESOLUTION_LEVEL, resolutionLevel); - newIFD.put(IFD.IMAGE_WIDTH, newImageWidth); - newIFD.put(IFD.IMAGE_LENGTH, newImageLength); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format( - "Added JPEG 2000 sub-resolution IFD level %d: %dx%d", - resolutionLevel, newImageWidth, newImageLength)); + if (resolutionLevels != null) { + LOGGER.debug("JPEG 2000 resolution levels: {}", resolutionLevels); + for (int level = 1; level <= resolutionLevels; level++) { + IFD newIFD = new IFD(ifd); + long factor = (long) Math.pow(2, level); + long newImageWidth = ifd.getImageWidth() / factor; + long newImageLength = ifd.getImageLength() / factor; + int resolutionLevel = Math.abs(level - resolutionLevels); + newIFD.put(IFD.RESOLUTION_LEVEL, resolutionLevel); + newIFD.put(IFD.IMAGE_WIDTH, newImageWidth); + newIFD.put(IFD.IMAGE_LENGTH, newImageLength); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(String.format( + "Added JPEG 2000 sub-resolution IFD level %d: %dx%d", + resolutionLevel, newImageWidth, newImageLength)); + } + subResolutionIFDs.add(newIFD); } - subResolutionIFDs.add(newIFD); } } else { LOGGER.warn("IFD has no strip offsets!"); } } } IFD firstIFD = ifds.get(0); PhotoInterp photo = firstIFD.getPhotometricInterpretation(); int samples = firstIFD.getSamplesPerPixel(); core[0].rgb = samples > 1 || photo == PhotoInterp.RGB; core[0].interleaved = false; core[0].littleEndian = firstIFD.isLittleEndian(); core[0].sizeX = (int) firstIFD.getImageWidth(); core[0].sizeY = (int) firstIFD.getImageLength(); core[0].sizeZ = 1; core[0].sizeC = isRGB() ? samples : 1; core[0].sizeT = ifds.size(); core[0].pixelType = firstIFD.getPixelType(); core[0].metadataComplete = true; core[0].indexed = photo == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null); if (isIndexed()) { core[0].sizeC = 1; core[0].rgb = false; for (IFD ifd : ifds) { ifd.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, PhotoInterp.RGB_PALETTE); } } if (getSizeC() == 1 && !isIndexed()) core[0].rgb = false; core[0].dimensionOrder = "XYCZT"; core[0].bitsPerPixel = firstIFD.getBitsPerSample()[0]; // New core metadata now that we know how many sub-resolutions we have. if (resolutionLevels != null) { CoreMetadata[] newCore = new CoreMetadata[subResolutionIFDs.size() + 1]; newCore[0] = core[0]; int i = 1; for (IFD ifd : subResolutionIFDs) { newCore[i] = new CoreMetadata(this, 0); newCore[i].sizeX = (int) ifd.getImageWidth(); newCore[i].sizeY = (int) ifd.getImageLength(); newCore[i].thumbnail = true; resolutionLevel.put(i, (Integer) ifd.get(IFD.RESOLUTION_LEVEL)); i++; } core = newCore; } } }
false
true
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); tiffParser = new TiffParser(in); tiffParser.setDoCaching(false); Boolean littleEndian = tiffParser.checkHeader(); if (littleEndian == null) { throw new FormatException("Invalid TIFF file"); } boolean little = littleEndian.booleanValue(); in.order(little); LOGGER.info("Reading IFDs"); ifds = tiffParser.getNonThumbnailIFDs(); if (ifds == null || ifds.size() == 0) { throw new FormatException("No IFDs found"); } thumbnailIFDs = tiffParser.getThumbnailIFDs(); LOGGER.info("Populating metadata"); core[0].imageCount = ifds.size(); IFDList subResolutionIFDs = new IFDList(); for (IFD ifd : ifds) { tiffParser.fillInIFD(ifd); if (ifd.getCompression() == TiffCompression.JPEG_2000 || ifd.getCompression() == TiffCompression.JPEG_2000_LOSSY) { LOGGER.debug("Found IFD with JPEG 2000 compression"); long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); if (stripOffsets.length > 0) { long stripOffset = stripOffsets[0]; in.seek(stripOffset); JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in, stripOffset + stripByteCounts[0]); resolutionLevels = metadataParser.getResolutionLevels(); LOGGER.debug("JPEG 2000 resolution levels: {}", resolutionLevels); for (int level = 1; level <= resolutionLevels; level++) { IFD newIFD = new IFD(ifd); long factor = (long) Math.pow(2, level); long newImageWidth = ifd.getImageWidth() / factor; long newImageLength = ifd.getImageLength() / factor; int resolutionLevel = Math.abs(level - resolutionLevels); newIFD.put(IFD.RESOLUTION_LEVEL, resolutionLevel); newIFD.put(IFD.IMAGE_WIDTH, newImageWidth); newIFD.put(IFD.IMAGE_LENGTH, newImageLength); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "Added JPEG 2000 sub-resolution IFD level %d: %dx%d", resolutionLevel, newImageWidth, newImageLength)); } subResolutionIFDs.add(newIFD); } } else { LOGGER.warn("IFD has no strip offsets!"); } } } IFD firstIFD = ifds.get(0); PhotoInterp photo = firstIFD.getPhotometricInterpretation(); int samples = firstIFD.getSamplesPerPixel(); core[0].rgb = samples > 1 || photo == PhotoInterp.RGB; core[0].interleaved = false; core[0].littleEndian = firstIFD.isLittleEndian(); core[0].sizeX = (int) firstIFD.getImageWidth(); core[0].sizeY = (int) firstIFD.getImageLength(); core[0].sizeZ = 1; core[0].sizeC = isRGB() ? samples : 1; core[0].sizeT = ifds.size(); core[0].pixelType = firstIFD.getPixelType(); core[0].metadataComplete = true; core[0].indexed = photo == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null); if (isIndexed()) { core[0].sizeC = 1; core[0].rgb = false; for (IFD ifd : ifds) { ifd.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, PhotoInterp.RGB_PALETTE); } } if (getSizeC() == 1 && !isIndexed()) core[0].rgb = false; core[0].dimensionOrder = "XYCZT"; core[0].bitsPerPixel = firstIFD.getBitsPerSample()[0]; // New core metadata now that we know how many sub-resolutions we have. if (resolutionLevels != null) { CoreMetadata[] newCore = new CoreMetadata[subResolutionIFDs.size() + 1]; newCore[0] = core[0]; int i = 1; for (IFD ifd : subResolutionIFDs) { newCore[i] = new CoreMetadata(this, 0); newCore[i].sizeX = (int) ifd.getImageWidth(); newCore[i].sizeY = (int) ifd.getImageLength(); newCore[i].thumbnail = true; resolutionLevel.put(i, (Integer) ifd.get(IFD.RESOLUTION_LEVEL)); i++; } core = newCore; } }
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); tiffParser = new TiffParser(in); tiffParser.setDoCaching(false); Boolean littleEndian = tiffParser.checkHeader(); if (littleEndian == null) { throw new FormatException("Invalid TIFF file"); } boolean little = littleEndian.booleanValue(); in.order(little); LOGGER.info("Reading IFDs"); ifds = tiffParser.getNonThumbnailIFDs(); if (ifds == null || ifds.size() == 0) { throw new FormatException("No IFDs found"); } thumbnailIFDs = tiffParser.getThumbnailIFDs(); LOGGER.info("Populating metadata"); core[0].imageCount = ifds.size(); IFDList subResolutionIFDs = new IFDList(); for (IFD ifd : ifds) { tiffParser.fillInIFD(ifd); if (ifd.getCompression() == TiffCompression.JPEG_2000 || ifd.getCompression() == TiffCompression.JPEG_2000_LOSSY) { LOGGER.debug("Found IFD with JPEG 2000 compression"); long[] stripOffsets = ifd.getStripOffsets(); long[] stripByteCounts = ifd.getStripByteCounts(); if (stripOffsets.length > 0) { long stripOffset = stripOffsets[0]; in.seek(stripOffset); JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in, stripOffset + stripByteCounts[0]); resolutionLevels = metadataParser.getResolutionLevels(); if (resolutionLevels != null) { LOGGER.debug("JPEG 2000 resolution levels: {}", resolutionLevels); for (int level = 1; level <= resolutionLevels; level++) { IFD newIFD = new IFD(ifd); long factor = (long) Math.pow(2, level); long newImageWidth = ifd.getImageWidth() / factor; long newImageLength = ifd.getImageLength() / factor; int resolutionLevel = Math.abs(level - resolutionLevels); newIFD.put(IFD.RESOLUTION_LEVEL, resolutionLevel); newIFD.put(IFD.IMAGE_WIDTH, newImageWidth); newIFD.put(IFD.IMAGE_LENGTH, newImageLength); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format( "Added JPEG 2000 sub-resolution IFD level %d: %dx%d", resolutionLevel, newImageWidth, newImageLength)); } subResolutionIFDs.add(newIFD); } } } else { LOGGER.warn("IFD has no strip offsets!"); } } } IFD firstIFD = ifds.get(0); PhotoInterp photo = firstIFD.getPhotometricInterpretation(); int samples = firstIFD.getSamplesPerPixel(); core[0].rgb = samples > 1 || photo == PhotoInterp.RGB; core[0].interleaved = false; core[0].littleEndian = firstIFD.isLittleEndian(); core[0].sizeX = (int) firstIFD.getImageWidth(); core[0].sizeY = (int) firstIFD.getImageLength(); core[0].sizeZ = 1; core[0].sizeC = isRGB() ? samples : 1; core[0].sizeT = ifds.size(); core[0].pixelType = firstIFD.getPixelType(); core[0].metadataComplete = true; core[0].indexed = photo == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null); if (isIndexed()) { core[0].sizeC = 1; core[0].rgb = false; for (IFD ifd : ifds) { ifd.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, PhotoInterp.RGB_PALETTE); } } if (getSizeC() == 1 && !isIndexed()) core[0].rgb = false; core[0].dimensionOrder = "XYCZT"; core[0].bitsPerPixel = firstIFD.getBitsPerSample()[0]; // New core metadata now that we know how many sub-resolutions we have. if (resolutionLevels != null) { CoreMetadata[] newCore = new CoreMetadata[subResolutionIFDs.size() + 1]; newCore[0] = core[0]; int i = 1; for (IFD ifd : subResolutionIFDs) { newCore[i] = new CoreMetadata(this, 0); newCore[i].sizeX = (int) ifd.getImageWidth(); newCore[i].sizeY = (int) ifd.getImageLength(); newCore[i].thumbnail = true; resolutionLevel.put(i, (Integer) ifd.get(IFD.RESOLUTION_LEVEL)); i++; } core = newCore; } }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java index 9a9a14164..8c1d20a0c 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java @@ -1,1793 +1,1795 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.message; import gov.nist.javax.sip.DialogExt; import gov.nist.javax.sip.SipStackImpl; import gov.nist.javax.sip.TransactionExt; import gov.nist.javax.sip.header.ims.PathHeader; import gov.nist.javax.sip.message.MessageExt; import gov.nist.javax.sip.stack.SIPTransaction; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.sip.Address; import javax.servlet.sip.AuthInfo; import javax.servlet.sip.B2buaHelper; import javax.servlet.sip.Parameterable; import javax.servlet.sip.Proxy; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipURI; import javax.servlet.sip.TooManyHopsException; import javax.servlet.sip.URI; import javax.servlet.sip.SipSession.State; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingDirective; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogState; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.SipProvider; import javax.sip.Transaction; import javax.sip.address.TelURL; import javax.sip.header.AuthorizationHeader; import javax.sip.header.ContactHeader; import javax.sip.header.FromHeader; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.RecordRouteHeader; import javax.sip.header.RouteHeader; import javax.sip.header.SubscriptionStateHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.header.WWWAuthenticateHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipConnector; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.AddressImpl; import org.mobicents.servlet.sip.address.SipURIImpl; import org.mobicents.servlet.sip.address.TelURLImpl; import org.mobicents.servlet.sip.address.URIImpl; import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer; import org.mobicents.servlet.sip.core.ExtendedListeningPoint; import org.mobicents.servlet.sip.core.RoutingState; import org.mobicents.servlet.sip.core.SipNetworkInterfaceManager; import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher; import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession; import org.mobicents.servlet.sip.core.session.MobicentsSipSession; import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey; import org.mobicents.servlet.sip.core.session.SipRequestDispatcher; import org.mobicents.servlet.sip.core.session.SipSessionKey; import org.mobicents.servlet.sip.proxy.ProxyImpl; import org.mobicents.servlet.sip.security.AuthInfoEntry; import org.mobicents.servlet.sip.security.AuthInfoImpl; import org.mobicents.servlet.sip.security.authentication.DigestAuthenticator; import org.mobicents.servlet.sip.startup.StaticServiceHolder; import org.mobicents.servlet.sip.startup.loading.SipServletImpl; public class SipServletRequestImpl extends SipServletMessageImpl implements SipServletRequest { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(SipServletRequestImpl.class); private static final String EXCEPTION_MESSAGE = "The context does not allow you to modify this request !"; public static final Set<String> NON_INITIAL_SIP_REQUEST_METHODS = new HashSet<String>(); static { NON_INITIAL_SIP_REQUEST_METHODS.add("CANCEL"); NON_INITIAL_SIP_REQUEST_METHODS.add("BYE"); NON_INITIAL_SIP_REQUEST_METHODS.add("PRACK"); NON_INITIAL_SIP_REQUEST_METHODS.add("ACK"); NON_INITIAL_SIP_REQUEST_METHODS.add("UPDATE"); NON_INITIAL_SIP_REQUEST_METHODS.add("INFO"); }; /* Linked request (for b2bua) */ private SipServletRequestImpl linkedRequest; private boolean createDialog; /* * Popped route header - when we are the UAS we pop and keep the route * header */ private AddressImpl poppedRoute; private RouteHeader poppedRouteHeader; /* Cache the application routing directive in the record route header */ private SipApplicationRoutingDirective routingDirective = SipApplicationRoutingDirective.NEW; private RoutingState routingState; private transient SipServletResponse lastFinalResponse; private transient SipServletResponse lastInformationalResponse; /** * Routing region. */ private SipApplicationRoutingRegion routingRegion; private transient URI subscriberURI; private boolean isInitial; private boolean isFinalResponseGenerated; private boolean is1xxResponseGenerated; private transient boolean isReadOnly; // This field is only used in CANCEL requests where we need the INVITe transaction private transient Transaction inviteTransactionToCancel; public SipServletRequestImpl(Request request, SipFactoryImpl sipFactoryImpl, MobicentsSipSession sipSession, Transaction transaction, Dialog dialog, boolean createDialog) { super(request, sipFactoryImpl, transaction, sipSession, dialog); this.createDialog = createDialog; routingState = checkRoutingState(this, dialog); if(RoutingState.INITIAL.equals(routingState)) { isInitial = true; } isFinalResponseGenerated = false; } @Override public boolean isSystemHeader(String headerName) { String hName = getFullHeaderName(headerName); /* * Contact is a system header field in messages other than REGISTER * requests and responses, 3xx and 485 responses, and 200/OPTIONS * responses so it is not contained in system headers and as such * as a special treatment */ boolean isSystemHeader = JainSipUtils.SYSTEM_HEADERS.contains(hName); if (isSystemHeader) return isSystemHeader; boolean isContactSystem = false; Request request = (Request) this.message; String method = request.getMethod(); if (method.equals(Request.REGISTER)) { isContactSystem = false; } else { isContactSystem = true; } if (isContactSystem && hName.equals(ContactHeader.NAME)) { isSystemHeader = true; } else { isSystemHeader = false; } return isSystemHeader; } public SipServletRequest createCancel() { checkReadOnly(); if (!((Request) message).getMethod().equals(Request.INVITE)) { throw new IllegalStateException( "Cannot create CANCEL for non inivte"); } if (super.getTransaction() == null || super.getTransaction() instanceof ServerTransaction) throw new IllegalStateException("No client transaction found!"); if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || lastFinalResponse != null) { throw new IllegalStateException("final response already sent!"); } try { Request cancelRequest = ((ClientTransaction) getTransaction()) .createCancel(); SipServletRequestImpl newRequest = new SipServletRequestImpl( cancelRequest, sipFactoryImpl, getSipSession(), null, getTransaction().getDialog(), false); newRequest.inviteTransactionToCancel = super.getTransaction(); return newRequest; } catch (SipException ex) { throw new IllegalStateException("Could not create cancel", ex); } } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletRequest#createResponse(int) */ public SipServletResponse createResponse(int statusCode) { return createResponse(statusCode, null); } public SipServletResponse createResponse(final int statusCode, final String reasonPhrase) { return createResponse(statusCode, reasonPhrase, true); } public SipServletResponse createResponse(final int statusCode, final String reasonPhrase, boolean validate) { checkReadOnly(); final Transaction transaction = getTransaction(); if(RoutingState.CANCELLED.equals(routingState)) { throw new IllegalStateException("Cannot create a response for the invite, a CANCEL has been received and the INVITE was replied with a 487!"); } if (transaction == null || transaction instanceof ClientTransaction) { if(validate) { throw new IllegalStateException( "Cannot create a response - not a server transaction " + transaction); } } try { final Request request = (Request) this.getMessage(); final Response response = SipFactories.messageFactory.createResponse( statusCode, request); if(reasonPhrase!=null) { response.setReasonPhrase(reasonPhrase); } final MobicentsSipSession session = getSipSession(); final String requestMethod = getMethod(); //add a To tag for all responses except Trying (or trying too if it's a subsequent request) if((statusCode > Response.TRYING || !isInitial()) && statusCode <= Response.SESSION_NOT_ACCEPTABLE) { final ToHeader toHeader = (ToHeader) response .getHeader(ToHeader.NAME); // If we already have a to tag, dont create new if (toHeader.getTag() == null) { // if a dialog has already been created // reuse local tag final Dialog dialog = transaction.getDialog(); if(dialog != null && dialog.getLocalTag() != null && dialog.getLocalTag().length() > 0) { toHeader.setTag(dialog.getLocalTag()); } else if(session != null && session.getSipApplicationSession() != null) { final SipApplicationSessionKey sipAppSessionKey = session.getSipApplicationSession().getKey(); final SipSessionKey sipSessionKey = session.getKey(); // Fix for Issue 1044 : javax.sip.SipException: Tag mismatch dialogTag during process B2B response // make sure not to generate a new tag synchronized (this) { String toTag = sipSessionKey.getToTag(); if(toTag == null) { toTag = ApplicationRoutingHeaderComposer.getHash(sipFactoryImpl.getSipApplicationDispatcher(),sipSessionKey.getApplicationName(), sipAppSessionKey.getId()); session.getKey().setToTag(toTag); } toHeader.setTag(toTag); } } else { //if the sessions are null, it means it is a cancel response toHeader.setTag(Integer.toString(new Random().nextInt(10000000))); } } // Following restrictions in JSR 289 Section 4.1.3 Contact Header Field // + constraints from Issue 1687 : Contact Header is present in SIP Message where it shouldn't boolean setContactHeader = true; if ((statusCode >= 300 && statusCode < 400) || statusCode == 485 || Request.REGISTER.equals(requestMethod) || Request.OPTIONS.equals(requestMethod) || Request.BYE.equals(requestMethod) || Request.CANCEL.equals(requestMethod) || Request.PRACK.equals(requestMethod) || Request.MESSAGE.equals(requestMethod) || Request.PUBLISH.equals(requestMethod)) { // don't set the contact header in those case setContactHeader = false; } if(setContactHeader) { String outboundInterface = null; if(session != null) { outboundInterface = session.getOutboundInterface(); } // Add the contact header for the dialog. ContactHeader contactHeader = JainSipUtils.createContactHeader( super.sipFactoryImpl.getSipNetworkInterfaceManager(), request, null, outboundInterface); String transport = "udp"; if(session != null && session.getTransport() != null) transport = session.getTransport(); SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(transport); if(sipConnector != null && sipConnector.isUseStaticAddress()) { if(session != null && session.getProxy() == null) { boolean sipURI = contactHeader.getAddress().getURI().isSipURI(); if(sipURI) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) contactHeader.getAddress().getURI(); sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } } } if(logger.isDebugEnabled()) { logger.debug("We're adding this contact header to our new response: '" + contactHeader + ", transport=" + JainSipUtils.findTransport(request)); } response.setHeader(contactHeader); } } // Issue 1355 http://code.google.com/p/mobicents/issues/detail?id=1355 Not RFC compliant : // Application Routing : Adding the recorded route headers as route headers // final ListIterator<RecordRouteHeader> recordRouteHeaders = request.getHeaders(RecordRouteHeader.NAME); // while (recordRouteHeaders.hasNext()) { // RecordRouteHeader recordRouteHeader = (RecordRouteHeader) recordRouteHeaders // .next(); // RouteHeader routeHeader = SipFactories.headerFactory.createRouteHeader(recordRouteHeader.getAddress()); // response.addHeader(routeHeader); // } final SipServletResponseImpl newSipServletResponse = new SipServletResponseImpl(response, super.sipFactoryImpl, validate ? (ServerTransaction) transaction : transaction, session, getDialog(), false); newSipServletResponse.setOriginalRequest(this); if(!Request.PRACK.equals(requestMethod) && statusCode >= Response.OK && statusCode <= Response.SESSION_NOT_ACCEPTABLE) { isFinalResponseGenerated = true; } if(statusCode >= Response.TRYING && statusCode < Response.OK) { is1xxResponseGenerated = true; } return newSipServletResponse; } catch (ParseException ex) { throw new IllegalArgumentException("Bad status code" + statusCode, ex); } } public B2buaHelper getB2buaHelper() { checkReadOnly(); final MobicentsSipSession session = getSipSession(); if (session.getProxy() != null) throw new IllegalStateException("Proxy already present"); B2buaHelperImpl b2buaHelper = session.getB2buaHelper(); if (b2buaHelper != null) return b2buaHelper; b2buaHelper = new B2buaHelperImpl(); b2buaHelper.setSipFactoryImpl(sipFactoryImpl); b2buaHelper.setSipManager(session.getSipApplicationSession().getSipContext().getSipManager()); if(JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) { this.createDialog = true; // flag that we want to create a dialog for outgoing request. } session.setB2buaHelper(b2buaHelper); return b2buaHelper; } public ServletInputStream getInputStream() throws IOException { return null; } public int getMaxForwards() { return ((MaxForwardsHeader) ((Request) message) .getHeader(MaxForwardsHeader.NAME)).getMaxForwards(); } /* * (non-Javadoc) * * @see javax.servlet.sip.SipServletRequest#getPoppedRoute() */ public Address getPoppedRoute() { if((this.poppedRoute == null && poppedRouteHeader != null) || (poppedRoute != null && poppedRouteHeader != null && !poppedRoute.getAddress().equals(poppedRouteHeader.getAddress()))) { this.poppedRoute = new AddressImpl(poppedRouteHeader.getAddress(), null, getTransaction() == null ? true : false); } return poppedRoute; } public RouteHeader getPoppedRouteHeader() { return poppedRouteHeader; } /** * Set the popped route * * @param routeHeader * the popped route header to set */ public void setPoppedRoute(RouteHeader routeHeader) { this.poppedRouteHeader = routeHeader; } /** * {@inheritDoc} */ public Proxy getProxy() throws TooManyHopsException { checkReadOnly(); final MobicentsSipSession session = getSipSession(); if (session.getB2buaHelper() != null ) throw new IllegalStateException("Cannot proxy request"); return getProxy(true); } /** * {@inheritDoc} */ public Proxy getProxy(boolean create) throws TooManyHopsException { checkReadOnly(); final MobicentsSipSession session = getSipSession(); if (session.getB2buaHelper() != null ) throw new IllegalStateException("Cannot proxy request"); final MaxForwardsHeader mfHeader = (MaxForwardsHeader)this.message.getHeader(MaxForwardsHeader.NAME); if(mfHeader.getMaxForwards()<=0) { try { this.createResponse(Response.TOO_MANY_HOPS, "Too many hops").send(); } catch (IOException e) { throw new RuntimeException("could not send the Too many hops response out !", e); } throw new TooManyHopsException(); } // For requests like PUBLISH dialogs(sessions) do not exist, but some clients // attempt to send them in sequence as if they support dialogs and when such a subsequent request // comes in it gets assigned to the previous request session where the proxy is destroyed. // In this case we must create a new proxy. And we recoginze this case by additionally checking // if this request is initial. TODO: Consider deleting the session contents too? JSR 289 says // the session is keyed against the headers, not against initial/non-initial... if (create) { ProxyImpl proxy = session.getProxy(); boolean createNewProxy = false; if(isInitial() && proxy != null && proxy.getOriginalRequest() == null) { createNewProxy = true; } if(proxy == null || createNewProxy) { session.setProxy(new ProxyImpl(this, super.sipFactoryImpl)); } } return session.getProxy(); } /** * {@inheritDoc} */ public BufferedReader getReader() throws IOException { return null; } /** * {@inheritDoc} */ public URI getRequestURI() { Request request = (Request) super.message; if (request.getRequestURI() instanceof javax.sip.address.SipURI) return new SipURIImpl((javax.sip.address.SipURI) request .getRequestURI()); else if (request.getRequestURI() instanceof javax.sip.address.TelURL) return new TelURLImpl((javax.sip.address.TelURL) request .getRequestURI()); else throw new UnsupportedOperationException("Unsupported scheme"); } /** * {@inheritDoc} */ public boolean isInitial() { return isInitial; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletMessage#isCommitted() */ public boolean isCommitted() { //the message is an incoming request for which a final response has been generated if(getTransaction() instanceof ServerTransaction && (RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || isFinalResponseGenerated)) { return true; } //the message is an outgoing request which has been sent if(getTransaction() instanceof ClientTransaction && this.isMessageSent) { return true; } /* if(Request.ACK.equals((((Request)message).getMethod()))) { return true; }*/ return false; } protected void checkMessageState() { if(isMessageSent || getTransaction() instanceof ServerTransaction) { throw new IllegalStateException("Message already sent or incoming message"); } } /** * {@inheritDoc} */ public void pushPath(Address uri) { checkReadOnly(); if(!Request.REGISTER.equalsIgnoreCase(((Request)message).getMethod())) { throw new IllegalStateException("Cannot push a Path on a non REGISTER request !"); } if(uri.getURI() instanceof TelURL) { throw new IllegalArgumentException("Cannot push a TelUrl as a path !"); } if (logger.isDebugEnabled()) logger.debug("Pushing path into message of value [" + uri + "]"); try { javax.sip.header.Header p = SipFactories.headerFactory .createHeader(PathHeader.NAME, uri.toString()); this.message.addFirst(p); } catch (Exception e) { logger.error("Error while pushing path [" + uri + "]"); throw new IllegalArgumentException("Error pushing path ", e); } } /** * {@inheritDoc} */ public void pushRoute(Address address) { checkReadOnly(); if(address.getURI() instanceof TelURL) { throw new IllegalArgumentException("Cannot push a TelUrl as a route !"); } javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) ((AddressImpl) address) .getAddress().getURI(); pushRoute(sipUri); } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletRequest#pushRoute(javax.servlet.sip.SipURI) */ public void pushRoute(SipURI uri) { checkReadOnly(); javax.sip.address.SipURI sipUri = ((SipURIImpl) uri).getSipURI(); sipUri.setLrParam(); pushRoute(sipUri); } /** * Pushes a route header on initial request based on the jain sip sipUri given on parameter * @param sipUri the jain sip sip uri to use to construct the route header to push on the request */ private void pushRoute(javax.sip.address.SipURI sipUri) { if(isInitial()) { if (logger.isDebugEnabled()) logger.debug("Pushing route into message of value [" + sipUri + "]"); sipUri.setLrParam(); try { javax.sip.header.Header p = SipFactories.headerFactory .createRouteHeader(SipFactories.addressFactory .createAddress(sipUri)); this.message.addFirst(p); } catch (SipException e) { logger.error("Error while pushing route [" + sipUri + "]"); throw new IllegalArgumentException("Error pushing route ", e); } } else { //as per JSR 289 Section 11.1.3 Pushing Route Header Field Values // pushRoute can only be done on the initial requests. // Subsequent requests within a dialog follow the route set. // Any attempt to do a pushRoute on a subsequent request in a dialog // MUST throw and IllegalStateException. throw new IllegalStateException("Cannot push route on subsequent requests, only intial ones"); } } public void setMaxForwards(int n) { checkReadOnly(); MaxForwardsHeader mfh = (MaxForwardsHeader) this.message .getHeader(MaxForwardsHeader.NAME); try { if (mfh != null) { mfh.setMaxForwards(n); } } catch (Exception ex) { String s = "Error while setting max forwards"; logger.error(s, ex); throw new IllegalArgumentException(s, ex); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletRequest#setRequestURI(javax.servlet.sip.URI) */ public void setRequestURI(URI uri) { checkReadOnly(); Request request = (Request) message; URIImpl uriImpl = (URIImpl) uri; javax.sip.address.URI wrappedUri = uriImpl.getURI(); request.setRequestURI(wrappedUri); //TODO look through all contacts of the user and change them depending of if STUN is enabled //and the request is aimed to the local network or outside } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletRequest#setRoutingDirective(javax.servlet.sip.SipApplicationRoutingDirective, javax.servlet.sip.SipServletRequest) */ public void setRoutingDirective(SipApplicationRoutingDirective directive, SipServletRequest origRequest) throws IllegalStateException { checkReadOnly(); SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest; final MobicentsSipSession session = getSipSession(); //@jean.deruelle Commenting this out, why origRequestImpl.isCommitted() is needed ? // if ((directive == SipApplicationRoutingDirective.REVERSE || directive == SipApplicationRoutingDirective.CONTINUE) // && (!origRequestImpl.isInitial() || origRequestImpl.isCommitted())) { // If directive is CONTINUE or REVERSE, the parameter origRequest must be an //initial request dispatched by the container to this application, //i.e. origRequest.isInitial() must be true if ((directive == SipApplicationRoutingDirective.REVERSE || directive == SipApplicationRoutingDirective.CONTINUE)){ if(origRequestImpl == null || !origRequestImpl.isInitial()) { if(logger.isDebugEnabled()) { logger.debug("directive to set : " + directive); logger.debug("Original Request Routing State : " + origRequestImpl.getRoutingState()); } throw new IllegalStateException( "Bad state -- cannot set routing directive"); } else { //set AR State Info from previous request session.setStateInfo(origRequestImpl.getSipSession().getStateInfo()); //needed for application composition currentApplicationName = origRequestImpl.getCurrentApplicationName(); //linking the requests //FIXME one request can be linked to many more as for B2BUA origRequestImpl.setLinkedRequest(this); setLinkedRequest(origRequestImpl); } } else { //This request must be a request created in a new SipSession //or from an initial request, and must not have been sent. //If any one of these preconditions are not met, the method throws an IllegalStateException. Set<Transaction> ongoingTransactions = session.getOngoingTransactions(); if(!State.INITIAL.equals(session.getState()) && ongoingTransactions != null && ongoingTransactions.size() > 0) { if(logger.isDebugEnabled()) { logger.debug("session state : " + session.getState()); logger.debug("numbers of ongoing transactions : " + ongoingTransactions.size()); } throw new IllegalStateException( "Bad state -- cannot set routing directive"); } } routingDirective = directive; linkedRequest = origRequestImpl; //@jean.deruelle Commenting this out, is this really needed ? // RecordRouteHeader rrh = (RecordRouteHeader) request // .getHeader(RecordRouteHeader.NAME); // javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) rrh // .getAddress().getURI(); // // try { // if (directive == SipApplicationRoutingDirective.NEW) { // sipUri.setParameter("rd", "NEW"); // } else if (directive == SipApplicationRoutingDirective.REVERSE) { // sipUri.setParameter("rd", "REVERSE"); // } else if (directive == SipApplicationRoutingDirective.CONTINUE) { // sipUri.setParameter("rd", "CONTINUE"); // } // // } catch (Exception ex) { // String s = "error while setting routing directive"; // logger.error(s, ex); // throw new IllegalArgumentException(s, ex); // } } /* * (non-Javadoc) * * @see javax.servlet.ServletRequest#getLocalName() */ public String getLocalName() { // TODO Auto-generated method stub return null; } public Locale getLocale() { // TODO Auto-generated method stub return null; } public Enumeration getLocales() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see javax.servlet.ServletRequest#getParameter(java.lang.String) */ public String getParameter(String name) { // JSR 289 Section 5.6.1 Parameters : // For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header. // For initial requests where the application is invoked the parameters are those present on the request URI, // if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined. // For subsequent requests in a dialog, the parameters presented to the application are those that the application itself // set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters). // These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a // "strict router" they may be returned in the request URI (see RFC 3261). // It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly. if(this.getPoppedRoute() != null) { return this.getPoppedRoute().getURI().getParameter(name); } else { return this.getRequestURI().getParameter(name); } } /* * (non-Javadoc) * @see javax.servlet.ServletRequest#getParameterMap() */ public Map<String, String> getParameterMap() { // JSR 289 Section 5.6.1 Parameters : // For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header. // For initial requests where the application is invoked the parameters are those present on the request URI, // if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined. // For subsequent requests in a dialog, the parameters presented to the application are those that the application itself // set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters). // These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a // "strict router" they may be returned in the request URI (see RFC 3261). // It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly. HashMap<String, String> retval = new HashMap<String, String>(); if(this.getPoppedRoute() != null) { Iterator<String> parameterNamesIt = this.getPoppedRoute().getURI().getParameterNames(); while (parameterNamesIt.hasNext()) { String parameterName = parameterNamesIt.next(); retval.put(parameterName, this.getPoppedRoute().getURI().getParameter(parameterName)); } } else { Iterator<String> parameterNamesIt = this.getRequestURI().getParameterNames(); while (parameterNamesIt.hasNext()) { String parameterName = parameterNamesIt.next(); retval.put(parameterName, this.getRequestURI().getParameter(parameterName)); } } return retval; } /* * (non-Javadoc) * @see javax.servlet.ServletRequest#getParameterNames() */ public Enumeration<String> getParameterNames() { // JSR 289 Section 5.6.1 Parameters : // For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header. // For initial requests where the application is invoked the parameters are those present on the request URI, // if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined. // For subsequent requests in a dialog, the parameters presented to the application are those that the application itself // set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters). // These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a // "strict router" they may be returned in the request URI (see RFC 3261). // It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly. Vector<String> retval = new Vector<String>(); if(this.getPoppedRoute() != null) { Iterator<String> parameterNamesIt = this.getPoppedRoute().getURI().getParameterNames(); while (parameterNamesIt.hasNext()) { String parameterName = parameterNamesIt.next(); retval.add(parameterName); } } else { Iterator<String> parameterNamesIt = this.getRequestURI().getParameterNames(); while (parameterNamesIt.hasNext()) { String parameterName = parameterNamesIt.next(); retval.add(parameterName); } } return retval.elements(); } /* * (non-Javadoc) * * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String) */ public String[] getParameterValues(String name) { // JSR 289 Section 5.6.1 Parameters : // The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name. // The value returned from the getParameter method must always equal the first value in the array of String objects returned by getParameterValues. // Note:Support for multi-valued parameters is defined mainly for HTTP because HTML forms may contain multi-valued parameters in form submissions. return new String[] {getParameter(name)}; } public String getRealPath(String arg0) { // TODO Auto-generated method stub return null; } public String getRemoteHost() { // TODO Auto-generated method stub return null; } /** * {@inheritDoc} */ public RequestDispatcher getRequestDispatcher(String handler) { SipServletImpl sipServletImpl = (SipServletImpl) getSipSession().getSipApplicationSession().getSipContext().findChildrenByName(handler); if(sipServletImpl == null) { throw new IllegalArgumentException(handler + " is not a valid servlet name"); } return new SipRequestDispatcher(sipServletImpl); } public String getScheme() { return ((Request)message).getRequestURI().getScheme(); } public String getServerName() { // TODO Auto-generated method stub return null; } public int getServerPort() { // TODO Auto-generated method stub return 0; } /** * @return the routingDirective */ public SipApplicationRoutingDirective getRoutingDirective() { if(!isInitial()) { throw new IllegalStateException("the request is not initial"); } return routingDirective; } public static void optimizeRouteHeaderAddressForInternalRoutingrequest(SipConnector sipConnector, Request request, MobicentsSipSession session, SipFactoryImpl sipFactoryImpl, String transport) { SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager(); RouteHeader rh = (RouteHeader) request.getHeader(RouteHeader.NAME); if(rh != null) { javax.sip.address.URI uri = rh.getAddress().getURI(); if(uri.isSipURI()) { try { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; boolean isExternal = sipFactoryImpl.getSipApplicationDispatcher().isExternal(sipUri.getHost(), sipUri.getPort(), transport); if(!isExternal) { if(logger.isDebugEnabled()) { logger.debug("The request is going internally due to RR = " + rh); } ExtendedListeningPoint lp = null; if(session.getOutboundInterface() != null) { javax.sip.address.SipURI outboundInterfaceURI = (javax.sip.address.SipURI) SipFactories.addressFactory.createURI(session.getOutboundInterface()); lp = sipNetworkInterfaceManager.findMatchingListeningPoint(outboundInterfaceURI, false); } else { lp = sipNetworkInterfaceManager.findMatchingListeningPoint(transport, false); } sipUri.setHost(lp.getHost(false)); sipUri.setPort(lp.getPort()); sipUri.setTransportParam(lp.getTransport()); } } catch (ParseException e) { logger.error("AR optimization error", e); } } } } /* * (non-Javadoc) * * @see org.mobicents.servlet.sip.message.SipServletMessageImpl#send() */ @Override public void send() { checkReadOnly(); final Request request = (Request) super.message; final MobicentsSipSession session = getSipSession(); try { ProxyImpl proxy = null; if(session != null) { proxy = session.getProxy(); } final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager(); final String sessionTransport = session.getTransport(); if(logger.isDebugEnabled()) { logger.debug("session transport is " + sessionTransport); } ((MessageExt)message).setApplicationData(sessionTransport); ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME); //Issue 112 fix by folsson if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) { boolean addViaHeader = false; if(proxy == null) { addViaHeader = true; } else if(isInitial) { if(proxy.getRecordRoute()) { addViaHeader = true; } } else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) { addViaHeader = true; } if(addViaHeader) { // Issue viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, null, session.getOutboundInterface()); message.addHeader(viaHeader); if(logger.isDebugEnabled()) { logger.debug("Added via Header" + viaHeader); } } } else { if(getMethod().equalsIgnoreCase(Request.CANCEL)) { if(getSipSession().getState().equals(State.INITIAL)) { Transaction tx = inviteTransactionToCancel; if(tx != null) { logger.debug("Can not send CANCEL. Will try to STOP retransmissions " + tx); // We still haven't received any response on this call, so we can not send CANCEL, // we will just stop the retransmissions StaticServiceHolder.disableRetransmissionTimer.invoke(tx); if(tx.getApplicationData() instanceof TransactionApplicationData) { TransactionApplicationData tad = (TransactionApplicationData) tx.getApplicationData(); tad.setCanceled(true); } return; } else { logger.debug("Can not send CANCEL because noe response arrived. " + "Can not stop retransmissions. The transaction is null"); } } } } final String transport = JainSipUtils.findTransport(request); if(sessionTransport == null) { session.setTransport(transport); } if(logger.isDebugEnabled()) { logger.debug("The found transport for sending request is '" + transport + "'"); } SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(transport); // Bypass the load balancer for outgoing requests by removing the route header for them if(sipConnector != null && sipConnector.isUseStaticAddress()) { RouteHeader rh = (RouteHeader) request.getHeader(RouteHeader.NAME); if(logger.isDebugEnabled()) { logger.debug("We are looking at route header " + rh + " and SC is" + sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort()); } if(rh != null) { if(rh.getAddress().getURI().isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI)rh.getAddress().getURI(); if(sipUri.getHost().equals(sipConnector.getStaticServerAddress())) { int port = sipUri.getPort(); if(port <= 0) port = 5060; if(port == sipConnector.getStaticServerPort()) { request.removeHeader(RouteHeader.NAME); } } } } } final String requestMethod = getMethod(); if(Request.ACK.equals(requestMethod)) { session.getSessionCreatingDialog().sendAck(request); final Transaction transaction = getTransaction(); final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); final B2buaHelperImpl b2buaHelperImpl = sipSession.getB2buaHelper(); - if(b2buaHelperImpl != null) { + if(b2buaHelperImpl != null && tad != null) { // we unlink the originalRequest early to avoid keeping the messages in mem for too long b2buaHelperImpl.unlinkOriginalRequestInternal((SipServletRequestImpl)tad.getSipServletMessage()); } - session.removeOngoingTransaction(transaction); - tad.cleanUp(); + session.removeOngoingTransaction(transaction); + if(tad != null) { + tad.cleanUp(); + } final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); // Issue 1468 : to handle forking, we shouldn't cleanup the app data since it is needed for the forked responses if(((SipStackImpl)sipProvider.getSipStack()).getMaxForkTime() == 0) { transaction.setApplicationData(null); } return; } //Added for initial requests only (that are not REGISTER) not for subsequent requests if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) { // Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29 // if(session.getProxy() != null && // session.getProxy().getRecordRoute()) // If the app is proxying it already does that // { // if(logger.isDebugEnabled()) { // logger.debug("Add a record route header for app composition "); // } // getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); // //Add a record route header for app composition // addAppCompositionRRHeader(); // } final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are interested."); } //Adding Route Header for LB if we are in a HA configuration if(sipFactoryImpl.isUseLoadBalancer() && isInitial) { sipFactoryImpl.addLoadBalancerRouteHeader(request); if(logger.isDebugEnabled()) { logger.debug("adding route to Load Balancer since we are in a HA configuration " + " and no more apps are interested."); } } } } final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession(); if(viaHeader.getBranch() == null) { final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName())); viaHeader.setBranch(branch); } if(logger.isDebugEnabled()) { getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); } if (super.getTransaction() == null) { ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME); if(contactHeader == null && !Request.REGISTER.equalsIgnoreCase(requestMethod) && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) { final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME); final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI(); String fromName = null; if(fromUri instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromUri).getUser(); } // Create the contact name address. contactHeader = JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface()); request.addHeader(contactHeader); } if(sipConnector != null && sipConnector.isUseStaticAddress()) { if(proxy == null && contactHeader != null) { boolean sipURI = contactHeader.getAddress().getURI().isSipURI(); if(sipURI) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) contactHeader.getAddress().getURI(); sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } } } if(logger.isDebugEnabled()) { logger.debug("Getting new Client Tx for request " + request); } final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); /* * If we the next hop is in this container we optimize the traffic by directing it here instead of going through load balancers. * This is must be done before creating the transaction, otherwise it will go to the host/port specified prior to the changes here. */ if(!isInitial() && sipConnector != null && // Initial requests already use local address in RouteHeader. sipConnector.isUseStaticAddress()) { optimizeRouteHeaderAddressForInternalRoutingrequest(sipConnector, request, session, sipFactoryImpl, transport); } final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); Dialog dialog = ctx.getDialog(); if(session.getProxy() != null) { // no dialogs in proxy dialog = null; // take care of the RRH if(isInitial()) { if(session.getProxy().getRecordRoute()) { RecordRouteHeader rrh = (RecordRouteHeader) request.getHeader(RecordRouteHeader.NAME); if(rrh == null) { if(logger.isDebugEnabled()) { logger.debug("Unexpected RRH = null for this request" + request); } } else { javax.sip.address.URI uri = rrh.getAddress().getURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; if(sipConnector != null && sipConnector.isUseStaticAddress()) { sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } sipUri.setTransportParam(transport); if(logger.isDebugEnabled()) { logger.debug("Updated the RRH with static server address " + sipUri); } } } } } } if (dialog == null && this.createDialog && JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) { dialog = sipProvider.getNewDialog(ctx); ((DialogExt)dialog).disableSequenceNumberValidation(); session.setSessionCreatingDialog(dialog); if(logger.isDebugEnabled()) { logger.debug("new Dialog for request " + request + ", ref = " + dialog); } } //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { final Transaction linkedTransaction = linkedRequest.getTransaction(); final Dialog linkedDialog = linkedRequest.getDialog(); //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx); if(linkedDialog != null && linkedDialog.getApplicationData() != null) { ((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedTransaction); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction); } } // Make the dialog point here so that when the dialog event // comes in we can find the session quickly. if (dialog != null) { dialog.setApplicationData(this.transactionApplicationData); } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); super.setTransaction(ctx); session.setSessionCreatingTransactionRequest(this); } else if (Request.PRACK.equals(request.getMethod())) { final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx); if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) { ((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedRequest.getTransaction()); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction()); } } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); setTransaction(ctx); } else { if(logger.isDebugEnabled()) { logger.debug("Transaction is not null, where was it created? " + getTransaction()); } } //tells the application dispatcher to stop routing the linked request // (in this case it would be the original request) since it has been relayed if(linkedRequest != null && !SipApplicationRoutingDirective.NEW.equals(routingDirective)) { if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) { linkedRequest.setRoutingState(RoutingState.RELAYED); } } if(!Request.ACK.equals(getMethod())) { session.addOngoingTransaction(getTransaction()); } // Update Session state session.updateStateOnSubsequentRequest(this, false); // Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481 // proxy should not add or remove subscription since there is no dialog associated with it if(Request.NOTIFY.equals(getMethod()) && session.getProxy() == null) { final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) getMessage().getHeader(SubscriptionStateHeader.NAME); // RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates // a new subscription and a new dialog (unless they have already been // created by a matching response, as described above). if (subscriptionStateHeader != null && (SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) || SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) { session.addSubscription(this); } // A subscription is destroyed when a notifier sends a NOTIFY request // with a "Subscription-State" of "terminated". if (subscriptionStateHeader != null && SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) { session.removeSubscription(this); } } updateContactHeaderTransport(transport); //updating the last accessed times session.access(); sipApplicationSession.access(); Dialog dialog = getDialog(); if(session.getProxy() != null) dialog = null; // If dialog does not exist or has no state. if (dialog == null || dialog.getState() == null || (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod)) || Request.CANCEL.equals(requestMethod)) { if(logger.isDebugEnabled()) { logger.debug("Sending the request " + request); } ((ClientTransaction) super.getTransaction()).sendRequest(); } else { // This is a subsequent (an in-dialog) request. // we don't redirect it to the container for now if(logger.isDebugEnabled()) { logger.debug("Sending the in dialog request " + request); } dialog.sendRequest((ClientTransaction) getTransaction()); } isMessageSent = true; } catch (Exception ex) { throw new IllegalStateException("Error sending request " + request,ex); } } protected void updateContactHeaderTransport(String transport) throws ParseException { ContactHeader contactHeader = (ContactHeader)message.getHeader(ContactHeader.NAME); if(contactHeader != null) { // We need to update the originally created contact header if the request changed the transport javax.sip.address.URI uri = contactHeader.getAddress().getURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; // It is always UDP by default, so we only need to modify it if it is different that UDP if(!transport.equalsIgnoreCase("udp")) { sipUri.setTransportParam(transport); } } } } /** * Add a route header to route back to the container * @param applicationName the application name that was chosen by the AR to route the request * @throws ParseException * @throws SipException * @throws NullPointerException */ public void addInfoForRoutingBackToContainer(SipApplicationRouterInfo routerInfo, String applicationSessionId, String applicationName) throws ParseException, SipException { final Request request = (Request) super.message; final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), request); sipURI.setLrParam(); sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_DIRECTIVE, routingDirective.toString()); if(getSipSession().getRegionInternal() != null) { sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_REGION_LABEL, getSipSession().getRegionInternal().getLabel()); sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_REGION_TYPE, getSipSession().getRegionInternal().getType().toString()); } sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_PREV_APPLICATION_NAME, applicationName); sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_PREV_APP_ID, applicationSessionId); final javax.sip.address.Address routeAddress = SipFactories.addressFactory.createAddress(sipURI); final RouteHeader routeHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); request.addFirst(routeHeader); // adding the application router info to avoid calling the AppRouter twice // See Issue 791 : http://code.google.com/p/mobicents/issues/detail?id=791 final MobicentsSipSession session = getSipSession(); session.setNextSipApplicationRouterInfo(routerInfo); } /** * Add a record route header for app composition * @throws ParseException if anything goes wrong while creating the record route header * @throws SipException * @throws NullPointerException public void addAppCompositionRRHeader() throws ParseException, SipException { final Request request = (Request) super.message; final MobicentsSipSession session = getSipSession(); javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), request); sipURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, session.getKey().getApplicationName()); sipURI.setLrParam(); javax.sip.address.Address recordRouteAddress = SipFactories.addressFactory.createAddress(sipURI); RecordRouteHeader recordRouteHeader = SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress); request.addFirst(recordRouteHeader); }*/ public void setLinkedRequest(SipServletRequestImpl linkedRequest) { this.linkedRequest = linkedRequest; } public SipServletRequestImpl getLinkedRequest() { return this.linkedRequest; } /** * @return the routingState */ public RoutingState getRoutingState() { return routingState; } /** * @param routingState the routingState to set */ public void setRoutingState(RoutingState routingState) throws IllegalStateException { //JSR 289 Section 11.2.3 && 10.2.6 if(routingState.equals(RoutingState.CANCELLED) && (this.routingState.equals(RoutingState.FINAL_RESPONSE_SENT) || this.routingState.equals(RoutingState.PROXIED))) { throw new IllegalStateException("Cannot cancel final response already sent!"); } if((routingState.equals(RoutingState.FINAL_RESPONSE_SENT)|| routingState.equals(RoutingState.PROXIED)) && this.routingState.equals(RoutingState.CANCELLED)) { throw new IllegalStateException("Cancel received and already replied with a 487!"); } if(routingState.equals(RoutingState.SUBSEQUENT)) { isInitial = false; } this.routingState = routingState; } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, javax.servlet.sip.AuthInfo) */ public void addAuthHeader(SipServletResponse challengeResponse, AuthInfo authInfo) { checkReadOnly(); AuthInfoImpl authInfoImpl = (AuthInfoImpl) authInfo; SipServletResponseImpl challengeResponseImpl = (SipServletResponseImpl) challengeResponse; Response response = (Response) challengeResponseImpl.getMessage(); // First check for WWWAuthentication headers ListIterator authHeaderIterator = response.getHeaders(WWWAuthenticateHeader.NAME); while(authHeaderIterator.hasNext()) { WWWAuthenticateHeader wwwAuthHeader = (WWWAuthenticateHeader) authHeaderIterator.next(); // String uri = wwwAuthHeader.getParameter("uri"); AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm()); if(authInfoEntry == null) throw new SecurityException( "Cannot add authorization header. No credentials for the following realm: " + wwwAuthHeader.getRealm()); addChallengeResponse(wwwAuthHeader, authInfoEntry.getUserName(), authInfoEntry.getPassword(), this.getRequestURI().toString()); } // Now check for Proxy-Authentication authHeaderIterator = response.getHeaders(ProxyAuthenticateHeader.NAME); while(authHeaderIterator.hasNext()) { ProxyAuthenticateHeader wwwAuthHeader = (ProxyAuthenticateHeader) authHeaderIterator.next(); // String uri = wwwAuthHeader.getParameter("uri"); AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm()); if(authInfoEntry == null) throw new SecurityException( "No credentials for the following realm: " + wwwAuthHeader.getRealm()); addChallengeResponse(wwwAuthHeader, authInfoEntry.getUserName(), authInfoEntry.getPassword(), this.getRequestURI().toString()); } } /* * (non-Javadoc) * @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, java.lang.String, java.lang.String) */ public void addAuthHeader(SipServletResponse challengeResponse, String username, String password) { checkReadOnly(); SipServletResponseImpl challengeResponseImpl = (SipServletResponseImpl) challengeResponse; Response response = (Response) challengeResponseImpl.getMessage(); ListIterator authHeaderIterator = response.getHeaders(WWWAuthenticateHeader.NAME); // First while(authHeaderIterator.hasNext()) { WWWAuthenticateHeader wwwAuthHeader = (WWWAuthenticateHeader) authHeaderIterator.next(); // String uri = wwwAuthHeader.getParameter("uri"); addChallengeResponse(wwwAuthHeader, username, password, this.getRequestURI().toString()); } authHeaderIterator = response.getHeaders(ProxyAuthenticateHeader.NAME); while(authHeaderIterator.hasNext()) { ProxyAuthenticateHeader wwwAuthHeader = (ProxyAuthenticateHeader) authHeaderIterator.next(); String uri = wwwAuthHeader.getParameter("uri"); if(uri == null) uri = this.getRequestURI().toString(); addChallengeResponse(wwwAuthHeader, username, password, uri); } } private void addChallengeResponse( WWWAuthenticateHeader wwwAuthHeader, String username, String password, String uri) { AuthorizationHeader authorization = DigestAuthenticator.getAuthorizationHeader( getMethod(), uri, "", // TODO: What is this entity-body? wwwAuthHeader, username, password); message.addHeader(authorization); } /** * @return the finalResponse */ public SipServletResponse getLastFinalResponse() { return lastFinalResponse; } /** * @param finalResponse the finalResponse to set */ public void setResponse(SipServletResponseImpl response) { if(response.getStatus() >= 200 && (lastFinalResponse == null || lastFinalResponse.getStatus() < response.getStatus())) { this.lastFinalResponse = response; } // we keep the last informational response for noPrackReceived only if(containsRel100(response.getMessage()) && (response.getStatus() > 100 && response.getStatus() < 200) && (lastInformationalResponse == null || lastInformationalResponse.getStatus() < response.getStatus())) { this.lastInformationalResponse = response; } } /** * {@inheritDoc} */ public Address getInitialPoppedRoute() { return transactionApplicationData.getInitialPoppedRoute(); } /** * {@inheritDoc} */ public SipApplicationRoutingRegion getRegion() { return routingRegion; } /** * This method allows the application to set the region that the application * is in with respect to this SipSession * @param routingRegion the region that the application is in */ public void setRoutingRegion(SipApplicationRoutingRegion routingRegion) { this.routingRegion = routingRegion; } /** * {@inheritDoc} */ public URI getSubscriberURI() { return subscriberURI; } public void setSubscriberURI(URI uri) { this.subscriberURI = uri; } /** * Method checking whether or not the sip servlet request in parameter is initial * according to algorithm defined in JSR289 Appendix B * @param sipServletRequest the sip servlet request to check * @param dialog the dialog associated with this request * @return true if the request is initial false otherwise */ private static RoutingState checkRoutingState(SipServletRequestImpl sipServletRequest, Dialog dialog) { // 2. Ongoing Transaction Detection - Employ methods of Section 17.2.3 in RFC 3261 //to see if the request matches an existing transaction. //If it does, stop. The request is not an initial request. if(dialog != null && DialogState.CONFIRMED.equals(dialog.getState())) { return RoutingState.SUBSEQUENT; } // 3. Examine Request Method. If it is CANCEL, BYE, PRACK or ACK, stop. //The request is not an initial request for which application selection occurs. if(NON_INITIAL_SIP_REQUEST_METHODS.contains(sipServletRequest.getMethod())) { return RoutingState.SUBSEQUENT; } // 4. Existing Dialog Detection - If the request has a tag in the To header field, // the container computes the dialog identifier (as specified in section 12 of RFC 3261) // corresponding to the request and compares it with existing dialogs. // If it matches an existing dialog, stop. The request is not an initial request. // The request is a subsequent request and must be routed to the application path // associated with the existing dialog. // If the request has a tag in the To header field, // but the dialog identifier does not match any existing dialogs, // the container must reject the request with a 481 (Call/Transaction Does Not Exist). // Note: When this occurs, RFC 3261 says either the UAS has crashed or the request was misrouted. // In the latter case, the misrouted request is best handled by rejecting the request. // For the Sip Servlet environment, a UAS crash may mean either an application crashed // or the container itself crashed. In either case, it is impossible to route the request // as a subsequent request and it is inappropriate to route it as an initial request. // Therefore, the only viable approach is to reject the request. if(dialog != null && !DialogState.EARLY.equals(dialog.getState())) { return RoutingState.SUBSEQUENT; } // 6. Detection of Requests Sent to Encoded URIs - // Requests may be sent to a container instance addressed to a URI obtained by calling // the encodeURI() method of a SipApplicationSession managed by this container instance. // When a container receives such a request, stop. This request is not an initial request. // Refer to section 15.11.1 Session Targeting and Application Selection //for more information on how a request sent to an encoded URI is handled by the container. //This part will be done in routeIntialRequest since this is where the Session Targeting retrieval is done return RoutingState.INITIAL; } /** * @return the is1xxResponseGenerated */ public boolean is1xxResponseGenerated() { return is1xxResponseGenerated; } /** * @return the isFinalResponseGenerated */ public boolean isFinalResponseGenerated() { return isFinalResponseGenerated; } /** * @return the lastInformationalResponse */ public SipServletResponse getLastInformationalResponse() { return lastInformationalResponse; } public void setReadOnly(boolean isReadOnly) { this.isReadOnly = isReadOnly; } protected void checkReadOnly() { if(isReadOnly) { throw new IllegalStateException(EXCEPTION_MESSAGE); } } @Override public void addAcceptLanguage(Locale locale) { checkReadOnly(); super.addAcceptLanguage(locale); } @Override public void addAddressHeader(String name, Address addr, boolean first) throws IllegalArgumentException { checkReadOnly(); super.addAddressHeader(name, addr, first); } @Override public void addHeader(String name, String value) { checkReadOnly(); super.addHeader(name, value); } @Override public void addParameterableHeader(String name, Parameterable param, boolean first) { checkReadOnly(); super.addParameterableHeader(name, param, first); } @Override public void removeAttribute(String name) { checkReadOnly(); super.removeAttribute(name); } @Override public void removeHeader(String name) { checkReadOnly(); super.removeHeader(name); } @Override public void setAcceptLanguage(Locale locale) { checkReadOnly(); super.setAcceptLanguage(locale); } @Override public void setAddressHeader(String name, Address addr) { checkReadOnly(); super.setAddressHeader(name, addr); } @Override public void setAttribute(String name, Object o) { checkReadOnly(); super.setAttribute(name, o); } @Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { checkReadOnly(); super.setCharacterEncoding(enc); } @Override public void setContent(Object content, String contentType) throws UnsupportedEncodingException { checkReadOnly(); super.setContent(content, contentType); } @Override public void setContentLanguage(Locale locale) { checkReadOnly(); super.setContentLanguage(locale); } @Override public void setContentType(String type) { checkReadOnly(); super.setContentType(type); } @Override public void setExpires(int seconds) { checkReadOnly(); super.setExpires(seconds); } @Override public void setHeader(String name, String value) { checkReadOnly(); super.setHeader(name, value); } @Override public void setHeaderForm(HeaderForm form) { checkReadOnly(); super.setHeaderForm(form); } @Override public void setParameterableHeader(String name, Parameterable param) { checkReadOnly(); super.setParameterableHeader(name, param); } /** * {@inheritDoc} */ public String getInitialRemoteAddr() { if(((SIPTransaction)getTransaction()).getPeerPacketSourceAddress() != null) { return ((SIPTransaction)getTransaction()).getPeerPacketSourceAddress().getHostAddress(); } else { return ((SIPTransaction)getTransaction()).getPeerAddress(); } } /** * {@inheritDoc} */ public int getInitialRemotePort() { if(((SIPTransaction)getTransaction()).getPeerPacketSourceAddress() != null) { return ((SIPTransaction)getTransaction()).getPeerPacketSourcePort(); } else { return ((SIPTransaction)getTransaction()).getPeerPort(); } } /** * {@inheritDoc} */ public String getInitialTransport() { return ((SIPTransaction)getTransaction()).getTransport(); } public void cleanUp() { // super.cleanUp(); if(transactionApplicationData != null) { transactionApplicationData.cleanUp(); transactionApplicationData = null; } setTransaction(null); poppedRoute =null; poppedRouteHeader = null; routingDirective =null; routingRegion = null; routingState = null; subscriberURI = null; // lastFinalResponse = null; // lastInformationalResponse = null; linkedRequest = null; } public void cleanUpLastResponses() { lastFinalResponse = null; lastInformationalResponse = null; } }
false
true
public void send() { checkReadOnly(); final Request request = (Request) super.message; final MobicentsSipSession session = getSipSession(); try { ProxyImpl proxy = null; if(session != null) { proxy = session.getProxy(); } final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager(); final String sessionTransport = session.getTransport(); if(logger.isDebugEnabled()) { logger.debug("session transport is " + sessionTransport); } ((MessageExt)message).setApplicationData(sessionTransport); ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME); //Issue 112 fix by folsson if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) { boolean addViaHeader = false; if(proxy == null) { addViaHeader = true; } else if(isInitial) { if(proxy.getRecordRoute()) { addViaHeader = true; } } else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) { addViaHeader = true; } if(addViaHeader) { // Issue viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, null, session.getOutboundInterface()); message.addHeader(viaHeader); if(logger.isDebugEnabled()) { logger.debug("Added via Header" + viaHeader); } } } else { if(getMethod().equalsIgnoreCase(Request.CANCEL)) { if(getSipSession().getState().equals(State.INITIAL)) { Transaction tx = inviteTransactionToCancel; if(tx != null) { logger.debug("Can not send CANCEL. Will try to STOP retransmissions " + tx); // We still haven't received any response on this call, so we can not send CANCEL, // we will just stop the retransmissions StaticServiceHolder.disableRetransmissionTimer.invoke(tx); if(tx.getApplicationData() instanceof TransactionApplicationData) { TransactionApplicationData tad = (TransactionApplicationData) tx.getApplicationData(); tad.setCanceled(true); } return; } else { logger.debug("Can not send CANCEL because noe response arrived. " + "Can not stop retransmissions. The transaction is null"); } } } } final String transport = JainSipUtils.findTransport(request); if(sessionTransport == null) { session.setTransport(transport); } if(logger.isDebugEnabled()) { logger.debug("The found transport for sending request is '" + transport + "'"); } SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(transport); // Bypass the load balancer for outgoing requests by removing the route header for them if(sipConnector != null && sipConnector.isUseStaticAddress()) { RouteHeader rh = (RouteHeader) request.getHeader(RouteHeader.NAME); if(logger.isDebugEnabled()) { logger.debug("We are looking at route header " + rh + " and SC is" + sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort()); } if(rh != null) { if(rh.getAddress().getURI().isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI)rh.getAddress().getURI(); if(sipUri.getHost().equals(sipConnector.getStaticServerAddress())) { int port = sipUri.getPort(); if(port <= 0) port = 5060; if(port == sipConnector.getStaticServerPort()) { request.removeHeader(RouteHeader.NAME); } } } } } final String requestMethod = getMethod(); if(Request.ACK.equals(requestMethod)) { session.getSessionCreatingDialog().sendAck(request); final Transaction transaction = getTransaction(); final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); final B2buaHelperImpl b2buaHelperImpl = sipSession.getB2buaHelper(); if(b2buaHelperImpl != null) { // we unlink the originalRequest early to avoid keeping the messages in mem for too long b2buaHelperImpl.unlinkOriginalRequestInternal((SipServletRequestImpl)tad.getSipServletMessage()); } session.removeOngoingTransaction(transaction); tad.cleanUp(); final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); // Issue 1468 : to handle forking, we shouldn't cleanup the app data since it is needed for the forked responses if(((SipStackImpl)sipProvider.getSipStack()).getMaxForkTime() == 0) { transaction.setApplicationData(null); } return; } //Added for initial requests only (that are not REGISTER) not for subsequent requests if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) { // Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29 // if(session.getProxy() != null && // session.getProxy().getRecordRoute()) // If the app is proxying it already does that // { // if(logger.isDebugEnabled()) { // logger.debug("Add a record route header for app composition "); // } // getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); // //Add a record route header for app composition // addAppCompositionRRHeader(); // } final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are interested."); } //Adding Route Header for LB if we are in a HA configuration if(sipFactoryImpl.isUseLoadBalancer() && isInitial) { sipFactoryImpl.addLoadBalancerRouteHeader(request); if(logger.isDebugEnabled()) { logger.debug("adding route to Load Balancer since we are in a HA configuration " + " and no more apps are interested."); } } } } final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession(); if(viaHeader.getBranch() == null) { final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName())); viaHeader.setBranch(branch); } if(logger.isDebugEnabled()) { getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); } if (super.getTransaction() == null) { ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME); if(contactHeader == null && !Request.REGISTER.equalsIgnoreCase(requestMethod) && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) { final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME); final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI(); String fromName = null; if(fromUri instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromUri).getUser(); } // Create the contact name address. contactHeader = JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface()); request.addHeader(contactHeader); } if(sipConnector != null && sipConnector.isUseStaticAddress()) { if(proxy == null && contactHeader != null) { boolean sipURI = contactHeader.getAddress().getURI().isSipURI(); if(sipURI) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) contactHeader.getAddress().getURI(); sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } } } if(logger.isDebugEnabled()) { logger.debug("Getting new Client Tx for request " + request); } final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); /* * If we the next hop is in this container we optimize the traffic by directing it here instead of going through load balancers. * This is must be done before creating the transaction, otherwise it will go to the host/port specified prior to the changes here. */ if(!isInitial() && sipConnector != null && // Initial requests already use local address in RouteHeader. sipConnector.isUseStaticAddress()) { optimizeRouteHeaderAddressForInternalRoutingrequest(sipConnector, request, session, sipFactoryImpl, transport); } final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); Dialog dialog = ctx.getDialog(); if(session.getProxy() != null) { // no dialogs in proxy dialog = null; // take care of the RRH if(isInitial()) { if(session.getProxy().getRecordRoute()) { RecordRouteHeader rrh = (RecordRouteHeader) request.getHeader(RecordRouteHeader.NAME); if(rrh == null) { if(logger.isDebugEnabled()) { logger.debug("Unexpected RRH = null for this request" + request); } } else { javax.sip.address.URI uri = rrh.getAddress().getURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; if(sipConnector != null && sipConnector.isUseStaticAddress()) { sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } sipUri.setTransportParam(transport); if(logger.isDebugEnabled()) { logger.debug("Updated the RRH with static server address " + sipUri); } } } } } } if (dialog == null && this.createDialog && JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) { dialog = sipProvider.getNewDialog(ctx); ((DialogExt)dialog).disableSequenceNumberValidation(); session.setSessionCreatingDialog(dialog); if(logger.isDebugEnabled()) { logger.debug("new Dialog for request " + request + ", ref = " + dialog); } } //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { final Transaction linkedTransaction = linkedRequest.getTransaction(); final Dialog linkedDialog = linkedRequest.getDialog(); //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx); if(linkedDialog != null && linkedDialog.getApplicationData() != null) { ((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedTransaction); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction); } } // Make the dialog point here so that when the dialog event // comes in we can find the session quickly. if (dialog != null) { dialog.setApplicationData(this.transactionApplicationData); } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); super.setTransaction(ctx); session.setSessionCreatingTransactionRequest(this); } else if (Request.PRACK.equals(request.getMethod())) { final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx); if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) { ((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedRequest.getTransaction()); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction()); } } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); setTransaction(ctx); } else { if(logger.isDebugEnabled()) { logger.debug("Transaction is not null, where was it created? " + getTransaction()); } } //tells the application dispatcher to stop routing the linked request // (in this case it would be the original request) since it has been relayed if(linkedRequest != null && !SipApplicationRoutingDirective.NEW.equals(routingDirective)) { if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) { linkedRequest.setRoutingState(RoutingState.RELAYED); } } if(!Request.ACK.equals(getMethod())) { session.addOngoingTransaction(getTransaction()); } // Update Session state session.updateStateOnSubsequentRequest(this, false); // Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481 // proxy should not add or remove subscription since there is no dialog associated with it if(Request.NOTIFY.equals(getMethod()) && session.getProxy() == null) { final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) getMessage().getHeader(SubscriptionStateHeader.NAME); // RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates // a new subscription and a new dialog (unless they have already been // created by a matching response, as described above). if (subscriptionStateHeader != null && (SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) || SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) { session.addSubscription(this); } // A subscription is destroyed when a notifier sends a NOTIFY request // with a "Subscription-State" of "terminated". if (subscriptionStateHeader != null && SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) { session.removeSubscription(this); } } updateContactHeaderTransport(transport); //updating the last accessed times session.access(); sipApplicationSession.access(); Dialog dialog = getDialog(); if(session.getProxy() != null) dialog = null; // If dialog does not exist or has no state. if (dialog == null || dialog.getState() == null || (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod)) || Request.CANCEL.equals(requestMethod)) { if(logger.isDebugEnabled()) { logger.debug("Sending the request " + request); } ((ClientTransaction) super.getTransaction()).sendRequest(); } else { // This is a subsequent (an in-dialog) request. // we don't redirect it to the container for now if(logger.isDebugEnabled()) { logger.debug("Sending the in dialog request " + request); } dialog.sendRequest((ClientTransaction) getTransaction()); } isMessageSent = true; } catch (Exception ex) { throw new IllegalStateException("Error sending request " + request,ex); } }
public void send() { checkReadOnly(); final Request request = (Request) super.message; final MobicentsSipSession session = getSipSession(); try { ProxyImpl proxy = null; if(session != null) { proxy = session.getProxy(); } final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager(); final String sessionTransport = session.getTransport(); if(logger.isDebugEnabled()) { logger.debug("session transport is " + sessionTransport); } ((MessageExt)message).setApplicationData(sessionTransport); ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME); //Issue 112 fix by folsson if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) { boolean addViaHeader = false; if(proxy == null) { addViaHeader = true; } else if(isInitial) { if(proxy.getRecordRoute()) { addViaHeader = true; } } else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) { addViaHeader = true; } if(addViaHeader) { // Issue viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, request, null, session.getOutboundInterface()); message.addHeader(viaHeader); if(logger.isDebugEnabled()) { logger.debug("Added via Header" + viaHeader); } } } else { if(getMethod().equalsIgnoreCase(Request.CANCEL)) { if(getSipSession().getState().equals(State.INITIAL)) { Transaction tx = inviteTransactionToCancel; if(tx != null) { logger.debug("Can not send CANCEL. Will try to STOP retransmissions " + tx); // We still haven't received any response on this call, so we can not send CANCEL, // we will just stop the retransmissions StaticServiceHolder.disableRetransmissionTimer.invoke(tx); if(tx.getApplicationData() instanceof TransactionApplicationData) { TransactionApplicationData tad = (TransactionApplicationData) tx.getApplicationData(); tad.setCanceled(true); } return; } else { logger.debug("Can not send CANCEL because noe response arrived. " + "Can not stop retransmissions. The transaction is null"); } } } } final String transport = JainSipUtils.findTransport(request); if(sessionTransport == null) { session.setTransport(transport); } if(logger.isDebugEnabled()) { logger.debug("The found transport for sending request is '" + transport + "'"); } SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(transport); // Bypass the load balancer for outgoing requests by removing the route header for them if(sipConnector != null && sipConnector.isUseStaticAddress()) { RouteHeader rh = (RouteHeader) request.getHeader(RouteHeader.NAME); if(logger.isDebugEnabled()) { logger.debug("We are looking at route header " + rh + " and SC is" + sipConnector.getStaticServerAddress() + ":" + sipConnector.getStaticServerPort()); } if(rh != null) { if(rh.getAddress().getURI().isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI)rh.getAddress().getURI(); if(sipUri.getHost().equals(sipConnector.getStaticServerAddress())) { int port = sipUri.getPort(); if(port <= 0) port = 5060; if(port == sipConnector.getStaticServerPort()) { request.removeHeader(RouteHeader.NAME); } } } } } final String requestMethod = getMethod(); if(Request.ACK.equals(requestMethod)) { session.getSessionCreatingDialog().sendAck(request); final Transaction transaction = getTransaction(); final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); final B2buaHelperImpl b2buaHelperImpl = sipSession.getB2buaHelper(); if(b2buaHelperImpl != null && tad != null) { // we unlink the originalRequest early to avoid keeping the messages in mem for too long b2buaHelperImpl.unlinkOriginalRequestInternal((SipServletRequestImpl)tad.getSipServletMessage()); } session.removeOngoingTransaction(transaction); if(tad != null) { tad.cleanUp(); } final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); // Issue 1468 : to handle forking, we shouldn't cleanup the app data since it is needed for the forked responses if(((SipStackImpl)sipProvider.getSipStack()).getMaxForkTime() == 0) { transaction.setApplicationData(null); } return; } //Added for initial requests only (that are not REGISTER) not for subsequent requests if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) { // Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29 // if(session.getProxy() != null && // session.getProxy().getRecordRoute()) // If the app is proxying it already does that // { // if(logger.isDebugEnabled()) { // logger.debug("Add a record route header for app composition "); // } // getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); // //Add a record route header for app composition // addAppCompositionRRHeader(); // } final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are interested."); } //Adding Route Header for LB if we are in a HA configuration if(sipFactoryImpl.isUseLoadBalancer() && isInitial) { sipFactoryImpl.addLoadBalancerRouteHeader(request); if(logger.isDebugEnabled()) { logger.debug("adding route to Load Balancer since we are in a HA configuration " + " and no more apps are interested."); } } } } final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession(); if(viaHeader.getBranch() == null) { final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName())); viaHeader.setBranch(branch); } if(logger.isDebugEnabled()) { getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions(); } if (super.getTransaction() == null) { ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME); if(contactHeader == null && !Request.REGISTER.equalsIgnoreCase(requestMethod) && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) { final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME); final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI(); String fromName = null; if(fromUri instanceof javax.sip.address.SipURI) { fromName = ((javax.sip.address.SipURI)fromUri).getUser(); } // Create the contact name address. contactHeader = JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface()); request.addHeader(contactHeader); } if(sipConnector != null && sipConnector.isUseStaticAddress()) { if(proxy == null && contactHeader != null) { boolean sipURI = contactHeader.getAddress().getURI().isSipURI(); if(sipURI) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) contactHeader.getAddress().getURI(); sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } } } if(logger.isDebugEnabled()) { logger.debug("Getting new Client Tx for request " + request); } final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); /* * If we the next hop is in this container we optimize the traffic by directing it here instead of going through load balancers. * This is must be done before creating the transaction, otherwise it will go to the host/port specified prior to the changes here. */ if(!isInitial() && sipConnector != null && // Initial requests already use local address in RouteHeader. sipConnector.isUseStaticAddress()) { optimizeRouteHeaderAddressForInternalRoutingrequest(sipConnector, request, session, sipFactoryImpl, transport); } final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); Dialog dialog = ctx.getDialog(); if(session.getProxy() != null) { // no dialogs in proxy dialog = null; // take care of the RRH if(isInitial()) { if(session.getProxy().getRecordRoute()) { RecordRouteHeader rrh = (RecordRouteHeader) request.getHeader(RecordRouteHeader.NAME); if(rrh == null) { if(logger.isDebugEnabled()) { logger.debug("Unexpected RRH = null for this request" + request); } } else { javax.sip.address.URI uri = rrh.getAddress().getURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; if(sipConnector != null && sipConnector.isUseStaticAddress()) { sipUri.setHost(sipConnector.getStaticServerAddress()); sipUri.setPort(sipConnector.getStaticServerPort()); } sipUri.setTransportParam(transport); if(logger.isDebugEnabled()) { logger.debug("Updated the RRH with static server address " + sipUri); } } } } } } if (dialog == null && this.createDialog && JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) { dialog = sipProvider.getNewDialog(ctx); ((DialogExt)dialog).disableSequenceNumberValidation(); session.setSessionCreatingDialog(dialog); if(logger.isDebugEnabled()) { logger.debug("new Dialog for request " + request + ", ref = " + dialog); } } //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { final Transaction linkedTransaction = linkedRequest.getTransaction(); final Dialog linkedDialog = linkedRequest.getDialog(); //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx); if(linkedDialog != null && linkedDialog.getApplicationData() != null) { ((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedTransaction); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction); } } // Make the dialog point here so that when the dialog event // comes in we can find the session quickly. if (dialog != null) { dialog.setApplicationData(this.transactionApplicationData); } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); super.setTransaction(ctx); session.setSessionCreatingTransactionRequest(this); } else if (Request.PRACK.equals(request.getMethod())) { final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint( transport, false).getSipProvider(); final ClientTransaction ctx = sipProvider.getNewClientTransaction(request); ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval()); ((TransactionExt)ctx).setTimerT2(sipFactoryImpl.getSipApplicationDispatcher().getT2Interval()); ((TransactionExt)ctx).setTimerT4(sipFactoryImpl.getSipApplicationDispatcher().getT4Interval()); ((TransactionExt)ctx).setTimerD(sipFactoryImpl.getSipApplicationDispatcher().getTimerDInterval()); //Keeping the transactions mapping in application data for CANCEL handling if(linkedRequest != null) { //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx); if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) { ((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx); } //keeping the server transaction in the client transaction's application data this.transactionApplicationData.setTransaction(linkedRequest.getTransaction()); if(dialog!= null && dialog.getApplicationData() != null) { ((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction()); } } // SIP Request is ALWAYS pointed to by the client tx. // Notice that the tx appplication data is cached in the request // copied over to the tx so it can be quickly accessed when response // arrives. ctx.setApplicationData(this.transactionApplicationData); setTransaction(ctx); } else { if(logger.isDebugEnabled()) { logger.debug("Transaction is not null, where was it created? " + getTransaction()); } } //tells the application dispatcher to stop routing the linked request // (in this case it would be the original request) since it has been relayed if(linkedRequest != null && !SipApplicationRoutingDirective.NEW.equals(routingDirective)) { if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) { linkedRequest.setRoutingState(RoutingState.RELAYED); } } if(!Request.ACK.equals(getMethod())) { session.addOngoingTransaction(getTransaction()); } // Update Session state session.updateStateOnSubsequentRequest(this, false); // Issue 1481 http://code.google.com/p/mobicents/issues/detail?id=1481 // proxy should not add or remove subscription since there is no dialog associated with it if(Request.NOTIFY.equals(getMethod()) && session.getProxy() == null) { final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) getMessage().getHeader(SubscriptionStateHeader.NAME); // RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates // a new subscription and a new dialog (unless they have already been // created by a matching response, as described above). if (subscriptionStateHeader != null && (SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) || SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) { session.addSubscription(this); } // A subscription is destroyed when a notifier sends a NOTIFY request // with a "Subscription-State" of "terminated". if (subscriptionStateHeader != null && SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) { session.removeSubscription(this); } } updateContactHeaderTransport(transport); //updating the last accessed times session.access(); sipApplicationSession.access(); Dialog dialog = getDialog(); if(session.getProxy() != null) dialog = null; // If dialog does not exist or has no state. if (dialog == null || dialog.getState() == null || (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod)) || Request.CANCEL.equals(requestMethod)) { if(logger.isDebugEnabled()) { logger.debug("Sending the request " + request); } ((ClientTransaction) super.getTransaction()).sendRequest(); } else { // This is a subsequent (an in-dialog) request. // we don't redirect it to the container for now if(logger.isDebugEnabled()) { logger.debug("Sending the in dialog request " + request); } dialog.sendRequest((ClientTransaction) getTransaction()); } isMessageSent = true; } catch (Exception ex) { throw new IllegalStateException("Error sending request " + request,ex); } }
diff --git a/demo/src/main/java/com/thoughtworks/selenium/grid/demo/MartinOnAmazonSeleniumTest.java b/demo/src/main/java/com/thoughtworks/selenium/grid/demo/MartinOnAmazonSeleniumTest.java index 9a9375c..06906ae 100755 --- a/demo/src/main/java/com/thoughtworks/selenium/grid/demo/MartinOnAmazonSeleniumTest.java +++ b/demo/src/main/java/com/thoughtworks/selenium/grid/demo/MartinOnAmazonSeleniumTest.java @@ -1,75 +1,75 @@ package com.thoughtworks.selenium.grid.demo; import static junit.framework.Assert.assertEquals; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.Selenium; import junit.framework.Assert; import junit.framework.TestCase; /** * Traditional Selenium Test checking the quality of Amazon comments ;o). * <br/> * Each test request a different browser/environment. * <br/> * <code>testAmazonOnFirefox</code> can run against a plain vanilla * Selenium remote control. * <br/> * The other tests need to run again a Selenium Hub: They demonstrate * the capacity of requesting a specific environment per * test/test suite/build. Of course these environments must be defined * on the Hub and at least one remote control must register as providing * this particular environment. */ public class MartinOnAmazonSeleniumTest extends TestCase { private Selenium selenium; public MartinOnAmazonSeleniumTest(String s) { super(s); } public void tearDown() throws Exception { selenium.stop(); } public void testAmazonOnFirefox() throws Throwable { runAmazonScript("*chrome"); } public void testAmazonOnFirefoxOnWindows() throws Throwable { runAmazonScript("Firefox on Windows"); } public void testAmazonOnFirefoxOnLinux() throws Throwable { runAmazonScript("Firefox on Linux"); } public void testAmazonOnFirefoxOnMac() throws Throwable { runAmazonScript("Firefox on Mac"); } public void testAmazonOnIEOnWindows() throws Throwable { // windows implicitly runAmazonScript("IE on Windows"); } protected void runAmazonScript(String browser) { createDriver(4444, "http://amazon.com", browser); selenium.open("/"); selenium.type("twotabsearchtextbox", "refactoring"); - selenium.click("Go"); + selenium.click("navGoButtonPanel"); selenium.waitForPageToLoad("60000"); assertTrue(selenium.getLocation().startsWith("http://amazon.com/s/ref=")); - selenium.click("//img[@alt='Refactoring: Improving the Design of Existing Code']"); + selenium.click("//img[@alt='Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)']"); selenium.waitForPageToLoad("60000"); assertEquals("1", selenium.getValue("name=quantity")); assertTrue(selenium.isTextPresent("excellent")); assertTrue(selenium.isTextPresent("Hidden Treasure")); } protected void createDriver(int port, String url, String browser) { selenium = new DefaultSelenium("localhost", port, browser, url); selenium.start(); } }
false
true
protected void runAmazonScript(String browser) { createDriver(4444, "http://amazon.com", browser); selenium.open("/"); selenium.type("twotabsearchtextbox", "refactoring"); selenium.click("Go"); selenium.waitForPageToLoad("60000"); assertTrue(selenium.getLocation().startsWith("http://amazon.com/s/ref=")); selenium.click("//img[@alt='Refactoring: Improving the Design of Existing Code']"); selenium.waitForPageToLoad("60000"); assertEquals("1", selenium.getValue("name=quantity")); assertTrue(selenium.isTextPresent("excellent")); assertTrue(selenium.isTextPresent("Hidden Treasure")); }
protected void runAmazonScript(String browser) { createDriver(4444, "http://amazon.com", browser); selenium.open("/"); selenium.type("twotabsearchtextbox", "refactoring"); selenium.click("navGoButtonPanel"); selenium.waitForPageToLoad("60000"); assertTrue(selenium.getLocation().startsWith("http://amazon.com/s/ref=")); selenium.click("//img[@alt='Refactoring: Improving the Design of Existing Code (The Addison-Wesley Object Technology Series)']"); selenium.waitForPageToLoad("60000"); assertEquals("1", selenium.getValue("name=quantity")); assertTrue(selenium.isTextPresent("excellent")); assertTrue(selenium.isTextPresent("Hidden Treasure")); }
diff --git a/SoundStream-test/src/com/lastcrusade/soundstream/net/message/FoundGuestsMessageTest.java b/SoundStream-test/src/com/lastcrusade/soundstream/net/message/FoundGuestsMessageTest.java index edf09cd..7ee3e9d 100644 --- a/SoundStream-test/src/com/lastcrusade/soundstream/net/message/FoundGuestsMessageTest.java +++ b/SoundStream-test/src/com/lastcrusade/soundstream/net/message/FoundGuestsMessageTest.java @@ -1,34 +1,34 @@ package com.lastcrusade.soundstream.net.message; import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.lastcrusade.soundstream.net.message.FoundGuest; import com.lastcrusade.soundstream.net.message.FoundGuestsMessage; public class FoundGuestsMessageTest extends SerializationTest<FoundGuestsMessage> { @Test public void testSerializeFoundGuestsMessage() throws IOException { //NOTE: no fields to check, and the base class will ensure we create the right class. List<FoundGuest> foundGuests = new ArrayList<FoundGuest>(); - foundGuests.add(new FoundGuest("Test1", "00:11:22:33:44:55:66")); - foundGuests.add(new FoundGuest("Test2", "00:11:22:33:44:55:67")); - foundGuests.add(new FoundGuest("Test3", "00:11:22:33:44:55:68")); - foundGuests.add(new FoundGuest("Test4", "00:11:22:33:44:55:69")); + foundGuests.add(new FoundGuest("Test1", "00:11:22:33:44:55:66", true)); + foundGuests.add(new FoundGuest("Test2", "00:11:22:33:44:55:67", true)); + foundGuests.add(new FoundGuest("Test3", "00:11:22:33:44:55:68", false)); + foundGuests.add(new FoundGuest("Test4", "00:11:22:33:44:55:69", false)); FoundGuestsMessage oldMessage = new FoundGuestsMessage(foundGuests); FoundGuestsMessage newMessage = super.testSerializeMessage(oldMessage); //verify that the FoundGuests objects are equal and in the same order. for (int ii = 0; ii < foundGuests.size(); ii++) { FoundGuest expected = foundGuests.get(ii); FoundGuest actual = newMessage.getFoundGuests().get(ii); assertEquals(expected, actual); } } }
true
true
public void testSerializeFoundGuestsMessage() throws IOException { //NOTE: no fields to check, and the base class will ensure we create the right class. List<FoundGuest> foundGuests = new ArrayList<FoundGuest>(); foundGuests.add(new FoundGuest("Test1", "00:11:22:33:44:55:66")); foundGuests.add(new FoundGuest("Test2", "00:11:22:33:44:55:67")); foundGuests.add(new FoundGuest("Test3", "00:11:22:33:44:55:68")); foundGuests.add(new FoundGuest("Test4", "00:11:22:33:44:55:69")); FoundGuestsMessage oldMessage = new FoundGuestsMessage(foundGuests); FoundGuestsMessage newMessage = super.testSerializeMessage(oldMessage); //verify that the FoundGuests objects are equal and in the same order. for (int ii = 0; ii < foundGuests.size(); ii++) { FoundGuest expected = foundGuests.get(ii); FoundGuest actual = newMessage.getFoundGuests().get(ii); assertEquals(expected, actual); } }
public void testSerializeFoundGuestsMessage() throws IOException { //NOTE: no fields to check, and the base class will ensure we create the right class. List<FoundGuest> foundGuests = new ArrayList<FoundGuest>(); foundGuests.add(new FoundGuest("Test1", "00:11:22:33:44:55:66", true)); foundGuests.add(new FoundGuest("Test2", "00:11:22:33:44:55:67", true)); foundGuests.add(new FoundGuest("Test3", "00:11:22:33:44:55:68", false)); foundGuests.add(new FoundGuest("Test4", "00:11:22:33:44:55:69", false)); FoundGuestsMessage oldMessage = new FoundGuestsMessage(foundGuests); FoundGuestsMessage newMessage = super.testSerializeMessage(oldMessage); //verify that the FoundGuests objects are equal and in the same order. for (int ii = 0; ii < foundGuests.size(); ii++) { FoundGuest expected = foundGuests.get(ii); FoundGuest actual = newMessage.getFoundGuests().get(ii); assertEquals(expected, actual); } }
diff --git a/src/org/dita/dost/writer/KeyrefPaser.java b/src/org/dita/dost/writer/KeyrefPaser.java index 2e651d40f..a1b02533b 100644 --- a/src/org/dita/dost/writer/KeyrefPaser.java +++ b/src/org/dita/dost/writer/KeyrefPaser.java @@ -1,786 +1,776 @@ /* * This file is part of the DITA Open Toolkit project hosted on * Sourceforge.net. See the accompanying license.txt file for * applicable licenses. */ /* * (c) Copyright IBM Corp. 2010 All Rights Reserved. */ package org.dita.dost.writer; import static org.dita.dost.util.Constants.*; import static javax.xml.XMLConstants.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.Content; import org.dita.dost.util.DitaClass; import org.dita.dost.util.FileUtils; import org.dita.dost.util.MergeUtils; import org.dita.dost.util.StringUtils; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLFilterImpl; import org.xml.sax.helpers.AttributesImpl; /** * Filter for processing key reference elements in DITA files. * Instances are reusable but not thread-safe. */ public final class KeyrefPaser extends XMLFilterImpl { /** * Set of attributes which should not be copied from * key definition to key reference which is {@code <topicref>}. */ private static final Set<String> no_copy; static { final Set<String> nc = new HashSet<String>(); nc.add(ATTRIBUTE_NAME_ID); nc.add(ATTRIBUTE_NAME_CLASS); nc.add(ATTRIBUTE_NAME_XTRC); nc.add(ATTRIBUTE_NAME_XTRF); nc.add(ATTRIBUTE_NAME_HREF); nc.add(ATTRIBUTE_NAME_KEYS); nc.add(ATTRIBUTE_NAME_TOC); nc.add(ATTRIBUTE_NAME_PROCESSING_ROLE); no_copy = Collections.unmodifiableSet(nc); } /** * Set of attributes which should not be copied from * key definition to key reference which is not {@code <topicref>}. */ private static final Set<String> no_copy_topic; static { final Set<String> nct = new HashSet<String>(); nct.addAll(no_copy); nct.add("query"); nct.add("search"); nct.add(ATTRIBUTE_NAME_TOC); nct.add(ATTRIBUTE_NAME_PRINT); nct.add(ATTRIBUTE_NAME_COPY_TO); nct.add(ATTRIBUTE_NAME_CHUNK); nct.add(ATTRIBUTE_NAME_NAVTITLE); no_copy_topic = Collections.unmodifiableSet(nct); } /** List of key reference element definitions. */ private final static List<KeyrefInfo> keyrefInfos; static { final List<KeyrefInfo> ki = new ArrayList<KeyrefInfo>(); ki.add(new KeyrefInfo(TOPIC_AUTHOR, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_DATA, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_DATA_ABOUT, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_IMAGE, ATTRIBUTE_NAME_HREF, true)); ki.add(new KeyrefInfo(TOPIC_LINK, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_LQ, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(MAP_NAVREF, "mapref", true)); ki.add(new KeyrefInfo(TOPIC_PUBLISHER, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_SOURCE, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(MAP_TOPICREF, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_XREF, ATTRIBUTE_NAME_HREF, false)); ki.add(new KeyrefInfo(TOPIC_CITE, null, false)); ki.add(new KeyrefInfo(TOPIC_DT, null, false)); ki.add(new KeyrefInfo(TOPIC_KEYWORD, null, false)); ki.add(new KeyrefInfo(TOPIC_TERM, null, false)); ki.add(new KeyrefInfo(TOPIC_PH, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEXTERM, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEX_BASE, null, false)); ki.add(new KeyrefInfo(TOPIC_INDEXTERMREF, null, false)); keyrefInfos = Collections.unmodifiableList(ki); } private final XMLReader parser; private final TransformerFactory tf; private DITAOTLogger logger; private Hashtable<String, String> definitionMap; private String tempDir; /** * It is stack used to store the place of current element * relative to the key reference element. Because keyref can be nested. */ private final Stack<Integer> keyrefLevalStack; /** * It is used to store the place of current element * relative to the key reference element. If it is out of range of key * reference element it is zero, otherwise it is positive number. * It is also used to indicate whether current element is descendant of the * key reference element. */ private int keyrefLeval; /** Relative path of the filename to the temporary directory. */ private String filepath; private String extName; /** * It is used to store the target of the keys * In the from the map <keys, target>. */ private Map<String, String> keyMap; /** * It is used to indicate whether the keyref is valid. * The descendant element should know whether keyref is valid because keyrefs can be nested. */ private final Stack<Boolean> validKeyref; /** * Flag indicating whether the key reference element is empty, * if it is empty, it should pull matching content from the key definition. */ private boolean empty; /** Stack of element names of the element containing keyref attribute. */ private final Stack<String> elemName; /** Current element keyref info, {@code null} if not keyref type element. */ private KeyrefInfo currentElement; private boolean hasChecked; /** Flag stack to indicate whether key reference element has sub-elements. */ private final Stack<Boolean> hasSubElem; /** Current key definition. */ private Document doc; /** File name with relative path to the temporary directory of input file. */ private String fileName; /** * Constructor. */ public KeyrefPaser() { keyrefLeval = 0; keyrefLevalStack = new Stack<Integer>(); validKeyref = new Stack<Boolean>(); empty = true; keyMap = new HashMap<String, String>(); elemName = new Stack<String>(); hasSubElem = new Stack<Boolean>(); try { parser = StringUtils.getXMLReader(); parser.setFeature(FEATURE_NAMESPACE_PREFIX, true); parser.setFeature(FEATURE_NAMESPACE, true); setParent(parser); tf = TransformerFactory.newInstance(); } catch (final Exception e) { throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e); } } /** * Set logger * * @param logger output logger */ public void setLogger(final DITAOTLogger logger) { this.logger = logger; } /** * Get extension name. * @return extension name */ public String getExtName() { return extName; } /** * Set extension name. * @param extName extension name */ public void setExtName(final String extName) { this.extName = extName; } /** * Set key definition map. * * @param content value {@code Hashtable<String, String>} */ @SuppressWarnings("unchecked") public void setContent(final Content content) { definitionMap = (Hashtable<String, String>) content.getValue(); if (definitionMap == null) { throw new IllegalArgumentException("Content value must be non-null Hashtable<String, String>"); } } /** * Set temp dir. * @param tempDir temp dir */ public void setTempDir(final String tempDir) { this.tempDir = tempDir; } /** * Set key map. * @param map key map */ public void setKeyMap(final Map<String, String> map) { this.keyMap = map; } /** * Process key references. * * @param filename file to process * @throws DITAOTException if key reference resolution failed */ public void write(final String filename) throws DITAOTException { final File inputFile = new File(tempDir, filename); filepath = inputFile.getAbsolutePath(); final File outputFile = new File(tempDir, filename + ATTRIBUTE_NAME_KEYREF); this.fileName = filename; OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(outputFile)); final Transformer t = tf.newTransformer(); final Source src = new SAXSource(this, new InputSource(inputFile.toURI().toString())); final Result dst = new StreamResult(output); t.transform(src, dst); } catch (final Exception e) { throw new DITAOTException("Failed to process key references: " + e.getMessage(), e); } finally { if (output != null) { try { output.close(); } catch (final Exception ex) { logger.logError("Failed to close output stream: " + ex.getMessage(), ex); } } } if (!inputFile.delete()) { final Properties prop = new Properties(); prop.put("%1", inputFile.getPath()); prop.put("%2", outputFile.getPath()); logger.logError(MessageUtils.getMessage("DOTJ009E", prop).toString()); } if (!outputFile.renameTo(inputFile)) { final Properties prop = new Properties(); prop.put("%1", inputFile.getPath()); prop.put("%2", outputFile.getPath()); logger.logError(MessageUtils.getMessage("DOTJ009E", prop).toString()); } } // XML filter methods ------------------------------------------------------ @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { if (keyrefLeval != 0 && new String(ch,start,length).trim().length() == 0) { if (!hasChecked) { empty = true; } } else { hasChecked = true; empty = false; } getContentHandler().characters(ch, start, length); } @Override public void endElement(final String uri, final String localName, final String name) throws SAXException { if (keyrefLeval != 0 && empty && !elemName.peek().equals(MAP_TOPICREF.localName)) { // If current element is in the scope of key reference element // and the element is empty if (!validKeyref.isEmpty() && validKeyref.peek()) { // Key reference is valid, // need to pull matching content from the key definition final Element elem = doc.getDocumentElement(); NodeList nodeList = null; // If current element name doesn't equal the key reference element // just grab the content from the matching element of key definition if(!name.equals(elemName.peek())){ nodeList = elem.getElementsByTagName(name); if(nodeList.getLength() > 0){ final Node node = nodeList.item(0); final NodeList nList = node.getChildNodes(); int index = 0; while(index < nList.getLength()){ final Node n = nList.item(index++); if(n.getNodeType() == Node.TEXT_NODE){ final char[] ch = n.getNodeValue().toCharArray(); getContentHandler().characters(ch, 0, ch.length); break; } } } }else{ // Current element name equals the key reference element // grab keyword or term from key definition nodeList = elem.getElementsByTagName(TOPIC_KEYWORD.localName); if(nodeList.getLength() == 0 ){ nodeList = elem.getElementsByTagName(TOPIC_TERM.localName); } if(!hasSubElem.peek()){ if(nodeList.getLength() > 0){ if(currentElement != null && !currentElement.isRefType){ // only one keyword or term is used. nodeToString((Element)nodeList.item(0), false); } else if(currentElement != null){ // If the key reference element carries href attribute // all keyword or term are used. if(TOPIC_LINK.matches(currentElement.type)){ final AttributesImpl atts = new AttributesImpl(); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString()); getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts); } if (!currentElement.isEmpty) { for(int index =0; index<nodeList.getLength(); index++){ final Node node = nodeList.item(index); if(node.getNodeType() == Node.ELEMENT_NODE){ nodeToString((Element)node, true); } } } if(TOPIC_LINK.matches(currentElement.type)){ getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName); } } }else{ if(currentElement != null && TOPIC_LINK.matches(currentElement.type)){ // If the key reference element is link or its specification, // should pull in the linktext final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName); if(linktext.getLength()>0){ nodeToString((Element)linktext.item(0), true); }else if (!StringUtils.isEmptyString(elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE))){ final AttributesImpl atts = new AttributesImpl(); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString()); getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts); if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) { final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray(); getContentHandler().characters(ch, 0, ch.length); } getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName); } }else if(currentElement != null && currentElement.isRefType){ final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName); if(linktext.getLength()>0){ nodeToString((Element)linktext.item(0), false); }else{ if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) { final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray(); getContentHandler().characters(ch, 0, ch.length); } } } } } } } } if (keyrefLeval != 0){ keyrefLeval--; empty = false; } if (keyrefLeval == 0 && !keyrefLevalStack.empty()) { // To the end of key reference, pop the stacks. keyrefLeval = keyrefLevalStack.pop(); validKeyref.pop(); elemName.pop(); hasSubElem.pop(); } getContentHandler().endElement(uri, localName, name); } @Override public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(cls.equalsIgnoreCase(MAPGROUP_D_MAPREF.toString()) && target.toLowerCase().endsWith(".ditamap")) ){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } } else if(target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); - //must set local name of attribute 'xml:lang' with vale 'lang' ,or it will cause saxon parse problem - if (node.getNodeName().equalsIgnoreCase("xml:lang")) { - Attr a = (Attr) node; - XMLUtils.addOrSetAttribute(resAtts,a.getNamespaceURI() != null ? a.getNamespaceURI() : NULL_NS_URI, - a.getLocalName() != null ? a.getLocalName() : "lang", - a.getName() != null ? a.getName() : "", - a.isId() ? "ID" : "CDATA", - a.getValue()) ; - } else { - XMLUtils.addOrSetAttribute(resAtts,node); - } + XMLUtils.addOrSetAttribute(resAtts, node); } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); } // Private methods --------------------------------------------------------- /** * Read key definition * * @param key key definition XML string * @return parsed key definition document */ private Document keyDefToDoc(final String key) { final InputSource inputSource = new InputSource(new StringReader(key)); final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = null; try { final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.parse(inputSource); } catch (final Exception e) { logger.logError("Failed to parse key definition: " + e.getMessage(), e); } return document; } /** * Serialize DOM node into a string. * * @param elem element to serialize * @param flag {@code true} to serialize elements, {@code false} to only serialize text nodes. * @return */ private void nodeToString(final Element elem, final boolean flag) throws SAXException{ // use flag to indicate that whether there is need to copy the element name if(flag){ final AttributesImpl atts = new AttributesImpl(); final NamedNodeMap namedNodeMap = elem.getAttributes(); for(int i=0; i<namedNodeMap.getLength(); i++){ final Attr a = (Attr) namedNodeMap.item(i); if(a.getNodeName().equals(ATTRIBUTE_NAME_CLASS)) { XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, changeclassValue(a.getNodeValue())); } else { XMLUtils.addOrSetAttribute(atts, a); } } getContentHandler().startElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName(), atts); } final NodeList nodeList = elem.getChildNodes(); for(int i=0; i<nodeList.getLength(); i++){ final Node node = nodeList.item(i); if(node.getNodeType() == Node.ELEMENT_NODE){ final Element e = (Element) node; //special process for tm tag. if(TOPIC_TM.matches(e)){ nodeToString(e, true); }else{ // If the type of current node is ELEMENT_NODE, process current node. nodeToString(e, flag); } // If the type of current node is ELEMENT_NODE, process current node. //stringBuffer.append(nodeToString((Element)node, flag)); } else if(node.getNodeType() == Node.TEXT_NODE){ final char[] ch = node.getNodeValue().toCharArray(); getContentHandler().characters(ch, 0, ch.length); } } if(flag) { getContentHandler().endElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName()); } } /** * Change map type to topic type. */ private String changeclassValue(final String classValue){ return classValue.replaceAll("map/", "topic/"); } /** * change elementId into topicId if there is no topicId in key definition. */ private static String normalizeHrefValue(final String keyName, final String tail) { final int sharpIndex=keyName.indexOf(SHARP); if(sharpIndex == -1){ return keyName + tail.replaceAll(SLASH, SHARP); } return keyName + tail; } /** * Get first topic id */ private String getFirstTopicId(final File topicFile) { final String path = topicFile.getParent(); final String name = topicFile.getName(); final String topicId = MergeUtils.getFirstTopicId(name, path, false); return topicId; } /** * Insert topic id into href */ private static String normalizeHrefValue(final String fileName, final String tail, final String topicId) { final int sharpIndex=fileName.indexOf(SHARP); //Insert first topic id only when topicid is not set in keydef //and keyref has elementid if(sharpIndex == -1 && !"".equals(tail)){ return fileName + SHARP + topicId + tail; } return fileName + tail; } // Inner classes ----------------------------------------------------------- private static final class KeyrefInfo { /** DITA class. */ final DitaClass type; /** Reference attribute name. */ final String refAttr; /** Element is reference type. */ final boolean isRefType; /** Element is empty. */ final boolean isEmpty; /** * Construct a new key reference info object. * * @param type element type * @param refAttr hyperlink attribute name * @param isEmpty flag if element is empty */ KeyrefInfo(final DitaClass type, final String refAttr, final boolean isEmpty) { this.type = type; this.refAttr = refAttr; this.isEmpty = isEmpty; this.isRefType = refAttr != null; } } }
true
true
public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(cls.equalsIgnoreCase(MAPGROUP_D_MAPREF.toString()) && target.toLowerCase().endsWith(".ditamap")) ){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } } else if(target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); //must set local name of attribute 'xml:lang' with vale 'lang' ,or it will cause saxon parse problem if (node.getNodeName().equalsIgnoreCase("xml:lang")) { Attr a = (Attr) node; XMLUtils.addOrSetAttribute(resAtts,a.getNamespaceURI() != null ? a.getNamespaceURI() : NULL_NS_URI, a.getLocalName() != null ? a.getLocalName() : "lang", a.getName() != null ? a.getName() : "", a.isId() ? "ID" : "CDATA", a.getValue()) ; } else { XMLUtils.addOrSetAttribute(resAtts,node); } } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); }
public void startElement(final String uri, final String localName, final String name, final Attributes atts) throws SAXException { currentElement = null; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); for (final KeyrefInfo k: keyrefInfos) { if (k.type.matches(cls)) { currentElement = k; } } final AttributesImpl resAtts = new AttributesImpl(atts); hasChecked = false; empty = true; boolean valid = false; if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) { // If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element if(keyrefLeval != 0){ keyrefLeval ++; hasSubElem.pop(); hasSubElem.push(true); } } else { // If there is @keyref, use the key definition to do // combination. // HashSet to store the attributes copied from key // definition to key reference. elemName.push(name); //hasKeyref = true; if (keyrefLeval != 0) { keyrefLevalStack.push(keyrefLeval); hasSubElem.pop(); hasSubElem.push(true); } hasSubElem.push(false); keyrefLeval = 0; keyrefLeval++; //keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF)); //the @keyref could be in the following forms: // 1.keyName 2.keyName/elementId /*String definition = ((Hashtable<String, String>) content .getValue()).get(atts .getValue(ATTRIBUTE_NAME_KEYREF));*/ final String keyrefValue=atts.getValue(ATTRIBUTE_NAME_KEYREF); final int slashIndex=keyrefValue.indexOf(SLASH); String keyName= keyrefValue; String tail= ""; if (slashIndex != -1) { keyName = keyrefValue.substring(0, slashIndex); tail = keyrefValue.substring(slashIndex); } final String definition = definitionMap.get(keyName); // If definition is not null if(definition!=null){ doc = keyDefToDoc(definition); final Element elem = doc.getDocumentElement(); final NamedNodeMap namedNodeMap = elem.getAttributes(); // first resolve the keyref attribute if (currentElement != null && currentElement.isRefType) { String target = keyMap.get(keyName); if (target != null && target.length() != 0) { String target_output = target; // if the scope equals local, the target should be verified that // it exists. final String scopeValue=elem.getAttribute(ATTRIBUTE_NAME_SCOPE); if (TOPIC_IMAGE.matches(currentElement.type)) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = FileUtils.getRelativePathFromMap(fileName, target_output); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else if ("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)){ if (!(cls.equalsIgnoreCase(MAPGROUP_D_MAPREF.toString()) && target.toLowerCase().endsWith(".ditamap")) ){ target = FileUtils.replaceExtName(target,extName); } final File topicFile = new File(FileUtils.resolveFile(tempDir, target)); if (topicFile.exists()) { final String topicId = this.getFirstTopicId(topicFile); target_output = FileUtils.getRelativePathFromMap(filepath, new File(tempDir, target).getAbsolutePath()); valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail, topicId); XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output); } else { // referenced file does not exist, emits a message. // Should only emit this if in a debug mode; comment out for now /*Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); javaLogger .logInfo(MessageUtils.getMessage("DOTJ047I", prop) .toString());*/ } } // scope equals peer or external else { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); target_output = normalizeHrefValue(target_output, tail); XMLUtils.addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, target_output); } } else if(target.length() == 0){ // Key definition does not carry an href or href equals "". valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); }else{ // key does not exist. final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } else if (currentElement != null && !currentElement.isRefType) { final String target = keyMap.get(keyName); if (target != null) { valid = true; XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE); XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT); } else { // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString()); } } // copy attributes in key definition to key reference // Set no_copy and no_copy_topic define some attributes should not be copied. if (valid) { if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) { // @keyref in topicref for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else { // @keyref not in topicref // different elements have different attributes if (currentElement != null && currentElement.isRefType) { // current element with href attribute for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName())) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } else if (currentElement != null && !currentElement.isRefType) { // current element without href attribute // so attributes about href should not be copied. for (int index = 0; index < namedNodeMap.getLength(); index++) { final Node node = namedNodeMap.item(index); if (node.getNodeType() == Node.ATTRIBUTE_NODE && !no_copy_topic.contains(node.getNodeName()) && !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE) || node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT) || node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) { XMLUtils.removeAttribute(resAtts, node.getNodeName()); XMLUtils.addOrSetAttribute(resAtts, node); } } } } } else { // keyref is not valid, don't copy any attribute. } }else{ // key does not exist final Properties prop = new Properties(); prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF)); logger.logInfo(MessageUtils.getMessage("DOTJ047I", prop).toString());; } validKeyref.push(valid); } getContentHandler().startElement(uri, localName, name, resAtts); }
diff --git a/src/com/android/musicfx/ControlPanelEffect.java b/src/com/android/musicfx/ControlPanelEffect.java index 8abb4f3..db46c3e 100644 --- a/src/com/android/musicfx/ControlPanelEffect.java +++ b/src/com/android/musicfx/ControlPanelEffect.java @@ -1,1419 +1,1419 @@ /* * Copyright (C) 2010-2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.musicfx; import android.content.Context; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.media.audiofx.AudioEffect; import android.media.audiofx.BassBoost; import android.media.audiofx.Equalizer; import android.media.audiofx.PresetReverb; import android.media.audiofx.Virtualizer; import android.util.Log; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; /** * The Common class defines constants to be used by the control panels. */ public class ControlPanelEffect { private final static String TAG = "MusicFXControlPanelEffect"; /** * Audio session priority */ private static final int PRIORITY = 0; /** * The control mode specifies if control panel updates effects and preferences or only * preferences. */ static enum ControlMode { /** * Control panel updates effects and preferences. Applicable when audio session is delivered * by user. */ CONTROL_EFFECTS, /** * Control panel only updates preferences. Applicable when there was no audio or invalid * session provided by user. */ CONTROL_PREFERENCES } static enum Key { global_enabled, virt_enabled, virt_strength, virt_type, bb_enabled, bb_strength, te_enabled, te_strength, avl_enabled, lm_enabled, lm_strength, eq_enabled, eq_num_bands, eq_level_range, eq_center_freq, eq_band_level, eq_num_presets, eq_preset_name, eq_preset_user_band_level, eq_preset_user_band_level_default, eq_preset_opensl_es_band_level, eq_preset_ci_extreme_band_level, eq_current_preset, pr_enabled, pr_current_preset } // Effect/audio session Mappings /** * Hashmap initial capacity */ private static final int HASHMAP_INITIAL_CAPACITY = 16; /** * Hashmap load factor */ private static final float HASHMAP_LOAD_FACTOR = 0.75f; /** * ConcurrentHashMap concurrency level */ private static final int HASHMAP_CONCURRENCY_LEVEL = 2; /** * Map containing the Virtualizer audio session, effect mappings. */ private static final ConcurrentHashMap<Integer, Virtualizer> mVirtualizerInstances = new ConcurrentHashMap<Integer, Virtualizer>( HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL); /** * Map containing the BB audio session, effect mappings. */ private static final ConcurrentHashMap<Integer, BassBoost> mBassBoostInstances = new ConcurrentHashMap<Integer, BassBoost>( HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL); /** * Map containing the EQ audio session, effect mappings. */ private static final ConcurrentHashMap<Integer, Equalizer> mEQInstances = new ConcurrentHashMap<Integer, Equalizer>( HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL); /** * Map containing the PR audio session, effect mappings. */ private static final ConcurrentHashMap<Integer, PresetReverb> mPresetReverbInstances = new ConcurrentHashMap<Integer, PresetReverb>( HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL); /** * Map containing the package name, audio session mappings. */ private static final ConcurrentHashMap<String, Integer> mPackageSessions = new ConcurrentHashMap<String, Integer>( HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL); // Defaults final static boolean GLOBAL_ENABLED_DEFAULT = false; private final static boolean VIRTUALIZER_ENABLED_DEFAULT = true; private final static int VIRTUALIZER_STRENGTH_DEFAULT = 1000; private final static boolean BASS_BOOST_ENABLED_DEFAULT = true; private final static int BASS_BOOST_STRENGTH_DEFAULT = 667; private final static boolean PRESET_REVERB_ENABLED_DEFAULT = false; private final static int PRESET_REVERB_CURRENT_PRESET_DEFAULT = 0; // None // EQ defaults private final static boolean EQUALIZER_ENABLED_DEFAULT = true; private final static String EQUALIZER_PRESET_NAME_DEFAULT = "Preset"; private final static short EQUALIZER_NUMBER_BANDS_DEFAULT = 5; private final static short EQUALIZER_NUMBER_PRESETS_DEFAULT = 0; private final static short[] EQUALIZER_BAND_LEVEL_RANGE_DEFAULT = { -1500, 1500 }; private final static int[] EQUALIZER_CENTER_FREQ_DEFAULT = { 60000, 230000, 910000, 3600000, 14000000 }; private final static short[] EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL = { 0, 800, 400, 100, 1000 }; private final static short[] EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT = { 0, 0, 0, 0, 0 }; private final static short[][] EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT = new short[EQUALIZER_NUMBER_PRESETS_DEFAULT][EQUALIZER_NUMBER_BANDS_DEFAULT]; // EQ effect properties which are invariable over all EQ effects sessions private static short[] mEQBandLevelRange = EQUALIZER_BAND_LEVEL_RANGE_DEFAULT; private static short mEQNumBands = EQUALIZER_NUMBER_BANDS_DEFAULT; private static int[] mEQCenterFreq = EQUALIZER_CENTER_FREQ_DEFAULT; private static short mEQNumPresets = EQUALIZER_NUMBER_PRESETS_DEFAULT; private static short[][] mEQPresetOpenSLESBandLevel = EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT; private static String[] mEQPresetNames; private static boolean mIsEQInitialized = false; private final static Object mEQInitLock = new Object(); /** * Default int argument used in methods to see that the arg is a dummy. Used for method * overloading. */ private final static int DUMMY_ARGUMENT = -1; /** * Inits effects preferences for the given context and package name in the control panel. If * preferences for the given package name don't exist, they are created and initialized. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. */ public static void initEffectsPreferences(final Context context, final String packageName, final int audioSession) { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); final ControlMode controlMode = getControlMode(audioSession); // init preferences try { // init global on/off switch final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(), GLOBAL_ENABLED_DEFAULT); editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled); Log.v(TAG, "isGlobalEnabled = " + isGlobalEnabled); // Virtualizer final boolean isVIEnabled = prefs.getBoolean(Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT); final int vIStrength = prefs.getInt(Key.virt_strength.toString(), VIRTUALIZER_STRENGTH_DEFAULT); editor.putBoolean(Key.virt_enabled.toString(), isVIEnabled); editor.putInt(Key.virt_strength.toString(), vIStrength); // BassBoost final boolean isBBEnabled = prefs.getBoolean(Key.bb_enabled.toString(), BASS_BOOST_ENABLED_DEFAULT); final int bBStrength = prefs.getInt(Key.bb_strength.toString(), BASS_BOOST_STRENGTH_DEFAULT); editor.putBoolean(Key.bb_enabled.toString(), isBBEnabled); editor.putInt(Key.bb_strength.toString(), bBStrength); // Equalizer synchronized (mEQInitLock) { // If EQ is not initialized already create "dummy" audio session created by // MediaPlayer and create effect on it to retrieve the invariable EQ properties if (!mIsEQInitialized) { final MediaPlayer mediaPlayer = new MediaPlayer(); final int session = mediaPlayer.getAudioSessionId(); Equalizer equalizerEffect = null; try { Log.d(TAG, "Creating dummy EQ effect on session " + session); equalizerEffect = new Equalizer(PRIORITY, session); mEQBandLevelRange = equalizerEffect.getBandLevelRange(); mEQNumBands = equalizerEffect.getNumberOfBands(); mEQCenterFreq = new int[mEQNumBands]; for (short band = 0; band < mEQNumBands; band++) { mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band); } mEQNumPresets = equalizerEffect.getNumberOfPresets(); mEQPresetNames = new String[mEQNumPresets]; mEQPresetOpenSLESBandLevel = new short[mEQNumPresets][mEQNumBands]; for (short preset = 0; preset < mEQNumPresets; preset++) { mEQPresetNames[preset] = equalizerEffect.getPresetName(preset); equalizerEffect.usePreset(preset); for (short band = 0; band < mEQNumBands; band++) { mEQPresetOpenSLESBandLevel[preset][band] = equalizerEffect .getBandLevel(band); } } mIsEQInitialized = true; } catch (final IllegalStateException e) { Log.e(TAG, "Equalizer: " + e); } catch (final IllegalArgumentException e) { Log.e(TAG, "Equalizer: " + e); } catch (final UnsupportedOperationException e) { Log.e(TAG, "Equalizer: " + e); } catch (final RuntimeException e) { Log.e(TAG, "Equalizer: " + e); } finally { if (equalizerEffect != null) { Log.d(TAG, "Releasing dummy EQ effect"); equalizerEffect.release(); } mediaPlayer.release(); // When there was a failure set some good defaults if (!mIsEQInitialized) { mEQPresetOpenSLESBandLevel = new short[mEQNumPresets][mEQNumBands]; for (short preset = 0; preset < mEQNumPresets; preset++) { // Init preset names to a dummy name mEQPresetNames[preset] = prefs.getString( Key.eq_preset_name.toString() + preset, EQUALIZER_PRESET_NAME_DEFAULT + preset); if (preset < EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT.length) { mEQPresetOpenSLESBandLevel[preset] = Arrays.copyOf( EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT[preset], mEQNumBands); } } } } } editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]); editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]); editor.putInt(Key.eq_num_bands.toString(), mEQNumBands); editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets); // Resetting the EQ arrays depending on the real # bands with defaults if // band < default size else 0 by copying default arrays over new ones final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands); // If no preset prefs set use CI EXTREME (= numPresets) final short eQPreset = (short) prefs.getInt(Key.eq_current_preset.toString(), mEQNumPresets); editor.putInt(Key.eq_current_preset.toString(), eQPreset); final short[] bandLevel = new short[mEQNumBands]; for (short band = 0; band < mEQNumBands; band++) { if (controlMode == ControlMode.CONTROL_PREFERENCES) { if (eQPreset < mEQNumPresets) { // OpenSL ES effect presets bandLevel[band] = mEQPresetOpenSLESBandLevel[eQPreset][band]; } else if (eQPreset == mEQNumPresets) { // CI EXTREME bandLevel[band] = eQPresetCIExtremeBandLevel[band]; } else { // User bandLevel[band] = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]); } editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]); editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevel[band]); editor.putInt(Key.eq_preset_user_band_level_default.toString() + band, eQPresetUserBandLevelDefault[band]); } for (short preset = 0; preset < mEQNumPresets; preset++) { editor.putString(Key.eq_preset_name.toString() + preset, mEQPresetNames[preset]); for (short band = 0; band < mEQNumBands; band++) { editor.putInt(Key.eq_preset_opensl_es_band_level.toString() + preset + "_" + band, mEQPresetOpenSLESBandLevel[preset][band]); } } } final boolean isEQEnabled = prefs.getBoolean(Key.eq_enabled.toString(), EQUALIZER_ENABLED_DEFAULT); editor.putBoolean(Key.eq_enabled.toString(), isEQEnabled); // Preset reverb final boolean isEnabledPR = prefs.getBoolean(Key.pr_enabled.toString(), PRESET_REVERB_ENABLED_DEFAULT); final short presetPR = (short) prefs.getInt(Key.pr_current_preset.toString(), PRESET_REVERB_CURRENT_PRESET_DEFAULT); editor.putBoolean(Key.pr_enabled.toString(), isEnabledPR); editor.putInt(Key.pr_current_preset.toString(), presetPR); editor.commit(); } catch (final RuntimeException e) { Log.e(TAG, "initEffectsPreferences: processingEnabled: " + e); } } /** * Gets the effect control mode based on the given audio session in the control panel. Control * mode defines if the control panel is controlling effects and/or preferences * * @param audioSession * System wide unique audio session identifier. * @return effect control mode */ public static ControlMode getControlMode(final int audioSession) { if (audioSession == AudioEffect.ERROR_BAD_VALUE) { return ControlMode.CONTROL_PREFERENCES; } return ControlMode.CONTROL_EFFECTS; } /** * Sets boolean parameter to value for given key * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @param value */ public static void setParameterBoolean(final Context context, final String packageName, final int audioSession, final Key key, final boolean value) { try { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final ControlMode controlMode = getControlMode(audioSession); boolean enabled = value; // Global on/off if (key == Key.global_enabled) { boolean processingEnabled = false; if (value == true) { // enable all with respect to preferences if (controlMode == ControlMode.CONTROL_EFFECTS) { final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); if (virtualizerEffect != null) { virtualizerEffect.setEnabled(prefs.getBoolean( Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT)); final int vIStrength = prefs.getInt(Key.virt_strength.toString(), VIRTUALIZER_STRENGTH_DEFAULT); setParameterInt(context, packageName, audioSession, Key.virt_strength, vIStrength); } final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); if (bassBoostEffect != null) { bassBoostEffect.setEnabled(prefs.getBoolean(Key.bb_enabled.toString(), BASS_BOOST_ENABLED_DEFAULT)); final int bBStrength = prefs.getInt(Key.bb_strength.toString(), BASS_BOOST_STRENGTH_DEFAULT); setParameterInt(context, packageName, audioSession, Key.bb_strength, bBStrength); } final Equalizer equalizerEffect = getEqualizerEffect(audioSession); if (equalizerEffect != null) { equalizerEffect.setEnabled(prefs.getBoolean(Key.eq_enabled.toString(), EQUALIZER_ENABLED_DEFAULT)); final int[] bandLevels = getParameterIntArray(context, packageName, audioSession, Key.eq_band_level); final int len = bandLevels.length; for (short band = 0; band < len; band++) { final int level = bandLevels[band]; setParameterInt(context, packageName, audioSession, Key.eq_band_level, level, band); } } // XXX: Preset Reverb not used for the moment, so commented out the effect // creation to not use MIPS // final PresetReverb presetReverbEffect = // getPresetReverbEffect(audioSession); // if (presetReverbEffect != null) { // presetReverbEffect.setEnabled(prefs.getBoolean( // Key.pr_enabled.toString(), PRESET_REVERB_ENABLED_DEFAULT)); // } } processingEnabled = true; Log.v(TAG, "processingEnabled=" + processingEnabled); } else { // disable all if (controlMode == ControlMode.CONTROL_EFFECTS) { final Virtualizer virtualizerEffect = getVirtualizerEffectNoCreate(audioSession); if (virtualizerEffect != null) { mVirtualizerInstances.remove(audioSession, virtualizerEffect); virtualizerEffect.setEnabled(false); virtualizerEffect.release(); } final BassBoost bassBoostEffect = getBassBoostEffectNoCreate(audioSession); if (bassBoostEffect != null) { mBassBoostInstances.remove(audioSession, bassBoostEffect); bassBoostEffect.setEnabled(false); bassBoostEffect.release(); } final Equalizer equalizerEffect = getEqualizerEffectNoCreate(audioSession); if (equalizerEffect != null) { mEQInstances.remove(audioSession, equalizerEffect); equalizerEffect.setEnabled(false); equalizerEffect.release(); } // XXX: Preset Reverb not used for the moment, so commented out the effect // creation to not use MIPS // final PresetReverb presetReverbEffect = // getPresetReverbEffect(audioSession); // if (presetReverbEffect != null) { // presetReverbEffect.setEnabled(false); // } } processingEnabled = false; Log.v(TAG, "processingEnabled=" + processingEnabled); } enabled = processingEnabled; } else if (controlMode == ControlMode.CONTROL_EFFECTS) { final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(), GLOBAL_ENABLED_DEFAULT); if (isGlobalEnabled == true) { // Set effect parameters switch (key) { case global_enabled: // Global, already handled, to get out error free break; // Virtualizer case virt_enabled: final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); if (virtualizerEffect != null) { virtualizerEffect.setEnabled(value); enabled = virtualizerEffect.getEnabled(); } break; // BassBoost case bb_enabled: final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); if (bassBoostEffect != null) { bassBoostEffect.setEnabled(value); enabled = bassBoostEffect.getEnabled(); } break; // Equalizer case eq_enabled: final Equalizer equalizerEffect = getEqualizerEffect(audioSession); if (equalizerEffect != null) { equalizerEffect.setEnabled(value); enabled = equalizerEffect.getEnabled(); } break; // PresetReverb case pr_enabled: // XXX: Preset Reverb not used for the moment, so commented out the effect // creation to not use MIPS // final PresetReverb presetReverbEffect = // getPresetReverbEffect(audioSession); // if (presetReverbEffect != null) { // presetReverbEffect.setEnabled(value); // enabled = presetReverbEffect.getEnabled(); // } break; default: Log.e(TAG, "Unknown/unsupported key " + key); return; } } } // Set preferences final SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(key.toString(), enabled); editor.commit(); } catch (final RuntimeException e) { Log.e(TAG, "setParameterBoolean: " + key + "; " + value + "; " + e); } } /** * Gets boolean parameter for given key * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value */ public static Boolean getParameterBoolean(final Context context, final String packageName, final int audioSession, final Key key) { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); boolean value = false; try { value = prefs.getBoolean(key.toString(), value); } catch (final RuntimeException e) { Log.e(TAG, "getParameterBoolean: " + key + "; " + value + "; " + e); } return value; } /** * Sets int parameter for given key and value arg0, arg1 * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @param arg0 * @param arg1 */ public static void setParameterInt(final Context context, final String packageName, final int audioSession, final Key key, final int arg0, final int arg1) { String strKey = key.toString(); int value = arg0; try { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); final ControlMode controlMode = getControlMode(audioSession); // Set effect parameters if (controlMode == ControlMode.CONTROL_EFFECTS) { switch (key) { // Virtualizer case virt_strength: { final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); if (virtualizerEffect != null) { virtualizerEffect.setStrength((short) value); value = virtualizerEffect.getRoundedStrength(); } break; } // BassBoost case bb_strength: { final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); if (bassBoostEffect != null) { bassBoostEffect.setStrength((short) value); value = bassBoostEffect.getRoundedStrength(); } break; } // Equalizer case eq_band_level: { if (arg1 == DUMMY_ARGUMENT) { throw new IllegalArgumentException("Dummy arg passed."); } final short band = (short) arg1; strKey = strKey + band; final Equalizer equalizerEffect = getEqualizerEffect(audioSession); if (equalizerEffect != null) { equalizerEffect.setBandLevel(band, (short) value); value = equalizerEffect.getBandLevel(band); // save band level in User preset editor.putInt(Key.eq_preset_user_band_level.toString() + band, value); } break; } case eq_current_preset: { final Equalizer equalizerEffect = getEqualizerEffect(audioSession); if (equalizerEffect != null) { final short preset = (short) value; final int numBands = prefs.getInt(Key.eq_num_bands.toString(), EQUALIZER_NUMBER_BANDS_DEFAULT); final int numPresets = prefs.getInt(Key.eq_num_presets.toString(), EQUALIZER_NUMBER_PRESETS_DEFAULT); if (preset < numPresets) { // OpenSL ES EQ Effect presets equalizerEffect.usePreset(preset); value = equalizerEffect.getCurrentPreset(); } else { final short[] eQPresetCIExtremeBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, numBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, numBands); // Set the band levels manually for custom presets for (short band = 0; band < numBands; band++) { short bandLevel = 0; if (preset == numPresets) { // CI EXTREME bandLevel = (short) prefs.getInt( Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevelDefault[band]); } else { // User bandLevel = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } equalizerEffect.setBandLevel(band, bandLevel); } } // update band levels for (short band = 0; band < numBands; band++) { final short level = equalizerEffect.getBandLevel(band); editor.putInt(Key.eq_band_level.toString() + band, level); } } break; } case eq_preset_user_band_level: // Fall through case eq_preset_user_band_level_default: // Fall through case eq_preset_ci_extreme_band_level: { if (arg1 == DUMMY_ARGUMENT) { throw new IllegalArgumentException("Dummy arg passed."); } final short band = (short) arg1; strKey = strKey + band; break; } case pr_current_preset: // XXX: Preset Reverb not used for the moment, so commented out the effect // creation to not use MIPS // final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession); // if (presetReverbEffect != null) { // presetReverbEffect.setPreset((short) value); // value = presetReverbEffect.getPreset(); // } break; default: Log.e(TAG, "setParameterInt: Unknown/unsupported key " + key); return; } } else { switch (key) { // Virtualizer case virt_strength: // Do nothing break; case virt_type: // Do nothing break; // BassBoost case bb_strength: // Do nothing break; // Equalizer case eq_band_level: { if (arg1 == DUMMY_ARGUMENT) { throw new IllegalArgumentException("Dummy arg passed."); } final short band = (short) arg1; strKey = strKey + band; editor.putInt(Key.eq_preset_user_band_level.toString() + band, value); break; } case eq_current_preset: { final short preset = (short) value; final int numBands = prefs.getInt(Key.eq_num_bands.toString(), EQUALIZER_NUMBER_BANDS_DEFAULT); final int numPresets = prefs.getInt(Key.eq_num_presets.toString(), EQUALIZER_NUMBER_PRESETS_DEFAULT); final short[][] eQPresetOpenSLESBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT, numBands); final short[] eQPresetCIExtremeBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, numBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, numBands); for (short band = 0; band < numBands; band++) { short bandLevel = 0; if (preset < numPresets) { // OpenSL ES EQ Effect presets bandLevel = (short) prefs.getInt( Key.eq_preset_opensl_es_band_level.toString() + preset + "_" + band, eQPresetOpenSLESBandLevelDefault[preset][band]); } else if (preset == numPresets) { // CI EXTREME bandLevel = (short) prefs.getInt( Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevelDefault[band]); } else { // User bandLevel = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } editor.putInt(Key.eq_band_level.toString() + band, bandLevel); } break; } case eq_preset_user_band_level: // Fall through case eq_preset_user_band_level_default: // Fall through case eq_preset_ci_extreme_band_level: { if (arg1 == DUMMY_ARGUMENT) { throw new IllegalArgumentException("Dummy arg passed."); } final short band = (short) arg1; strKey = strKey + band; break; } case pr_current_preset: // Do nothing break; default: Log.e(TAG, "setParameterInt: Unknown/unsupported key " + key); return; } } // Set preferences editor.putInt(strKey, value); editor.apply(); } catch (final RuntimeException e) { Log.e(TAG, "setParameterInt: " + key + "; " + arg0 + "; " + arg1 + "; " + e); } } /** * Sets int parameter for given key and value arg * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @param arg */ public static void setParameterInt(final Context context, final String packageName, final int audioSession, final Key key, final int arg) { setParameterInt(context, packageName, audioSession, key, arg, DUMMY_ARGUMENT); } /** * Gets int parameter given key * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value */ public static int getParameterInt(final Context context, final String packageName, final int audioSession, final String key) { int value = 0; try { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); value = prefs.getInt(key, value); } catch (final RuntimeException e) { Log.e(TAG, "getParameterInt: " + key + "; " + e); } return value; } /** * Gets int parameter given key * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value */ public static int getParameterInt(final Context context, final String packageName, final int audioSession, final Key key) { return getParameterInt(context, packageName, audioSession, key.toString()); } /** * Gets int parameter given key and arg * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param audioSession * @param key * @param arg * @return parameter value */ public static int getParameterInt(final Context context, final String packageName, final int audioSession, final Key key, final int arg) { return getParameterInt(context, packageName, audioSession, key.toString() + arg); } /** * Gets int parameter given key, arg0 and arg1 * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param audioSession * @param key * @param arg0 * @param arg1 * @return parameter value */ public static int getParameterInt(final Context context, final String packageName, final int audioSession, final Key key, final int arg0, final int arg1) { return getParameterInt(context, packageName, audioSession, key.toString() + arg0 + "_" + arg1); } /** * Gets integer array parameter given key. Returns null if not found. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value array */ public static int[] getParameterIntArray(final Context context, final String packageName, final int audioSession, final Key key) { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); int[] intArray = null; try { // Get effect parameters switch (key) { case eq_level_range: { intArray = new int[2]; break; } case eq_center_freq: // Fall through case eq_band_level: // Fall through case eq_preset_user_band_level: // Fall through case eq_preset_user_band_level_default: // Fall through case eq_preset_ci_extreme_band_level: { final int numBands = prefs.getInt(Key.eq_num_bands.toString(), 0); intArray = new int[numBands]; break; } default: Log.e(TAG, "getParameterIntArray: Unknown/unsupported key " + key); return null; } for (int i = 0; i < intArray.length; i++) { intArray[i] = prefs.getInt(key.toString() + i, 0); } } catch (final RuntimeException e) { Log.e(TAG, "getParameterIntArray: " + key + "; " + e); } return intArray; } /** * Gets string parameter given key. Returns empty string if not found. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value */ public static String getParameterString(final Context context, final String packageName, final int audioSession, final String key) { String value = ""; try { final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); // Get effect parameters value = prefs.getString(key, value); } catch (final RuntimeException e) { Log.e(TAG, "getParameterString: " + key + "; " + e); } return value; } /** * Gets string parameter given key. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param key * @return parameter value */ public static String getParameterString(final Context context, final String packageName, final int audioSession, final Key key) { return getParameterString(context, packageName, audioSession, key.toString()); } /** * Gets string parameter given key and arg. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param args * @return parameter value */ public static String getParameterString(final Context context, final String packageName, final int audioSession, final Key key, final int arg) { return getParameterString(context, packageName, audioSession, key.toString() + arg); } /** * Opens/initializes the effects session for the given audio session with preferences linked to * the given package name and context. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. */ public static void openSession(final Context context, final String packageName, final int audioSession) { Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")"); final String methodTag = "openSession: "; // init preferences final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(), GLOBAL_ENABLED_DEFAULT); editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled); if (!isGlobalEnabled) { return; } // Manage audioSession information // Retrieve AudioSession Id from map boolean isExistingAudioSession = false; try { final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName, audioSession); if (currentAudioSession != null) { // Compare with passed argument if (currentAudioSession == audioSession) { // FIXME: Normally, we should exit the function here // BUT: we have to take care of the virtualizer because of // a bug in the Android Effects Framework // editor.commit(); // return; isExistingAudioSession = true; } else { closeSession(context, packageName, currentAudioSession); } } } catch (final NullPointerException e) { Log.e(TAG, methodTag + e); editor.commit(); return; } // Because the audioSession is new, get effects & settings from shared preferences // Virtualizer // create effect final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); { final String errorTag = methodTag + "Virtualizer error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.virt_strength.toString(), VIRTUALIZER_STRENGTH_DEFAULT); // init settings Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength=" + strength); virtualizerEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { virtualizerEffect.setEnabled(isEnabled); } else { virtualizerEffect.setEnabled(false); } // get parameters settings = virtualizerEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.virt_enabled.toString(), isEnabled); editor.putInt(Key.virt_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // In case of an existing audio session // Exit after the virtualizer has been re-enabled if (isExistingAudioSession) { - editor.commit(); + editor.apply(); return; } // BassBoost // create effect final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); { final String errorTag = methodTag + "BassBoost error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(), BASS_BOOST_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.bb_strength.toString(), BASS_BOOST_STRENGTH_DEFAULT); // init settings BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength=" + strength); bassBoostEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { bassBoostEffect.setEnabled(isEnabled); } else { bassBoostEffect.setEnabled(false); } // get parameters settings = bassBoostEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.bb_enabled.toString(), isEnabled); editor.putInt(Key.bb_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // Equalizer // create effect final Equalizer equalizerEffect = getEqualizerEffect(audioSession); { final String errorTag = methodTag + "Equalizer error: "; try { final short eQNumBands; final short[] bandLevel; final int[] eQCenterFreq; final short eQNumPresets; final String[] eQPresetNames; short eQPreset; synchronized (mEQInitLock) { // read parameters mEQBandLevelRange = equalizerEffect.getBandLevelRange(); mEQNumBands = equalizerEffect.getNumberOfBands(); mEQCenterFreq = new int[mEQNumBands]; mEQNumPresets = equalizerEffect.getNumberOfPresets(); mEQPresetNames = new String[mEQNumPresets]; for (short preset = 0; preset < mEQNumPresets; preset++) { mEQPresetNames[preset] = equalizerEffect.getPresetName(preset); editor.putString(Key.eq_preset_name.toString() + preset, mEQPresetNames[preset]); } editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]); editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]); editor.putInt(Key.eq_num_bands.toString(), mEQNumBands); editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets); // Resetting the EQ arrays depending on the real # bands with defaults if band < // default size else 0 by copying default arrays over new ones final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands); // If no preset prefs set use CI EXTREME (= numPresets) eQPreset = (short) prefs .getInt(Key.eq_current_preset.toString(), mEQNumPresets); if (eQPreset < mEQNumPresets) { // OpenSL ES effect presets equalizerEffect.usePreset(eQPreset); eQPreset = equalizerEffect.getCurrentPreset(); } else { for (short band = 0; band < mEQNumBands; band++) { short level = 0; if (eQPreset == mEQNumPresets) { // CI EXTREME level = eQPresetCIExtremeBandLevel[band]; } else { // User level = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } equalizerEffect.setBandLevel(band, level); } } editor.putInt(Key.eq_current_preset.toString(), eQPreset); bandLevel = new short[mEQNumBands]; for (short band = 0; band < mEQNumBands; band++) { mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band); bandLevel[band] = equalizerEffect.getBandLevel(band); editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]); editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]); editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevel[band]); editor.putInt(Key.eq_preset_user_band_level_default.toString() + band, eQPresetUserBandLevelDefault[band]); } eQNumBands = mEQNumBands; eQCenterFreq = mEQCenterFreq; eQNumPresets = mEQNumPresets; eQPresetNames = mEQPresetNames; } final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(), EQUALIZER_ENABLED_DEFAULT); editor.putBoolean(Key.eq_enabled.toString(), isEnabled); if (isGlobalEnabled == true) { equalizerEffect.setEnabled(isEnabled); } else { equalizerEffect.setEnabled(false); } // dump Log.v(TAG, "Parameters: Equalizer"); Log.v(TAG, "bands=" + eQNumBands); String str = "levels="; for (short band = 0; band < eQNumBands; band++) { str = str + bandLevel[band] + "; "; } Log.v(TAG, str); str = "center="; for (short band = 0; band < eQNumBands; band++) { str = str + eQCenterFreq[band] + "; "; } Log.v(TAG, str); str = "presets="; for (short preset = 0; preset < eQNumPresets; preset++) { str = str + eQPresetNames[preset] + "; "; } Log.v(TAG, str); Log.v(TAG, "current=" + eQPreset); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // XXX: Preset Reverb not used for the moment, so commented out the effect creation to not // use MIPS left in the code for (future) reference. // Preset reverb // create effect // final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession); // { // final String errorTag = methodTag + "PresetReverb error: "; // // try { // // read parameters // final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(), // PRESET_REVERB_ENABLED_DEFAULT); // final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(), // PRESET_REVERB_CURRENT_PRESET_DEFAULT); // // // init settings // PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset=" // + preset); // // // read/update preferences // presetReverbEffect.setProperties(settings); // // // set parameters // if (isGlobalEnabled == true) { // presetReverbEffect.setEnabled(isEnabled); // } else { // presetReverbEffect.setEnabled(false); // } // // // get parameters // settings = presetReverbEffect.getProperties(); // Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // // // update preferences // editor.putBoolean(Key.pr_enabled.toString(), isEnabled); // editor.putInt(Key.pr_current_preset.toString(), settings.preset); // } catch (final RuntimeException e) { // Log.e(TAG, errorTag + e); // } // } editor.commit(); } /** * Closes the audio session (release effects) for the given session * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. */ public static void closeSession(final Context context, final String packageName, final int audioSession) { Log.v(TAG, "closeSession(" + context + ", " + packageName + ", " + audioSession + ")"); // PresetReverb final PresetReverb presetReverb = mPresetReverbInstances.remove(audioSession); if (presetReverb != null) { presetReverb.release(); } // Equalizer final Equalizer equalizer = mEQInstances.remove(audioSession); if (equalizer != null) { equalizer.release(); } // BassBoost final BassBoost bassBoost = mBassBoostInstances.remove(audioSession); if (bassBoost != null) { bassBoost.release(); } // Virtualizer final Virtualizer virtualizer = mVirtualizerInstances.remove(audioSession); if (virtualizer != null) { virtualizer.release(); } mPackageSessions.remove(packageName); } /** * Enables or disables all effects (global enable/disable) for a given context, package name and * audio session. It sets/inits the control mode and preferences and then sets the global * enabled parameter. * * @param context * @param packageName * @param audioSession * System wide unique audio session identifier. * @param enabled */ public static void setEnabledAll(final Context context, final String packageName, final int audioSession, final boolean enabled) { initEffectsPreferences(context, packageName, audioSession); setParameterBoolean(context, packageName, audioSession, Key.global_enabled, enabled); } /** * Gets the virtualizer effect for the given audio session. If the effect on the session doesn't * exist yet, create it and add to collection. * * @param audioSession * System wide unique audio session identifier. * @return virtualizerEffect */ private static Virtualizer getVirtualizerEffectNoCreate(final int audioSession) { return mVirtualizerInstances.get(audioSession); } private static Virtualizer getVirtualizerEffect(final int audioSession) { Virtualizer virtualizerEffect = getVirtualizerEffectNoCreate(audioSession); if (virtualizerEffect == null) { try { final Virtualizer newVirtualizerEffect = new Virtualizer(PRIORITY, audioSession); virtualizerEffect = mVirtualizerInstances.putIfAbsent(audioSession, newVirtualizerEffect); if (virtualizerEffect == null) { // put succeeded, use new value virtualizerEffect = newVirtualizerEffect; } } catch (final IllegalArgumentException e) { Log.e(TAG, "Virtualizer: " + e); } catch (final UnsupportedOperationException e) { Log.e(TAG, "Virtualizer: " + e); } catch (final RuntimeException e) { Log.e(TAG, "Virtualizer: " + e); } } return virtualizerEffect; } /** * Gets the bass boost effect for the given audio session. If the effect on the session doesn't * exist yet, create it and add to collection. * * @param audioSession * System wide unique audio session identifier. * @return bassBoostEffect */ private static BassBoost getBassBoostEffectNoCreate(final int audioSession) { return mBassBoostInstances.get(audioSession); } private static BassBoost getBassBoostEffect(final int audioSession) { BassBoost bassBoostEffect = getBassBoostEffectNoCreate(audioSession); if (bassBoostEffect == null) { try { final BassBoost newBassBoostEffect = new BassBoost(PRIORITY, audioSession); bassBoostEffect = mBassBoostInstances.putIfAbsent(audioSession, newBassBoostEffect); if (bassBoostEffect == null) { // put succeeded, use new value bassBoostEffect = newBassBoostEffect; } } catch (final IllegalArgumentException e) { Log.e(TAG, "BassBoost: " + e); } catch (final UnsupportedOperationException e) { Log.e(TAG, "BassBoost: " + e); } catch (final RuntimeException e) { Log.e(TAG, "BassBoost: " + e); } } return bassBoostEffect; } /** * Gets the equalizer effect for the given audio session. If the effect on the session doesn't * exist yet, create it and add to collection. * * @param audioSession * System wide unique audio session identifier. * @return equalizerEffect */ private static Equalizer getEqualizerEffectNoCreate(final int audioSession) { return mEQInstances.get(audioSession); } private static Equalizer getEqualizerEffect(final int audioSession) { Equalizer equalizerEffect = getEqualizerEffectNoCreate(audioSession); if (equalizerEffect == null) { try { final Equalizer newEqualizerEffect = new Equalizer(PRIORITY, audioSession); equalizerEffect = mEQInstances.putIfAbsent(audioSession, newEqualizerEffect); if (equalizerEffect == null) { // put succeeded, use new value equalizerEffect = newEqualizerEffect; } } catch (final IllegalArgumentException e) { Log.e(TAG, "Equalizer: " + e); } catch (final UnsupportedOperationException e) { Log.e(TAG, "Equalizer: " + e); } catch (final RuntimeException e) { Log.e(TAG, "Equalizer: " + e); } } return equalizerEffect; } // XXX: Preset Reverb not used for the moment, so commented out the effect creation to not // use MIPS // /** // * Gets the preset reverb effect for the given audio session. If the effect on the session // * doesn't exist yet, create it and add to collection. // * // * @param audioSession // * System wide unique audio session identifier. // * @return presetReverbEffect // */ // private static PresetReverb getPresetReverbEffect(final int audioSession) { // PresetReverb presetReverbEffect = mPresetReverbInstances.get(audioSession); // if (presetReverbEffect == null) { // try { // final PresetReverb newPresetReverbEffect = new PresetReverb(PRIORITY, audioSession); // presetReverbEffect = mPresetReverbInstances.putIfAbsent(audioSession, // newPresetReverbEffect); // if (presetReverbEffect == null) { // // put succeeded, use new value // presetReverbEffect = newPresetReverbEffect; // } // } catch (final IllegalArgumentException e) { // Log.e(TAG, "PresetReverb: " + e); // } catch (final UnsupportedOperationException e) { // Log.e(TAG, "PresetReverb: " + e); // } catch (final RuntimeException e) { // Log.e(TAG, "PresetReverb: " + e); // } // } // return presetReverbEffect; // } }
true
true
public static void openSession(final Context context, final String packageName, final int audioSession) { Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")"); final String methodTag = "openSession: "; // init preferences final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(), GLOBAL_ENABLED_DEFAULT); editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled); if (!isGlobalEnabled) { return; } // Manage audioSession information // Retrieve AudioSession Id from map boolean isExistingAudioSession = false; try { final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName, audioSession); if (currentAudioSession != null) { // Compare with passed argument if (currentAudioSession == audioSession) { // FIXME: Normally, we should exit the function here // BUT: we have to take care of the virtualizer because of // a bug in the Android Effects Framework // editor.commit(); // return; isExistingAudioSession = true; } else { closeSession(context, packageName, currentAudioSession); } } } catch (final NullPointerException e) { Log.e(TAG, methodTag + e); editor.commit(); return; } // Because the audioSession is new, get effects & settings from shared preferences // Virtualizer // create effect final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); { final String errorTag = methodTag + "Virtualizer error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.virt_strength.toString(), VIRTUALIZER_STRENGTH_DEFAULT); // init settings Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength=" + strength); virtualizerEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { virtualizerEffect.setEnabled(isEnabled); } else { virtualizerEffect.setEnabled(false); } // get parameters settings = virtualizerEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.virt_enabled.toString(), isEnabled); editor.putInt(Key.virt_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // In case of an existing audio session // Exit after the virtualizer has been re-enabled if (isExistingAudioSession) { editor.commit(); return; } // BassBoost // create effect final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); { final String errorTag = methodTag + "BassBoost error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(), BASS_BOOST_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.bb_strength.toString(), BASS_BOOST_STRENGTH_DEFAULT); // init settings BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength=" + strength); bassBoostEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { bassBoostEffect.setEnabled(isEnabled); } else { bassBoostEffect.setEnabled(false); } // get parameters settings = bassBoostEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.bb_enabled.toString(), isEnabled); editor.putInt(Key.bb_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // Equalizer // create effect final Equalizer equalizerEffect = getEqualizerEffect(audioSession); { final String errorTag = methodTag + "Equalizer error: "; try { final short eQNumBands; final short[] bandLevel; final int[] eQCenterFreq; final short eQNumPresets; final String[] eQPresetNames; short eQPreset; synchronized (mEQInitLock) { // read parameters mEQBandLevelRange = equalizerEffect.getBandLevelRange(); mEQNumBands = equalizerEffect.getNumberOfBands(); mEQCenterFreq = new int[mEQNumBands]; mEQNumPresets = equalizerEffect.getNumberOfPresets(); mEQPresetNames = new String[mEQNumPresets]; for (short preset = 0; preset < mEQNumPresets; preset++) { mEQPresetNames[preset] = equalizerEffect.getPresetName(preset); editor.putString(Key.eq_preset_name.toString() + preset, mEQPresetNames[preset]); } editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]); editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]); editor.putInt(Key.eq_num_bands.toString(), mEQNumBands); editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets); // Resetting the EQ arrays depending on the real # bands with defaults if band < // default size else 0 by copying default arrays over new ones final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands); // If no preset prefs set use CI EXTREME (= numPresets) eQPreset = (short) prefs .getInt(Key.eq_current_preset.toString(), mEQNumPresets); if (eQPreset < mEQNumPresets) { // OpenSL ES effect presets equalizerEffect.usePreset(eQPreset); eQPreset = equalizerEffect.getCurrentPreset(); } else { for (short band = 0; band < mEQNumBands; band++) { short level = 0; if (eQPreset == mEQNumPresets) { // CI EXTREME level = eQPresetCIExtremeBandLevel[band]; } else { // User level = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } equalizerEffect.setBandLevel(band, level); } } editor.putInt(Key.eq_current_preset.toString(), eQPreset); bandLevel = new short[mEQNumBands]; for (short band = 0; band < mEQNumBands; band++) { mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band); bandLevel[band] = equalizerEffect.getBandLevel(band); editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]); editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]); editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevel[band]); editor.putInt(Key.eq_preset_user_band_level_default.toString() + band, eQPresetUserBandLevelDefault[band]); } eQNumBands = mEQNumBands; eQCenterFreq = mEQCenterFreq; eQNumPresets = mEQNumPresets; eQPresetNames = mEQPresetNames; } final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(), EQUALIZER_ENABLED_DEFAULT); editor.putBoolean(Key.eq_enabled.toString(), isEnabled); if (isGlobalEnabled == true) { equalizerEffect.setEnabled(isEnabled); } else { equalizerEffect.setEnabled(false); } // dump Log.v(TAG, "Parameters: Equalizer"); Log.v(TAG, "bands=" + eQNumBands); String str = "levels="; for (short band = 0; band < eQNumBands; band++) { str = str + bandLevel[band] + "; "; } Log.v(TAG, str); str = "center="; for (short band = 0; band < eQNumBands; band++) { str = str + eQCenterFreq[band] + "; "; } Log.v(TAG, str); str = "presets="; for (short preset = 0; preset < eQNumPresets; preset++) { str = str + eQPresetNames[preset] + "; "; } Log.v(TAG, str); Log.v(TAG, "current=" + eQPreset); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // XXX: Preset Reverb not used for the moment, so commented out the effect creation to not // use MIPS left in the code for (future) reference. // Preset reverb // create effect // final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession); // { // final String errorTag = methodTag + "PresetReverb error: "; // // try { // // read parameters // final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(), // PRESET_REVERB_ENABLED_DEFAULT); // final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(), // PRESET_REVERB_CURRENT_PRESET_DEFAULT); // // // init settings // PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset=" // + preset); // // // read/update preferences // presetReverbEffect.setProperties(settings); // // // set parameters // if (isGlobalEnabled == true) { // presetReverbEffect.setEnabled(isEnabled); // } else { // presetReverbEffect.setEnabled(false); // } // // // get parameters // settings = presetReverbEffect.getProperties(); // Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // // // update preferences // editor.putBoolean(Key.pr_enabled.toString(), isEnabled); // editor.putInt(Key.pr_current_preset.toString(), settings.preset); // } catch (final RuntimeException e) { // Log.e(TAG, errorTag + e); // } // } editor.commit(); }
public static void openSession(final Context context, final String packageName, final int audioSession) { Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")"); final String methodTag = "openSession: "; // init preferences final SharedPreferences prefs = context.getSharedPreferences(packageName, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = prefs.edit(); final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(), GLOBAL_ENABLED_DEFAULT); editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled); if (!isGlobalEnabled) { return; } // Manage audioSession information // Retrieve AudioSession Id from map boolean isExistingAudioSession = false; try { final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName, audioSession); if (currentAudioSession != null) { // Compare with passed argument if (currentAudioSession == audioSession) { // FIXME: Normally, we should exit the function here // BUT: we have to take care of the virtualizer because of // a bug in the Android Effects Framework // editor.commit(); // return; isExistingAudioSession = true; } else { closeSession(context, packageName, currentAudioSession); } } } catch (final NullPointerException e) { Log.e(TAG, methodTag + e); editor.commit(); return; } // Because the audioSession is new, get effects & settings from shared preferences // Virtualizer // create effect final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession); { final String errorTag = methodTag + "Virtualizer error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.virt_strength.toString(), VIRTUALIZER_STRENGTH_DEFAULT); // init settings Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength=" + strength); virtualizerEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { virtualizerEffect.setEnabled(isEnabled); } else { virtualizerEffect.setEnabled(false); } // get parameters settings = virtualizerEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.virt_enabled.toString(), isEnabled); editor.putInt(Key.virt_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // In case of an existing audio session // Exit after the virtualizer has been re-enabled if (isExistingAudioSession) { editor.apply(); return; } // BassBoost // create effect final BassBoost bassBoostEffect = getBassBoostEffect(audioSession); { final String errorTag = methodTag + "BassBoost error: "; try { // read parameters final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(), BASS_BOOST_ENABLED_DEFAULT); final int strength = prefs.getInt(Key.bb_strength.toString(), BASS_BOOST_STRENGTH_DEFAULT); // init settings BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength=" + strength); bassBoostEffect.setProperties(settings); // set parameters if (isGlobalEnabled == true) { bassBoostEffect.setEnabled(isEnabled); } else { bassBoostEffect.setEnabled(false); } // get parameters settings = bassBoostEffect.getProperties(); Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // update preferences editor.putBoolean(Key.bb_enabled.toString(), isEnabled); editor.putInt(Key.bb_strength.toString(), settings.strength); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // Equalizer // create effect final Equalizer equalizerEffect = getEqualizerEffect(audioSession); { final String errorTag = methodTag + "Equalizer error: "; try { final short eQNumBands; final short[] bandLevel; final int[] eQCenterFreq; final short eQNumPresets; final String[] eQPresetNames; short eQPreset; synchronized (mEQInitLock) { // read parameters mEQBandLevelRange = equalizerEffect.getBandLevelRange(); mEQNumBands = equalizerEffect.getNumberOfBands(); mEQCenterFreq = new int[mEQNumBands]; mEQNumPresets = equalizerEffect.getNumberOfPresets(); mEQPresetNames = new String[mEQNumPresets]; for (short preset = 0; preset < mEQNumPresets; preset++) { mEQPresetNames[preset] = equalizerEffect.getPresetName(preset); editor.putString(Key.eq_preset_name.toString() + preset, mEQPresetNames[preset]); } editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]); editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]); editor.putInt(Key.eq_num_bands.toString(), mEQNumBands); editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets); // Resetting the EQ arrays depending on the real # bands with defaults if band < // default size else 0 by copying default arrays over new ones final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf( EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands); final short[] eQPresetUserBandLevelDefault = Arrays.copyOf( EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands); // If no preset prefs set use CI EXTREME (= numPresets) eQPreset = (short) prefs .getInt(Key.eq_current_preset.toString(), mEQNumPresets); if (eQPreset < mEQNumPresets) { // OpenSL ES effect presets equalizerEffect.usePreset(eQPreset); eQPreset = equalizerEffect.getCurrentPreset(); } else { for (short band = 0; band < mEQNumBands; band++) { short level = 0; if (eQPreset == mEQNumPresets) { // CI EXTREME level = eQPresetCIExtremeBandLevel[band]; } else { // User level = (short) prefs.getInt( Key.eq_preset_user_band_level.toString() + band, eQPresetUserBandLevelDefault[band]); } equalizerEffect.setBandLevel(band, level); } } editor.putInt(Key.eq_current_preset.toString(), eQPreset); bandLevel = new short[mEQNumBands]; for (short band = 0; band < mEQNumBands; band++) { mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band); bandLevel[band] = equalizerEffect.getBandLevel(band); editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]); editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]); editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band, eQPresetCIExtremeBandLevel[band]); editor.putInt(Key.eq_preset_user_band_level_default.toString() + band, eQPresetUserBandLevelDefault[band]); } eQNumBands = mEQNumBands; eQCenterFreq = mEQCenterFreq; eQNumPresets = mEQNumPresets; eQPresetNames = mEQPresetNames; } final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(), EQUALIZER_ENABLED_DEFAULT); editor.putBoolean(Key.eq_enabled.toString(), isEnabled); if (isGlobalEnabled == true) { equalizerEffect.setEnabled(isEnabled); } else { equalizerEffect.setEnabled(false); } // dump Log.v(TAG, "Parameters: Equalizer"); Log.v(TAG, "bands=" + eQNumBands); String str = "levels="; for (short band = 0; band < eQNumBands; band++) { str = str + bandLevel[band] + "; "; } Log.v(TAG, str); str = "center="; for (short band = 0; band < eQNumBands; band++) { str = str + eQCenterFreq[band] + "; "; } Log.v(TAG, str); str = "presets="; for (short preset = 0; preset < eQNumPresets; preset++) { str = str + eQPresetNames[preset] + "; "; } Log.v(TAG, str); Log.v(TAG, "current=" + eQPreset); } catch (final RuntimeException e) { Log.e(TAG, errorTag + e); } } // XXX: Preset Reverb not used for the moment, so commented out the effect creation to not // use MIPS left in the code for (future) reference. // Preset reverb // create effect // final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession); // { // final String errorTag = methodTag + "PresetReverb error: "; // // try { // // read parameters // final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(), // PRESET_REVERB_ENABLED_DEFAULT); // final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(), // PRESET_REVERB_CURRENT_PRESET_DEFAULT); // // // init settings // PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset=" // + preset); // // // read/update preferences // presetReverbEffect.setProperties(settings); // // // set parameters // if (isGlobalEnabled == true) { // presetReverbEffect.setEnabled(isEnabled); // } else { // presetReverbEffect.setEnabled(false); // } // // // get parameters // settings = presetReverbEffect.getProperties(); // Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled); // // // update preferences // editor.putBoolean(Key.pr_enabled.toString(), isEnabled); // editor.putInt(Key.pr_current_preset.toString(), settings.preset); // } catch (final RuntimeException e) { // Log.e(TAG, errorTag + e); // } // } editor.commit(); }
diff --git a/src/main/java/be/Balor/Player/sql/SQLPlayerFactory.java b/src/main/java/be/Balor/Player/sql/SQLPlayerFactory.java index f48128d8..09b662bd 100644 --- a/src/main/java/be/Balor/Player/sql/SQLPlayerFactory.java +++ b/src/main/java/be/Balor/Player/sql/SQLPlayerFactory.java @@ -1,189 +1,192 @@ /*This file is part of AdminCmd. AdminCmd 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. AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.*/ package be.Balor.Player.sql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.Map; import java.util.Set; import lib.SQL.PatPeter.SQLibrary.Database; import org.bukkit.entity.Player; import be.Balor.Player.ACPlayer; import be.Balor.Player.EmptyPlayer; import be.Balor.Player.IPlayerFactory; import be.Balor.Tools.Debug.ACLogger; import be.Balor.Tools.Debug.DebugLog; import com.google.common.base.Joiner; import com.google.common.collect.MapMaker; /** * @author Balor (aka Antoine Aflalo) * */ public class SQLPlayerFactory implements IPlayerFactory { private final PreparedStatement insertPlayer; private final Map<String, Long> playersID = new MapMaker() .concurrencyLevel(6).makeMap(); private final PreparedStatement doubleCheckPlayer; /** * */ public SQLPlayerFactory() { insertPlayer = Database.DATABASE .prepare("INSERT INTO `ac_players` (`name`) VALUES (?);"); final ResultSet rs = Database.DATABASE .query("SELECT `name`,`id` FROM `ac_players`"); doubleCheckPlayer = Database.DATABASE .prepare("SELECT `id` FROM `ac_players` WHERE `name` = ?"); try { while (rs.next()) { playersID.put(rs.getString("name"), rs.getLong("id")); } rs.close(); } catch (final SQLException e) { ACLogger.severe("Problem when getting players from the DB", e); } DebugLog.INSTANCE.info("Players found : " + Joiner.on(", ").join(playersID.keySet())); } private Long getPlayerID(final String playername) { Long id = playersID.get(playername); if (id != null) { return id; } + try { + Database.DATABASE.autoReconnect(); + } catch (final Throwable e) { + } - Database.DATABASE.autoReconnect(); ResultSet rs = null; synchronized (doubleCheckPlayer) { try { doubleCheckPlayer.clearParameters(); doubleCheckPlayer.setString(1, playername); doubleCheckPlayer.execute(); rs = doubleCheckPlayer.getResultSet(); if (rs == null) { return null; } if (!rs.next()) { return null; } id = rs.getLong(1); if (id != null) { playersID.put(playername, id); } } catch (final SQLException e) { return null; } finally { try { if (rs != null) { rs.close(); } } catch (final SQLException e) { } } } return id; } /* * (Non javadoc) * * @see be.Balor.Player.IPlayerFactory#createPlayer(java.lang.String) */ @Override public ACPlayer createPlayer(final String playername) { final Long id = getPlayerID(playername); if (id == null) { return new EmptyPlayer(playername); } else { return new SQLPlayer(playername, id); } } /* * (Non javadoc) * * @see * be.Balor.Player.IPlayerFactory#createPlayer(org.bukkit.entity.Player) */ @Override public ACPlayer createPlayer(final Player player) { final Long id = getPlayerID(player.getName()); if (id == null) { return new EmptyPlayer(player); } else { return new SQLPlayer(player, id); } } /* * (Non javadoc) * * @see be.Balor.Player.IPlayerFactory#getExistingPlayers() */ @Override public Set<String> getExistingPlayers() { return Collections.unmodifiableSet(playersID.keySet()); } /* * (Non javadoc) * * @see be.Balor.Player.IPlayerFactory#addExistingPlayer(java.lang.String) */ @Override public void addExistingPlayer(final String player) { if (!playersID.containsKey(player)) { ResultSet rs = null; try { synchronized (insertPlayer) { insertPlayer.clearParameters(); insertPlayer.setString(1, player); insertPlayer.executeUpdate(); rs = insertPlayer.getGeneratedKeys(); if (rs.next()) { playersID.put(player, rs.getLong(1)); } if (rs != null) { rs.close(); } } } catch (final SQLException e) { ACLogger.severe("Problem when adding player to the DB", e); if (rs != null) { try { rs.close(); } catch (final SQLException e1) { } } } } } }
false
true
private Long getPlayerID(final String playername) { Long id = playersID.get(playername); if (id != null) { return id; } Database.DATABASE.autoReconnect(); ResultSet rs = null; synchronized (doubleCheckPlayer) { try { doubleCheckPlayer.clearParameters(); doubleCheckPlayer.setString(1, playername); doubleCheckPlayer.execute(); rs = doubleCheckPlayer.getResultSet(); if (rs == null) { return null; } if (!rs.next()) { return null; } id = rs.getLong(1); if (id != null) { playersID.put(playername, id); } } catch (final SQLException e) { return null; } finally { try { if (rs != null) { rs.close(); } } catch (final SQLException e) { } } } return id; }
private Long getPlayerID(final String playername) { Long id = playersID.get(playername); if (id != null) { return id; } try { Database.DATABASE.autoReconnect(); } catch (final Throwable e) { } ResultSet rs = null; synchronized (doubleCheckPlayer) { try { doubleCheckPlayer.clearParameters(); doubleCheckPlayer.setString(1, playername); doubleCheckPlayer.execute(); rs = doubleCheckPlayer.getResultSet(); if (rs == null) { return null; } if (!rs.next()) { return null; } id = rs.getLong(1); if (id != null) { playersID.put(playername, id); } } catch (final SQLException e) { return null; } finally { try { if (rs != null) { rs.close(); } } catch (final SQLException e) { } } } return id; }
diff --git a/src/com/android/contacts/detail/ContactDetailFragment.java b/src/com/android/contacts/detail/ContactDetailFragment.java index 87c321ef6..cde1215d6 100644 --- a/src/com/android/contacts/detail/ContactDetailFragment.java +++ b/src/com/android/contacts/detail/ContactDetailFragment.java @@ -1,2233 +1,2242 @@ /* * 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.contacts.detail; import android.app.Activity; import android.app.Fragment; import android.app.SearchManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.ParseException; import android.net.Uri; import android.net.WebAddress; import android.os.Bundle; import android.os.Parcelable; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.DisplayNameSources; import android.provider.ContactsContract.StatusUpdates; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.DragEvent; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnDragListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListPopupWindow; import android.widget.ListView; import android.widget.TextView; import com.android.contacts.Collapser; import com.android.contacts.Collapser.Collapsible; import com.android.contacts.ContactPresenceIconUtil; import com.android.contacts.ContactSaveService; import com.android.contacts.ContactsUtils; import com.android.contacts.GroupMetaData; import com.android.contacts.R; import com.android.contacts.TypePrecedence; import com.android.contacts.activities.ContactDetailActivity.FragmentKeyListener; import com.android.contacts.editor.SelectAccountDialogFragment; import com.android.contacts.model.AccountTypeManager; import com.android.contacts.model.Contact; import com.android.contacts.model.RawContact; import com.android.contacts.model.RawContactDelta; import com.android.contacts.model.RawContactDelta.ValuesDelta; import com.android.contacts.model.RawContactDeltaList; import com.android.contacts.model.RawContactModifier; import com.android.contacts.model.account.AccountType; import com.android.contacts.model.account.AccountType.EditType; import com.android.contacts.model.account.AccountWithDataSet; import com.android.contacts.model.dataitem.DataItem; import com.android.contacts.model.dataitem.DataKind; import com.android.contacts.model.dataitem.EmailDataItem; import com.android.contacts.model.dataitem.EventDataItem; import com.android.contacts.model.dataitem.GroupMembershipDataItem; import com.android.contacts.model.dataitem.ImDataItem; import com.android.contacts.model.dataitem.NicknameDataItem; import com.android.contacts.model.dataitem.NoteDataItem; import com.android.contacts.model.dataitem.OrganizationDataItem; import com.android.contacts.model.dataitem.PhoneDataItem; import com.android.contacts.model.dataitem.RelationDataItem; import com.android.contacts.model.dataitem.SipAddressDataItem; import com.android.contacts.model.dataitem.StructuredNameDataItem; import com.android.contacts.model.dataitem.StructuredPostalDataItem; import com.android.contacts.model.dataitem.WebsiteDataItem; import com.android.contacts.util.AccountsListAdapter.AccountListFilter; import com.android.contacts.util.ClipboardUtils; import com.android.contacts.util.Constants; import com.android.contacts.util.DataStatus; import com.android.contacts.util.DateUtils; import com.android.contacts.util.PhoneCapabilityTester; import com.android.contacts.util.StructuredPostalUtils; import com.android.internal.telephony.ITelephony; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class ContactDetailFragment extends Fragment implements FragmentKeyListener, SelectAccountDialogFragment.Listener, OnItemClickListener { private static final String TAG = "ContactDetailFragment"; private interface ContextMenuIds { static final int COPY_TEXT = 0; static final int CLEAR_DEFAULT = 1; static final int SET_DEFAULT = 2; } private static final String KEY_CONTACT_URI = "contactUri"; private static final String KEY_LIST_STATE = "liststate"; private Context mContext; private View mView; private OnScrollListener mVerticalScrollListener; private Uri mLookupUri; private Listener mListener; private Contact mContactData; private ViewGroup mStaticPhotoContainer; private View mPhotoTouchOverlay; private ListView mListView; private ViewAdapter mAdapter; private Uri mPrimaryPhoneUri = null; private ViewEntryDimensions mViewEntryDimensions; private final ContactDetailPhotoSetter mPhotoSetter = new ContactDetailPhotoSetter(); private Button mQuickFixButton; private QuickFix mQuickFix; private String mDefaultCountryIso; private boolean mContactHasSocialUpdates; private boolean mShowStaticPhoto = true; private final QuickFix[] mPotentialQuickFixes = new QuickFix[] { new MakeLocalCopyQuickFix(), new AddToMyContactsQuickFix() }; /** * Device capability: Set during buildEntries and used in the long-press context menu */ private boolean mHasPhone; /** * Device capability: Set during buildEntries and used in the long-press context menu */ private boolean mHasSms; /** * Device capability: Set during buildEntries and used in the long-press context menu */ private boolean mHasSip; /** * The view shown if the detail list is empty. * We set this to the list view when first bind the adapter, so that it won't be shown while * we're loading data. */ private View mEmptyView; /** * Saved state of the {@link ListView}. This must be saved and applied to the {@ListView} only * when the adapter has been populated again. */ private Parcelable mListState; /** * Lists of specific types of entries to be shown in contact details. */ private ArrayList<DetailViewEntry> mPhoneEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mSmsEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mEmailEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mPostalEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mImEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mNicknameEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mGroupEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mRelationEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mNoteEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mWebsiteEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mSipEntries = new ArrayList<DetailViewEntry>(); private ArrayList<DetailViewEntry> mEventEntries = new ArrayList<DetailViewEntry>(); private final Map<AccountType, List<DetailViewEntry>> mOtherEntriesMap = new HashMap<AccountType, List<DetailViewEntry>>(); private ArrayList<ViewEntry> mAllEntries = new ArrayList<ViewEntry>(); private LayoutInflater mInflater; private boolean mIsUniqueNumber; private boolean mIsUniqueEmail; private ListPopupWindow mPopup; /** * This is to forward touch events to the list view to enable users to scroll the list view * from the blank area underneath the static photo when the layout with static photo is used. */ private OnTouchListener mForwardTouchToListView = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (mListView != null) { mListView.dispatchTouchEvent(event); return true; } return false; } }; /** * This is to forward drag events to the list view to enable users to scroll the list view * from the blank area underneath the static photo when the layout with static photo is used. */ private OnDragListener mForwardDragToListView = new OnDragListener() { @Override public boolean onDrag(View v, DragEvent event) { if (mListView != null) { mListView.dispatchDragEvent(event); return true; } return false; } }; public ContactDetailFragment() { // Explicit constructor for inflation } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mLookupUri = savedInstanceState.getParcelable(KEY_CONTACT_URI); mListState = savedInstanceState.getParcelable(KEY_LIST_STATE); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(KEY_CONTACT_URI, mLookupUri); if (mListView != null) { outState.putParcelable(KEY_LIST_STATE, mListView.onSaveInstanceState()); } } @Override public void onPause() { dismissPopupIfShown(); super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = activity; mDefaultCountryIso = ContactsUtils.getCurrentCountryIso(mContext); mViewEntryDimensions = new ViewEntryDimensions(mContext.getResources()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) { mView = inflater.inflate(R.layout.contact_detail_fragment, container, false); // Set the touch and drag listener to forward the event to the mListView so that // vertical scrolling can happen from outside of the list view. mView.setOnTouchListener(mForwardTouchToListView); mView.setOnDragListener(mForwardDragToListView); mInflater = inflater; mStaticPhotoContainer = (ViewGroup) mView.findViewById(R.id.static_photo_container); mPhotoTouchOverlay = mView.findViewById(R.id.photo_touch_intercept_overlay); mListView = (ListView) mView.findViewById(android.R.id.list); mListView.setOnItemClickListener(this); mListView.setItemsCanFocus(true); mListView.setOnScrollListener(mVerticalScrollListener); // Don't set it to mListView yet. We do so later when we bind the adapter. mEmptyView = mView.findViewById(android.R.id.empty); mQuickFixButton = (Button) mView.findViewById(R.id.contact_quick_fix); mQuickFixButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mQuickFix != null) { mQuickFix.execute(); } } }); mView.setVisibility(View.INVISIBLE); if (mContactData != null) { bindData(); } return mView; } public void setListener(Listener value) { mListener = value; } protected Context getContext() { return mContext; } protected Listener getListener() { return mListener; } protected Contact getContactData() { return mContactData; } public void setVerticalScrollListener(OnScrollListener listener) { mVerticalScrollListener = listener; } public Uri getUri() { return mLookupUri; } /** * Sets whether the static contact photo (that is not in a scrolling region), should be shown * or not. */ public void setShowStaticPhoto(boolean showPhoto) { mShowStaticPhoto = showPhoto; } /** * Shows the contact detail with a message indicating there are no contact details. */ public void showEmptyState() { setData(null, null); } public void setData(Uri lookupUri, Contact result) { mLookupUri = lookupUri; mContactData = result; bindData(); } /** * Reset the list adapter in this {@link Fragment} to get rid of any saved scroll position * from a previous contact. */ public void resetAdapter() { if (mListView != null) { mListView.setAdapter(mAdapter); } } /** * Returns the top coordinate of the first item in the {@link ListView}. If the first item * in the {@link ListView} is not visible or there are no children in the list, then return * Integer.MIN_VALUE. Note that the returned value will be <= 0 because the first item in the * list cannot have a positive offset. */ public int getFirstListItemOffset() { return ContactDetailDisplayUtils.getFirstListItemOffset(mListView); } /** * Tries to scroll the first item to the given offset (this can be a no-op if the list is * already in the correct position). * @param offset which should be <= 0 */ public void requestToMoveToOffset(int offset) { ContactDetailDisplayUtils.requestToMoveToOffset(mListView, offset); } protected void bindData() { if (mView == null) { return; } if (isAdded()) { getActivity().invalidateOptionsMenu(); } if (mContactData == null) { mView.setVisibility(View.INVISIBLE); if (mStaticPhotoContainer != null) { mStaticPhotoContainer.setVisibility(View.GONE); } mAllEntries.clear(); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } return; } // Figure out if the contact has social updates or not mContactHasSocialUpdates = !mContactData.getStreamItems().isEmpty(); // Setup the photo if applicable if (mStaticPhotoContainer != null) { // The presence of a static photo container is not sufficient to determine whether or // not we should show the photo. Check the mShowStaticPhoto flag which can be set by an // outside class depending on screen size, layout, and whether the contact has social // updates or not. if (mShowStaticPhoto) { mStaticPhotoContainer.setVisibility(View.VISIBLE); final ImageView photoView = (ImageView) mStaticPhotoContainer.findViewById( R.id.photo); final boolean expandPhotoOnClick = mContactData.getPhotoUri() != null; final OnClickListener listener = mPhotoSetter.setupContactPhotoForClick( mContext, mContactData, photoView, expandPhotoOnClick); if (mPhotoTouchOverlay != null) { mPhotoTouchOverlay.setVisibility(View.VISIBLE); if (expandPhotoOnClick || mContactData.isWritableContact(mContext)) { mPhotoTouchOverlay.setOnClickListener(listener); } else { mPhotoTouchOverlay.setClickable(false); } } } else { mStaticPhotoContainer.setVisibility(View.GONE); } } // Build up the contact entries buildEntries(); // Collapse similar data items for select {@link DataKind}s. Collapser.collapseList(mPhoneEntries); Collapser.collapseList(mSmsEntries); Collapser.collapseList(mEmailEntries); Collapser.collapseList(mPostalEntries); Collapser.collapseList(mImEntries); mIsUniqueNumber = mPhoneEntries.size() == 1; mIsUniqueEmail = mEmailEntries.size() == 1; // Make one aggregated list of all entries for display to the user. setupFlattenedList(); if (mAdapter == null) { mAdapter = new ViewAdapter(); mListView.setAdapter(mAdapter); } // Restore {@link ListView} state if applicable because the adapter is now populated. if (mListState != null) { mListView.onRestoreInstanceState(mListState); mListState = null; } mAdapter.notifyDataSetChanged(); mListView.setEmptyView(mEmptyView); configureQuickFix(); mView.setVisibility(View.VISIBLE); } /* * Sets {@link #mQuickFix} to a useful action and configures the visibility of * {@link #mQuickFixButton} */ private void configureQuickFix() { mQuickFix = null; for (QuickFix fix : mPotentialQuickFixes) { if (fix.isApplicable()) { mQuickFix = fix; break; } } // Configure the button if (mQuickFix == null) { mQuickFixButton.setVisibility(View.GONE); } else { mQuickFixButton.setVisibility(View.VISIBLE); mQuickFixButton.setText(mQuickFix.getTitle()); } } /** @return default group id or -1 if no group or several groups are marked as default */ private long getDefaultGroupId(List<GroupMetaData> groups) { long defaultGroupId = -1; for (GroupMetaData group : groups) { if (group.isDefaultGroup()) { // two default groups? return neither if (defaultGroupId != -1) return -1; defaultGroupId = group.getGroupId(); } } return defaultGroupId; } /** * Build up the entries to display on the screen. */ private final void buildEntries() { mHasPhone = PhoneCapabilityTester.isPhone(mContext); mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext); mHasSip = PhoneCapabilityTester.isSipPhone(mContext); // Clear out the old entries mAllEntries.clear(); mPrimaryPhoneUri = null; // Build up method entries if (mContactData == null) { return; } ArrayList<String> groups = new ArrayList<String>(); for (RawContact rawContact: mContactData.getRawContacts()) { final long rawContactId = rawContact.getId(); for (DataItem dataItem : rawContact.getDataItems()) { dataItem.setRawContactId(rawContactId); if (dataItem.getMimeType() == null) continue; if (dataItem instanceof GroupMembershipDataItem) { GroupMembershipDataItem groupMembership = (GroupMembershipDataItem) dataItem; Long groupId = groupMembership.getGroupRowId(); if (groupId != null) { handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId); } continue; } final DataKind kind = dataItem.getDataKind(); if (kind == null) continue; final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); entry.maxLines = kind.maxLinesForDisplay; final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = dataItem.isSuperPrimary(); if (dataItem instanceof StructuredNameDataItem) { // Always ignore the name. It is shown in the header if set } else if (dataItem instanceof PhoneDataItem && hasData) { PhoneDataItem phone = (PhoneDataItem) dataItem; // Build phone entries entry.data = phone.getFormattedPhoneNumber(); + if (entry.data == null) { + // This case happens when the quick contact was opened from the contact + // list, and then, the user touches the quick contact image and brings the + // user to the detail card. In this case, the Contact object that was + // loaded from quick contacts does not contain the formatted phone number, + // so it must be loaded here. + phone.computeFormattedPhoneNumber(mDefaultCountryIso); + entry.data = phone.getFormattedPhoneNumber(); + } final Intent phoneIntent = mHasPhone ? ContactsUtils.getCallIntent(entry.data) : null; final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null; // Configure Icons and Intents. if (mHasPhone && mHasSms) { entry.intent = phoneIntent; entry.secondaryIntent = smsIntent; entry.secondaryActionIcon = kind.iconAltRes; entry.secondaryActionDescription = kind.iconAltDescriptionRes; } else if (mHasPhone) { entry.intent = phoneIntent; } else if (mHasSms) { entry.intent = smsIntent; } else { entry.intent = null; } // Remember super-primary phone if (isSuperPrimary) mPrimaryPhoneUri = entry.uri; entry.isPrimary = isSuperPrimary; // If the entry is a primary entry, then render it first in the view. if (entry.isPrimary) { // add to beginning of list so that this phone number shows up first mPhoneEntries.add(0, entry); } else { // add to end of list mPhoneEntries.add(entry); } } else if (dataItem instanceof EmailDataItem && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; // If entry is a primary entry, then render it first in the view. if (entry.isPrimary) { mEmailEntries.add(0, entry); } else { mEmailEntries.add(entry); } // When Email rows have status, create additional Im row final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { EmailDataItem email = (EmailDataItem) dataItem; ImDataItem im = ImDataItem.createFromEmail(email); final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); buildImActions(mContext, imEntry, im); imEntry.setPresence(status.getPresence()); imEntry.maxLines = kind.maxLinesForDisplay; mImEntries.add(imEntry); } } else if (dataItem instanceof StructuredPostalDataItem && hasData) { // Build postal entries entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data); mPostalEntries.add(entry); } else if (dataItem instanceof ImDataItem && hasData) { // Build IM entries buildImActions(mContext, entry, (ImDataItem) dataItem); // Apply presence when available final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { entry.setPresence(status.getPresence()); } mImEntries.add(entry); } else if (dataItem instanceof OrganizationDataItem) { // Organizations are not shown. The first one is shown in the header // and subsequent ones are not supported anymore } else if (dataItem instanceof NicknameDataItem && hasData) { // Build nickname entries final boolean isNameRawContact = (mContactData.getNameRawContactId() == rawContactId); final boolean duplicatesTitle = isNameRawContact && mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME; if (!duplicatesTitle) { entry.uri = null; mNicknameEntries.add(entry); } } else if (dataItem instanceof NoteDataItem && hasData) { // Build note entries entry.uri = null; mNoteEntries.add(entry); } else if (dataItem instanceof WebsiteDataItem && hasData) { // Build Website entries entry.uri = null; try { WebAddress webAddress = new WebAddress(entry.data); entry.intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString())); } catch (ParseException e) { Log.e(TAG, "Couldn't parse website: " + entry.data); } mWebsiteEntries.add(entry); } else if (dataItem instanceof SipAddressDataItem && hasData) { // Build SipAddress entries entry.uri = null; if (mHasSip) { entry.intent = ContactsUtils.getCallIntent( Uri.fromParts(Constants.SCHEME_SIP, entry.data, null)); } else { entry.intent = null; } mSipEntries.add(entry); // TODO: Now that SipAddress is in its own list of entries // (instead of grouped in mOtherEntries), consider // repositioning it right under the phone number. // (Then, we'd also update FallbackAccountType.java to set // secondary=false for this field, and tweak the weight // of its DataKind.) } else if (dataItem instanceof EventDataItem && hasData) { entry.data = DateUtils.formatDate(mContext, entry.data); entry.uri = null; mEventEntries.add(entry); } else if (dataItem instanceof RelationDataItem && hasData) { entry.intent = new Intent(Intent.ACTION_SEARCH); entry.intent.putExtra(SearchManager.QUERY, entry.data); entry.intent.setType(Contacts.CONTENT_TYPE); mRelationEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW); entry.intent.setDataAndType(entry.uri, entry.mimetype); entry.data = dataItem.buildDataString(); if (!TextUtils.isEmpty(entry.data)) { // If the account type exists in the hash map, add it as another entry for // that account type AccountType type = dataItem.getAccountType(); if (mOtherEntriesMap.containsKey(type)) { List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type); listEntries.add(entry); } else { // Otherwise create a new list with the entry and add it to the hash map List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>(); listEntries.add(entry); mOtherEntriesMap.put(type, listEntries); } } } } } if (!groups.isEmpty()) { DetailViewEntry entry = new DetailViewEntry(); Collections.sort(groups); StringBuilder sb = new StringBuilder(); int size = groups.size(); for (int i = 0; i < size; i++) { if (i != 0) { sb.append(", "); } sb.append(groups.get(i)); } entry.mimetype = GroupMembership.MIMETYPE; entry.kind = mContext.getString(R.string.groupsLabel); entry.data = sb.toString(); mGroupEntries.add(entry); } } /** * Collapse all contact detail entries into one aggregated list with a {@link HeaderViewEntry} * at the top. */ private void setupFlattenedList() { // All contacts should have a header view (even if there is no data for the contact). mAllEntries.add(new HeaderViewEntry()); addPhoneticName(); flattenList(mPhoneEntries); flattenList(mSmsEntries); flattenList(mEmailEntries); flattenList(mImEntries); flattenList(mNicknameEntries); flattenList(mWebsiteEntries); addNetworks(); flattenList(mSipEntries); flattenList(mPostalEntries); flattenList(mEventEntries); flattenList(mGroupEntries); flattenList(mRelationEntries); flattenList(mNoteEntries); } /** * Add phonetic name (if applicable) to the aggregated list of contact details. This has to be * done manually because phonetic name doesn't have a mimetype or action intent. */ private void addPhoneticName() { String phoneticName = ContactDetailDisplayUtils.getPhoneticName(mContext, mContactData); if (TextUtils.isEmpty(phoneticName)) { return; } // Add a title String phoneticNameKindTitle = mContext.getString(R.string.name_phonetic); mAllEntries.add(new KindTitleViewEntry(phoneticNameKindTitle.toUpperCase())); // Add the phonetic name final DetailViewEntry entry = new DetailViewEntry(); entry.kind = phoneticNameKindTitle; entry.data = phoneticName; mAllEntries.add(entry); } /** * Add attribution and other third-party entries (if applicable) under the "networks" section * of the aggregated list of contact details. This has to be done manually because the * attribution does not have a mimetype and the third-party entries don't have actually belong * to the same {@link DataKind}. */ private void addNetworks() { String attribution = ContactDetailDisplayUtils.getAttribution(mContext, mContactData); boolean hasAttribution = !TextUtils.isEmpty(attribution); int networksCount = mOtherEntriesMap.keySet().size(); // Note: invitableCount will always be 0 for me profile. (ContactLoader won't set // invitable types for me profile.) int invitableCount = mContactData.getInvitableAccountTypes().size(); if (!hasAttribution && networksCount == 0 && invitableCount == 0) { return; } // Add a title String networkKindTitle = mContext.getString(R.string.connections); mAllEntries.add(new KindTitleViewEntry(networkKindTitle.toUpperCase())); // Add the attribution if applicable if (hasAttribution) { final DetailViewEntry entry = new DetailViewEntry(); entry.kind = networkKindTitle; entry.data = attribution; mAllEntries.add(entry); // Add a divider below the attribution if there are network details that will follow if (networksCount > 0) { mAllEntries.add(new SeparatorViewEntry()); } } // Add the other entries from third parties for (AccountType accountType : mOtherEntriesMap.keySet()) { // Add a title for each third party app mAllEntries.add(new NetworkTitleViewEntry(mContext, accountType)); for (DetailViewEntry detailEntry : mOtherEntriesMap.get(accountType)) { // Add indented separator SeparatorViewEntry separatorEntry = new SeparatorViewEntry(); separatorEntry.setIsInSubSection(true); mAllEntries.add(separatorEntry); // Add indented detail detailEntry.setIsInSubSection(true); mAllEntries.add(detailEntry); } } mOtherEntriesMap.clear(); // Add the "More networks" button, which opens the invitable account type list popup. if (invitableCount > 0) { addMoreNetworks(); } } /** * Add the "More networks" entry. When clicked, show a popup containing a list of invitable * account types. */ private void addMoreNetworks() { // First, prepare for the popup. // Adapter for the list popup. final InvitableAccountTypesAdapter popupAdapter = new InvitableAccountTypesAdapter(mContext, mContactData); // Listener called when a popup item is clicked. final AdapterView.OnItemClickListener popupItemListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mListener != null && mContactData != null) { mListener.onItemClicked(ContactsUtils.getInvitableIntent( popupAdapter.getItem(position) /* account type */, mContactData.getLookupUri())); } } }; // Then create the click listener for the "More network" entry. Open the popup. View.OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View v) { showListPopup(v, popupAdapter, popupItemListener); } }; // Finally create the entry. mAllEntries.add(new AddConnectionViewEntry(mContext, onClickListener)); } /** * Iterate through {@link DetailViewEntry} in the given list and add it to a list of all * entries. Add a {@link KindTitleViewEntry} at the start if the length of the list is not 0. * Add {@link SeparatorViewEntry}s as dividers as appropriate. Clear the original list. */ private void flattenList(ArrayList<DetailViewEntry> entries) { int count = entries.size(); // Add a title for this kind by extracting the kind from the first entry if (count > 0) { String kind = entries.get(0).kind; mAllEntries.add(new KindTitleViewEntry(kind.toUpperCase())); } // Add all the data entries for this kind for (int i = 0; i < count; i++) { // For all entries except the first one, add a divider above the entry if (i != 0) { mAllEntries.add(new SeparatorViewEntry()); } mAllEntries.add(entries.get(i)); } // Clear old list because it's not needed anymore. entries.clear(); } /** * Maps group ID to the corresponding group name, collapses all synonymous groups. * Ignores default groups (e.g. My Contacts) and favorites groups. */ private void handleGroupMembership( ArrayList<String> groups, List<GroupMetaData> groupMetaData, long groupId) { if (groupMetaData == null) { return; } for (GroupMetaData group : groupMetaData) { if (group.getGroupId() == groupId) { if (!group.isDefaultGroup() && !group.isFavorites()) { String title = group.getTitle(); if (!TextUtils.isEmpty(title) && !groups.contains(title)) { groups.add(title); } } break; } } } /** * Writes the Instant Messaging action into the given entry value. */ @VisibleForTesting public static void buildImActions(Context context, DetailViewEntry entry, ImDataItem im) { final boolean isEmail = im.isCreatedFromEmail(); if (!isEmail && !im.isProtocolValid()) { return; } final String data = im.getData(); if (TextUtils.isEmpty(data)) { return; } final int protocol = isEmail ? Im.PROTOCOL_GOOGLE_TALK : im.getProtocol(); if (protocol == Im.PROTOCOL_GOOGLE_TALK) { final int chatCapability = im.getChatCapability(); entry.chatCapability = chatCapability; entry.typeString = Im.getProtocolLabel(context.getResources(), Im.PROTOCOL_GOOGLE_TALK, null).toString(); if ((chatCapability & Im.CAPABILITY_HAS_CAMERA) != 0) { entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message")); entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?call")); } else if ((chatCapability & Im.CAPABILITY_HAS_VOICE) != 0) { // Allow Talking and Texting entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message")); entry.secondaryIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?call")); } else { entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("xmpp:" + data + "?message")); } } else { // Build an IM Intent String host = im.getCustomProtocol(); if (protocol != Im.PROTOCOL_CUSTOM) { // Try bringing in a well-known host for specific protocols host = ContactsUtils.lookupProviderNameFromId(protocol); } if (!TextUtils.isEmpty(host)) { final String authority = host.toLowerCase(); final Uri imUri = new Uri.Builder().scheme(Constants.SCHEME_IMTO).authority( authority).appendPath(data).build(); entry.intent = new Intent(Intent.ACTION_SENDTO, imUri); } } } /** * Show a list popup. Used for "popup-able" entry, such as "More networks". */ private void showListPopup(View anchorView, ListAdapter adapter, final AdapterView.OnItemClickListener onItemClickListener) { dismissPopupIfShown(); mPopup = new ListPopupWindow(mContext, null); mPopup.setAnchorView(anchorView); mPopup.setWidth(anchorView.getWidth()); mPopup.setAdapter(adapter); mPopup.setModal(true); // We need to wrap the passed onItemClickListener here, so that we can dismiss() the // popup afterwards. Otherwise we could directly use the passed listener. mPopup.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onItemClickListener.onItemClick(parent, view, position, id); dismissPopupIfShown(); } }); mPopup.show(); } private void dismissPopupIfShown() { if (mPopup != null && mPopup.isShowing()) { mPopup.dismiss(); } mPopup = null; } /** * Base class for an item in the {@link ViewAdapter} list of data, which is * supplied to the {@link ListView}. */ static class ViewEntry { private final int viewTypeForAdapter; protected long id = -1; /** Whether or not the entry can be focused on or not. */ protected boolean isEnabled = false; ViewEntry(int viewType) { viewTypeForAdapter = viewType; } int getViewType() { return viewTypeForAdapter; } long getId() { return id; } boolean isEnabled(){ return isEnabled; } /** * Called when the entry is clicked. Only {@link #isEnabled} entries can get clicked. * * @param clickedView {@link View} that was clicked (Used, for example, as the anchor view * for a popup.) * @param fragmentListener {@link Listener} set to {@link ContactDetailFragment} */ public void click(View clickedView, Listener fragmentListener) { } } /** * Header item in the {@link ViewAdapter} list of data. */ private static class HeaderViewEntry extends ViewEntry { HeaderViewEntry() { super(ViewAdapter.VIEW_TYPE_HEADER_ENTRY); } } /** * Separator between items of the same {@link DataKind} in the * {@link ViewAdapter} list of data. */ private static class SeparatorViewEntry extends ViewEntry { /** * Whether or not the entry is in a subsection (if true then the contents will be indented * to the right) */ private boolean mIsInSubSection = false; SeparatorViewEntry() { super(ViewAdapter.VIEW_TYPE_SEPARATOR_ENTRY); } public void setIsInSubSection(boolean isInSubSection) { mIsInSubSection = isInSubSection; } public boolean isInSubSection() { return mIsInSubSection; } } /** * Title entry for items of the same {@link DataKind} in the * {@link ViewAdapter} list of data. */ private static class KindTitleViewEntry extends ViewEntry { private final String mTitle; KindTitleViewEntry(String titleText) { super(ViewAdapter.VIEW_TYPE_KIND_TITLE_ENTRY); mTitle = titleText; } public String getTitle() { return mTitle; } } /** * A title for a section of contact details from a single 3rd party network. */ private static class NetworkTitleViewEntry extends ViewEntry { private final Drawable mIcon; private final CharSequence mLabel; public NetworkTitleViewEntry(Context context, AccountType type) { super(ViewAdapter.VIEW_TYPE_NETWORK_TITLE_ENTRY); this.mIcon = type.getDisplayIcon(context); this.mLabel = type.getDisplayLabel(context); this.isEnabled = false; } public Drawable getIcon() { return mIcon; } public CharSequence getLabel() { return mLabel; } } /** * This is used for the "Add Connections" entry. */ private static class AddConnectionViewEntry extends ViewEntry { private final Drawable mIcon; private final CharSequence mLabel; private final View.OnClickListener mOnClickListener; private AddConnectionViewEntry(Context context, View.OnClickListener onClickListener) { super(ViewAdapter.VIEW_TYPE_ADD_CONNECTION_ENTRY); this.mIcon = context.getResources().getDrawable( R.drawable.ic_menu_add_field_holo_light); this.mLabel = context.getString(R.string.add_connection_button); this.mOnClickListener = onClickListener; this.isEnabled = true; } @Override public void click(View clickedView, Listener fragmentListener) { if (mOnClickListener == null) return; mOnClickListener.onClick(clickedView); } public Drawable getIcon() { return mIcon; } public CharSequence getLabel() { return mLabel; } } /** * An item with a single detail for a contact in the {@link ViewAdapter} * list of data. */ static class DetailViewEntry extends ViewEntry implements Collapsible<DetailViewEntry> { // TODO: Make getters/setters for these fields public int type = -1; public String kind; public String typeString; public String data; public Uri uri; public int maxLines = 1; public String mimetype; public Context context = null; public boolean isPrimary = false; public int secondaryActionIcon = -1; public int secondaryActionDescription = -1; public Intent intent; public Intent secondaryIntent = null; public ArrayList<Long> ids = new ArrayList<Long>(); public int collapseCount = 0; public int presence = -1; public int chatCapability = 0; private boolean mIsInSubSection = false; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("== DetailViewEntry ==\n"); sb.append(" type: " + type + "\n"); sb.append(" kind: " + kind + "\n"); sb.append(" typeString: " + typeString + "\n"); sb.append(" data: " + data + "\n"); sb.append(" uri: " + uri.toString() + "\n"); sb.append(" maxLines: " + maxLines + "\n"); sb.append(" mimetype: " + mimetype + "\n"); sb.append(" isPrimary: " + (isPrimary ? "true" : "false") + "\n"); sb.append(" secondaryActionIcon: " + secondaryActionIcon + "\n"); sb.append(" secondaryActionDescription: " + secondaryActionDescription + "\n"); if (intent == null) { sb.append(" intent: " + intent.toString() + "\n"); } else { sb.append(" intent: " + intent.toString() + "\n"); } if (secondaryIntent == null) { sb.append(" secondaryIntent: (null)\n"); } else { sb.append(" secondaryIntent: " + secondaryIntent.toString() + "\n"); } sb.append(" ids: " + Iterables.toString(ids) + "\n"); sb.append(" collapseCount: " + collapseCount + "\n"); sb.append(" presence: " + presence + "\n"); sb.append(" chatCapability: " + chatCapability + "\n"); sb.append(" mIsInSubsection: " + (mIsInSubSection ? "true" : "false") + "\n"); return sb.toString(); } DetailViewEntry() { super(ViewAdapter.VIEW_TYPE_DETAIL_ENTRY); isEnabled = true; } /** * Build new {@link DetailViewEntry} and populate from the given values. */ public static DetailViewEntry fromValues(Context context, DataItem item, boolean isDirectoryEntry, long directoryId) { final DetailViewEntry entry = new DetailViewEntry(); entry.id = item.getId(); entry.context = context; entry.uri = ContentUris.withAppendedId(Data.CONTENT_URI, entry.id); if (isDirectoryEntry) { entry.uri = entry.uri.buildUpon().appendQueryParameter( ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(directoryId)).build(); } entry.mimetype = item.getMimeType(); entry.kind = item.getKindString(); entry.data = item.buildDataString(); if (item.hasKindTypeColumn()) { entry.type = item.getKindTypeColumn(); // get type string entry.typeString = ""; for (EditType type : item.getDataKind().typeList) { if (type.rawValue == entry.type) { if (type.customColumn == null) { // Non-custom type. Get its description from the resource entry.typeString = context.getString(type.labelRes); } else { // Custom type. Read it from the database entry.typeString = item.getContentValues().getAsString(type.customColumn); } break; } } } else { entry.typeString = ""; } return entry; } public void setPresence(int presence) { this.presence = presence; } public void setIsInSubSection(boolean isInSubSection) { mIsInSubSection = isInSubSection; } public boolean isInSubSection() { return mIsInSubSection; } @Override public boolean collapseWith(DetailViewEntry entry) { // assert equal collapse keys if (!shouldCollapseWith(entry)) { return false; } // Choose the label associated with the highest type precedence. if (TypePrecedence.getTypePrecedence(mimetype, type) > TypePrecedence.getTypePrecedence(entry.mimetype, entry.type)) { type = entry.type; kind = entry.kind; typeString = entry.typeString; } // Choose the max of the maxLines and maxLabelLines values. maxLines = Math.max(maxLines, entry.maxLines); // Choose the presence with the highest precedence. if (StatusUpdates.getPresencePrecedence(presence) < StatusUpdates.getPresencePrecedence(entry.presence)) { presence = entry.presence; } // If any of the collapsed entries are primary make the whole thing primary. isPrimary = entry.isPrimary ? true : isPrimary; // uri, and contactdId, shouldn't make a difference. Just keep the original. // Keep track of all the ids that have been collapsed with this one. ids.add(entry.getId()); collapseCount++; return true; } @Override public boolean shouldCollapseWith(DetailViewEntry entry) { if (entry == null) { return false; } if (!ContactsUtils.shouldCollapse(mimetype, data, entry.mimetype, entry.data)) { return false; } if (!TextUtils.equals(mimetype, entry.mimetype) || !ContactsUtils.areIntentActionEqual(intent, entry.intent) || !ContactsUtils.areIntentActionEqual( secondaryIntent, entry.secondaryIntent)) { return false; } return true; } @Override public void click(View clickedView, Listener fragmentListener) { if (fragmentListener == null || intent == null) return; fragmentListener.onItemClicked(intent); } } /** * Cache of the children views for a view that displays a header view entry. */ private static class HeaderViewCache { public final TextView displayNameView; public final TextView companyView; public final ImageView photoView; public final View photoOverlayView; public final ImageView starredView; public final int layoutResourceId; public HeaderViewCache(View view, int layoutResourceInflated) { displayNameView = (TextView) view.findViewById(R.id.name); companyView = (TextView) view.findViewById(R.id.company); photoView = (ImageView) view.findViewById(R.id.photo); photoOverlayView = view.findViewById(R.id.photo_touch_intercept_overlay); starredView = (ImageView) view.findViewById(R.id.star); layoutResourceId = layoutResourceInflated; } public void enablePhotoOverlay(OnClickListener listener) { if (photoOverlayView != null) { photoOverlayView.setOnClickListener(listener); photoOverlayView.setVisibility(View.VISIBLE); } } } private static class KindTitleViewCache { public final TextView titleView; public KindTitleViewCache(View view) { titleView = (TextView)view.findViewById(R.id.title); } } /** * Cache of the children views for a view that displays a {@link NetworkTitleViewEntry} */ private static class NetworkTitleViewCache { public final TextView name; public final ImageView icon; public NetworkTitleViewCache(View view) { name = (TextView) view.findViewById(R.id.network_title); icon = (ImageView) view.findViewById(R.id.network_icon); } } /** * Cache of the children views for a view that displays a {@link AddConnectionViewEntry} */ private static class AddConnectionViewCache { public final TextView name; public final ImageView icon; public final View primaryActionView; public AddConnectionViewCache(View view) { name = (TextView) view.findViewById(R.id.add_connection_label); icon = (ImageView) view.findViewById(R.id.add_connection_icon); primaryActionView = view.findViewById(R.id.primary_action_view); } } /** * Cache of the children views of a contact detail entry represented by a * {@link DetailViewEntry} */ private static class DetailViewCache { public final TextView type; public final TextView data; public final ImageView presenceIcon; public final ImageView secondaryActionButton; public final View actionsViewContainer; public final View primaryActionView; public final View secondaryActionViewContainer; public final View secondaryActionDivider; public final View primaryIndicator; public DetailViewCache(View view, OnClickListener primaryActionClickListener, OnClickListener secondaryActionClickListener) { type = (TextView) view.findViewById(R.id.type); data = (TextView) view.findViewById(R.id.data); primaryIndicator = view.findViewById(R.id.primary_indicator); presenceIcon = (ImageView) view.findViewById(R.id.presence_icon); actionsViewContainer = view.findViewById(R.id.actions_view_container); actionsViewContainer.setOnClickListener(primaryActionClickListener); primaryActionView = view.findViewById(R.id.primary_action_view); secondaryActionViewContainer = view.findViewById( R.id.secondary_action_view_container); secondaryActionViewContainer.setOnClickListener( secondaryActionClickListener); secondaryActionButton = (ImageView) view.findViewById( R.id.secondary_action_button); secondaryActionDivider = view.findViewById(R.id.vertical_divider); } } private final class ViewAdapter extends BaseAdapter { public static final int VIEW_TYPE_DETAIL_ENTRY = 0; public static final int VIEW_TYPE_HEADER_ENTRY = 1; public static final int VIEW_TYPE_KIND_TITLE_ENTRY = 2; public static final int VIEW_TYPE_NETWORK_TITLE_ENTRY = 3; public static final int VIEW_TYPE_ADD_CONNECTION_ENTRY = 4; public static final int VIEW_TYPE_SEPARATOR_ENTRY = 5; private static final int VIEW_TYPE_COUNT = 6; @Override public View getView(int position, View convertView, ViewGroup parent) { switch (getItemViewType(position)) { case VIEW_TYPE_HEADER_ENTRY: return getHeaderEntryView(convertView, parent); case VIEW_TYPE_SEPARATOR_ENTRY: return getSeparatorEntryView(position, convertView, parent); case VIEW_TYPE_KIND_TITLE_ENTRY: return getKindTitleEntryView(position, convertView, parent); case VIEW_TYPE_DETAIL_ENTRY: return getDetailEntryView(position, convertView, parent); case VIEW_TYPE_NETWORK_TITLE_ENTRY: return getNetworkTitleEntryView(position, convertView, parent); case VIEW_TYPE_ADD_CONNECTION_ENTRY: return getAddConnectionEntryView(position, convertView, parent); default: throw new IllegalStateException("Invalid view type ID " + getItemViewType(position)); } } private View getHeaderEntryView(View convertView, ViewGroup parent) { final int desiredLayoutResourceId = mContactHasSocialUpdates ? R.layout.detail_header_contact_with_updates : R.layout.detail_header_contact_without_updates; View result = null; HeaderViewCache viewCache = null; // Only use convertView if it has the same layout resource ID as the one desired // (the two can be different on wide 2-pane screens where the detail fragment is reused // for many different contacts that do and do not have social updates). if (convertView != null) { viewCache = (HeaderViewCache) convertView.getTag(); if (viewCache.layoutResourceId == desiredLayoutResourceId) { result = convertView; } } // Otherwise inflate a new header view and create a new view cache. if (result == null) { result = mInflater.inflate(desiredLayoutResourceId, parent, false); viewCache = new HeaderViewCache(result, desiredLayoutResourceId); result.setTag(viewCache); } ContactDetailDisplayUtils.setDisplayName(mContext, mContactData, viewCache.displayNameView); ContactDetailDisplayUtils.setCompanyName(mContext, mContactData, viewCache.companyView); // Set the photo if it should be displayed if (viewCache.photoView != null) { final boolean expandOnClick = mContactData.getPhotoUri() != null; final OnClickListener listener = mPhotoSetter.setupContactPhotoForClick( mContext, mContactData, viewCache.photoView, expandOnClick); if (expandOnClick || mContactData.isWritableContact(mContext)) { viewCache.enablePhotoOverlay(listener); } } // Set the starred state if it should be displayed final ImageView favoritesStar = viewCache.starredView; if (favoritesStar != null) { ContactDetailDisplayUtils.configureStarredImageView(favoritesStar, mContactData.isDirectoryEntry(), mContactData.isUserProfile(), mContactData.getStarred()); final Uri lookupUri = mContactData.getLookupUri(); favoritesStar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Toggle "starred" state // Make sure there is a contact if (lookupUri != null) { // Read the current starred value from the UI instead of using the last // loaded state. This allows rapid tapping without writing the same // value several times final Object tag = favoritesStar.getTag(); final boolean isStarred = tag == null ? false : (Boolean) favoritesStar.getTag(); // To improve responsiveness, swap out the picture (and tag) in the UI // already ContactDetailDisplayUtils.configureStarredImageView(favoritesStar, mContactData.isDirectoryEntry(), mContactData.isUserProfile(), !isStarred); // Now perform the real save Intent intent = ContactSaveService.createSetStarredIntent( getContext(), lookupUri, !isStarred); getContext().startService(intent); } } }); } return result; } private View getSeparatorEntryView(int position, View convertView, ViewGroup parent) { final SeparatorViewEntry entry = (SeparatorViewEntry) getItem(position); final View result = (convertView != null) ? convertView : mInflater.inflate(R.layout.contact_detail_separator_entry_view, parent, false); result.setPadding(entry.isInSubSection() ? mViewEntryDimensions.getWidePaddingLeft() : mViewEntryDimensions.getPaddingLeft(), 0, mViewEntryDimensions.getPaddingRight(), 0); return result; } private View getKindTitleEntryView(int position, View convertView, ViewGroup parent) { final KindTitleViewEntry entry = (KindTitleViewEntry) getItem(position); final View result; final KindTitleViewCache viewCache; if (convertView != null) { result = convertView; viewCache = (KindTitleViewCache)result.getTag(); } else { result = mInflater.inflate(R.layout.list_separator, parent, false); viewCache = new KindTitleViewCache(result); result.setTag(viewCache); } viewCache.titleView.setText(entry.getTitle()); return result; } private View getNetworkTitleEntryView(int position, View convertView, ViewGroup parent) { final NetworkTitleViewEntry entry = (NetworkTitleViewEntry) getItem(position); final View result; final NetworkTitleViewCache viewCache; if (convertView != null) { result = convertView; viewCache = (NetworkTitleViewCache) result.getTag(); } else { result = mInflater.inflate(R.layout.contact_detail_network_title_entry_view, parent, false); viewCache = new NetworkTitleViewCache(result); result.setTag(viewCache); } viewCache.name.setText(entry.getLabel()); viewCache.icon.setImageDrawable(entry.getIcon()); return result; } private View getAddConnectionEntryView(int position, View convertView, ViewGroup parent) { final AddConnectionViewEntry entry = (AddConnectionViewEntry) getItem(position); final View result; final AddConnectionViewCache viewCache; if (convertView != null) { result = convertView; viewCache = (AddConnectionViewCache) result.getTag(); } else { result = mInflater.inflate(R.layout.contact_detail_add_connection_entry_view, parent, false); viewCache = new AddConnectionViewCache(result); result.setTag(viewCache); } viewCache.name.setText(entry.getLabel()); viewCache.icon.setImageDrawable(entry.getIcon()); viewCache.primaryActionView.setOnClickListener(entry.mOnClickListener); return result; } private View getDetailEntryView(int position, View convertView, ViewGroup parent) { final DetailViewEntry entry = (DetailViewEntry) getItem(position); final View v; final DetailViewCache viewCache; // Check to see if we can reuse convertView if (convertView != null) { v = convertView; viewCache = (DetailViewCache) v.getTag(); } else { // Create a new view if needed v = mInflater.inflate(R.layout.contact_detail_list_item, parent, false); // Cache the children viewCache = new DetailViewCache(v, mPrimaryActionClickListener, mSecondaryActionClickListener); v.setTag(viewCache); } bindDetailView(position, v, entry); return v; } private void bindDetailView(int position, View view, DetailViewEntry entry) { final Resources resources = mContext.getResources(); DetailViewCache views = (DetailViewCache) view.getTag(); if (!TextUtils.isEmpty(entry.typeString)) { views.type.setText(entry.typeString.toUpperCase()); views.type.setVisibility(View.VISIBLE); } else { views.type.setVisibility(View.GONE); } views.data.setText(entry.data); setMaxLines(views.data, entry.maxLines); // Set the default contact method views.primaryIndicator.setVisibility(entry.isPrimary ? View.VISIBLE : View.GONE); // Set the presence icon final Drawable presenceIcon = ContactPresenceIconUtil.getPresenceIcon( mContext, entry.presence); final ImageView presenceIconView = views.presenceIcon; if (presenceIcon != null) { presenceIconView.setImageDrawable(presenceIcon); presenceIconView.setVisibility(View.VISIBLE); } else { presenceIconView.setVisibility(View.GONE); } final ActionsViewContainer actionsButtonContainer = (ActionsViewContainer) views.actionsViewContainer; actionsButtonContainer.setTag(entry); actionsButtonContainer.setPosition(position); registerForContextMenu(actionsButtonContainer); // Set the secondary action button final ImageView secondaryActionView = views.secondaryActionButton; Drawable secondaryActionIcon = null; String secondaryActionDescription = null; if (entry.secondaryActionIcon != -1) { secondaryActionIcon = resources.getDrawable(entry.secondaryActionIcon); secondaryActionDescription = resources.getString(entry.secondaryActionDescription); } else if ((entry.chatCapability & Im.CAPABILITY_HAS_CAMERA) != 0) { secondaryActionIcon = resources.getDrawable(R.drawable.sym_action_videochat_holo_light); secondaryActionDescription = resources.getString(R.string.video_chat); } else if ((entry.chatCapability & Im.CAPABILITY_HAS_VOICE) != 0) { secondaryActionIcon = resources.getDrawable(R.drawable.sym_action_audiochat_holo_light); secondaryActionDescription = resources.getString(R.string.audio_chat); } final View secondaryActionViewContainer = views.secondaryActionViewContainer; if (entry.secondaryIntent != null && secondaryActionIcon != null) { secondaryActionView.setImageDrawable(secondaryActionIcon); secondaryActionView.setContentDescription(secondaryActionDescription); secondaryActionViewContainer.setTag(entry); secondaryActionViewContainer.setVisibility(View.VISIBLE); views.secondaryActionDivider.setVisibility(View.VISIBLE); } else { secondaryActionViewContainer.setVisibility(View.GONE); views.secondaryActionDivider.setVisibility(View.GONE); } // Right and left padding should not have "pressed" effect. view.setPadding( entry.isInSubSection() ? mViewEntryDimensions.getWidePaddingLeft() : mViewEntryDimensions.getPaddingLeft(), 0, mViewEntryDimensions.getPaddingRight(), 0); // Top and bottom padding should have "pressed" effect. final View primaryActionView = views.primaryActionView; primaryActionView.setPadding( primaryActionView.getPaddingLeft(), mViewEntryDimensions.getPaddingTop(), primaryActionView.getPaddingRight(), mViewEntryDimensions.getPaddingBottom()); secondaryActionViewContainer.setPadding( secondaryActionViewContainer.getPaddingLeft(), mViewEntryDimensions.getPaddingTop(), secondaryActionViewContainer.getPaddingRight(), mViewEntryDimensions.getPaddingBottom()); } private void setMaxLines(TextView textView, int maxLines) { if (maxLines == 1) { textView.setSingleLine(true); textView.setEllipsize(TextUtils.TruncateAt.END); } else { textView.setSingleLine(false); textView.setMaxLines(maxLines); textView.setEllipsize(null); } } private final OnClickListener mPrimaryActionClickListener = new OnClickListener() { @Override public void onClick(View view) { if (mListener == null) return; final ViewEntry entry = (ViewEntry) view.getTag(); if (entry == null) return; entry.click(view, mListener); } }; private final OnClickListener mSecondaryActionClickListener = new OnClickListener() { @Override public void onClick(View view) { if (mListener == null) return; if (view == null) return; final ViewEntry entry = (ViewEntry) view.getTag(); if (entry == null || !(entry instanceof DetailViewEntry)) return; final DetailViewEntry detailViewEntry = (DetailViewEntry) entry; final Intent intent = detailViewEntry.secondaryIntent; if (intent == null) return; mListener.onItemClicked(intent); } }; @Override public int getCount() { return mAllEntries.size(); } @Override public ViewEntry getItem(int position) { return mAllEntries.get(position); } @Override public int getItemViewType(int position) { return mAllEntries.get(position).getViewType(); } @Override public int getViewTypeCount() { return VIEW_TYPE_COUNT; } @Override public long getItemId(int position) { final ViewEntry entry = mAllEntries.get(position); if (entry != null) { return entry.getId(); } return -1; } @Override public boolean areAllItemsEnabled() { // Header will always be an item that is not enabled. return false; } @Override public boolean isEnabled(int position) { return getItem(position).isEnabled(); } } @Override public void onAccountSelectorCancelled() { } @Override public void onAccountChosen(AccountWithDataSet account, Bundle extraArgs) { createCopy(account); } private void createCopy(AccountWithDataSet account) { if (mListener != null) { mListener.onCreateRawContactRequested(mContactData.getContentValues(), account); } } /** * Default (fallback) list item click listener. Note the click event for DetailViewEntry is * caught by individual views in the list item view to distinguish the primary action and the * secondary action, so this method won't be invoked for that. (The listener is set in the * bindview in the adapter) * This listener is used for other kind of entries. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mListener == null) return; final ViewEntry entry = mAdapter.getItem(position); if (entry == null) return; entry.click(view, mListener); } @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; DetailViewEntry selectedEntry = (DetailViewEntry) mAllEntries.get(info.position); menu.setHeaderTitle(selectedEntry.data); menu.add(ContextMenu.NONE, ContextMenuIds.COPY_TEXT, ContextMenu.NONE, getString(R.string.copy_text)); String selectedMimeType = selectedEntry.mimetype; // Defaults to true will only enable the detail to be copied to the clipboard. boolean isUniqueMimeType = true; // Only allow primary support for Phone and Email content types if (Phone.CONTENT_ITEM_TYPE.equals(selectedMimeType)) { isUniqueMimeType = mIsUniqueNumber; } else if (Email.CONTENT_ITEM_TYPE.equals(selectedMimeType)) { isUniqueMimeType = mIsUniqueEmail; } // Checking for previously set default if (selectedEntry.isPrimary) { menu.add(ContextMenu.NONE, ContextMenuIds.CLEAR_DEFAULT, ContextMenu.NONE, getString(R.string.clear_default)); } else if (!isUniqueMimeType) { menu.add(ContextMenu.NONE, ContextMenuIds.SET_DEFAULT, ContextMenu.NONE, getString(R.string.set_default)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } switch (item.getItemId()) { case ContextMenuIds.COPY_TEXT: copyToClipboard(menuInfo.position); return true; case ContextMenuIds.SET_DEFAULT: setDefaultContactMethod(mListView.getItemIdAtPosition(menuInfo.position)); return true; case ContextMenuIds.CLEAR_DEFAULT: clearDefaultContactMethod(mListView.getItemIdAtPosition(menuInfo.position)); return true; default: throw new IllegalArgumentException("Unknown menu option " + item.getItemId()); } } private void setDefaultContactMethod(long id) { Intent setIntent = ContactSaveService.createSetSuperPrimaryIntent(mContext, id); mContext.startService(setIntent); } private void clearDefaultContactMethod(long id) { Intent clearIntent = ContactSaveService.createClearPrimaryIntent(mContext, id); mContext.startService(clearIntent); } private void copyToClipboard(int viewEntryPosition) { // Getting the text to copied DetailViewEntry detailViewEntry = (DetailViewEntry) mAllEntries.get(viewEntryPosition); CharSequence textToCopy = detailViewEntry.data; // Checking for empty string if (TextUtils.isEmpty(textToCopy)) return; ClipboardUtils.copyText(getActivity(), detailViewEntry.typeString, textToCopy, true); } @Override public boolean handleKeyDown(int keyCode) { switch (keyCode) { case KeyEvent.KEYCODE_CALL: { try { ITelephony phone = ITelephony.Stub.asInterface( ServiceManager.checkService("phone")); if (phone != null && !phone.isIdle()) { // Skip out and let the key be handled at a higher level break; } } catch (RemoteException re) { // Fall through and try to call the contact } int index = mListView.getSelectedItemPosition(); if (index != -1) { final DetailViewEntry entry = (DetailViewEntry) mAdapter.getItem(index); if (entry != null && entry.intent != null && entry.intent.getAction() == Intent.ACTION_CALL_PRIVILEGED) { mContext.startActivity(entry.intent); return true; } } else if (mPrimaryPhoneUri != null) { // There isn't anything selected, call the default number mContext.startActivity(ContactsUtils.getCallIntent(mPrimaryPhoneUri)); return true; } return false; } } return false; } /** * Base class for QuickFixes. QuickFixes quickly fix issues with the Contact without * requiring the user to go to the editor. Example: Add to My Contacts. */ private static abstract class QuickFix { public abstract boolean isApplicable(); public abstract String getTitle(); public abstract void execute(); } private class AddToMyContactsQuickFix extends QuickFix { @Override public boolean isApplicable() { // Only local contacts if (mContactData == null || mContactData.isDirectoryEntry()) return false; // User profile cannot be added to contacts if (mContactData.isUserProfile()) return false; // Only if exactly one raw contact if (mContactData.getRawContacts().size() != 1) return false; // test if the default group is assigned final List<GroupMetaData> groups = mContactData.getGroupMetaData(); // For accounts without group support, groups is null if (groups == null) return false; // remember the default group id. no default group? bail out early final long defaultGroupId = getDefaultGroupId(groups); if (defaultGroupId == -1) return false; final RawContact rawContact = (RawContact) mContactData.getRawContacts().get(0); final AccountType type = rawContact.getAccountType(); // Offline or non-writeable account? Nothing to fix if (type == null || !type.areContactsWritable()) return false; // Check whether the contact is in the default group boolean isInDefaultGroup = false; for (DataItem dataItem : Iterables.filter( rawContact.getDataItems(), GroupMembershipDataItem.class)) { GroupMembershipDataItem groupMembership = (GroupMembershipDataItem) dataItem; final Long groupId = groupMembership.getGroupRowId(); if (groupId == defaultGroupId) { isInDefaultGroup = true; break; } } return !isInDefaultGroup; } @Override public String getTitle() { return getString(R.string.add_to_my_contacts); } @Override public void execute() { final long defaultGroupId = getDefaultGroupId(mContactData.getGroupMetaData()); // there should always be a default group (otherwise the button would be invisible), // but let's be safe here if (defaultGroupId == -1) return; // add the group membership to the current state final RawContactDeltaList contactDeltaList = mContactData.createRawContactDeltaList(); final RawContactDelta rawContactEntityDelta = contactDeltaList.get(0); final AccountTypeManager accountTypes = AccountTypeManager.getInstance(mContext); final AccountType type = rawContactEntityDelta.getAccountType(accountTypes); final DataKind groupMembershipKind = type.getKindForMimetype( GroupMembership.CONTENT_ITEM_TYPE); final ValuesDelta entry = RawContactModifier.insertChild(rawContactEntityDelta, groupMembershipKind); entry.setGroupRowId(defaultGroupId); // and fire off the intent. we don't need a callback, as the database listener // should update the ui final Intent intent = ContactSaveService.createSaveContactIntent(getActivity(), contactDeltaList, "", 0, false, getActivity().getClass(), Intent.ACTION_VIEW, null); getActivity().startService(intent); } } private class MakeLocalCopyQuickFix extends QuickFix { @Override public boolean isApplicable() { // Not a directory contact? Nothing to fix here if (mContactData == null || !mContactData.isDirectoryEntry()) return false; // No export support? Too bad if (mContactData.getDirectoryExportSupport() == Directory.EXPORT_SUPPORT_NONE) { return false; } return true; } @Override public String getTitle() { return getString(R.string.menu_copyContact); } @Override public void execute() { if (mListener == null) { return; } int exportSupport = mContactData.getDirectoryExportSupport(); switch (exportSupport) { case Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY: { createCopy(new AccountWithDataSet(mContactData.getDirectoryAccountName(), mContactData.getDirectoryAccountType(), null)); break; } case Directory.EXPORT_SUPPORT_ANY_ACCOUNT: { final List<AccountWithDataSet> accounts = AccountTypeManager.getInstance(mContext).getAccounts(true); if (accounts.isEmpty()) { createCopy(null); return; // Don't show a dialog. } // In the common case of a single writable account, auto-select // it without showing a dialog. if (accounts.size() == 1) { createCopy(accounts.get(0)); return; // Don't show a dialog. } SelectAccountDialogFragment.show(getFragmentManager(), ContactDetailFragment.this, R.string.dialog_new_contact_account, AccountListFilter.ACCOUNTS_CONTACT_WRITABLE, null); break; } } } } /** * This class loads the correct padding values for a contact detail item so they can be applied * dynamically. For example, this supports the case where some detail items can be indented and * need extra padding. */ private static class ViewEntryDimensions { private final int mWidePaddingLeft; private final int mPaddingLeft; private final int mPaddingRight; private final int mPaddingTop; private final int mPaddingBottom; public ViewEntryDimensions(Resources resources) { mPaddingLeft = resources.getDimensionPixelSize( R.dimen.detail_item_side_margin); mPaddingTop = resources.getDimensionPixelSize( R.dimen.detail_item_vertical_margin); mWidePaddingLeft = mPaddingLeft + resources.getDimensionPixelSize(R.dimen.detail_item_icon_margin) + resources.getDimensionPixelSize(R.dimen.detail_network_icon_size); mPaddingRight = mPaddingLeft; mPaddingBottom = mPaddingTop; } public int getWidePaddingLeft() { return mWidePaddingLeft; } public int getPaddingLeft() { return mPaddingLeft; } public int getPaddingRight() { return mPaddingRight; } public int getPaddingTop() { return mPaddingTop; } public int getPaddingBottom() { return mPaddingBottom; } } public static interface Listener { /** * User clicked a single item (e.g. mail). The intent passed in could be null. */ public void onItemClicked(Intent intent); /** * User requested creation of a new contact with the specified values. * * @param values ContentValues containing data rows for the new contact. * @param account Account where the new contact should be created. */ public void onCreateRawContactRequested(ArrayList<ContentValues> values, AccountWithDataSet account); } /** * Adapter for the invitable account types; used for the invitable account type list popup. */ private final static class InvitableAccountTypesAdapter extends BaseAdapter { private final Context mContext; private final LayoutInflater mInflater; private final ArrayList<AccountType> mAccountTypes; public InvitableAccountTypesAdapter(Context context, Contact contactData) { mContext = context; mInflater = LayoutInflater.from(context); final List<AccountType> types = contactData.getInvitableAccountTypes(); mAccountTypes = new ArrayList<AccountType>(types.size()); for (int i = 0; i < types.size(); i++) { mAccountTypes.add(types.get(i)); } Collections.sort(mAccountTypes, new AccountType.DisplayLabelComparator(mContext)); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View resultView = (convertView != null) ? convertView : mInflater.inflate(R.layout.account_selector_list_item, parent, false); final TextView text1 = (TextView)resultView.findViewById(android.R.id.text1); final TextView text2 = (TextView)resultView.findViewById(android.R.id.text2); final ImageView icon = (ImageView)resultView.findViewById(android.R.id.icon); final AccountType accountType = mAccountTypes.get(position); CharSequence action = accountType.getInviteContactActionLabel(mContext); CharSequence label = accountType.getDisplayLabel(mContext); if (TextUtils.isEmpty(action)) { text1.setText(label); text2.setVisibility(View.GONE); } else { text1.setText(action); text2.setVisibility(View.VISIBLE); text2.setText(label); } icon.setImageDrawable(accountType.getDisplayIcon(mContext)); return resultView; } @Override public int getCount() { return mAccountTypes.size(); } @Override public AccountType getItem(int position) { return mAccountTypes.get(position); } @Override public long getItemId(int position) { return position; } } }
true
true
private final void buildEntries() { mHasPhone = PhoneCapabilityTester.isPhone(mContext); mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext); mHasSip = PhoneCapabilityTester.isSipPhone(mContext); // Clear out the old entries mAllEntries.clear(); mPrimaryPhoneUri = null; // Build up method entries if (mContactData == null) { return; } ArrayList<String> groups = new ArrayList<String>(); for (RawContact rawContact: mContactData.getRawContacts()) { final long rawContactId = rawContact.getId(); for (DataItem dataItem : rawContact.getDataItems()) { dataItem.setRawContactId(rawContactId); if (dataItem.getMimeType() == null) continue; if (dataItem instanceof GroupMembershipDataItem) { GroupMembershipDataItem groupMembership = (GroupMembershipDataItem) dataItem; Long groupId = groupMembership.getGroupRowId(); if (groupId != null) { handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId); } continue; } final DataKind kind = dataItem.getDataKind(); if (kind == null) continue; final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); entry.maxLines = kind.maxLinesForDisplay; final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = dataItem.isSuperPrimary(); if (dataItem instanceof StructuredNameDataItem) { // Always ignore the name. It is shown in the header if set } else if (dataItem instanceof PhoneDataItem && hasData) { PhoneDataItem phone = (PhoneDataItem) dataItem; // Build phone entries entry.data = phone.getFormattedPhoneNumber(); final Intent phoneIntent = mHasPhone ? ContactsUtils.getCallIntent(entry.data) : null; final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null; // Configure Icons and Intents. if (mHasPhone && mHasSms) { entry.intent = phoneIntent; entry.secondaryIntent = smsIntent; entry.secondaryActionIcon = kind.iconAltRes; entry.secondaryActionDescription = kind.iconAltDescriptionRes; } else if (mHasPhone) { entry.intent = phoneIntent; } else if (mHasSms) { entry.intent = smsIntent; } else { entry.intent = null; } // Remember super-primary phone if (isSuperPrimary) mPrimaryPhoneUri = entry.uri; entry.isPrimary = isSuperPrimary; // If the entry is a primary entry, then render it first in the view. if (entry.isPrimary) { // add to beginning of list so that this phone number shows up first mPhoneEntries.add(0, entry); } else { // add to end of list mPhoneEntries.add(entry); } } else if (dataItem instanceof EmailDataItem && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; // If entry is a primary entry, then render it first in the view. if (entry.isPrimary) { mEmailEntries.add(0, entry); } else { mEmailEntries.add(entry); } // When Email rows have status, create additional Im row final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { EmailDataItem email = (EmailDataItem) dataItem; ImDataItem im = ImDataItem.createFromEmail(email); final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); buildImActions(mContext, imEntry, im); imEntry.setPresence(status.getPresence()); imEntry.maxLines = kind.maxLinesForDisplay; mImEntries.add(imEntry); } } else if (dataItem instanceof StructuredPostalDataItem && hasData) { // Build postal entries entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data); mPostalEntries.add(entry); } else if (dataItem instanceof ImDataItem && hasData) { // Build IM entries buildImActions(mContext, entry, (ImDataItem) dataItem); // Apply presence when available final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { entry.setPresence(status.getPresence()); } mImEntries.add(entry); } else if (dataItem instanceof OrganizationDataItem) { // Organizations are not shown. The first one is shown in the header // and subsequent ones are not supported anymore } else if (dataItem instanceof NicknameDataItem && hasData) { // Build nickname entries final boolean isNameRawContact = (mContactData.getNameRawContactId() == rawContactId); final boolean duplicatesTitle = isNameRawContact && mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME; if (!duplicatesTitle) { entry.uri = null; mNicknameEntries.add(entry); } } else if (dataItem instanceof NoteDataItem && hasData) { // Build note entries entry.uri = null; mNoteEntries.add(entry); } else if (dataItem instanceof WebsiteDataItem && hasData) { // Build Website entries entry.uri = null; try { WebAddress webAddress = new WebAddress(entry.data); entry.intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString())); } catch (ParseException e) { Log.e(TAG, "Couldn't parse website: " + entry.data); } mWebsiteEntries.add(entry); } else if (dataItem instanceof SipAddressDataItem && hasData) { // Build SipAddress entries entry.uri = null; if (mHasSip) { entry.intent = ContactsUtils.getCallIntent( Uri.fromParts(Constants.SCHEME_SIP, entry.data, null)); } else { entry.intent = null; } mSipEntries.add(entry); // TODO: Now that SipAddress is in its own list of entries // (instead of grouped in mOtherEntries), consider // repositioning it right under the phone number. // (Then, we'd also update FallbackAccountType.java to set // secondary=false for this field, and tweak the weight // of its DataKind.) } else if (dataItem instanceof EventDataItem && hasData) { entry.data = DateUtils.formatDate(mContext, entry.data); entry.uri = null; mEventEntries.add(entry); } else if (dataItem instanceof RelationDataItem && hasData) { entry.intent = new Intent(Intent.ACTION_SEARCH); entry.intent.putExtra(SearchManager.QUERY, entry.data); entry.intent.setType(Contacts.CONTENT_TYPE); mRelationEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW); entry.intent.setDataAndType(entry.uri, entry.mimetype); entry.data = dataItem.buildDataString(); if (!TextUtils.isEmpty(entry.data)) { // If the account type exists in the hash map, add it as another entry for // that account type AccountType type = dataItem.getAccountType(); if (mOtherEntriesMap.containsKey(type)) { List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type); listEntries.add(entry); } else { // Otherwise create a new list with the entry and add it to the hash map List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>(); listEntries.add(entry); mOtherEntriesMap.put(type, listEntries); } } } } } if (!groups.isEmpty()) { DetailViewEntry entry = new DetailViewEntry(); Collections.sort(groups); StringBuilder sb = new StringBuilder(); int size = groups.size(); for (int i = 0; i < size; i++) { if (i != 0) { sb.append(", "); } sb.append(groups.get(i)); } entry.mimetype = GroupMembership.MIMETYPE; entry.kind = mContext.getString(R.string.groupsLabel); entry.data = sb.toString(); mGroupEntries.add(entry); } }
private final void buildEntries() { mHasPhone = PhoneCapabilityTester.isPhone(mContext); mHasSms = PhoneCapabilityTester.isSmsIntentRegistered(mContext); mHasSip = PhoneCapabilityTester.isSipPhone(mContext); // Clear out the old entries mAllEntries.clear(); mPrimaryPhoneUri = null; // Build up method entries if (mContactData == null) { return; } ArrayList<String> groups = new ArrayList<String>(); for (RawContact rawContact: mContactData.getRawContacts()) { final long rawContactId = rawContact.getId(); for (DataItem dataItem : rawContact.getDataItems()) { dataItem.setRawContactId(rawContactId); if (dataItem.getMimeType() == null) continue; if (dataItem instanceof GroupMembershipDataItem) { GroupMembershipDataItem groupMembership = (GroupMembershipDataItem) dataItem; Long groupId = groupMembership.getGroupRowId(); if (groupId != null) { handleGroupMembership(groups, mContactData.getGroupMetaData(), groupId); } continue; } final DataKind kind = dataItem.getDataKind(); if (kind == null) continue; final DetailViewEntry entry = DetailViewEntry.fromValues(mContext, dataItem, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); entry.maxLines = kind.maxLinesForDisplay; final boolean hasData = !TextUtils.isEmpty(entry.data); final boolean isSuperPrimary = dataItem.isSuperPrimary(); if (dataItem instanceof StructuredNameDataItem) { // Always ignore the name. It is shown in the header if set } else if (dataItem instanceof PhoneDataItem && hasData) { PhoneDataItem phone = (PhoneDataItem) dataItem; // Build phone entries entry.data = phone.getFormattedPhoneNumber(); if (entry.data == null) { // This case happens when the quick contact was opened from the contact // list, and then, the user touches the quick contact image and brings the // user to the detail card. In this case, the Contact object that was // loaded from quick contacts does not contain the formatted phone number, // so it must be loaded here. phone.computeFormattedPhoneNumber(mDefaultCountryIso); entry.data = phone.getFormattedPhoneNumber(); } final Intent phoneIntent = mHasPhone ? ContactsUtils.getCallIntent(entry.data) : null; final Intent smsIntent = mHasSms ? new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_SMSTO, entry.data, null)) : null; // Configure Icons and Intents. if (mHasPhone && mHasSms) { entry.intent = phoneIntent; entry.secondaryIntent = smsIntent; entry.secondaryActionIcon = kind.iconAltRes; entry.secondaryActionDescription = kind.iconAltDescriptionRes; } else if (mHasPhone) { entry.intent = phoneIntent; } else if (mHasSms) { entry.intent = smsIntent; } else { entry.intent = null; } // Remember super-primary phone if (isSuperPrimary) mPrimaryPhoneUri = entry.uri; entry.isPrimary = isSuperPrimary; // If the entry is a primary entry, then render it first in the view. if (entry.isPrimary) { // add to beginning of list so that this phone number shows up first mPhoneEntries.add(0, entry); } else { // add to end of list mPhoneEntries.add(entry); } } else if (dataItem instanceof EmailDataItem && hasData) { // Build email entries entry.intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(Constants.SCHEME_MAILTO, entry.data, null)); entry.isPrimary = isSuperPrimary; // If entry is a primary entry, then render it first in the view. if (entry.isPrimary) { mEmailEntries.add(0, entry); } else { mEmailEntries.add(entry); } // When Email rows have status, create additional Im row final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { EmailDataItem email = (EmailDataItem) dataItem; ImDataItem im = ImDataItem.createFromEmail(email); final DetailViewEntry imEntry = DetailViewEntry.fromValues(mContext, im, mContactData.isDirectoryEntry(), mContactData.getDirectoryId()); buildImActions(mContext, imEntry, im); imEntry.setPresence(status.getPresence()); imEntry.maxLines = kind.maxLinesForDisplay; mImEntries.add(imEntry); } } else if (dataItem instanceof StructuredPostalDataItem && hasData) { // Build postal entries entry.intent = StructuredPostalUtils.getViewPostalAddressIntent(entry.data); mPostalEntries.add(entry); } else if (dataItem instanceof ImDataItem && hasData) { // Build IM entries buildImActions(mContext, entry, (ImDataItem) dataItem); // Apply presence when available final DataStatus status = mContactData.getStatuses().get(entry.id); if (status != null) { entry.setPresence(status.getPresence()); } mImEntries.add(entry); } else if (dataItem instanceof OrganizationDataItem) { // Organizations are not shown. The first one is shown in the header // and subsequent ones are not supported anymore } else if (dataItem instanceof NicknameDataItem && hasData) { // Build nickname entries final boolean isNameRawContact = (mContactData.getNameRawContactId() == rawContactId); final boolean duplicatesTitle = isNameRawContact && mContactData.getDisplayNameSource() == DisplayNameSources.NICKNAME; if (!duplicatesTitle) { entry.uri = null; mNicknameEntries.add(entry); } } else if (dataItem instanceof NoteDataItem && hasData) { // Build note entries entry.uri = null; mNoteEntries.add(entry); } else if (dataItem instanceof WebsiteDataItem && hasData) { // Build Website entries entry.uri = null; try { WebAddress webAddress = new WebAddress(entry.data); entry.intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webAddress.toString())); } catch (ParseException e) { Log.e(TAG, "Couldn't parse website: " + entry.data); } mWebsiteEntries.add(entry); } else if (dataItem instanceof SipAddressDataItem && hasData) { // Build SipAddress entries entry.uri = null; if (mHasSip) { entry.intent = ContactsUtils.getCallIntent( Uri.fromParts(Constants.SCHEME_SIP, entry.data, null)); } else { entry.intent = null; } mSipEntries.add(entry); // TODO: Now that SipAddress is in its own list of entries // (instead of grouped in mOtherEntries), consider // repositioning it right under the phone number. // (Then, we'd also update FallbackAccountType.java to set // secondary=false for this field, and tweak the weight // of its DataKind.) } else if (dataItem instanceof EventDataItem && hasData) { entry.data = DateUtils.formatDate(mContext, entry.data); entry.uri = null; mEventEntries.add(entry); } else if (dataItem instanceof RelationDataItem && hasData) { entry.intent = new Intent(Intent.ACTION_SEARCH); entry.intent.putExtra(SearchManager.QUERY, entry.data); entry.intent.setType(Contacts.CONTENT_TYPE); mRelationEntries.add(entry); } else { // Handle showing custom rows entry.intent = new Intent(Intent.ACTION_VIEW); entry.intent.setDataAndType(entry.uri, entry.mimetype); entry.data = dataItem.buildDataString(); if (!TextUtils.isEmpty(entry.data)) { // If the account type exists in the hash map, add it as another entry for // that account type AccountType type = dataItem.getAccountType(); if (mOtherEntriesMap.containsKey(type)) { List<DetailViewEntry> listEntries = mOtherEntriesMap.get(type); listEntries.add(entry); } else { // Otherwise create a new list with the entry and add it to the hash map List<DetailViewEntry> listEntries = new ArrayList<DetailViewEntry>(); listEntries.add(entry); mOtherEntriesMap.put(type, listEntries); } } } } } if (!groups.isEmpty()) { DetailViewEntry entry = new DetailViewEntry(); Collections.sort(groups); StringBuilder sb = new StringBuilder(); int size = groups.size(); for (int i = 0; i < size; i++) { if (i != 0) { sb.append(", "); } sb.append(groups.get(i)); } entry.mimetype = GroupMembership.MIMETYPE; entry.kind = mContext.getString(R.string.groupsLabel); entry.data = sb.toString(); mGroupEntries.add(entry); } }
diff --git a/src/main/java/com/springrts/springls/commands/impl/ForceJoinBattleCommandProcessor.java b/src/main/java/com/springrts/springls/commands/impl/ForceJoinBattleCommandProcessor.java index ed28bd9..77b89a6 100644 --- a/src/main/java/com/springrts/springls/commands/impl/ForceJoinBattleCommandProcessor.java +++ b/src/main/java/com/springrts/springls/commands/impl/ForceJoinBattleCommandProcessor.java @@ -1,109 +1,109 @@ /* Copyright (c) 2012 Robin Vobruba <[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 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, see <http://www.gnu.org/licenses/>. */ package com.springrts.springls.commands.impl; import com.springrts.springls.Account; import com.springrts.springls.Battle; import com.springrts.springls.Client; import com.springrts.springls.commands.AbstractCommandProcessor; import com.springrts.springls.commands.CommandProcessingException; import com.springrts.springls.commands.SupportedCommand; import java.util.ArrayList; import java.util.List; /** * Sent by a client that is battle host or lobby moderator, * to request a user being moved to an other host. * @author cheesecan */ @SupportedCommand("FORCEJOINBATTLE") public class ForceJoinBattleCommandProcessor extends AbstractCommandProcessor { public ForceJoinBattleCommandProcessor() { super(2, 3, Account.Access.NORMAL, true); } @Override public boolean process(Client client, List<String> args) throws CommandProcessingException { boolean checksOk = super.process(client, args); if (!checksOk) { return false; } String userName = args.get(0); Client affectedClient = getContext().getClients().getClient(userName); if (affectedClient == null) { client.sendLine("FORCEJOINBATTLE Failed, must specify valid user."); return false; } int battleId = client.getBattleID(); Battle battle = getContext().getBattles().getBattleByID(battleId); if (!(battle.getFounder().equals(client) && battle.isClientInBattle(affectedClient)) && !client.getAccount().getAccess().isAtLeast(Account.Access.PRIVILEGED)) { client.sendLine("FORCEJOINBATTLE Failed, source client must be lobby moderator or host of the affected client's current battle."); return false; } int destinationBattleId; String destinationBattleIdStr = args.get(1); try { destinationBattleId = Integer.parseInt(destinationBattleIdStr); } catch (NumberFormatException ex) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (needs to be an integer): " + destinationBattleIdStr); return false; } Battle destinationBattle = getContext().getBattles().getBattleByID(battleId); if (destinationBattle == null) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (battle does not exist): " + destinationBattleIdStr); return false; } String battlePassword = null; if (args.size() > 2) { // if optional battlePassword was set battlePassword = args.get(2); } - boolean clientSupportsCmd = client.getCompatFlags().contains("m"); + boolean clientSupportsCmd = affectedClient.getCompatFlags().contains("m"); if (clientSupportsCmd) { String successResponseMessage = (battlePassword == null) ? String.format("FORCEJOINBATTLE %i", destinationBattleId) : String.format("FORCEJOINBATTLE %i %s", destinationBattleId, battlePassword); // Issue response command to notify affected client affectedClient.sendLine(successResponseMessage); } else { // Leave the current battle. getContext().getBattles().leaveBattle(client, battle); // Join the destination battle. // We fake a JOINBATTLE command, as if it was sent // by the affected client List<String> joinBattleArgs = new ArrayList<String>(1); joinBattleArgs.add(destinationBattleIdStr); getContext().getCommandProcessors().get("JOINBATTLE").process(affectedClient, joinBattleArgs); } return true; } }
true
true
public boolean process(Client client, List<String> args) throws CommandProcessingException { boolean checksOk = super.process(client, args); if (!checksOk) { return false; } String userName = args.get(0); Client affectedClient = getContext().getClients().getClient(userName); if (affectedClient == null) { client.sendLine("FORCEJOINBATTLE Failed, must specify valid user."); return false; } int battleId = client.getBattleID(); Battle battle = getContext().getBattles().getBattleByID(battleId); if (!(battle.getFounder().equals(client) && battle.isClientInBattle(affectedClient)) && !client.getAccount().getAccess().isAtLeast(Account.Access.PRIVILEGED)) { client.sendLine("FORCEJOINBATTLE Failed, source client must be lobby moderator or host of the affected client's current battle."); return false; } int destinationBattleId; String destinationBattleIdStr = args.get(1); try { destinationBattleId = Integer.parseInt(destinationBattleIdStr); } catch (NumberFormatException ex) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (needs to be an integer): " + destinationBattleIdStr); return false; } Battle destinationBattle = getContext().getBattles().getBattleByID(battleId); if (destinationBattle == null) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (battle does not exist): " + destinationBattleIdStr); return false; } String battlePassword = null; if (args.size() > 2) { // if optional battlePassword was set battlePassword = args.get(2); } boolean clientSupportsCmd = client.getCompatFlags().contains("m"); if (clientSupportsCmd) { String successResponseMessage = (battlePassword == null) ? String.format("FORCEJOINBATTLE %i", destinationBattleId) : String.format("FORCEJOINBATTLE %i %s", destinationBattleId, battlePassword); // Issue response command to notify affected client affectedClient.sendLine(successResponseMessage); } else { // Leave the current battle. getContext().getBattles().leaveBattle(client, battle); // Join the destination battle. // We fake a JOINBATTLE command, as if it was sent // by the affected client List<String> joinBattleArgs = new ArrayList<String>(1); joinBattleArgs.add(destinationBattleIdStr); getContext().getCommandProcessors().get("JOINBATTLE").process(affectedClient, joinBattleArgs); } return true; }
public boolean process(Client client, List<String> args) throws CommandProcessingException { boolean checksOk = super.process(client, args); if (!checksOk) { return false; } String userName = args.get(0); Client affectedClient = getContext().getClients().getClient(userName); if (affectedClient == null) { client.sendLine("FORCEJOINBATTLE Failed, must specify valid user."); return false; } int battleId = client.getBattleID(); Battle battle = getContext().getBattles().getBattleByID(battleId); if (!(battle.getFounder().equals(client) && battle.isClientInBattle(affectedClient)) && !client.getAccount().getAccess().isAtLeast(Account.Access.PRIVILEGED)) { client.sendLine("FORCEJOINBATTLE Failed, source client must be lobby moderator or host of the affected client's current battle."); return false; } int destinationBattleId; String destinationBattleIdStr = args.get(1); try { destinationBattleId = Integer.parseInt(destinationBattleIdStr); } catch (NumberFormatException ex) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (needs to be an integer): " + destinationBattleIdStr); return false; } Battle destinationBattle = getContext().getBattles().getBattleByID(battleId); if (destinationBattle == null) { client.sendLine("FORCEJOINBATTLE Failed, invalid destination battle ID (battle does not exist): " + destinationBattleIdStr); return false; } String battlePassword = null; if (args.size() > 2) { // if optional battlePassword was set battlePassword = args.get(2); } boolean clientSupportsCmd = affectedClient.getCompatFlags().contains("m"); if (clientSupportsCmd) { String successResponseMessage = (battlePassword == null) ? String.format("FORCEJOINBATTLE %i", destinationBattleId) : String.format("FORCEJOINBATTLE %i %s", destinationBattleId, battlePassword); // Issue response command to notify affected client affectedClient.sendLine(successResponseMessage); } else { // Leave the current battle. getContext().getBattles().leaveBattle(client, battle); // Join the destination battle. // We fake a JOINBATTLE command, as if it was sent // by the affected client List<String> joinBattleArgs = new ArrayList<String>(1); joinBattleArgs.add(destinationBattleIdStr); getContext().getCommandProcessors().get("JOINBATTLE").process(affectedClient, joinBattleArgs); } return true; }
diff --git a/syncronizer/src/org/sync/GitImporter.java b/syncronizer/src/org/sync/GitImporter.java index ded5904..74cac74 100644 --- a/syncronizer/src/org/sync/GitImporter.java +++ b/syncronizer/src/org/sync/GitImporter.java @@ -1,481 +1,487 @@ /***************************************************************************** This file is part of Git-Starteam. Git-Starteam 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. Git-Starteam 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 Git-Starteam. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.sync; import java.io.IOException; import java.io.OutputStream; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.ossnoize.git.fastimport.Blob; import org.ossnoize.git.fastimport.Commit; import org.ossnoize.git.fastimport.Data; import org.ossnoize.git.fastimport.FileDelete; import org.ossnoize.git.fastimport.FileModification; import org.ossnoize.git.fastimport.FileOperation; import org.ossnoize.git.fastimport.enumeration.GitFileType; import org.ossnoize.git.fastimport.exception.InvalidPathException; import org.sync.util.CommitInformation; import org.sync.util.TempFileManager; import com.starbase.starteam.Folder; import com.starbase.starteam.Item; import com.starbase.starteam.Project; import com.starbase.starteam.RecycleBin; import com.starbase.starteam.Server; import com.starbase.starteam.Status; import com.starbase.starteam.Type; import com.starbase.starteam.View; import com.starbase.starteam.File; import com.starbase.starteam.CheckoutManager; import com.starbase.starteam.ViewConfiguration; import com.starbase.util.OLEDate; public class GitImporter { private Server server; private Project project; private Folder folder; private int folderNameLength; private long lastModifiedTime = 0; private Map<CommitInformation, File> sortedFileList = new TreeMap<CommitInformation, File>(); private Map<CommitInformation, File> AddedSortedFileList = new TreeMap<CommitInformation, File>(); private Map<CommitInformation, File> lastSortedFileList = new TreeMap<CommitInformation, File>(); private Commit lastCommit; // get the really old time as base information; private CommitInformation lastInformation = null; private OutputStream exportStream; private String alternateHead = null; private boolean isResume = false; private RepositoryHelper helper; // Use these sets to find all the deleted files. private Set<String> files = new HashSet<String>(); private Set<String> deletedFiles = new HashSet<String>(); private Set<String> lastFiles = new HashSet<String>(); public GitImporter(Server s, Project p) { server = s; project = p; helper = RepositoryHelperFactory.getFactory().createHelper(); } public long getLastModifiedTime() { return lastModifiedTime; } public void setFolder(View view, String folderPath) { if(null != folderPath) { recursiveFolderPopulation(view.getRootFolder(), folderPath); folderNameLength = folderPath.length(); } else { folder = view.getRootFolder(); folderNameLength = 0; } } public Folder getFolder() { return folder; } public void recursiveLastModifiedTime(Folder f) { for(Item i : f.getItems(f.getTypeNames().FILE)) { if(i instanceof File) { long modifiedTime = i.getModifiedTime().getLongValue(); if(modifiedTime > lastModifiedTime) { lastModifiedTime = modifiedTime; } i.discard(); } } for(Folder subfolder : f.getSubFolders()) { recursiveLastModifiedTime(subfolder); } f.discard(); } public void setLastFilesLastSortedFileList(View view, String folderPath) { folder = null; setFolder(view, folderPath); if(null == folder) { return; } files.clear(); deletedFiles.clear(); deletedFiles.addAll(lastFiles); sortedFileList.clear(); recursiveFilePopulation(folder); lastFiles.clear(); lastFiles.addAll(files); lastSortedFileList.clear(); lastSortedFileList.putAll(sortedFileList); AddedSortedFileList.clear(); } public void generateFastImportStream(View view, String folderPath, String domain) { // http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html // said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead." CheckoutManager cm = new CheckoutManager(view); cm.getOptions().setEOLConversionEnabled(false); lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", ""); folder = null; setFolder(view, folderPath); if(null == folder) { return; } String head = view.getName(); if(null != alternateHead) { head = alternateHead; } files.clear(); deletedFiles.clear(); deletedFiles.addAll(lastFiles); sortedFileList.clear(); recursiveFilePopulation(folder); lastFiles.clear(); lastFiles.addAll(files); lastSortedFileList.clear(); lastSortedFileList.putAll(sortedFileList); recoverDeleteInformation(deletedFiles, head, view); exportStream = helper.getFastImportStream(); for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) { File f = e.getValue(); CommitInformation current = e.getKey(); String userName = server.getUser(current.getUid()).getName(); String userEmail = userName.replaceAll(" ", ".") + "@" + domain; String path = f.getParentFolderHierarchy() + f.getName(); path = path.replace('\\', '/'); // Strip the view name from the path int indexOfFirstPath = path.indexOf('/'); path = path.substring(indexOfFirstPath + 1 + folderNameLength); try { if(f.getStatus() == Status.CURRENT) { f.discard(); continue; } if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) { f.discard(); continue; } FileOperation fo = null; java.io.File aFile = null; if(f.isDeleted() || current.isFileMove()) { fo = new FileDelete(); fo.setPath(current.getPath()); helper.unregisterFileId(head, path); } else { aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp"); cm.checkoutTo(f, aFile); Integer fileid = helper.getRegisteredFileId(head, path); if(null == fileid) { helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber()); } else { helper.updateFileVersion(head, path, f.getRevisionNumber()); } Blob fileToStage = new Blob(new Data(aFile)); helper.writeBlob(fileToStage); FileModification fm = new FileModification(fileToStage); if(aFile.canExecute()) { fm.setFileType(GitFileType.Executable); } else { fm.setFileType(GitFileType.Normal); } fm.setPath(path); fo = fm; } if(null != lastCommit && lastInformation.equivalent(current)) { if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) { lastInformation = current; lastCommit.setComment(current.getComment()); } lastCommit.addFileOperation(fo); } else { Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime())); commit.addFileOperation(fo); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); commit.setFromCommit(lastCommit); } /** Keep last for information **/ lastCommit = commit; lastInformation = current; } } catch (IOException io) { io.printStackTrace(); System.err.println("Git outputstream just crash unexpectedly. Stopping process"); System.exit(-1); } catch (InvalidPathException e1) { e1.printStackTrace(); } f.discard(); } // TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of // TODO: delete event. (as known from now) if(deletedFiles.size() > 0) { try { System.err.println("Janitor was needed for cleanup"); + java.util.Date janitorTime; + if(view.getConfiguration().isTimeBased()) { + janitorTime = new java.util.Date(view.getConfiguration().getTime().getLongValue()); + } else { + janitorTime = new java.util.Date(lastModifiedTime); + } Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", head, - new java.util.Date(view.getConfiguration().getTime().getLongValue())); + janitorTime); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); commit.setFromCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } for(String path : deletedFiles) { if(!helper.isSpecialFile(path)) { FileOperation fileDelete = new FileDelete(); try { fileDelete.setPath(path); commit.addFileOperation(fileDelete); } catch (InvalidPathException e1) { e1.printStackTrace(); } } } lastCommit = commit; } catch (IOException e1) { e1.printStackTrace(); } } if(null != lastCommit) { try { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } catch (IOException e1) { e1.printStackTrace(); } } else { if(AddedSortedFileList.size() > 0) { System.err.println("There was no new revision in the starteam view."); System.err.println("All the files in the repository are at theire lastest version"); } else { // System.err.println("The starteam view specified was empty."); } } AddedSortedFileList.clear(); cm = null; System.gc(); } @Override protected void finalize() throws Throwable { exportStream.close(); while(helper.isFastImportRunning()) { Thread.sleep(500); // active wait but leave him a chance to actually finish. } super.finalize(); } private void recoverDeleteInformation(Set<String> listOfFiles, String head, View view) { RecycleBin recycleBin = view.getRecycleBin(); recycleBin.setIncludeDeletedItems(true); Type fileType = server.typeForName(recycleBin.getTypeNames().FILE); for(Iterator<String> ith = listOfFiles.iterator(); ith.hasNext(); ) { String path = ith.next(); Integer fileID = helper.getRegisteredFileId(head, path); if(null != fileID) { CommitInformation info = null; Item item = recycleBin.findItem(fileType, fileID); if(null != item && item.isDeleted()) { info = new CommitInformation(item.getDeletedTime().getLongValue(), item.getDeletedUserID(), "", path); item.discard(); } else { item = view.findItem(fileType, fileID); if(null != item) { info = new CommitInformation(item.getModifiedTime().getLongValue(), item.getModifiedBy(), "", path); info.setFileMove(true); item.discard(); } } if(info != null) { ith.remove(); sortedFileList.put(info, (File)item); AddedSortedFileList.put(info, (File)item); } } else { System.err.println("Never seen the file " + path + " in " + head); } } } public void setResume(boolean b) { isResume = b; } private void recursiveFolderPopulation(Folder f, String folderPath) { for(Folder subfolder : f.getSubFolders()) { if(null != folder) { subfolder.discard(); f.discard(); break; } String path = subfolder.getFolderHierarchy(); path = path.replace('\\', '/'); int indexOfFirstPath = path.indexOf('/'); path = path.substring(indexOfFirstPath + 1); if(folderPath.equalsIgnoreCase(path)) { folder = subfolder; break; } recursiveFolderPopulation(subfolder, folderPath); } f.discard(); } private void recursiveFilePopulation(Folder f) { for(Item i : f.getItems(f.getTypeNames().FILE)) { if(i instanceof File) { File historyFile = (File) i; String path = i.getParentFolderHierarchy() + historyFile.getName(); path = path.replace('\\', '/'); //path = path.substring(1); int indexOfFirstPath = path.indexOf('/'); path = path.substring(indexOfFirstPath + 1 + folderNameLength); if(deletedFiles.contains(path)) { deletedFiles.remove(path); } files.add(path); CommitInformation info = new CommitInformation(i.getModifiedTime().getLongValue(), i.getModifiedBy(), i.getComment(), path); if(! lastSortedFileList.containsKey(info)) { AddedSortedFileList.put(info, historyFile); // System.err.println("Found file marked as: " + key); } sortedFileList.put(info, historyFile); } i.discard(); } for(Folder subfolder : f.getSubFolders()) { recursiveFilePopulation(subfolder); } f.discard(); } public void setHeadName(String head) { alternateHead = head; } public void setDumpFile(java.io.File file) { if(null != helper) { helper.setFastExportDumpFile(file); } else { throw new NullPointerException("Ensure that the helper is correctly started."); } } public void generateDayByDayImport(View view, Date date, String baseFolder, String domain) { View vc; long hour = 3600000L; // mSec long day = 24 * hour; // 86400000 mSec long firstTime = 0; if(isResume) { String head = view.getName(); if(null != alternateHead) { head = alternateHead; } java.util.Date lastCommit = helper.getLastCommitOfBranch(head); if(null != lastCommit) { firstTime = lastCommit.getTime(); } else { System.err.println("Cannot resume an import in a non existing branch"); return; } } if(firstTime < view.getCreatedTime().getLongValue()) { firstTime = view.getCreatedTime().getLongValue(); } System.err.println("View Created Time: " + new java.util.Date(firstTime)); if (null == date){ if(isResume) { // -R is for branch view // 2000 mSec here is to avoid side effect in StarTeam View Configuration vc = new View(view, ViewConfiguration.createFromTime(new OLEDate(firstTime + 2000))); setLastFilesLastSortedFileList(vc, baseFolder); vc.discard(); } Calendar time = Calendar.getInstance(); time.setTimeInMillis(firstTime); time.set(Calendar.HOUR_OF_DAY, 23); time.set(Calendar.MINUTE, 59); time.set(Calendar.SECOND, 59); date = time.getTime(); } firstTime = date.getTime(); // get the most recent commit // could we just get the current date ? like (now) setFolder(view, baseFolder); recursiveLastModifiedTime(getFolder()); long lastTime = getLastModifiedTime(); // in case View life less than 24 hours if(firstTime > lastTime) { firstTime = view.getCreatedTime().getLongValue(); } System.err.println("Commit from " + new java.util.Date(firstTime) + " to " + new java.util.Date(lastTime)); Calendar timeIncrement = Calendar.getInstance(); timeIncrement.setTimeInMillis(firstTime); for(;timeIncrement.getTimeInMillis() < lastTime; timeIncrement.add(Calendar.DAY_OF_YEAR, 1)) { if(lastTime - timeIncrement.getTimeInMillis() <= day) { vc = view; } else { vc = new View(view, ViewConfiguration.createFromTime(new OLEDate(timeIncrement.getTimeInMillis()))); } System.err.println("View Configuration Time: " + timeIncrement.getTime()); generateFastImportStream(vc, baseFolder, domain); vc.discard(); vc = null; } helper.gc(); } public void dispose() { helper.dispose(); } }
false
true
public void generateFastImportStream(View view, String folderPath, String domain) { // http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html // said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead." CheckoutManager cm = new CheckoutManager(view); cm.getOptions().setEOLConversionEnabled(false); lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", ""); folder = null; setFolder(view, folderPath); if(null == folder) { return; } String head = view.getName(); if(null != alternateHead) { head = alternateHead; } files.clear(); deletedFiles.clear(); deletedFiles.addAll(lastFiles); sortedFileList.clear(); recursiveFilePopulation(folder); lastFiles.clear(); lastFiles.addAll(files); lastSortedFileList.clear(); lastSortedFileList.putAll(sortedFileList); recoverDeleteInformation(deletedFiles, head, view); exportStream = helper.getFastImportStream(); for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) { File f = e.getValue(); CommitInformation current = e.getKey(); String userName = server.getUser(current.getUid()).getName(); String userEmail = userName.replaceAll(" ", ".") + "@" + domain; String path = f.getParentFolderHierarchy() + f.getName(); path = path.replace('\\', '/'); // Strip the view name from the path int indexOfFirstPath = path.indexOf('/'); path = path.substring(indexOfFirstPath + 1 + folderNameLength); try { if(f.getStatus() == Status.CURRENT) { f.discard(); continue; } if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) { f.discard(); continue; } FileOperation fo = null; java.io.File aFile = null; if(f.isDeleted() || current.isFileMove()) { fo = new FileDelete(); fo.setPath(current.getPath()); helper.unregisterFileId(head, path); } else { aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp"); cm.checkoutTo(f, aFile); Integer fileid = helper.getRegisteredFileId(head, path); if(null == fileid) { helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber()); } else { helper.updateFileVersion(head, path, f.getRevisionNumber()); } Blob fileToStage = new Blob(new Data(aFile)); helper.writeBlob(fileToStage); FileModification fm = new FileModification(fileToStage); if(aFile.canExecute()) { fm.setFileType(GitFileType.Executable); } else { fm.setFileType(GitFileType.Normal); } fm.setPath(path); fo = fm; } if(null != lastCommit && lastInformation.equivalent(current)) { if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) { lastInformation = current; lastCommit.setComment(current.getComment()); } lastCommit.addFileOperation(fo); } else { Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime())); commit.addFileOperation(fo); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); commit.setFromCommit(lastCommit); } /** Keep last for information **/ lastCommit = commit; lastInformation = current; } } catch (IOException io) { io.printStackTrace(); System.err.println("Git outputstream just crash unexpectedly. Stopping process"); System.exit(-1); } catch (InvalidPathException e1) { e1.printStackTrace(); } f.discard(); } // TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of // TODO: delete event. (as known from now) if(deletedFiles.size() > 0) { try { System.err.println("Janitor was needed for cleanup"); Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", head, new java.util.Date(view.getConfiguration().getTime().getLongValue())); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); commit.setFromCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } for(String path : deletedFiles) { if(!helper.isSpecialFile(path)) { FileOperation fileDelete = new FileDelete(); try { fileDelete.setPath(path); commit.addFileOperation(fileDelete); } catch (InvalidPathException e1) { e1.printStackTrace(); } } } lastCommit = commit; } catch (IOException e1) { e1.printStackTrace(); } } if(null != lastCommit) { try { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } catch (IOException e1) { e1.printStackTrace(); } } else { if(AddedSortedFileList.size() > 0) { System.err.println("There was no new revision in the starteam view."); System.err.println("All the files in the repository are at theire lastest version"); } else { // System.err.println("The starteam view specified was empty."); } } AddedSortedFileList.clear(); cm = null; System.gc(); }
public void generateFastImportStream(View view, String folderPath, String domain) { // http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html // said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead." CheckoutManager cm = new CheckoutManager(view); cm.getOptions().setEOLConversionEnabled(false); lastInformation = new CommitInformation(Long.MIN_VALUE, Integer.MIN_VALUE, "", ""); folder = null; setFolder(view, folderPath); if(null == folder) { return; } String head = view.getName(); if(null != alternateHead) { head = alternateHead; } files.clear(); deletedFiles.clear(); deletedFiles.addAll(lastFiles); sortedFileList.clear(); recursiveFilePopulation(folder); lastFiles.clear(); lastFiles.addAll(files); lastSortedFileList.clear(); lastSortedFileList.putAll(sortedFileList); recoverDeleteInformation(deletedFiles, head, view); exportStream = helper.getFastImportStream(); for(Map.Entry<CommitInformation, File> e : AddedSortedFileList.entrySet()) { File f = e.getValue(); CommitInformation current = e.getKey(); String userName = server.getUser(current.getUid()).getName(); String userEmail = userName.replaceAll(" ", ".") + "@" + domain; String path = f.getParentFolderHierarchy() + f.getName(); path = path.replace('\\', '/'); // Strip the view name from the path int indexOfFirstPath = path.indexOf('/'); path = path.substring(indexOfFirstPath + 1 + folderNameLength); try { if(f.getStatus() == Status.CURRENT) { f.discard(); continue; } if(f.getStatusByMD5(helper.getMD5Of(path, head)) == Status.CURRENT) { f.discard(); continue; } FileOperation fo = null; java.io.File aFile = null; if(f.isDeleted() || current.isFileMove()) { fo = new FileDelete(); fo.setPath(current.getPath()); helper.unregisterFileId(head, path); } else { aFile = TempFileManager.getInstance().createTempFile("StarteamFile", ".tmp"); cm.checkoutTo(f, aFile); Integer fileid = helper.getRegisteredFileId(head, path); if(null == fileid) { helper.registerFileId(head, path, f.getItemID(), f.getRevisionNumber()); } else { helper.updateFileVersion(head, path, f.getRevisionNumber()); } Blob fileToStage = new Blob(new Data(aFile)); helper.writeBlob(fileToStage); FileModification fm = new FileModification(fileToStage); if(aFile.canExecute()) { fm.setFileType(GitFileType.Executable); } else { fm.setFileType(GitFileType.Normal); } fm.setPath(path); fo = fm; } if(null != lastCommit && lastInformation.equivalent(current)) { if(lastInformation.getComment().trim().length() == 0 && current.getComment().trim().length() > 0) { lastInformation = current; lastCommit.setComment(current.getComment()); } lastCommit.addFileOperation(fo); } else { Commit commit = new Commit(userName, userEmail, current.getComment(), head, new java.util.Date(current.getTime())); commit.addFileOperation(fo); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); commit.setFromCommit(lastCommit); } /** Keep last for information **/ lastCommit = commit; lastInformation = current; } } catch (IOException io) { io.printStackTrace(); System.err.println("Git outputstream just crash unexpectedly. Stopping process"); System.exit(-1); } catch (InvalidPathException e1) { e1.printStackTrace(); } f.discard(); } // TODO: Simple hack to make deletion of diapered files. Since starteam does not carry some kind of // TODO: delete event. (as known from now) if(deletedFiles.size() > 0) { try { System.err.println("Janitor was needed for cleanup"); java.util.Date janitorTime; if(view.getConfiguration().isTimeBased()) { janitorTime = new java.util.Date(view.getConfiguration().getTime().getLongValue()); } else { janitorTime = new java.util.Date(lastModifiedTime); } Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", head, janitorTime); if(null == lastCommit) { if(isResume) { commit.resumeOnTopOfRef(); } } else { helper.writeCommit(lastCommit); commit.setFromCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } for(String path : deletedFiles) { if(!helper.isSpecialFile(path)) { FileOperation fileDelete = new FileDelete(); try { fileDelete.setPath(path); commit.addFileOperation(fileDelete); } catch (InvalidPathException e1) { e1.printStackTrace(); } } } lastCommit = commit; } catch (IOException e1) { e1.printStackTrace(); } } if(null != lastCommit) { try { helper.writeCommit(lastCommit); TempFileManager.getInstance().deleteTempFiles(); } catch (IOException e1) { e1.printStackTrace(); } } else { if(AddedSortedFileList.size() > 0) { System.err.println("There was no new revision in the starteam view."); System.err.println("All the files in the repository are at theire lastest version"); } else { // System.err.println("The starteam view specified was empty."); } } AddedSortedFileList.clear(); cm = null; System.gc(); }
diff --git a/net.sourceforge.eclipseccase.ui/src/net/sourceforge/eclipseccase/ui/actions/FindMergeAction.java b/net.sourceforge.eclipseccase.ui/src/net/sourceforge/eclipseccase/ui/actions/FindMergeAction.java index 5815173..1a8c7fc 100644 --- a/net.sourceforge.eclipseccase.ui/src/net/sourceforge/eclipseccase/ui/actions/FindMergeAction.java +++ b/net.sourceforge.eclipseccase.ui/src/net/sourceforge/eclipseccase/ui/actions/FindMergeAction.java @@ -1,70 +1,72 @@ package net.sourceforge.eclipseccase.ui.actions; import java.io.File; import java.lang.reflect.InvocationTargetException; import net.sourceforge.clearcase.commandline.CleartoolCommandLine; import net.sourceforge.clearcase.commandline.CommandLauncher; import net.sourceforge.eclipseccase.ClearcaseProvider; import net.sourceforge.eclipseccase.ui.console.ConsoleOperationListener; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.IAction; public class FindMergeAction extends ClearcaseWorkspaceAction { private IResource[] resources = null; /** * {@inheritDoc */ @Override public boolean isEnabled() { boolean bRes = true; IResource[] resources = getSelectedResources(); if (resources.length != 0) { for (int i = 0; (i < resources.length) && (bRes); i++) { IResource resource = resources[i]; ClearcaseProvider provider = ClearcaseProvider.getClearcaseProvider(resource); if (provider == null || provider.isUnknownState(resource) || provider.isIgnored(resource) || !provider.isClearcaseElement(resource)) { bRes = false; } } } else { bRes = false; } return bRes; } @Override public void execute(IAction action) throws InvocationTargetException, InterruptedException { resources = getSelectedResources(); IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { try { if (resources != null && resources.length != 0) { IResource resource = resources[0]; File workingDir = null; if (resource.getType() == IResource.FOLDER) { workingDir = new File(resource.getLocation().toOSString()); } else { workingDir = new File(resource.getLocation().toOSString()).getParentFile(); } - new CommandLauncher().execute(new CleartoolCommandLine("findmerge").addOption("-graphical").create(), workingDir, null, new ConsoleOperationListener(monitor)); + CommandLauncher launcher = new CommandLauncher(); + launcher.setAutoReturn(3); // FIXME: use CC Provider API + launcher.execute(new CleartoolCommandLine("findmerge").addOption("-graphical").create(), workingDir, null, new ConsoleOperationListener(monitor)); } } catch (Exception e) { } finally { monitor.done(); } } }; executeInBackground(runnable, "Make Branch Type"); } }
true
true
public void execute(IAction action) throws InvocationTargetException, InterruptedException { resources = getSelectedResources(); IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { try { if (resources != null && resources.length != 0) { IResource resource = resources[0]; File workingDir = null; if (resource.getType() == IResource.FOLDER) { workingDir = new File(resource.getLocation().toOSString()); } else { workingDir = new File(resource.getLocation().toOSString()).getParentFile(); } new CommandLauncher().execute(new CleartoolCommandLine("findmerge").addOption("-graphical").create(), workingDir, null, new ConsoleOperationListener(monitor)); } } catch (Exception e) { } finally { monitor.done(); } } }; executeInBackground(runnable, "Make Branch Type"); }
public void execute(IAction action) throws InvocationTargetException, InterruptedException { resources = getSelectedResources(); IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { try { if (resources != null && resources.length != 0) { IResource resource = resources[0]; File workingDir = null; if (resource.getType() == IResource.FOLDER) { workingDir = new File(resource.getLocation().toOSString()); } else { workingDir = new File(resource.getLocation().toOSString()).getParentFile(); } CommandLauncher launcher = new CommandLauncher(); launcher.setAutoReturn(3); // FIXME: use CC Provider API launcher.execute(new CleartoolCommandLine("findmerge").addOption("-graphical").create(), workingDir, null, new ConsoleOperationListener(monitor)); } } catch (Exception e) { } finally { monitor.done(); } } }; executeInBackground(runnable, "Make Branch Type"); }
diff --git a/src/org/cyanogenmod/nemesis/CameraManager.java b/src/org/cyanogenmod/nemesis/CameraManager.java index 261a5c2..769d4b7 100644 --- a/src/org/cyanogenmod/nemesis/CameraManager.java +++ b/src/org/cyanogenmod/nemesis/CameraManager.java @@ -1,787 +1,787 @@ /** * Copyright (C) 2013 The CyanogenMod Project * * 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 org.cyanogenmod.nemesis; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Point; import android.graphics.Rect; import android.hardware.Camera; import android.hardware.Camera.AutoFocusCallback; import android.hardware.Camera.AutoFocusMoveCallback; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.Handler; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * This class is responsible for interacting with the Camera HAL. * It provides easy open/close, helper methods to set parameters or * toggle features, etc. in an asynchronous fashion. */ public class CameraManager { private final static String TAG = "CameraManager"; private final static int FOCUS_WIDTH = 80; private final static int FOCUS_HEIGHT = 80; private CameraPreview mPreview; private Camera mCamera; private boolean mCameraReady; private int mCurrentFacing; private Point mTargetSize; private AutoFocusMoveCallback mAutoFocusMoveCallback; private Camera.Parameters mParameters; private int mOrientation; private MediaRecorder mMediaRecorder; private PreviewPauseListener mPreviewPauseListener; private CameraReadyListener mCameraReadyListener; private Handler mHandler; private long mLastPreviewFrameTime; public interface PreviewPauseListener { /** * This method is called when the preview is about to pause. * This allows the CameraActivity to display an animation when the preview * has to stop. */ public void onPreviewPause(); /** * This method is called when the preview resumes */ public void onPreviewResume(); } public interface CameraReadyListener { /** * Called when a camera has been successfully opened. This allows the * main activity to continue setup operations while the camera * sets up in a different thread. */ public void onCameraReady(); /** * Called when the camera failed to initialize */ public void onCameraFailed(); } private class AsyncParamRunnable implements Runnable { private String mKey; private String mValue; public AsyncParamRunnable(String key, String value) { mKey = key; mValue = value; } public void run() { Log.v(TAG, "Asynchronously setting parameter " + mKey + " to " + mValue); Camera.Parameters params = getParameters(); params.set(mKey, mValue); try { mCamera.setParameters(params); } catch (RuntimeException e) { Log.e(TAG, "Could not set parameter " + mKey + " to '" + mValue + "'", e); // Reset the camera as it likely crashed if we reached here open(mCurrentFacing); } // Read them from sensor next time mParameters = null; } } ; private class AsyncParamClassRunnable implements Runnable { private Camera.Parameters mParameters; public AsyncParamClassRunnable(Camera.Parameters params) { mParameters = params; } public void run() { try { mCamera.setParameters(mParameters); } catch (RuntimeException e) { Log.e(TAG, "Could not set parameters", e); // Reset the camera as it likely crashed if we reached here open(mCurrentFacing); } // Read them from sensor next time mParameters = null; } } public CameraManager(Context context) { mPreview = new CameraPreview(context); mMediaRecorder = new MediaRecorder(); mCameraReady = true; mHandler = new Handler(); } /** * Opens the camera and show its preview in the preview * * @param cameraId * @return true if the operation succeeded, false otherwise */ public boolean open(final int cameraId) { if (mCamera != null) { if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewPause(); } // Close the previous camera releaseCamera(); } mCameraReady = false; // Try to open the camera new Thread() { public void run() { try { if (mCamera != null) { Log.e(TAG, "Previous camera not closed! Not opening"); return; } mCamera = Camera.open(cameraId); mCamera.enableShutterSound(false); mCamera.setPreviewCallback(mPreview); mCurrentFacing = cameraId; mParameters = mCamera.getParameters(); // Default to the biggest preview size List<Camera.Size> sizes = mParameters.getSupportedPictureSizes(); - mParameters.setPictureSize(sizes.get(0).width, sizes.get(1).height); + mParameters.setPictureSize(sizes.get(0).width, sizes.get(0).height); String params = mCamera.getParameters().flatten(); final int step = params.length() > 256 ? 256 : params.length(); for (int i = 0; i < params.length(); i += step) { Log.e(TAG, params); params = params.substring(step); } if (mTargetSize != null) setPreviewSize(mTargetSize.x, mTargetSize.y); if (mAutoFocusMoveCallback != null) mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback); // Default focus mode to continuous } catch (Exception e) { Log.e(TAG, "Error while opening cameras: " + e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (StackTraceElement elemt : st) { Log.e(TAG, elemt.toString()); } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraFailed(); } return; } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraReady(); } // Update the preview surface holder with the new opened camera mPreview.notifyCameraChanged(); if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewResume(); } mCameraReady = true; } }.start(); return true; } public void setPreviewPauseListener(PreviewPauseListener listener) { mPreviewPauseListener = listener; } public void setCameraReadyListener(CameraReadyListener listener) { mCameraReadyListener = listener; } /** * Returns the preview surface used to display the Camera's preview * * @return CameraPreview */ public CameraPreview getPreviewSurface() { return mPreview; } /** * @return The facing of the current open camera */ public int getCurrentFacing() { return mCurrentFacing; } /** * Returns the parameters structure of the current running camera * * @return Camera.Parameters */ public Camera.Parameters getParameters() { if (mCamera == null) return null; if (mParameters == null) mParameters = mCamera.getParameters(); return mParameters; } public void pause() { releaseCamera(); } public void resume() { reconnectToCamera(); } private void releaseCamera() { if (mCamera != null && mCameraReady) { Log.v(TAG, "Releasing camera facing " + mCurrentFacing); mCamera.release(); mCamera = null; mParameters = null; mPreview.notifyCameraChanged(); mCameraReady = true; } } private void reconnectToCamera() { if (mCameraReady) { open(mCurrentFacing); } } public void setPreviewSize(int width, int height) { mTargetSize = new Point(width, height); if (mCamera != null) { mParameters.setPreviewSize(width, height); Log.v(TAG, "Preview size is " + width + "x" + height); mCamera.stopPreview(); mCamera.setParameters(mParameters); mPreview.notifyPreviewSize(width, height); mCamera.startPreview(); } } public void setParameterAsync(String key, String value) { AsyncParamRunnable run = new AsyncParamRunnable(key, value); new Thread(run).start(); } public void setParametersAsync(Camera.Parameters params) { AsyncParamClassRunnable run = new AsyncParamClassRunnable(params); new Thread(run).start(); } /** * Locks the automatic settings of the camera device, like White balance and * exposure. * * @param lock true to lock, false to unlock */ public void setLockSetup(boolean lock) { Camera.Parameters params = getParameters(); if (params == null) { // Params might be null if we pressed or swipe the shutter button // while the camera is not ready return; } if (params.isAutoExposureLockSupported()) { params.setAutoExposureLock(lock); } if (params.isAutoWhiteBalanceLockSupported()) { params.setAutoWhiteBalanceLock(lock); } mCamera.setParameters(params); } /** * Returns the last frame of the preview surface * * @return Bitmap */ public Bitmap getLastPreviewFrame() { // Decode the last frame bytes byte[] data = mPreview.getLastFrameBytes(); Camera.Parameters params = getParameters(); if (params == null) { return null; } Camera.Size previewSize = params.getPreviewSize(); if (previewSize == null) { return null; } int previewWidth = previewSize.width; int previewHeight = previewSize.height; // Convert YUV420SP preview data to RGB if (data != null) { return Util.decodeYUV420SP(mPreview.getContext(), data, previewWidth, previewHeight); } else { return null; } } /** * Returns the system time of when the last preview frame was received * * @return long */ public long getLastPreviewFrameTime() { return mLastPreviewFrameTime; } /** * Defines a new size for the recorded picture * XXX: Should it update preview size?! * * @param sz The new picture size */ public void setPictureSize(Camera.Size sz) { Camera.Parameters params = getParameters(); params.setPictureSize(sz.width, sz.height); mCamera.setParameters(params); } /** * Takes a snapshot */ public void takeSnapshot(Camera.ShutterCallback shutterCallback, Camera.PictureCallback raw, Camera.PictureCallback jpeg) { Log.v(TAG, "takePicture"); SoundManager.getSingleton().play(SoundManager.SOUND_SHUTTER); mCamera.takePicture(shutterCallback, raw, jpeg); } /** * Prepares the MediaRecorder to record a video. This must be called before * startVideoRecording to setup the recording environment. * * @param fileName Target file path * @param profile Target profile (quality) */ public void prepareVideoRecording(String fileName, CamcorderProfile profile) { // Unlock the camera for use with MediaRecorder mCamera.unlock(); mMediaRecorder.setCamera(mCamera); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setProfile(profile); mMediaRecorder.setOutputFile(fileName); // Set maximum file size. long maxFileSize = Storage.getStorage().getAvailableSpace() - Storage.LOW_STORAGE_THRESHOLD; mMediaRecorder.setMaxFileSize(maxFileSize); mMediaRecorder.setMaxDuration(0); // infinite mMediaRecorder.setPreviewDisplay(mPreview.getSurfaceHolder().getSurface()); try { mMediaRecorder.prepare(); } catch (IllegalStateException e) { Log.e(TAG, "Cannot prepare MediaRecorder", e); } catch (IOException e) { Log.e(TAG, "Cannot prepare MediaRecorder", e); } mPreview.postCallbackBuffer(); } public void startVideoRecording() { Log.v(TAG, "startVideoRecording"); mMediaRecorder.start(); mPreview.postCallbackBuffer(); } public void stopVideoRecording() { Log.v(TAG, "stopVideoRecording"); mMediaRecorder.stop(); mCamera.lock(); mMediaRecorder.reset(); mPreview.postCallbackBuffer(); } /** * Returns the orientation of the device * * @return */ public int getOrientation() { return mOrientation; } public void setOrientation(int orientation) { mOrientation = orientation; } public void restartPreviewIfNeeded() { try { mCamera.startPreview(); } catch (Exception e) { // ignore } } public void setCameraMode(final int mode) { if (mPreviewPauseListener != null) { // mPreviewPauseListener.onPreviewPause(); return; } new Thread() { public void run() { // We voluntarily sleep the thread here for the animation being done // in the CameraActivity try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } Camera.Parameters params = getParameters(); if (mode == CameraActivity.CAMERA_MODE_VIDEO) { params.setRecordingHint(true); } else { params.setRecordingHint(false); } mCamera.stopPreview(); mCamera.setParameters(params); try { mCamera.startPreview(); } catch (RuntimeException e) { Log.e(TAG, "Unable to start preview", e); } mPreview.postCallbackBuffer(); if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewResume(); } } }.start(); } /** * Trigger the autofocus function of the device * * @param cb The AF callback * @return true if we could start the AF, false otherwise */ public boolean doAutofocus(final AutoFocusCallback cb) { if (mCamera != null) { try { // make sure our auto settings aren't locked setLockSetup(false); // trigger af mCamera.cancelAutoFocus(); mHandler.post(new Runnable() { public void run() { mCamera.autoFocus(cb); } }); } catch (Exception e) { return false; } return true; } else { return false; } } /** * Returns whether or not the current open camera device supports * focus area (focus ring) * * @return true if supported */ public boolean isFocusAreaSupported() { if (mCamera != null) { try { return (getParameters().getMaxNumFocusAreas() > 0); } catch (Exception e) { return false; } } else { return false; } } /** * Returns whether or not the current open camera device supports * exposure metering area (exposure ring) * * @return true if supported */ public boolean isExposureAreaSupported() { if (mCamera != null) { try { return (getParameters().getMaxNumMeteringAreas() > 0); } catch (Exception e) { return false; } } else { return false; } } /** * Defines the main focus point of the camera to the provided x and y values. * Those values must between -1000 and 1000, where -1000 is the top/left, and 1000 the bottom/right * * @param x The X position of the focus point * @param y The Y position of the focus point */ public void setFocusPoint(int x, int y) { Camera.Parameters params = getParameters(); if (params.getMaxNumFocusAreas() > 0) { List<Camera.Area> focusArea = new ArrayList<Camera.Area>(); focusArea.add(new Camera.Area(new Rect(x, y, x + FOCUS_WIDTH, y + FOCUS_HEIGHT), 1000)); params.setFocusAreas(focusArea); try { mCamera.setParameters(params); } catch (Exception e) { // ignore, we might be setting it too fast since previous attempt } } } /** * Defines the exposure metering point of the camera to the provided x and y values. * Those values must between -1000 and 1000, where -1000 is the top/left, and 1000 the bottom/right * * @param x The X position of the exposure metering point * @param y The Y position of the exposure metering point */ public void setExposurePoint(int x, int y) { Camera.Parameters params = getParameters(); if (params != null && params.getMaxNumMeteringAreas() > 0) { List<Camera.Area> exposureArea = new ArrayList<Camera.Area>(); exposureArea.add(new Camera.Area(new Rect(x, y, x + FOCUS_WIDTH, y + FOCUS_HEIGHT), 1000)); params.setMeteringAreas(exposureArea); try { mCamera.setParameters(params); } catch (Exception e) { // ignore, we might be setting it too fast since previous attempt } } } public void setAutoFocusMoveCallback(AutoFocusMoveCallback cb) { mAutoFocusMoveCallback = cb; if (mCamera != null) mCamera.setAutoFocusMoveCallback(cb); } /** * Enable the device image stabilization system. Toggle device-specific * stab as well if they exist and are implemented. * @param enabled */ public void setStabilization(boolean enabled) { Camera.Parameters params = getParameters(); if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_PHOTO) { // Sony if (params.get("sony-is") != null) { // XXX: on-still-hdr params.set("sony-is", enabled ? "on" : "off"); } // HTC else if (params.get("ois_mode") != null) { params.set("ois_mode", enabled ? "on" : "off"); } } else if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_VIDEO) { if (params.get("sony-vs") != null) { params.set("sony-vs", enabled ? "on" : "off"); } else { params.setVideoStabilization(enabled); } } } /** * The CameraPreview class handles the Camera preview feed * and setting the surface holder. */ public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback { private final static String TAG = "CameraManager.CameraPreview"; private SurfaceHolder mHolder; private byte[] mLastFrameBytes; public CameraPreview(Context context) { super(context); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); } public void notifyPreviewSize(int width, int height) { mLastFrameBytes = new byte[(int) (width * height * 1.5 + 0.5)]; } public byte[] getLastFrameBytes() { return mLastFrameBytes; } public SurfaceHolder getSurfaceHolder() { return mHolder; } public void notifyCameraChanged() { if (mCamera != null) { setupCamera(); try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); mPreview.postCallbackBuffer(); } catch (IOException e) { Log.e(TAG, "Error setting camera preview: " + e.getMessage()); } } } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. if (mCamera == null) return; try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); mPreview.postCallbackBuffer(); } catch (IOException e) { Log.e(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { if (mHolder.getSurface() == null) { // preview surface does not exist return; } // stop preview before making changes try { mCamera.stopPreview(); } catch (Exception e) { // ignore: tried to stop a non-existent preview } setupCamera(); // start preview with new settings try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e) { Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } } public void postCallbackBuffer() { mCamera.addCallbackBuffer(mLastFrameBytes); mCamera.setPreviewCallbackWithBuffer(this); } private void setupCamera() { // Set device-specifics here try { Camera.Parameters params = mCamera.getParameters(); if (getResources().getBoolean(R.bool.config_qualcommZslCameraMode)) { params.set("camera-mode", 1); } mCamera.setParameters(params); postCallbackBuffer(); } catch (Exception e) { Log.e(TAG, "Could not set device specifics"); } } @Override public void onPreviewFrame(byte[] data, Camera camera) { mLastPreviewFrameTime = System.currentTimeMillis(); if (mCamera != null) { mCamera.addCallbackBuffer(mLastFrameBytes); } } } }
true
true
public boolean open(final int cameraId) { if (mCamera != null) { if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewPause(); } // Close the previous camera releaseCamera(); } mCameraReady = false; // Try to open the camera new Thread() { public void run() { try { if (mCamera != null) { Log.e(TAG, "Previous camera not closed! Not opening"); return; } mCamera = Camera.open(cameraId); mCamera.enableShutterSound(false); mCamera.setPreviewCallback(mPreview); mCurrentFacing = cameraId; mParameters = mCamera.getParameters(); // Default to the biggest preview size List<Camera.Size> sizes = mParameters.getSupportedPictureSizes(); mParameters.setPictureSize(sizes.get(0).width, sizes.get(1).height); String params = mCamera.getParameters().flatten(); final int step = params.length() > 256 ? 256 : params.length(); for (int i = 0; i < params.length(); i += step) { Log.e(TAG, params); params = params.substring(step); } if (mTargetSize != null) setPreviewSize(mTargetSize.x, mTargetSize.y); if (mAutoFocusMoveCallback != null) mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback); // Default focus mode to continuous } catch (Exception e) { Log.e(TAG, "Error while opening cameras: " + e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (StackTraceElement elemt : st) { Log.e(TAG, elemt.toString()); } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraFailed(); } return; } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraReady(); } // Update the preview surface holder with the new opened camera mPreview.notifyCameraChanged(); if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewResume(); } mCameraReady = true; } }.start(); return true; }
public boolean open(final int cameraId) { if (mCamera != null) { if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewPause(); } // Close the previous camera releaseCamera(); } mCameraReady = false; // Try to open the camera new Thread() { public void run() { try { if (mCamera != null) { Log.e(TAG, "Previous camera not closed! Not opening"); return; } mCamera = Camera.open(cameraId); mCamera.enableShutterSound(false); mCamera.setPreviewCallback(mPreview); mCurrentFacing = cameraId; mParameters = mCamera.getParameters(); // Default to the biggest preview size List<Camera.Size> sizes = mParameters.getSupportedPictureSizes(); mParameters.setPictureSize(sizes.get(0).width, sizes.get(0).height); String params = mCamera.getParameters().flatten(); final int step = params.length() > 256 ? 256 : params.length(); for (int i = 0; i < params.length(); i += step) { Log.e(TAG, params); params = params.substring(step); } if (mTargetSize != null) setPreviewSize(mTargetSize.x, mTargetSize.y); if (mAutoFocusMoveCallback != null) mCamera.setAutoFocusMoveCallback(mAutoFocusMoveCallback); // Default focus mode to continuous } catch (Exception e) { Log.e(TAG, "Error while opening cameras: " + e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (StackTraceElement elemt : st) { Log.e(TAG, elemt.toString()); } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraFailed(); } return; } if (mCameraReadyListener != null) { mCameraReadyListener.onCameraReady(); } // Update the preview surface holder with the new opened camera mPreview.notifyCameraChanged(); if (mPreviewPauseListener != null) { mPreviewPauseListener.onPreviewResume(); } mCameraReady = true; } }.start(); return true; }
diff --git a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java index dd118703e..b0a5dbc88 100644 --- a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java +++ b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java @@ -1,196 +1,200 @@ /* * (c) Fachhochschule Potsdam */ package org.fritzing.fritzing.diagram.part; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.URI; import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.fritzing.fritzing.diagram.export.Fritzing2Eagle; import org.fritzing.fritzing.diagram.preferences.EaglePreferencePage; /** * @generated NOT */ public class FritzingPCBExportAction implements IWorkbenchWindowActionDelegate { /** * @generated NOT */ private IWorkbenchWindow window; /** * @generated NOT */ public void init(IWorkbenchWindow window) { this.window = window; } /** * @generated NOT */ public void dispose() { window = null; } /** * @generated NOT */ public void selectionChanged(IAction action, ISelection selection) { } /** * @generated NOT */ private Shell getShell() { return window.getShell(); } /** * @generated NOT */ public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files IDiagramWorkbenchPart editor = null; URI diagramUri = null; try { // use currently active diagram editor = FritzingDiagramEditorUtil.getActiveDiagramPart(); diagramUri = FritzingDiagramEditorUtil.getActiveDiagramURI(); } catch (NullPointerException npe) { ErrorDialog.openError(getShell(), "PCB Export Error", Messages.FritzingPCBExportAction_NoOpenSketchError, new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No sketch currently opened.", npe)); return; } // validate ValidateAction.runValidation(editor.getDiagramEditPart(), editor.getDiagram()); // TODO: warn if validation shows errors // Specify paths to scripts and ULPs needed by Eagle // these include fritzing_master.ulp, auto_place.ulp, fritzing_setup-arduino_shield.scr, // and fritzing_menu-placement.scr at the moment // (done here because the location of the Fritzing Eagle library must be passed // to the method that creates the schematic-generation script) String fritzingLocation = Platform.getInstallLocation().getURL().getPath(); + if (Platform.getOS().equals(Platform.OS_WIN32)) { + fritzingLocation = fritzingLocation.startsWith("/") ? + fritzingLocation.substring(1) : fritzingLocation; + } // transform into EAGLE script String script = Fritzing2Eagle.createEagleScript(editor.getDiagramGraphicalViewer()); String fritzing2eagleSCR = diagramUri.trimFileExtension() .appendFileExtension("scr").toFileString(); // Delete existing one so that EAGLE will create new ones File eagleScrFile = new File(fritzing2eagleSCR); if (eagleScrFile.exists()) { eagleScrFile.delete(); } try { FileOutputStream fos = new FileOutputStream(fritzing2eagleSCR); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(script); fos.flush(); fos.getFD().sync(); osw.close(); // NOTE: FileWriter would be nice here, but it doesn't sync immediately } catch (IOException ioe) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not create file " + fritzing2eagleSCR + " for writing the EAGLE script.\n"+ "Please check if Fritzing has write access.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "File could not be written.", ioe)); return; } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance() .getPluginPreferences(); String eagleLocation = preferences .getString(EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = eagleLocation + "bin\\eagle.exe"; } else if (Platform.getOS().equals(Platform.OS_MACOSX)) { eagleExec = eagleLocation + "EAGLE.app/Contents/MacOS/eagle"; } else if (Platform.getOS().equals(Platform.OS_LINUX)) { eagleExec = eagleLocation + "bin/eagle"; } if (! new File(eagleExec).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find EAGLE installation at " + eagleLocation + ".\n"+ "Please check if you correctly set the EAGLE location in the preferences.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No EAGLE executable at "+eagleExec, null)); return; } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = "\"" + eagleExec + "\""; } // EAGLE PCB .ulp String eagleULP = fritzingLocation + "ulp" + File.separator + "fritzing_master.ulp"; if (! new File(eagleULP).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find Fritzing ULP at " + eagleULP + ".\n"+ "Please check if you copied the Fritzing EAGLE files to the EAGLE subfolders.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "Fritzing ULP not found.", null)); return; } // EAGLE .sch and .brd files String eagleSCH = diagramUri.trimFileExtension() .appendFileExtension("sch").toFileString(); String eagleBRD = diagramUri.trimFileExtension() .appendFileExtension("brd").toFileString(); // Delete existing ones so that EAGLE will create new ones File eagleSchFile = new File(eagleSCH); if (eagleSchFile.exists()) { eagleSchFile.delete(); } File eagleBrdFile = new File(eagleBRD); if (eagleBrdFile.exists()) { eagleBrdFile.delete(); } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleSCH = "\"" + eagleSCH + "\""; } // EAGLE parameters String eagleParams = "RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "' " + "'" + fritzingLocation + "'"; // Run! try { ProcessBuilder runEagle = new ProcessBuilder( eagleExec, "-C", eagleParams, eagleSCH); Process p = runEagle.start(); // p.waitFor(); // don't wait for Eagle to quit } catch (IOException ioe1) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not launch EAGLE PCB export.\n"+ "Please check that all of the following files exist:\n\n"+ String.format("%s, %s, %s, %s", eagleExec, eagleULP, fritzing2eagleSCR, eagleSCH), new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "EAGLE PCB export failed.", ioe1)); return; } } }
true
true
public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files IDiagramWorkbenchPart editor = null; URI diagramUri = null; try { // use currently active diagram editor = FritzingDiagramEditorUtil.getActiveDiagramPart(); diagramUri = FritzingDiagramEditorUtil.getActiveDiagramURI(); } catch (NullPointerException npe) { ErrorDialog.openError(getShell(), "PCB Export Error", Messages.FritzingPCBExportAction_NoOpenSketchError, new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No sketch currently opened.", npe)); return; } // validate ValidateAction.runValidation(editor.getDiagramEditPart(), editor.getDiagram()); // TODO: warn if validation shows errors // Specify paths to scripts and ULPs needed by Eagle // these include fritzing_master.ulp, auto_place.ulp, fritzing_setup-arduino_shield.scr, // and fritzing_menu-placement.scr at the moment // (done here because the location of the Fritzing Eagle library must be passed // to the method that creates the schematic-generation script) String fritzingLocation = Platform.getInstallLocation().getURL().getPath(); // transform into EAGLE script String script = Fritzing2Eagle.createEagleScript(editor.getDiagramGraphicalViewer()); String fritzing2eagleSCR = diagramUri.trimFileExtension() .appendFileExtension("scr").toFileString(); // Delete existing one so that EAGLE will create new ones File eagleScrFile = new File(fritzing2eagleSCR); if (eagleScrFile.exists()) { eagleScrFile.delete(); } try { FileOutputStream fos = new FileOutputStream(fritzing2eagleSCR); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(script); fos.flush(); fos.getFD().sync(); osw.close(); // NOTE: FileWriter would be nice here, but it doesn't sync immediately } catch (IOException ioe) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not create file " + fritzing2eagleSCR + " for writing the EAGLE script.\n"+ "Please check if Fritzing has write access.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "File could not be written.", ioe)); return; } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance() .getPluginPreferences(); String eagleLocation = preferences .getString(EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = eagleLocation + "bin\\eagle.exe"; } else if (Platform.getOS().equals(Platform.OS_MACOSX)) { eagleExec = eagleLocation + "EAGLE.app/Contents/MacOS/eagle"; } else if (Platform.getOS().equals(Platform.OS_LINUX)) { eagleExec = eagleLocation + "bin/eagle"; } if (! new File(eagleExec).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find EAGLE installation at " + eagleLocation + ".\n"+ "Please check if you correctly set the EAGLE location in the preferences.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No EAGLE executable at "+eagleExec, null)); return; } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = "\"" + eagleExec + "\""; } // EAGLE PCB .ulp String eagleULP = fritzingLocation + "ulp" + File.separator + "fritzing_master.ulp"; if (! new File(eagleULP).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find Fritzing ULP at " + eagleULP + ".\n"+ "Please check if you copied the Fritzing EAGLE files to the EAGLE subfolders.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "Fritzing ULP not found.", null)); return; } // EAGLE .sch and .brd files String eagleSCH = diagramUri.trimFileExtension() .appendFileExtension("sch").toFileString(); String eagleBRD = diagramUri.trimFileExtension() .appendFileExtension("brd").toFileString(); // Delete existing ones so that EAGLE will create new ones File eagleSchFile = new File(eagleSCH); if (eagleSchFile.exists()) { eagleSchFile.delete(); } File eagleBrdFile = new File(eagleBRD); if (eagleBrdFile.exists()) { eagleBrdFile.delete(); } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleSCH = "\"" + eagleSCH + "\""; } // EAGLE parameters String eagleParams = "RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "' " + "'" + fritzingLocation + "'"; // Run! try { ProcessBuilder runEagle = new ProcessBuilder( eagleExec, "-C", eagleParams, eagleSCH); Process p = runEagle.start(); // p.waitFor(); // don't wait for Eagle to quit } catch (IOException ioe1) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not launch EAGLE PCB export.\n"+ "Please check that all of the following files exist:\n\n"+ String.format("%s, %s, %s, %s", eagleExec, eagleULP, fritzing2eagleSCR, eagleSCH), new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "EAGLE PCB export failed.", ioe1)); return; } }
public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files IDiagramWorkbenchPart editor = null; URI diagramUri = null; try { // use currently active diagram editor = FritzingDiagramEditorUtil.getActiveDiagramPart(); diagramUri = FritzingDiagramEditorUtil.getActiveDiagramURI(); } catch (NullPointerException npe) { ErrorDialog.openError(getShell(), "PCB Export Error", Messages.FritzingPCBExportAction_NoOpenSketchError, new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No sketch currently opened.", npe)); return; } // validate ValidateAction.runValidation(editor.getDiagramEditPart(), editor.getDiagram()); // TODO: warn if validation shows errors // Specify paths to scripts and ULPs needed by Eagle // these include fritzing_master.ulp, auto_place.ulp, fritzing_setup-arduino_shield.scr, // and fritzing_menu-placement.scr at the moment // (done here because the location of the Fritzing Eagle library must be passed // to the method that creates the schematic-generation script) String fritzingLocation = Platform.getInstallLocation().getURL().getPath(); if (Platform.getOS().equals(Platform.OS_WIN32)) { fritzingLocation = fritzingLocation.startsWith("/") ? fritzingLocation.substring(1) : fritzingLocation; } // transform into EAGLE script String script = Fritzing2Eagle.createEagleScript(editor.getDiagramGraphicalViewer()); String fritzing2eagleSCR = diagramUri.trimFileExtension() .appendFileExtension("scr").toFileString(); // Delete existing one so that EAGLE will create new ones File eagleScrFile = new File(fritzing2eagleSCR); if (eagleScrFile.exists()) { eagleScrFile.delete(); } try { FileOutputStream fos = new FileOutputStream(fritzing2eagleSCR); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(script); fos.flush(); fos.getFD().sync(); osw.close(); // NOTE: FileWriter would be nice here, but it doesn't sync immediately } catch (IOException ioe) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not create file " + fritzing2eagleSCR + " for writing the EAGLE script.\n"+ "Please check if Fritzing has write access.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "File could not be written.", ioe)); return; } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance() .getPluginPreferences(); String eagleLocation = preferences .getString(EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = eagleLocation + "bin\\eagle.exe"; } else if (Platform.getOS().equals(Platform.OS_MACOSX)) { eagleExec = eagleLocation + "EAGLE.app/Contents/MacOS/eagle"; } else if (Platform.getOS().equals(Platform.OS_LINUX)) { eagleExec = eagleLocation + "bin/eagle"; } if (! new File(eagleExec).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find EAGLE installation at " + eagleLocation + ".\n"+ "Please check if you correctly set the EAGLE location in the preferences.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "No EAGLE executable at "+eagleExec, null)); return; } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = "\"" + eagleExec + "\""; } // EAGLE PCB .ulp String eagleULP = fritzingLocation + "ulp" + File.separator + "fritzing_master.ulp"; if (! new File(eagleULP).exists()) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not find Fritzing ULP at " + eagleULP + ".\n"+ "Please check if you copied the Fritzing EAGLE files to the EAGLE subfolders.", new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "Fritzing ULP not found.", null)); return; } // EAGLE .sch and .brd files String eagleSCH = diagramUri.trimFileExtension() .appendFileExtension("sch").toFileString(); String eagleBRD = diagramUri.trimFileExtension() .appendFileExtension("brd").toFileString(); // Delete existing ones so that EAGLE will create new ones File eagleSchFile = new File(eagleSCH); if (eagleSchFile.exists()) { eagleSchFile.delete(); } File eagleBrdFile = new File(eagleBRD); if (eagleBrdFile.exists()) { eagleBrdFile.delete(); } if (Platform.getOS().equals(Platform.OS_WIN32)) { eagleSCH = "\"" + eagleSCH + "\""; } // EAGLE parameters String eagleParams = "RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "' " + "'" + fritzingLocation + "'"; // Run! try { ProcessBuilder runEagle = new ProcessBuilder( eagleExec, "-C", eagleParams, eagleSCH); Process p = runEagle.start(); // p.waitFor(); // don't wait for Eagle to quit } catch (IOException ioe1) { ErrorDialog.openError(getShell(), "PCB Export Error", "Could not launch EAGLE PCB export.\n"+ "Please check that all of the following files exist:\n\n"+ String.format("%s, %s, %s, %s", eagleExec, eagleULP, fritzing2eagleSCR, eagleSCH), new Status(Status.ERROR, FritzingDiagramEditorPlugin.ID, "EAGLE PCB export failed.", ioe1)); return; } }
diff --git a/src/android/src/pro/trousev/cleer/android/service/AndroidCleerService.java b/src/android/src/pro/trousev/cleer/android/service/AndroidCleerService.java index ace7707..92a413c 100644 --- a/src/android/src/pro/trousev/cleer/android/service/AndroidCleerService.java +++ b/src/android/src/pro/trousev/cleer/android/service/AndroidCleerService.java @@ -1,242 +1,242 @@ package pro.trousev.cleer.android.service; import pro.trousev.cleer.Database; import pro.trousev.cleer.Item; import pro.trousev.cleer.Item.NoSuchTagException; import pro.trousev.cleer.Messaging; import pro.trousev.cleer.Messaging.Message; import pro.trousev.cleer.Playlist; import pro.trousev.cleer.Queue; import pro.trousev.cleer.Queue.EnqueueMode; import pro.trousev.cleer.android.AndroidMessages; import pro.trousev.cleer.android.AndroidMessages.ServiceRequestMessage; import pro.trousev.cleer.android.AndroidMessages.ServiceRespondMessage; import pro.trousev.cleer.android.AndroidMessages.ServiceTaskMessage; import pro.trousev.cleer.android.AndroidMessages.TypeOfResult; import pro.trousev.cleer.android.Constants; import pro.trousev.cleer.sys.QueueImpl; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class AndroidCleerService extends Service { private static ServiceRespondMessage respondMessage = new ServiceRespondMessage(); private Queue queue = null; private Database database = null; // TODO Notification update on song change private Notification notification = null; private NotificationManager notificationManager = null; // Binder allow us get Service.this from the Activity public class CleerBinder extends Binder { public AndroidCleerService getService() { return AndroidCleerService.this; } } private Notification makeNotification() { String _s = null; Notification notification = null; try { _s = "Song: " + queue.playing_track().tag("name").value(); notification = new Notification.Builder(getApplicationContext()) .setContentTitle(Constants.NOTIFICATION_TITLE) .setContentText(_s).build(); } catch (NoSuchTagException e) { notification = new Notification.Builder(getApplicationContext()) .setContentTitle(Constants.NOTIFICATION_TITLE) .setContentText("NO SONG NAME AVALIBLE").build(); // e.printStackTrace(); } return notification; } private void updateNotification() { notification = makeNotification(); notificationManager.notify(Constants.PLAYER_NOTIFICATION_ID, notification); } public void onCreate() { super.onCreate(); queue = new QueueImpl(new PlayerAndroid()); - database = new DatabaseImpl(Constants.DATABASE_PATH); + //database = new DatabaseImpl(Constants.DATABASE_PATH); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Messaging.subscribe(AndroidMessages.ServiceRequestMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceRequestMessage mes = (ServiceRequestMessage) message; if (mes.type == TypeOfResult.Compositions) ; switch (mes.type) { case Compositions: break; case Queue: break; case Albums: break; case Genres: break; case Artists: break; case Playlists: break; case Playlist: break; case PlaylistsInDialog: break; } respondMessage.typeOfContent = mes.type; Messaging.fire(respondMessage); } }); Messaging.subscribe(AndroidMessages.ServiceTaskMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceTaskMessage mes = (ServiceTaskMessage) message; switch (mes.action) { case Play: notification = makeNotification(); startForeground(Constants.PLAYER_NOTIFICATION_ID, notification); queue.play(); break; case Pause: queue.pause(); stopForeground(false); break; case Next: queue.next(); break; case Previous: queue.prev(); break; case addToQueue: queue.enqueue(mes.list, EnqueueMode.AfterAll); break; case setToQueue: queue.enqueue(mes.list, EnqueueMode.ReplaceAll); break; default: break; // TODO add others... } updateNotification(); } }); Log.d(Constants.LOG_TAG, "Service.onCreate()"); } // // private void play() { // // TODO delete that // PlayerChangeEvent changeEvent = new PlayerChangeEvent(); // changeEvent.status = Status.Playing; // Messaging.fire(changeEvent); // Log.d(Constants.LOG_TAG, "Service.play()"); // } // // private void pause() { // // TODO delete that // PlayerChangeEvent changeEvent = new PlayerChangeEvent(); // changeEvent.status = Status.Paused; // Messaging.fire(changeEvent); // Log.d(Constants.LOG_TAG, "Service.pause()"); // } // // private void next() { // Log.d(Constants.LOG_TAG, "Service.next()"); // } // // private void prev() { // Log.d(Constants.LOG_TAG, "Service.prev()"); // } // // // adds songs at the end of queue // public void addToQueue(List<Item> tracks) { // // } // // // clear queue, set list<item> in it, start playing song with current // index // public void setToQueue(List<Item> tracks, int index) { // Log.d(Constants.LOG_TAG, "Service.setToQueue"); // } // // // returns songs from the queue // public List<Item> getQueueItems() { // return null; // } // // // add item into the user playlist // public void addItemToList(Item item, Playlist playlist) { // // } // // // create new user playlist // public void createNewList(String name) { // // Do we need that method? // } // // // returns list of user playlists // public List<Playlist> getPlaylists() { // return null; // } // // // returns list of Items from database, which suit to the searchQuery // public List<Item> getListOfTracks(String searchQuery) { // return null; // } // // // Returns list of items with all represented values of some tag tagName // public List<Item> getListOfTagValues(String tagName) { // // return null; // } // // // return all albums with information about artist // // album == item // public List<Item> getListOfAlbums() { // return null; // } // This method is called every time UI starts public int onStartCommand(Intent intent, int flags, int startId) { Log.d(Constants.LOG_TAG, "Service.onStartCommand()"); return super.onStartCommand(intent, flags, startId); } public void onDestroy() { Log.d(Constants.LOG_TAG, "Service.onDestroy()"); super.onDestroy(); } public IBinder onBind(Intent intent) { Log.d(Constants.LOG_TAG, "Service.onBind()"); return new CleerBinder(); } public boolean onUnbind(Intent intent) { Log.d(Constants.LOG_TAG, "Service.onUnbind()"); return true; // for onServiceConnected } public void onRebind(Intent intent) { Log.d(Constants.LOG_TAG, "Service.onRebind()"); } }
true
true
public void onCreate() { super.onCreate(); queue = new QueueImpl(new PlayerAndroid()); database = new DatabaseImpl(Constants.DATABASE_PATH); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Messaging.subscribe(AndroidMessages.ServiceRequestMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceRequestMessage mes = (ServiceRequestMessage) message; if (mes.type == TypeOfResult.Compositions) ; switch (mes.type) { case Compositions: break; case Queue: break; case Albums: break; case Genres: break; case Artists: break; case Playlists: break; case Playlist: break; case PlaylistsInDialog: break; } respondMessage.typeOfContent = mes.type; Messaging.fire(respondMessage); } }); Messaging.subscribe(AndroidMessages.ServiceTaskMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceTaskMessage mes = (ServiceTaskMessage) message; switch (mes.action) { case Play: notification = makeNotification(); startForeground(Constants.PLAYER_NOTIFICATION_ID, notification); queue.play(); break; case Pause: queue.pause(); stopForeground(false); break; case Next: queue.next(); break; case Previous: queue.prev(); break; case addToQueue: queue.enqueue(mes.list, EnqueueMode.AfterAll); break; case setToQueue: queue.enqueue(mes.list, EnqueueMode.ReplaceAll); break; default: break; // TODO add others... } updateNotification(); } }); Log.d(Constants.LOG_TAG, "Service.onCreate()"); }
public void onCreate() { super.onCreate(); queue = new QueueImpl(new PlayerAndroid()); //database = new DatabaseImpl(Constants.DATABASE_PATH); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Messaging.subscribe(AndroidMessages.ServiceRequestMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceRequestMessage mes = (ServiceRequestMessage) message; if (mes.type == TypeOfResult.Compositions) ; switch (mes.type) { case Compositions: break; case Queue: break; case Albums: break; case Genres: break; case Artists: break; case Playlists: break; case Playlist: break; case PlaylistsInDialog: break; } respondMessage.typeOfContent = mes.type; Messaging.fire(respondMessage); } }); Messaging.subscribe(AndroidMessages.ServiceTaskMessage.class, new Messaging.Event() { @Override public void messageReceived(Message message) { // TODO end implementation of that event ServiceTaskMessage mes = (ServiceTaskMessage) message; switch (mes.action) { case Play: notification = makeNotification(); startForeground(Constants.PLAYER_NOTIFICATION_ID, notification); queue.play(); break; case Pause: queue.pause(); stopForeground(false); break; case Next: queue.next(); break; case Previous: queue.prev(); break; case addToQueue: queue.enqueue(mes.list, EnqueueMode.AfterAll); break; case setToQueue: queue.enqueue(mes.list, EnqueueMode.ReplaceAll); break; default: break; // TODO add others... } updateNotification(); } }); Log.d(Constants.LOG_TAG, "Service.onCreate()"); }
diff --git a/src/org/fao/gast/lib/EmbeddedSCLib.java b/src/org/fao/gast/lib/EmbeddedSCLib.java index ab3b13db58..146317bcc3 100644 --- a/src/org/fao/gast/lib/EmbeddedSCLib.java +++ b/src/org/fao/gast/lib/EmbeddedSCLib.java @@ -1,177 +1,180 @@ //============================================================================= //=== Copyright (C) 2001-2007 Food and Agriculture Organization of the //=== United Nations (FAO-UN), United Nations World Food Programme (WFP) //=== and United Nations Environment Programme (UNEP) //=== //=== 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 St, Fifth Floor, Boston, MA 02110-1301, USA //=== //=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, //=== Rome - Italy. email: [email protected] //============================================================================== package org.fao.gast.lib; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; //============================================================================= /** Embedde Servlet Container lib */ public class EmbeddedSCLib { //--------------------------------------------------------------------------- //--- //--- Constructor //--- //--------------------------------------------------------------------------- public EmbeddedSCLib(String appPath) throws JDOMException, IOException { this.appPath = appPath; jetty = Lib.xml.load(appPath + JETTY_FILE); webXml = Lib.xml.load(appPath + WEBXML_FILE); //--- retrieve 'host', 'port' and 'servlet' parameters from jetty for (Object call : jetty.getRootElement().getChildren("Call")) { Element elCall = (Element) call; if ("addListener".equals(elCall.getAttributeValue("name"))) { Element elNew = elCall.getChild("Arg").getChild("New"); for (Object set : elNew.getChildren("Set")) { Element elSet = (Element) set; if ("host".equals(elSet.getAttributeValue("name"))) hostElem = elSet; else if ("port".equals(elSet.getAttributeValue("name"))) portElem = elSet; } } else if ("addWebApplication".equals(elCall.getAttributeValue("name"))) - servletElem = elCall.getChild("Arg"); + { + if (servletElem == null) + servletElem = elCall.getChild("Arg"); + } } } //--------------------------------------------------------------------------- //--- //--- API methods //--- //--------------------------------------------------------------------------- public String getHost() { return (hostElem == null) ? null : hostElem.getText(); } //--------------------------------------------------------------------------- public String getPort() { return (portElem == null) ? null : portElem.getText(); } //--------------------------------------------------------------------------- public String getServlet() { //--- we have to skip the initial '/' return (servletElem == null) ? null : servletElem.getText().substring(1); } //--------------------------------------------------------------------------- public void setHost(String host) { } //--------------------------------------------------------------------------- public void setPort(String port) { if (portElem != null) portElem.setText(port); } //--------------------------------------------------------------------------- public void setServlet(String name) { if (servletElem != null) servletElem.setText("/"+name); for (Object e : webXml.getRootElement().getChildren()) { Element elem = (Element) e; if (elem.getName().equals("display-name")) { elem.setText(name); return; } } } //--------------------------------------------------------------------------- public void save() throws FileNotFoundException, IOException { Lib.xml.save(appPath + JETTY_FILE, jetty); Lib.xml.save(appPath + WEBXML_FILE, webXml); //--- create proper index.html file to point to correct servlet Map<String, String> vars = new HashMap<String, String>(); vars.put("$SERVLET", getServlet()); List<String> lines = Lib.text.load(appPath + INDEX_SRC_FILE); Lib.text.replace(lines, vars); Lib.text.save(appPath + INDEX_DES_FILE, lines); } //--------------------------------------------------------------------------- //--- //--- Variables //--- //--------------------------------------------------------------------------- private String appPath; private Document jetty; private Element hostElem; private Element portElem; private Element servletElem; private Document webXml; private static final String JETTY_FILE = "/bin/jetty.xml"; private static final String WEBXML_FILE = "/web/geonetwork/WEB-INF/web.xml"; private static final String INDEX_SRC_FILE = "/gast/data/index.html"; private static final String INDEX_DES_FILE = "/web/geonetwork/index.html"; } //=============================================================================
true
true
public EmbeddedSCLib(String appPath) throws JDOMException, IOException { this.appPath = appPath; jetty = Lib.xml.load(appPath + JETTY_FILE); webXml = Lib.xml.load(appPath + WEBXML_FILE); //--- retrieve 'host', 'port' and 'servlet' parameters from jetty for (Object call : jetty.getRootElement().getChildren("Call")) { Element elCall = (Element) call; if ("addListener".equals(elCall.getAttributeValue("name"))) { Element elNew = elCall.getChild("Arg").getChild("New"); for (Object set : elNew.getChildren("Set")) { Element elSet = (Element) set; if ("host".equals(elSet.getAttributeValue("name"))) hostElem = elSet; else if ("port".equals(elSet.getAttributeValue("name"))) portElem = elSet; } } else if ("addWebApplication".equals(elCall.getAttributeValue("name"))) servletElem = elCall.getChild("Arg"); } }
public EmbeddedSCLib(String appPath) throws JDOMException, IOException { this.appPath = appPath; jetty = Lib.xml.load(appPath + JETTY_FILE); webXml = Lib.xml.load(appPath + WEBXML_FILE); //--- retrieve 'host', 'port' and 'servlet' parameters from jetty for (Object call : jetty.getRootElement().getChildren("Call")) { Element elCall = (Element) call; if ("addListener".equals(elCall.getAttributeValue("name"))) { Element elNew = elCall.getChild("Arg").getChild("New"); for (Object set : elNew.getChildren("Set")) { Element elSet = (Element) set; if ("host".equals(elSet.getAttributeValue("name"))) hostElem = elSet; else if ("port".equals(elSet.getAttributeValue("name"))) portElem = elSet; } } else if ("addWebApplication".equals(elCall.getAttributeValue("name"))) { if (servletElem == null) servletElem = elCall.getChild("Arg"); } } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/RepositorySynchronizationManager.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/RepositorySynchronizationManager.java index 12a64b69f..ce500fd10 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/RepositorySynchronizationManager.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/RepositorySynchronizationManager.java @@ -1,522 +1,520 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 Mylar committers 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 *******************************************************************************/ package org.eclipse.mylar.tasks.ui; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.mylar.context.core.MylarStatusHandler; import org.eclipse.mylar.internal.tasks.ui.util.WebBrowserDialog; import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.RepositoryTaskAttribute; import org.eclipse.mylar.tasks.core.RepositoryTaskData; import org.eclipse.mylar.tasks.core.TaskList; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.core.UnrecognizedReponseException; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask.RepositoryTaskSyncState; import org.eclipse.ui.PlatformUI; /** * Encapsulates synchronization policy TODO: move into core? * * @author Mik Kersten * @author Rob Elves */ public class RepositorySynchronizationManager { private boolean updateLocalCopy = false; private final MutexRule taskRule = new MutexRule(); private final MutexRule queryRule = new MutexRule(); protected boolean forceSyncExecForTesting = false; /** * Synchronize a single task. Note that if you have a collection of tasks to * synchronize with this connector then you should call synchronize(Set<Set<AbstractRepositoryTask> * repositoryTasks, ...) * * @param listener * can be null */ public final Job synchronize(AbstractRepositoryConnector connector, AbstractRepositoryTask repositoryTask, boolean forceSynch, IJobChangeListener listener) { Set<AbstractRepositoryTask> toSync = new HashSet<AbstractRepositoryTask>(); toSync.add(repositoryTask); return synchronize(connector, toSync, forceSynch, listener); } /** * @param listener * can be null */ public final Job synchronize(AbstractRepositoryConnector connector, Set<AbstractRepositoryTask> repositoryTasks, boolean forceSynch, final IJobChangeListener listener) { final SynchronizeTaskJob synchronizeJob = new SynchronizeTaskJob(connector, repositoryTasks); synchronizeJob.setForceSynch(forceSynch); synchronizeJob.setPriority(Job.DECORATE); synchronizeJob.setRule(taskRule); if (listener != null) { synchronizeJob.addJobChangeListener(listener); } for (AbstractRepositoryTask repositoryTask : repositoryTasks) { repositoryTask.setCurrentlySynchronizing(true); } if (!forceSyncExecForTesting) { synchronizeJob.schedule(); } else { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { synchronizeJob.run(new NullProgressMonitor()); if (listener != null) { listener.done(null); } } }); } return synchronizeJob; } /** * For synchronizing a single query. Use synchronize(Set, * IJobChangeListener) if synchronizing multiple queries at a time. */ public final Job synchronize(AbstractRepositoryConnector connector, final AbstractRepositoryQuery repositoryQuery, IJobChangeListener listener) { HashSet<AbstractRepositoryQuery> items = new HashSet<AbstractRepositoryQuery>(); items.add(repositoryQuery); return synchronize(connector, items, listener, Job.LONG, 0, true); } public final Job synchronize(AbstractRepositoryConnector connector, final Set<AbstractRepositoryQuery> repositoryQueries, final IJobChangeListener listener, int priority, long delay, boolean syncTasks) { TaskList taskList = TasksUiPlugin.getTaskListManager().getTaskList(); final SynchronizeQueryJob job = new SynchronizeQueryJob(this, connector, repositoryQueries, taskList); job.setSynchTasks(syncTasks); for (AbstractRepositoryQuery repositoryQuery : repositoryQueries) { repositoryQuery.setCurrentlySynchronizing(true); // TasksUiPlugin.getTaskListManager().getTaskList().notifyContainerUpdated(repositoryQuery); } if (listener != null) { job.addJobChangeListener(listener); } job.setRule(queryRule); job.setPriority(priority); if (!forceSyncExecForTesting) { job.schedule(delay); } else { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { job.run(new NullProgressMonitor()); if (listener != null) { listener.done(null); } } }); } return job; } /** * Synchronizes only those tasks that have changed since the last time the * given repository was synchronized. Calls to this method update * TaskRepository.syncTime. */ public final void synchronizeChanged(final AbstractRepositoryConnector connector, final TaskRepository repository) { if (connector.getTaskDataHandler() != null) { final GetChangedTasksJob getChangedTasksJob = new GetChangedTasksJob(connector, repository); getChangedTasksJob.setSystem(true); getChangedTasksJob.setRule(new RepositoryMutexRule(repository)); if (!forceSyncExecForTesting) { getChangedTasksJob.schedule(); } else { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { getChangedTasksJob.run(new NullProgressMonitor()); } }); } } } private class GetChangedTasksJob extends Job { private AbstractRepositoryConnector connector; private TaskRepository repository; public GetChangedTasksJob(AbstractRepositoryConnector connector, TaskRepository repository) { super("Get Changed Tasks"); this.connector = connector; this.repository = repository; } @Override public IStatus run(IProgressMonitor monitor) { TaskList taskList = TasksUiPlugin.getTaskListManager().getTaskList(); Set<AbstractRepositoryTask> repositoryTasks = Collections.unmodifiableSet(taskList .getRepositoryTasks(repository.getUrl())); final Set<AbstractRepositoryTask> tasksToSync = new HashSet<AbstractRepositoryTask>(); Set<AbstractRepositoryTask> changedTasks = null; try { changedTasks = connector.getTaskDataHandler().getChangedSinceLastSync(repository, repositoryTasks); if (changedTasks != null) { for (AbstractRepositoryTask task : changedTasks) { if (task.getSyncState() == RepositoryTaskSyncState.SYNCHRONIZED || task.getSyncState() == RepositoryTaskSyncState.INCOMING) { tasksToSync.add(task); } } } if (tasksToSync.size() == 0) { return Status.OK_STATUS; } synchronize(connector, tasksToSync, false, new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (!Platform.isRunning() || TasksUiPlugin.getRepositoryManager() == null) { return; } Date mostRecent = new Date(0); String mostRecentTimeStamp = repository.getSyncTimeStamp(); for (AbstractRepositoryTask task : tasksToSync) { Date taskModifiedDate; if (connector.getTaskDataHandler() != null && task.getTaskData() != null && task.getTaskData().getLastModified() != null) { taskModifiedDate = connector.getTaskDataHandler().getDateForAttributeType( RepositoryTaskAttribute.DATE_MODIFIED, task.getTaskData().getLastModified()); } else { continue; } if (taskModifiedDate != null && taskModifiedDate.after(mostRecent)) { mostRecent = taskModifiedDate; mostRecentTimeStamp = task.getTaskData().getLastModified(); } } // TODO: Get actual time stamp of query from // repository rather // than above hack TasksUiPlugin.getRepositoryManager().setSyncTime(repository, mostRecentTimeStamp, TasksUiPlugin.getDefault().getRepositoriesFilePath()); } }); } catch (final CoreException e) { if (e.getStatus().getException() instanceof UnrecognizedReponseException) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { WebBrowserDialog.openAcceptAgreement(null, "Unrecognized response from " + repository.getUrl(), e.getStatus().getMessage(), e.getStatus().getException() .getMessage()); } }); } else { // ignore, indicates working offline // error reported in ui (tooltip and warning icon) } } catch (UnsupportedEncodingException e) { MylarStatusHandler.log(e, "Could not determine modified tasks for " + repository.getUrl() + "."); } return Status.OK_STATUS; }; }; /** * Precondition: offline file is removed upon submit to repository resulting * in a synchronized state * * @return true if call results in change of syc state */ public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getSummary() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } // NOTE: Doesn't work since we leave task in synchronized state // else if (offlineTaskData != null && // !offlineTaskData.hasLocalChanges()) { // // Case of successful task submission // status = RepositoryTaskSyncState.SYNCHRONIZED; // break; // } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, - "Local Task Conflicts with Repository", - "Local copy of: " - + repositoryTask.getSummary() - + "\n\n on: " - + repositoryTask.getRepositoryUrl() - + "\n\n has changes, override local? \n\nNOTE: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost."); + "Repository Task Conflict", + "Task: " + repositoryTask.getSummary() + + "\n\nHas been modified locally, discard local changes?" + + "\nIf you select \"No\" only the new comment will be retained."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { // bug#163850 -Make sync retrieve new data but not mark as // read // status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (offlineTaskData != null && offlineTaskData.hasLocalChanges()) { // offlineTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } else if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } if (status == RepositoryTaskSyncState.SYNCHRONIZED || repositoryTask.getLastSyncDateStamp() == null) { repositoryTask.setLastSyncDateStamp(newTaskData.getLastModified()); } } if (status == RepositoryTaskSyncState.INCOMING) { // if(offlineTaskData != null) { // markChanged(offlineTaskData, newTaskData); // } repositoryTask.setNotified(false); } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); TasksUiPlugin.getDefault().getTaskDataManager().put(newTaskData); return startState != repositoryTask.getSyncState(); } // private void markChanged(RepositoryTaskData oldData, RepositoryTaskData // newData) { // for (RepositoryTaskAttribute attribute : newData.getAttributes()) { // RepositoryTaskAttribute oldAttribute = // oldData.getAttribute(attribute.getID()); // if (!oldAttribute.getValue().equals(attribute.getValue())) { // attribute.setHasChanged(true); // continue; // } else if (!oldAttribute.getValues().equals(attribute.getValues())) { // attribute.setHasChanged(true); // continue; // } // } // } // private void clearChanged(RepositoryTaskData newData) { // for (RepositoryTaskAttribute attribute : newData.getAttributes()) { // attribute.setHasChanged(false); // } // } /** public for testing purposes */ public boolean checkHasIncoming(AbstractRepositoryTask repositoryTask, RepositoryTaskData newData) { String lastModified = repositoryTask.getLastSyncDateStamp(); if (newData != null) { RepositoryTaskData oldTaskData = repositoryTask.getTaskData(); if (oldTaskData != null) { lastModified = oldTaskData.getLastModified(); } else if (lastModified == null && repositoryTask.getSyncState() != RepositoryTaskSyncState.INCOMING) { // both lastModified and oldTaskData is null! // (don't have a sync time or any offline data) // HACK: Assume this is a query hit. // We can't get proper date stamp from query hits // so mark read doesn't set proper date stamp. // Once we have this data this should be fixed. return false; } } RepositoryTaskAttribute modifiedDateAttribute = newData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED); if (lastModified != null && modifiedDateAttribute != null && modifiedDateAttribute.getValue() != null) { if (lastModified.trim().compareTo(modifiedDateAttribute.getValue().trim()) == 0 && repositoryTask.getSyncState() != RepositoryTaskSyncState.INCOMING) { // Only set to synchronized state if not in incoming state. // Case of incoming->sync handled by markRead upon opening // or a forced synchronization on the task only. return false; } } return true; // DND - relves // RepositoryTaskAttribute modifiedDateAttribute = // newData.getAttribute(RepositoryTaskAttribute.DATE_MODIFIED); // if (repositoryTask.getLastSyncDateStamp() != null && // modifiedDateAttribute != null // && modifiedDateAttribute.getValue() != null) { // Date newModifiedDate = // connector.getOfflineTaskHandler().getDateForAttributeType( // RepositoryTaskAttribute.DATE_MODIFIED, // modifiedDateAttribute.getValue()); // Date oldModifiedDate = // connector.getOfflineTaskHandler().getDateForAttributeType( // RepositoryTaskAttribute.DATE_MODIFIED, lastModified); // if (oldModifiedDate != null && newModifiedDate != null) { // if (newModifiedDate.compareTo(oldModifiedDate) <= 0 && // repositoryTask.getSyncState() != RepositoryTaskSyncState.INCOMING) { // // Only move to synchronized state if not in incoming state. // // Case of incoming->sync handled by markRead upon opening // // or a forced synchronization on the task. // return false; // } // } // } // return true; } /** non-final for testing purposes */ protected void removeOfflineTaskData(RepositoryTaskData bug) { if (bug == null) return; ArrayList<RepositoryTaskData> bugList = new ArrayList<RepositoryTaskData>(); bugList.add(bug); TasksUiPlugin.getDefault().getTaskDataManager().remove(bugList); } /** * @param repositoryTask - * repository task to mark as read or unread * @param read - * true to mark as read, false to mark as unread */ public void setTaskRead(AbstractRepositoryTask repositoryTask, boolean read) { if (read && repositoryTask.getSyncState().equals(RepositoryTaskSyncState.INCOMING)) { if (repositoryTask.getTaskData() != null && repositoryTask.getTaskData().getLastModified() != null) { repositoryTask.setLastSyncDateStamp(repositoryTask.getTaskData().getLastModified()); // clearChanged(repositoryTask.getTaskData()); } repositoryTask.setSyncState(RepositoryTaskSyncState.SYNCHRONIZED); TasksUiPlugin.getTaskListManager().getTaskList().notifyRepositoryInfoChanged(repositoryTask); } else if (!read && repositoryTask.getSyncState().equals(RepositoryTaskSyncState.SYNCHRONIZED)) { repositoryTask.setSyncState(RepositoryTaskSyncState.INCOMING); TasksUiPlugin.getTaskListManager().getTaskList().notifyRepositoryInfoChanged(repositoryTask); } } /** * For testing */ public final void setForceSyncExec(boolean forceSyncExec) { this.forceSyncExecForTesting = forceSyncExec; } private static class MutexRule implements ISchedulingRule { public boolean isConflicting(ISchedulingRule rule) { return rule == this; } public boolean contains(ISchedulingRule rule) { return rule == this; } } private static class RepositoryMutexRule implements ISchedulingRule { private TaskRepository repository = null; public RepositoryMutexRule(TaskRepository repository) { this.repository = repository; } public boolean isConflicting(ISchedulingRule rule) { if (rule instanceof RepositoryMutexRule) { return repository.equals(((RepositoryMutexRule) rule).getRepository()); } else { return false; } } public boolean contains(ISchedulingRule rule) { return rule == this; } public TaskRepository getRepository() { return repository; } } }
true
true
public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getSummary() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } // NOTE: Doesn't work since we leave task in synchronized state // else if (offlineTaskData != null && // !offlineTaskData.hasLocalChanges()) { // // Case of successful task submission // status = RepositoryTaskSyncState.SYNCHRONIZED; // break; // } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, "Local Task Conflicts with Repository", "Local copy of: " + repositoryTask.getSummary() + "\n\n on: " + repositoryTask.getRepositoryUrl() + "\n\n has changes, override local? \n\nNOTE: if you select No, only the new comment will be saved with the updated bug, all other changes will be lost."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { // bug#163850 -Make sync retrieve new data but not mark as // read // status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (offlineTaskData != null && offlineTaskData.hasLocalChanges()) { // offlineTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } else if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } if (status == RepositoryTaskSyncState.SYNCHRONIZED || repositoryTask.getLastSyncDateStamp() == null) { repositoryTask.setLastSyncDateStamp(newTaskData.getLastModified()); } } if (status == RepositoryTaskSyncState.INCOMING) { // if(offlineTaskData != null) { // markChanged(offlineTaskData, newTaskData); // } repositoryTask.setNotified(false); } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); TasksUiPlugin.getDefault().getTaskDataManager().put(newTaskData); return startState != repositoryTask.getSyncState(); }
public synchronized boolean updateOfflineState(final AbstractRepositoryTask repositoryTask, final RepositoryTaskData newTaskData, boolean forceSync) { RepositoryTaskSyncState startState = repositoryTask.getSyncState(); RepositoryTaskSyncState status = repositoryTask.getSyncState(); if (newTaskData == null) { MylarStatusHandler.log("Download of " + repositoryTask.getSummary() + " from " + repositoryTask.getRepositoryUrl() + " failed.", this); return false; } RepositoryTaskData offlineTaskData = repositoryTask.getTaskData(); if (newTaskData.hasLocalChanges()) { // Special case for saving changes to local task data status = RepositoryTaskSyncState.OUTGOING; } else { switch (status) { case OUTGOING: if (!forceSync) { // Never overwrite local task data unless forced return false; } // NOTE: Doesn't work since we leave task in synchronized state // else if (offlineTaskData != null && // !offlineTaskData.hasLocalChanges()) { // // Case of successful task submission // status = RepositoryTaskSyncState.SYNCHRONIZED; // break; // } case CONFLICT: // use a parameter rather than this null check if (offlineTaskData != null) { // TODO: pull this ui out of here if (!forceSyncExecForTesting) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { public void run() { updateLocalCopy = MessageDialog .openQuestion( null, "Repository Task Conflict", "Task: " + repositoryTask.getSummary() + "\n\nHas been modified locally, discard local changes?" + "\nIf you select \"No\" only the new comment will be retained."); } }); } else { updateLocalCopy = true; } if (!updateLocalCopy) { newTaskData.setNewComment(offlineTaskData.getNewComment()); newTaskData.setHasLocalChanges(true); status = RepositoryTaskSyncState.CONFLICT; } else { newTaskData.setHasLocalChanges(false); if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } } } else { newTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case INCOMING: if (!forceSync && checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { // bug#163850 -Make sync retrieve new data but not mark as // read // status = RepositoryTaskSyncState.SYNCHRONIZED; } break; case SYNCHRONIZED: if (offlineTaskData != null && offlineTaskData.hasLocalChanges()) { // offlineTaskData.setHasLocalChanges(false); status = RepositoryTaskSyncState.SYNCHRONIZED; } else if (checkHasIncoming(repositoryTask, newTaskData)) { status = RepositoryTaskSyncState.INCOMING; } else { status = RepositoryTaskSyncState.SYNCHRONIZED; } break; } if (status == RepositoryTaskSyncState.SYNCHRONIZED || repositoryTask.getLastSyncDateStamp() == null) { repositoryTask.setLastSyncDateStamp(newTaskData.getLastModified()); } } if (status == RepositoryTaskSyncState.INCOMING) { // if(offlineTaskData != null) { // markChanged(offlineTaskData, newTaskData); // } repositoryTask.setNotified(false); } repositoryTask.setTaskData(newTaskData); repositoryTask.setSyncState(status); TasksUiPlugin.getDefault().getTaskDataManager().put(newTaskData); return startState != repositoryTask.getSyncState(); }
diff --git a/src/com/android/browser/BrowserActivity.java b/src/com/android/browser/BrowserActivity.java index 65b7911e..59378810 100644 --- a/src/com/android/browser/BrowserActivity.java +++ b/src/com/android/browser/BrowserActivity.java @@ -1,4650 +1,4648 @@ /* * Copyright (C) 2006 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.browser; import com.google.android.googleapps.IGoogleLoginService; import com.google.android.googlelogin.GoogleLoginServiceConstants; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.DialogInterface.OnCancelListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.DrawFilter; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.Picture; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.WebAddress; import android.net.http.EventHandler; import android.net.http.SslCertificate; import android.net.http.SslError; import android.os.AsyncTask; import android.os.Bundle; import android.os.Debug; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.provider.Browser; import android.provider.ContactsContract; import android.provider.ContactsContract.Intents.Insert; import android.provider.Downloads; import android.provider.MediaStore; import android.text.IClipboard; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.util.Regex; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem.OnMenuItemClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.DownloadListener; import android.webkit.GeolocationPermissions; import android.webkit.HttpAuthHandler; import android.webkit.PluginManager; import android.webkit.SslErrorHandler; import android.webkit.URLUtil; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebChromeClient.CustomViewCallback; import android.webkit.WebHistoryItem; import android.webkit.WebIconDatabase; import android.webkit.WebStorage; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class BrowserActivity extends Activity implements View.OnCreateContextMenuListener, DownloadListener { /* Define some aliases to make these debugging flags easier to refer to. * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG". */ private final static boolean DEBUG = com.android.browser.Browser.DEBUG; private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED; private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; private IGoogleLoginService mGls = null; private ServiceConnection mGlsConnection = null; private SensorManager mSensorManager = null; // These are single-character shortcuts for searching popular sources. private static final int SHORTCUT_INVALID = 0; private static final int SHORTCUT_GOOGLE_SEARCH = 1; private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2; private static final int SHORTCUT_DICTIONARY_SEARCH = 3; private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4; /* Whitelisted webpages private static HashSet<String> sWhiteList; static { sWhiteList = new HashSet<String>(); sWhiteList.add("cnn.com/"); sWhiteList.add("espn.go.com/"); sWhiteList.add("nytimes.com/"); sWhiteList.add("engadget.com/"); sWhiteList.add("yahoo.com/"); sWhiteList.add("msn.com/"); sWhiteList.add("amazon.com/"); sWhiteList.add("consumerist.com/"); sWhiteList.add("google.com/m/news"); } */ private void setupHomePage() { final Runnable getAccount = new Runnable() { public void run() { // Lower priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // get the default home page String homepage = mSettings.getHomePage(); try { if (mGls == null) return; if (!homepage.startsWith("http://www.google.")) return; if (homepage.indexOf('?') == -1) return; String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED); String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE); // three cases: // // hostedUser == googleUser // The device has only a google account // // hostedUser != googleUser // The device has a hosted account and a google account // // hostedUser != null, googleUser == null // The device has only a hosted account (so far) // developers might have no accounts at all if (hostedUser == null) return; if (googleUser == null || !hostedUser.equals(googleUser)) { String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1); homepage = homepage.replace("?", "/a/" + domain + "?"); } } catch (RemoteException ignore) { // Login service died; carry on } catch (RuntimeException ignore) { // Login service died; carry on } finally { finish(homepage); } } private void finish(final String homepage) { mHandler.post(new Runnable() { public void run() { mSettings.setHomePage(BrowserActivity.this, homepage); resumeAfterCredentials(); // as this is running in a separate thread, // BrowserActivity's onDestroy() may have been called, // which also calls unbindService(). if (mGlsConnection != null) { // we no longer need to keep GLS open unbindService(mGlsConnection); mGlsConnection = null; } } }); } }; final boolean[] done = { false }; // Open a connection to the Google Login Service. The first // time the connection is established, set up the homepage depending on // the account in a background thread. mGlsConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mGls = IGoogleLoginService.Stub.asInterface(service); if (done[0] == false) { done[0] = true; Thread account = new Thread(getAccount); account.setName("GLSAccount"); account.start(); } } public void onServiceDisconnected(ComponentName className) { mGls = null; } }; bindService(GoogleLoginServiceConstants.SERVICE_INTENT, mGlsConnection, Context.BIND_AUTO_CREATE); } private static class ClearThumbnails extends AsyncTask<File, Void, Void> { @Override public Void doInBackground(File... files) { if (files != null) { for (File f : files) { if (!f.delete()) { Log.e(LOGTAG, f.getPath() + " was not deleted"); } } } return null; } } /** * This layout holds everything you see below the status bar, including the * error console, the custom view container, and the webviews. */ private FrameLayout mBrowserFrameLayout; @Override public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } // // start MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //startService(proxyServiceIntent, null); mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { - NetworkInfo info = - (NetworkInfo) intent.getParcelableExtra( - ConnectivityManager.EXTRA_NETWORK_INFO); - onNetworkToggle( - (info != null) ? info.isConnected() : false); + boolean noConnectivity = intent.getBooleanExtra( + ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + onNetworkToggle(!noConnectivity); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final TabControl.Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } } @Override protected void onNewIntent(Intent intent) { TabControl.Tab current = mTabControl.getCurrentTab(); // When a tab is closed on exit, the current tab index is set to -1. // Reset before proceed as Browser requires the current tab to be set. if (current == null) { // Try to reset the tab in case the index was incorrect. current = mTabControl.getTab(0); if (current == null) { // No tabs at all so just ignore this intent. return; } mTabControl.setCurrentTab(current); attachTabToContentView(current); resetTitleAndIcon(current.getWebView()); } final String action = intent.getAction(); final int flags = intent.getFlags(); if (Intent.ACTION_MAIN.equals(action) || (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { // just resume the browser return; } if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { // If this was a search request (e.g. search query directly typed into the address bar), // pass it on to the default web search provider. if (handleWebSearchIntent(intent)) { return; } UrlData urlData = getUrlDataFromIntent(intent); if (urlData.isEmpty()) { urlData = new UrlData(mSettings.getHomePage()); } urlData.setPostData(intent .getByteArrayExtra(Browser.EXTRA_POST_DATA)); final String appId = intent .getStringExtra(Browser.EXTRA_APPLICATION_ID); if (Intent.ACTION_VIEW.equals(action) && !getPackageName().equals(appId) && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { TabControl.Tab appTab = mTabControl.getTabFromId(appId); if (appTab != null) { Log.i(LOGTAG, "Reusing tab for " + appId); // Dismiss the subwindow if applicable. dismissSubWindow(appTab); // Since we might kill the WebView, remove it from the // content view first. removeTabFromContentView(appTab); // Recreate the main WebView after destroying the old one. // If the WebView has the same original url and is on that // page, it can be reused. boolean needsLoad = mTabControl.recreateWebView(appTab, urlData.mUrl); if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } else { // If the tab was the current tab, we have to attach // it to the view system again. attachTabToContentView(appTab); if (needsLoad) { urlData.loadIn(appTab.getWebView()); } } return; } else { // No matching application tab, try to find a regular tab // with a matching url. appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl); if (appTab != null) { if (current != appTab) { switchToTab(mTabControl.getTabIndex(appTab)); } // Otherwise, we are already viewing the correct tab. } else { // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url // will be opened in a new tab unless we have reached // MAX_TABS. Then the url will be opened in the current // tab. If a new tab is created, it will have "true" for // exit on close. openTabAndShow(urlData, true, appId); } } } else { if ("about:debug".equals(urlData.mUrl)) { mSettings.toggleDebugSettings(); return; } // Get rid of the subwindow if it exists dismissSubWindow(current); urlData.loadIn(current.getWebView()); } } } private int parseUrlShortcut(String url) { if (url == null) return SHORTCUT_INVALID; // FIXME: quick search, need to be customized by setting if (url.length() > 2 && url.charAt(1) == ' ') { switch (url.charAt(0)) { case 'g': return SHORTCUT_GOOGLE_SEARCH; case 'w': return SHORTCUT_WIKIPEDIA_SEARCH; case 'd': return SHORTCUT_DICTIONARY_SEARCH; case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH; } } return SHORTCUT_INVALID; } /** * Launches the default web search activity with the query parameters if the given intent's data * are identified as plain search terms and not URLs/shortcuts. * @return true if the intent was handled and web search activity was launched, false if not. */ private boolean handleWebSearchIntent(Intent intent) { if (intent == null) return false; String url = null; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { Uri data = intent.getData(); if (data != null) url = data.toString(); } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); } return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA), intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } /** * Launches the default web search activity with the query parameters if the given url string * was identified as plain search terms and not URL/shortcut. * @return true if the request was handled and web search activity was launched, false if not. */ private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) { if (inUrl == null) return false; // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. String url = fixUrl(inUrl).trim(); // URLs and site specific search shortcuts are handled by the regular flow of control, so // return early. if (Regex.WEB_URL_PATTERN.matcher(url).matches() || ACCEPTED_URI_SCHEMA.matcher(url).matches() || parseUrlShortcut(url) != SHORTCUT_INVALID) { return false; } Browser.updateVisitedHistory(mResolver, url, false); Browser.addSearchUrl(mResolver, url); Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(SearchManager.QUERY, url); if (appData != null) { intent.putExtra(SearchManager.APP_DATA, appData); } if (extraData != null) { intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); } intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName()); startActivity(intent); return true; } private UrlData getUrlDataFromIntent(Intent intent) { String url = null; if (intent != null) { final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action)) { url = smartUrlFilter(intent.getData()); if (url != null && url.startsWith("content:")) { /* Append mimetype so webview knows how to display */ String mimeType = intent.resolveType(getContentResolver()); if (mimeType != null) { url += "?" + mimeType; } } if ("inline:".equals(url)) { return new InlinedUrlData( intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT), intent.getType(), intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING), intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL)); } } else if (Intent.ACTION_SEARCH.equals(action) || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) || Intent.ACTION_WEB_SEARCH.equals(action)) { url = intent.getStringExtra(SearchManager.QUERY); if (url != null) { mLastEnteredUrl = url; // Don't add Urls, just search terms. // Urls will get added when the page is loaded. if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) { Browser.updateVisitedHistory(mResolver, url, false); } // In general, we shouldn't modify URL from Intent. // But currently, we get the user-typed URL from search box as well. url = fixUrl(url); url = smartUrlFilter(url); String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; if (url.contains(searchSource)) { String source = null; final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { source = appData.getString(SearchManager.SOURCE); } if (TextUtils.isEmpty(source)) { source = GOOGLE_SEARCH_SOURCE_UNKNOWN; } url = url.replace(searchSource, "&source=android-"+source+"&"); } } } } return new UrlData(url); } /* package */ static String fixUrl(String inUrl) { // FIXME: Converting the url to lower case // duplicates functionality in smartUrlFilter(). // However, changing all current callers of fixUrl to // call smartUrlFilter in addition may have unwanted // consequences, and is deferred for now. int colon = inUrl.indexOf(':'); boolean allLower = true; for (int index = 0; index < colon; index++) { char ch = inUrl.charAt(index); if (!Character.isLetter(ch)) { break; } allLower &= Character.isLowerCase(ch); if (index == colon - 1 && !allLower) { inUrl = inUrl.substring(0, colon).toLowerCase() + inUrl.substring(colon); } } if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) return inUrl; if (inUrl.startsWith("http:") || inUrl.startsWith("https:")) { if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { inUrl = inUrl.replaceFirst("/", "//"); } else inUrl = inUrl.replaceFirst(":", "://"); } return inUrl; } /** * Looking for the pattern like this * * * * * * * *** * ******* * * * * * * * * */ private final SensorListener mSensorListener = new SensorListener() { private long mLastGestureTime; private float[] mPrev = new float[3]; private float[] mPrevDiff = new float[3]; private float[] mDiff = new float[3]; private float[] mRevertDiff = new float[3]; public void onSensorChanged(int sensor, float[] values) { boolean show = false; float[] diff = new float[3]; for (int i = 0; i < 3; i++) { diff[i] = values[i] - mPrev[i]; if (Math.abs(diff[i]) > 1) { show = true; } if ((diff[i] > 1.0 && mDiff[i] < 0.2) || (diff[i] < -1.0 && mDiff[i] > -0.2)) { // start track when there is a big move, or revert mRevertDiff[i] = mDiff[i]; mDiff[i] = 0; } else if (diff[i] > -0.2 && diff[i] < 0.2) { // reset when it is flat mDiff[i] = mRevertDiff[i] = 0; } mDiff[i] += diff[i]; mPrevDiff[i] = diff[i]; mPrev[i] = values[i]; } if (false) { // only shows if we think the delta is big enough, in an attempt // to detect "serious" moves left/right or up/down Log.d("BrowserSensorHack", "sensorChanged " + sensor + " (" + values[0] + ", " + values[1] + ", " + values[2] + ")" + " diff(" + diff[0] + " " + diff[1] + " " + diff[2] + ")"); Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " " + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff(" + mRevertDiff[0] + " " + mRevertDiff[1] + " " + mRevertDiff[2] + ")"); } long now = android.os.SystemClock.uptimeMillis(); if (now - mLastGestureTime > 1000) { mLastGestureTime = 0; float y = mDiff[1]; float z = mDiff[2]; float ay = Math.abs(y); float az = Math.abs(z); float ry = mRevertDiff[1]; float rz = mRevertDiff[2]; float ary = Math.abs(ry); float arz = Math.abs(rz); boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary; boolean gestZ = az > 3.5f && arz > 1.0f && az > arz; if ((gestY || gestZ) && !(gestY && gestZ)) { WebView view = mTabControl.getCurrentWebView(); if (view != null) { if (gestZ) { if (z < 0) { view.zoomOut(); } else { view.zoomIn(); } } else { view.flingScroll(0, Math.round(y * 100)); } } mLastGestureTime = now; } } } public void onAccuracyChanged(int sensor, int accuracy) { // TODO Auto-generated method stub } }; @Override protected void onResume() { super.onResume(); if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this); } if (!mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already resumed."); return; } mTabControl.resumeCurrentTab(); mActivityInPause = false; resumeWebViewTimers(); if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } if (mCredsDlg != null) { if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) { // In case credential request never comes back mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000); } } registerReceiver(mNetworkStateIntentReceiver, mNetworkStateChangedFilter); WebView.enablePlatformNotifications(); if (mSettings.doFlick()) { if (mSensorManager == null) { mSensorManager = (SensorManager) getSystemService( Context.SENSOR_SERVICE); } mSensorManager.registerListener(mSensorListener, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_FASTEST); } else { mSensorManager = null; } } /** * Since the actual title bar is embedded in the WebView, and removing it * would change its appearance, create a temporary title bar to go at * the top of the screen while the menu is open. */ private TitleBar mFakeTitleBar; /** * Holder for the fake title bar. It will have a foreground shadow, as well * as a white background, so the fake title bar looks like the real one. */ private ViewGroup mFakeTitleBarHolder; /** * Layout parameters for the fake title bar within mFakeTitleBarHolder */ private FrameLayout.LayoutParams mFakeTitleBarParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); /** * Keeps track of whether the options menu is open. This is important in * determining whether to show or hide the title bar overlay. */ private boolean mOptionsMenuOpen; /** * Only meaningful when mOptionsMenuOpen is true. This variable keeps track * of whether the configuration has changed. The first onMenuOpened call * after a configuration change is simply a reopening of the same menu * (i.e. mIconView did not change). */ private boolean mConfigChanged; /** * Whether or not the options menu is in its smaller, icon menu form. When * true, we want the title bar overlay to be up. When false, we do not. * Only meaningful if mOptionsMenuOpen is true. */ private boolean mIconView; @Override public boolean onMenuOpened(int featureId, Menu menu) { if (Window.FEATURE_OPTIONS_PANEL == featureId) { if (mOptionsMenuOpen) { if (mConfigChanged) { // We do not need to make any changes to the state of the // title bar, since the only thing that happened was a // change in orientation mConfigChanged = false; } else { if (mIconView) { // Switching the menu to expanded view, so hide the // title bar. hideFakeTitleBar(); mIconView = false; } else { // Switching the menu back to icon view, so show the // title bar once again. showFakeTitleBar(); mIconView = true; } } } else { // The options menu is closed, so open it, and show the title showFakeTitleBar(); mOptionsMenuOpen = true; mConfigChanged = false; mIconView = true; } } return true; } /** * Special class used exclusively for the shadow drawn underneath the fake * title bar. The shadow does not need to be drawn if the WebView * underneath is scrolled to the top, because it will draw directly on top * of the embedded shadow. */ private static class Shadow extends View { private WebView mWebView; public Shadow(Context context, AttributeSet attrs) { super(context, attrs); } public void setWebView(WebView view) { mWebView = view; } @Override public void draw(Canvas canvas) { // In general onDraw is the method to override, but we care about // whether or not the background gets drawn, which happens in draw() if (mWebView == null || mWebView.getScrollY() > getHeight()) { super.draw(canvas); } // Need to invalidate so that if the scroll position changes, we // still draw as appropriate. invalidate(); } } private void showFakeTitleBar() { final View decor = getWindow().peekDecorView(); if (mFakeTitleBar == null && mActiveTabsPage == null && !mActivityInPause && decor != null && decor.getWindowToken() != null) { Rect visRect = new Rect(); if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) { if (LOGD_ENABLED) { Log.d(LOGTAG, "showFakeTitleBar visRect failed"); } return; } final WebView webView = getTopWindow(); mFakeTitleBar = new TitleBar(this); mFakeTitleBar.setTitleAndUrl(null, webView.getUrl()); mFakeTitleBar.setProgress(webView.getProgress()); mFakeTitleBar.setFavicon(webView.getFavicon()); updateLockIconToLatest(); WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); // Add the title bar to the window manager so it can receive touches // while the menu is up WindowManager.LayoutParams params = new WindowManager.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP; WebView mainView = mTabControl.getCurrentWebView(); boolean atTop = mainView != null && mainView.getScrollY() == 0; params.windowAnimations = atTop ? 0 : R.style.TitleBar; // XXX : Without providing an offset, the fake title bar will be // placed underneath the status bar. Use the global visible rect // of mBrowserFrameLayout to determine the bottom of the status bar params.y = visRect.top; // Add a holder for the title bar. It also holds a shadow to show // below the title bar. if (mFakeTitleBarHolder == null) { mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this) .inflate(R.layout.title_bar_bg, null); } Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById( R.id.shadow); shadow.setWebView(mainView); mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams); manager.addView(mFakeTitleBarHolder, params); } } @Override public void onOptionsMenuClosed(Menu menu) { mOptionsMenuOpen = false; if (!mInLoad) { hideFakeTitleBar(); } else if (!mIconView) { // The page is currently loading, and we are in expanded mode, so // we were not showing the menu. Show it once again. It will be // removed when the page finishes. showFakeTitleBar(); } } private void hideFakeTitleBar() { if (mFakeTitleBar == null) return; WindowManager.LayoutParams params = (WindowManager.LayoutParams) mFakeTitleBarHolder.getLayoutParams(); WebView mainView = mTabControl.getCurrentWebView(); // Although we decided whether or not to animate based on the current // scroll position, the scroll position may have changed since the // fake title bar was displayed. Make sure it has the appropriate // animation/lack thereof before removing. params.windowAnimations = mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar; WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); manager.updateViewLayout(mFakeTitleBarHolder, params); mFakeTitleBarHolder.removeView(mFakeTitleBar); manager.removeView(mFakeTitleBarHolder); mFakeTitleBar = null; } /** * Special method for the fake title bar to call when displaying its context * menu, since it is in its own Window, and its parent does not show a * context menu. */ /* package */ void showTitleBarContextMenu() { if (null == mTitleBar.getParent()) { return; } openContextMenu(mTitleBar); } /** * onSaveInstanceState(Bundle map) * onSaveInstanceState is called right before onStop(). The map contains * the saved state. */ @Override protected void onSaveInstanceState(Bundle outState) { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this); } // the default implementation requires each view to have an id. As the // browser handles the state itself and it doesn't use id for the views, // don't call the default implementation. Otherwise it will trigger the // warning like this, "couldn't save which view has focus because the // focused view XXX has no id". // Save all the tabs mTabControl.saveState(outState); } @Override protected void onPause() { super.onPause(); if (mActivityInPause) { Log.e(LOGTAG, "BrowserActivity is already paused."); return; } mTabControl.pauseCurrentTab(); mActivityInPause = true; if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) { mWakeLock.acquire(); mHandler.sendMessageDelayed(mHandler .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); } // Clear the credentials toast if it is up if (mCredsDlg != null && mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // FIXME: This removes the active tabs page and resets the menu to // MAIN_MENU. A better solution might be to do this work in onNewIntent // but then we would need to save it in onSaveInstanceState and restore // it in onCreate/onRestoreInstanceState if (mActiveTabsPage != null) { removeActiveTabPage(true); } cancelStopToast(); // unregister network state listener unregisterReceiver(mNetworkStateIntentReceiver); WebView.disablePlatformNotifications(); if (mSensorManager != null) { mSensorManager.unregisterListener(mSensorListener); } } @Override protected void onDestroy() { if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this); } super.onDestroy(); if (mTabControl == null) return; // Remove the current tab and sub window TabControl.Tab t = mTabControl.getCurrentTab(); if (t != null) { dismissSubWindow(t); removeTabFromContentView(t); } // Destroy all the tabs mTabControl.destroy(); WebIconDatabase.getInstance().close(); if (mGlsConnection != null) { unbindService(mGlsConnection); mGlsConnection = null; } // // stop MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //stopService(proxyServiceIntent); unregisterReceiver(mPackageInstallationReceiver); } @Override public void onConfigurationChanged(Configuration newConfig) { mConfigChanged = true; super.onConfigurationChanged(newConfig); if (mPageInfoDialog != null) { mPageInfoDialog.dismiss(); showPageInfo( mPageInfoView, mPageInfoFromShowSSLCertificateOnError.booleanValue()); } if (mSSLCertificateDialog != null) { mSSLCertificateDialog.dismiss(); showSSLCertificate( mSSLCertificateView); } if (mSSLCertificateOnErrorDialog != null) { mSSLCertificateOnErrorDialog.dismiss(); showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } if (mHttpAuthenticationDialog != null) { String title = ((TextView) mHttpAuthenticationDialog .findViewById(com.android.internal.R.id.alertTitle)).getText() .toString(); String name = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.username_edit)).getText().toString(); String password = ((TextView) mHttpAuthenticationDialog .findViewById(R.id.password_edit)).getText().toString(); int focusId = mHttpAuthenticationDialog.getCurrentFocus() .getId(); mHttpAuthenticationDialog.dismiss(); showHttpAuthentication(mHttpAuthHandler, null, null, title, name, password, focusId); } if (mFindDialog != null && mFindDialog.isShowing()) { mFindDialog.onConfigurationChanged(newConfig); } } @Override public void onLowMemory() { super.onLowMemory(); mTabControl.freeMemory(); } private boolean resumeWebViewTimers() { if ((!mActivityInPause && !mPageStarted) || (mActivityInPause && mPageStarted)) { CookieSyncManager.getInstance().startSync(); WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.resumeTimers(); } return true; } else { return false; } } private boolean pauseWebViewTimers() { if (mActivityInPause && !mPageStarted) { CookieSyncManager.getInstance().stopSync(); WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.pauseTimers(); } return true; } else { return false; } } // FIXME: Do we want to call this when loading google for the first time? /* * This function is called when we are launching for the first time. We * are waiting for the login credentials before loading Google home * pages. This way the user will be logged in straight away. */ private void waitForCredentials() { // Show a toast mCredsDlg = new ProgressDialog(this); mCredsDlg.setIndeterminate(true); mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg)); // If the user cancels the operation, then cancel the Google // Credentials request. mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST)); mCredsDlg.show(); // We set a timeout for the retrieval of credentials in onResume() // as that is when we have freed up some CPU time to get // the login credentials. } /* * If we have received the credentials or we have timed out and we are * showing the credentials dialog, then it is time to move on. */ private void resumeAfterCredentials() { if (mCredsDlg == null) { return; } // Clear the toast if (mCredsDlg.isShowing()) { mCredsDlg.dismiss(); } mCredsDlg = null; // Clear any pending timeout mHandler.removeMessages(CANCEL_CREDS_REQUEST); // Load the page WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.loadUrl(mSettings.getHomePage()); } // Update the settings, need to do this last as it can take a moment // to persist the settings. In the mean time we could be loading // content. mSettings.setLoginInitialized(this); } // Open the icon database and retain all the icons for visited sites. private void retainIconsOnStartup() { final WebIconDatabase db = WebIconDatabase.getInstance(); db.open(getDir("icons", 0).getPath()); try { Cursor c = Browser.getAllBookmarks(mResolver); if (!c.moveToFirst()) { c.deactivate(); return; } int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); do { String url = c.getString(urlIndex); db.retainIconForPageUrl(url); } while (c.moveToNext()); c.deactivate(); } catch (IllegalStateException e) { Log.e(LOGTAG, "retainIconsOnStartup", e); } } // Helper method for getting the top window. WebView getTopWindow() { return mTabControl.getCurrentTopWebView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browser, menu); mMenu = menu; updateInLoadMenuItems(); return true; } /** * As the menu can be open when loading state changes * we must manually update the state of the stop/reload menu * item */ private void updateInLoadMenuItems() { if (mMenu == null) { return; } MenuItem src = mInLoad ? mMenu.findItem(R.id.stop_menu_id): mMenu.findItem(R.id.reload_menu_id); MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id); dest.setIcon(src.getIcon()); dest.setTitle(src.getTitle()); } @Override public boolean onContextItemSelected(MenuItem item) { // chording is not an issue with context menus, but we use the same // options selector, so set mCanChord to true so we can access them. mCanChord = true; int id = item.getItemId(); switch (id) { // For the context menu from the title bar case R.id.title_bar_share_page_url: case R.id.title_bar_copy_page_url: WebView mainView = mTabControl.getCurrentWebView(); if (null == mainView) { return false; } if (id == R.id.title_bar_share_page_url) { Browser.sendString(this, mainView.getUrl()); } else { copy(mainView.getUrl()); } break; // -- Browser context menu case R.id.open_context_menu_id: case R.id.open_newtab_context_menu_id: case R.id.bookmark_context_menu_id: case R.id.save_link_context_menu_id: case R.id.share_link_context_menu_id: case R.id.copy_link_context_menu_id: final WebView webView = getTopWindow(); if (null == webView) { return false; } final HashMap hrefMap = new HashMap(); hrefMap.put("webview", webView); final Message msg = mHandler.obtainMessage( FOCUS_NODE_HREF, id, 0, hrefMap); webView.requestFocusNodeHref(msg); break; default: // For other context menus return onOptionsItemSelected(item); } mCanChord = false; return true; } private Bundle createGoogleSearchSourceBundle(String source) { Bundle bundle = new Bundle(); bundle.putString(SearchManager.SOURCE, source); return bundle; } /** * Overriding this to insert a local information bundle */ @Override public boolean onSearchRequested() { if (mOptionsMenuOpen) closeOptionsMenu(); String url = (getTopWindow() == null) ? null : getTopWindow().getUrl(); startSearch(mSettings.getHomePage().equals(url) ? null : url, true, createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false); return true; } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (appSearchData == null) { appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE); } super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); } /** * Switch tabs. Called by the TitleBarSet when sliding the title bar * results in changing tabs. * @param index Index of the tab to change to, as defined by * mTabControl.getTabIndex(Tab t). * @return boolean True if we successfully switched to a different tab. If * the indexth tab is null, or if that tab is the same as * the current one, return false. */ /* package */ boolean switchToTab(int index) { TabControl.Tab tab = mTabControl.getTab(index); TabControl.Tab currentTab = mTabControl.getCurrentTab(); if (tab == null || tab == currentTab) { return false; } if (currentTab != null) { // currentTab may be null if it was just removed. In that case, // we do not need to remove it removeTabFromContentView(currentTab); } mTabControl.setCurrentTab(tab); attachTabToContentView(tab); resetTitleIconAndProgress(); updateLockIconToLatest(); return true; } /* package */ TabControl.Tab openTabToHomePage() { return openTabAndShow(mSettings.getHomePage(), false, null); } /* package */ void closeCurrentWindow() { final TabControl.Tab current = mTabControl.getCurrentTab(); if (mTabControl.getTabCount() == 1) { // This is the last tab. Open a new one, with the home // page and close the current one. TabControl.Tab newTab = openTabToHomePage(); closeTab(current); return; } final TabControl.Tab parent = current.getParentTab(); int indexToShow = -1; if (parent != null) { indexToShow = mTabControl.getTabIndex(parent); } else { final int currentIndex = mTabControl.getCurrentIndex(); // Try to move to the tab to the right indexToShow = currentIndex + 1; if (indexToShow > mTabControl.getTabCount() - 1) { // Try to move to the tab to the left indexToShow = currentIndex - 1; } } if (switchToTab(indexToShow)) { // Close window closeTab(current); } } private ActiveTabsPage mActiveTabsPage; /** * Remove the active tabs page. * @param needToAttach If true, the active tabs page did not attach a tab * to the content view, so we need to do that here. */ /* package */ void removeActiveTabPage(boolean needToAttach) { mContentView.removeView(mActiveTabsPage); mActiveTabsPage = null; mMenuState = R.id.MAIN_MENU; if (needToAttach) { attachTabToContentView(mTabControl.getCurrentTab()); } getTopWindow().requestFocus(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!mCanChord) { // The user has already fired a shortcut with this hold down of the // menu key. return false; } if (null == getTopWindow()) { return false; } if (mMenuIsDown) { // The shortcut action consumes the MENU. Even if it is still down, // it won't trigger the next shortcut action. In the case of the // shortcut action triggering a new activity, like Bookmarks, we // won't get onKeyUp for MENU. So it is important to reset it here. mMenuIsDown = false; } switch (item.getItemId()) { // -- Main menu case R.id.new_tab_menu_id: openTabToHomePage(); break; case R.id.goto_menu_id: onSearchRequested(); break; case R.id.bookmarks_menu_id: bookmarksOrHistoryPicker(false); break; case R.id.active_tabs_menu_id: mActiveTabsPage = new ActiveTabsPage(this, mTabControl); removeTabFromContentView(mTabControl.getCurrentTab()); hideFakeTitleBar(); mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS); mActiveTabsPage.requestFocus(); mMenuState = EMPTY_MENU; break; case R.id.add_bookmark_menu_id: Intent i = new Intent(BrowserActivity.this, AddBookmarkPage.class); WebView w = getTopWindow(); i.putExtra("url", w.getUrl()); i.putExtra("title", w.getTitle()); i.putExtra("touch_icon_url", w.getTouchIconUrl()); i.putExtra("thumbnail", createScreenshot(w)); startActivity(i); break; case R.id.stop_reload_menu_id: if (mInLoad) { stopLoading(); } else { getTopWindow().reload(); } break; case R.id.back_menu_id: getTopWindow().goBack(); break; case R.id.forward_menu_id: getTopWindow().goForward(); break; case R.id.close_menu_id: // Close the subwindow if it exists. if (mTabControl.getCurrentSubWindow() != null) { dismissSubWindow(mTabControl.getCurrentTab()); break; } closeCurrentWindow(); break; case R.id.homepage_menu_id: TabControl.Tab current = mTabControl.getCurrentTab(); if (current != null) { dismissSubWindow(current); current.getWebView().loadUrl(mSettings.getHomePage()); } break; case R.id.preferences_menu_id: Intent intent = new Intent(this, BrowserPreferencesPage.class); startActivityForResult(intent, PREFERENCES_PAGE); break; case R.id.find_menu_id: if (null == mFindDialog) { mFindDialog = new FindDialog(this); } mFindDialog.setWebView(getTopWindow()); mFindDialog.show(); mMenuState = EMPTY_MENU; break; case R.id.select_text_id: getTopWindow().emulateShiftHeld(); break; case R.id.page_info_menu_id: showPageInfo(mTabControl.getCurrentTab(), false); break; case R.id.classic_history_menu_id: bookmarksOrHistoryPicker(true); break; case R.id.share_page_menu_id: Browser.sendString(this, getTopWindow().getUrl(), getText(R.string.choosertitle_sharevia).toString()); break; case R.id.dump_nav_menu_id: getTopWindow().debugDump(); break; case R.id.zoom_in_menu_id: getTopWindow().zoomIn(); break; case R.id.zoom_out_menu_id: getTopWindow().zoomOut(); break; case R.id.view_downloads_menu_id: viewDownloads(null); break; case R.id.window_one_menu_id: case R.id.window_two_menu_id: case R.id.window_three_menu_id: case R.id.window_four_menu_id: case R.id.window_five_menu_id: case R.id.window_six_menu_id: case R.id.window_seven_menu_id: case R.id.window_eight_menu_id: { int menuid = item.getItemId(); for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { TabControl.Tab desiredTab = mTabControl.getTab(id); if (desiredTab != null && desiredTab != mTabControl.getCurrentTab()) { switchToTab(id); } break; } } } break; default: if (!super.onOptionsItemSelected(item)) { return false; } // Otherwise fall through. } mCanChord = false; return true; } public void closeFind() { mMenuState = R.id.MAIN_MENU; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // This happens when the user begins to hold down the menu key, so // allow them to chord to get a shortcut. mCanChord = true; // Note: setVisible will decide whether an item is visible; while // setEnabled() will decide whether an item is enabled, which also means // whether the matching shortcut key will function. super.onPrepareOptionsMenu(menu); switch (mMenuState) { case EMPTY_MENU: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_MENU, false); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); } break; default: if (mCurrentMenuState != mMenuState) { menu.setGroupVisible(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_MENU, true); menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); } final WebView w = getTopWindow(); boolean canGoBack = false; boolean canGoForward = false; boolean isHome = false; if (w != null) { canGoBack = w.canGoBack(); canGoForward = w.canGoForward(); isHome = mSettings.getHomePage().equals(w.getUrl()); } final MenuItem back = menu.findItem(R.id.back_menu_id); back.setEnabled(canGoBack); final MenuItem home = menu.findItem(R.id.homepage_menu_id); home.setEnabled(!isHome); menu.findItem(R.id.forward_menu_id) .setEnabled(canGoForward); menu.findItem(R.id.new_tab_menu_id).setEnabled( mTabControl.getTabCount() < TabControl.MAX_TABS); // decide whether to show the share link option PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); boolean isNavDump = mSettings.isNavDump(); final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); nav.setVisible(isNavDump); nav.setEnabled(isNavDump); break; } mCurrentMenuState = mMenuState; return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { WebView webview = (WebView) v; WebView.HitTestResult result = webview.getHitTestResult(); if (result == null) { return; } int type = result.getType(); if (type == WebView.HitTestResult.UNKNOWN_TYPE) { Log.w(LOGTAG, "We should not show context menu when nothing is touched"); return; } if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { // let TextView handles context menu return; } // Note, http://b/issue?id=1106666 is requesting that // an inflated menu can be used again. This is not available // yet, so inflate each time (yuk!) MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.browsercontext, menu); // Show the correct menu group String extra = result.getExtra(); menu.setGroupVisible(R.id.PHONE_MENU, type == WebView.HitTestResult.PHONE_TYPE); menu.setGroupVisible(R.id.EMAIL_MENU, type == WebView.HitTestResult.EMAIL_TYPE); menu.setGroupVisible(R.id.GEO_MENU, type == WebView.HitTestResult.GEO_TYPE); menu.setGroupVisible(R.id.IMAGE_MENU, type == WebView.HitTestResult.IMAGE_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); menu.setGroupVisible(R.id.ANCHOR_MENU, type == WebView.HitTestResult.SRC_ANCHOR_TYPE || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); // Setup custom handling depending on the type switch (type) { case WebView.HitTestResult.PHONE_TYPE: menu.setHeaderTitle(Uri.decode(extra)); menu.findItem(R.id.dial_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_TEL + extra))); Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); menu.findItem(R.id.add_contact_context_menu_id).setIntent( addIntent); menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.EMAIL_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.email_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_MAILTO + extra))); menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.GEO_TYPE: menu.setHeaderTitle(extra); menu.findItem(R.id.map_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_GEO + URLEncoder.encode(extra)))); menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener( new Copy(extra)); break; case WebView.HitTestResult.SRC_ANCHOR_TYPE: case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: TextView titleView = (TextView) LayoutInflater.from(this) .inflate(android.R.layout.browser_link_context_header, null); titleView.setText(extra); menu.setHeaderView(titleView); // decide whether to show the open link in new tab option menu.findItem(R.id.open_newtab_context_menu_id).setVisible( mTabControl.getTabCount() < TabControl.MAX_TABS); PackageManager pm = getPackageManager(); Intent send = new Intent(Intent.ACTION_SEND); send.setType("text/plain"); ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null); if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { break; } // otherwise fall through to handle image part case WebView.HitTestResult.IMAGE_TYPE: if (type == WebView.HitTestResult.IMAGE_TYPE) { menu.setHeaderTitle(extra); } menu.findItem(R.id.view_image_context_menu_id).setIntent( new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); menu.findItem(R.id.download_context_menu_id). setOnMenuItemClickListener(new Download(extra)); break; default: Log.w(LOGTAG, "We should not get here."); break; } } // Attach the given tab to the content view. // this should only be called for the current tab. private void attachTabToContentView(TabControl.Tab t) { // Attach the container that contains the main WebView and any other UI // associated with the tab. t.attachTabToContentView(mContentView); if (mShouldShowErrorConsole) { ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); if (errorConsole.numberOfErrors() == 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } setLockIconType(t.getLockIconType()); setPrevLockType(t.getPrevLockIconType()); // this is to match the code in removeTabFromContentView() if (!mPageStarted && t.getTopWindow().getProgress() < 100) { mPageStarted = true; } WebView view = t.getWebView(); view.setEmbeddedTitleBar(mTitleBar); // Request focus on the top window. t.getTopWindow().requestFocus(); } // Attach a sub window to the main WebView of the given tab. private void attachSubWindow(TabControl.Tab t) { t.attachSubWindow(mContentView); getTopWindow().requestFocus(); } // Remove the given tab from the content view. private void removeTabFromContentView(TabControl.Tab t) { // Remove the container that contains the main WebView. t.removeTabFromContentView(mContentView); if (mTabControl.getCurrentErrorConsole(false) != null) { mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false)); } WebView view = t.getWebView(); if (view != null) { view.setEmbeddedTitleBar(null); } // unlike attachTabToContentView(), removeTabFromContentView() can be // called for the non-current tab. Need to add the check. if (t == mTabControl.getCurrentTab()) { t.setLockIconType(getLockIconType()); t.setPrevLockIconType(getPrevLockType()); // this is not a perfect solution. But currently there is one // WebViewClient for all the WebView. if user switches from an // in-load window to an already loaded window, mPageStarted will not // be set to false. If user leaves the Browser, pauseWebViewTimers() // won't do anything and leaves the timer running even Browser is in // the background. if (mPageStarted) { mPageStarted = false; } } } // Remove the sub window if it exists. Also called by TabControl when the // user clicks the 'X' to dismiss a sub window. /* package */ void dismissSubWindow(TabControl.Tab t) { t.removeSubWindow(mContentView); // Tell the TabControl to dismiss the subwindow. This will destroy // the WebView. mTabControl.dismissSubWindow(t); getTopWindow().requestFocus(); } // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)} // that accepts url as string. private TabControl.Tab openTabAndShow(String url, boolean closeOnExit, String appId) { return openTabAndShow(new UrlData(url), closeOnExit, appId); } // This method does a ton of stuff. It will attempt to create a new tab // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If // url isn't null, it will load the given url. /* package */ TabControl.Tab openTabAndShow(UrlData urlData, boolean closeOnExit, String appId) { final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS; final TabControl.Tab currentTab = mTabControl.getCurrentTab(); if (newTab) { final TabControl.Tab tab = mTabControl.createNewTab( closeOnExit, appId, urlData.mUrl); WebView webview = tab.getWebView(); // If the last tab was removed from the active tabs page, currentTab // will be null. if (currentTab != null) { removeTabFromContentView(currentTab); } // We must set the new tab as the current tab to reflect the old // animation behavior. mTabControl.setCurrentTab(tab); attachTabToContentView(tab); if (!urlData.isEmpty()) { urlData.loadIn(webview); } return tab; } else { // Get rid of the subwindow if it exists dismissSubWindow(currentTab); if (!urlData.isEmpty()) { // Load the given url. urlData.loadIn(currentTab.getWebView()); } } return currentTab; } private TabControl.Tab openTab(String url) { if (mSettings.openInBackground()) { TabControl.Tab t = mTabControl.createNewTab(); if (t != null) { WebView view = t.getWebView(); view.loadUrl(url); } return t; } else { return openTabAndShow(url, false, null); } } private class Copy implements OnMenuItemClickListener { private CharSequence mText; public boolean onMenuItemClick(MenuItem item) { copy(mText); return true; } public Copy(CharSequence toCopy) { mText = toCopy; } } private class Download implements OnMenuItemClickListener { private String mText; public boolean onMenuItemClick(MenuItem item) { onDownloadStartNoStream(mText, null, null, null, -1); return true; } public Download(String toDownload) { mText = toDownload; } } private void copy(CharSequence text) { try { IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard")); if (clip != null) { clip.setClipboardText(text); } } catch (android.os.RemoteException e) { Log.e(LOGTAG, "Copy failed", e); } } /** * Resets the browser title-view to whatever it must be * (for example, if we had a loading error) * When we have a new page, we call resetTitle, when we * have to reset the titlebar to whatever it used to be * (for example, if the user chose to stop loading), we * call resetTitleAndRevertLockIcon. */ /* package */ void resetTitleAndRevertLockIcon() { revertLockIcon(); resetTitleIconAndProgress(); } /** * Reset the title, favicon, and progress. */ private void resetTitleIconAndProgress() { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } resetTitleAndIcon(current); int progress = current.getProgress(); mWebChromeClient.onProgressChanged(current, progress); } // Reset the title and the icon based on the given item. private void resetTitleAndIcon(WebView view) { WebHistoryItem item = view.copyBackForwardList().getCurrentItem(); if (item != null) { setUrlTitle(item.getUrl(), item.getTitle()); setFavicon(item.getFavicon()); } else { setUrlTitle(null, null); setFavicon(null); } } /** * Sets a title composed of the URL and the title string. * @param url The URL of the site being loaded. * @param title The title of the site being loaded. */ private void setUrlTitle(String url, String title) { mUrl = url; mTitle = title; mTitleBar.setTitleAndUrl(title, url); if (mFakeTitleBar != null) { mFakeTitleBar.setTitleAndUrl(title, url); } } /** * @param url The URL to build a title version of the URL from. * @return The title version of the URL or null if fails. * The title version of the URL can be either the URL hostname, * or the hostname with an "https://" prefix (for secure URLs), * or an empty string if, for example, the URL in question is a * file:// URL with no hostname. */ /* package */ static String buildTitleUrl(String url) { String titleUrl = null; if (url != null) { try { // parse the url string URL urlObj = new URL(url); if (urlObj != null) { titleUrl = ""; String protocol = urlObj.getProtocol(); String host = urlObj.getHost(); if (host != null && 0 < host.length()) { titleUrl = host; if (protocol != null) { // if a secure site, add an "https://" prefix! if (protocol.equalsIgnoreCase("https")) { titleUrl = protocol + "://" + host; } } } } } catch (MalformedURLException e) {} } return titleUrl; } // Set the favicon in the title bar. private void setFavicon(Bitmap icon) { mTitleBar.setFavicon(icon); if (mFakeTitleBar != null) { mFakeTitleBar.setFavicon(icon); } } /** * Saves the current lock-icon state before resetting * the lock icon. If we have an error, we may need to * roll back to the previous state. */ private void saveLockIcon() { mPrevLockType = mLockIconType; } /** * Reverts the lock-icon state to the last saved state, * for example, if we had an error, and need to cancel * the load. */ private void revertLockIcon() { mLockIconType = mPrevLockType; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" + " revert lock icon to " + mLockIconType); } updateLockIconToLatest(); } /** * Close the tab, remove its associated title bar, and adjust mTabControl's * current tab to a valid value. */ /* package */ void closeTab(TabControl.Tab t) { int currentIndex = mTabControl.getCurrentIndex(); int removeIndex = mTabControl.getTabIndex(t); mTabControl.removeTab(t); if (currentIndex >= removeIndex && currentIndex != 0) { currentIndex--; } mTabControl.setCurrentTab(mTabControl.getTab(currentIndex)); resetTitleIconAndProgress(); } private void goBackOnePageOrQuit() { TabControl.Tab current = mTabControl.getCurrentTab(); if (current == null) { /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); return; } WebView w = current.getWebView(); if (w.canGoBack()) { w.goBack(); } else { // Check to see if we are closing a window that was created by // another window. If so, we switch back to that window. TabControl.Tab parent = current.getParentTab(); if (parent != null) { switchToTab(mTabControl.getTabIndex(parent)); // Now we close the other tab closeTab(current); } else { if (current.closeOnExit()) { // force mPageStarted to be false as we are going to either // finish the activity or remove the tab. This will ensure // pauseWebView() taking action. mPageStarted = false; if (mTabControl.getTabCount() == 1) { finish(); return; } // call pauseWebViewTimers() now, we won't be able to call // it in onPause() as the WebView won't be valid. // Temporarily change mActivityInPause to be true as // pauseWebViewTimers() will do nothing if mActivityInPause // is false. boolean savedState = mActivityInPause; if (savedState) { Log.e(LOGTAG, "BrowserActivity is already paused " + "while handing goBackOnePageOrQuit."); } mActivityInPause = true; pauseWebViewTimers(); mActivityInPause = savedState; removeTabFromContentView(current); mTabControl.removeTab(current); } /* * Instead of finishing the activity, simply push this to the back * of the stack and let ActivityManager to choose the foreground * activity. As BrowserActivity is singleTask, it will be always the * root of the task. So we can use either true or false for * moveTaskToBack(). */ moveTaskToBack(true); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is // still down, we don't want to trigger the search. Pretend to consume // the key and do nothing. if (mMenuIsDown) return true; switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = true; break; case KeyEvent.KEYCODE_SPACE: // WebView/WebTextView handle the keys in the KeyDown. As // the Activity's shortcut keys are only handled when WebView // doesn't, have to do it in onKeyDown instead of onKeyUp. if (event.isShiftPressed()) { getTopWindow().pageUp(false); } else { getTopWindow().pageDown(false); } return true; case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { event.startTracking(); return true; } else if (mCustomView == null && mActiveTabsPage == null && event.isLongPress()) { bookmarksOrHistoryPicker(true); return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_MENU: mMenuIsDown = false; break; case KeyEvent.KEYCODE_BACK: if (event.isTracking() && !event.isCanceled()) { if (mCustomView != null) { // if a custom view is showing, hide it mWebChromeClient.onHideCustomView(); } else if (mActiveTabsPage != null) { // if tab page is showing, hide it removeActiveTabPage(true); } else { WebView subwindow = mTabControl.getCurrentSubWindow(); if (subwindow != null) { if (subwindow.canGoBack()) { subwindow.goBack(); } else { dismissSubWindow(mTabControl.getCurrentTab()); } } else { goBackOnePageOrQuit(); } } return true; } break; } return super.onKeyUp(keyCode, event); } /* package */ void stopLoading() { mDidStopLoad = true; resetTitleAndRevertLockIcon(); WebView w = getTopWindow(); w.stopLoading(); mWebViewClient.onPageFinished(w, w.getUrl()); cancelStopToast(); mStopToast = Toast .makeText(this, R.string.stopping, Toast.LENGTH_SHORT); mStopToast.show(); } private void cancelStopToast() { if (mStopToast != null) { mStopToast.cancel(); mStopToast = null; } } // called by a non-UI thread to post the message public void postMessage(int what, int arg1, int arg2, Object obj) { mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj)); } // public message ids public final static int LOAD_URL = 1001; public final static int STOP_LOAD = 1002; // Message Ids private static final int FOCUS_NODE_HREF = 102; private static final int CANCEL_CREDS_REQUEST = 103; private static final int RELEASE_WAKELOCK = 107; private static final int UPDATE_BOOKMARK_THUMBNAIL = 108; // Private handler for handling javascript and saving passwords private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case FOCUS_NODE_HREF: { String url = (String) msg.getData().get("url"); if (url == null || url.length() == 0) { break; } HashMap focusNodeMap = (HashMap) msg.obj; WebView view = (WebView) focusNodeMap.get("webview"); // Only apply the action if the top window did not change. if (getTopWindow() != view) { break; } switch (msg.arg1) { case R.id.open_context_menu_id: case R.id.view_image_context_menu_id: loadURL(getTopWindow(), url); break; case R.id.open_newtab_context_menu_id: final TabControl.Tab parent = mTabControl .getCurrentTab(); final TabControl.Tab newTab = openTab(url); if (newTab != parent) { parent.addChildTab(newTab); } break; case R.id.bookmark_context_menu_id: Intent intent = new Intent(BrowserActivity.this, AddBookmarkPage.class); intent.putExtra("url", url); startActivity(intent); break; case R.id.share_link_context_menu_id: Browser.sendString(BrowserActivity.this, url, getText(R.string.choosertitle_sharevia).toString()); break; case R.id.copy_link_context_menu_id: copy(url); break; case R.id.save_link_context_menu_id: case R.id.download_context_menu_id: onDownloadStartNoStream(url, null, null, null, -1); break; } break; } case LOAD_URL: loadURL(getTopWindow(), (String) msg.obj); break; case STOP_LOAD: stopLoading(); break; case CANCEL_CREDS_REQUEST: resumeAfterCredentials(); break; case RELEASE_WAKELOCK: if (mWakeLock.isHeld()) { mWakeLock.release(); } break; case UPDATE_BOOKMARK_THUMBNAIL: WebView view = (WebView) msg.obj; if (view != null) { updateScreenshot(view); } break; } } }; private void updateScreenshot(WebView view) { // If this is a bookmarked site, add a screenshot to the database. // FIXME: When should we update? Every time? // FIXME: Would like to make sure there is actually something to // draw, but the API for that (WebViewCore.pictureReady()) is not // currently accessible here. ContentResolver cr = getContentResolver(); final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl( cr, view.getOriginalUrl(), view.getUrl(), true); if (c != null) { boolean succeed = c.moveToFirst(); ContentValues values = null; while (succeed) { if (values == null) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); Bitmap bm = createScreenshot(view); if (bm == null) { c.close(); return; } bm.compress(Bitmap.CompressFormat.PNG, 100, os); values = new ContentValues(); values.put(Browser.BookmarkColumns.THUMBNAIL, os.toByteArray()); } cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI, c.getInt(0)), values, null, null); succeed = c.moveToNext(); } c.close(); } } /** * Values for the size of the thumbnail created when taking a screenshot. * Lazily initialized. Instead of using these directly, use * getDesiredThumbnailWidth() or getDesiredThumbnailHeight(). */ private static int THUMBNAIL_WIDTH = 0; private static int THUMBNAIL_HEIGHT = 0; /** * Return the desired width for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired width for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailWidth(Context context) { if (THUMBNAIL_WIDTH == 0) { float density = context.getResources().getDisplayMetrics().density; THUMBNAIL_WIDTH = (int) (90 * density); THUMBNAIL_HEIGHT = (int) (80 * density); } return THUMBNAIL_WIDTH; } /** * Return the desired height for thumbnail screenshots, which are stored in * the database, and used on the bookmarks screen. * @param context Context for finding out the density of the screen. * @return int desired height for thumbnail screenshot. */ /* package */ static int getDesiredThumbnailHeight(Context context) { // To ensure that they are both initialized. getDesiredThumbnailWidth(context); return THUMBNAIL_HEIGHT; } private Bitmap createScreenshot(WebView view) { Picture thumbnail = view.capturePicture(); if (thumbnail == null) { return null; } Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this), getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); // May need to tweak these values to determine what is the // best scale factor int thumbnailWidth = thumbnail.getWidth(); if (thumbnailWidth > 0) { float scaleFactor = (float) getDesiredThumbnailWidth(this) / (float)thumbnailWidth; canvas.scale(scaleFactor, scaleFactor); } thumbnail.draw(canvas); return bm; } // ------------------------------------------------------------------------- // WebViewClient implementation. //------------------------------------------------------------------------- // Use in overrideUrlLoading /* package */ final static String SCHEME_WTAI = "wtai://wp/"; /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;"; /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;"; /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;"; /* package */ WebViewClient getWebViewClient() { return mWebViewClient; } private void updateIcon(WebView view, Bitmap icon) { if (icon != null) { BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver, view.getOriginalUrl(), view.getUrl(), icon); } setFavicon(icon); } private void updateIcon(String url, Bitmap icon) { if (icon != null) { BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver, null, url, icon); } setFavicon(icon); } private final WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { resetLockIcon(url); setUrlTitle(url, null); // We've started to load a new page. If there was a pending message // to save a screenshot then we will now take the new page and // save an incorrect screenshot. Therefore, remove any pending // thumbnail messages from the queue. mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL); // If we start a touch icon load and then load a new page, we don't // want to cancel the current touch icon loader. But, we do want to // create a new one when the touch icon url is known. if (mTouchIconLoader != null) { mTouchIconLoader.mActivity = null; mTouchIconLoader = null; } ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false); if (errorConsole != null) { errorConsole.clearErrorMessages(); if (mShouldShowErrorConsole) { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } } // Call updateIcon instead of setFavicon so the bookmark // database can be updated. updateIcon(url, favicon); if (mSettings.isTracing()) { String host; try { WebAddress uri = new WebAddress(url); host = uri.mHost; } catch (android.net.ParseException ex) { host = "browser"; } host = host.replace('.', '_'); host += ".trace"; mInTrace = true; Debug.startMethodTracing(host, 20 * 1024 * 1024); } // Performance probe if (false) { mStart = SystemClock.uptimeMillis(); mProcessStart = Process.getElapsedCpuTime(); long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { mUserStart = sysCpu[0] + sysCpu[1]; mSystemStart = sysCpu[2]; mIdleStart = sysCpu[3]; mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6]; } mUiStart = SystemClock.currentThreadTimeMillis(); } if (!mPageStarted) { mPageStarted = true; // if onResume() has been called, resumeWebViewTimers() does // nothing. resumeWebViewTimers(); } // reset sync timer to avoid sync starts during loading a page CookieSyncManager.getInstance().resetSync(); mInLoad = true; mDidStopLoad = false; showFakeTitleBar(); updateInLoadMenuItems(); if (!mIsNetworkUp) { createAndShowNetworkDialog(); if (view != null) { view.setNetworkAvailable(false); } } } @Override public void onPageFinished(WebView view, String url) { // Reset the title and icon in case we stopped a provisional // load. resetTitleAndIcon(view); if (!mDidStopLoad) { // Only update the bookmark screenshot if the user did not // cancel the load early. Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view); mHandler.sendMessageDelayed(updateScreenshot, 500); } // Update the lock icon image only once we are done loading updateLockIconToLatest(); // Performance probe if (false) { long[] sysCpu = new long[7]; if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, sysCpu, null)) { String uiInfo = "UI thread used " + (SystemClock.currentThreadTimeMillis() - mUiStart) + " ms"; if (LOGD_ENABLED) { Log.d(LOGTAG, uiInfo); } //The string that gets written to the log String performanceString = "It took total " + (SystemClock.uptimeMillis() - mStart) + " ms clock time to load the page." + "\nbrowser process used " + (Process.getElapsedCpuTime() - mProcessStart) + " ms, user processes used " + (sysCpu[0] + sysCpu[1] - mUserStart) * 10 + " ms, kernel used " + (sysCpu[2] - mSystemStart) * 10 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10 + " ms and irq took " + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart) * 10 + " ms, " + uiInfo; if (LOGD_ENABLED) { Log.d(LOGTAG, performanceString + "\nWebpage: " + url); } if (url != null) { // strip the url to maintain consistency String newUrl = new String(url); if (newUrl.startsWith("http://www.")) { newUrl = newUrl.substring(11); } else if (newUrl.startsWith("http://")) { newUrl = newUrl.substring(7); } else if (newUrl.startsWith("https://www.")) { newUrl = newUrl.substring(12); } else if (newUrl.startsWith("https://")) { newUrl = newUrl.substring(8); } if (LOGD_ENABLED) { Log.d(LOGTAG, newUrl + " loaded"); } /* if (sWhiteList.contains(newUrl)) { // The string that gets pushed to the statistcs // service performanceString = performanceString + "\nWebpage: " + newUrl + "\nCarrier: " + android.os.SystemProperties .get("gsm.sim.operator.alpha"); if (mWebView != null && mWebView.getContext() != null && mWebView.getContext().getSystemService( Context.CONNECTIVITY_SERVICE) != null) { ConnectivityManager cManager = (ConnectivityManager) mWebView .getContext().getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo nInfo = cManager .getActiveNetworkInfo(); if (nInfo != null) { performanceString = performanceString + "\nNetwork Type: " + nInfo.getType().toString(); } } Checkin.logEvent(mResolver, Checkin.Events.Tag.WEBPAGE_LOAD, performanceString); Log.w(LOGTAG, "pushed to the statistics service"); } */ } } } if (mInTrace) { mInTrace = false; Debug.stopMethodTracing(); } if (mPageStarted) { mPageStarted = false; // pauseWebViewTimers() will do nothing and return false if // onPause() is not called yet. if (pauseWebViewTimers()) { if (mWakeLock.isHeld()) { mHandler.removeMessages(RELEASE_WAKELOCK); mWakeLock.release(); } } } } // return true if want to hijack the url to let another app to handle it @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith(SCHEME_WTAI)) { // wtai://wp/mc;number // number=string(phone-number) if (url.startsWith(SCHEME_WTAI_MC)) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(WebView.SCHEME_TEL + url.substring(SCHEME_WTAI_MC.length()))); startActivity(intent); return true; } // wtai://wp/sd;dtmf // dtmf=string(dialstring) if (url.startsWith(SCHEME_WTAI_SD)) { // TODO // only send when there is active voice connection return false; } // wtai://wp/ap;number;name // number=string(phone-number) // name=string if (url.startsWith(SCHEME_WTAI_AP)) { // TODO return false; } } // The "about:" schemes are internal to the browser; don't // want these to be dispatched to other apps. if (url.startsWith("about:")) { return false; } Intent intent; // perform generic parsing of the URI to turn it into an Intent. try { intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); } catch (URISyntaxException ex) { Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage()); return false; } // check whether the intent can be resolved. If not, we will see // whether we can download it from the Market. if (getPackageManager().resolveActivity(intent, 0) == null) { String packagename = intent.getPackage(); if (packagename != null) { intent = new Intent(Intent.ACTION_VIEW, Uri .parse("market://search?q=pname:" + packagename)); intent.addCategory(Intent.CATEGORY_BROWSABLE); startActivity(intent); return true; } else { return false; } } // sanitize the Intent, ensuring web pages can not bypass browser // security (only access to BROWSABLE activities). intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setComponent(null); try { if (startActivityIfNeeded(intent, -1)) { return true; } } catch (ActivityNotFoundException ex) { // ignore the error. If no application can handle the URL, // eg about:blank, assume the browser can handle it. } if (mMenuIsDown) { openTab(url); closeOptionsMenu(); return true; } return false; } /** * Updates the lock icon. This method is called when we discover another * resource to be loaded for this page (for example, javascript). While * we update the icon type, we do not update the lock icon itself until * we are done loading, it is slightly more secure this way. */ @Override public void onLoadResource(WebView view, String url) { if (url != null && url.length() > 0) { // It is only if the page claims to be secure // that we may have to update the lock: if (mLockIconType == LOCK_ICON_SECURE) { // If NOT a 'safe' url, change the lock to mixed content! if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) { mLockIconType = LOCK_ICON_MIXED; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" + " updated lock icon to " + mLockIconType + " due to " + url); } } } } } /** * Show the dialog, asking the user if they would like to continue after * an excessive number of HTTP redirects. */ @Override public void onTooManyRedirects(WebView view, final Message cancelMsg, final Message continueMsg) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.browserFrameRedirect) .setMessage(R.string.browserFrame307Post) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { continueMsg.sendToTarget(); }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelMsg.sendToTarget(); }}) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { cancelMsg.sendToTarget(); }}) .show(); } // Container class for the next error dialog that needs to be // displayed. class ErrorDialog { public final int mTitle; public final String mDescription; public final int mError; ErrorDialog(int title, String desc, int error) { mTitle = title; mDescription = desc; mError = error; } }; private void processNextError() { if (mQueuedErrors == null) { return; } // The first one is currently displayed so just remove it. mQueuedErrors.removeFirst(); if (mQueuedErrors.size() == 0) { mQueuedErrors = null; return; } showError(mQueuedErrors.getFirst()); } private DialogInterface.OnDismissListener mDialogListener = new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface d) { processNextError(); } }; private LinkedList<ErrorDialog> mQueuedErrors; private void queueError(int err, String desc) { if (mQueuedErrors == null) { mQueuedErrors = new LinkedList<ErrorDialog>(); } for (ErrorDialog d : mQueuedErrors) { if (d.mError == err) { // Already saw a similar error, ignore the new one. return; } } ErrorDialog errDialog = new ErrorDialog( err == WebViewClient.ERROR_FILE_NOT_FOUND ? R.string.browserFrameFileErrorLabel : R.string.browserFrameNetworkErrorLabel, desc, err); mQueuedErrors.addLast(errDialog); // Show the dialog now if the queue was empty. if (mQueuedErrors.size() == 1) { showError(errDialog); } } private void showError(ErrorDialog errDialog) { AlertDialog d = new AlertDialog.Builder(BrowserActivity.this) .setTitle(errDialog.mTitle) .setMessage(errDialog.mDescription) .setPositiveButton(R.string.ok, null) .create(); d.setOnDismissListener(mDialogListener); d.show(); } /** * Show a dialog informing the user of the network error reported by * WebCore. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { if (errorCode != WebViewClient.ERROR_HOST_LOOKUP && errorCode != WebViewClient.ERROR_CONNECT && errorCode != WebViewClient.ERROR_BAD_URL && errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME && errorCode != WebViewClient.ERROR_FILE) { queueError(errorCode, description); } Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl + " " + description); // We need to reset the title after an error. resetTitleAndRevertLockIcon(); } /** * Check with the user if it is ok to resend POST data as the page they * are trying to navigate to is the result of a POST. */ @Override public void onFormResubmission(WebView view, final Message dontResend, final Message resend) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.browserFrameFormResubmitLabel) .setMessage(R.string.browserFrameFormResubmitMessage) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { resend.sendToTarget(); }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dontResend.sendToTarget(); }}) .setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { dontResend.sendToTarget(); }}) .show(); } /** * Insert the url into the visited history database. * @param url The url to be inserted. * @param isReload True if this url is being reloaded. * FIXME: Not sure what to do when reloading the page. */ @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { if (url.regionMatches(true, 0, "about:", 0, 6)) { return; } // remove "client" before updating it to the history so that it wont // show up in the auto-complete list. int index = url.indexOf("client=ms-"); if (index > 0 && url.contains(".google.")) { int end = url.indexOf('&', index); if (end > 0) { url = url.substring(0, index) .concat(url.substring(end + 1)); } else { // the url.charAt(index-1) should be either '?' or '&' url = url.substring(0, index-1); } } Browser.updateVisitedHistory(mResolver, url, true); WebIconDatabase.getInstance().retainIconForPageUrl(url); } /** * Displays SSL error(s) dialog to the user. */ @Override public void onReceivedSslError( final WebView view, final SslErrorHandler handler, final SslError error) { if (mSettings.showSecurityWarnings()) { final LayoutInflater factory = LayoutInflater.from(BrowserActivity.this); final View warningsView = factory.inflate(R.layout.ssl_warnings, null); final LinearLayout placeholder = (LinearLayout)warningsView.findViewById(R.id.placeholder); if (error.hasError(SslError.SSL_UNTRUSTED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_untrusted); placeholder.addView(ll); } if (error.hasError(SslError.SSL_IDMISMATCH)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_mismatch); placeholder.addView(ll); } if (error.hasError(SslError.SSL_EXPIRED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_expired); placeholder.addView(ll); } if (error.hasError(SslError.SSL_NOTYETVALID)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, null); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_not_yet_valid); placeholder.addView(ll); } new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.security_warning) .setIcon(android.R.drawable.ic_dialog_alert) .setView(warningsView) .setPositiveButton(R.string.ssl_continue, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.proceed(); } }) .setNeutralButton(R.string.view_certificate, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { showSSLCertificateOnError(view, handler, error); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); } }) .show(); } else { handler.proceed(); } } /** * Handles an HTTP authentication request. * * @param handler The authentication handler * @param host The host * @param realm The realm */ @Override public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, final String host, final String realm) { String username = null; String password = null; boolean reuseHttpAuthUsernamePassword = handler.useHttpAuthUsernamePassword(); if (reuseHttpAuthUsernamePassword && (mTabControl.getCurrentWebView() != null)) { String[] credentials = mTabControl.getCurrentWebView() .getHttpAuthUsernamePassword(host, realm); if (credentials != null && credentials.length == 2) { username = credentials[0]; password = credentials[1]; } } if (username != null && password != null) { handler.proceed(username, password); } else { showHttpAuthentication(handler, host, realm, null, null, null, 0); } } @Override public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) { if (mMenuIsDown) { // only check shortcut key when MENU is held return getWindow().isShortcutKey(event.getKeyCode(), event); } else { return false; } } @Override public void onUnhandledKeyEvent(WebView view, KeyEvent event) { if (view != mTabControl.getCurrentTopWebView()) { return; } if (event.isDown()) { BrowserActivity.this.onKeyDown(event.getKeyCode(), event); } else { BrowserActivity.this.onKeyUp(event.getKeyCode(), event); } } }; //-------------------------------------------------------------------------- // WebChromeClient implementation //-------------------------------------------------------------------------- /* package */ WebChromeClient getWebChromeClient() { return mWebChromeClient; } private final WebChromeClient mWebChromeClient = new WebChromeClient() { // Helper method to create a new tab or sub window. private void createWindow(final boolean dialog, final Message msg) { if (dialog) { mTabControl.createSubWindow(); final TabControl.Tab t = mTabControl.getCurrentTab(); attachSubWindow(t); WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj; transport.setWebView(t.getSubWebView()); msg.sendToTarget(); } else { final TabControl.Tab parent = mTabControl.getCurrentTab(); final TabControl.Tab newTab = openTabAndShow(EMPTY_URL_DATA, false, null); if (newTab != parent) { parent.addChildTab(newTab); } WebView.WebViewTransport transport = (WebView.WebViewTransport) msg.obj; transport.setWebView(mTabControl.getCurrentWebView()); msg.sendToTarget(); } } @Override public boolean onCreateWindow(WebView view, final boolean dialog, final boolean userGesture, final Message resultMsg) { // Short-circuit if we can't create any more tabs or sub windows. if (dialog && mTabControl.getCurrentSubWindow() != null) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.too_many_subwindows_dialog_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.too_many_subwindows_dialog_message) .setPositiveButton(R.string.ok, null) .show(); return false; } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) { new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.too_many_windows_dialog_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.too_many_windows_dialog_message) .setPositiveButton(R.string.ok, null) .show(); return false; } // Short-circuit if this was a user gesture. if (userGesture) { createWindow(dialog, resultMsg); return true; } // Allow the popup and create the appropriate window. final AlertDialog.OnClickListener allowListener = new AlertDialog.OnClickListener() { public void onClick(DialogInterface d, int which) { createWindow(dialog, resultMsg); } }; // Block the popup by returning a null WebView. final AlertDialog.OnClickListener blockListener = new AlertDialog.OnClickListener() { public void onClick(DialogInterface d, int which) { resultMsg.sendToTarget(); } }; // Build a confirmation dialog to display to the user. final AlertDialog d = new AlertDialog.Builder(BrowserActivity.this) .setTitle(R.string.attention) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.popup_window_attempt) .setPositiveButton(R.string.allow, allowListener) .setNegativeButton(R.string.block, blockListener) .setCancelable(false) .create(); // Show the confirmation dialog. d.show(); return true; } @Override public void onCloseWindow(WebView window) { final TabControl.Tab current = mTabControl.getCurrentTab(); final TabControl.Tab parent = current.getParentTab(); if (parent != null) { // JavaScript can only close popup window. switchToTab(mTabControl.getTabIndex(parent)); // Now we need to close the window closeTab(current); } } @Override public void onProgressChanged(WebView view, int newProgress) { mTitleBar.setProgress(newProgress); if (mFakeTitleBar != null) { mFakeTitleBar.setProgress(newProgress); } if (newProgress == 100) { // onProgressChanged() may continue to be called after the main // frame has finished loading, as any remaining sub frames // continue to load. We'll only get called once though with // newProgress as 100 when everything is loaded. // (onPageFinished is called once when the main frame completes // loading regardless of the state of any sub frames so calls // to onProgressChanges may continue after onPageFinished has // executed) // sync cookies and cache promptly here. CookieSyncManager.getInstance().sync(); if (mInLoad) { mInLoad = false; updateInLoadMenuItems(); // If the options menu is open, leave the title bar if (!mOptionsMenuOpen || !mIconView) { hideFakeTitleBar(); } } } else if (!mInLoad) { // onPageFinished may have already been called but a subframe // is still loading and updating the progress. Reset mInLoad // and update the menu items. mInLoad = true; updateInLoadMenuItems(); if (!mOptionsMenuOpen || mIconView) { // This page has begun to load, so show the title bar showFakeTitleBar(); } } } @Override public void onReceivedTitle(WebView view, String title) { String url = view.getUrl(); // here, if url is null, we want to reset the title setUrlTitle(url, title); if (url == null || url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) { return; } // See if we can find the current url in our history database and // add the new title to it. if (url.startsWith("http://www.")) { url = url.substring(11); } else if (url.startsWith("http://")) { url = url.substring(4); } try { url = "%" + url; String [] selArgs = new String[] { url }; String where = Browser.BookmarkColumns.URL + " LIKE ? AND " + Browser.BookmarkColumns.BOOKMARK + " = 0"; Cursor c = mResolver.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, where, selArgs, null); if (c.moveToFirst()) { // Current implementation of database only has one entry per // url. ContentValues map = new ContentValues(); map.put(Browser.BookmarkColumns.TITLE, title); mResolver.update(Browser.BOOKMARKS_URI, map, "_id = " + c.getInt(0), null); } c.close(); } catch (IllegalStateException e) { Log.e(LOGTAG, "BrowserActivity onReceived title", e); } catch (SQLiteException ex) { Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex); } } @Override public void onReceivedIcon(WebView view, Bitmap icon) { updateIcon(view, icon); } @Override public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) { final ContentResolver cr = getContentResolver(); final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(cr, view.getOriginalUrl(), view.getUrl(), true); if (c != null) { if (c.getCount() > 0) { // Let precomposed icons take precedence over non-composed // icons. if (precomposed && mTouchIconLoader != null) { mTouchIconLoader.cancel(false); mTouchIconLoader = null; } // Have only one async task at a time. if (mTouchIconLoader == null) { mTouchIconLoader = new DownloadTouchIcon( BrowserActivity.this, cr, c, view); mTouchIconLoader.execute(url); } } else { c.close(); } } } @Override public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (mCustomView != null) return; // Add the custom view to its container. mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); mCustomView = view; mCustomViewCallback = callback; // Save the menu state and set it to empty while the custom // view is showing. mOldMenuState = mMenuState; mMenuState = EMPTY_MENU; // Hide the content view. mContentView.setVisibility(View.GONE); // Finally show the custom view container. mCustomViewContainer.setVisibility(View.VISIBLE); mCustomViewContainer.bringToFront(); } @Override public void onHideCustomView() { if (mCustomView == null) return; // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. mCustomViewContainer.removeView(mCustomView); mCustomView = null; // Reset the old menu state. mMenuState = mOldMenuState; mOldMenuState = EMPTY_MENU; mCustomViewContainer.setVisibility(View.GONE); mCustomViewCallback.onCustomViewHidden(); // Show the content view. mContentView.setVisibility(View.VISIBLE); } /** * The origin has exceeded its database quota. * @param url the URL that exceeded the quota * @param databaseIdentifier the identifier of the database on * which the transaction that caused the quota overflow was run * @param currentQuota the current quota for the origin. * @param estimatedSize the estimated size of the database. * @param totalUsedQuota is the sum of all origins' quota. * @param quotaUpdater The callback to run when a decision to allow or * deny quota has been made. Don't forget to call this! */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { mSettings.getWebStorageSizeManager().onExceededDatabaseQuota( url, databaseIdentifier, currentQuota, estimatedSize, totalUsedQuota, quotaUpdater); } /** * The Application Cache has exceeded its max size. * @param spaceNeeded is the amount of disk space that would be needed * in order for the last appcache operation to succeed. * @param totalUsedQuota is the sum of all origins' quota. * @param quotaUpdater A callback to inform the WebCore thread that a new * app cache size is available. This callback must always be executed at * some point to ensure that the sleeping WebCore thread is woken up. */ @Override public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize( spaceNeeded, totalUsedQuota, quotaUpdater); } /** * Instructs the browser to show a prompt to ask the user to set the * Geolocation permission state for the specified origin. * @param origin The origin for which Geolocation permissions are * requested. * @param callback The callback to call once the user has set the * Geolocation permission state. */ @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show( origin, callback); } /** * Instructs the browser to hide the Geolocation permissions prompt. */ @Override public void onGeolocationPermissionsHidePrompt() { mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide(); } /* Adds a JavaScript error message to the system log. * @param message The error message to report. * @param lineNumber The line number of the error. * @param sourceID The name of the source file that caused the error. */ @Override public void addMessageToConsole(String message, int lineNumber, String sourceID) { ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); errorConsole.addErrorMessage(message, sourceID, lineNumber); if (mShouldShowErrorConsole && errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber); } /** * Ask the browser for an icon to represent a <video> element. * This icon will be used if the Web page did not specify a poster attribute. * * @return Bitmap The icon or null if no such icon is available. * @hide pending API Council approval */ @Override public Bitmap getDefaultVideoPoster() { if (mDefaultVideoPoster == null) { mDefaultVideoPoster = BitmapFactory.decodeResource( getResources(), R.drawable.default_video_poster); } return mDefaultVideoPoster; } /** * Ask the host application for a custom progress view to show while * a <video> is loading. * * @return View The progress view. * @hide pending API Council approval */ @Override public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this); mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null); } return mVideoProgressView; } /** * Deliver a list of already-visited URLs * @hide pending API Council approval */ @Override public void getVisitedHistory(final ValueCallback<String[]> callback) { AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() { public String[] doInBackground(Void... unused) { return Browser.getVisitedHistory(getContentResolver()); } public void onPostExecute(String[] result) { callback.onReceiveValue(result); }; }; task.execute(); }; }; /** * Notify the host application a download should be done, or that * the data should be streamed if a streaming viewer is available. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // if we're dealing wih A/V content that's not explicitly marked // for download, check if it's streamable. if (contentDisposition == null || !contentDisposition.regionMatches( true, 0, "attachment", 0, 10)) { // query the package manager to see if there's a registered handler // that matches. Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), mimetype); ResolveInfo info = getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { ComponentName myName = getComponentName(); // If we resolved to ourselves, we don't want to attempt to // load the url only to try and download it again. if (!myName.getPackageName().equals( info.activityInfo.packageName) || !myName.getClassName().equals( info.activityInfo.name)) { // someone (other than us) knows how to handle this mime // type with this scheme, don't download. try { startActivity(intent); return; } catch (ActivityNotFoundException ex) { if (LOGD_ENABLED) { Log.d(LOGTAG, "activity not found for " + mimetype + " over " + Uri.parse(url).getScheme(), ex); } // Best behavior is to fall back to a download in this // case } } } } onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength); } /** * Notify the host application a download should be done, even if there * is a streaming viewer available for thise type. * @param url The full url to the content that should be downloaded * @param contentDisposition Content-disposition http header, if * present. * @param mimetype The mimetype of the content reported by the server * @param contentLength The file size reported by the server */ /*package */ void onDownloadStartNoStream(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { String filename = URLUtil.guessFileName(url, contentDisposition, mimetype); // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int title; String msg; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { msg = getString(R.string.download_sdcard_busy_dlg_msg); title = R.string.download_sdcard_busy_dlg_title; } else { msg = getString(R.string.download_no_sdcard_dlg_msg, filename); title = R.string.download_no_sdcard_dlg_title; } new AlertDialog.Builder(this) .setTitle(title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(msg) .setPositiveButton(R.string.ok, null) .show(); return; } // java.net.URI is a lot stricter than KURL so we have to undo // KURL's percent-encoding and redo the encoding using java.net.URI. URI uri = null; try { // Undo the percent-encoding that KURL may have done. String newUrl = new String(URLUtil.decode(url.getBytes())); // Parse the url into pieces WebAddress w = new WebAddress(newUrl); String frag = null; String query = null; String path = w.mPath; // Break the path into path, query, and fragment if (path.length() > 0) { // Strip the fragment int idx = path.lastIndexOf('#'); if (idx != -1) { frag = path.substring(idx + 1); path = path.substring(0, idx); } idx = path.lastIndexOf('?'); if (idx != -1) { query = path.substring(idx + 1); path = path.substring(0, idx); } } uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path, query, frag); } catch (Exception e) { Log.e(LOGTAG, "Could not parse url for download: " + url, e); return; } // XXX: Have to use the old url since the cookies were stored using the // old percent-encoded url. String cookies = CookieManager.getInstance().getCookie(url); ContentValues values = new ContentValues(); values.put(Downloads.COLUMN_URI, uri.toString()); values.put(Downloads.COLUMN_COOKIE_DATA, cookies); values.put(Downloads.COLUMN_USER_AGENT, userAgent); values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE, getPackageName()); values.put(Downloads.COLUMN_NOTIFICATION_CLASS, BrowserDownloadPage.class.getCanonicalName()); values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); values.put(Downloads.COLUMN_MIME_TYPE, mimetype); values.put(Downloads.COLUMN_FILE_NAME_HINT, filename); values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost()); if (contentLength > 0) { values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength); } if (mimetype == null) { // We must have long pressed on a link or image to download it. We // are not sure of the mimetype in this case, so do a head request new FetchUrlMimeType(this).execute(values); } else { final Uri contentUri = getContentResolver().insert(Downloads.CONTENT_URI, values); viewDownloads(contentUri); } } /** * Resets the lock icon. This method is called when we start a new load and * know the url to be loaded. */ private void resetLockIcon(String url) { // Save the lock-icon state (we revert to it if the load gets cancelled) saveLockIcon(); mLockIconType = LOCK_ICON_UNSECURE; if (URLUtil.isHttpsUrl(url)) { mLockIconType = LOCK_ICON_SECURE; if (LOGV_ENABLED) { Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" + " reset lock icon to " + mLockIconType); } } updateLockIconImage(LOCK_ICON_UNSECURE); } /* package */ void setLockIconType(int type) { mLockIconType = type; } /* package */ int getLockIconType() { return mLockIconType; } /* package */ void setPrevLockType(int type) { mPrevLockType = type; } /* package */ int getPrevLockType() { return mPrevLockType; } /** * Update the lock icon to correspond to our latest state. */ /* package */ void updateLockIconToLatest() { updateLockIconImage(mLockIconType); } /** * Updates the lock-icon image in the title-bar. */ private void updateLockIconImage(int lockIconType) { Drawable d = null; if (lockIconType == LOCK_ICON_SECURE) { d = mSecLockIcon; } else if (lockIconType == LOCK_ICON_MIXED) { d = mMixLockIcon; } mTitleBar.setLock(d); if (mFakeTitleBar != null) { mFakeTitleBar.setLock(d); } } /** * Displays a page-info dialog. * @param tab The tab to show info about * @param fromShowSSLCertificateOnError The flag that indicates whether * this dialog was opened from the SSL-certificate-on-error dialog or * not. This is important, since we need to know whether to return to * the parent dialog or simply dismiss. */ private void showPageInfo(final TabControl.Tab tab, final boolean fromShowSSLCertificateOnError) { final LayoutInflater factory = LayoutInflater .from(this); final View pageInfoView = factory.inflate(R.layout.page_info, null); final WebView view = tab.getWebView(); String url = null; String title = null; if (view == null) { url = tab.getUrl(); title = tab.getTitle(); } else if (view == mTabControl.getCurrentWebView()) { // Use the cached title and url if this is the current WebView url = mUrl; title = mTitle; } else { url = view.getUrl(); title = view.getTitle(); } if (url == null) { url = ""; } if (title == null) { title = ""; } ((TextView) pageInfoView.findViewById(R.id.address)).setText(url); ((TextView) pageInfoView.findViewById(R.id.title)).setText(title); mPageInfoView = tab; mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this) .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info) .setView(pageInfoView) .setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } } }); // if we have a main top-level page SSL certificate set or a certificate // error if (fromShowSSLCertificateOnError || (view != null && view.getCertificate() != null)) { // add a 'View Certificate' button alertDialogBuilder.setNeutralButton( R.string.view_certificate, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPageInfoDialog = null; mPageInfoView = null; mPageInfoFromShowSSLCertificateOnError = null; // if we came here from the SSL error dialog if (fromShowSSLCertificateOnError) { // go back to the SSL error dialog showSSLCertificateOnError( mSSLCertificateOnErrorView, mSSLCertificateOnErrorHandler, mSSLCertificateOnErrorError); } else { // otherwise, display the top-most certificate from // the chain if (view.getCertificate() != null) { showSSLCertificate(tab); } } } }); } mPageInfoDialog = alertDialogBuilder.show(); } /** * Displays the main top-level page SSL certificate dialog * (accessible from the Page-Info dialog). * @param tab The tab to show certificate for. */ private void showSSLCertificate(final TabControl.Tab tab) { final View certificateView = inflateCertificateView(tab.getWebView().getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); LinearLayout ll = (LinearLayout) factory.inflate( R.layout.ssl_success, placeholder); ((TextView)ll.findViewById(R.id.success)) .setText(R.string.ssl_certificate_is_valid); mSSLCertificateView = tab; mSSLCertificateDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateDialog = null; mSSLCertificateView = null; showPageInfo(tab, false); } }) .show(); } /** * Displays the SSL error certificate dialog. * @param view The target web-view. * @param handler The SSL error handler responsible for cancelling the * connection that resulted in an SSL error or proceeding per user request. * @param error The SSL error object. */ private void showSSLCertificateOnError( final WebView view, final SslErrorHandler handler, final SslError error) { final View certificateView = inflateCertificateView(error.getCertificate()); if (certificateView == null) { return; } LayoutInflater factory = LayoutInflater.from(this); final LinearLayout placeholder = (LinearLayout)certificateView.findViewById(R.id.placeholder); if (error.hasError(SslError.SSL_UNTRUSTED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_untrusted); } if (error.hasError(SslError.SSL_IDMISMATCH)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_mismatch); } if (error.hasError(SslError.SSL_EXPIRED)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_expired); } if (error.hasError(SslError.SSL_NOTYETVALID)) { LinearLayout ll = (LinearLayout)factory .inflate(R.layout.ssl_warning, placeholder); ((TextView)ll.findViewById(R.id.warning)) .setText(R.string.ssl_not_yet_valid); } mSSLCertificateOnErrorHandler = handler; mSSLCertificateOnErrorView = view; mSSLCertificateOnErrorError = error; mSSLCertificateOnErrorDialog = new AlertDialog.Builder(this) .setTitle(R.string.ssl_certificate).setIcon( R.drawable.ic_dialog_browser_certificate_partially_secure) .setView(certificateView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; mWebViewClient.onReceivedSslError( view, handler, error); } }) .setNeutralButton(R.string.page_info_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mSSLCertificateOnErrorDialog = null; // do not clear the dialog state: we will // need to show the dialog again once the // user is done exploring the page-info details showPageInfo(mTabControl.getTabFromView(view), true); } }) .setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mSSLCertificateOnErrorDialog = null; mSSLCertificateOnErrorView = null; mSSLCertificateOnErrorHandler = null; mSSLCertificateOnErrorError = null; mWebViewClient.onReceivedSslError( view, handler, error); } }) .show(); } /** * Inflates the SSL certificate view (helper method). * @param certificate The SSL certificate. * @return The resultant certificate view with issued-to, issued-by, * issued-on, expires-on, and possibly other fields set. * If the input certificate is null, returns null. */ private View inflateCertificateView(SslCertificate certificate) { if (certificate == null) { return null; } LayoutInflater factory = LayoutInflater.from(this); View certificateView = factory.inflate( R.layout.ssl_certificate, null); // issued to: SslCertificate.DName issuedTo = certificate.getIssuedTo(); if (issuedTo != null) { ((TextView) certificateView.findViewById(R.id.to_common)) .setText(issuedTo.getCName()); ((TextView) certificateView.findViewById(R.id.to_org)) .setText(issuedTo.getOName()); ((TextView) certificateView.findViewById(R.id.to_org_unit)) .setText(issuedTo.getUName()); } // issued by: SslCertificate.DName issuedBy = certificate.getIssuedBy(); if (issuedBy != null) { ((TextView) certificateView.findViewById(R.id.by_common)) .setText(issuedBy.getCName()); ((TextView) certificateView.findViewById(R.id.by_org)) .setText(issuedBy.getOName()); ((TextView) certificateView.findViewById(R.id.by_org_unit)) .setText(issuedBy.getUName()); } // issued on: String issuedOn = reformatCertificateDate( certificate.getValidNotBefore()); ((TextView) certificateView.findViewById(R.id.issued_on)) .setText(issuedOn); // expires on: String expiresOn = reformatCertificateDate( certificate.getValidNotAfter()); ((TextView) certificateView.findViewById(R.id.expires_on)) .setText(expiresOn); return certificateView; } /** * Re-formats the certificate date (Date.toString()) string to * a properly localized date string. * @return Properly localized version of the certificate date string and * the original certificate date string if fails to localize. * If the original string is null, returns an empty string "". */ private String reformatCertificateDate(String certificateDate) { String reformattedDate = null; if (certificateDate != null) { Date date = null; try { date = java.text.DateFormat.getInstance().parse(certificateDate); } catch (ParseException e) { date = null; } if (date != null) { reformattedDate = DateFormat.getDateFormat(this).format(date); } } return reformattedDate != null ? reformattedDate : (certificateDate != null ? certificateDate : ""); } /** * Displays an http-authentication dialog. */ private void showHttpAuthentication(final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password, int focusId) { LayoutInflater factory = LayoutInflater.from(this); final View v = factory .inflate(R.layout.http_authentication, null); if (name != null) { ((EditText) v.findViewById(R.id.username_edit)).setText(name); } if (password != null) { ((EditText) v.findViewById(R.id.password_edit)).setText(password); } String titleText = title; if (titleText == null) { titleText = getText(R.string.sign_in_to).toString().replace( "%s1", host).replace("%s2", realm); } mHttpAuthHandler = handler; AlertDialog dialog = new AlertDialog.Builder(this) .setTitle(titleText) .setIcon(android.R.drawable.ic_dialog_alert) .setView(v) .setPositiveButton(R.string.action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String nm = ((EditText) v .findViewById(R.id.username_edit)) .getText().toString(); String pw = ((EditText) v .findViewById(R.id.password_edit)) .getText().toString(); BrowserActivity.this.setHttpAuthUsernamePassword (host, realm, nm, pw); handler.proceed(nm, pw); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { handler.cancel(); BrowserActivity.this.resetTitleAndRevertLockIcon(); mHttpAuthenticationDialog = null; mHttpAuthHandler = null; }}) .create(); // Make the IME appear when the dialog is displayed if applicable. dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); if (focusId != 0) { dialog.findViewById(focusId).requestFocus(); } else { v.findViewById(R.id.username_edit).requestFocus(); } mHttpAuthenticationDialog = dialog; } public int getProgress() { WebView w = mTabControl.getCurrentWebView(); if (w != null) { return w.getProgress(); } else { return 100; } } /** * Set HTTP authentication password. * * @param host The host for the password * @param realm The realm for the password * @param username The username for the password. If it is null, it means * password can't be saved. * @param password The password */ public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setHttpAuthUsernamePassword(host, realm, username, password); } } /** * connectivity manager says net has come or gone... inform the user * @param up true if net has come up, false if net has gone down */ public void onNetworkToggle(boolean up) { if (up == mIsNetworkUp) { return; } else if (up) { mIsNetworkUp = true; if (mAlertDialog != null) { mAlertDialog.cancel(); mAlertDialog = null; } } else { mIsNetworkUp = false; if (mInLoad) { createAndShowNetworkDialog(); } } WebView w = mTabControl.getCurrentWebView(); if (w != null) { w.setNetworkAvailable(up); } } // This method shows the network dialog alerting the user that the net is // down. It will only show the dialog if mAlertDialog is null. private void createAndShowNetworkDialog() { if (mAlertDialog == null) { mAlertDialog = new AlertDialog.Builder(this) .setTitle(R.string.loadSuspendedTitle) .setMessage(R.string.loadSuspended) .setPositiveButton(R.string.ok, null) .show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case COMBO_PAGE: if (resultCode == RESULT_OK && intent != null) { String data = intent.getAction(); Bundle extras = intent.getExtras(); if (extras != null && extras.getBoolean("new_window", false)) { openTab(data); } else { final TabControl.Tab currentTab = mTabControl.getCurrentTab(); dismissSubWindow(currentTab); if (data != null && data.length() != 0) { getTopWindow().loadUrl(data); } } } break; default: break; } getTopWindow().requestFocus(); } /* * This method is called as a result of the user selecting the options * menu to see the download window, or when a download changes state. It * shows the download window ontop of the current window. */ /* package */ void viewDownloads(Uri downloadRecord) { Intent intent = new Intent(this, BrowserDownloadPage.class); intent.setData(downloadRecord); startActivityForResult(intent, this.DOWNLOAD_PAGE); } /** * Open the Go page. * @param startWithHistory If true, open starting on the history tab. * Otherwise, start with the bookmarks tab. */ /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) { WebView current = mTabControl.getCurrentWebView(); if (current == null) { return; } Intent intent = new Intent(this, CombinedBookmarkHistoryActivity.class); String title = current.getTitle(); String url = current.getUrl(); Bitmap thumbnail = createScreenshot(current); // Just in case the user opens bookmarks before a page finishes loading // so the current history item, and therefore the page, is null. if (null == url) { url = mLastEnteredUrl; // This can happen. if (null == url) { url = mSettings.getHomePage(); } } // In case the web page has not yet received its associated title. if (title == null) { title = url; } intent.putExtra("title", title); intent.putExtra("url", url); intent.putExtra("thumbnail", thumbnail); // Disable opening in a new window if we have maxed out the windows intent.putExtra("disable_new_window", mTabControl.getTabCount() >= TabControl.MAX_TABS); intent.putExtra("touch_icon_url", current.getTouchIconUrl()); if (startWithHistory) { intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB, CombinedBookmarkHistoryActivity.HISTORY_TAB); } startActivityForResult(intent, COMBO_PAGE); } // Called when loading from context menu or LOAD_URL message private void loadURL(WebView view, String url) { // In case the user enters nothing. if (url != null && url.length() != 0 && view != null) { url = smartUrlFilter(url); if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) { view.loadUrl(url); } } } private String smartUrlFilter(Uri inUri) { if (inUri != null) { return smartUrlFilter(inUri.toString()); } return null; } // get window count int getWindowCount(){ if(mTabControl != null){ return mTabControl.getTabCount(); } return 0; } protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( "(?i)" + // switch on case insensitive matching "(" + // begin group for schema "(?:http|https|file):\\/\\/" + "|(?:inline|data|about|content|javascript):" + ")" + "(.*)" ); /** * Attempts to determine whether user input is a URL or search * terms. Anything with a space is passed to search. * * Converts to lowercase any mistakenly uppercased schema (i.e., * "Http://" converts to "http://" * * @return Original or modified URL * */ String smartUrlFilter(String url) { String inUrl = url.trim(); boolean hasSpace = inUrl.indexOf(' ') != -1; Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); if (matcher.matches()) { // force scheme to lowercase String scheme = matcher.group(1); String lcScheme = scheme.toLowerCase(); if (!lcScheme.equals(scheme)) { inUrl = lcScheme + matcher.group(2); } if (hasSpace) { inUrl = inUrl.replace(" ", "%20"); } return inUrl; } if (hasSpace) { // FIXME: Is this the correct place to add to searches? // what if someone else calls this function? int shortcut = parseUrlShortcut(inUrl); if (shortcut != SHORTCUT_INVALID) { Browser.addSearchUrl(mResolver, inUrl); String query = inUrl.substring(2); switch (shortcut) { case SHORTCUT_GOOGLE_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER); case SHORTCUT_WIKIPEDIA_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER); case SHORTCUT_DICTIONARY_SEARCH: return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER); case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH: // FIXME: we need location in this case return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER); } } } else { if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) { return URLUtil.guessUrl(inUrl); } } Browser.addSearchUrl(mResolver, inUrl); return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER); } /* package */ void setShouldShowErrorConsole(boolean flag) { if (flag == mShouldShowErrorConsole) { // Nothing to do. return; } mShouldShowErrorConsole = flag; ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true); if (flag) { // Setting the show state of the console will cause it's the layout to be inflated. if (errorConsole.numberOfErrors() > 0) { errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); } else { errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); } // Now we can add it to the main view. mErrorConsoleContainer.addView(errorConsole, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } else { mErrorConsoleContainer.removeView(errorConsole); } } final static int LOCK_ICON_UNSECURE = 0; final static int LOCK_ICON_SECURE = 1; final static int LOCK_ICON_MIXED = 2; private int mLockIconType = LOCK_ICON_UNSECURE; private int mPrevLockType = LOCK_ICON_UNSECURE; private BrowserSettings mSettings; private TabControl mTabControl; private ContentResolver mResolver; private FrameLayout mContentView; private View mCustomView; private FrameLayout mCustomViewContainer; private WebChromeClient.CustomViewCallback mCustomViewCallback; // FIXME, temp address onPrepareMenu performance problem. When we move everything out of // view, we should rewrite this. private int mCurrentMenuState = 0; private int mMenuState = R.id.MAIN_MENU; private int mOldMenuState = EMPTY_MENU; private static final int EMPTY_MENU = -1; private Menu mMenu; private FindDialog mFindDialog; // Used to prevent chording to result in firing two shortcuts immediately // one after another. Fixes bug 1211714. boolean mCanChord; private boolean mInLoad; private boolean mIsNetworkUp; private boolean mDidStopLoad; private boolean mPageStarted; private boolean mActivityInPause = true; private boolean mMenuIsDown; private static boolean mInTrace; // Performance probe private static final int[] SYSTEM_CPU_FORMAT = new int[] { Process.PROC_SPACE_TERM | Process.PROC_COMBINE, Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time }; private long mStart; private long mProcessStart; private long mUserStart; private long mSystemStart; private long mIdleStart; private long mIrqStart; private long mUiStart; private Drawable mMixLockIcon; private Drawable mSecLockIcon; /* hold a ref so we can auto-cancel if necessary */ private AlertDialog mAlertDialog; // Wait for credentials before loading google.com private ProgressDialog mCredsDlg; // The up-to-date URL and title (these can be different from those stored // in WebView, since it takes some time for the information in WebView to // get updated) private String mUrl; private String mTitle; // As PageInfo has different style for landscape / portrait, we have // to re-open it when configuration changed private AlertDialog mPageInfoDialog; private TabControl.Tab mPageInfoView; // If the Page-Info dialog is launched from the SSL-certificate-on-error // dialog, we should not just dismiss it, but should get back to the // SSL-certificate-on-error dialog. This flag is used to store this state private Boolean mPageInfoFromShowSSLCertificateOnError; // as SSLCertificateOnError has different style for landscape / portrait, // we have to re-open it when configuration changed private AlertDialog mSSLCertificateOnErrorDialog; private WebView mSSLCertificateOnErrorView; private SslErrorHandler mSSLCertificateOnErrorHandler; private SslError mSSLCertificateOnErrorError; // as SSLCertificate has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mSSLCertificateDialog; private TabControl.Tab mSSLCertificateView; // as HttpAuthentication has different style for landscape / portrait, we // have to re-open it when configuration changed private AlertDialog mHttpAuthenticationDialog; private HttpAuthHandler mHttpAuthHandler; /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER); // Google search final static String QuickSearch_G = "http://www.google.com/m?q=%s"; // Wikipedia search final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; // Dictionary search final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s"; // Google Mobile Local search final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view"; final static String QUERY_PLACE_HOLDER = "%s"; // "source" parameter for Google search through search key final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; // "source" parameter for Google search through goto menu final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto"; // "source" parameter for Google search through simplily type final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; // "source" parameter for Google search suggested by the browser final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; // "source" parameter for Google search from unknown source final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; private final static String LOGTAG = "browser"; private String mLastEnteredUrl; private PowerManager.WakeLock mWakeLock; private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes private Toast mStopToast; private TitleBar mTitleBar; private LinearLayout mErrorConsoleContainer = null; private boolean mShouldShowErrorConsole = false; // As the ids are dynamically created, we can't guarantee that they will // be in sequence, so this static array maps ids to a window number. final static private int[] WINDOW_SHORTCUT_ID_ARRAY = { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id, R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id, R.id.window_seven_menu_id, R.id.window_eight_menu_id }; // monitor platform changes private IntentFilter mNetworkStateChangedFilter; private BroadcastReceiver mNetworkStateIntentReceiver; private BroadcastReceiver mPackageInstallationReceiver; // AsyncTask for downloading touch icons /* package */ DownloadTouchIcon mTouchIconLoader; // activity requestCode final static int COMBO_PAGE = 1; final static int DOWNLOAD_PAGE = 2; final static int PREFERENCES_PAGE = 3; // the default <video> poster private Bitmap mDefaultVideoPoster; // the video progress view private View mVideoProgressView; /** * A UrlData class to abstract how the content will be set to WebView. * This base class uses loadUrl to show the content. */ private static class UrlData { String mUrl; byte[] mPostData; UrlData(String url) { this.mUrl = url; } void setPostData(byte[] postData) { mPostData = postData; } boolean isEmpty() { return mUrl == null || mUrl.length() == 0; } public void loadIn(WebView webView) { if (mPostData != null) { webView.postUrl(mUrl, mPostData); } else { webView.loadUrl(mUrl); } } }; /** * A subclass of UrlData class that can display inlined content using * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}. */ private static class InlinedUrlData extends UrlData { InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) { super(failUrl); mInlined = inlined; mMimeType = mimeType; mEncoding = encoding; } String mMimeType; String mInlined; String mEncoding; @Override boolean isEmpty() { return mInlined == null || mInlined.length() == 0 || super.isEmpty(); } @Override public void loadIn(WebView webView) { webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl); } } /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null); }
true
true
@Override public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } // // start MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //startService(proxyServiceIntent, null); mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo info = (NetworkInfo) intent.getParcelableExtra( ConnectivityManager.EXTRA_NETWORK_INFO); onNetworkToggle( (info != null) ? info.isConnected() : false); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final TabControl.Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } }
@Override public void onCreate(Bundle icicle) { if (LOGV_ENABLED) { Log.v(LOGTAG, this + " onStart"); } super.onCreate(icicle); // test the browser in OpenGL // requestWindowFeature(Window.FEATURE_OPENGL); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mResolver = getContentResolver(); // If this was a web search request, pass it on to the default web // search provider and finish this activity. if (handleWebSearchIntent(getIntent())) { finish(); return; } // // start MASF proxy service // //Intent proxyServiceIntent = new Intent(); //proxyServiceIntent.setComponent // (new ComponentName( // "com.android.masfproxyservice", // "com.android.masfproxyservice.MasfProxyService")); //startService(proxyServiceIntent, null); mSecLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_secure); mMixLockIcon = Resources.getSystem().getDrawable( android.R.drawable.ic_partial_secure); FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() .findViewById(com.android.internal.R.id.content); mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) .inflate(R.layout.custom_screen, null); mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( R.id.main_content); mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout .findViewById(R.id.error_console); mCustomViewContainer = (FrameLayout) mBrowserFrameLayout .findViewById(R.id.fullscreen_custom_content); frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); mTitleBar = new TitleBar(this); // Create the tab control and our initial tab mTabControl = new TabControl(this); // Open the icon database and retain all the bookmark urls for favicons retainIconsOnStartup(); // Keep a settings instance handy. mSettings = BrowserSettings.getInstance(); mSettings.setTabControl(mTabControl); mSettings.loadFromDb(this); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); /* enables registration for changes in network status from http stack */ mNetworkStateChangedFilter = new IntentFilter(); mNetworkStateChangedFilter.addAction( ConnectivityManager.CONNECTIVITY_ACTION); mNetworkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( ConnectivityManager.CONNECTIVITY_ACTION)) { boolean noConnectivity = intent.getBooleanExtra( ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); onNetworkToggle(!noConnectivity); } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addDataScheme("package"); mPackageInstallationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); final String packageName = intent.getData() .getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra( Intent.EXTRA_REPLACING, false); if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { // if it is replacing, refreshPlugins() when adding return; } PackageManager pm = BrowserActivity.this.getPackageManager(); PackageInfo pkgInfo = null; try { pkgInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS); } catch (PackageManager.NameNotFoundException e) { return; } if (pkgInfo != null) { String permissions[] = pkgInfo.requestedPermissions; if (permissions == null) { return; } boolean permissionOk = false; for (String permit : permissions) { if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { permissionOk = true; break; } } if (permissionOk) { PluginManager.getInstance(BrowserActivity.this) .refreshPlugins( Intent.ACTION_PACKAGE_ADDED .equals(action)); } } } }; registerReceiver(mPackageInstallationReceiver, filter); if (!mTabControl.restoreState(icicle)) { // clear up the thumbnail directory if we can't restore the state as // none of the files in the directory are referenced any more. new ClearThumbnails().execute( mTabControl.getThumbnailDir().listFiles()); // there is no quit on Android. But if we can't restore the state, // we can treat it as a new Browser, remove the old session cookies. CookieManager.getInstance().removeSessionCookie(); final Intent intent = getIntent(); final Bundle extra = intent.getExtras(); // Create an initial tab. // If the intent is ACTION_VIEW and data is not null, the Browser is // invoked to view the content by another application. In this case, // the tab will be close when exit. UrlData urlData = getUrlDataFromIntent(intent); final TabControl.Tab t = mTabControl.createNewTab( Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null, intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl); mTabControl.setCurrentTab(t); attachTabToContentView(t); WebView webView = t.getWebView(); if (extra != null) { int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); if (scale > 0 && scale <= 1000) { webView.setInitialScale(scale); } } // If we are not restoring from an icicle, then there is a high // likely hood this is the first run. So, check to see if the // homepage needs to be configured and copy any plugins from our // asset directory to the data partition. if ((extra == null || !extra.getBoolean("testing")) && !mSettings.isLoginInitialized()) { setupHomePage(); } if (urlData.isEmpty()) { if (mSettings.isLoginInitialized()) { webView.loadUrl(mSettings.getHomePage()); } else { waitForCredentials(); } } else { if (extra != null) { urlData.setPostData(extra .getByteArray(Browser.EXTRA_POST_DATA)); } urlData.loadIn(webView); } } else { // TabControl.restoreState() will create a new tab even if // restoring the state fails. attachTabToContentView(mTabControl.getCurrentTab()); } // Read JavaScript flags if it exists. String jsFlags = mSettings.getJsFlags(); if (jsFlags.trim().length() != 0) { mTabControl.getCurrentWebView().setJsFlags(jsFlags); } }
diff --git a/Average_Calc/Average_Calc.java b/Average_Calc/Average_Calc.java index 08dac74..5e381a6 100644 --- a/Average_Calc/Average_Calc.java +++ b/Average_Calc/Average_Calc.java @@ -1,32 +1,32 @@ /* Author: Kyle Disc: Average_Calc :: finds the sum on num1, ... num5 and then displayes it to the user via. PrintLN. Creation: Sep. 10, 2013 Laste edit: 4:25 ET */ import java.io.*; import java.util.*; public class Average_Calc { - public static void main (String args[]) - { - //add floats, num1, ... num5, ADV, sum - float num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, ADV = 0, sum = 0; - //add Scaner - Scanner keyboard = new Scanner (System.in); + public static void main (String args[]) + { + //add floats, num1, ... num5, ADV, sum + float num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, ADV = 0, sum = 0; + //add Scaner + Scanner keyboard = new Scanner (System.in); // - System.out.println("Welcome!\n"); - System.out.println("Number 1: "); + System.out.println("Welcome!\n"); + System.out.println("Number 1: "); num1 = keyboard.nextFloat(); //get num1 System.out.println("Number 2: "); num2 = keyboard.nextFloat(); //get num2 System.out.println("Number 3: "); num3 = keyboard.nextFloat(); //get num 3 System.out.println("Number 4: "); num4 = keyboard.nextFloat(); //get num 4 System.out.println("Number 5: "); num5 = keyboard.nextFloat(); //get num 5 sum = num1 + num2 + num3 + num4 + num5; //set sum. add num1, to num5 together. ADV = sum / 5; //get ADV. Divide sum by 5 for the Adv. System.out.println("Sum was: "+sum +". Average was "+ADV +"."); } //end main } //end class
false
true
public static void main (String args[]) { //add floats, num1, ... num5, ADV, sum float num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, ADV = 0, sum = 0; //add Scaner Scanner keyboard = new Scanner (System.in); // System.out.println("Welcome!\n"); System.out.println("Number 1: "); num1 = keyboard.nextFloat(); //get num1 System.out.println("Number 2: "); num2 = keyboard.nextFloat(); //get num2 System.out.println("Number 3: "); num3 = keyboard.nextFloat(); //get num 3 System.out.println("Number 4: "); num4 = keyboard.nextFloat(); //get num 4 System.out.println("Number 5: "); num5 = keyboard.nextFloat(); //get num 5 sum = num1 + num2 + num3 + num4 + num5; //set sum. add num1, to num5 together. ADV = sum / 5; //get ADV. Divide sum by 5 for the Adv. System.out.println("Sum was: "+sum +". Average was "+ADV +"."); } //end main
public static void main (String args[]) { //add floats, num1, ... num5, ADV, sum float num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, ADV = 0, sum = 0; //add Scaner Scanner keyboard = new Scanner (System.in); // System.out.println("Welcome!\n"); System.out.println("Number 1: "); num1 = keyboard.nextFloat(); //get num1 System.out.println("Number 2: "); num2 = keyboard.nextFloat(); //get num2 System.out.println("Number 3: "); num3 = keyboard.nextFloat(); //get num 3 System.out.println("Number 4: "); num4 = keyboard.nextFloat(); //get num 4 System.out.println("Number 5: "); num5 = keyboard.nextFloat(); //get num 5 sum = num1 + num2 + num3 + num4 + num5; //set sum. add num1, to num5 together. ADV = sum / 5; //get ADV. Divide sum by 5 for the Adv. System.out.println("Sum was: "+sum +". Average was "+ADV +"."); } //end main
diff --git a/aciitemeditor/src/main/java/org/apache/directory/studio/aciitemeditor/model/ProtectedItemWrapper.java b/aciitemeditor/src/main/java/org/apache/directory/studio/aciitemeditor/model/ProtectedItemWrapper.java index 49a068f25..3e4600eb5 100644 --- a/aciitemeditor/src/main/java/org/apache/directory/studio/aciitemeditor/model/ProtectedItemWrapper.java +++ b/aciitemeditor/src/main/java/org/apache/directory/studio/aciitemeditor/model/ProtectedItemWrapper.java @@ -1,407 +1,409 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.aciitemeditor.model; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.naming.NamingException; import javax.naming.directory.Attribute; import org.apache.directory.shared.ldap.aci.ACIItemParser; import org.apache.directory.shared.ldap.aci.ItemFirstACIItem; import org.apache.directory.shared.ldap.aci.ProtectedItem; import org.apache.directory.studio.valueeditors.AbstractDialogStringValueEditor; import org.eclipse.osgi.util.NLS; /** * The ProtectedItemWrapper is used as input for the table viewer. * The protected item values are always stored as raw string value. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class ProtectedItemWrapper { /** This map contains all possible protected item identifiers */ public static final Map<Class<? extends ProtectedItem>, String> classToIdentifierMap; static { Map<Class<? extends ProtectedItem>, String> map = new HashMap<Class<? extends ProtectedItem>, String>(); map.put( ProtectedItem.Entry.class, "entry" ); //$NON-NLS-1$ map.put( ProtectedItem.AllUserAttributeTypes.class, "allUserAttributeTypes" ); //$NON-NLS-1$ map.put( ProtectedItem.AttributeType.class, "attributeType" ); //$NON-NLS-1$ map.put( ProtectedItem.AllAttributeValues.class, "allAttributeValues" ); //$NON-NLS-1$ map.put( ProtectedItem.AllUserAttributeTypesAndValues.class, "allUserAttributeTypesAndValues" ); //$NON-NLS-1$ map.put( ProtectedItem.AttributeValue.class, "attributeValue" ); //$NON-NLS-1$ map.put( ProtectedItem.SelfValue.class, "selfValue" ); //$NON-NLS-1$ map.put( ProtectedItem.RangeOfValues.class, "rangeOfValues" ); //$NON-NLS-1$ map.put( ProtectedItem.MaxValueCount.class, "maxValueCount" ); //$NON-NLS-1$ map.put( ProtectedItem.MaxImmSub.class, "maxImmSub" ); //$NON-NLS-1$ map.put( ProtectedItem.RestrictedBy.class, "restrictedBy" ); //$NON-NLS-1$ map.put( ProtectedItem.Classes.class, "classes" ); //$NON-NLS-1$ classToIdentifierMap = Collections.unmodifiableMap( map ); } /** This map contains all protected item display values */ public static final Map<Class<? extends ProtectedItem>, String> classToDisplayMap; static { Map<Class<? extends ProtectedItem>, String> map = new HashMap<Class<? extends ProtectedItem>, String>(); map.put( ProtectedItem.Entry.class, Messages.getString( "ProtectedItemWrapper.protectedItem.entry.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.AllUserAttributeTypes.class, Messages .getString( "ProtectedItemWrapper.protectedItem.allUserAttributeTypes.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.AttributeType.class, Messages .getString( "ProtectedItemWrapper.protectedItem.attributeType.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.AllAttributeValues.class, Messages .getString( "ProtectedItemWrapper.protectedItem.allAttributeValues.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.AllUserAttributeTypesAndValues.class, Messages .getString( "ProtectedItemWrapper.protectedItem.allUserAttributeTypesAndValues.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.AttributeValue.class, Messages .getString( "ProtectedItemWrapper.protectedItem.attributeValue.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.SelfValue.class, Messages .getString( "ProtectedItemWrapper.protectedItem.selfValue.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.RangeOfValues.class, Messages .getString( "ProtectedItemWrapper.protectedItem.rangeOfValues.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.MaxValueCount.class, Messages .getString( "ProtectedItemWrapper.protectedItem.maxValueCount.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.MaxImmSub.class, Messages .getString( "ProtectedItemWrapper.protectedItem.maxImmSub.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.RestrictedBy.class, Messages .getString( "ProtectedItemWrapper.protectedItem.restrictedBy.label" ) ); //$NON-NLS-1$ map.put( ProtectedItem.Classes.class, Messages.getString( "ProtectedItemWrapper.protectedItem.classes.label" ) ); //$NON-NLS-1$ classToDisplayMap = Collections.unmodifiableMap( map ); } /** A dummy ACI to check syntax of the protectedItemValue */ private static final String DUMMY = "{ identificationTag \"id1\", precedence 1, authenticationLevel simple, " //$NON-NLS-1$ + "itemOrUserFirst itemFirst: { protectedItems { #identifier# #values# }, " //$NON-NLS-1$ + "itemPermissions { { userClasses { allUsers }, grantsAndDenials { grantRead } } } } }"; //$NON-NLS-1$ /** The class of the protected item, never null. */ private final Class<? extends ProtectedItem> clazz; /** The protected item values, may be empty. */ private List<String> values; /** The value prefix, prepended to the value. */ private String valuePrefix; /** The value suffix, appended to the value. */ private String valueSuffix; /** The value editor, null means no value. */ private AbstractDialogStringValueEditor valueEditor; /** The multivalued. */ private boolean isMultivalued; /** * Creates a new instance of ProtectedItemWrapper. * * @param clazz the java class of the UserClass * @param isMultivalued the is multivalued * @param valuePrefix the identifier * @param valueSuffix the dislpay name * @param valueEditor the value editor */ public ProtectedItemWrapper( Class<? extends ProtectedItem> clazz, boolean isMultivalued, String valuePrefix, String valueSuffix, AbstractDialogStringValueEditor valueEditor ) { this.clazz = clazz; this.isMultivalued = isMultivalued; this.valuePrefix = valuePrefix; this.valueSuffix = valueSuffix; this.valueEditor = valueEditor; this.values = new ArrayList<String>(); } /** * Creates a new protected item object. Therefore it uses the * dummy ACI, injects the protected item and its value, parses * the ACI and extracts the protected item from the parsed bean. * * @return the parsed protected item * * @throws ParseException if parsing fails */ public ProtectedItem getProtectedItem() throws ParseException { String flatValue = getFlatValue(); String spec = DUMMY; spec = spec.replaceAll( "#identifier#", getIdentifier() ); //$NON-NLS-1$ spec = spec.replaceAll( "#values#", flatValue ); //$NON-NLS-1$ ACIItemParser parser = new ACIItemParser( null ); ItemFirstACIItem aci = null; try { aci = ( ItemFirstACIItem ) parser.parse( spec ); } catch ( ParseException e ) { String msg = NLS .bind( Messages.getString( "ProtectedItemWrapper.error.message" ), new String[] { getIdentifier(), flatValue } ); //$NON-NLS-1$ throw new ParseException( msg, 0 ); } ProtectedItem item = aci.getProtectedItems().iterator().next(); return item; } /** * Sets the protected item. * * @param item the protected item */ public void setProtectedItem( ProtectedItem item ) { assert item.getClass() == getClazz(); // first clear values values.clear(); // switch on userClass type // no value in ProtectedItem.Entry, ProtectedItem.AllUserAttributeTypes and ProtectedItem.AllUserAttributeTypesAndValues if ( item.getClass() == ProtectedItem.AttributeType.class ) { ProtectedItem.AttributeType at = ( ProtectedItem.AttributeType ) item; for ( Iterator<String> it = at.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AllAttributeValues.class ) { ProtectedItem.AllAttributeValues aav = ( ProtectedItem.AllAttributeValues ) item; for ( Iterator<String> it = aav.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AttributeValue.class ) { ProtectedItem.AttributeValue av = ( ProtectedItem.AttributeValue ) item; for ( Iterator<Attribute> it = av.iterator(); it.hasNext(); ) { Attribute attribute = it.next(); try { values.add( attribute.getID() + "=" + attribute.get() ); //$NON-NLS-1$ } catch ( NamingException e ) { } } } else if ( item.getClass() == ProtectedItem.SelfValue.class ) { ProtectedItem.SelfValue sv = ( ProtectedItem.SelfValue ) item; for ( Iterator<String> it = sv.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.RangeOfValues.class ) { ProtectedItem.RangeOfValues rov = ( ProtectedItem.RangeOfValues ) item; values.add( rov.getFilter().toString() ); } else if ( item.getClass() == ProtectedItem.MaxValueCount.class ) { ProtectedItem.MaxValueCount mvc = ( ProtectedItem.MaxValueCount ) item; for ( Iterator<ProtectedItem.MaxValueCountItem> it = mvc.iterator(); it.hasNext(); ) { ProtectedItem.MaxValueCountItem mvci = it.next(); values.add( mvci.toString() ); } } else if ( item.getClass() == ProtectedItem.MaxImmSub.class ) { ProtectedItem.MaxImmSub mis = ( ProtectedItem.MaxImmSub ) item; values.add( Integer.toString( mis.getValue() ) ); } else if ( item.getClass() == ProtectedItem.RestrictedBy.class ) { ProtectedItem.RestrictedBy rb = ( ProtectedItem.RestrictedBy ) item; for ( Iterator<ProtectedItem.RestrictedByItem> it = rb.iterator(); it.hasNext(); ) { ProtectedItem.RestrictedByItem rbi = it.next(); values.add( rbi.toString() ); } } else if ( item.getClass() == ProtectedItem.Classes.class ) { ProtectedItem.Classes classes = ( ProtectedItem.Classes ) item; - values.add( classes.toString() ); + StringBuilder sb = new StringBuilder(); + classes.getClasses().printRefinementToBuffer( sb ); + values.add( sb.toString() ); } } /** * Returns a user-friedly string, displayed in the table. * * @return the string */ public String toString() { String flatValue = getFlatValue(); if ( flatValue.length() > 0 ) { flatValue = flatValue.replace( '\r', ' ' ); flatValue = flatValue.replace( '\n', ' ' ); flatValue = ": " + flatValue; //$NON-NLS-1$ if ( flatValue.length() > 40 ) { String temp = flatValue; flatValue = temp.substring( 0, 20 ); flatValue = flatValue + "..."; //$NON-NLS-1$ flatValue = flatValue + temp.substring( temp.length() - 20, temp.length() ); } } return getDisplayName() + " " + flatValue; //$NON-NLS-1$ } /** * Returns the flat value. * * @return the flat value */ private String getFlatValue() { if ( valueEditor == null || values.isEmpty() ) { return ""; //$NON-NLS-1$ } StringBuffer sb = new StringBuffer(); if ( isMultivalued() ) { sb.append( "{ " ); //$NON-NLS-1$ } for ( Iterator<String> it = values.iterator(); it.hasNext(); ) { sb.append( valuePrefix ); String value = it.next(); sb.append( value ); sb.append( valueSuffix ); if ( it.hasNext() ) { sb.append( ", " ); //$NON-NLS-1$ } } if ( isMultivalued() ) { sb.append( " }" ); //$NON-NLS-1$ } return sb.toString(); } /** * Returns the list of values, may be modified. * * @return the modifiable list of values. */ public List<String> getValues() { return values; } /** * Gets the display name. * * @return the display name */ public String getDisplayName() { return classToDisplayMap.get( clazz ); } /** * Gets the identifier. * * @return the identifier */ public String getIdentifier() { return classToIdentifierMap.get( clazz ); } /** * Returns the class of the user class. * * @return the class of the user class. */ public Class<? extends ProtectedItem> getClazz() { return clazz; } /** * Checks if is editable. * * @return true, if is editable */ public boolean isEditable() { return valueEditor != null; } /** * Gets the value editor. * * @return the value editor, may be null. */ public AbstractDialogStringValueEditor getValueEditor() { return valueEditor; } /** * Checks if is multivalued. * * @return true, if is multivalued */ public boolean isMultivalued() { return isMultivalued; } }
true
true
public void setProtectedItem( ProtectedItem item ) { assert item.getClass() == getClazz(); // first clear values values.clear(); // switch on userClass type // no value in ProtectedItem.Entry, ProtectedItem.AllUserAttributeTypes and ProtectedItem.AllUserAttributeTypesAndValues if ( item.getClass() == ProtectedItem.AttributeType.class ) { ProtectedItem.AttributeType at = ( ProtectedItem.AttributeType ) item; for ( Iterator<String> it = at.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AllAttributeValues.class ) { ProtectedItem.AllAttributeValues aav = ( ProtectedItem.AllAttributeValues ) item; for ( Iterator<String> it = aav.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AttributeValue.class ) { ProtectedItem.AttributeValue av = ( ProtectedItem.AttributeValue ) item; for ( Iterator<Attribute> it = av.iterator(); it.hasNext(); ) { Attribute attribute = it.next(); try { values.add( attribute.getID() + "=" + attribute.get() ); //$NON-NLS-1$ } catch ( NamingException e ) { } } } else if ( item.getClass() == ProtectedItem.SelfValue.class ) { ProtectedItem.SelfValue sv = ( ProtectedItem.SelfValue ) item; for ( Iterator<String> it = sv.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.RangeOfValues.class ) { ProtectedItem.RangeOfValues rov = ( ProtectedItem.RangeOfValues ) item; values.add( rov.getFilter().toString() ); } else if ( item.getClass() == ProtectedItem.MaxValueCount.class ) { ProtectedItem.MaxValueCount mvc = ( ProtectedItem.MaxValueCount ) item; for ( Iterator<ProtectedItem.MaxValueCountItem> it = mvc.iterator(); it.hasNext(); ) { ProtectedItem.MaxValueCountItem mvci = it.next(); values.add( mvci.toString() ); } } else if ( item.getClass() == ProtectedItem.MaxImmSub.class ) { ProtectedItem.MaxImmSub mis = ( ProtectedItem.MaxImmSub ) item; values.add( Integer.toString( mis.getValue() ) ); } else if ( item.getClass() == ProtectedItem.RestrictedBy.class ) { ProtectedItem.RestrictedBy rb = ( ProtectedItem.RestrictedBy ) item; for ( Iterator<ProtectedItem.RestrictedByItem> it = rb.iterator(); it.hasNext(); ) { ProtectedItem.RestrictedByItem rbi = it.next(); values.add( rbi.toString() ); } } else if ( item.getClass() == ProtectedItem.Classes.class ) { ProtectedItem.Classes classes = ( ProtectedItem.Classes ) item; values.add( classes.toString() ); } }
public void setProtectedItem( ProtectedItem item ) { assert item.getClass() == getClazz(); // first clear values values.clear(); // switch on userClass type // no value in ProtectedItem.Entry, ProtectedItem.AllUserAttributeTypes and ProtectedItem.AllUserAttributeTypesAndValues if ( item.getClass() == ProtectedItem.AttributeType.class ) { ProtectedItem.AttributeType at = ( ProtectedItem.AttributeType ) item; for ( Iterator<String> it = at.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AllAttributeValues.class ) { ProtectedItem.AllAttributeValues aav = ( ProtectedItem.AllAttributeValues ) item; for ( Iterator<String> it = aav.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.AttributeValue.class ) { ProtectedItem.AttributeValue av = ( ProtectedItem.AttributeValue ) item; for ( Iterator<Attribute> it = av.iterator(); it.hasNext(); ) { Attribute attribute = it.next(); try { values.add( attribute.getID() + "=" + attribute.get() ); //$NON-NLS-1$ } catch ( NamingException e ) { } } } else if ( item.getClass() == ProtectedItem.SelfValue.class ) { ProtectedItem.SelfValue sv = ( ProtectedItem.SelfValue ) item; for ( Iterator<String> it = sv.iterator(); it.hasNext(); ) { values.add( it.next() ); } } else if ( item.getClass() == ProtectedItem.RangeOfValues.class ) { ProtectedItem.RangeOfValues rov = ( ProtectedItem.RangeOfValues ) item; values.add( rov.getFilter().toString() ); } else if ( item.getClass() == ProtectedItem.MaxValueCount.class ) { ProtectedItem.MaxValueCount mvc = ( ProtectedItem.MaxValueCount ) item; for ( Iterator<ProtectedItem.MaxValueCountItem> it = mvc.iterator(); it.hasNext(); ) { ProtectedItem.MaxValueCountItem mvci = it.next(); values.add( mvci.toString() ); } } else if ( item.getClass() == ProtectedItem.MaxImmSub.class ) { ProtectedItem.MaxImmSub mis = ( ProtectedItem.MaxImmSub ) item; values.add( Integer.toString( mis.getValue() ) ); } else if ( item.getClass() == ProtectedItem.RestrictedBy.class ) { ProtectedItem.RestrictedBy rb = ( ProtectedItem.RestrictedBy ) item; for ( Iterator<ProtectedItem.RestrictedByItem> it = rb.iterator(); it.hasNext(); ) { ProtectedItem.RestrictedByItem rbi = it.next(); values.add( rbi.toString() ); } } else if ( item.getClass() == ProtectedItem.Classes.class ) { ProtectedItem.Classes classes = ( ProtectedItem.Classes ) item; StringBuilder sb = new StringBuilder(); classes.getClasses().printRefinementToBuffer( sb ); values.add( sb.toString() ); } }
diff --git a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java index dc8a8f627..5f215dcf6 100644 --- a/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java +++ b/apps/i2ptunnel/java/src/net/i2p/i2ptunnel/I2PTunnelHTTPClient.java @@ -1,1047 +1,1062 @@ /* I2PTunnel is GPL'ed (with the exception mentioned in I2PTunnel.java) * (c) 2003 - 2004 mihi */ package net.i2p.i2ptunnel; import java.io.ByteArrayOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; import net.i2p.I2PAppContext; import net.i2p.I2PException; import net.i2p.client.streaming.I2PSocket; import net.i2p.client.streaming.I2PSocketManager; import net.i2p.client.streaming.I2PSocketOptions; import net.i2p.data.Base32; import net.i2p.data.DataFormatException; import net.i2p.data.DataHelper; import net.i2p.data.Destination; import net.i2p.util.EventDispatcher; import net.i2p.util.FileUtil; import net.i2p.util.Log; import net.i2p.util.Translate; /** * Act as a mini HTTP proxy, handling various different types of requests, * forwarding them through I2P appropriately, and displaying the reply. Supported * request formats are: <pre> * $method http://$site[$port]/$path $protocolVersion * or * $method $path $protocolVersion\nHost: $site * or * $method http://i2p/$b64key/$path $protocolVersion * or * $method /$site/$path $protocolVersion * or (deprecated) * $method /eepproxy/$site/$path $protocolVersion * </pre> * * Note that http://i2p/$b64key/... and /eepproxy/$site/... are not recommended * in browsers or other user-visible applications, as relative links will not * resolve correctly, cookies won't work, etc. * * If the $site resolves with the I2P naming service, then it is directed towards * that eepsite, otherwise it is directed towards this client's outproxy (typically * "squid.i2p"). Only HTTP is supported (no HTTPS, ftp, mailto, etc). Both GET * and POST have been tested, though other $methods should work. * */ public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable { private static final Log _log = new Log(I2PTunnelHTTPClient.class); protected final List proxyList = new ArrayList(); private HashMap addressHelpers = new HashMap(); /** * These are backups if the xxx.ht error page is missing. */ private final static byte[] ERR_REQUEST_DENIED = ("HTTP/1.1 403 Access Denied\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+ "You attempted to connect to a non-I2P website or location.<BR>") .getBytes(); private final static byte[] ERR_DESTINATION_UNKNOWN = ("HTTP/1.1 503 Service Unavailable\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: DESTINATION NOT FOUND</H1>"+ "That I2P Destination was not found. Perhaps you pasted in the "+ "wrong BASE64 I2P Destination or the link you are following is "+ "bad. The host (or the WWW proxy, if you're using one) could also "+ "be temporarily offline. You may want to <b>retry</b>. "+ "Could not find the following Destination:<BR><BR><div>") .getBytes(); /***** private final static byte[] ERR_TIMEOUT = ("HTTP/1.1 504 Gateway Timeout\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n\r\n"+ "<html><body><H1>I2P ERROR: TIMEOUT</H1>"+ "That Destination was reachable, but timed out getting a "+ "response. This is likely a temporary error, so you should simply "+ "try to refresh, though if the problem persists, the remote "+ "destination may have issues. Could not get a response from "+ "the following Destination:<BR><BR>") .getBytes(); *****/ private final static byte[] ERR_NO_OUTPROXY = ("HTTP/1.1 503 Service Unavailable\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: No outproxy found</H1>"+ "Your request was for a site outside of I2P, but you have no "+ "HTTP outproxy configured. Please configure an outproxy in I2PTunnel") .getBytes(); private final static byte[] ERR_AHELPER_CONFLICT = ("HTTP/1.1 409 Conflict\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: Destination key conflict</H1>"+ "The addresshelper link you followed specifies a different destination key "+ "than a host entry in your host database. "+ "Someone could be trying to impersonate another eepsite, "+ "or people have given two eepsites identical names.<p>"+ "You can resolve the conflict by considering which key you trust, "+ "and either discarding the addresshelper link, "+ "discarding the host entry from your host database, "+ "or naming one of them differently.<p>") .getBytes(); private final static byte[] ERR_BAD_PROTOCOL = ("HTTP/1.1 403 Bad Protocol\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: NON-HTTP PROTOCOL</H1>"+ "The request uses a bad protocol. "+ "The I2P HTTP Proxy supports http:// requests ONLY. Other protocols such as https:// and ftp:// are not allowed.<BR>") .getBytes(); private final static byte[] ERR_LOCALHOST = ("HTTP/1.1 403 Access Denied\r\n"+ "Content-Type: text/html; charset=iso-8859-1\r\n"+ "Cache-control: no-cache\r\n"+ "\r\n"+ "<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+ "Your browser is misconfigured. Do not use the proxy to access the router console or other localhost destinations.<BR>") .getBytes(); /** used to assign unique IDs to the threads / clients. no logic or functionality */ private static volatile long __clientId = 0; private static final File _errorDir = new File(I2PAppContext.getGlobalContext().getBaseDir(), "docs"); public I2PTunnelHTTPClient(int localPort, Logging l, I2PSocketManager sockMgr, I2PTunnel tunnel, EventDispatcher notifyThis, long clientId) { super(localPort, l, sockMgr, tunnel, notifyThis, clientId); // proxyList = new ArrayList(); setName(getLocalPort() + " -> HTTPClient [NO PROXIES]"); startRunning(); notifyEvent("openHTTPClientResult", "ok"); } /** * @throws IllegalArgumentException if the I2PTunnel does not contain * valid config to contact the router */ public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest, String wwwProxy, EventDispatcher notifyThis, I2PTunnel tunnel) throws IllegalArgumentException { super(localPort, ownDest, l, notifyThis, "HTTPHandler " + (++__clientId), tunnel); //proxyList = new ArrayList(); // We won't use outside of i2p if (waitEventValue("openBaseClientResult").equals("error")) { notifyEvent("openHTTPClientResult", "error"); return; } if (wwwProxy != null) { StringTokenizer tok = new StringTokenizer(wwwProxy, ", "); while (tok.hasMoreTokens()) proxyList.add(tok.nextToken().trim()); } setName(getLocalPort() + " -> HTTPClient [WWW outproxy list: " + wwwProxy + "]"); startRunning(); notifyEvent("openHTTPClientResult", "ok"); } private String getPrefix(long requestId) { return "Client[" + _clientId + "/" + requestId + "]: "; } private String selectProxy() { synchronized (proxyList) { int size = proxyList.size(); if (size <= 0) { if (_log.shouldLog(Log.INFO)) _log.info("Proxy list is empty - no outproxy available"); l.log("Proxy list is emtpy - no outproxy available"); return null; } int index = I2PAppContext.getGlobalContext().random().nextInt(size); String proxy = (String)proxyList.get(index); return proxy; } } private static final int DEFAULT_READ_TIMEOUT = 60*1000; /** * create the default options (using the default timeout, etc) * unused? */ @Override protected I2PSocketOptions getDefaultOptions() { Properties defaultOpts = getTunnel().getClientOptions(); if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT)) defaultOpts.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, ""+DEFAULT_READ_TIMEOUT); //if (!defaultOpts.contains("i2p.streaming.inactivityTimeout")) // defaultOpts.setProperty("i2p.streaming.inactivityTimeout", ""+DEFAULT_READ_TIMEOUT); I2PSocketOptions opts = sockMgr.buildOptions(defaultOpts); if (!defaultOpts.containsKey(I2PSocketOptions.PROP_CONNECT_TIMEOUT)) opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); return opts; } /** * create the default options (using the default timeout, etc) * */ @Override protected I2PSocketOptions getDefaultOptions(Properties overrides) { Properties defaultOpts = getTunnel().getClientOptions(); defaultOpts.putAll(overrides); if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT)) defaultOpts.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, ""+DEFAULT_READ_TIMEOUT); if (!defaultOpts.contains("i2p.streaming.inactivityTimeout")) defaultOpts.setProperty("i2p.streaming.inactivityTimeout", ""+DEFAULT_READ_TIMEOUT); // delayed start verifySocketManager(); I2PSocketOptions opts = sockMgr.buildOptions(defaultOpts); if (!defaultOpts.containsKey(I2PSocketOptions.PROP_CONNECT_TIMEOUT)) opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); return opts; } private InternalSocketRunner isr; /** * Actually start working on incoming connections. * Overridden to start an internal socket too. * */ @Override public void startRunning() { super.startRunning(); this.isr = new InternalSocketRunner(this); } /** * Overridden to close internal socket too. */ @Override public boolean close(boolean forced) { boolean rv = super.close(forced); if (this.isr != null) this.isr.stopRunning(); return rv; } private static final boolean DEFAULT_GZIP = true; // all default to false public static final String PROP_REFERER = "i2ptunnel.httpclient.sendReferer"; public static final String PROP_USER_AGENT = "i2ptunnel.httpclient.sendUserAgent"; public static final String PROP_VIA = "i2ptunnel.httpclient.sendVia"; public static final String PROP_JUMP_SERVERS = "i2ptunnel.httpclient.jumpServers"; private static long __requestId = 0; protected void clientConnectionRun(Socket s) { InputStream in = null; OutputStream out = null; String targetRequest = null; boolean usingWWWProxy = false; boolean usingInternalServer = false; String currentProxy = null; long requestId = ++__requestId; try { out = s.getOutputStream(); InputReader reader = new InputReader(s.getInputStream()); String line, method = null, protocol = null, host = null, destination = null; StringBuilder newRequest = new StringBuilder(); int ahelper = 0; while ((line = reader.readLine(method)) != null) { line = line.trim(); if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Line=[" + line + "]"); String lowercaseLine = line.toLowerCase(); if (lowercaseLine.startsWith("connection: ") || lowercaseLine.startsWith("keep-alive: ") || lowercaseLine.startsWith("proxy-connection: ")) continue; if (method == null) { // first line (GET /base64/realaddr) if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "First line [" + line + "]"); int pos = line.indexOf(" "); if (pos == -1) break; method = line.substring(0, pos); // TODO use Java URL class to make all this simpler and more robust // That will also fix IPV6 [a:b:c] String request = line.substring(pos + 1); if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) { // what is this for ??? request = "http://i2p" + request; } else if (request.startsWith("/eepproxy/")) { // /eepproxy/foo.i2p/bar/baz.html HTTP/1.0 String subRequest = request.substring("/eepproxy/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } else if (request.toLowerCase().startsWith("http://i2p/")) { // http://i2p/b64key/bar/baz.html HTTP/1.0 String subRequest = request.substring("http://i2p/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "b64key/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } pos = request.indexOf("//"); if (pos == -1) { method = null; break; } protocol = request.substring(0, pos + 2); request = request.substring(pos + 2); targetRequest = request; // pos is the start of the path pos = request.indexOf("/"); if (pos == -1) { method = null; break; } host = request.substring(0, pos); // parse port int posPort = host.indexOf(":"); int port = 80; if(posPort != -1) { String[] parts = host.split(":"); host = parts[0]; try { port = Integer.parseInt(parts[1]); } catch(Exception exc) { // TODO: log this } } // Go through the various types of host names, set // the host and destination variables accordingly, // and transform the first line. // For all i2p network hosts, ensure that the host is a // Base 32 hostname so that we do not reveal our name for it // in our addressbook (all naming is local), // and it is removed from the request line. if (host.length() >= 516 && host.indexOf(".") < 0) { // http://b64key/bar/baz.html destination = host; host = getHostName(destination); line = method + ' ' + request.substring(pos); } else if (host.toLowerCase().equals("proxy.i2p")) { // so we don't do any naming service lookups destination = host; usingInternalServer = true; } else if (host.toLowerCase().endsWith(".i2p")) { // Destination gets the host name destination = host; // Host becomes the destination key host = getHostName(destination); int pos2; if ((pos2 = request.indexOf("?")) != -1) { // Try to find an address helper in the fragments // and split the request into it's component parts for rebuilding later String ahelperKey = null; boolean ahelperConflict = false; String fragments = request.substring(pos2 + 1); String uriPath = request.substring(0, pos2); pos2 = fragments.indexOf(" "); String protocolVersion = fragments.substring(pos2 + 1); String urlEncoding = ""; fragments = fragments.substring(0, pos2); String initialFragments = fragments; fragments = fragments + "&"; String fragment; while(fragments.length() > 0) { pos2 = fragments.indexOf("&"); fragment = fragments.substring(0, pos2); fragments = fragments.substring(pos2 + 1); // Fragment looks like addresshelper key if (fragment.startsWith("i2paddresshelper=")) { pos2 = fragment.indexOf("="); ahelperKey = fragment.substring(pos2 + 1); // Key contains data, lets not ignore it if (ahelperKey != null) { + // ahelperKey will be validated later // Host resolvable only with addresshelper if ( (host == null) || ("i2p".equals(host)) ) { // Cannot check, use addresshelper key addressHelpers.put(destination,ahelperKey); } else { // Host resolvable from database, verify addresshelper key // Silently bypass correct keys, otherwise alert - if (!host.equals(ahelperKey)) + String destB64 = null; + try { + Destination dest = I2PTunnel.destFromName(host); + if (dest != null) + destB64 = dest.toBase64(); + } catch (DataFormatException dfe) {} + if (destB64 != null && !destB64.equals(ahelperKey)) { // Conflict: handle when URL reconstruction done ahelperConflict = true; if (_log.shouldLog(Log.WARN)) - _log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + host + "], specified key [" + ahelperKey + "]."); + _log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + destB64 + "], specified key [" + ahelperKey + "]."); } } } } else { // Other fragments, just pass along // Append each fragment to urlEncoding if ("".equals(urlEncoding)) { urlEncoding = "?" + fragment; } else { urlEncoding = urlEncoding + "&" + fragment; } } } // Reconstruct the request minus the i2paddresshelper GET var request = uriPath + urlEncoding + " " + protocolVersion; // Did addresshelper key conflict? if (ahelperConflict) { if (out != null) { - long alias = I2PAppContext.getGlobalContext().random().nextLong(); - String trustedURL = protocol + uriPath + urlEncoding; - String conflictURL = protocol + alias + ".i2p/?" + initialFragments; - byte[] header = getErrorPage("ahelper-conflict", ERR_AHELPER_CONFLICT); - out.write(header); - out.write(_("To visit the destination in your host database, click <a href=\"{0}\">here</a>. To visit the conflicting addresshelper link by temporarily giving it a random alias, click <a href=\"{1}\">here</a>.", trustedURL, conflictURL).getBytes("UTF-8")); - out.write(("<p></div>").getBytes()); - writeFooter(out); + // convert ahelperKey to b32 + String alias = getHostName(ahelperKey); + if (alias.equals("i2p")) { + // bad ahelperKey + byte[] header = getErrorPage("dnfb", ERR_DESTINATION_UNKNOWN); + writeErrorMessage(header, out, targetRequest, false, destination, null); + } else { + String trustedURL = protocol + uriPath + urlEncoding; + // Fixme - any path is lost + String conflictURL = protocol + alias + '/' + urlEncoding; + byte[] header = getErrorPage("ahelper-conflict", ERR_AHELPER_CONFLICT); + out.write(header); + out.write(_("To visit the destination in your host database, click <a href=\"{0}\">here</a>. To visit the conflicting addresshelper destination, click <a href=\"{1}\">here</a>.", trustedURL, conflictURL).getBytes("UTF-8")); + out.write(("<p></div>").getBytes()); + writeFooter(out); + } } s.close(); return; } } String addressHelper = (String) addressHelpers.get(destination); if (addressHelper != null) { destination = addressHelper; host = getHostName(destination); ahelper = 1; } line = method + " " + request.substring(pos); } else if (host.toLowerCase().equals("localhost") || host.equals("127.0.0.1")) { if (out != null) { out.write(getErrorPage("localhost", ERR_LOCALHOST)); writeFooter(out); } s.close(); return; } else if (host.indexOf(".") != -1) { // rebuild host host = host + ":" + port; // The request must be forwarded to a WWW proxy if (_log.shouldLog(Log.DEBUG)) _log.debug("Before selecting outproxy for " + host); currentProxy = selectProxy(); if (_log.shouldLog(Log.DEBUG)) _log.debug("After selecting outproxy for " + host + ": " + currentProxy); if (currentProxy == null) { if (_log.shouldLog(Log.WARN)) _log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!"); l.log("No HTTP outproxy found for the request."); if (out != null) { out.write(getErrorPage("noproxy", ERR_NO_OUTPROXY)); writeFooter(out); } s.close(); return; } destination = currentProxy; usingWWWProxy = true; if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!"); } else { // what is left for here? a hostname with no dots, and != "i2p" // and not a destination ??? // Perhaps something in privatehosts.txt ... request = request.substring(pos + 1); pos = request.indexOf("/"); if (pos < 0) { l.log("Invalid request url [" + request + "]"); if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } destination = request.substring(0, pos); host = getHostName(destination); line = method + " " + request.substring(pos); } // end host name processing if (port != 80 && !usingWWWProxy) { if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } boolean isValid = usingWWWProxy || usingInternalServer || isSupportedAddress(host, protocol); if (!isValid) { if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")"); method = null; destination = null; break; } // don't do this, it forces yet another hostname lookup, // and in all cases host was already set above //if ((!usingWWWProxy) && (!usingInternalServer)) { // String oldhost = host; // host = getHostName(destination); // hide original host // if (_log.shouldLog(Log.INFO)) // _log.info(getPrefix(requestId) + " oldhost " + oldhost + " newhost " + host + " dest " + destination); //} if (_log.shouldLog(Log.DEBUG)) { _log.debug(getPrefix(requestId) + "METHOD: \"" + method + "\""); _log.debug(getPrefix(requestId) + "PROTOC: \"" + protocol + "\""); _log.debug(getPrefix(requestId) + "HOST : \"" + host + "\""); _log.debug(getPrefix(requestId) + "DEST : \"" + destination + "\""); } // end first line processing } else { if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) { // Note that we only pass the original Host: line through to the outproxy // But we don't create a Host: line if it wasn't sent to us line = "Host: " + host; if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "Setting host = " + host); } else if (lowercaseLine.startsWith("user-agent: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) { line = null; continue; } else if (lowercaseLine.startsWith("accept")) { // strip the accept-blah headers, as they vary dramatically from // browser to browser line = null; continue; } else if (lowercaseLine.startsWith("referer: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) { // Shouldn't we be more specific, like accepting in-site referers ? //line = "Referer: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("via: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) { //line = "Via: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("from: ")) { //line = "From: i2p"; line = null; continue; // completely strip the line } } if (line.length() == 0) { String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip"); boolean gzip = DEFAULT_GZIP; if (ok != null) gzip = Boolean.valueOf(ok).booleanValue(); if (gzip && !usingInternalServer) { // according to rfc2616 s14.3, this *should* force identity, even if // an explicit q=0 for gzip doesn't. tested against orion.i2p, and it // seems to work. newRequest.append("Accept-Encoding: \r\n"); newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n"); } if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n"); newRequest.append("Connection: close\r\n\r\n"); break; } else { newRequest.append(line).append("\r\n"); // HTTP spec } } // end header processing if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]"); if (method == null || destination == null) { //l.log("No HTTP method found in the request."); if (out != null) { if ("http://".equalsIgnoreCase(protocol)) out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); else out.write(getErrorPage("protocol", ERR_BAD_PROTOCOL)); writeFooter(out); } s.close(); return; } if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Destination: " + destination); // Serve local proxy files (images, css linked from error pages) // Ignore all the headers if (usingInternalServer) { serveLocalFile(out, method, targetRequest); s.close(); return; } // If the host is "i2p", the getHostName() lookup failed, don't try to // look it up again as the naming service does not do negative caching // so it will be slow. Destination clientDest; if ("i2p".equals(host)) clientDest = null; else clientDest = I2PTunnel.destFromName(destination); if (clientDest == null) { //l.log("Could not resolve " + destination + "."); if (_log.shouldLog(Log.WARN)) _log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest); byte[] header; String jumpServers = null; if (usingWWWProxy) header = getErrorPage("dnfp", ERR_DESTINATION_UNKNOWN); else if(ahelper != 0) header = getErrorPage("dnfb", ERR_DESTINATION_UNKNOWN); else if (destination.length() == 60 && destination.endsWith(".b32.i2p")) header = getErrorPage("dnf", ERR_DESTINATION_UNKNOWN); else { header = getErrorPage("dnfh", ERR_DESTINATION_UNKNOWN); jumpServers = getTunnel().getClientOptions().getProperty(PROP_JUMP_SERVERS); if (jumpServers == null) jumpServers = DEFAULT_JUMP_SERVERS; } writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, jumpServers); s.close(); return; } String remoteID; Properties opts = new Properties(); //opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000); // 1 == disconnect. see ConnectionOptions in the new streaming lib, which i // dont want to hard link to here //opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1); I2PSocket i2ps = createI2PSocket(clientDest, getDefaultOptions(opts)); byte[] data = newRequest.toString().getBytes("ISO-8859-1"); Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId); I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout); } catch (SocketException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (IOException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (I2PException ex) { _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (OutOfMemoryError oom) { IOException ex = new IOException("OOM"); _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } } /** * Read the first line unbuffered. * After that, switch to a BufferedReader, unless the method is "POST". * We can't use BufferedReader for POST because we can't have readahead, * since we are passing the stream on to I2PTunnelRunner for the POST data. * */ private static class InputReader { BufferedReader _br; InputStream _s; public InputReader(InputStream s) { _br = null; _s = s; } String readLine(String method) throws IOException { if (method == null || "POST".equals(method)) return DataHelper.readLine(_s); if (_br == null) _br = new BufferedReader(new InputStreamReader(_s, "ISO-8859-1")); return _br.readLine(); } } /** * @return b32hash.b32.i2p, or "i2p" on lookup failure. * Prior to 0.7.12, returned b64 key */ private final static String getHostName(String host) { if (host == null) return null; if (host.length() == 60 && host.toLowerCase().endsWith(".b32.i2p")) return host; try { Destination dest = I2PTunnel.destFromName(host); if (dest == null) return "i2p"; return Base32.encode(dest.calculateHash().getData()) + ".b32.i2p"; } catch (DataFormatException dfe) { return "i2p"; } } /** * foo => errordir/foo-header_xx.ht for lang xx, or errordir/foo-header.ht, * or the backup byte array on fail. * * .ht files must be UTF-8 encoded and use \r\n terminators so the * HTTP headers are conformant. * We can't use FileUtil.readFile() because it strips \r * * @return non-null */ private byte[] getErrorPage(String base, byte[] backup) { return getErrorPage(getTunnel().getContext(), base, backup); } private static byte[] getErrorPage(I2PAppContext ctx, String base, byte[] backup) { File errorDir = new File(ctx.getBaseDir(), "docs"); String lang = ctx.getProperty("routerconsole.lang", Locale.getDefault().getLanguage()); if (lang != null && lang.length() > 0 && !lang.equals("en")) { File file = new File(errorDir, base + "-header_" + lang + ".ht"); try { return readFile(file); } catch (IOException ioe) { // try the english version now } } File file = new File(errorDir, base + "-header.ht"); try { return readFile(file); } catch (IOException ioe) { return backup; } } private static byte[] readFile(File file) throws IOException { FileInputStream fis = null; byte[] buf = new byte[512]; ByteArrayOutputStream baos = new ByteArrayOutputStream(2048); try { int len = 0; fis = new FileInputStream(file); while ((len = fis.read(buf)) > 0) { baos.write(buf, 0, len); } return baos.toByteArray(); } finally { try { if (fis != null) fis.close(); } catch (IOException foo) {} } // we won't ever get here } private static void writeFooter(OutputStream out) throws IOException { // the css is hiding this div for now, but we'll keep it here anyway out.write("<div class=\"proxyfooter\"><p><i>I2P HTTP Proxy Server<br>Generated on: ".getBytes()); out.write(new Date().toString().getBytes()); out.write("</i></div></body></html>\n".getBytes()); out.flush(); } private static class OnTimeout implements Runnable { private Socket _socket; private OutputStream _out; private String _target; private boolean _usingProxy; private String _wwwProxy; private long _requestId; public OnTimeout(Socket s, OutputStream out, String target, boolean usingProxy, String wwwProxy, long id) { _socket = s; _out = out; _target = target; _usingProxy = usingProxy; _wwwProxy = wwwProxy; _requestId = id; } public void run() { if (_log.shouldLog(Log.DEBUG)) _log.debug("Timeout occured requesting " + _target); handleHTTPClientException(new RuntimeException("Timeout"), _out, _target, _usingProxy, _wwwProxy, _requestId); closeSocket(_socket); } } private static String DEFAULT_JUMP_SERVERS = "http://i2host.i2p/cgi-bin/i2hostjump?," + "http://stats.i2p/cgi-bin/jump.cgi?a=," + "http://i2jump.i2p/"; /** * @param jumpServers comma- or space-separated list, or null */ private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy, String jumpServers) throws IOException { if (out != null) { out.write(errMessage); if (targetRequest != null) { int protopos = targetRequest.indexOf(" "); String uri = null; if (protopos >= 0) uri = targetRequest.substring(0, protopos); else uri = targetRequest; out.write("<a href=\"http://".getBytes()); out.write(uri.getBytes()); out.write("\">http://".getBytes()); out.write(uri.getBytes()); out.write("</a>".getBytes()); if (usingWWWProxy) out.write(("<br>WWW proxy: " + wwwProxy).getBytes()); if (jumpServers != null && jumpServers.length() > 0) { out.write("<br><br>".getBytes()); out.write(_("Click a link below to look for an address helper by using a \"jump\" service:").getBytes("UTF-8")); out.write("<br>".getBytes()); StringTokenizer tok = new StringTokenizer(jumpServers, ", "); while (tok.hasMoreTokens()) { String jurl = tok.nextToken(); if (!jurl.startsWith("http://")) continue; // Skip jump servers we don't know String jumphost = jurl.substring(7); // "http://" jumphost = jumphost.substring(0, jumphost.indexOf('/')); try { Destination dest = I2PTunnel.destFromName(jumphost); if (dest == null) continue; } catch (DataFormatException dfe) { continue; } out.write("<br><a href=\"".getBytes()); out.write(jurl.getBytes()); out.write(uri.getBytes()); out.write("\">".getBytes()); out.write(jurl.getBytes()); out.write(uri.getBytes()); out.write("</a>".getBytes()); } } } out.write("</div>".getBytes()); writeFooter(out); } } private static void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest, boolean usingWWWProxy, String wwwProxy, long requestId) { // static //if (_log.shouldLog(Log.WARN)) // _log.warn(getPrefix(requestId) + "Error sending to " + wwwProxy + " (proxy? " + usingWWWProxy + ", request: " + targetRequest, ex); if (out != null) { try { byte[] header; if (usingWWWProxy) header = getErrorPage(I2PAppContext.getGlobalContext(), "dnfp", ERR_DESTINATION_UNKNOWN); else header = getErrorPage(I2PAppContext.getGlobalContext(), "dnf", ERR_DESTINATION_UNKNOWN); writeErrorMessage(header, out, targetRequest, usingWWWProxy, wwwProxy, null); } catch (IOException ioe) { // static //_log.warn(getPrefix(requestId) + "Error writing out the 'destination was unknown' " + "message", ioe); } } else { // static //_log.warn(getPrefix(requestId) + "Client disconnected before we could say that destination " + "was unknown", ex); } } private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com", "i2p."}; /** @param host ignored */ private static boolean isSupportedAddress(String host, String protocol) { if ((host == null) || (protocol == null)) return false; /**** * Let's not look up the name _again_ * and now that host is a b32, this was failing * boolean found = false; String lcHost = host.toLowerCase(); for (int i = 0; i < SUPPORTED_HOSTS.length; i++) { if (SUPPORTED_HOSTS[i].equals(lcHost)) { found = true; break; } } if (!found) { try { Destination d = I2PTunnel.destFromName(host); if (d == null) return false; } catch (DataFormatException dfe) { } } ****/ return protocol.equalsIgnoreCase("http://"); } private final static byte[] ERR_404 = ("HTTP/1.1 404 Not Found\r\n"+ "Content-Type: text/plain\r\n"+ "\r\n"+ "HTTP Proxy local file not found") .getBytes(); /** * Very simple web server. * * Serve local files in the docs/ directory, for CSS and images in * error pages, using the reserved address proxy.i2p * (similar to p.p in privoxy). * This solves the problems with including links to the router console, * as assuming the router console is at 127.0.0.1 leads to broken * links if it isn't. * * Ignore all request headers (If-Modified-Since, etc.) * * There is basic protection here - * FileUtil.readFile() prevents traversal above the base directory - * but inproxy/gateway ops would be wise to block proxy.i2p to prevent * exposing the docs/ directory or perhaps other issues through * uncaught vulnerabilities. * Restrict to the /themes/ directory for now. * * @param targetRequest "proxy.i2p/themes/foo.png HTTP/1.1" */ private static void serveLocalFile(OutputStream out, String method, String targetRequest) { // a home page message for the curious... if (targetRequest.startsWith("proxy.i2p/ ")) { try { out.write(("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nCache-Control: max-age=86400\r\n\r\nI2P HTTP proxy OK").getBytes()); out.flush(); } catch (IOException ioe) {} return; } if ((method.equals("GET") || method.equals("HEAD")) && targetRequest.startsWith("proxy.i2p/themes/") && !targetRequest.contains("..")) { int space = targetRequest.indexOf(' '); String filename = null; try { filename = targetRequest.substring(17, space); // "proxy.i2p/themes/".length } catch (IndexOutOfBoundsException ioobe) {} // theme hack if (filename.startsWith("console/default/")) filename = filename.replaceFirst("default", I2PAppContext.getGlobalContext().getProperty("routerconsole.theme", "light")); File themesDir = new File(_errorDir, "themes"); File file = new File(themesDir, filename); if (file.exists() && !file.isDirectory()) { String type; if (filename.endsWith(".css")) type = "text/css"; else if (filename.endsWith(".ico")) type = "image/x-icon"; else if (filename.endsWith(".png")) type = "image/png"; else if (filename.endsWith(".jpg")) type = "image/jpeg"; else type = "text/html"; try { out.write("HTTP/1.1 200 OK\r\nContent-Type: ".getBytes()); out.write(type.getBytes()); out.write("\r\nCache-Control: max-age=86400\r\n\r\n".getBytes()); FileUtil.readFile(filename, themesDir.getAbsolutePath(), out); return; } catch (IOException ioe) {} } } try { out.write(ERR_404); out.flush(); } catch (IOException ioe) {} } private static final String BUNDLE_NAME = "net.i2p.i2ptunnel.web.messages"; /** lang in routerconsole.lang property, else current locale */ public static String _(String key) { return Translate.getString(key, I2PAppContext.getGlobalContext(), BUNDLE_NAME); } /** {0} and {1} */ public static String _(String key, Object o, Object o2) { return Translate.getString(key, o, o2, I2PAppContext.getGlobalContext(), BUNDLE_NAME); } }
false
true
protected void clientConnectionRun(Socket s) { InputStream in = null; OutputStream out = null; String targetRequest = null; boolean usingWWWProxy = false; boolean usingInternalServer = false; String currentProxy = null; long requestId = ++__requestId; try { out = s.getOutputStream(); InputReader reader = new InputReader(s.getInputStream()); String line, method = null, protocol = null, host = null, destination = null; StringBuilder newRequest = new StringBuilder(); int ahelper = 0; while ((line = reader.readLine(method)) != null) { line = line.trim(); if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Line=[" + line + "]"); String lowercaseLine = line.toLowerCase(); if (lowercaseLine.startsWith("connection: ") || lowercaseLine.startsWith("keep-alive: ") || lowercaseLine.startsWith("proxy-connection: ")) continue; if (method == null) { // first line (GET /base64/realaddr) if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "First line [" + line + "]"); int pos = line.indexOf(" "); if (pos == -1) break; method = line.substring(0, pos); // TODO use Java URL class to make all this simpler and more robust // That will also fix IPV6 [a:b:c] String request = line.substring(pos + 1); if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) { // what is this for ??? request = "http://i2p" + request; } else if (request.startsWith("/eepproxy/")) { // /eepproxy/foo.i2p/bar/baz.html HTTP/1.0 String subRequest = request.substring("/eepproxy/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } else if (request.toLowerCase().startsWith("http://i2p/")) { // http://i2p/b64key/bar/baz.html HTTP/1.0 String subRequest = request.substring("http://i2p/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "b64key/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } pos = request.indexOf("//"); if (pos == -1) { method = null; break; } protocol = request.substring(0, pos + 2); request = request.substring(pos + 2); targetRequest = request; // pos is the start of the path pos = request.indexOf("/"); if (pos == -1) { method = null; break; } host = request.substring(0, pos); // parse port int posPort = host.indexOf(":"); int port = 80; if(posPort != -1) { String[] parts = host.split(":"); host = parts[0]; try { port = Integer.parseInt(parts[1]); } catch(Exception exc) { // TODO: log this } } // Go through the various types of host names, set // the host and destination variables accordingly, // and transform the first line. // For all i2p network hosts, ensure that the host is a // Base 32 hostname so that we do not reveal our name for it // in our addressbook (all naming is local), // and it is removed from the request line. if (host.length() >= 516 && host.indexOf(".") < 0) { // http://b64key/bar/baz.html destination = host; host = getHostName(destination); line = method + ' ' + request.substring(pos); } else if (host.toLowerCase().equals("proxy.i2p")) { // so we don't do any naming service lookups destination = host; usingInternalServer = true; } else if (host.toLowerCase().endsWith(".i2p")) { // Destination gets the host name destination = host; // Host becomes the destination key host = getHostName(destination); int pos2; if ((pos2 = request.indexOf("?")) != -1) { // Try to find an address helper in the fragments // and split the request into it's component parts for rebuilding later String ahelperKey = null; boolean ahelperConflict = false; String fragments = request.substring(pos2 + 1); String uriPath = request.substring(0, pos2); pos2 = fragments.indexOf(" "); String protocolVersion = fragments.substring(pos2 + 1); String urlEncoding = ""; fragments = fragments.substring(0, pos2); String initialFragments = fragments; fragments = fragments + "&"; String fragment; while(fragments.length() > 0) { pos2 = fragments.indexOf("&"); fragment = fragments.substring(0, pos2); fragments = fragments.substring(pos2 + 1); // Fragment looks like addresshelper key if (fragment.startsWith("i2paddresshelper=")) { pos2 = fragment.indexOf("="); ahelperKey = fragment.substring(pos2 + 1); // Key contains data, lets not ignore it if (ahelperKey != null) { // Host resolvable only with addresshelper if ( (host == null) || ("i2p".equals(host)) ) { // Cannot check, use addresshelper key addressHelpers.put(destination,ahelperKey); } else { // Host resolvable from database, verify addresshelper key // Silently bypass correct keys, otherwise alert if (!host.equals(ahelperKey)) { // Conflict: handle when URL reconstruction done ahelperConflict = true; if (_log.shouldLog(Log.WARN)) _log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + host + "], specified key [" + ahelperKey + "]."); } } } } else { // Other fragments, just pass along // Append each fragment to urlEncoding if ("".equals(urlEncoding)) { urlEncoding = "?" + fragment; } else { urlEncoding = urlEncoding + "&" + fragment; } } } // Reconstruct the request minus the i2paddresshelper GET var request = uriPath + urlEncoding + " " + protocolVersion; // Did addresshelper key conflict? if (ahelperConflict) { if (out != null) { long alias = I2PAppContext.getGlobalContext().random().nextLong(); String trustedURL = protocol + uriPath + urlEncoding; String conflictURL = protocol + alias + ".i2p/?" + initialFragments; byte[] header = getErrorPage("ahelper-conflict", ERR_AHELPER_CONFLICT); out.write(header); out.write(_("To visit the destination in your host database, click <a href=\"{0}\">here</a>. To visit the conflicting addresshelper link by temporarily giving it a random alias, click <a href=\"{1}\">here</a>.", trustedURL, conflictURL).getBytes("UTF-8")); out.write(("<p></div>").getBytes()); writeFooter(out); } s.close(); return; } } String addressHelper = (String) addressHelpers.get(destination); if (addressHelper != null) { destination = addressHelper; host = getHostName(destination); ahelper = 1; } line = method + " " + request.substring(pos); } else if (host.toLowerCase().equals("localhost") || host.equals("127.0.0.1")) { if (out != null) { out.write(getErrorPage("localhost", ERR_LOCALHOST)); writeFooter(out); } s.close(); return; } else if (host.indexOf(".") != -1) { // rebuild host host = host + ":" + port; // The request must be forwarded to a WWW proxy if (_log.shouldLog(Log.DEBUG)) _log.debug("Before selecting outproxy for " + host); currentProxy = selectProxy(); if (_log.shouldLog(Log.DEBUG)) _log.debug("After selecting outproxy for " + host + ": " + currentProxy); if (currentProxy == null) { if (_log.shouldLog(Log.WARN)) _log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!"); l.log("No HTTP outproxy found for the request."); if (out != null) { out.write(getErrorPage("noproxy", ERR_NO_OUTPROXY)); writeFooter(out); } s.close(); return; } destination = currentProxy; usingWWWProxy = true; if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!"); } else { // what is left for here? a hostname with no dots, and != "i2p" // and not a destination ??? // Perhaps something in privatehosts.txt ... request = request.substring(pos + 1); pos = request.indexOf("/"); if (pos < 0) { l.log("Invalid request url [" + request + "]"); if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } destination = request.substring(0, pos); host = getHostName(destination); line = method + " " + request.substring(pos); } // end host name processing if (port != 80 && !usingWWWProxy) { if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } boolean isValid = usingWWWProxy || usingInternalServer || isSupportedAddress(host, protocol); if (!isValid) { if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")"); method = null; destination = null; break; } // don't do this, it forces yet another hostname lookup, // and in all cases host was already set above //if ((!usingWWWProxy) && (!usingInternalServer)) { // String oldhost = host; // host = getHostName(destination); // hide original host // if (_log.shouldLog(Log.INFO)) // _log.info(getPrefix(requestId) + " oldhost " + oldhost + " newhost " + host + " dest " + destination); //} if (_log.shouldLog(Log.DEBUG)) { _log.debug(getPrefix(requestId) + "METHOD: \"" + method + "\""); _log.debug(getPrefix(requestId) + "PROTOC: \"" + protocol + "\""); _log.debug(getPrefix(requestId) + "HOST : \"" + host + "\""); _log.debug(getPrefix(requestId) + "DEST : \"" + destination + "\""); } // end first line processing } else { if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) { // Note that we only pass the original Host: line through to the outproxy // But we don't create a Host: line if it wasn't sent to us line = "Host: " + host; if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "Setting host = " + host); } else if (lowercaseLine.startsWith("user-agent: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) { line = null; continue; } else if (lowercaseLine.startsWith("accept")) { // strip the accept-blah headers, as they vary dramatically from // browser to browser line = null; continue; } else if (lowercaseLine.startsWith("referer: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) { // Shouldn't we be more specific, like accepting in-site referers ? //line = "Referer: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("via: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) { //line = "Via: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("from: ")) { //line = "From: i2p"; line = null; continue; // completely strip the line } } if (line.length() == 0) { String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip"); boolean gzip = DEFAULT_GZIP; if (ok != null) gzip = Boolean.valueOf(ok).booleanValue(); if (gzip && !usingInternalServer) { // according to rfc2616 s14.3, this *should* force identity, even if // an explicit q=0 for gzip doesn't. tested against orion.i2p, and it // seems to work. newRequest.append("Accept-Encoding: \r\n"); newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n"); } if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n"); newRequest.append("Connection: close\r\n\r\n"); break; } else { newRequest.append(line).append("\r\n"); // HTTP spec } } // end header processing if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]"); if (method == null || destination == null) { //l.log("No HTTP method found in the request."); if (out != null) { if ("http://".equalsIgnoreCase(protocol)) out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); else out.write(getErrorPage("protocol", ERR_BAD_PROTOCOL)); writeFooter(out); } s.close(); return; } if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Destination: " + destination); // Serve local proxy files (images, css linked from error pages) // Ignore all the headers if (usingInternalServer) { serveLocalFile(out, method, targetRequest); s.close(); return; } // If the host is "i2p", the getHostName() lookup failed, don't try to // look it up again as the naming service does not do negative caching // so it will be slow. Destination clientDest; if ("i2p".equals(host)) clientDest = null; else clientDest = I2PTunnel.destFromName(destination); if (clientDest == null) { //l.log("Could not resolve " + destination + "."); if (_log.shouldLog(Log.WARN)) _log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest); byte[] header; String jumpServers = null; if (usingWWWProxy) header = getErrorPage("dnfp", ERR_DESTINATION_UNKNOWN); else if(ahelper != 0) header = getErrorPage("dnfb", ERR_DESTINATION_UNKNOWN); else if (destination.length() == 60 && destination.endsWith(".b32.i2p")) header = getErrorPage("dnf", ERR_DESTINATION_UNKNOWN); else { header = getErrorPage("dnfh", ERR_DESTINATION_UNKNOWN); jumpServers = getTunnel().getClientOptions().getProperty(PROP_JUMP_SERVERS); if (jumpServers == null) jumpServers = DEFAULT_JUMP_SERVERS; } writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, jumpServers); s.close(); return; } String remoteID; Properties opts = new Properties(); //opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000); // 1 == disconnect. see ConnectionOptions in the new streaming lib, which i // dont want to hard link to here //opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1); I2PSocket i2ps = createI2PSocket(clientDest, getDefaultOptions(opts)); byte[] data = newRequest.toString().getBytes("ISO-8859-1"); Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId); I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout); } catch (SocketException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (IOException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (I2PException ex) { _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (OutOfMemoryError oom) { IOException ex = new IOException("OOM"); _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } }
protected void clientConnectionRun(Socket s) { InputStream in = null; OutputStream out = null; String targetRequest = null; boolean usingWWWProxy = false; boolean usingInternalServer = false; String currentProxy = null; long requestId = ++__requestId; try { out = s.getOutputStream(); InputReader reader = new InputReader(s.getInputStream()); String line, method = null, protocol = null, host = null, destination = null; StringBuilder newRequest = new StringBuilder(); int ahelper = 0; while ((line = reader.readLine(method)) != null) { line = line.trim(); if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Line=[" + line + "]"); String lowercaseLine = line.toLowerCase(); if (lowercaseLine.startsWith("connection: ") || lowercaseLine.startsWith("keep-alive: ") || lowercaseLine.startsWith("proxy-connection: ")) continue; if (method == null) { // first line (GET /base64/realaddr) if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "First line [" + line + "]"); int pos = line.indexOf(" "); if (pos == -1) break; method = line.substring(0, pos); // TODO use Java URL class to make all this simpler and more robust // That will also fix IPV6 [a:b:c] String request = line.substring(pos + 1); if (request.startsWith("/") && getTunnel().getClientOptions().getProperty("i2ptunnel.noproxy") != null) { // what is this for ??? request = "http://i2p" + request; } else if (request.startsWith("/eepproxy/")) { // /eepproxy/foo.i2p/bar/baz.html HTTP/1.0 String subRequest = request.substring("/eepproxy/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "foo.i2p/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } else if (request.toLowerCase().startsWith("http://i2p/")) { // http://i2p/b64key/bar/baz.html HTTP/1.0 String subRequest = request.substring("http://i2p/".length()); int protopos = subRequest.indexOf(" "); String uri = subRequest.substring(0, protopos); if (uri.indexOf("/") == -1) { uri = uri + "/"; } // "http://" + "b64key/bar/baz.html" + " HTTP/1.0" request = "http://" + uri + subRequest.substring(protopos); } pos = request.indexOf("//"); if (pos == -1) { method = null; break; } protocol = request.substring(0, pos + 2); request = request.substring(pos + 2); targetRequest = request; // pos is the start of the path pos = request.indexOf("/"); if (pos == -1) { method = null; break; } host = request.substring(0, pos); // parse port int posPort = host.indexOf(":"); int port = 80; if(posPort != -1) { String[] parts = host.split(":"); host = parts[0]; try { port = Integer.parseInt(parts[1]); } catch(Exception exc) { // TODO: log this } } // Go through the various types of host names, set // the host and destination variables accordingly, // and transform the first line. // For all i2p network hosts, ensure that the host is a // Base 32 hostname so that we do not reveal our name for it // in our addressbook (all naming is local), // and it is removed from the request line. if (host.length() >= 516 && host.indexOf(".") < 0) { // http://b64key/bar/baz.html destination = host; host = getHostName(destination); line = method + ' ' + request.substring(pos); } else if (host.toLowerCase().equals("proxy.i2p")) { // so we don't do any naming service lookups destination = host; usingInternalServer = true; } else if (host.toLowerCase().endsWith(".i2p")) { // Destination gets the host name destination = host; // Host becomes the destination key host = getHostName(destination); int pos2; if ((pos2 = request.indexOf("?")) != -1) { // Try to find an address helper in the fragments // and split the request into it's component parts for rebuilding later String ahelperKey = null; boolean ahelperConflict = false; String fragments = request.substring(pos2 + 1); String uriPath = request.substring(0, pos2); pos2 = fragments.indexOf(" "); String protocolVersion = fragments.substring(pos2 + 1); String urlEncoding = ""; fragments = fragments.substring(0, pos2); String initialFragments = fragments; fragments = fragments + "&"; String fragment; while(fragments.length() > 0) { pos2 = fragments.indexOf("&"); fragment = fragments.substring(0, pos2); fragments = fragments.substring(pos2 + 1); // Fragment looks like addresshelper key if (fragment.startsWith("i2paddresshelper=")) { pos2 = fragment.indexOf("="); ahelperKey = fragment.substring(pos2 + 1); // Key contains data, lets not ignore it if (ahelperKey != null) { // ahelperKey will be validated later // Host resolvable only with addresshelper if ( (host == null) || ("i2p".equals(host)) ) { // Cannot check, use addresshelper key addressHelpers.put(destination,ahelperKey); } else { // Host resolvable from database, verify addresshelper key // Silently bypass correct keys, otherwise alert String destB64 = null; try { Destination dest = I2PTunnel.destFromName(host); if (dest != null) destB64 = dest.toBase64(); } catch (DataFormatException dfe) {} if (destB64 != null && !destB64.equals(ahelperKey)) { // Conflict: handle when URL reconstruction done ahelperConflict = true; if (_log.shouldLog(Log.WARN)) _log.warn(getPrefix(requestId) + "Addresshelper key conflict for site [" + destination + "], trusted key [" + destB64 + "], specified key [" + ahelperKey + "]."); } } } } else { // Other fragments, just pass along // Append each fragment to urlEncoding if ("".equals(urlEncoding)) { urlEncoding = "?" + fragment; } else { urlEncoding = urlEncoding + "&" + fragment; } } } // Reconstruct the request minus the i2paddresshelper GET var request = uriPath + urlEncoding + " " + protocolVersion; // Did addresshelper key conflict? if (ahelperConflict) { if (out != null) { // convert ahelperKey to b32 String alias = getHostName(ahelperKey); if (alias.equals("i2p")) { // bad ahelperKey byte[] header = getErrorPage("dnfb", ERR_DESTINATION_UNKNOWN); writeErrorMessage(header, out, targetRequest, false, destination, null); } else { String trustedURL = protocol + uriPath + urlEncoding; // Fixme - any path is lost String conflictURL = protocol + alias + '/' + urlEncoding; byte[] header = getErrorPage("ahelper-conflict", ERR_AHELPER_CONFLICT); out.write(header); out.write(_("To visit the destination in your host database, click <a href=\"{0}\">here</a>. To visit the conflicting addresshelper destination, click <a href=\"{1}\">here</a>.", trustedURL, conflictURL).getBytes("UTF-8")); out.write(("<p></div>").getBytes()); writeFooter(out); } } s.close(); return; } } String addressHelper = (String) addressHelpers.get(destination); if (addressHelper != null) { destination = addressHelper; host = getHostName(destination); ahelper = 1; } line = method + " " + request.substring(pos); } else if (host.toLowerCase().equals("localhost") || host.equals("127.0.0.1")) { if (out != null) { out.write(getErrorPage("localhost", ERR_LOCALHOST)); writeFooter(out); } s.close(); return; } else if (host.indexOf(".") != -1) { // rebuild host host = host + ":" + port; // The request must be forwarded to a WWW proxy if (_log.shouldLog(Log.DEBUG)) _log.debug("Before selecting outproxy for " + host); currentProxy = selectProxy(); if (_log.shouldLog(Log.DEBUG)) _log.debug("After selecting outproxy for " + host + ": " + currentProxy); if (currentProxy == null) { if (_log.shouldLog(Log.WARN)) _log.warn(getPrefix(requestId) + "Host wants to be outproxied, but we dont have any!"); l.log("No HTTP outproxy found for the request."); if (out != null) { out.write(getErrorPage("noproxy", ERR_NO_OUTPROXY)); writeFooter(out); } s.close(); return; } destination = currentProxy; usingWWWProxy = true; if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!"); } else { // what is left for here? a hostname with no dots, and != "i2p" // and not a destination ??? // Perhaps something in privatehosts.txt ... request = request.substring(pos + 1); pos = request.indexOf("/"); if (pos < 0) { l.log("Invalid request url [" + request + "]"); if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } destination = request.substring(0, pos); host = getHostName(destination); line = method + " " + request.substring(pos); } // end host name processing if (port != 80 && !usingWWWProxy) { if (out != null) { out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); writeFooter(out); } s.close(); return; } boolean isValid = usingWWWProxy || usingInternalServer || isSupportedAddress(host, protocol); if (!isValid) { if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "notValid(" + host + ")"); method = null; destination = null; break; } // don't do this, it forces yet another hostname lookup, // and in all cases host was already set above //if ((!usingWWWProxy) && (!usingInternalServer)) { // String oldhost = host; // host = getHostName(destination); // hide original host // if (_log.shouldLog(Log.INFO)) // _log.info(getPrefix(requestId) + " oldhost " + oldhost + " newhost " + host + " dest " + destination); //} if (_log.shouldLog(Log.DEBUG)) { _log.debug(getPrefix(requestId) + "METHOD: \"" + method + "\""); _log.debug(getPrefix(requestId) + "PROTOC: \"" + protocol + "\""); _log.debug(getPrefix(requestId) + "HOST : \"" + host + "\""); _log.debug(getPrefix(requestId) + "DEST : \"" + destination + "\""); } // end first line processing } else { if (lowercaseLine.startsWith("host: ") && !usingWWWProxy) { // Note that we only pass the original Host: line through to the outproxy // But we don't create a Host: line if it wasn't sent to us line = "Host: " + host; if (_log.shouldLog(Log.INFO)) _log.info(getPrefix(requestId) + "Setting host = " + host); } else if (lowercaseLine.startsWith("user-agent: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) { line = null; continue; } else if (lowercaseLine.startsWith("accept")) { // strip the accept-blah headers, as they vary dramatically from // browser to browser line = null; continue; } else if (lowercaseLine.startsWith("referer: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_REFERER)).booleanValue()) { // Shouldn't we be more specific, like accepting in-site referers ? //line = "Referer: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("via: ") && !Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_VIA)).booleanValue()) { //line = "Via: i2p"; line = null; continue; // completely strip the line } else if (lowercaseLine.startsWith("from: ")) { //line = "From: i2p"; line = null; continue; // completely strip the line } } if (line.length() == 0) { String ok = getTunnel().getClientOptions().getProperty("i2ptunnel.gzip"); boolean gzip = DEFAULT_GZIP; if (ok != null) gzip = Boolean.valueOf(ok).booleanValue(); if (gzip && !usingInternalServer) { // according to rfc2616 s14.3, this *should* force identity, even if // an explicit q=0 for gzip doesn't. tested against orion.i2p, and it // seems to work. newRequest.append("Accept-Encoding: \r\n"); newRequest.append("X-Accept-Encoding: x-i2p-gzip;q=1.0, identity;q=0.5, deflate;q=0, gzip;q=0, *;q=0\r\n"); } if (!Boolean.valueOf(getTunnel().getClientOptions().getProperty(PROP_USER_AGENT)).booleanValue()) newRequest.append("User-Agent: MYOB/6.66 (AN/ON)\r\n"); newRequest.append("Connection: close\r\n\r\n"); break; } else { newRequest.append(line).append("\r\n"); // HTTP spec } } // end header processing if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "NewRequest header: [" + newRequest.toString() + "]"); if (method == null || destination == null) { //l.log("No HTTP method found in the request."); if (out != null) { if ("http://".equalsIgnoreCase(protocol)) out.write(getErrorPage("denied", ERR_REQUEST_DENIED)); else out.write(getErrorPage("protocol", ERR_BAD_PROTOCOL)); writeFooter(out); } s.close(); return; } if (_log.shouldLog(Log.DEBUG)) _log.debug(getPrefix(requestId) + "Destination: " + destination); // Serve local proxy files (images, css linked from error pages) // Ignore all the headers if (usingInternalServer) { serveLocalFile(out, method, targetRequest); s.close(); return; } // If the host is "i2p", the getHostName() lookup failed, don't try to // look it up again as the naming service does not do negative caching // so it will be slow. Destination clientDest; if ("i2p".equals(host)) clientDest = null; else clientDest = I2PTunnel.destFromName(destination); if (clientDest == null) { //l.log("Could not resolve " + destination + "."); if (_log.shouldLog(Log.WARN)) _log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest); byte[] header; String jumpServers = null; if (usingWWWProxy) header = getErrorPage("dnfp", ERR_DESTINATION_UNKNOWN); else if(ahelper != 0) header = getErrorPage("dnfb", ERR_DESTINATION_UNKNOWN); else if (destination.length() == 60 && destination.endsWith(".b32.i2p")) header = getErrorPage("dnf", ERR_DESTINATION_UNKNOWN); else { header = getErrorPage("dnfh", ERR_DESTINATION_UNKNOWN); jumpServers = getTunnel().getClientOptions().getProperty(PROP_JUMP_SERVERS); if (jumpServers == null) jumpServers = DEFAULT_JUMP_SERVERS; } writeErrorMessage(header, out, targetRequest, usingWWWProxy, destination, jumpServers); s.close(); return; } String remoteID; Properties opts = new Properties(); //opts.setProperty("i2p.streaming.inactivityTimeout", ""+120*1000); // 1 == disconnect. see ConnectionOptions in the new streaming lib, which i // dont want to hard link to here //opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1); I2PSocket i2ps = createI2PSocket(clientDest, getDefaultOptions(opts)); byte[] data = newRequest.toString().getBytes("ISO-8859-1"); Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId); I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout); } catch (SocketException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (IOException ex) { _log.info(getPrefix(requestId) + "Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (I2PException ex) { _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } catch (OutOfMemoryError oom) { IOException ex = new IOException("OOM"); _log.info("getPrefix(requestId) + Error trying to connect", ex); l.log(ex.getMessage()); handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, currentProxy, requestId); closeSocket(s); } }
diff --git a/src/com/triposo/automator/androidmarket/HomePage.java b/src/com/triposo/automator/androidmarket/HomePage.java index c39a9bf..821defc 100644 --- a/src/com/triposo/automator/androidmarket/HomePage.java +++ b/src/com/triposo/automator/androidmarket/HomePage.java @@ -1,65 +1,65 @@ package com.triposo.automator.androidmarket; import com.google.common.base.Splitter; import com.triposo.automator.Page; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HomePage extends Page { @FindBy(linkText = "Next ›") private WebElement nextLink; @FindBy(id = "gwt-debug-applistingappList") private WebElement appsTable; public HomePage(WebDriver driver) { super(driver); } public boolean hasNext() { try { return nextLink.isDisplayed(); } catch (NoSuchElementException e) { return false; } } public HomePage clickNext() { nextLink.click(); return new HomePage(driver); } public void printStats() { List<WebElement> rows = appsTable.findElements(By.className("listingRow")); for (WebElement row : rows) { String text = row.getText(); String name = null; String totalInstalls = null; String netInstalls = null; Iterable<String> lines = Splitter.on("\n").split(text); for (String line : lines) { if (name == null) { name = line; } else { - Matcher matcher = Pattern.compile("^(.*) total installs").matcher(line); + Matcher matcher = Pattern.compile("^(.*) total user installs").matcher(line); if (matcher.find()) { totalInstalls = matcher.group(1).trim().replaceAll(",", ""); } - matcher = Pattern.compile("^(.*) net installs").matcher(line); + matcher = Pattern.compile("^(.*) active device installs").matcher(line); if (matcher.find()) { netInstalls = matcher.group(1).trim().replaceAll(",", ""); } } } System.out.println(String.format("%s,%s,%s", name, totalInstalls, netInstalls)); } } }
false
true
public void printStats() { List<WebElement> rows = appsTable.findElements(By.className("listingRow")); for (WebElement row : rows) { String text = row.getText(); String name = null; String totalInstalls = null; String netInstalls = null; Iterable<String> lines = Splitter.on("\n").split(text); for (String line : lines) { if (name == null) { name = line; } else { Matcher matcher = Pattern.compile("^(.*) total installs").matcher(line); if (matcher.find()) { totalInstalls = matcher.group(1).trim().replaceAll(",", ""); } matcher = Pattern.compile("^(.*) net installs").matcher(line); if (matcher.find()) { netInstalls = matcher.group(1).trim().replaceAll(",", ""); } } } System.out.println(String.format("%s,%s,%s", name, totalInstalls, netInstalls)); } }
public void printStats() { List<WebElement> rows = appsTable.findElements(By.className("listingRow")); for (WebElement row : rows) { String text = row.getText(); String name = null; String totalInstalls = null; String netInstalls = null; Iterable<String> lines = Splitter.on("\n").split(text); for (String line : lines) { if (name == null) { name = line; } else { Matcher matcher = Pattern.compile("^(.*) total user installs").matcher(line); if (matcher.find()) { totalInstalls = matcher.group(1).trim().replaceAll(",", ""); } matcher = Pattern.compile("^(.*) active device installs").matcher(line); if (matcher.find()) { netInstalls = matcher.group(1).trim().replaceAll(",", ""); } } } System.out.println(String.format("%s,%s,%s", name, totalInstalls, netInstalls)); } }
diff --git a/app/program/program/src/main/java/org/jbundle/app/program/script/scan/DateOffsetScanListener.java b/app/program/program/src/main/java/org/jbundle/app/program/script/scan/DateOffsetScanListener.java index 76cc94ca..8a527526 100644 --- a/app/program/program/src/main/java/org/jbundle/app/program/script/scan/DateOffsetScanListener.java +++ b/app/program/program/src/main/java/org/jbundle/app/program/script/scan/DateOffsetScanListener.java @@ -1,198 +1,207 @@ /** * @(#)DateOffsetScanListener. * Copyright © 2010 tourapp.com. All rights reserved. */ package org.jbundle.app.program.script.scan; import java.awt.*; import java.util.*; import org.jbundle.base.db.*; import org.jbundle.thin.base.util.*; import org.jbundle.thin.base.db.*; import org.jbundle.base.db.event.*; import org.jbundle.base.db.filter.*; import org.jbundle.base.field.*; import org.jbundle.base.field.convert.*; import org.jbundle.base.field.event.*; import org.jbundle.base.screen.model.*; import org.jbundle.base.screen.model.util.*; import org.jbundle.base.util.*; import org.jbundle.model.*; import org.jbundle.base.db.xmlutil.*; import java.text.*; /** * DateOffsetScanListener - Offset dates in an XML file dayOffset = days to offset monthOffset = yearOffset = endOfMonthFields = comma delimited fields to set to end of month if previous date was oem. */ public class DateOffsetScanListener extends BaseScanListener { protected int dayOffset = 0; protected String[] eomFields = null; protected int monthOffset = 0; protected int yearOffset = 0; /** * Default constructor. */ public DateOffsetScanListener() { super(); } /** * Constructor. */ public DateOffsetScanListener(RecordOwnerParent parent, String strSourcePrefix) { this(); this.init(parent, strSourcePrefix); } /** * Init Method. */ public void init(RecordOwnerParent parent, String strSourcePrefix) { super.init(parent, strSourcePrefix); if (this.getProperty("dayOffset") != null) dayOffset = Integer.parseInt(this.getProperty("dayOffset")); if (this.getProperty("monthOffset") != null) monthOffset = Integer.parseInt(this.getProperty("monthOffset")); if (this.getProperty("yearOffset") != null) yearOffset = Integer.parseInt(this.getProperty("yearOffset")); if (this.getProperty("endOfMonthFields") != null) { String fields = this.getProperty("endOfMonthFields"); eomFields = fields.split(","); } } /** * Do any string conversion on the file text. */ public String convertString(String string) { if (string != null) { int startTag = string.indexOf('<'); int endTag = string.indexOf('>'); if (startTag > -1) if (endTag > startTag) { String tag = string.substring(startTag + 1, endTag); - if (tag.toUpperCase().contains("DATE")) + boolean bDateField = tag.toUpperCase().contains("DATE"); + if (eomFields != null) + { + for (String token : eomFields) + { + if (tag.equals(token)) + bDateField = true; + } + } + if (bDateField) { int endData = string.indexOf('<', endTag); if (endData != -1) { String dateString = string.substring(endTag + 1, endData); Date date = new Date(); int type = this.parseDate(dateString, date); if (type != 0) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (yearOffset != 0) { calendar.add(Calendar.YEAR, yearOffset); } int day = 0; if (monthOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, 1); day = calendar.get(Calendar.DAY_OF_MONTH); // Just want to see if this was the end of the month calendar.add(Calendar.DAY_OF_MONTH, -1); // Restore original date calendar.add(Calendar.MONTH, monthOffset); // Add the month offset if (eomFields != null) { for (String token : eomFields) { if (tag.equals(token)) { if (day == 1) { // end of (next) month calendar.add(Calendar.DAY_OF_MONTH, 5); // next month calendar.set(Calendar.DAY_OF_MONTH, 1); // First of next month calendar.add(Calendar.DAY_OF_MONTH, -1); // End of month } } } } } if (dayOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, dayOffset); } date = calendar.getTime(); String newDateString = this.formatDate(date, type); if (newDateString != null) string = string.substring(0, endTag + 1) + newDateString + string.substring(endData); } } } } } return super.convertString(string); } /** * Decode date time value and set the field value. * @param field * @return. */ public int parseDate(String strValue, Date date) { int type = 0; if (strValue == null) return type; Date parsedDate = null; try { parsedDate = XmlUtilities.dateTimeFormat.parse(strValue); type = DBConstants.DATE_TIME_FORMAT; } catch (ParseException e) { } try { if (parsedDate == null) { parsedDate = XmlUtilities.dateFormat.parse(strValue); type = DBConstants.DATE_ONLY_FORMAT; } } catch (ParseException e) { } try { if (parsedDate == null) { parsedDate = XmlUtilities.timeFormat.parse(strValue); type = DBConstants.TIME_ONLY_FORMAT; } } catch (ParseException e) { } if (parsedDate != null) date.setTime(parsedDate.getTime()); else type = 0; return type; } /** * FormatDate Method. */ public String formatDate(Date date, int type) { String string = null; if (type == DBConstants.DATE_TIME_FORMAT) string = XmlUtilities.dateTimeFormat.format(date); else if (type == DBConstants.DATE_ONLY_FORMAT) string = XmlUtilities.dateFormat.format(date); else if (type == DBConstants.TIME_ONLY_FORMAT) string = XmlUtilities.timeFormat.format(date); return string; } }
true
true
public String convertString(String string) { if (string != null) { int startTag = string.indexOf('<'); int endTag = string.indexOf('>'); if (startTag > -1) if (endTag > startTag) { String tag = string.substring(startTag + 1, endTag); if (tag.toUpperCase().contains("DATE")) { int endData = string.indexOf('<', endTag); if (endData != -1) { String dateString = string.substring(endTag + 1, endData); Date date = new Date(); int type = this.parseDate(dateString, date); if (type != 0) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (yearOffset != 0) { calendar.add(Calendar.YEAR, yearOffset); } int day = 0; if (monthOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, 1); day = calendar.get(Calendar.DAY_OF_MONTH); // Just want to see if this was the end of the month calendar.add(Calendar.DAY_OF_MONTH, -1); // Restore original date calendar.add(Calendar.MONTH, monthOffset); // Add the month offset if (eomFields != null) { for (String token : eomFields) { if (tag.equals(token)) { if (day == 1) { // end of (next) month calendar.add(Calendar.DAY_OF_MONTH, 5); // next month calendar.set(Calendar.DAY_OF_MONTH, 1); // First of next month calendar.add(Calendar.DAY_OF_MONTH, -1); // End of month } } } } } if (dayOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, dayOffset); } date = calendar.getTime(); String newDateString = this.formatDate(date, type); if (newDateString != null) string = string.substring(0, endTag + 1) + newDateString + string.substring(endData); } } } } } return super.convertString(string); }
public String convertString(String string) { if (string != null) { int startTag = string.indexOf('<'); int endTag = string.indexOf('>'); if (startTag > -1) if (endTag > startTag) { String tag = string.substring(startTag + 1, endTag); boolean bDateField = tag.toUpperCase().contains("DATE"); if (eomFields != null) { for (String token : eomFields) { if (tag.equals(token)) bDateField = true; } } if (bDateField) { int endData = string.indexOf('<', endTag); if (endData != -1) { String dateString = string.substring(endTag + 1, endData); Date date = new Date(); int type = this.parseDate(dateString, date); if (type != 0) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (yearOffset != 0) { calendar.add(Calendar.YEAR, yearOffset); } int day = 0; if (monthOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, 1); day = calendar.get(Calendar.DAY_OF_MONTH); // Just want to see if this was the end of the month calendar.add(Calendar.DAY_OF_MONTH, -1); // Restore original date calendar.add(Calendar.MONTH, monthOffset); // Add the month offset if (eomFields != null) { for (String token : eomFields) { if (tag.equals(token)) { if (day == 1) { // end of (next) month calendar.add(Calendar.DAY_OF_MONTH, 5); // next month calendar.set(Calendar.DAY_OF_MONTH, 1); // First of next month calendar.add(Calendar.DAY_OF_MONTH, -1); // End of month } } } } } if (dayOffset != 0) { calendar.add(Calendar.DAY_OF_MONTH, dayOffset); } date = calendar.getTime(); String newDateString = this.formatDate(date, type); if (newDateString != null) string = string.substring(0, endTag + 1) + newDateString + string.substring(endData); } } } } } return super.convertString(string); }
diff --git a/slim3/src/main/java/org/slim3/controller/router/RouterFactory.java b/slim3/src/main/java/org/slim3/controller/router/RouterFactory.java index 7758e065..c3fa44e8 100644 --- a/slim3/src/main/java/org/slim3/controller/router/RouterFactory.java +++ b/slim3/src/main/java/org/slim3/controller/router/RouterFactory.java @@ -1,99 +1,99 @@ /* * Copyright 2004-2010 the Seasar Foundation and the Others. * * 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.slim3.controller.router; import javax.servlet.ServletContext; import org.slim3.controller.ControllerConstants; import org.slim3.util.ClassUtil; import org.slim3.util.Cleanable; import org.slim3.util.Cleaner; import org.slim3.util.ServletContextLocator; import org.slim3.util.StringUtil; /** * A factory for {@link Router}. * * @author higa * @since 1.0.0 * */ public final class RouterFactory { /** * The key of {@link Router}. */ public static final String ROUTER_KEY = "slim3.router"; private static Router defaultRouter = new RouterImpl(); /** * Returns a router. * * @return a router */ public static synchronized Router getRouter() { ServletContext servletContext = getServletContext(); Router router = (Router) servletContext.getAttribute(ROUTER_KEY); if (router == null) { router = createRouter(servletContext); servletContext.setAttribute(ROUTER_KEY, router); Cleaner.add(new Cleanable() { public void clean() { getServletContext().removeAttribute(ROUTER_KEY); } }); } return router; } private static ServletContext getServletContext() { ServletContext servletContext = ServletContextLocator.get(); if (servletContext == null) { throw new IllegalStateException("The servletContext is not found."); } return servletContext; } private static Router createRouter(ServletContext servletContext) { String rootPackageName = servletContext .getInitParameter(ControllerConstants.ROOT_PACKAGE_KEY); if (StringUtil.isEmpty(rootPackageName)) { throw new IllegalStateException("The context-param(" + ControllerConstants.ROOT_PACKAGE_KEY + ") is not found in web.xml."); } String contollerPackageName = (String) servletContext .getAttribute(ControllerConstants.CONTROLLER_PACKAGE_KEY); if (contollerPackageName == null) { contollerPackageName = ControllerConstants.DEFAULT_CONTROLLER_PACKAGE; } try { - return ClassUtil.newInstance(rootPackageName - + "." - + contollerPackageName - + ".AppRouter"); - } catch (Throwable ignore) { + String className = + rootPackageName + "." + contollerPackageName + ".AppRouter"; + Class<?> clazz = Class.forName(className); + return ClassUtil.newInstance(clazz); + } catch (ClassNotFoundException e) { return defaultRouter; } } private RouterFactory() { } }
true
true
private static Router createRouter(ServletContext servletContext) { String rootPackageName = servletContext .getInitParameter(ControllerConstants.ROOT_PACKAGE_KEY); if (StringUtil.isEmpty(rootPackageName)) { throw new IllegalStateException("The context-param(" + ControllerConstants.ROOT_PACKAGE_KEY + ") is not found in web.xml."); } String contollerPackageName = (String) servletContext .getAttribute(ControllerConstants.CONTROLLER_PACKAGE_KEY); if (contollerPackageName == null) { contollerPackageName = ControllerConstants.DEFAULT_CONTROLLER_PACKAGE; } try { return ClassUtil.newInstance(rootPackageName + "." + contollerPackageName + ".AppRouter"); } catch (Throwable ignore) { return defaultRouter; } }
private static Router createRouter(ServletContext servletContext) { String rootPackageName = servletContext .getInitParameter(ControllerConstants.ROOT_PACKAGE_KEY); if (StringUtil.isEmpty(rootPackageName)) { throw new IllegalStateException("The context-param(" + ControllerConstants.ROOT_PACKAGE_KEY + ") is not found in web.xml."); } String contollerPackageName = (String) servletContext .getAttribute(ControllerConstants.CONTROLLER_PACKAGE_KEY); if (contollerPackageName == null) { contollerPackageName = ControllerConstants.DEFAULT_CONTROLLER_PACKAGE; } try { String className = rootPackageName + "." + contollerPackageName + ".AppRouter"; Class<?> clazz = Class.forName(className); return ClassUtil.newInstance(clazz); } catch (ClassNotFoundException e) { return defaultRouter; } }
diff --git a/src/main/java/com/fasterxml/jackson/dataformat/smile/SmileParser.java b/src/main/java/com/fasterxml/jackson/dataformat/smile/SmileParser.java index 15a2ad2..82e6c2b 100644 --- a/src/main/java/com/fasterxml/jackson/dataformat/smile/SmileParser.java +++ b/src/main/java/com/fasterxml/jackson/dataformat/smile/SmileParser.java @@ -1,2673 +1,2673 @@ package com.fasterxml.jackson.dataformat.smile; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.SoftReference; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserBase; import com.fasterxml.jackson.core.io.IOContext; import com.fasterxml.jackson.core.sym.BytesToNameCanonicalizer; import com.fasterxml.jackson.core.sym.Name; import static com.fasterxml.jackson.dataformat.smile.SmileConstants.BYTE_MARKER_END_OF_STRING; public class SmileParser extends ParserBase { /** * Enumeration that defines all togglable features for Smile generators. */ public enum Feature { /** * Feature that determines whether 4-byte Smile header is mandatory in input, * or optional. If enabled, it means that only input that starts with the header * is accepted as valid; if disabled, header is optional. In latter case,r * settings for content are assumed to be defaults. */ REQUIRE_HEADER(true) ; final boolean _defaultState; final int _mask; /** * Method that calculates bit set (flags) of all features that * are enabled by default. */ public static int collectDefaults() { int flags = 0; for (Feature f : values()) { if (f.enabledByDefault()) { flags |= f.getMask(); } } return flags; } private Feature(boolean defaultState) { _defaultState = defaultState; _mask = (1 << ordinal()); } public boolean enabledByDefault() { return _defaultState; } public int getMask() { return _mask; } } private final static int[] NO_INTS = new int[0]; private final static String[] NO_STRINGS = new String[0]; /* /********************************************************** /* Configuration /********************************************************** */ /** * Codec used for data binding when (if) requested. */ protected ObjectCodec _objectCodec; /** * Flag that indicates whether content can legally have raw (unquoted) * binary data. Since this information is included both in header and * in actual binary data blocks there is redundancy, and we want to * ensure settings are compliant. Using application may also want to * know this setting in case it does some direct (random) access. */ protected boolean _mayContainRawBinary; /** * Helper object used for low-level recycling of Smile-generator * specific buffers. */ final protected SmileBufferRecycler<String> _smileBufferRecycler; /* /********************************************************** /* Input source config, state (from ex StreamBasedParserBase) /********************************************************** */ /** * Input stream that can be used for reading more content, if one * in use. May be null, if input comes just as a full buffer, * or if the stream has been closed. */ protected InputStream _inputStream; /** * Current buffer from which data is read; generally data is read into * buffer from input source, but in some cases pre-loaded buffer * is handed to the parser. */ protected byte[] _inputBuffer; /** * Flag that indicates whether the input buffer is recycable (and * needs to be returned to recycler once we are done) or not. *<p> * If it is not, it also means that parser can NOT modify underlying * buffer. */ protected boolean _bufferRecyclable; /* /********************************************************** /* Additional parsing state /********************************************************** */ /** * Flag that indicates that the current token has not yet * been fully processed, and needs to be finished for * some access (or skipped to obtain the next token) */ protected boolean _tokenIncomplete = false; /** * Type byte of the current token */ protected int _typeByte; /** * Specific flag that is set when we encountered a 32-bit * floating point value; needed since numeric super classes do * not track distinction between float and double, but Smile * format does, and we want to retain that separation. */ protected boolean _got32BitFloat; /* /********************************************************** /* Symbol handling, decoding /********************************************************** */ /** * Symbol table that contains field names encountered so far */ final protected BytesToNameCanonicalizer _symbols; /** * Temporary buffer used for name parsing. */ protected int[] _quadBuffer = NO_INTS; /** * Quads used for hash calculation */ protected int _quad1, _quad2; /** * Array of recently seen field names, which may be back referenced * by later fields. * Defaults set to enable handling even if no header found. */ protected String[] _seenNames = NO_STRINGS; protected int _seenNameCount = 0; /** * Array of recently seen field names, which may be back referenced * by later fields * Defaults set to disable handling if no header found. */ protected String[] _seenStringValues = null; protected int _seenStringValueCount = -1; /* /********************************************************** /* Thread-local recycling /********************************************************** */ /** * <code>ThreadLocal</code> contains a {@link java.lang.ref.SoftReference} * to a buffer recycler used to provide a low-cost * buffer recycling for Smile-specific buffers. */ final protected static ThreadLocal<SoftReference<SmileBufferRecycler<String>>> _smileRecyclerRef = new ThreadLocal<SoftReference<SmileBufferRecycler<String>>>(); /* /********************************************************** /* Life-cycle /********************************************************** */ public SmileParser(IOContext ctxt, int parserFeatures, int smileFeatures, ObjectCodec codec, BytesToNameCanonicalizer sym, InputStream in, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) { super(ctxt, parserFeatures); _objectCodec = codec; _symbols = sym; _inputStream = in; _inputBuffer = inputBuffer; _inputPtr = start; _inputEnd = end; _bufferRecyclable = bufferRecyclable; _tokenInputRow = -1; _tokenInputCol = -1; _smileBufferRecycler = _smileBufferRecycler(); } @Override public ObjectCodec getCodec() { return _objectCodec; } @Override public void setCodec(ObjectCodec c) { _objectCodec = c; } /** * Helper method called when it looks like input might contain the signature; * and it is necessary to detect and handle signature to get configuration * information it might have. * * @return True if valid signature was found and handled; false if not */ protected boolean handleSignature(boolean consumeFirstByte, boolean throwException) throws IOException, JsonParseException { if (consumeFirstByte) { ++_inputPtr; } if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } if (_inputBuffer[_inputPtr] != SmileConstants.HEADER_BYTE_2) { if (throwException) { _reportError("Malformed content: signature not valid, starts with 0x3a but followed by 0x" +Integer.toHexString(_inputBuffer[_inputPtr])+", not 0x29"); } return false; } if (++_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } if (_inputBuffer[_inputPtr] != SmileConstants.HEADER_BYTE_3) { if (throwException) { _reportError("Malformed content: signature not valid, starts with 0x3a, 0x29, but followed by 0x" +Integer.toHexString(_inputBuffer[_inputPtr])+", not 0xA"); } return false; } // Good enough; just need version info from 4th byte... if (++_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int ch = _inputBuffer[_inputPtr++]; int versionBits = (ch >> 4) & 0x0F; // but failure with version number is fatal, can not ignore if (versionBits != SmileConstants.HEADER_VERSION_0) { _reportError("Header version number bits (0x"+Integer.toHexString(versionBits)+") indicate unrecognized version; only 0x0 handled by parser"); } // can avoid tracking names, if explicitly disabled if ((ch & SmileConstants.HEADER_BIT_HAS_SHARED_NAMES) == 0) { _seenNames = null; _seenNameCount = -1; } // conversely, shared string values must be explicitly enabled if ((ch & SmileConstants.HEADER_BIT_HAS_SHARED_STRING_VALUES) != 0) { _seenStringValues = NO_STRINGS; _seenStringValueCount = 0; } _mayContainRawBinary = ((ch & SmileConstants.HEADER_BIT_HAS_RAW_BINARY) != 0); return true; } protected final static SmileBufferRecycler<String> _smileBufferRecycler() { SoftReference<SmileBufferRecycler<String>> ref = _smileRecyclerRef.get(); SmileBufferRecycler<String> br = (ref == null) ? null : ref.get(); if (br == null) { br = new SmileBufferRecycler<String>(); _smileRecyclerRef.set(new SoftReference<SmileBufferRecycler<String>>(br)); } return br; } /* /********************************************************** /* Versioned /********************************************************** */ @Override public Version version() { return PackageVersion.VERSION; } /* /********************************************************** /* Former StreamBasedParserBase methods /********************************************************** */ @Override public int releaseBuffered(OutputStream out) throws IOException { int count = _inputEnd - _inputPtr; if (count < 1) { return 0; } // let's just advance ptr to end int origPtr = _inputPtr; out.write(_inputBuffer, origPtr, count); return count; } @Override public Object getInputSource() { return _inputStream; } /** * Overridden since we do not really have character-based locations, * but we do have byte offset to specify. */ @Override public JsonLocation getTokenLocation() { // token location is correctly managed... return new JsonLocation(_ioContext.getSourceReference(), _tokenInputTotal, // bytes -1, -1, (int) _tokenInputTotal); // char offset, line, column } /** * Overridden since we do not really have character-based locations, * but we do have byte offset to specify. */ @Override public JsonLocation getCurrentLocation() { final long offset = _currInputProcessed + _inputPtr; return new JsonLocation(_ioContext.getSourceReference(), offset, // bytes -1, -1, (int) offset); // char offset, line, column } /* /********************************************************** /* Low-level reading, other /********************************************************** */ @Override protected final boolean loadMore() throws IOException { _currInputProcessed += _inputEnd; //_currInputRowStart -= _inputEnd; if (_inputStream != null) { int count = _inputStream.read(_inputBuffer, 0, _inputBuffer.length); if (count > 0) { _inputPtr = 0; _inputEnd = count; return true; } // End of input _closeInput(); // Should never return 0, so let's fail if (count == 0) { throw new IOException("InputStream.read() returned 0 characters when trying to read "+_inputBuffer.length+" bytes"); } } return false; } /** * Helper method that will try to load at least specified number bytes in * input buffer, possible moving existing data around if necessary * * @since 1.6 */ protected final boolean _loadToHaveAtLeast(int minAvailable) throws IOException { // No input stream, no leading (either we are closed, or have non-stream input source) if (_inputStream == null) { return false; } // Need to move remaining data in front? int amount = _inputEnd - _inputPtr; if (amount > 0 && _inputPtr > 0) { _currInputProcessed += _inputPtr; //_currInputRowStart -= _inputPtr; System.arraycopy(_inputBuffer, _inputPtr, _inputBuffer, 0, amount); _inputEnd = amount; } else { _inputEnd = 0; } _inputPtr = 0; while (_inputEnd < minAvailable) { int count = _inputStream.read(_inputBuffer, _inputEnd, _inputBuffer.length - _inputEnd); if (count < 1) { // End of input _closeInput(); // Should never return 0, so let's fail if (count == 0) { throw new IOException("InputStream.read() returned 0 characters when trying to read "+amount+" bytes"); } return false; } _inputEnd += count; } return true; } @Override protected void _closeInput() throws IOException { /* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close() * on the underlying InputStream, unless we "own" it, or auto-closing * feature is enabled. */ if (_inputStream != null) { if (_ioContext.isResourceManaged() || isEnabled(JsonParser.Feature.AUTO_CLOSE_SOURCE)) { _inputStream.close(); } _inputStream = null; } } /* /********************************************************** /* Overridden methods /********************************************************** */ @Override protected void _finishString() throws IOException, JsonParseException { // should never be called; but must be defined for superclass _throwInternal(); } @Override public void close() throws IOException { super.close(); // Merge found symbols, if any: _symbols.release(); } @Override public boolean hasTextCharacters() { if (_currToken == JsonToken.VALUE_STRING) { // yes; is or can be made available efficiently as char[] return _textBuffer.hasTextAsCharacters(); } if (_currToken == JsonToken.FIELD_NAME) { // not necessarily; possible but: return _nameCopied; } // other types, no benefit from accessing as char[] return false; } /** * Method called to release internal buffers owned by the base * reader. This may be called along with {@link #_closeInput} (for * example, when explicitly closing this reader instance), or * separately (if need be). */ @Override protected void _releaseBuffers() throws IOException { super._releaseBuffers(); if (_bufferRecyclable) { byte[] buf = _inputBuffer; if (buf != null) { _inputBuffer = null; _ioContext.releaseReadIOBuffer(buf); } } { String[] nameBuf = _seenNames; if (nameBuf != null && nameBuf.length > 0) { _seenNames = null; /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer; * but we only need to clear up to count as it is not a hash area */ if (_seenNameCount > 0) { Arrays.fill(nameBuf, 0, _seenNameCount, null); } _smileBufferRecycler.releaseSeenNamesBuffer(nameBuf); } } { String[] valueBuf = _seenStringValues; if (valueBuf != null && valueBuf.length > 0) { _seenStringValues = null; /* 28-Jun-2011, tatu: With 1.9, caller needs to clear the buffer; * but we only need to clear up to count as it is not a hash area */ if (_seenStringValueCount > 0) { Arrays.fill(valueBuf, 0, _seenStringValueCount, null); } _smileBufferRecycler.releaseSeenStringValuesBuffer(valueBuf); } } } /* /********************************************************** /* Extended API /********************************************************** */ public boolean mayContainRawBinary() { return _mayContainRawBinary; } /* /********************************************************** /* JsonParser impl /********************************************************** */ @Override public JsonToken nextToken() throws IOException, JsonParseException { _numTypesValid = NR_UNKNOWN; // For longer tokens (text, binary), we'll only read when requested if (_tokenIncomplete) { _skipIncomplete(); } _tokenInputTotal = _currInputProcessed + _inputPtr; // also: clear any data retained so far _binaryValue = null; // Two main modes: values, and field names. if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) { return (_currToken = _handleFieldName()); } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _handleEOF(); /* NOTE: here we can and should close input, release buffers, * since this is "hard" EOF, not a boundary imposed by * header token. */ close(); return (_currToken = null); } } int ch = _inputBuffer[_inputPtr++]; _typeByte = ch; switch ((ch >> 5) & 0x7) { case 0: // short shared string value reference if (ch == 0) { // important: this is invalid, don't accept _reportError("Invalid token byte 0x00"); } return _handleSharedString(ch-1); case 1: // simple literals, numbers { int typeBits = ch & 0x1F; if (typeBits < 4) { switch (typeBits) { case 0x00: _textBuffer.resetWithEmpty(); return (_currToken = JsonToken.VALUE_STRING); case 0x01: return (_currToken = JsonToken.VALUE_NULL); case 0x02: // false return (_currToken = JsonToken.VALUE_FALSE); default: // 0x03 == true return (_currToken = JsonToken.VALUE_TRUE); } } // next 3 bytes define subtype if (typeBits < 8) { // VInt (zigzag), BigInteger if ((typeBits & 0x3) <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; return (_currToken = JsonToken.VALUE_NUMBER_INT); } break; } if (typeBits < 12) { // floating-point int subtype = typeBits & 0x3; if (subtype <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; _got32BitFloat = (subtype == 0); return (_currToken = JsonToken.VALUE_NUMBER_FLOAT); } break; } if (typeBits == 0x1A) { // == 0x3A == ':' -> possibly header signature for next chunk? if (handleSignature(false, false)) { /* Ok, now; end-marker and header both imply doc boundary and a * 'null token'; but if both are seen, they are collapsed. * We can check this by looking at current token; if it's null, * need to get non-null token */ if (_currToken == null) { return nextToken(); } return (_currToken = null); } } _reportError("Unrecognized token byte 0x3A (malformed segment header?"); } // and everything else is reserved, for now break; case 2: // tiny ASCII // fall through case 3: // short ASCII // fall through case 4: // tiny Unicode // fall through case 5: // short Unicode // No need to decode, unless we have to keep track of back-references (for shared string values) _currToken = JsonToken.VALUE_STRING; if (_seenStringValueCount >= 0) { // shared text values enabled _addSeenStringValue(); } else { _tokenIncomplete = true; } return _currToken; case 6: // small integers; zigzag encoded _numberInt = SmileUtil.zigzagDecode(ch & 0x1F); _numTypesValid = NR_INT; return (_currToken = JsonToken.VALUE_NUMBER_INT); case 7: // binary/long-text/long-shared/start-end-markers switch (ch & 0x1F) { case 0x00: // long variable length ASCII case 0x04: // long variable length unicode _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_STRING); - case 0x08: // binary, 7-bit + case 0x08: // binary, 7-bit (0xE8) _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); - case 0x0C: // long shared string + case 0x0C: // long shared string (0xEC) case 0x0D: case 0x0E: case 0x0F: if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return _handleSharedString(((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF)); case 0x18: // START_ARRAY _parsingContext = _parsingContext.createChildArrayContext(-1, -1); return (_currToken = JsonToken.START_ARRAY); case 0x19: // END_ARRAY if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(']', '}'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_ARRAY); case 0x1A: // START_OBJECT _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); case 0x1B: // not used in this mode; would be END_OBJECT _reportError("Invalid type marker byte 0xFB in value mode (would be END_OBJECT in key mode)"); case 0x1D: // binary, raw _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); case 0x1F: // 0xFF, end of content return (_currToken = null); } break; } // If we get this far, type byte is corrupt _reportError("Invalid type marker byte 0x"+Integer.toHexString(ch & 0xFF)+" for expected value token"); return null; } private final JsonToken _handleSharedString(int index) throws IOException, JsonParseException { if (index >= _seenStringValueCount) { _reportInvalidSharedStringValue(index); } _textBuffer.resetWithString(_seenStringValues[index]); return (_currToken = JsonToken.VALUE_STRING); } private final void _addSeenStringValue() throws IOException, JsonParseException { _finishToken(); if (_seenStringValueCount < _seenStringValues.length) { // !!! TODO: actually only store char[], first time around? _seenStringValues[_seenStringValueCount++] = _textBuffer.contentsAsString(); return; } _expandSeenStringValues(); } private final void _expandSeenStringValues() { String[] oldShared = _seenStringValues; int len = oldShared.length; String[] newShared; if (len == 0) { newShared = _smileBufferRecycler.allocSeenStringValuesBuffer(); if (newShared == null) { newShared = new String[SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH]; } } else if (len == SmileConstants.MAX_SHARED_STRING_VALUES) { // too many? Just flush... newShared = oldShared; _seenStringValueCount = 0; // could also clear, but let's not yet bother } else { int newSize = (len == SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH) ? 256 : SmileConstants.MAX_SHARED_STRING_VALUES; newShared = new String[newSize]; System.arraycopy(oldShared, 0, newShared, 0, oldShared.length); } _seenStringValues = newShared; _seenStringValues[_seenStringValueCount++] = _textBuffer.contentsAsString(); } // base impl is fine: //public String getCurrentName() throws IOException, JsonParseException @Override public NumberType getNumberType() throws IOException, JsonParseException { if (_got32BitFloat) { return NumberType.FLOAT; } return super.getNumberType(); } /* /********************************************************** /* Public API, traversal, nextXxxValue/nextFieldName /********************************************************** */ @Override public boolean nextFieldName(SerializableString str) throws IOException, JsonParseException { // Two parsing modes; can only succeed if expecting field name, so handle that first: if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) { byte[] nameBytes = str.asQuotedUTF8(); final int byteLen = nameBytes.length; // need room for type byte, name bytes, possibly end marker, so: if ((_inputPtr + byteLen + 1) < _inputEnd) { // maybe... int ptr = _inputPtr; int ch = _inputBuffer[ptr++]; _typeByte = ch; main_switch: switch ((ch >> 6) & 3) { case 0: // misc, including end marker switch (ch) { case 0x20: // empty String as name, legal if unusual _currToken = JsonToken.FIELD_NAME; _inputPtr = ptr; _parsingContext.setCurrentName(""); return (byteLen == 0); case 0x30: // long shared case 0x31: case 0x32: case 0x33: { int index = ((ch & 0x3) << 8) + (_inputBuffer[ptr++] & 0xFF); if (index >= _seenNameCount) { _reportInvalidSharedName(index); } String name = _seenNames[index]; _parsingContext.setCurrentName(name); _inputPtr = ptr; _currToken = JsonToken.FIELD_NAME; return (name.equals(str.getValue())); } //case 0x34: // long ASCII/Unicode name; let's not even try... } break; case 1: // short shared, can fully process { int index = (ch & 0x3F); if (index >= _seenNameCount) { _reportInvalidSharedName(index); } _parsingContext.setCurrentName(_seenNames[index]); String name = _seenNames[index]; _parsingContext.setCurrentName(name); _inputPtr = ptr; _currToken = JsonToken.FIELD_NAME; return (name.equals(str.getValue())); } case 2: // short ASCII { int len = 1 + (ch & 0x3f); if (len == byteLen) { int i = 0; for (; i < len; ++i) { if (nameBytes[i] != _inputBuffer[ptr+i]) { break main_switch; } } // yes, does match... _inputPtr = ptr + len; final String name = str.getValue(); if (_seenNames != null) { if (_seenNameCount >= _seenNames.length) { _seenNames = _expandSeenNames(_seenNames); } _seenNames[_seenNameCount++] = name; } _parsingContext.setCurrentName(name); _currToken = JsonToken.FIELD_NAME; return true; } } break; case 3: // short Unicode // all valid, except for 0xFF { int len = (ch & 0x3F); if (len > 0x37) { if (len == 0x3B) { _currToken = JsonToken.END_OBJECT; if (!_parsingContext.inObject()) { _reportMismatchedEndMarker('}', ']'); } _inputPtr = ptr; _parsingContext = _parsingContext.getParent(); return false; } // error, but let's not worry about that here break; } len += 2; // values from 2 to 57... if (len == byteLen) { int i = 0; for (; i < len; ++i) { if (nameBytes[i] != _inputBuffer[ptr+i]) { break main_switch; } } // yes, does match... _inputPtr = ptr + len; final String name = str.getValue(); if (_seenNames != null) { if (_seenNameCount >= _seenNames.length) { _seenNames = _expandSeenNames(_seenNames); } _seenNames[_seenNameCount++] = name; } _parsingContext.setCurrentName(name); _currToken = JsonToken.FIELD_NAME; return true; } } break; } } // otherwise fall back to default processing: JsonToken t = _handleFieldName(); _currToken = t; return (t == JsonToken.FIELD_NAME) && str.getValue().equals(_parsingContext.getCurrentName()); } // otherwise just fall back to default handling; should occur rarely return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName()); } @Override public String nextTextValue() throws IOException, JsonParseException { // can't get text value if expecting name, so if (!_parsingContext.inObject() || _currToken == JsonToken.FIELD_NAME) { if (_tokenIncomplete) { _skipIncomplete(); } int ptr = _inputPtr; if (ptr >= _inputEnd) { if (!loadMore()) { _handleEOF(); close(); _currToken = null; return null; } ptr = _inputPtr; } int ch = _inputBuffer[ptr++]; _tokenInputTotal = _currInputProcessed + _inputPtr; // also: clear any data retained so far _binaryValue = null; _typeByte = ch; switch ((ch >> 5) & 0x7) { case 0: // short shared string value reference if (ch == 0) { // important: this is invalid, don't accept _reportError("Invalid token byte 0x00"); } // _handleSharedString... { --ch; if (ch >= _seenStringValueCount) { _reportInvalidSharedStringValue(ch); } _inputPtr = ptr; String text = _seenStringValues[ch]; _textBuffer.resetWithString(text); _currToken = JsonToken.VALUE_STRING; return text; } case 1: // simple literals, numbers { int typeBits = ch & 0x1F; if (typeBits == 0x00) { _inputPtr = ptr; _textBuffer.resetWithEmpty(); _currToken = JsonToken.VALUE_STRING; return ""; } } break; case 2: // tiny ASCII // fall through case 3: // short ASCII _currToken = JsonToken.VALUE_STRING; _inputPtr = ptr; _decodeShortAsciiValue(1 + (ch & 0x3F)); { // No need to decode, unless we have to keep track of back-references (for shared string values) String text; if (_seenStringValueCount >= 0) { // shared text values enabled if (_seenStringValueCount < _seenStringValues.length) { text = _textBuffer.contentsAsString(); _seenStringValues[_seenStringValueCount++] = text; } else { _expandSeenStringValues(); text = _textBuffer.contentsAsString(); } } else { text = _textBuffer.contentsAsString(); } return text; } case 4: // tiny Unicode // fall through case 5: // short Unicode _currToken = JsonToken.VALUE_STRING; _inputPtr = ptr; _decodeShortUnicodeValue(2 + (ch & 0x3F)); { // No need to decode, unless we have to keep track of back-references (for shared string values) String text; if (_seenStringValueCount >= 0) { // shared text values enabled if (_seenStringValueCount < _seenStringValues.length) { text = _textBuffer.contentsAsString(); _seenStringValues[_seenStringValueCount++] = text; } else { _expandSeenStringValues(); text = _textBuffer.contentsAsString(); } } else { text = _textBuffer.contentsAsString(); } return text; } case 6: // small integers; zigzag encoded break; case 7: // binary/long-text/long-shared/start-end-markers // TODO: support longer strings too? /* switch (ch & 0x1F) { case 0x00: // long variable length ASCII case 0x04: // long variable length unicode _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_STRING); case 0x08: // binary, 7-bit break main; case 0x0C: // long shared string case 0x0D: case 0x0E: case 0x0F: if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return _handleSharedString(((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF)); } break; */ break; } } // otherwise fall back to generic handling: return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; } @Override public int nextIntValue(int defaultValue) throws IOException, JsonParseException { if (nextToken() == JsonToken.VALUE_NUMBER_INT) { return getIntValue(); } return defaultValue; } @Override public long nextLongValue(long defaultValue) throws IOException, JsonParseException { if (nextToken() == JsonToken.VALUE_NUMBER_INT) { return getLongValue(); } return defaultValue; } @Override public Boolean nextBooleanValue() throws IOException, JsonParseException { switch (nextToken()) { case VALUE_TRUE: return Boolean.TRUE; case VALUE_FALSE: return Boolean.FALSE; default: return null; } } /* /********************************************************** /* Public API, access to token information, text /********************************************************** */ /** * Method for accessing textual representation of the current event; * if no current event (before first call to {@link #nextToken}, or * after encountering end-of-input), returns null. * Method can be called for any event. */ @Override public String getText() throws IOException, JsonParseException { if (_tokenIncomplete) { _tokenIncomplete = false; // Let's inline part of "_finishToken", common case int tb = _typeByte; int type = (tb >> 5) & 0x7; if (type == 2 || type == 3) { // tiny & short ASCII _decodeShortAsciiValue(1 + (tb & 0x3F)); return _textBuffer.contentsAsString(); } if (type == 4 || type == 5) { // tiny & short Unicode // short unicode; note, lengths 2 - 65 (off-by-one compared to ASCII) _decodeShortUnicodeValue(2 + (tb & 0x3F)); return _textBuffer.contentsAsString(); } _finishToken(); } if (_currToken == JsonToken.VALUE_STRING) { return _textBuffer.contentsAsString(); } JsonToken t = _currToken; if (t == null) { // null only before/after document return null; } if (t == JsonToken.FIELD_NAME) { return _parsingContext.getCurrentName(); } if (t.isNumeric()) { // TODO: optimize? return getNumberValue().toString(); } return _currToken.asString(); } @Override public char[] getTextCharacters() throws IOException, JsonParseException { if (_currToken != null) { // null only before/after document if (_tokenIncomplete) { _finishToken(); } switch (_currToken) { case VALUE_STRING: return _textBuffer.getTextBuffer(); case FIELD_NAME: if (!_nameCopied) { String name = _parsingContext.getCurrentName(); int nameLen = name.length(); if (_nameCopyBuffer == null) { _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen); } else if (_nameCopyBuffer.length < nameLen) { _nameCopyBuffer = new char[nameLen]; } name.getChars(0, nameLen, _nameCopyBuffer, 0); _nameCopied = true; } return _nameCopyBuffer; // fall through case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: // TODO: optimize return getNumberValue().toString().toCharArray(); default: return _currToken.asCharArray(); } } return null; } @Override public int getTextLength() throws IOException, JsonParseException { if (_currToken != null) { // null only before/after document if (_tokenIncomplete) { _finishToken(); } switch (_currToken) { case VALUE_STRING: return _textBuffer.size(); case FIELD_NAME: return _parsingContext.getCurrentName().length(); // fall through case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: // TODO: optimize return getNumberValue().toString().length(); default: return _currToken.asCharArray().length; } } return 0; } @Override public int getTextOffset() throws IOException, JsonParseException { return 0; } @Override public String getValueAsString() throws IOException, JsonParseException { if (_currToken != JsonToken.VALUE_STRING) { if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) { return null; } } return getText(); } @Override public String getValueAsString(String defaultValue) throws IOException, JsonParseException { if (_currToken != JsonToken.VALUE_STRING) { if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) { return defaultValue; } } return getText(); } /* /********************************************************** /* Public API, access to token information, binary /********************************************************** */ @Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { if (_tokenIncomplete) { _finishToken(); } if (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT ) { // Todo, maybe: support base64 for text? _reportError("Current token ("+_currToken+") not VALUE_EMBEDDED_OBJECT, can not access as binary"); } return _binaryValue; } @Override public Object getEmbeddedObject() throws IOException, JsonParseException { if (_tokenIncomplete) { _finishToken(); } if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT ) { return _binaryValue; } return null; } @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException, JsonParseException { if (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT ) { // Todo, maybe: support base64 for text? _reportError("Current token ("+_currToken+") not VALUE_EMBEDDED_OBJECT, can not access as binary"); } // Ok, first, unlikely (but legal?) case where someone already requested binary data: if (!_tokenIncomplete) { if (_binaryValue == null) { // most likely already read... return 0; } final int len = _binaryValue.length; out.write(_binaryValue, 0, len); return len; } // otherwise, handle, mark as complete // first, raw inlined binary data (simple) if (_typeByte == SmileConstants.TOKEN_MISC_BINARY_RAW) { final int totalCount = _readUnsignedVInt(); int left = totalCount; while (left > 0) { int avail = _inputEnd - _inputPtr; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); avail = _inputEnd - _inputPtr; } int count = Math.min(avail, left); out.write(_inputBuffer, _inputPtr, count); _inputPtr += count; left -= count; } _tokenIncomplete = false; return totalCount; } if (_typeByte != SmileConstants.TOKEN_MISC_BINARY_7BIT) { _throwInternal(); } // or, alternative, 7-bit encoded stuff: final int totalCount = _readUnsignedVInt(); byte[] encodingBuffer = _ioContext.allocBase64Buffer(); try { _readBinaryEncoded(out, totalCount, encodingBuffer); } finally { _ioContext.releaseBase64Buffer(encodingBuffer); } _tokenIncomplete = false; return totalCount; } private void _readBinaryEncoded(OutputStream out, int length, byte[] buffer) throws IOException, JsonParseException { int outPtr = 0; final int lastSafeOut = buffer.length - 7; // first handle all full 7/8 units while (length > 7) { if ((_inputEnd - _inputPtr) < 8) { _loadToHaveAtLeast(8); } int i1 = (_inputBuffer[_inputPtr++] << 25) + (_inputBuffer[_inputPtr++] << 18) + (_inputBuffer[_inputPtr++] << 11) + (_inputBuffer[_inputPtr++] << 4); int x = _inputBuffer[_inputPtr++]; i1 += x >> 3; int i2 = ((x & 0x7) << 21) + (_inputBuffer[_inputPtr++] << 14) + (_inputBuffer[_inputPtr++] << 7) + _inputBuffer[_inputPtr++]; // Ok: got our 7 bytes, just need to split, copy buffer[outPtr++] = (byte)(i1 >> 24); buffer[outPtr++] = (byte)(i1 >> 16); buffer[outPtr++] = (byte)(i1 >> 8); buffer[outPtr++] = (byte)i1; buffer[outPtr++] = (byte)(i2 >> 16); buffer[outPtr++] = (byte)(i2 >> 8); buffer[outPtr++] = (byte)i2; length -= 7; // ensure there's always room for at least 7 bytes more after looping: if (outPtr > lastSafeOut) { out.write(buffer, 0, outPtr); outPtr = 0; } } // and then leftovers: n+1 bytes to decode n bytes if (length > 0) { if ((_inputEnd - _inputPtr) < (length+1)) { _loadToHaveAtLeast(length+1); } int value = _inputBuffer[_inputPtr++]; for (int i = 1; i < length; ++i) { value = (value << 7) + _inputBuffer[_inputPtr++]; buffer[outPtr++] = (byte) (value >> (7 - i)); } // last byte is different, has remaining 1 - 6 bits, right-aligned value <<= length; buffer[outPtr++] = (byte) (value + _inputBuffer[_inputPtr++]); } if (outPtr > 0) { out.write(buffer, 0, outPtr); } } /* /********************************************************** /* Internal methods, field name parsing /********************************************************** */ /** * Method that handles initial token type recognition for token * that has to be either FIELD_NAME or END_OBJECT. */ protected final JsonToken _handleFieldName() throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int ch = _inputBuffer[_inputPtr++]; // is this needed? _typeByte = ch; switch ((ch >> 6) & 3) { case 0: // misc, including end marker switch (ch) { case 0x20: // empty String as name, legal if unusual _parsingContext.setCurrentName(""); return JsonToken.FIELD_NAME; case 0x30: // long shared case 0x31: case 0x32: case 0x33: { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int index = ((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF); if (index >= _seenNameCount) { _reportInvalidSharedName(index); } _parsingContext.setCurrentName(_seenNames[index]); } return JsonToken.FIELD_NAME; case 0x34: // long ASCII/Unicode name _handleLongFieldName(); return JsonToken.FIELD_NAME; } break; case 1: // short shared, can fully process { int index = (ch & 0x3F); if (index >= _seenNameCount) { _reportInvalidSharedName(index); } _parsingContext.setCurrentName(_seenNames[index]); } return JsonToken.FIELD_NAME; case 2: // short ASCII { int len = 1 + (ch & 0x3f); String name; Name n = _findDecodedFromSymbols(len); if (n != null) { name = n.getName(); _inputPtr += len; } else { name = _decodeShortAsciiName(len); name = _addDecodedToSymbols(len, name); } if (_seenNames != null) { if (_seenNameCount >= _seenNames.length) { _seenNames = _expandSeenNames(_seenNames); } _seenNames[_seenNameCount++] = name; } _parsingContext.setCurrentName(name); } return JsonToken.FIELD_NAME; case 3: // short Unicode // all valid, except for 0xFF ch &= 0x3F; { if (ch > 0x37) { if (ch == 0x3B) { if (!_parsingContext.inObject()) { _reportMismatchedEndMarker('}', ']'); } _parsingContext = _parsingContext.getParent(); return JsonToken.END_OBJECT; } } else { final int len = ch + 2; // values from 2 to 57... String name; Name n = _findDecodedFromSymbols(len); if (n != null) { name = n.getName(); _inputPtr += len; } else { name = _decodeShortUnicodeName(len); name = _addDecodedToSymbols(len, name); } if (_seenNames != null) { if (_seenNameCount >= _seenNames.length) { _seenNames = _expandSeenNames(_seenNames); } _seenNames[_seenNameCount++] = name; } _parsingContext.setCurrentName(name); return JsonToken.FIELD_NAME; } } break; } // Other byte values are illegal _reportError("Invalid type marker byte 0x"+Integer.toHexString(_typeByte)+" for expected field name (or END_OBJECT marker)"); return null; } /** * Method called to try to expand shared name area to fit one more potentially * shared String. If area is already at its biggest size, will just clear * the area (by setting next-offset to 0) */ private final String[] _expandSeenNames(String[] oldShared) { int len = oldShared.length; String[] newShared; if (len == 0) { newShared = _smileBufferRecycler.allocSeenNamesBuffer(); if (newShared == null) { newShared = new String[SmileBufferRecycler.DEFAULT_NAME_BUFFER_LENGTH]; } } else if (len == SmileConstants.MAX_SHARED_NAMES) { // too many? Just flush... newShared = oldShared; _seenNameCount = 0; // could also clear, but let's not yet bother } else { int newSize = (len == SmileBufferRecycler.DEFAULT_STRING_VALUE_BUFFER_LENGTH) ? 256 : SmileConstants.MAX_SHARED_NAMES; newShared = new String[newSize]; System.arraycopy(oldShared, 0, newShared, 0, oldShared.length); } return newShared; } private final String _addDecodedToSymbols(int len, String name) { if (len < 5) { return _symbols.addName(name, _quad1, 0).getName(); } if (len < 9) { return _symbols.addName(name, _quad1, _quad2).getName(); } int qlen = (len + 3) >> 2; return _symbols.addName(name, _quadBuffer, qlen).getName(); } private final String _decodeShortAsciiName(int len) throws IOException, JsonParseException { // note: caller ensures we have enough bytes available char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); int outPtr = 0; final byte[] inBuf = _inputBuffer; int inPtr = _inputPtr; // loop unrolling seems to help here: for (int inEnd = inPtr + len - 3; inPtr < inEnd; ) { outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; } int left = (len & 3); if (left > 0) { outBuf[outPtr++] = (char) inBuf[inPtr++]; if (left > 1) { outBuf[outPtr++] = (char) inBuf[inPtr++]; if (left > 2) { outBuf[outPtr++] = (char) inBuf[inPtr++]; } } } _inputPtr = inPtr; _textBuffer.setCurrentLength(len); return _textBuffer.contentsAsString(); } /** * Helper method used to decode short Unicode string, length for which actual * length (in bytes) is known * * @param len Length between 1 and 64 */ private final String _decodeShortUnicodeName(int len) throws IOException, JsonParseException { // note: caller ensures we have enough bytes available int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); int inPtr = _inputPtr; _inputPtr += len; final int[] codes = SmileConstants.sUtf8UnitLengths; final byte[] inBuf = _inputBuffer; for (int end = inPtr + len; inPtr < end; ) { int i = inBuf[inPtr++] & 0xFF; int code = codes[i]; if (code != 0) { // trickiest one, need surrogate handling switch (code) { case 1: i = ((i & 0x1F) << 6) | (inBuf[inPtr++] & 0x3F); break; case 2: i = ((i & 0x0F) << 12) | ((inBuf[inPtr++] & 0x3F) << 6) | (inBuf[inPtr++] & 0x3F); break; case 3: i = ((i & 0x07) << 18) | ((inBuf[inPtr++] & 0x3F) << 12) | ((inBuf[inPtr++] & 0x3F) << 6) | (inBuf[inPtr++] & 0x3F); // note: this is the codepoint value; need to split, too i -= 0x10000; outBuf[outPtr++] = (char) (0xD800 | (i >> 10)); i = 0xDC00 | (i & 0x3FF); break; default: // invalid _reportError("Invalid byte "+Integer.toHexString(i)+" in short Unicode text block"); } } outBuf[outPtr++] = (char) i; } _textBuffer.setCurrentLength(outPtr); return _textBuffer.contentsAsString(); } // note: slightly edited copy of UTF8StreamParser.addName() private final Name _decodeLongUnicodeName(int[] quads, int byteLen, int quadLen) throws IOException, JsonParseException { int lastQuadBytes = byteLen & 3; // Ok: must decode UTF-8 chars. No other validation SHOULD be needed (except bounds checks?) /* Note: last quad is not correctly aligned (leading zero bytes instead * need to shift a bit, instead of trailing). Only need to shift it * for UTF-8 decoding; need revert for storage (since key will not * be aligned, to optimize lookup speed) */ int lastQuad; if (lastQuadBytes < 4) { lastQuad = quads[quadLen-1]; // 8/16/24 bit left shift quads[quadLen-1] = (lastQuad << ((4 - lastQuadBytes) << 3)); } else { lastQuad = 0; } char[] cbuf = _textBuffer.emptyAndGetCurrentSegment(); int cix = 0; for (int ix = 0; ix < byteLen; ) { int ch = quads[ix >> 2]; // current quad, need to shift+mask int byteIx = (ix & 3); ch = (ch >> ((3 - byteIx) << 3)) & 0xFF; ++ix; if (ch > 127) { // multi-byte int needed; if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) ch &= 0x1F; needed = 1; } else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) ch &= 0x0F; needed = 2; } else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all... ch &= 0x07; needed = 3; } else { // 5- and 6-byte chars not valid chars _reportInvalidInitial(ch); needed = ch = 1; // never really gets this far } if ((ix + needed) > byteLen) { _reportInvalidEOF(" in long field name"); } // Ok, always need at least one more: int ch2 = quads[ix >> 2]; // current quad, need to shift+mask byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2); } ch = (ch << 6) | (ch2 & 0x3F); if (needed > 1) { ch2 = quads[ix >> 2]; byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2); } ch = (ch << 6) | (ch2 & 0x3F); if (needed > 2) { // 4 bytes? (need surrogates on output) ch2 = quads[ix >> 2]; byteIx = (ix & 3); ch2 = (ch2 >> ((3 - byteIx) << 3)); ++ix; if ((ch2 & 0xC0) != 0x080) { _reportInvalidOther(ch2 & 0xFF); } ch = (ch << 6) | (ch2 & 0x3F); } } if (needed > 2) { // surrogate pair? once again, let's output one here, one later on ch -= 0x10000; // to normalize it starting with 0x0 if (cix >= cbuf.length) { cbuf = _textBuffer.expandCurrentSegment(); } cbuf[cix++] = (char) (0xD800 + (ch >> 10)); ch = 0xDC00 | (ch & 0x03FF); } } if (cix >= cbuf.length) { cbuf = _textBuffer.expandCurrentSegment(); } cbuf[cix++] = (char) ch; } // Ok. Now we have the character array, and can construct the String String baseName = new String(cbuf, 0, cix); // And finally, un-align if necessary if (lastQuadBytes < 4) { quads[quadLen-1] = lastQuad; } return _symbols.addName(baseName, quads, quadLen); } private final void _handleLongFieldName() throws IOException, JsonParseException { // First: gather quads we need, looking for end marker final byte[] inBuf = _inputBuffer; int quads = 0; int bytes = 0; int q = 0; while (true) { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } byte b = inBuf[_inputPtr++]; if (BYTE_MARKER_END_OF_STRING == b) { bytes = 0; break; } q = ((int) b) & 0xFF; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } b = inBuf[_inputPtr++]; if (BYTE_MARKER_END_OF_STRING == b) { bytes = 1; break; } q = (q << 8) | (b & 0xFF); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } b = inBuf[_inputPtr++]; if (BYTE_MARKER_END_OF_STRING == b) { bytes = 2; break; } q = (q << 8) | (b & 0xFF); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } b = inBuf[_inputPtr++]; if (BYTE_MARKER_END_OF_STRING == b) { bytes = 3; break; } q = (q << 8) | (b & 0xFF); if (quads >= _quadBuffer.length) { _quadBuffer = _growArrayTo(_quadBuffer, _quadBuffer.length + 256); // grow by 1k } _quadBuffer[quads++] = q; } // and if we have more bytes, append those too int byteLen = (quads << 2); if (bytes > 0) { if (quads >= _quadBuffer.length) { _quadBuffer = _growArrayTo(_quadBuffer, _quadBuffer.length + 256); } _quadBuffer[quads++] = q; byteLen += bytes; } // Know this name already? String name; Name n = _symbols.findName(_quadBuffer, quads); if (n != null) { name = n.getName(); } else { name = _decodeLongUnicodeName(_quadBuffer, byteLen, quads).getName(); } if (_seenNames != null) { if (_seenNameCount >= _seenNames.length) { _seenNames = _expandSeenNames(_seenNames); } _seenNames[_seenNameCount++] = name; } _parsingContext.setCurrentName(name); } /** * Helper method for trying to find specified encoded UTF-8 byte sequence * from symbol table; if successful avoids actual decoding to String */ private final Name _findDecodedFromSymbols(int len) throws IOException, JsonParseException { if ((_inputEnd - _inputPtr) < len) { _loadToHaveAtLeast(len); } // First: maybe we already have this name decoded? if (len < 5) { int inPtr = _inputPtr; final byte[] inBuf = _inputBuffer; int q = inBuf[inPtr] & 0xFF; if (--len > 0) { q = (q << 8) + (inBuf[++inPtr] & 0xFF); if (--len > 0) { q = (q << 8) + (inBuf[++inPtr] & 0xFF); if (--len > 0) { q = (q << 8) + (inBuf[++inPtr] & 0xFF); } } } _quad1 = q; return _symbols.findName(q); } if (len < 9) { int inPtr = _inputPtr; final byte[] inBuf = _inputBuffer; // First quadbyte is easy int q1 = (inBuf[inPtr] & 0xFF) << 8; q1 += (inBuf[++inPtr] & 0xFF); q1 <<= 8; q1 += (inBuf[++inPtr] & 0xFF); q1 <<= 8; q1 += (inBuf[++inPtr] & 0xFF); int q2 = (inBuf[++inPtr] & 0xFF); len -= 5; if (len > 0) { q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF); if (--len > 0) { q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF); if (--len > 0) { q2 = (q2 << 8) + (inBuf[++inPtr] & 0xFF); } } } _quad1 = q1; _quad2 = q2; return _symbols.findName(q1, q2); } return _findDecodedMedium(len); } /** * Method for locating names longer than 8 bytes (in UTF-8) */ private final Name _findDecodedMedium(int len) throws IOException, JsonParseException { // first, need enough buffer to store bytes as ints: { int bufLen = (len + 3) >> 2; if (bufLen > _quadBuffer.length) { _quadBuffer = _growArrayTo(_quadBuffer, bufLen); } } // then decode, full quads first int offset = 0; int inPtr = _inputPtr; final byte[] inBuf = _inputBuffer; do { int q = (inBuf[inPtr++] & 0xFF) << 8; q |= inBuf[inPtr++] & 0xFF; q <<= 8; q |= inBuf[inPtr++] & 0xFF; q <<= 8; q |= inBuf[inPtr++] & 0xFF; _quadBuffer[offset++] = q; } while ((len -= 4) > 3); // and then leftovers if (len > 0) { int q = inBuf[inPtr] & 0xFF; if (--len > 0) { q = (q << 8) + (inBuf[++inPtr] & 0xFF); if (--len > 0) { q = (q << 8) + (inBuf[++inPtr] & 0xFF); } } _quadBuffer[offset++] = q; } return _symbols.findName(_quadBuffer, offset); } private static int[] _growArrayTo(int[] arr, int minSize) { int[] newArray = new int[minSize + 4]; if (arr != null) { // !!! TODO: JDK 1.6, Arrays.copyOf System.arraycopy(arr, 0, newArray, 0, arr.length); } return newArray; } /* /********************************************************** /* Internal methods, secondary parsing /********************************************************** */ @Override protected void _parseNumericValue(int expType) throws IOException, JsonParseException { if (_tokenIncomplete) { int tb = _typeByte; // ensure we got a numeric type with value that is lazily parsed if (((tb >> 5) & 0x7) != 1) { _reportError("Current token ("+_currToken+") not numeric, can not use numeric value accessors"); } _tokenIncomplete = false; _finishNumberToken(tb); } } /** * Method called to finish parsing of a token so that token contents * are retriable */ protected void _finishToken() throws IOException, JsonParseException { _tokenIncomplete = false; int tb = _typeByte; int type = ((tb >> 5) & 0x7); if (type == 1) { // simple literals, numbers _finishNumberToken(tb); return; } if (type <= 3) { // tiny & short ASCII _decodeShortAsciiValue(1 + (tb & 0x3F)); return; } if (type <= 5) { // tiny & short Unicode // short unicode; note, lengths 2 - 65 (off-by-one compared to ASCII) _decodeShortUnicodeValue(2 + (tb & 0x3F)); return; } if (type == 7) { tb &= 0x1F; // next 3 bytes define subtype switch (tb >> 2) { case 0: // long variable length ASCII _decodeLongAscii(); return; case 1: // long variable length Unicode _decodeLongUnicode(); return; case 2: // binary, 7-bit _binaryValue = _read7BitBinaryWithLength(); return; case 7: // binary, raw _finishRawBinary(); return; } } // sanity check _throwInternal(); } protected final void _finishNumberToken(int tb) throws IOException, JsonParseException { tb &= 0x1F; int type = (tb >> 2); if (type == 1) { // VInt (zigzag) or BigDecimal int subtype = tb & 0x03; if (subtype == 0) { // (v)int _finishInt(); } else if (subtype == 1) { // (v)long _finishLong(); } else if (subtype == 2) { _finishBigInteger(); } else { _throwInternal(); } return; } if (type == 2) { // other numbers switch (tb & 0x03) { case 0: // float _finishFloat(); return; case 1: // double _finishDouble(); return; case 2: // big-decimal _finishBigDecimal(); return; } } _throwInternal(); } /* /********************************************************** /* Internal methods, secondary Number parsing /********************************************************** */ private final void _finishInt() throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int value = _inputBuffer[_inputPtr++]; int i; if (value < 0) { // 6 bits value &= 0x3F; } else { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = _inputBuffer[_inputPtr++]; if (i >= 0) { // 13 bits value = (value << 7) + i; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = _inputBuffer[_inputPtr++]; if (i >= 0) { value = (value << 7) + i; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = _inputBuffer[_inputPtr++]; if (i >= 0) { value = (value << 7) + i; // and then we must get negative if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = _inputBuffer[_inputPtr++]; if (i >= 0) { _reportError("Corrupt input; 32-bit VInt extends beyond 5 data bytes"); } } } } value = (value << 6) + (i & 0x3F); } _numberInt = SmileUtil.zigzagDecode(value); _numTypesValid = NR_INT; } private final void _finishLong() throws IOException, JsonParseException { // Ok, first, will always get 4 full data bytes first; 1 was already passed long l = (long) _fourBytesToInt(); // and loop for the rest while (true) { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int value = _inputBuffer[_inputPtr++]; if (value < 0) { l = (l << 6) + (value & 0x3F); _numberLong = SmileUtil.zigzagDecode(l); _numTypesValid = NR_LONG; return; } l = (l << 7) + value; } } private final void _finishBigInteger() throws IOException, JsonParseException { byte[] raw = _read7BitBinaryWithLength(); _numberBigInt = new BigInteger(raw); _numTypesValid = NR_BIGINT; } private final void _finishFloat() throws IOException, JsonParseException { // just need 5 bytes to get int32 first; all are unsigned int i = _fourBytesToInt(); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = (i << 7) + _inputBuffer[_inputPtr++]; float f = Float.intBitsToFloat(i); _numberDouble = (double) f; _numTypesValid = NR_DOUBLE; } private final void _finishDouble() throws IOException, JsonParseException { // ok; let's take two sets of 4 bytes (each is int) long hi = _fourBytesToInt(); long value = (hi << 28) + (long) _fourBytesToInt(); // and then remaining 2 bytes if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } value = (value << 7) + _inputBuffer[_inputPtr++]; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } value = (value << 7) + _inputBuffer[_inputPtr++]; _numberDouble = Double.longBitsToDouble(value); _numTypesValid = NR_DOUBLE; } private final int _fourBytesToInt() throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int i = _inputBuffer[_inputPtr++]; // first 7 bits if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = (i << 7) + _inputBuffer[_inputPtr++]; // 14 bits if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } i = (i << 7) + _inputBuffer[_inputPtr++]; // 21 if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return (i << 7) + _inputBuffer[_inputPtr++]; } private final void _finishBigDecimal() throws IOException, JsonParseException { int scale = SmileUtil.zigzagDecode(_readUnsignedVInt()); byte[] raw = _read7BitBinaryWithLength(); _numberBigDecimal = new BigDecimal(new BigInteger(raw), scale); _numTypesValid = NR_BIGDECIMAL; } private final int _readUnsignedVInt() throws IOException, JsonParseException { int value = 0; while (true) { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int i = _inputBuffer[_inputPtr++]; if (i < 0) { // last byte value = (value << 6) + (i & 0x3F); return value; } value = (value << 7) + i; } } private final byte[] _read7BitBinaryWithLength() throws IOException, JsonParseException { int byteLen = _readUnsignedVInt(); byte[] result = new byte[byteLen]; int ptr = 0; int lastOkPtr = byteLen - 7; // first, read all 7-by-8 byte chunks while (ptr <= lastOkPtr) { if ((_inputEnd - _inputPtr) < 8) { _loadToHaveAtLeast(8); } int i1 = (_inputBuffer[_inputPtr++] << 25) + (_inputBuffer[_inputPtr++] << 18) + (_inputBuffer[_inputPtr++] << 11) + (_inputBuffer[_inputPtr++] << 4); int x = _inputBuffer[_inputPtr++]; i1 += x >> 3; int i2 = ((x & 0x7) << 21) + (_inputBuffer[_inputPtr++] << 14) + (_inputBuffer[_inputPtr++] << 7) + _inputBuffer[_inputPtr++]; // Ok: got our 7 bytes, just need to split, copy result[ptr++] = (byte)(i1 >> 24); result[ptr++] = (byte)(i1 >> 16); result[ptr++] = (byte)(i1 >> 8); result[ptr++] = (byte)i1; result[ptr++] = (byte)(i2 >> 16); result[ptr++] = (byte)(i2 >> 8); result[ptr++] = (byte)i2; } // and then leftovers: n+1 bytes to decode n bytes int toDecode = (result.length - ptr); if (toDecode > 0) { if ((_inputEnd - _inputPtr) < (toDecode+1)) { _loadToHaveAtLeast(toDecode+1); } int value = _inputBuffer[_inputPtr++]; for (int i = 1; i < toDecode; ++i) { value = (value << 7) + _inputBuffer[_inputPtr++]; result[ptr++] = (byte) (value >> (7 - i)); } // last byte is different, has remaining 1 - 6 bits, right-aligned value <<= toDecode; result[ptr] = (byte) (value + _inputBuffer[_inputPtr++]); } return result; } /* /********************************************************** /* Internal methods, secondary String parsing /********************************************************** */ protected final void _decodeShortAsciiValue(int len) throws IOException, JsonParseException { if ((_inputEnd - _inputPtr) < len) { _loadToHaveAtLeast(len); } // Note: we count on fact that buffer must have at least 'len' (<= 64) empty char slots final char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); int outPtr = 0; final byte[] inBuf = _inputBuffer; int inPtr = _inputPtr; // loop unrolling SHOULD be faster (as with _decodeShortAsciiName), but somehow // is NOT; as per testing, benchmarking... very weird. /* for (int inEnd = inPtr + len - 3; inPtr < inEnd; ) { outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; outBuf[outPtr++] = (char) inBuf[inPtr++]; } int left = (len & 3); if (left > 0) { outBuf[outPtr++] = (char) inBuf[inPtr++]; if (left > 1) { outBuf[outPtr++] = (char) inBuf[inPtr++]; if (left > 2) { outBuf[outPtr++] = (char) inBuf[inPtr++]; } } } */ // meaning: regular tight loop is no slower, typically faster here: for (final int end = inPtr + len; inPtr < end; ++inPtr) { outBuf[outPtr++] = (char) inBuf[inPtr]; } _inputPtr = inPtr; _textBuffer.setCurrentLength(len); } protected final void _decodeShortUnicodeValue(int len) throws IOException, JsonParseException { if ((_inputEnd - _inputPtr) < len) { _loadToHaveAtLeast(len); } int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); int inPtr = _inputPtr; _inputPtr += len; final int[] codes = SmileConstants.sUtf8UnitLengths; final byte[] inputBuf = _inputBuffer; for (int end = inPtr + len; inPtr < end; ) { int i = inputBuf[inPtr++] & 0xFF; int code = codes[i]; if (code != 0) { // trickiest one, need surrogate handling switch (code) { case 1: i = ((i & 0x1F) << 6) | (inputBuf[inPtr++] & 0x3F); break; case 2: i = ((i & 0x0F) << 12) | ((inputBuf[inPtr++] & 0x3F) << 6) | (inputBuf[inPtr++] & 0x3F); break; case 3: i = ((i & 0x07) << 18) | ((inputBuf[inPtr++] & 0x3F) << 12) | ((inputBuf[inPtr++] & 0x3F) << 6) | (inputBuf[inPtr++] & 0x3F); // note: this is the codepoint value; need to split, too i -= 0x10000; outBuf[outPtr++] = (char) (0xD800 | (i >> 10)); i = 0xDC00 | (i & 0x3FF); break; default: // invalid _reportError("Invalid byte "+Integer.toHexString(i)+" in short Unicode text block"); } } outBuf[outPtr++] = (char) i; } _textBuffer.setCurrentLength(outPtr); } private final void _decodeLongAscii() throws IOException, JsonParseException { int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); main_loop: while (true) { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int inPtr = _inputPtr; int left = _inputEnd - inPtr; if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } left = Math.min(left, outBuf.length - outPtr); do { byte b = _inputBuffer[inPtr++]; if (b == SmileConstants.BYTE_MARKER_END_OF_STRING) { _inputPtr = inPtr; break main_loop; } outBuf[outPtr++] = (char) b; } while (--left > 0); _inputPtr = inPtr; } _textBuffer.setCurrentLength(outPtr); } private final void _decodeLongUnicode() throws IOException, JsonParseException { int outPtr = 0; char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); final int[] codes = SmileConstants.sUtf8UnitLengths; int c; final byte[] inputBuffer = _inputBuffer; main_loop: while (true) { // First the tight ASCII loop: ascii_loop: while (true) { int ptr = _inputPtr; if (ptr >= _inputEnd) { loadMoreGuaranteed(); ptr = _inputPtr; } if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } int max = _inputEnd; { int max2 = ptr + (outBuf.length - outPtr); if (max2 < max) { max = max2; } } while (ptr < max) { c = (int) inputBuffer[ptr++] & 0xFF; if (codes[c] != 0) { _inputPtr = ptr; break ascii_loop; } outBuf[outPtr++] = (char) c; } _inputPtr = ptr; } // Ok: end marker, escape or multi-byte? if (c == SmileConstants.INT_MARKER_END_OF_STRING) { break main_loop; } switch (codes[c]) { case 1: // 2-byte UTF c = _decodeUtf8_2(c); break; case 2: // 3-byte UTF if ((_inputEnd - _inputPtr) >= 2) { c = _decodeUtf8_3fast(c); } else { c = _decodeUtf8_3(c); } break; case 3: // 4-byte UTF c = _decodeUtf8_4(c); // Let's add first part right away: outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } c = 0xDC00 | (c & 0x3FF); // And let the other char output down below break; default: // Is this good enough error message? _reportInvalidChar(c); } // Need more room? if (outPtr >= outBuf.length) { outBuf = _textBuffer.finishCurrentSegment(); outPtr = 0; } // Ok, let's add char to output: outBuf[outPtr++] = (char) c; } _textBuffer.setCurrentLength(outPtr); } private final void _finishRawBinary() throws IOException, JsonParseException { int byteLen = _readUnsignedVInt(); _binaryValue = new byte[byteLen]; if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int ptr = 0; while (true) { int toAdd = Math.min(byteLen, _inputEnd - _inputPtr); System.arraycopy(_inputBuffer, _inputPtr, _binaryValue, ptr, toAdd); _inputPtr += toAdd; ptr += toAdd; byteLen -= toAdd; if (byteLen <= 0) { return; } loadMoreGuaranteed(); } } /* /********************************************************** /* Internal methods, skipping /********************************************************** */ /** * Method called to skip remainders of an incomplete token, when * contents themselves will not be needed any more */ protected void _skipIncomplete() throws IOException, JsonParseException { _tokenIncomplete = false; int tb = _typeByte; switch ((tb >> 5) & 0x7) { case 1: // simple literals, numbers tb &= 0x1F; // next 3 bytes define subtype switch (tb >> 2) { case 1: // VInt (zigzag) // easy, just skip until we see sign bit... (should we try to limit damage?) switch (tb & 0x3) { case 1: // vlong _skipBytes(4); // min 5 bytes // fall through case 0: // vint while (true) { final int end = _inputEnd; final byte[] buf = _inputBuffer; while (_inputPtr < end) { if (buf[_inputPtr++] < 0) { return; } } loadMoreGuaranteed(); } case 2: // big-int // just has binary data _skip7BitBinary(); return; } break; case 2: // other numbers switch (tb & 0x3) { case 0: // float _skipBytes(5); return; case 1: // double _skipBytes(10); return; case 2: // big-decimal // first, skip scale _readUnsignedVInt(); // then length-prefixed binary serialization _skip7BitBinary(); return; } break; } break; case 2: // tiny ASCII // fall through case 3: // short ASCII _skipBytes(1 + (tb & 0x3F)); return; case 4: // tiny unicode // fall through case 5: // short unicode _skipBytes(2 + (tb & 0x3F)); return; case 7: tb &= 0x1F; // next 3 bytes define subtype switch (tb >> 2) { case 0: // long variable length ASCII case 1: // long variable length unicode /* Doesn't matter which one, just need to find the end marker * (note: can potentially skip invalid UTF-8 too) */ while (true) { final int end = _inputEnd; final byte[] buf = _inputBuffer; while (_inputPtr < end) { if (buf[_inputPtr++] == BYTE_MARKER_END_OF_STRING) { return; } } loadMoreGuaranteed(); } // never gets here case 2: // binary, 7-bit _skip7BitBinary(); return; case 7: // binary, raw _skipBytes(_readUnsignedVInt()); return; } } _throwInternal(); } protected void _skipBytes(int len) throws IOException, JsonParseException { while (true) { int toAdd = Math.min(len, _inputEnd - _inputPtr); _inputPtr += toAdd; len -= toAdd; if (len <= 0) { return; } loadMoreGuaranteed(); } } /** * Helper method for skipping length-prefixed binary data * section */ protected void _skip7BitBinary() throws IOException, JsonParseException { int origBytes = _readUnsignedVInt(); // Ok; 8 encoded bytes for 7 payload bytes first int chunks = origBytes / 7; int encBytes = chunks * 8; // and for last 0 - 6 bytes, last+1 (except none if no leftovers) origBytes -= 7 * chunks; if (origBytes > 0) { encBytes += 1 + origBytes; } _skipBytes(encBytes); } /* /********************************************************** /* Internal methods, UTF8 decoding /********************************************************** */ private final int _decodeUtf8_2(int c) throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } return ((c & 0x1F) << 6) | (d & 0x3F); } private final int _decodeUtf8_3(int c1) throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } c1 &= 0x0F; int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } int c = (c1 << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); return c; } private final int _decodeUtf8_3fast(int c1) throws IOException, JsonParseException { c1 &= 0x0F; int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } int c = (c1 << 6) | (d & 0x3F); d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); return c; } /** * @return Character value <b>minus 0x10000</c>; this so that caller * can readily expand it to actual surrogates */ private final int _decodeUtf8_4(int c) throws IOException, JsonParseException { if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } int d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = ((c & 0x07) << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } c = (c << 6) | (d & 0x3F); if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } d = (int) _inputBuffer[_inputPtr++]; if ((d & 0xC0) != 0x080) { _reportInvalidOther(d & 0xFF, _inputPtr); } /* note: won't change it to negative here, since caller * already knows it'll need a surrogate */ return ((c << 6) | (d & 0x3F)) - 0x10000; } /* /********************************************************** /* Internal methods, error reporting /********************************************************** */ protected void _reportInvalidSharedName(int index) throws IOException { if (_seenNames == null) { _reportError("Encountered shared name reference, even though document header explicitly declared no shared name references are included"); } _reportError("Invalid shared name reference "+index+"; only got "+_seenNameCount+" names in buffer (invalid content)"); } protected void _reportInvalidSharedStringValue(int index) throws IOException { if (_seenStringValues == null) { _reportError("Encountered shared text value reference, even though document header did not declared shared text value references may be included"); } _reportError("Invalid shared text value reference "+index+"; only got "+_seenStringValueCount+" names in buffer (invalid content)"); } protected void _reportInvalidChar(int c) throws JsonParseException { // Either invalid WS or illegal UTF-8 start char if (c < ' ') { _throwInvalidSpace(c); } _reportInvalidInitial(c); } protected void _reportInvalidInitial(int mask) throws JsonParseException { _reportError("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask)); } protected void _reportInvalidOther(int mask) throws JsonParseException { _reportError("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask)); } protected void _reportInvalidOther(int mask, int ptr) throws JsonParseException { _inputPtr = ptr; _reportInvalidOther(mask); } }
false
true
public JsonToken nextToken() throws IOException, JsonParseException { _numTypesValid = NR_UNKNOWN; // For longer tokens (text, binary), we'll only read when requested if (_tokenIncomplete) { _skipIncomplete(); } _tokenInputTotal = _currInputProcessed + _inputPtr; // also: clear any data retained so far _binaryValue = null; // Two main modes: values, and field names. if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) { return (_currToken = _handleFieldName()); } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _handleEOF(); /* NOTE: here we can and should close input, release buffers, * since this is "hard" EOF, not a boundary imposed by * header token. */ close(); return (_currToken = null); } } int ch = _inputBuffer[_inputPtr++]; _typeByte = ch; switch ((ch >> 5) & 0x7) { case 0: // short shared string value reference if (ch == 0) { // important: this is invalid, don't accept _reportError("Invalid token byte 0x00"); } return _handleSharedString(ch-1); case 1: // simple literals, numbers { int typeBits = ch & 0x1F; if (typeBits < 4) { switch (typeBits) { case 0x00: _textBuffer.resetWithEmpty(); return (_currToken = JsonToken.VALUE_STRING); case 0x01: return (_currToken = JsonToken.VALUE_NULL); case 0x02: // false return (_currToken = JsonToken.VALUE_FALSE); default: // 0x03 == true return (_currToken = JsonToken.VALUE_TRUE); } } // next 3 bytes define subtype if (typeBits < 8) { // VInt (zigzag), BigInteger if ((typeBits & 0x3) <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; return (_currToken = JsonToken.VALUE_NUMBER_INT); } break; } if (typeBits < 12) { // floating-point int subtype = typeBits & 0x3; if (subtype <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; _got32BitFloat = (subtype == 0); return (_currToken = JsonToken.VALUE_NUMBER_FLOAT); } break; } if (typeBits == 0x1A) { // == 0x3A == ':' -> possibly header signature for next chunk? if (handleSignature(false, false)) { /* Ok, now; end-marker and header both imply doc boundary and a * 'null token'; but if both are seen, they are collapsed. * We can check this by looking at current token; if it's null, * need to get non-null token */ if (_currToken == null) { return nextToken(); } return (_currToken = null); } } _reportError("Unrecognized token byte 0x3A (malformed segment header?"); } // and everything else is reserved, for now break; case 2: // tiny ASCII // fall through case 3: // short ASCII // fall through case 4: // tiny Unicode // fall through case 5: // short Unicode // No need to decode, unless we have to keep track of back-references (for shared string values) _currToken = JsonToken.VALUE_STRING; if (_seenStringValueCount >= 0) { // shared text values enabled _addSeenStringValue(); } else { _tokenIncomplete = true; } return _currToken; case 6: // small integers; zigzag encoded _numberInt = SmileUtil.zigzagDecode(ch & 0x1F); _numTypesValid = NR_INT; return (_currToken = JsonToken.VALUE_NUMBER_INT); case 7: // binary/long-text/long-shared/start-end-markers switch (ch & 0x1F) { case 0x00: // long variable length ASCII case 0x04: // long variable length unicode _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_STRING); case 0x08: // binary, 7-bit _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); case 0x0C: // long shared string case 0x0D: case 0x0E: case 0x0F: if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return _handleSharedString(((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF)); case 0x18: // START_ARRAY _parsingContext = _parsingContext.createChildArrayContext(-1, -1); return (_currToken = JsonToken.START_ARRAY); case 0x19: // END_ARRAY if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(']', '}'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_ARRAY); case 0x1A: // START_OBJECT _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); case 0x1B: // not used in this mode; would be END_OBJECT _reportError("Invalid type marker byte 0xFB in value mode (would be END_OBJECT in key mode)"); case 0x1D: // binary, raw _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); case 0x1F: // 0xFF, end of content return (_currToken = null); } break; } // If we get this far, type byte is corrupt _reportError("Invalid type marker byte 0x"+Integer.toHexString(ch & 0xFF)+" for expected value token"); return null; }
public JsonToken nextToken() throws IOException, JsonParseException { _numTypesValid = NR_UNKNOWN; // For longer tokens (text, binary), we'll only read when requested if (_tokenIncomplete) { _skipIncomplete(); } _tokenInputTotal = _currInputProcessed + _inputPtr; // also: clear any data retained so far _binaryValue = null; // Two main modes: values, and field names. if (_parsingContext.inObject() && _currToken != JsonToken.FIELD_NAME) { return (_currToken = _handleFieldName()); } if (_inputPtr >= _inputEnd) { if (!loadMore()) { _handleEOF(); /* NOTE: here we can and should close input, release buffers, * since this is "hard" EOF, not a boundary imposed by * header token. */ close(); return (_currToken = null); } } int ch = _inputBuffer[_inputPtr++]; _typeByte = ch; switch ((ch >> 5) & 0x7) { case 0: // short shared string value reference if (ch == 0) { // important: this is invalid, don't accept _reportError("Invalid token byte 0x00"); } return _handleSharedString(ch-1); case 1: // simple literals, numbers { int typeBits = ch & 0x1F; if (typeBits < 4) { switch (typeBits) { case 0x00: _textBuffer.resetWithEmpty(); return (_currToken = JsonToken.VALUE_STRING); case 0x01: return (_currToken = JsonToken.VALUE_NULL); case 0x02: // false return (_currToken = JsonToken.VALUE_FALSE); default: // 0x03 == true return (_currToken = JsonToken.VALUE_TRUE); } } // next 3 bytes define subtype if (typeBits < 8) { // VInt (zigzag), BigInteger if ((typeBits & 0x3) <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; return (_currToken = JsonToken.VALUE_NUMBER_INT); } break; } if (typeBits < 12) { // floating-point int subtype = typeBits & 0x3; if (subtype <= 0x2) { // 0x3 reserved (should never occur) _tokenIncomplete = true; _numTypesValid = 0; _got32BitFloat = (subtype == 0); return (_currToken = JsonToken.VALUE_NUMBER_FLOAT); } break; } if (typeBits == 0x1A) { // == 0x3A == ':' -> possibly header signature for next chunk? if (handleSignature(false, false)) { /* Ok, now; end-marker and header both imply doc boundary and a * 'null token'; but if both are seen, they are collapsed. * We can check this by looking at current token; if it's null, * need to get non-null token */ if (_currToken == null) { return nextToken(); } return (_currToken = null); } } _reportError("Unrecognized token byte 0x3A (malformed segment header?"); } // and everything else is reserved, for now break; case 2: // tiny ASCII // fall through case 3: // short ASCII // fall through case 4: // tiny Unicode // fall through case 5: // short Unicode // No need to decode, unless we have to keep track of back-references (for shared string values) _currToken = JsonToken.VALUE_STRING; if (_seenStringValueCount >= 0) { // shared text values enabled _addSeenStringValue(); } else { _tokenIncomplete = true; } return _currToken; case 6: // small integers; zigzag encoded _numberInt = SmileUtil.zigzagDecode(ch & 0x1F); _numTypesValid = NR_INT; return (_currToken = JsonToken.VALUE_NUMBER_INT); case 7: // binary/long-text/long-shared/start-end-markers switch (ch & 0x1F) { case 0x00: // long variable length ASCII case 0x04: // long variable length unicode _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_STRING); case 0x08: // binary, 7-bit (0xE8) _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); case 0x0C: // long shared string (0xEC) case 0x0D: case 0x0E: case 0x0F: if (_inputPtr >= _inputEnd) { loadMoreGuaranteed(); } return _handleSharedString(((ch & 0x3) << 8) + (_inputBuffer[_inputPtr++] & 0xFF)); case 0x18: // START_ARRAY _parsingContext = _parsingContext.createChildArrayContext(-1, -1); return (_currToken = JsonToken.START_ARRAY); case 0x19: // END_ARRAY if (!_parsingContext.inArray()) { _reportMismatchedEndMarker(']', '}'); } _parsingContext = _parsingContext.getParent(); return (_currToken = JsonToken.END_ARRAY); case 0x1A: // START_OBJECT _parsingContext = _parsingContext.createChildObjectContext(-1, -1); return (_currToken = JsonToken.START_OBJECT); case 0x1B: // not used in this mode; would be END_OBJECT _reportError("Invalid type marker byte 0xFB in value mode (would be END_OBJECT in key mode)"); case 0x1D: // binary, raw _tokenIncomplete = true; return (_currToken = JsonToken.VALUE_EMBEDDED_OBJECT); case 0x1F: // 0xFF, end of content return (_currToken = null); } break; } // If we get this far, type byte is corrupt _reportError("Invalid type marker byte 0x"+Integer.toHexString(ch & 0xFF)+" for expected value token"); return null; }
diff --git a/src/main/java/org/dynmap/MapManager.java b/src/main/java/org/dynmap/MapManager.java index 90cd4be7..3c7b0019 100644 --- a/src/main/java/org/dynmap/MapManager.java +++ b/src/main/java/org/dynmap/MapManager.java @@ -1,808 +1,810 @@ package org.dynmap; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.command.CommandSender; import org.dynmap.DynmapWorld.AutoGenerateOption; import org.dynmap.debug.Debug; import org.dynmap.hdmap.HDMapManager; import org.dynmap.utils.LegacyMapChunkCache; import org.dynmap.utils.MapChunkCache; import org.dynmap.utils.NewMapChunkCache; import org.dynmap.utils.SnapshotCache; public class MapManager { public AsynchronousQueue<MapTile> tileQueue; private static final int DEFAULT_CHUNKS_PER_TICK = 200; private static final int DEFAULT_ZOOMOUT_PERIOD = 60; public List<DynmapWorld> worlds = new ArrayList<DynmapWorld>(); public Map<String, DynmapWorld> worldsLookup = new HashMap<String, DynmapWorld>(); private BukkitScheduler scheduler; private DynmapPlugin plug_in; private long timeslice_int = 0; /* In milliseconds */ private int max_chunk_loads_per_tick = DEFAULT_CHUNKS_PER_TICK; private int zoomout_period = DEFAULT_ZOOMOUT_PERIOD; /* Zoom-out tile processing period, in seconds */ /* Which fullrenders are active */ private HashMap<String, FullWorldRenderState> active_renders = new HashMap<String, FullWorldRenderState>(); /* Chunk load handling */ private Object loadlock = new Object(); private int chunks_in_cur_tick = 0; private long cur_tick; /* Tile hash manager */ public TileHashManager hashman; /* lock for our data structures */ public static final Object lock = new Object(); public static MapManager mapman; /* Our singleton */ public HDMapManager hdmapman; public SnapshotCache sscache; /* Thread pool for processing renders */ private DynmapScheduledThreadPoolExecutor render_pool; private static final int POOL_SIZE = 3; private HashMap<String, MapStats> mapstats = new HashMap<String, MapStats>(); private static class MapStats { int loggedcnt; int renderedcnt; int updatedcnt; int transparentcnt; } public DynmapWorld getWorld(String name) { DynmapWorld world = worldsLookup.get(name); return world; } public Collection<DynmapWorld> getWorlds() { return worlds; } private static class OurThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); t.setPriority(Thread.MIN_PRIORITY); t.setName("Dynmap Render Thread"); return t; } } private class DynmapScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor { DynmapScheduledThreadPoolExecutor() { super(POOL_SIZE); this.setThreadFactory(new OurThreadFactory()); /* Set shutdown policy to stop everything */ setContinueExistingPeriodicTasksAfterShutdownPolicy(false); setExecuteExistingDelayedTasksAfterShutdownPolicy(false); } protected void afterExecute(Runnable r, Throwable x) { if(r instanceof FullWorldRenderState) { ((FullWorldRenderState)r).cleanup(); } if(x != null) { Log.severe("Exception during render job: " + r); x.printStackTrace(); } } @Override public void execute(final Runnable r) { try { super.execute(new Runnable() { public void run() { try { r.run(); } catch (Exception x) { Log.severe("Exception during render job: " + r); x.printStackTrace(); } } }); } catch (RejectedExecutionException rxe) { /* Pool shutdown - nominal for reload or unload */ } } @Override public ScheduledFuture<?> schedule(final Runnable command, long delay, TimeUnit unit) { try { return super.schedule(new Runnable() { public void run() { try { command.run(); } catch (Exception x) { Log.severe("Exception during render job: " + command); x.printStackTrace(); } } }, delay, unit); } catch (RejectedExecutionException rxe) { return null; /* Pool shut down when we reload or unload */ } } } /* This always runs on render pool threads - no bukkit calls from here */ private class FullWorldRenderState implements Runnable { DynmapWorld world; /* Which world are we rendering */ Location loc; int map_index = -1; /* Which map are we on */ MapType map; HashSet<MapTile> found = null; HashSet<MapTile> rendered = null; LinkedList<MapTile> renderQueue = null; MapTile tile0 = null; MapTile tile = null; int rendercnt = 0; CommandSender sender; long timeaccum; HashSet<MapType> renderedmaps = new HashSet<MapType>(); String activemaps; List<String> activemaplist; /* Min and max limits for chunk coords (for radius limit) */ int cxmin, cxmax, czmin, czmax; String rendertype; boolean cancelled; /* Full world, all maps render */ FullWorldRenderState(DynmapWorld dworld, Location l, CommandSender sender) { this(dworld, l, sender, -1); rendertype = "Full render"; } /* Full world, all maps render, with optional render radius */ FullWorldRenderState(DynmapWorld dworld, Location l, CommandSender sender, int radius) { world = dworld; loc = l; found = new HashSet<MapTile>(); rendered = new HashSet<MapTile>(); renderQueue = new LinkedList<MapTile>(); this.sender = sender; if(radius < 0) { cxmin = czmin = Integer.MIN_VALUE; cxmax = czmax = Integer.MAX_VALUE; rendertype = "Full render"; } else { cxmin = (l.getBlockX() - radius)>>4; czmin = (l.getBlockZ() - radius)>>4; cxmax = (l.getBlockX() + radius+15)>>4; czmax = (l.getBlockZ() + radius+15)>>4; rendertype = "Radius render"; } } /* Single tile render - used for incremental renders */ FullWorldRenderState(MapTile t) { world = getWorld(t.getWorld().getName()); tile0 = t; cxmin = czmin = Integer.MIN_VALUE; cxmax = czmax = Integer.MAX_VALUE; } public String toString() { return "world=" + world.world.getName() + ", map=" + map + " tile=" + tile; } public void cleanup() { if(tile0 == null) { synchronized(lock) { active_renders.remove(world.world.getName()); } } } public void run() { long tstart = System.currentTimeMillis(); if(cancelled) { cleanup(); return; } if(tile0 == null) { /* Not single tile render */ /* If render queue is empty, start next map */ if(renderQueue.isEmpty()) { if(map_index >= 0) { /* Finished a map? */ double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } found.clear(); rendered.clear(); rendercnt = 0; timeaccum = 0; /* Advance to next unrendered map */ while(map_index < world.maps.size()) { map_index++; /* Move to next one */ if((map_index < world.maps.size()) && (renderedmaps.contains(world.maps.get(map_index)) == false)) break; } if(map_index >= world.maps.size()) { /* Last one done? */ sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished."); cleanup(); return; } map = world.maps.get(map_index); activemaplist = map.getMapNamesSharingRender(world); /* Build active map list */ activemaps = ""; for(String n : activemaplist) { if(activemaps.length() > 0) activemaps += ","; activemaps += n; } /* Mark all the concurrently rendering maps rendered */ renderedmaps.addAll(map.getMapsSharingRender(world)); /* Now, prime the render queue */ for (MapTile mt : map.getTiles(loc)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } if(world.seedloc != null) { for(Location seed : world.seedloc) { for (MapTile mt : map.getTiles(seed)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } } } } tile = renderQueue.pollFirst(); } else { /* Else, single tile render */ tile = tile0; } World w = world.world; /* Get list of chunks required for tile */ List<DynmapChunk> requiredChunks = tile.getRequiredChunks(); /* If we are doing radius limit render, see if any are inside limits */ if(cxmin != Integer.MIN_VALUE) { boolean good = false; for(DynmapChunk c : requiredChunks) { if((c.x >= cxmin) && (c.x <= cxmax) && (c.z >= czmin) && (c.z <= czmax)) { good = true; break; } } if(!good) requiredChunks = Collections.emptyList(); } /* Fetch chunk cache from server thread */ MapChunkCache cache = createMapChunkCache(world, requiredChunks, tile.isBlockTypeDataNeeded(), tile.isHightestBlockYDataNeeded(), tile.isBiomeDataNeeded(), tile.isRawBiomeDataNeeded()); if(cache == null) { cleanup(); return; /* Cancelled/aborted */ } if(tile0 != null) { /* Single tile? */ if(cache.isEmpty() == false) tile.render(cache); } else { - if ((cache.isEmpty() == false) && tile.render(cache)) { + /* Switch to not checking if rendered tile is blank - breaks us on skylands, where tiles can be nominally blank - just work off chunk cache empty */ + if (cache.isEmpty() == false) { + tile.render(cache); found.remove(tile); rendered.add(tile); for (MapTile adjTile : map.getAdjecentTiles(tile)) { if (!found.contains(adjTile) && !rendered.contains(adjTile)) { found.add(adjTile); renderQueue.add(adjTile); } } } found.remove(tile); if(!cache.isEmpty()) { rendercnt++; timeaccum += System.currentTimeMillis() - tstart; if((rendercnt % 100) == 0) { double msecpertile = (double)timeaccum / (double)rendercnt / (double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } } } /* And unload what we loaded */ cache.unloadChunks(); if(tile0 == null) { /* fullrender */ long tend = System.currentTimeMillis(); if(timeslice_int > (tend-tstart)) { /* We were fast enough */ scheduleDelayedJob(this, timeslice_int - (tend-tstart)); } else { /* Schedule to run ASAP */ scheduleDelayedJob(this, 0); } } else { cleanup(); } } public void cancelRender() { cancelled = true; } } private class CheckWorldTimes implements Runnable { public void run() { Future<Integer> f = scheduler.callSyncMethod(plug_in, new Callable<Integer>() { public Integer call() throws Exception { for(DynmapWorld w : worlds) { int new_servertime = (int)(w.world.getTime() % 24000); /* Check if we went from night to day */ boolean wasday = w.servertime >= 0 && w.servertime < 13700; boolean isday = new_servertime >= 0 && new_servertime < 13700; w.servertime = new_servertime; if(wasday != isday) { pushUpdate(w.world, new Client.DayNight(isday)); } } return 0; } }); try { f.get(); } catch (Exception ix) { Log.severe(ix); } scheduleDelayedJob(this, 5000); } } private class DoZoomOutProcessing implements Runnable { public void run() { Debug.debug("DoZoomOutProcessing started"); ArrayList<DynmapWorld> wl = new ArrayList<DynmapWorld>(worlds); for(DynmapWorld w : wl) { w.freshenZoomOutFiles(); } scheduleDelayedJob(this, zoomout_period*1000); Debug.debug("DoZoomOutProcessing finished"); } } public MapManager(DynmapPlugin plugin, ConfigurationNode configuration) { plug_in = plugin; mapman = this; /* Clear color scheme */ ColorScheme.reset(); /* Initialize HD map manager */ hdmapman = new HDMapManager(); hdmapman.loadHDShaders(plugin); hdmapman.loadHDPerspectives(plugin); hdmapman.loadHDLightings(plugin); sscache = new SnapshotCache(configuration.getInteger("snapshotcachesize", 500)); this.tileQueue = new AsynchronousQueue<MapTile>(new Handler<MapTile>() { @Override public void handle(MapTile t) { scheduleDelayedJob(new FullWorldRenderState(t), 0); } }, (int) (configuration.getDouble("renderinterval", 0.5) * 1000)); /* On dedicated thread, so default to no delays */ timeslice_int = (long)(configuration.getDouble("timesliceinterval", 0.0) * 1000); max_chunk_loads_per_tick = configuration.getInteger("maxchunkspertick", DEFAULT_CHUNKS_PER_TICK); if(max_chunk_loads_per_tick < 5) max_chunk_loads_per_tick = 5; /* Get zoomout processing periond in seconds */ zoomout_period = configuration.getInteger("zoomoutperiod", DEFAULT_ZOOMOUT_PERIOD); if(zoomout_period < 5) zoomout_period = 5; scheduler = plugin.getServer().getScheduler(); hashman = new TileHashManager(DynmapPlugin.tilesDirectory, configuration.getBoolean("enabletilehash", true)); tileQueue.start(); for (World world : plug_in.getServer().getWorlds()) { activateWorld(world); } } void renderFullWorld(Location l, CommandSender sender) { DynmapWorld world = getWorld(l.getWorld().getName()); if (world == null) { sender.sendMessage("Could not render: world '" + l.getWorld().getName() + "' not defined in configuration."); return; } String wname = l.getWorld().getName(); FullWorldRenderState rndr; synchronized(lock) { rndr = active_renders.get(wname); if(rndr != null) { sender.sendMessage(rndr.rendertype + " of world '" + wname + "' already active."); return; } rndr = new FullWorldRenderState(world,l,sender); /* Make new activation record */ active_renders.put(wname, rndr); /* Add to active table */ } /* Schedule first tile to be worked */ scheduleDelayedJob(rndr, 0); sender.sendMessage("Full render starting on world '" + wname + "'..."); } void renderWorldRadius(Location l, CommandSender sender, int radius) { DynmapWorld world = getWorld(l.getWorld().getName()); if (world == null) { sender.sendMessage("Could not render: world '" + l.getWorld().getName() + "' not defined in configuration."); return; } String wname = l.getWorld().getName(); FullWorldRenderState rndr; synchronized(lock) { rndr = active_renders.get(wname); if(rndr != null) { sender.sendMessage(rndr.rendertype + " of world '" + wname + "' already active."); return; } rndr = new FullWorldRenderState(world,l,sender, radius); /* Make new activation record */ active_renders.put(wname, rndr); /* Add to active table */ } /* Schedule first tile to be worked */ scheduleDelayedJob(rndr, 0); sender.sendMessage("Render of " + radius + " block radius starting on world '" + wname + "'..."); } void cancelRender(World w, CommandSender sender) { synchronized(lock) { if(w != null) { FullWorldRenderState rndr; rndr = active_renders.get(w.getName()); if(rndr != null) { rndr.cancelRender(); /* Cancel render */ if(sender != null) { sender.sendMessage("Cancelled render for '" + w.getName() + "'"); } } } else { /* Else, cancel all */ for(String wid : active_renders.keySet()) { FullWorldRenderState rnd = active_renders.get(wid); rnd.cancelRender(); if(sender != null) { sender.sendMessage("Cancelled render for '" + wid + "'"); } } } } } public void activateWorld(World w) { ConfigurationNode worldConfiguration = plug_in.getWorldConfiguration(w); if (!worldConfiguration.getBoolean("enabled", false)) { Log.info("World '" + w.getName() + "' disabled"); return; } String worldName = w.getName(); DynmapWorld dynmapWorld = new DynmapWorld(); dynmapWorld.world = w; dynmapWorld.configuration = worldConfiguration; Log.verboseinfo("Loading maps of world '" + worldName + "'..."); for(MapType map : worldConfiguration.<MapType>createInstances("maps", new Class<?>[0], new Object[0])) { if(map.getName() != null) dynmapWorld.maps.add(map); } Log.info("Loaded " + dynmapWorld.maps.size() + " maps of world '" + worldName + "'."); List<ConfigurationNode> loclist = worldConfiguration.getNodes("fullrenderlocations"); dynmapWorld.seedloc = new ArrayList<Location>(); dynmapWorld.servertime = (int)(w.getTime() % 24000); dynmapWorld.sendposition = worldConfiguration.getBoolean("sendposition", true); dynmapWorld.sendhealth = worldConfiguration.getBoolean("sendhealth", true); dynmapWorld.bigworld = worldConfiguration.getBoolean("bigworld", false); dynmapWorld.setExtraZoomOutLevels(worldConfiguration.getInteger("extrazoomout", 0)); dynmapWorld.worldtilepath = new File(DynmapPlugin.tilesDirectory, w.getName()); if(loclist != null) { for(ConfigurationNode loc : loclist) { Location lx = new Location(w, loc.getDouble("x", 0), loc.getDouble("y", 64), loc.getDouble("z", 0)); dynmapWorld.seedloc.add(lx); } } /* Load visibility limits, if any are defined */ List<ConfigurationNode> vislimits = worldConfiguration.getNodes("visibilitylimits"); if(vislimits != null) { dynmapWorld.visibility_limits = new ArrayList<MapChunkCache.VisibilityLimit>(); for(ConfigurationNode vis : vislimits) { MapChunkCache.VisibilityLimit lim = new MapChunkCache.VisibilityLimit(); lim.x0 = vis.getInteger("x0", 0); lim.x1 = vis.getInteger("x1", 0); lim.z0 = vis.getInteger("z0", 0); lim.z1 = vis.getInteger("z1", 0); dynmapWorld.visibility_limits.add(lim); /* Also, add a seed location for the middle of each visible area */ dynmapWorld.seedloc.add(new Location(w, (lim.x0+lim.x1)/2, 64, (lim.z0+lim.z1)/2)); } } String autogen = worldConfiguration.getString("autogenerate-to-visibilitylimits", "none"); if(autogen.equals("permanent")) { dynmapWorld.do_autogenerate = AutoGenerateOption.PERMANENT; } else if(autogen.equals("map-only")) { dynmapWorld.do_autogenerate = AutoGenerateOption.FORMAPONLY; } else { dynmapWorld.do_autogenerate = AutoGenerateOption.NONE; } if((dynmapWorld.do_autogenerate != AutoGenerateOption.NONE) && (dynmapWorld.visibility_limits == null)) { Log.info("Warning: Automatic world generation to visible limits option requires that visibitylimits be set - option disabled"); dynmapWorld.do_autogenerate = AutoGenerateOption.NONE; } String hiddenchunkstyle = worldConfiguration.getString("hidestyle", "stone"); if(hiddenchunkstyle.equals("air")) dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_AIR; else if(hiddenchunkstyle.equals("ocean")) dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_OCEAN; else dynmapWorld.hiddenchunkstyle = MapChunkCache.HiddenChunkStyle.FILL_STONE_PLAIN; // TODO: Make this less... weird... // Insert the world on the same spot as in the configuration. HashMap<String, Integer> indexLookup = new HashMap<String, Integer>(); List<ConfigurationNode> nodes = plug_in.configuration.getNodes("worlds"); for (int i = 0; i < nodes.size(); i++) { ConfigurationNode node = nodes.get(i); indexLookup.put(node.getString("name"), i); } Integer worldIndex = indexLookup.get(worldName); if(worldIndex == null) { worlds.add(dynmapWorld); /* Put at end if no world section */ } else { int insertIndex; for(insertIndex = 0; insertIndex < worlds.size(); insertIndex++) { Integer nextWorldIndex = indexLookup.get(worlds.get(insertIndex).world.getName()); if (nextWorldIndex == null || worldIndex < nextWorldIndex.intValue()) { break; } } worlds.add(insertIndex, dynmapWorld); } worldsLookup.put(w.getName(), dynmapWorld); plug_in.events.trigger("worldactivated", dynmapWorld); } public int touch(Location l) { DynmapWorld world = getWorld(l.getWorld().getName()); if (world == null) return 0; int invalidates = 0; for (int i = 0; i < world.maps.size(); i++) { MapTile[] tiles = world.maps.get(i).getTiles(l); for (int j = 0; j < tiles.length; j++) { invalidateTile(tiles[j]); invalidates++; } } return invalidates; } public void invalidateTile(MapTile tile) { Debug.debug("Invalidating tile " + tile.getFilename()); tileQueue.push(tile); } public static void scheduleDelayedJob(Runnable job, long delay_in_msec) { if((mapman != null) && (mapman.render_pool != null)) { if(delay_in_msec > 0) mapman.render_pool.schedule(job, delay_in_msec, TimeUnit.MILLISECONDS); else mapman.render_pool.execute(job); } } public void startRendering() { tileQueue.start(); render_pool = new DynmapScheduledThreadPoolExecutor(); scheduleDelayedJob(new DoZoomOutProcessing(), 60000); scheduleDelayedJob(new CheckWorldTimes(), 5000); } public void stopRendering() { /* Tell all worlds to cancel any zoom out processing */ for(DynmapWorld w: worlds) w.cancelZoomOutFreshen(); render_pool.shutdown(); try { render_pool.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ix) { } tileQueue.stop(); mapman = null; hdmapman = null; } private HashMap<World, File> worldTileDirectories = new HashMap<World, File>(); public File getTileFile(MapTile tile) { World world = tile.getWorld(); File worldTileDirectory = worldTileDirectories.get(world); if (worldTileDirectory == null) { worldTileDirectory = new File(DynmapPlugin.tilesDirectory, tile.getWorld().getName()); worldTileDirectories.put(world, worldTileDirectory); } if (!worldTileDirectory.isDirectory() && !worldTileDirectory.mkdirs()) { Log.warning("Could not create directory for tiles ('" + worldTileDirectory + "')."); } return new File(worldTileDirectory, tile.getFilename()); } public void pushUpdate(Object update) { for(DynmapWorld world : getWorlds()) { world.updates.pushUpdate(update); } } public void pushUpdate(World world, Object update) { pushUpdate(world.getName(), update); } public void pushUpdate(String worldName, Object update) { DynmapWorld world = getWorld(worldName); world.updates.pushUpdate(update); } public Object[] getWorldUpdates(String worldName, long since) { DynmapWorld world = getWorld(worldName); if (world == null) return new Object[0]; return world.updates.getUpdatedObjects(since); } private static boolean use_legacy = false; /** * Render processor helper - used by code running on render threads to request chunk snapshot cache from server/sync thread */ public MapChunkCache createMapChunkCache(DynmapWorld w, List<DynmapChunk> chunks, boolean blockdata, boolean highesty, boolean biome, boolean rawbiome) { MapChunkCache c = null; try { if(!use_legacy) c = new NewMapChunkCache(); } catch (NoClassDefFoundError ncdfe) { use_legacy = true; } if(c == null) c = new LegacyMapChunkCache(); if(w.visibility_limits != null) { for(MapChunkCache.VisibilityLimit limit: w.visibility_limits) { c.setVisibleRange(limit); } c.setHiddenFillStyle(w.hiddenchunkstyle); c.setAutoGenerateVisbileRanges(w.do_autogenerate); } c.setChunks(w.world, chunks); if(c.setChunkDataTypes(blockdata, biome, highesty, rawbiome) == false) Log.severe("CraftBukkit build does not support biome APIs"); if(chunks.size() == 0) { /* No chunks to get? */ return c; } synchronized(loadlock) { final MapChunkCache cc = c; long now = System.currentTimeMillis(); if(cur_tick != (now/50)) { /* New tick? */ chunks_in_cur_tick = max_chunk_loads_per_tick; cur_tick = now/50; } while(!cc.isDoneLoading()) { final int cntin = chunks_in_cur_tick; Future<Integer> f = scheduler.callSyncMethod(plug_in, new Callable<Integer>() { public Integer call() throws Exception { return Integer.valueOf(cntin - cc.loadChunks(cntin)); } }); try { chunks_in_cur_tick = f.get(); } catch (Exception ix) { Log.severe(ix); return null; } if(chunks_in_cur_tick == 0) { chunks_in_cur_tick = max_chunk_loads_per_tick; try { Thread.sleep(50); } catch (InterruptedException ix) {} } } } return c; } /** * Update map tile statistics */ public void updateStatistics(MapTile tile, String subtype, boolean rendered, boolean updated, boolean transparent) { synchronized(lock) { String k = tile.getKey(); if(subtype != null) k += "." + subtype; MapStats ms = mapstats.get(k); if(ms == null) { ms = new MapStats(); mapstats.put(k, ms); } ms.loggedcnt++; if(rendered) ms.renderedcnt++; if(updated) ms.updatedcnt++; if(transparent) ms.transparentcnt++; } } /** * Print statistics command */ public void printStats(CommandSender sender, String prefix) { sender.sendMessage("Tile Render Statistics:"); MapStats tot = new MapStats(); synchronized(lock) { for(String k: new TreeSet<String>(mapstats.keySet())) { if((prefix != null) && !k.startsWith(prefix)) continue; MapStats ms = mapstats.get(k); sender.sendMessage(" " + k + ": processed=" + ms.loggedcnt + ", rendered=" + ms.renderedcnt + ", updated=" + ms.updatedcnt + ", transparent=" + ms.transparentcnt); tot.loggedcnt += ms.loggedcnt; tot.renderedcnt += ms.renderedcnt; tot.updatedcnt += ms.updatedcnt; tot.transparentcnt += ms.transparentcnt; } } sender.sendMessage(" TOTALS: processed=" + tot.loggedcnt + ", rendered=" + tot.renderedcnt + ", updated=" + tot.updatedcnt + ", transparent=" + tot.transparentcnt); sender.sendMessage(" Cache hit rate: " + sscache.getHitRate() + "%"); } /** * Reset statistics */ public void resetStats(CommandSender sender, String prefix) { synchronized(lock) { for(String k : mapstats.keySet()) { if((prefix != null) && !k.startsWith(prefix)) continue; MapStats ms = mapstats.get(k); ms.loggedcnt = 0; ms.renderedcnt = 0; ms.updatedcnt = 0; ms.transparentcnt = 0; } } sscache.resetStats(); sender.sendMessage("Tile Render Statistics reset"); } }
true
true
public void run() { long tstart = System.currentTimeMillis(); if(cancelled) { cleanup(); return; } if(tile0 == null) { /* Not single tile render */ /* If render queue is empty, start next map */ if(renderQueue.isEmpty()) { if(map_index >= 0) { /* Finished a map? */ double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } found.clear(); rendered.clear(); rendercnt = 0; timeaccum = 0; /* Advance to next unrendered map */ while(map_index < world.maps.size()) { map_index++; /* Move to next one */ if((map_index < world.maps.size()) && (renderedmaps.contains(world.maps.get(map_index)) == false)) break; } if(map_index >= world.maps.size()) { /* Last one done? */ sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished."); cleanup(); return; } map = world.maps.get(map_index); activemaplist = map.getMapNamesSharingRender(world); /* Build active map list */ activemaps = ""; for(String n : activemaplist) { if(activemaps.length() > 0) activemaps += ","; activemaps += n; } /* Mark all the concurrently rendering maps rendered */ renderedmaps.addAll(map.getMapsSharingRender(world)); /* Now, prime the render queue */ for (MapTile mt : map.getTiles(loc)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } if(world.seedloc != null) { for(Location seed : world.seedloc) { for (MapTile mt : map.getTiles(seed)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } } } } tile = renderQueue.pollFirst(); } else { /* Else, single tile render */ tile = tile0; } World w = world.world; /* Get list of chunks required for tile */ List<DynmapChunk> requiredChunks = tile.getRequiredChunks(); /* If we are doing radius limit render, see if any are inside limits */ if(cxmin != Integer.MIN_VALUE) { boolean good = false; for(DynmapChunk c : requiredChunks) { if((c.x >= cxmin) && (c.x <= cxmax) && (c.z >= czmin) && (c.z <= czmax)) { good = true; break; } } if(!good) requiredChunks = Collections.emptyList(); } /* Fetch chunk cache from server thread */ MapChunkCache cache = createMapChunkCache(world, requiredChunks, tile.isBlockTypeDataNeeded(), tile.isHightestBlockYDataNeeded(), tile.isBiomeDataNeeded(), tile.isRawBiomeDataNeeded()); if(cache == null) { cleanup(); return; /* Cancelled/aborted */ } if(tile0 != null) { /* Single tile? */ if(cache.isEmpty() == false) tile.render(cache); } else { if ((cache.isEmpty() == false) && tile.render(cache)) { found.remove(tile); rendered.add(tile); for (MapTile adjTile : map.getAdjecentTiles(tile)) { if (!found.contains(adjTile) && !rendered.contains(adjTile)) { found.add(adjTile); renderQueue.add(adjTile); } } } found.remove(tile); if(!cache.isEmpty()) { rendercnt++; timeaccum += System.currentTimeMillis() - tstart; if((rendercnt % 100) == 0) { double msecpertile = (double)timeaccum / (double)rendercnt / (double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } } } /* And unload what we loaded */ cache.unloadChunks(); if(tile0 == null) { /* fullrender */ long tend = System.currentTimeMillis(); if(timeslice_int > (tend-tstart)) { /* We were fast enough */ scheduleDelayedJob(this, timeslice_int - (tend-tstart)); } else { /* Schedule to run ASAP */ scheduleDelayedJob(this, 0); } } else { cleanup(); } }
public void run() { long tstart = System.currentTimeMillis(); if(cancelled) { cleanup(); return; } if(tile0 == null) { /* Not single tile render */ /* If render queue is empty, start next map */ if(renderQueue.isEmpty()) { if(map_index >= 0) { /* Finished a map? */ double msecpertile = (double)timeaccum / (double)((rendercnt>0)?rendercnt:1)/(double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + world.world.getName() + "' completed - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } found.clear(); rendered.clear(); rendercnt = 0; timeaccum = 0; /* Advance to next unrendered map */ while(map_index < world.maps.size()) { map_index++; /* Move to next one */ if((map_index < world.maps.size()) && (renderedmaps.contains(world.maps.get(map_index)) == false)) break; } if(map_index >= world.maps.size()) { /* Last one done? */ sender.sendMessage(rendertype + " of '" + world.world.getName() + "' finished."); cleanup(); return; } map = world.maps.get(map_index); activemaplist = map.getMapNamesSharingRender(world); /* Build active map list */ activemaps = ""; for(String n : activemaplist) { if(activemaps.length() > 0) activemaps += ","; activemaps += n; } /* Mark all the concurrently rendering maps rendered */ renderedmaps.addAll(map.getMapsSharingRender(world)); /* Now, prime the render queue */ for (MapTile mt : map.getTiles(loc)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } if(world.seedloc != null) { for(Location seed : world.seedloc) { for (MapTile mt : map.getTiles(seed)) { if (!found.contains(mt)) { found.add(mt); renderQueue.add(mt); } } } } } tile = renderQueue.pollFirst(); } else { /* Else, single tile render */ tile = tile0; } World w = world.world; /* Get list of chunks required for tile */ List<DynmapChunk> requiredChunks = tile.getRequiredChunks(); /* If we are doing radius limit render, see if any are inside limits */ if(cxmin != Integer.MIN_VALUE) { boolean good = false; for(DynmapChunk c : requiredChunks) { if((c.x >= cxmin) && (c.x <= cxmax) && (c.z >= czmin) && (c.z <= czmax)) { good = true; break; } } if(!good) requiredChunks = Collections.emptyList(); } /* Fetch chunk cache from server thread */ MapChunkCache cache = createMapChunkCache(world, requiredChunks, tile.isBlockTypeDataNeeded(), tile.isHightestBlockYDataNeeded(), tile.isBiomeDataNeeded(), tile.isRawBiomeDataNeeded()); if(cache == null) { cleanup(); return; /* Cancelled/aborted */ } if(tile0 != null) { /* Single tile? */ if(cache.isEmpty() == false) tile.render(cache); } else { /* Switch to not checking if rendered tile is blank - breaks us on skylands, where tiles can be nominally blank - just work off chunk cache empty */ if (cache.isEmpty() == false) { tile.render(cache); found.remove(tile); rendered.add(tile); for (MapTile adjTile : map.getAdjecentTiles(tile)) { if (!found.contains(adjTile) && !rendered.contains(adjTile)) { found.add(adjTile); renderQueue.add(adjTile); } } } found.remove(tile); if(!cache.isEmpty()) { rendercnt++; timeaccum += System.currentTimeMillis() - tstart; if((rendercnt % 100) == 0) { double msecpertile = (double)timeaccum / (double)rendercnt / (double)activemaplist.size(); if(activemaplist.size() > 1) sender.sendMessage(rendertype + " of maps [" + activemaps + "] of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered each (" + String.format("%.2f", msecpertile) + " msec/map-tile)."); else sender.sendMessage(rendertype + " of map '" + activemaps + "' of '" + w.getName() + "' in progress - " + rendercnt + " tiles rendered (" + String.format("%.2f", msecpertile) + " msec/tile)."); } } } /* And unload what we loaded */ cache.unloadChunks(); if(tile0 == null) { /* fullrender */ long tend = System.currentTimeMillis(); if(timeslice_int > (tend-tstart)) { /* We were fast enough */ scheduleDelayedJob(this, timeslice_int - (tend-tstart)); } else { /* Schedule to run ASAP */ scheduleDelayedJob(this, 0); } } else { cleanup(); } }
diff --git a/HDX-System/src/main/java/org/ocha/hdx/persistence/dao/view/IndicatorMaxDateDAOImpl.java b/HDX-System/src/main/java/org/ocha/hdx/persistence/dao/view/IndicatorMaxDateDAOImpl.java index 852c517..fa0700d 100644 --- a/HDX-System/src/main/java/org/ocha/hdx/persistence/dao/view/IndicatorMaxDateDAOImpl.java +++ b/HDX-System/src/main/java/org/ocha/hdx/persistence/dao/view/IndicatorMaxDateDAOImpl.java @@ -1,55 +1,55 @@ package org.ocha.hdx.persistence.dao.view; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.ocha.hdx.persistence.entity.view.IndicatorMaxDate; public class IndicatorMaxDateDAOImpl implements IndicatorMaxDateDAO { @PersistenceContext private EntityManager em; @Override public List<IndicatorMaxDate> getValues(final List<String> entityCodes, final List<String> indicatorTypeCodes, final List<String> sourceCodes) { final StringBuilder builder = new StringBuilder("SELECT imd FROM IndicatorMaxDate imd WHERE "); boolean andNeeded = false; if (entityCodes != null && !entityCodes.isEmpty()) { - builder.append(" imd.entityCode IN (:entityCodes) "); + builder.append(" imd.locationCode IN (:entityCodes) "); andNeeded = true; } if (indicatorTypeCodes != null && !indicatorTypeCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.indicatorTypeCode IN (:indicatorTypeCodes) "); andNeeded = true; } if (sourceCodes != null && !sourceCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.sourceCode IN (:sourceCodes) "); } final TypedQuery<IndicatorMaxDate> query = em.createQuery(builder.toString(), IndicatorMaxDate.class); if (entityCodes != null) { query.setParameter("entityCodes", entityCodes); } if (indicatorTypeCodes != null) { query.setParameter("indicatorTypeCodes", indicatorTypeCodes); } if (sourceCodes != null) { query.setParameter("sourceCodes", sourceCodes); } return query.getResultList(); } }
true
true
public List<IndicatorMaxDate> getValues(final List<String> entityCodes, final List<String> indicatorTypeCodes, final List<String> sourceCodes) { final StringBuilder builder = new StringBuilder("SELECT imd FROM IndicatorMaxDate imd WHERE "); boolean andNeeded = false; if (entityCodes != null && !entityCodes.isEmpty()) { builder.append(" imd.entityCode IN (:entityCodes) "); andNeeded = true; } if (indicatorTypeCodes != null && !indicatorTypeCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.indicatorTypeCode IN (:indicatorTypeCodes) "); andNeeded = true; } if (sourceCodes != null && !sourceCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.sourceCode IN (:sourceCodes) "); } final TypedQuery<IndicatorMaxDate> query = em.createQuery(builder.toString(), IndicatorMaxDate.class); if (entityCodes != null) { query.setParameter("entityCodes", entityCodes); } if (indicatorTypeCodes != null) { query.setParameter("indicatorTypeCodes", indicatorTypeCodes); } if (sourceCodes != null) { query.setParameter("sourceCodes", sourceCodes); } return query.getResultList(); }
public List<IndicatorMaxDate> getValues(final List<String> entityCodes, final List<String> indicatorTypeCodes, final List<String> sourceCodes) { final StringBuilder builder = new StringBuilder("SELECT imd FROM IndicatorMaxDate imd WHERE "); boolean andNeeded = false; if (entityCodes != null && !entityCodes.isEmpty()) { builder.append(" imd.locationCode IN (:entityCodes) "); andNeeded = true; } if (indicatorTypeCodes != null && !indicatorTypeCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.indicatorTypeCode IN (:indicatorTypeCodes) "); andNeeded = true; } if (sourceCodes != null && !sourceCodes.isEmpty()) { if (andNeeded) { builder.append(" AND "); } builder.append(" imd.sourceCode IN (:sourceCodes) "); } final TypedQuery<IndicatorMaxDate> query = em.createQuery(builder.toString(), IndicatorMaxDate.class); if (entityCodes != null) { query.setParameter("entityCodes", entityCodes); } if (indicatorTypeCodes != null) { query.setParameter("indicatorTypeCodes", indicatorTypeCodes); } if (sourceCodes != null) { query.setParameter("sourceCodes", sourceCodes); } return query.getResultList(); }
diff --git a/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java b/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java index 1640e45ae..a1ec8accf 100644 --- a/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java +++ b/src/java/nl/b3p/viewer/admin/stripes/ApplicationStartMapActionBean.java @@ -1,480 +1,480 @@ /* * Copyright (C) 2012 B3Partners B.V. * * 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 nl.b3p.viewer.admin.stripes; import java.io.StringReader; import java.util.*; import javax.persistence.EntityManager; import javax.servlet.http.HttpServletResponse; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.*; import nl.b3p.viewer.config.app.*; import nl.b3p.web.stripes.ErrorMessageResolution; import org.json.*; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/applicationstartmap/{$event}") @StrictBinding public class ApplicationStartMapActionBean extends ApplicationActionBean { private static final String JSP = "/WEB-INF/jsp/application/applicationStartMap.jsp"; @Validate private String selectedContent; private JSONArray jsonContent; @Validate private String contentToBeSelected; @Validate private String checkedLayersString; private JSONArray jsonCheckedLayers; //private List<Long> checkedLayers = new ArrayList(); private JSONArray allCheckedLayers = new JSONArray(); @Validate private String nodeId; @Validate private String levelId; private Level rootlevel; @DefaultHandler @HandlesEvent("default") @DontValidate public Resolution view() throws JSONException { if (application == null) { getContext().getMessages().add(new SimpleError("Er moet eerst een bestaande applicatie geactiveerd of een nieuwe applicatie gemaakt worden.")); return new ForwardResolution("/WEB-INF/jsp/application/chooseApplication.jsp"); } else { rootlevel = application.getRoot(); getCheckedLayerList(allCheckedLayers, rootlevel); } return new ForwardResolution(JSP); } public Resolution save() throws JSONException { rootlevel = application.getRoot(); jsonContent = new JSONArray(selectedContent); jsonCheckedLayers = new JSONArray(checkedLayersString); walkAppTreeForSave(rootlevel); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Het startkaartbeeld is opgeslagen")); getCheckedLayerList(allCheckedLayers, rootlevel); return new ForwardResolution(JSP); } public Resolution canContentBeSelected() { try { jsonContent = new JSONArray(selectedContent); if(jsonContent.length() == 0) { JSONObject obj = new JSONObject(); obj.put("result", true); return new StreamingResolution("application/json", new StringReader(obj.toString())); } JSONObject o = new JSONObject(contentToBeSelected); Boolean result = true; String message = null; String id = o.getString("id"); - if(o.get("type").equals("appLayer")) { + if(o.get("type").equals("layer")) { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(id)); if(appLayer == null) { message = "Kaartlaag met id " + id + " is onbekend!"; result = false; } else { /* An appLayer can not be selected if: * - selectedContent contains the appLayer * - the appLayer is a layer of any level or its children in selectedContent */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); - if(content.getString("type").equals("appLayer")) { + if(content.getString("type").equals("layer")) { if(id.equals(content.getString("id"))) { result = false; message = "Kaartlaag is al geselecteerd"; break; } } else { Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLayerInSubtree(appLayer)) { result = false; message = "Kaartlaag is al geselecteerd als onderdeel van een niveau"; break; } } } } } } else { Level level = Stripersist.getEntityManager().find(Level.class, new Long(id)); if(level == null) { result = false; message = "Niveau met id " + id + " is onbekend!"; } else { /* A level can not be selected if: * any level in selectedContent is the level is a sublevel of the level * any level in selectedContent is a parent (recursive) of the level */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); if(content.getString("type").equals("level")) { if(id.equals(content.getString("id"))) { result = false; message = "Niveau is al geselecteerd"; break; } Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLevelInSubtree(level)) { result = false; - message = "Niveau kan niet worden geselecteerd omdat een subniveau al geselecteerd is"; + message = "Niveau kan niet worden geselecteerd omdat een bovenliggend niveau al geselecteerd is"; break; } if(l.isInSubtreeOf(level)) { result = false; - message = "Niveau kan niet worden geselecteerd omdat een bovenliggend niveau al geselecteerd is"; + message = "Niveau kan niet worden geselecteerd omdat een subniveau al geselecteerd is"; break; } } } else { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(content.getString("id"))); if(level.containsLayerInSubtree(appLayer)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een kaartlaag uit dit (of onderliggend) niveau al is geselecteerd"; break; } } } } } JSONObject obj = new JSONObject(); obj.put("result", result); obj.put("message", message); return new StreamingResolution("application/json", new StringReader(obj.toString())); } catch(Exception e) { return new ErrorMessageResolution("Exception " + e.getClass() + ": " + e.getMessage()); } } private void walkAppTreeForSave(Level l) throws JSONException{ l.setSelectedIndex(getSelectedContentIndex(l)); for(ApplicationLayer al: l.getLayers()) { al.setSelectedIndex(getSelectedContentIndex(al)); al.setChecked(getCheckedForLayerId(al.getId())); } for(Level child: l.getChildren()) { walkAppTreeForSave(child); } } private boolean getCheckedForLayerId(Long levelid) throws JSONException { for(int i = 0; i < jsonCheckedLayers.length(); i++){ if(levelid.equals(Long.parseLong(jsonCheckedLayers.getString(i)))) { return true; } } return false; } private Integer getSelectedContentIndex(Level l) throws JSONException{ Integer index = null; for(int i = 0; i < jsonContent.length(); i++){ JSONObject js = jsonContent.getJSONObject(i); String id = js.get("id").toString(); String type = js.get("type").toString(); if(id.equals(l.getId().toString()) && type.equals("level")){ index = i; } } return index; } private Integer getSelectedContentIndex(ApplicationLayer al) throws JSONException{ Integer index = null; for(int i = 0; i < jsonContent.length(); i++){ JSONObject js = jsonContent.getJSONObject(i); String id = js.get("id").toString(); String type = js.get("type").toString(); if(id.equals(al.getId().toString()) && type.equals("layer")){ index = i; } } return index; } public Resolution loadApplicationTree() throws JSONException { EntityManager em = Stripersist.getEntityManager(); final JSONArray children = new JSONArray(); if (!nodeId.equals("n")) { String type = nodeId.substring(0, 1); int id = Integer.parseInt(nodeId.substring(1)); if (type.equals("n")) { Level l = em.find(Level.class, new Long(id)); for (Level sub : l.getChildren()) { JSONObject j = new JSONObject(); j.put("id", "n" + sub.getId()); j.put("name", sub.getName()); j.put("type", "level"); j.put("isLeaf", sub.getChildren().isEmpty() && sub.getLayers().isEmpty()); if (sub.getParent() != null) { j.put("parentid", sub.getParent().getId()); } children.put(j); } for (ApplicationLayer layer : l.getLayers()) { JSONObject j = new JSONObject(); j.put("id", "s" + layer.getId()); j.put("name", layer.getLayerName()); j.put("type", "layer"); j.put("isLeaf", true); j.put("parentid", nodeId); children.put(j); } } } return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(children.toString()); } }; } public Resolution loadSelectedLayers() throws JSONException { EntityManager em = Stripersist.getEntityManager(); final JSONArray children = new JSONArray(); rootlevel = application.getRoot(); if(levelId != null && levelId.substring(1).equals(rootlevel.getId().toString())){ List selectedObjects = new ArrayList(); walkAppTreeForStartMap(selectedObjects, rootlevel); Collections.sort(selectedObjects, new Comparator() { @Override public int compare(Object lhs, Object rhs) { Integer lhsIndex, rhsIndex; if(lhs instanceof Level) { lhsIndex = ((Level)lhs).getSelectedIndex(); } else { lhsIndex = ((ApplicationLayer)lhs).getSelectedIndex(); } if(rhs instanceof Level) { rhsIndex = ((Level)rhs).getSelectedIndex(); } else { rhsIndex = ((ApplicationLayer)rhs).getSelectedIndex(); } return lhsIndex.compareTo(rhsIndex); } }); if(selectedObjects != null){ for (Iterator it = selectedObjects.iterator(); it.hasNext();) { Object map = it.next(); if(map instanceof ApplicationLayer){ ApplicationLayer layer = (ApplicationLayer) map; JSONObject j = new JSONObject(); j.put("id", "s" + layer.getId()); j.put("name", layer.getLayerName()); j.put("type", "layer"); j.put("isLeaf", true); j.put("parentid", ""); j.put("checked", layer.isChecked()); children.put(j); }else if(map instanceof Level){ Level level = (Level) map; JSONArray checked = new JSONArray(); getCheckedLayerList(checked, level); JSONObject j = new JSONObject(); j.put("id", "n" + level.getId()); j.put("name", level.getName()); j.put("type", "level"); j.put("isLeaf", level.getChildren().isEmpty() && level.getLayers().isEmpty()); j.put("parentid", ""); j.put("checkedlayers", checked); // j.put("checked", false); children.put(j); } } } }else{ String type = levelId.substring(0, 1); int id = Integer.parseInt(levelId.substring(1)); if (type.equals("n")) { Level l = em.find(Level.class, new Long(id)); for (Level sub : l.getChildren()) { JSONObject j = new JSONObject(); j.put("id", "n" + sub.getId()); j.put("name", sub.getName()); j.put("type", "level"); j.put("isLeaf", sub.getChildren().isEmpty() && sub.getLayers().isEmpty()); if (sub.getParent() != null) { j.put("parentid", sub.getParent().getId()); } // j.put("checked", false); children.put(j); } for (ApplicationLayer layer : l.getLayers()) { JSONObject j = new JSONObject(); j.put("id", "s" + layer.getId()); j.put("name", layer.getLayerName()); j.put("type", "layer"); j.put("isLeaf", true); j.put("parentid", levelId); j.put("checked", layer.isChecked()); children.put(j); } } } return new StreamingResolution("application/json") { @Override public void stream(HttpServletResponse response) throws Exception { response.getWriter().print(children.toString()); } }; } private static void walkAppTreeForStartMap(List selectedContent, Level l){ if(l.getSelectedIndex() != null) { selectedContent.add(l); } for(ApplicationLayer al: l.getLayers()) { if(al.getSelectedIndex() != null) { selectedContent.add(al); } } for(Level child: l.getChildren()) { walkAppTreeForStartMap(selectedContent, child); } } private static void getCheckedLayerList(JSONArray layers, Level l) throws JSONException{ for(ApplicationLayer al: l.getLayers()) { if(al.isChecked()) { layers.put(al.getId()); } } for(Level child: l.getChildren()) { getCheckedLayerList(layers, child); } } //<editor-fold defaultstate="collapsed" desc="getters & setters"> public String getCheckedLayersString() { return checkedLayersString; } public void setCheckedLayersString(String checkedLayersString) { this.checkedLayersString = checkedLayersString; } public String getSelectedContent() { return selectedContent; } public void setSelectedContent(String selectedContent) { this.selectedContent = selectedContent; } public Level getRootlevel() { return rootlevel; } public void setRootlevel(Level rootlevel) { this.rootlevel = rootlevel; } public String getLevelId() { return levelId; } public void setLevelId(String levelId) { this.levelId = levelId; } public JSONArray getAllCheckedLayers() { return allCheckedLayers; } public void setAllCheckedLayers(JSONArray allCheckedLayers) { this.allCheckedLayers = allCheckedLayers; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getContentToBeSelected() { return contentToBeSelected; } public void setContentToBeSelected(String contentToBeSelected) { this.contentToBeSelected = contentToBeSelected; } //</editor-fold> }
false
true
public Resolution canContentBeSelected() { try { jsonContent = new JSONArray(selectedContent); if(jsonContent.length() == 0) { JSONObject obj = new JSONObject(); obj.put("result", true); return new StreamingResolution("application/json", new StringReader(obj.toString())); } JSONObject o = new JSONObject(contentToBeSelected); Boolean result = true; String message = null; String id = o.getString("id"); if(o.get("type").equals("appLayer")) { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(id)); if(appLayer == null) { message = "Kaartlaag met id " + id + " is onbekend!"; result = false; } else { /* An appLayer can not be selected if: * - selectedContent contains the appLayer * - the appLayer is a layer of any level or its children in selectedContent */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); if(content.getString("type").equals("appLayer")) { if(id.equals(content.getString("id"))) { result = false; message = "Kaartlaag is al geselecteerd"; break; } } else { Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLayerInSubtree(appLayer)) { result = false; message = "Kaartlaag is al geselecteerd als onderdeel van een niveau"; break; } } } } } } else { Level level = Stripersist.getEntityManager().find(Level.class, new Long(id)); if(level == null) { result = false; message = "Niveau met id " + id + " is onbekend!"; } else { /* A level can not be selected if: * any level in selectedContent is the level is a sublevel of the level * any level in selectedContent is a parent (recursive) of the level */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); if(content.getString("type").equals("level")) { if(id.equals(content.getString("id"))) { result = false; message = "Niveau is al geselecteerd"; break; } Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLevelInSubtree(level)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een subniveau al geselecteerd is"; break; } if(l.isInSubtreeOf(level)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een bovenliggend niveau al geselecteerd is"; break; } } } else { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(content.getString("id"))); if(level.containsLayerInSubtree(appLayer)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een kaartlaag uit dit (of onderliggend) niveau al is geselecteerd"; break; } } } } } JSONObject obj = new JSONObject(); obj.put("result", result); obj.put("message", message); return new StreamingResolution("application/json", new StringReader(obj.toString())); } catch(Exception e) { return new ErrorMessageResolution("Exception " + e.getClass() + ": " + e.getMessage()); } }
public Resolution canContentBeSelected() { try { jsonContent = new JSONArray(selectedContent); if(jsonContent.length() == 0) { JSONObject obj = new JSONObject(); obj.put("result", true); return new StreamingResolution("application/json", new StringReader(obj.toString())); } JSONObject o = new JSONObject(contentToBeSelected); Boolean result = true; String message = null; String id = o.getString("id"); if(o.get("type").equals("layer")) { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(id)); if(appLayer == null) { message = "Kaartlaag met id " + id + " is onbekend!"; result = false; } else { /* An appLayer can not be selected if: * - selectedContent contains the appLayer * - the appLayer is a layer of any level or its children in selectedContent */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); if(content.getString("type").equals("layer")) { if(id.equals(content.getString("id"))) { result = false; message = "Kaartlaag is al geselecteerd"; break; } } else { Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLayerInSubtree(appLayer)) { result = false; message = "Kaartlaag is al geselecteerd als onderdeel van een niveau"; break; } } } } } } else { Level level = Stripersist.getEntityManager().find(Level.class, new Long(id)); if(level == null) { result = false; message = "Niveau met id " + id + " is onbekend!"; } else { /* A level can not be selected if: * any level in selectedContent is the level is a sublevel of the level * any level in selectedContent is a parent (recursive) of the level */ for(int i = 0; i < jsonContent.length(); i++) { JSONObject content = jsonContent.getJSONObject(i); if(content.getString("type").equals("level")) { if(id.equals(content.getString("id"))) { result = false; message = "Niveau is al geselecteerd"; break; } Level l = Stripersist.getEntityManager().find(Level.class, new Long(content.getString("id"))); if(l != null) { if(l.containsLevelInSubtree(level)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een bovenliggend niveau al geselecteerd is"; break; } if(l.isInSubtreeOf(level)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een subniveau al geselecteerd is"; break; } } } else { ApplicationLayer appLayer = Stripersist.getEntityManager().find(ApplicationLayer.class, new Long(content.getString("id"))); if(level.containsLayerInSubtree(appLayer)) { result = false; message = "Niveau kan niet worden geselecteerd omdat een kaartlaag uit dit (of onderliggend) niveau al is geselecteerd"; break; } } } } } JSONObject obj = new JSONObject(); obj.put("result", result); obj.put("message", message); return new StreamingResolution("application/json", new StringReader(obj.toString())); } catch(Exception e) { return new ErrorMessageResolution("Exception " + e.getClass() + ": " + e.getMessage()); } }
diff --git a/apps/i2psnark/java/src/org/klomp/snark/TrackerClient.java b/apps/i2psnark/java/src/org/klomp/snark/TrackerClient.java index fdb6ff763..01b6a829b 100644 --- a/apps/i2psnark/java/src/org/klomp/snark/TrackerClient.java +++ b/apps/i2psnark/java/src/org/klomp/snark/TrackerClient.java @@ -1,568 +1,568 @@ /* TrackerClient - Class that informs a tracker and gets new peers. Copyright (C) 2003 Mark J. Wielaard This file is part of Snark. 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.klomp.snark; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import net.i2p.I2PAppContext; import net.i2p.data.Hash; import net.i2p.util.I2PAppThread; import net.i2p.util.Log; /** * Informs metainfo tracker of events and gets new peers for peer * coordinator. * * @author Mark Wielaard ([email protected]) */ public class TrackerClient extends I2PAppThread { private final Log _log = I2PAppContext.getGlobalContext().logManager().getLog(TrackerClient.class); private static final String NO_EVENT = ""; private static final String STARTED_EVENT = "started"; private static final String COMPLETED_EVENT = "completed"; private static final String STOPPED_EVENT = "stopped"; private static final String NOT_REGISTERED = "torrent not registered"; //bytemonsoon private final static int SLEEP = 5; // 5 minutes. private final static int DELAY_MIN = 2000; // 2 secs. private final static int DELAY_MUL = 1500; // 1.5 secs. private final static int MAX_REGISTER_FAILS = 10; // * INITIAL_SLEEP = 15m to register private final static int INITIAL_SLEEP = 90*1000; private final static int MAX_CONSEC_FAILS = 5; // slow down after this private final static int LONG_SLEEP = 30*60*1000; // sleep a while after lots of fails private I2PSnarkUtil _util; private final MetaInfo meta; private final String additionalTrackerURL; private final PeerCoordinator coordinator; private final Snark snark; private final int port; private boolean stop; private boolean started; private List<Tracker> trackers; /** * @param meta null if in magnet mode * @param additionalTrackerURL may be null, from the ?tr= param in magnet mode, otherwise ignored */ public TrackerClient(I2PSnarkUtil util, MetaInfo meta, String additionalTrackerURL, PeerCoordinator coordinator, Snark snark) { super(); // Set unique name. String id = urlencode(snark.getID()); setName("TrackerClient " + id.substring(id.length() - 12)); _util = util; this.meta = meta; this.additionalTrackerURL = additionalTrackerURL; this.coordinator = coordinator; this.snark = snark; this.port = 6881; //(port == -1) ? 9 : port; } @Override public void start() { if (stop) throw new RuntimeException("Dont rerun me, create a copy"); super.start(); started = true; } public boolean halted() { return stop; } public boolean started() { return started; } /** * Interrupts this Thread to stop it. */ public void halt() { stop = true; this.interrupt(); } private boolean verifyConnected() { while (!stop && !_util.connected()) { boolean ok = _util.connect(); if (!ok) { try { Thread.sleep(30*1000); } catch (InterruptedException ie) {} } } return !stop && _util.connected(); } @Override public void run() { String infoHash = urlencode(snark.getInfoHash()); String peerID = urlencode(snark.getID()); // Construct the list of trackers for this torrent, // starting with the primary one listed in the metainfo, // followed by the secondary open trackers // It's painful, but try to make sure if an open tracker is also // the primary tracker, that we don't add it twice. // todo: check for b32 matches as well trackers = new ArrayList(2); String primary = null; if (meta != null) primary = meta.getAnnounce(); else if (additionalTrackerURL != null) primary = additionalTrackerURL; if (primary != null) { if (isValidAnnounce(primary)) { trackers.add(new Tracker(primary, true)); _log.debug("Announce: [" + primary + "] infoHash: " + infoHash); } else { _log.warn("Skipping invalid or non-i2p announce: " + primary); } } else { _log.warn("No primary announce"); primary = ""; } List tlist = _util.getOpenTrackers(); if (tlist != null && (meta == null || !meta.isPrivate())) { for (int i = 0; i < tlist.size(); i++) { String url = (String)tlist.get(i); if (!isValidAnnounce(url)) { _log.error("Bad announce URL: [" + url + "]"); continue; } int slash = url.indexOf('/', 7); if (slash <= 7) { _log.error("Bad announce URL: [" + url + "]"); continue; } if (primary.startsWith(url.substring(0, slash))) continue; String dest = _util.lookup(url.substring(7, slash)); if (dest == null) { _log.error("Announce host unknown: [" + url.substring(7, slash) + "]"); continue; } if (primary.startsWith("http://" + dest)) continue; if (primary.startsWith("http://i2p/" + dest)) continue; // opentrackers are primary if we don't have primary trackers.add(new Tracker(url, primary.equals(""))); _log.debug("Additional announce: [" + url + "] for infoHash: " + infoHash); } } if (trackers.isEmpty()) { stop = true; // FIXME translate SnarkManager.instance().addMessage("No valid trackers for " + this.snark.getBaseName() + " - enable opentrackers?"); _log.error("No valid trackers for " + this.snark.getBaseName()); // FIXME keep going if DHT enabled this.snark.stopTorrent(); return; } long uploaded = coordinator.getUploaded(); long downloaded = coordinator.getDownloaded(); long left = coordinator.getLeft(); boolean completed = (left == 0); try { if (!verifyConnected()) return; boolean runStarted = false; boolean firstTime = true; int consecutiveFails = 0; Random r = I2PAppContext.getGlobalContext().random(); while(!stop) { // Local DHT tracker announce if (_util.getDHT() != null) _util.getDHT().announce(snark.getInfoHash()); try { // Sleep some minutes... // Sleep the minimum interval for all the trackers, but 60s minimum // except for the first time... int delay; int random = r.nextInt(120*1000); if (firstTime) { delay = r.nextInt(30*1000); firstTime = false; } else if (completed && runStarted) delay = 3*SLEEP*60*1000 + random; else if (snark.getTrackerProblems() != null && ++consecutiveFails < MAX_CONSEC_FAILS) delay = INITIAL_SLEEP; else // sleep a while, when we wake up we will contact only the trackers whose intervals have passed delay = SLEEP*60*1000 + random; if (delay > 0) Thread.sleep(delay); } catch(InterruptedException interrupt) { // ignore } if (stop) break; if (!verifyConnected()) return; uploaded = coordinator.getUploaded(); downloaded = coordinator.getDownloaded(); left = coordinator.getLeft(); // -1 in magnet mode // First time we got a complete download? String event; if (!completed && left == 0) { completed = true; event = COMPLETED_EVENT; } else event = NO_EVENT; // *** loop once for each tracker int maxSeenPeers = 0; for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { Tracker tr = (Tracker)iter.next(); if ((!stop) && (!tr.stop) && - (completed || coordinator.needOutboundPeers()) && + (completed || coordinator.needOutboundPeers() || !tr.started) && (event.equals(COMPLETED_EVENT) || System.currentTimeMillis() > tr.lastRequestTime + tr.interval)) { try { if (!tr.started) event = STARTED_EVENT; TrackerInfo info = doRequest(tr, infoHash, peerID, uploaded, downloaded, left, event); snark.setTrackerProblems(null); tr.trackerProblems = null; tr.registerFails = 0; tr.consecutiveFails = 0; if (tr.isPrimary) consecutiveFails = 0; runStarted = true; tr.started = true; Set<Peer> peers = info.getPeers(); tr.seenPeers = info.getPeerCount(); if (snark.getTrackerSeenPeers() < tr.seenPeers) // update rising number quickly snark.setTrackerSeenPeers(tr.seenPeers); // pass everybody over to our tracker if (_util.getDHT() != null) { for (Peer peer : peers) { _util.getDHT().announce(snark.getInfoHash(), peer.getPeerID().getDestHash()); } } if (coordinator.needOutboundPeers()) { // we only want to talk to new people if we need things // from them (duh) List<Peer> ordered = new ArrayList(peers); Collections.shuffle(ordered, r); Iterator<Peer> it = ordered.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); // FIXME if id == us || dest == us continue; // only delay if we actually make an attempt to add peer if(coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } catch (IOException ioe) { // Probably not fatal (if it doesn't last to long...) _util.debug ("WARNING: Could not contact tracker at '" + tr.announce + "': " + ioe, Snark.WARNING); tr.trackerProblems = ioe.getMessage(); // don't show secondary tracker problems to the user if (tr.isPrimary) snark.setTrackerProblems(tr.trackerProblems); if (tr.trackerProblems.toLowerCase(Locale.US).startsWith(NOT_REGISTERED)) { // Give a guy some time to register it if using opentrackers too if (trackers.size() == 1) { stop = true; snark.stopTorrent(); } else { // hopefully each on the opentrackers list is really open if (tr.registerFails++ > MAX_REGISTER_FAILS) tr.stop = true; } } if (++tr.consecutiveFails == MAX_CONSEC_FAILS) { tr.seenPeers = 0; if (tr.interval < LONG_SLEEP) tr.interval = LONG_SLEEP; // slow down } } } if ((!tr.stop) && maxSeenPeers < tr.seenPeers) maxSeenPeers = tr.seenPeers; } // *** end of trackers loop here // Get peers from PEX if (coordinator.needOutboundPeers() && (meta == null || !meta.isPrivate()) && !stop) { Set<PeerID> pids = coordinator.getPEXPeers(); if (!pids.isEmpty()) { _util.debug("Got " + pids.size() + " from PEX", Snark.INFO); List<Peer> peers = new ArrayList(pids.size()); for (PeerID pID : pids) { peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // Get peers from DHT // FIXME this needs to be in its own thread if (_util.getDHT() != null && (meta == null || !meta.isPrivate()) && !stop) { int numwant; if (event.equals(STOPPED_EVENT) || !coordinator.needOutboundPeers()) numwant = 1; else numwant = _util.getMaxConnections(); List<Hash> hashes = _util.getDHT().getPeers(snark.getInfoHash(), numwant, 2*60*1000); _util.debug("Got " + hashes + " from DHT", Snark.INFO); // announce ourselves while the token is still good // FIXME this needs to be in its own thread if (!stop) { int good = _util.getDHT().announce(snark.getInfoHash(), 8, 5*60*1000); _util.debug("Sent " + good + " good announces to DHT", Snark.INFO); } // now try these peers if ((!stop) && !hashes.isEmpty()) { List<Peer> peers = new ArrayList(hashes.size()); for (Hash h : hashes) { PeerID pID = new PeerID(h.getData()); peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // we could try and total the unique peers but that's too hard for now snark.setTrackerSeenPeers(maxSeenPeers); if (!runStarted) _util.debug(" Retrying in one minute...", Snark.DEBUG); } // *** end of while loop } // try catch (Throwable t) { _util.debug("TrackerClient: " + t, Snark.ERROR, t); if (t instanceof OutOfMemoryError) throw (OutOfMemoryError)t; } finally { // Local DHT tracker unannounce if (_util.getDHT() != null) _util.getDHT().unannounce(snark.getInfoHash()); try { // try to contact everybody we can // Don't try to restart I2CP connection just to say goodbye for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { if (!_util.connected()) return; Tracker tr = (Tracker)iter.next(); if (tr.started && (!tr.stop) && tr.trackerProblems == null) doRequest(tr, infoHash, peerID, uploaded, downloaded, left, STOPPED_EVENT); } } catch(IOException ioe) { /* ignored */ } } } private TrackerInfo doRequest(Tracker tr, String infoHash, String peerID, long uploaded, long downloaded, long left, String event) throws IOException { StringBuilder buf = new StringBuilder(512); buf.append(tr.announce); if (tr.announce.contains("?")) buf.append('&'); else buf.append('?'); buf.append("info_hash=").append(infoHash) .append("&peer_id=").append(peerID) .append("&port=").append(port) .append("&ip=" ).append(_util.getOurIPString()).append(".i2p") .append("&uploaded=").append(uploaded) .append("&downloaded=").append(downloaded) .append("&left="); // What do we send for left in magnet mode? Can we omit it? if (left >= 0) buf.append(left); else buf.append('1'); buf.append("&compact=1"); // NOTE: opentracker will return 400 for &compact alone if (! event.equals(NO_EVENT)) buf.append("&event=").append(event); buf.append("&numwant="); if (left == 0 || event.equals(STOPPED_EVENT) || !coordinator.needOutboundPeers()) buf.append('0'); else buf.append(_util.getMaxConnections()); String s = buf.toString(); _util.debug("Sending TrackerClient request: " + s, Snark.INFO); tr.lastRequestTime = System.currentTimeMillis(); File fetched = _util.get(s); if (fetched == null) { throw new IOException("Error fetching " + s); } InputStream in = null; try { in = new FileInputStream(fetched); TrackerInfo info = new TrackerInfo(in, snark.getID(), snark.getInfoHash(), snark.getMetaInfo()); _util.debug("TrackerClient response: " + info, Snark.INFO); String failure = info.getFailureReason(); if (failure != null) throw new IOException(failure); tr.interval = info.getInterval() * 1000; return info; } finally { if (in != null) try { in.close(); } catch (IOException ioe) {} fetched.delete(); } } /** * Very lazy byte[] to URL encoder. Just encodes almost everything, even * some "normal" chars. * By not encoding about 1/4 of the chars, we make random data like hashes about 16% smaller. * * RFC1738: 0-9a-zA-Z$-_.+!*'(), * Us: 0-9a-zA-Z * */ public static String urlencode(byte[] bs) { StringBuilder sb = new StringBuilder(bs.length*3); for (int i = 0; i < bs.length; i++) { int c = bs[i] & 0xFF; if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { sb.append((char)c); } else { sb.append('%'); if (c < 16) sb.append('0'); sb.append(Integer.toHexString(c)); } } return sb.toString(); } /** * @return true for i2p hosts only * @since 0.7.12 */ static boolean isValidAnnounce(String ann) { URL url; try { url = new URL(ann); } catch (MalformedURLException mue) { return false; } return url.getProtocol().equals("http") && (url.getHost().endsWith(".i2p") || url.getHost().equals("i2p")) && url.getPort() < 0; } private static class Tracker { String announce; boolean isPrimary; long interval; long lastRequestTime; String trackerProblems; boolean stop; boolean started; int registerFails; int consecutiveFails; int seenPeers; public Tracker(String a, boolean p) { announce = a; isPrimary = p; interval = INITIAL_SLEEP; lastRequestTime = 0; trackerProblems = null; stop = false; started = false; registerFails = 0; consecutiveFails = 0; seenPeers = 0; } } }
true
true
public void run() { String infoHash = urlencode(snark.getInfoHash()); String peerID = urlencode(snark.getID()); // Construct the list of trackers for this torrent, // starting with the primary one listed in the metainfo, // followed by the secondary open trackers // It's painful, but try to make sure if an open tracker is also // the primary tracker, that we don't add it twice. // todo: check for b32 matches as well trackers = new ArrayList(2); String primary = null; if (meta != null) primary = meta.getAnnounce(); else if (additionalTrackerURL != null) primary = additionalTrackerURL; if (primary != null) { if (isValidAnnounce(primary)) { trackers.add(new Tracker(primary, true)); _log.debug("Announce: [" + primary + "] infoHash: " + infoHash); } else { _log.warn("Skipping invalid or non-i2p announce: " + primary); } } else { _log.warn("No primary announce"); primary = ""; } List tlist = _util.getOpenTrackers(); if (tlist != null && (meta == null || !meta.isPrivate())) { for (int i = 0; i < tlist.size(); i++) { String url = (String)tlist.get(i); if (!isValidAnnounce(url)) { _log.error("Bad announce URL: [" + url + "]"); continue; } int slash = url.indexOf('/', 7); if (slash <= 7) { _log.error("Bad announce URL: [" + url + "]"); continue; } if (primary.startsWith(url.substring(0, slash))) continue; String dest = _util.lookup(url.substring(7, slash)); if (dest == null) { _log.error("Announce host unknown: [" + url.substring(7, slash) + "]"); continue; } if (primary.startsWith("http://" + dest)) continue; if (primary.startsWith("http://i2p/" + dest)) continue; // opentrackers are primary if we don't have primary trackers.add(new Tracker(url, primary.equals(""))); _log.debug("Additional announce: [" + url + "] for infoHash: " + infoHash); } } if (trackers.isEmpty()) { stop = true; // FIXME translate SnarkManager.instance().addMessage("No valid trackers for " + this.snark.getBaseName() + " - enable opentrackers?"); _log.error("No valid trackers for " + this.snark.getBaseName()); // FIXME keep going if DHT enabled this.snark.stopTorrent(); return; } long uploaded = coordinator.getUploaded(); long downloaded = coordinator.getDownloaded(); long left = coordinator.getLeft(); boolean completed = (left == 0); try { if (!verifyConnected()) return; boolean runStarted = false; boolean firstTime = true; int consecutiveFails = 0; Random r = I2PAppContext.getGlobalContext().random(); while(!stop) { // Local DHT tracker announce if (_util.getDHT() != null) _util.getDHT().announce(snark.getInfoHash()); try { // Sleep some minutes... // Sleep the minimum interval for all the trackers, but 60s minimum // except for the first time... int delay; int random = r.nextInt(120*1000); if (firstTime) { delay = r.nextInt(30*1000); firstTime = false; } else if (completed && runStarted) delay = 3*SLEEP*60*1000 + random; else if (snark.getTrackerProblems() != null && ++consecutiveFails < MAX_CONSEC_FAILS) delay = INITIAL_SLEEP; else // sleep a while, when we wake up we will contact only the trackers whose intervals have passed delay = SLEEP*60*1000 + random; if (delay > 0) Thread.sleep(delay); } catch(InterruptedException interrupt) { // ignore } if (stop) break; if (!verifyConnected()) return; uploaded = coordinator.getUploaded(); downloaded = coordinator.getDownloaded(); left = coordinator.getLeft(); // -1 in magnet mode // First time we got a complete download? String event; if (!completed && left == 0) { completed = true; event = COMPLETED_EVENT; } else event = NO_EVENT; // *** loop once for each tracker int maxSeenPeers = 0; for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { Tracker tr = (Tracker)iter.next(); if ((!stop) && (!tr.stop) && (completed || coordinator.needOutboundPeers()) && (event.equals(COMPLETED_EVENT) || System.currentTimeMillis() > tr.lastRequestTime + tr.interval)) { try { if (!tr.started) event = STARTED_EVENT; TrackerInfo info = doRequest(tr, infoHash, peerID, uploaded, downloaded, left, event); snark.setTrackerProblems(null); tr.trackerProblems = null; tr.registerFails = 0; tr.consecutiveFails = 0; if (tr.isPrimary) consecutiveFails = 0; runStarted = true; tr.started = true; Set<Peer> peers = info.getPeers(); tr.seenPeers = info.getPeerCount(); if (snark.getTrackerSeenPeers() < tr.seenPeers) // update rising number quickly snark.setTrackerSeenPeers(tr.seenPeers); // pass everybody over to our tracker if (_util.getDHT() != null) { for (Peer peer : peers) { _util.getDHT().announce(snark.getInfoHash(), peer.getPeerID().getDestHash()); } } if (coordinator.needOutboundPeers()) { // we only want to talk to new people if we need things // from them (duh) List<Peer> ordered = new ArrayList(peers); Collections.shuffle(ordered, r); Iterator<Peer> it = ordered.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); // FIXME if id == us || dest == us continue; // only delay if we actually make an attempt to add peer if(coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } catch (IOException ioe) { // Probably not fatal (if it doesn't last to long...) _util.debug ("WARNING: Could not contact tracker at '" + tr.announce + "': " + ioe, Snark.WARNING); tr.trackerProblems = ioe.getMessage(); // don't show secondary tracker problems to the user if (tr.isPrimary) snark.setTrackerProblems(tr.trackerProblems); if (tr.trackerProblems.toLowerCase(Locale.US).startsWith(NOT_REGISTERED)) { // Give a guy some time to register it if using opentrackers too if (trackers.size() == 1) { stop = true; snark.stopTorrent(); } else { // hopefully each on the opentrackers list is really open if (tr.registerFails++ > MAX_REGISTER_FAILS) tr.stop = true; } } if (++tr.consecutiveFails == MAX_CONSEC_FAILS) { tr.seenPeers = 0; if (tr.interval < LONG_SLEEP) tr.interval = LONG_SLEEP; // slow down } } } if ((!tr.stop) && maxSeenPeers < tr.seenPeers) maxSeenPeers = tr.seenPeers; } // *** end of trackers loop here // Get peers from PEX if (coordinator.needOutboundPeers() && (meta == null || !meta.isPrivate()) && !stop) { Set<PeerID> pids = coordinator.getPEXPeers(); if (!pids.isEmpty()) { _util.debug("Got " + pids.size() + " from PEX", Snark.INFO); List<Peer> peers = new ArrayList(pids.size()); for (PeerID pID : pids) { peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // Get peers from DHT // FIXME this needs to be in its own thread if (_util.getDHT() != null && (meta == null || !meta.isPrivate()) && !stop) { int numwant; if (event.equals(STOPPED_EVENT) || !coordinator.needOutboundPeers()) numwant = 1; else numwant = _util.getMaxConnections(); List<Hash> hashes = _util.getDHT().getPeers(snark.getInfoHash(), numwant, 2*60*1000); _util.debug("Got " + hashes + " from DHT", Snark.INFO); // announce ourselves while the token is still good // FIXME this needs to be in its own thread if (!stop) { int good = _util.getDHT().announce(snark.getInfoHash(), 8, 5*60*1000); _util.debug("Sent " + good + " good announces to DHT", Snark.INFO); } // now try these peers if ((!stop) && !hashes.isEmpty()) { List<Peer> peers = new ArrayList(hashes.size()); for (Hash h : hashes) { PeerID pID = new PeerID(h.getData()); peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // we could try and total the unique peers but that's too hard for now snark.setTrackerSeenPeers(maxSeenPeers); if (!runStarted) _util.debug(" Retrying in one minute...", Snark.DEBUG); } // *** end of while loop } // try catch (Throwable t) { _util.debug("TrackerClient: " + t, Snark.ERROR, t); if (t instanceof OutOfMemoryError) throw (OutOfMemoryError)t; } finally { // Local DHT tracker unannounce if (_util.getDHT() != null) _util.getDHT().unannounce(snark.getInfoHash()); try { // try to contact everybody we can // Don't try to restart I2CP connection just to say goodbye for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { if (!_util.connected()) return; Tracker tr = (Tracker)iter.next(); if (tr.started && (!tr.stop) && tr.trackerProblems == null) doRequest(tr, infoHash, peerID, uploaded, downloaded, left, STOPPED_EVENT); } } catch(IOException ioe) { /* ignored */ } } }
public void run() { String infoHash = urlencode(snark.getInfoHash()); String peerID = urlencode(snark.getID()); // Construct the list of trackers for this torrent, // starting with the primary one listed in the metainfo, // followed by the secondary open trackers // It's painful, but try to make sure if an open tracker is also // the primary tracker, that we don't add it twice. // todo: check for b32 matches as well trackers = new ArrayList(2); String primary = null; if (meta != null) primary = meta.getAnnounce(); else if (additionalTrackerURL != null) primary = additionalTrackerURL; if (primary != null) { if (isValidAnnounce(primary)) { trackers.add(new Tracker(primary, true)); _log.debug("Announce: [" + primary + "] infoHash: " + infoHash); } else { _log.warn("Skipping invalid or non-i2p announce: " + primary); } } else { _log.warn("No primary announce"); primary = ""; } List tlist = _util.getOpenTrackers(); if (tlist != null && (meta == null || !meta.isPrivate())) { for (int i = 0; i < tlist.size(); i++) { String url = (String)tlist.get(i); if (!isValidAnnounce(url)) { _log.error("Bad announce URL: [" + url + "]"); continue; } int slash = url.indexOf('/', 7); if (slash <= 7) { _log.error("Bad announce URL: [" + url + "]"); continue; } if (primary.startsWith(url.substring(0, slash))) continue; String dest = _util.lookup(url.substring(7, slash)); if (dest == null) { _log.error("Announce host unknown: [" + url.substring(7, slash) + "]"); continue; } if (primary.startsWith("http://" + dest)) continue; if (primary.startsWith("http://i2p/" + dest)) continue; // opentrackers are primary if we don't have primary trackers.add(new Tracker(url, primary.equals(""))); _log.debug("Additional announce: [" + url + "] for infoHash: " + infoHash); } } if (trackers.isEmpty()) { stop = true; // FIXME translate SnarkManager.instance().addMessage("No valid trackers for " + this.snark.getBaseName() + " - enable opentrackers?"); _log.error("No valid trackers for " + this.snark.getBaseName()); // FIXME keep going if DHT enabled this.snark.stopTorrent(); return; } long uploaded = coordinator.getUploaded(); long downloaded = coordinator.getDownloaded(); long left = coordinator.getLeft(); boolean completed = (left == 0); try { if (!verifyConnected()) return; boolean runStarted = false; boolean firstTime = true; int consecutiveFails = 0; Random r = I2PAppContext.getGlobalContext().random(); while(!stop) { // Local DHT tracker announce if (_util.getDHT() != null) _util.getDHT().announce(snark.getInfoHash()); try { // Sleep some minutes... // Sleep the minimum interval for all the trackers, but 60s minimum // except for the first time... int delay; int random = r.nextInt(120*1000); if (firstTime) { delay = r.nextInt(30*1000); firstTime = false; } else if (completed && runStarted) delay = 3*SLEEP*60*1000 + random; else if (snark.getTrackerProblems() != null && ++consecutiveFails < MAX_CONSEC_FAILS) delay = INITIAL_SLEEP; else // sleep a while, when we wake up we will contact only the trackers whose intervals have passed delay = SLEEP*60*1000 + random; if (delay > 0) Thread.sleep(delay); } catch(InterruptedException interrupt) { // ignore } if (stop) break; if (!verifyConnected()) return; uploaded = coordinator.getUploaded(); downloaded = coordinator.getDownloaded(); left = coordinator.getLeft(); // -1 in magnet mode // First time we got a complete download? String event; if (!completed && left == 0) { completed = true; event = COMPLETED_EVENT; } else event = NO_EVENT; // *** loop once for each tracker int maxSeenPeers = 0; for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { Tracker tr = (Tracker)iter.next(); if ((!stop) && (!tr.stop) && (completed || coordinator.needOutboundPeers() || !tr.started) && (event.equals(COMPLETED_EVENT) || System.currentTimeMillis() > tr.lastRequestTime + tr.interval)) { try { if (!tr.started) event = STARTED_EVENT; TrackerInfo info = doRequest(tr, infoHash, peerID, uploaded, downloaded, left, event); snark.setTrackerProblems(null); tr.trackerProblems = null; tr.registerFails = 0; tr.consecutiveFails = 0; if (tr.isPrimary) consecutiveFails = 0; runStarted = true; tr.started = true; Set<Peer> peers = info.getPeers(); tr.seenPeers = info.getPeerCount(); if (snark.getTrackerSeenPeers() < tr.seenPeers) // update rising number quickly snark.setTrackerSeenPeers(tr.seenPeers); // pass everybody over to our tracker if (_util.getDHT() != null) { for (Peer peer : peers) { _util.getDHT().announce(snark.getInfoHash(), peer.getPeerID().getDestHash()); } } if (coordinator.needOutboundPeers()) { // we only want to talk to new people if we need things // from them (duh) List<Peer> ordered = new ArrayList(peers); Collections.shuffle(ordered, r); Iterator<Peer> it = ordered.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); // FIXME if id == us || dest == us continue; // only delay if we actually make an attempt to add peer if(coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } catch (IOException ioe) { // Probably not fatal (if it doesn't last to long...) _util.debug ("WARNING: Could not contact tracker at '" + tr.announce + "': " + ioe, Snark.WARNING); tr.trackerProblems = ioe.getMessage(); // don't show secondary tracker problems to the user if (tr.isPrimary) snark.setTrackerProblems(tr.trackerProblems); if (tr.trackerProblems.toLowerCase(Locale.US).startsWith(NOT_REGISTERED)) { // Give a guy some time to register it if using opentrackers too if (trackers.size() == 1) { stop = true; snark.stopTorrent(); } else { // hopefully each on the opentrackers list is really open if (tr.registerFails++ > MAX_REGISTER_FAILS) tr.stop = true; } } if (++tr.consecutiveFails == MAX_CONSEC_FAILS) { tr.seenPeers = 0; if (tr.interval < LONG_SLEEP) tr.interval = LONG_SLEEP; // slow down } } } if ((!tr.stop) && maxSeenPeers < tr.seenPeers) maxSeenPeers = tr.seenPeers; } // *** end of trackers loop here // Get peers from PEX if (coordinator.needOutboundPeers() && (meta == null || !meta.isPrivate()) && !stop) { Set<PeerID> pids = coordinator.getPEXPeers(); if (!pids.isEmpty()) { _util.debug("Got " + pids.size() + " from PEX", Snark.INFO); List<Peer> peers = new ArrayList(pids.size()); for (PeerID pID : pids) { peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // Get peers from DHT // FIXME this needs to be in its own thread if (_util.getDHT() != null && (meta == null || !meta.isPrivate()) && !stop) { int numwant; if (event.equals(STOPPED_EVENT) || !coordinator.needOutboundPeers()) numwant = 1; else numwant = _util.getMaxConnections(); List<Hash> hashes = _util.getDHT().getPeers(snark.getInfoHash(), numwant, 2*60*1000); _util.debug("Got " + hashes + " from DHT", Snark.INFO); // announce ourselves while the token is still good // FIXME this needs to be in its own thread if (!stop) { int good = _util.getDHT().announce(snark.getInfoHash(), 8, 5*60*1000); _util.debug("Sent " + good + " good announces to DHT", Snark.INFO); } // now try these peers if ((!stop) && !hashes.isEmpty()) { List<Peer> peers = new ArrayList(hashes.size()); for (Hash h : hashes) { PeerID pID = new PeerID(h.getData()); peers.add(new Peer(pID, snark.getID(), snark.getInfoHash(), snark.getMetaInfo())); } Collections.shuffle(peers, r); Iterator<Peer> it = peers.iterator(); while ((!stop) && it.hasNext() && coordinator.needOutboundPeers()) { Peer cur = it.next(); if (coordinator.addPeer(cur) && it.hasNext()) { int delay = (DELAY_MUL * r.nextInt(10)) + DELAY_MIN; try { Thread.sleep(delay); } catch (InterruptedException ie) {} } } } } // we could try and total the unique peers but that's too hard for now snark.setTrackerSeenPeers(maxSeenPeers); if (!runStarted) _util.debug(" Retrying in one minute...", Snark.DEBUG); } // *** end of while loop } // try catch (Throwable t) { _util.debug("TrackerClient: " + t, Snark.ERROR, t); if (t instanceof OutOfMemoryError) throw (OutOfMemoryError)t; } finally { // Local DHT tracker unannounce if (_util.getDHT() != null) _util.getDHT().unannounce(snark.getInfoHash()); try { // try to contact everybody we can // Don't try to restart I2CP connection just to say goodbye for (Iterator iter = trackers.iterator(); iter.hasNext(); ) { if (!_util.connected()) return; Tracker tr = (Tracker)iter.next(); if (tr.started && (!tr.stop) && tr.trackerProblems == null) doRequest(tr, infoHash, peerID, uploaded, downloaded, left, STOPPED_EVENT); } } catch(IOException ioe) { /* ignored */ } } }
diff --git a/app/controllers/Main.java b/app/controllers/Main.java index c17e5ac..320050a 100644 --- a/app/controllers/Main.java +++ b/app/controllers/Main.java @@ -1,146 +1,146 @@ package controllers; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import models.*; import play.libs.Mail; import play.mvc.Controller; import play.data.validation.Required; import repo.Repository; /** * Non-secured controller class. */ public class Main extends Controller { /** * Displays the main welcome page. */ public static void index(){ if(!Security.isConnected()) render(); else PageController.welcome(); } /** * Displays the form to create a new account */ public static void createAccount(){ render(); } /** * Creates a new user * @param email * @param password * @param firstName * @param lastName * @param address * @param phoneNumber * @param sex * @param code code to create the account as a physician */ public static void newAccount(@Required(message = "Please enter a valid email address") String email, @Required(message = "Please enter a password") String password, @Required(message = "Please enter your first name") String firstName, @Required(message = "Please enter your last name") String lastName, @Required(message = "Please enter your address") String address, @Required(message = "Please enter your phone number") String phoneNumber, @Required String sex, String code){ //Check that the email isnt registered already if(User.find("byUsername", email).fetch().size() > 0){ //Email already registered. validation.addError("email", "Email already registered", "email"); } //Validate email address String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("email", "Enter a valid email address", email); } //Validate the phone number expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; inputStr = phoneNumber; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber); } /* * Doesnt work currently, skipping //Validate the address expression = "\\d+ \\s+ \\.*"; inputStr = address; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("address", "Enter a valid address", address); }*/ //Check if there is an entered code, and if its valid - if(code != null && !code.equals("physician") ){ + if(!code.equals("") && !code.equals("physician") ){ validation.addError("code", "Please enter a valid physician code, or leave it blank", code); } if (validation.hasErrors()) { render("Main/createAccount.html", email, firstName, lastName, address, phoneNumber, code); } //If the code is correct, create user as physician if(code.equals("physician")){ new Physician(email, password, firstName, lastName).save(); } else { //Else, create them as a patient new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save(); } //Authenticate them automatically session.put("username", email); PageController.welcome(); } /** * Reders the forgot password page */ public static void forgotPassword(){ render(); } public static void sendPassword(@Required(message = "A valid email address is required") String email){ User user = User.find("byUsername", email).first(); if(validation.hasErrors() || user == null){ if(user == null) validation.addError(email, "Email address is not registered", email); render("Main/forgotPassword.html"); } try { //Will need to set up email prefs in the conf to be able to use SimpleEmail toSend = new SimpleEmail(); toSend.setFrom("[email protected]"); toSend.addTo(email, user.getName()); toSend.setSubject("Ultra Password"); toSend.setMsg("Your password to Ultra is: "+ Repository.decodePassword( user.getPassword() ) ); Mail.send(toSend); } catch (EmailException e) { e.printStackTrace(System.out); } render(email); } }
true
true
public static void newAccount(@Required(message = "Please enter a valid email address") String email, @Required(message = "Please enter a password") String password, @Required(message = "Please enter your first name") String firstName, @Required(message = "Please enter your last name") String lastName, @Required(message = "Please enter your address") String address, @Required(message = "Please enter your phone number") String phoneNumber, @Required String sex, String code){ //Check that the email isnt registered already if(User.find("byUsername", email).fetch().size() > 0){ //Email already registered. validation.addError("email", "Email already registered", "email"); } //Validate email address String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("email", "Enter a valid email address", email); } //Validate the phone number expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; inputStr = phoneNumber; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber); } /* * Doesnt work currently, skipping //Validate the address expression = "\\d+ \\s+ \\.*"; inputStr = address; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("address", "Enter a valid address", address); }*/ //Check if there is an entered code, and if its valid if(code != null && !code.equals("physician") ){ validation.addError("code", "Please enter a valid physician code, or leave it blank", code); } if (validation.hasErrors()) { render("Main/createAccount.html", email, firstName, lastName, address, phoneNumber, code); } //If the code is correct, create user as physician if(code.equals("physician")){ new Physician(email, password, firstName, lastName).save(); } else { //Else, create them as a patient new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save(); } //Authenticate them automatically session.put("username", email); PageController.welcome(); }
public static void newAccount(@Required(message = "Please enter a valid email address") String email, @Required(message = "Please enter a password") String password, @Required(message = "Please enter your first name") String firstName, @Required(message = "Please enter your last name") String lastName, @Required(message = "Please enter your address") String address, @Required(message = "Please enter your phone number") String phoneNumber, @Required String sex, String code){ //Check that the email isnt registered already if(User.find("byUsername", email).fetch().size() > 0){ //Email already registered. validation.addError("email", "Email already registered", "email"); } //Validate email address String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("email", "Enter a valid email address", email); } //Validate the phone number expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; inputStr = phoneNumber; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("phoneNumber", "Enter a valid phone number", phoneNumber); } /* * Doesnt work currently, skipping //Validate the address expression = "\\d+ \\s+ \\.*"; inputStr = address; pattern = Pattern.compile(expression); matcher = pattern.matcher(inputStr); if( !matcher.matches() ){ validation.addError("address", "Enter a valid address", address); }*/ //Check if there is an entered code, and if its valid if(!code.equals("") && !code.equals("physician") ){ validation.addError("code", "Please enter a valid physician code, or leave it blank", code); } if (validation.hasErrors()) { render("Main/createAccount.html", email, firstName, lastName, address, phoneNumber, code); } //If the code is correct, create user as physician if(code.equals("physician")){ new Physician(email, password, firstName, lastName).save(); } else { //Else, create them as a patient new Patient(email, password, firstName, lastName, address, phoneNumber, sex.charAt(0)).save(); } //Authenticate them automatically session.put("username", email); PageController.welcome(); }
diff --git a/Factory/src/factory/graphics/GraphicLaneManager.java b/Factory/src/factory/graphics/GraphicLaneManager.java index 05ae6c1..603cbe5 100644 --- a/Factory/src/factory/graphics/GraphicLaneManager.java +++ b/Factory/src/factory/graphics/GraphicLaneManager.java @@ -1,647 +1,649 @@ //Minh La package factory.graphics; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.ImageIcon; import factory.Part; public class GraphicLaneManager{ //Image Icons ImageIcon lane1Icon, lane2Icon; ImageIcon divergeLaneIcon; ImageIcon feederIcon; GraphicBin bin; //Bin coordinates int feederX,feederY; //Items ArrayList <GraphicItem> lane1Items; ArrayList <GraphicItem> lane2Items; ArrayList <Boolean> lane1QueueTaken; //The queue ArrayList <Boolean> lane2QueueTaken; //The queue //variables int vX, vY; //velocities int lane_xPos, lane_yPos; //lane relative position boolean laneStart; //default = false boolean divergeUp; //true - up, false - down int timerCount; //counter to periodic add item to lane int binItemCount; //current item in bin to dump int vibrationCount; //every 2 paint, it'll vibrate private int vibrationAmplitude; int laneManagerID; //lane Manager Number int laneAnimationCounter, laneAnimationSpeed; boolean feederOn; //Feeder on/off boolean binExists; boolean lane1PurgeOn; boolean lane2PurgeOn; boolean feederPurged; int feederPurgeTimer; int stabilizationCount[]; boolean isStable[]; int laneSpeed; GraphicPanel graphicPanel; public GraphicLaneManager(int laneX,int laneY, int ID, GraphicPanel gp){ lane_xPos = laneX; lane_yPos = laneY; //MODIFY to change Lane position laneManagerID = ID; graphicPanel = gp; //bin = null; //declaration of variables laneAnimationCounter = 0; laneAnimationSpeed = 1; // default value lane1Items = new ArrayList<GraphicItem>(); lane2Items = new ArrayList<GraphicItem>(); lane1QueueTaken = new ArrayList<Boolean>(); lane2QueueTaken = new ArrayList<Boolean>(); laneSpeed = 8; //Change speed of the lane later vX = -laneSpeed; vY = laneSpeed; laneStart = false; divergeUp = false; feederOn = false; binExists = false; lane1PurgeOn = false; //Nest purge is off unless turned on lane2PurgeOn = false; //Nest purge is off unless turned on feederPurged = false; timerCount = 1; binItemCount = 0; vibrationCount = 0; vibrationAmplitude = 2; stabilizationCount = new int[2]; isStable = new boolean[2]; for (int i = 0; i < 2; i++) { stabilizationCount[i] = 0; isStable[i] = false; } //Location of bin to appear. x is fixed feederX = lane_xPos + 250; feederY = lane_yPos + 15; //Declaration of variables lane1Icon = new ImageIcon("Images/lane.png"); lane2Icon = new ImageIcon("Images/lane.png"); divergeLaneIcon = new ImageIcon("Images/divergeLane.png"); feederIcon = new ImageIcon("Images/feeder.png"); } public void setBin(GraphicBin bin){ this.bin = bin; bin.getBinType().setX(feederX+35); bin.getBinType().setY(feederY+55); if (bin != null) binExists = true; } public GraphicBin getBin(){ return bin; } public boolean hasBin() { return binExists; } public GraphicBin popBin() { GraphicBin binCopy = bin; bin = null; binExists = false; return binCopy; } public void purgeFeeder() { bin.getBinItems().clear(); feederOn = false; feederPurged = true; feederPurgeTimer = 0; } public void paintLane(Graphics g){ Graphics2D g2 = (Graphics2D) g; // Draw lanes // horizontal Graphics2D g3 = (Graphics2D)g.create(); // vertical g3.rotate(Math.toRadians(90),lane_xPos+210, lane_yPos+20); g3.drawImage(new ImageIcon("Images/Lane/"+laneAnimationCounter/laneAnimationSpeed+".png").getImage(), lane_xPos+210, lane_yPos-25, 120, 40, null); g3.dispose(); g2.drawImage(new ImageIcon("Images/Lane/"+laneAnimationCounter/laneAnimationSpeed+".png").getImage(), lane_xPos+75, lane_yPos+20, 180, 40, null); g2.drawImage(new ImageIcon("Images/Lane/"+laneAnimationCounter/laneAnimationSpeed+".png").getImage(), lane_xPos+75, lane_yPos+100, 180, 40, null); laneAnimationCounter ++; if(laneAnimationCounter == laneAnimationSpeed*7) // 7 = number of images laneAnimationCounter = 0; for(int i = 0;i<lane1Items.size();i++) lane1Items.get(i).paint(g2); for(int i = 0;i<lane2Items.size();i++) lane2Items.get(i).paint(g2); vibrationCount++; } // END Paint function public void paintFeeder(Graphics g) { if (binExists) g.drawImage(bin.getBinImage().getImage(), feederX + 50, feederY+15, null); g.drawImage(feederIcon.getImage(), feederX, feederY, null); g.setColor(new Color(60, 33, 0)); g.fillRect(feederX+34, feederY+54, 22, 22); if (binExists && feederPurgeTimer < 7) bin.getBinType().paint(g); } public void moveLane() { for (int i = 0; i < 2; i++) { stabilizationCount[i]++; if (binExists && stabilizationCount[i] >= bin.getStabilizationTime()) { isStable[i] = true; } else isStable[i] = false; } if (feederPurged) { feederPurgeTimer++; if (feederPurgeTimer < 7) bin.getBinType().moveX(5); else { feederPurged = false; graphicPanel.purgeFeederDone(laneManagerID); } } if(binExists){ if(laneStart){ if(feederOn){ if(timerCount % 10 == 0){ //Put an item on lane on a timed interval if(bin.getBinItems().size() > 0){ bin.getBinItems().get(0).setX(lane_xPos + 220); bin.getBinItems().get(0).setY(lane_yPos + 70); if(divergeUp){ bin.getBinItems().get(0).setVY(-8); bin.getBinItems().get(0).setDivergeUp(true); } else{ bin.getBinItems().get(0).setVY(8); bin.getBinItems().get(0).setDivergeUp(false); } bin.getBinItems().get(0).setVX(0); if(divergeUp) lane1Items.add(bin.getBinItems().get(0)); else lane2Items.add(bin.getBinItems().get(0)); bin.getBinItems().remove(0); if(bin.getBinItems().size() == 0){ feederOn = false; graphicPanel.feedLaneDone(laneManagerID * 2 + ((divergeUp)?0:1)); } } } } processLane(); } timerCount++; } else{ processLane(); } } public void processLane(){ if(lane1PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2).clearItems(); for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } System.out.println("size " + lane1QueueTaken.size()); if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends - //lane1QueueTaken.clear(); + lane1QueueTaken.clear(); System.out.println("size " + lane1QueueTaken.size()); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(lane1Items.get(i).getStepX() == 0){ lane1Items.remove(i); i--; } } if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends + lane1QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ //Normal lane processing for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //MOVES ITEMS DOWN LANE //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2).getSize() < 9){ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepX() < lane1QueueTaken.size() + 1){ lane1Items.get(j).setVX(0); } } if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; continue; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(graphicPanel.getNest().get(laneManagerID * 2).getSize() >= 9){ if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } } } else if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ if(lane1Items.get(i).getVY() == 0){ //In the queue if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } } } } } // END OF LANE 1 if(lane2PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends lane2QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane2Items.size();i++){ lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends + lane2QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ for(int i = 0;i<lane2Items.size();i++){ //Do the same for lane 2 lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() < 9){ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.get(i).getStepX() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepX() < lane2QueueTaken.size() + 1){ lane2Items.get(j).setVX(0); } } if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ // To be changed according to size of lane lane2Items.remove(i); i--; continue; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(lane2PurgeOn){ graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ lane2Items.get(j).setVX(vX); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } if(lane2Items.size() == 0) lane2PurgeOn = false; } else if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() >= 9){ if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ lane2Items.remove(i); i--; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } } } else if(lane2Items.get(i).getStepX() == 0){ // reaches Nest //remove from queue or lane item, add to nest lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = !lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2 + 1).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ if(lane2Items.get(i).getVY() == 0){ // lane 2 queue stopped moving. needs to vibrate if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } } } } } } }
false
true
public void processLane(){ if(lane1PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2).clearItems(); for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } System.out.println("size " + lane1QueueTaken.size()); if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends //lane1QueueTaken.clear(); System.out.println("size " + lane1QueueTaken.size()); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(lane1Items.get(i).getStepX() == 0){ lane1Items.remove(i); i--; } } if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ //Normal lane processing for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //MOVES ITEMS DOWN LANE //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2).getSize() < 9){ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepX() < lane1QueueTaken.size() + 1){ lane1Items.get(j).setVX(0); } } if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; continue; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(graphicPanel.getNest().get(laneManagerID * 2).getSize() >= 9){ if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } } } else if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ if(lane1Items.get(i).getVY() == 0){ //In the queue if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } } } } } // END OF LANE 1 if(lane2PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends lane2QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane2Items.size();i++){ lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ for(int i = 0;i<lane2Items.size();i++){ //Do the same for lane 2 lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() < 9){ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.get(i).getStepX() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepX() < lane2QueueTaken.size() + 1){ lane2Items.get(j).setVX(0); } } if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ // To be changed according to size of lane lane2Items.remove(i); i--; continue; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(lane2PurgeOn){ graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ lane2Items.get(j).setVX(vX); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } if(lane2Items.size() == 0) lane2PurgeOn = false; } else if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() >= 9){ if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ lane2Items.remove(i); i--; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } } } else if(lane2Items.get(i).getStepX() == 0){ // reaches Nest //remove from queue or lane item, add to nest lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = !lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2 + 1).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ if(lane2Items.get(i).getVY() == 0){ // lane 2 queue stopped moving. needs to vibrate if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } } } } } }
public void processLane(){ if(lane1PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2).clearItems(); for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } System.out.println("size " + lane1QueueTaken.size()); if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends lane1QueueTaken.clear(); System.out.println("size " + lane1QueueTaken.size()); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(lane1Items.get(i).getStepX() == 0){ lane1Items.remove(i); i--; } } if(lane1Items.size() == 0){ lane1PurgeOn = false; //This is where the purge ends lane1QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ //Normal lane processing for(int i = 0;i<lane1Items.size();i++){ lane1Items.get(i).setX(lane1Items.get(i).getX() + lane1Items.get(i).getVX()); lane1Items.get(i).setY(lane1Items.get(i).getY() + lane1Items.get(i).getVY()); //MOVES ITEMS DOWN LANE //Lane items move vertically if(lane1Items.get(i).getVY() == vY || lane1Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setX(lane1Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setX(lane1Items.get(i).getX() - vibrationAmplitude); } lane1Items.get(i).setStepY(lane1Items.get(i).getStepY() - 1); if(lane1Items.get(i).getStepY() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2).getSize() < 9){ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepY() > 0){ lane1Items.get(j).setVY(-8); } else if(lane1Items.get(j).getStepX() > 0){ lane1Items.get(j).setVX(vX); } } if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ for(int j = 0; j <lane1Items.size();j++){ if(lane1Items.get(j).getStepX() < lane1QueueTaken.size() + 1){ lane1Items.get(j).setVX(0); } } if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; continue; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane1Items.get(i).getVX() == vX){ lane1Items.get(i).setStepX(lane1Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } if(graphicPanel.getNest().get(laneManagerID * 2).getSize() >= 9){ if(lane1Items.get(i).getStepX() == lane1QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane1QueueTaken.size() > 17){ // To be changed according to size of lane lane1Items.remove(i); i--; } else{ lane1Items.get(i).setVX(0); lane1QueueTaken.add(new Boolean(true)); } } } else if(lane1Items.get(i).getStepX() == 0){ lane1Items.get(i).setVY(0); lane1Items.get(i).setVX(0); stabilizationCount[0] = 0; lane1Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2).getSize() / 3)); boolean testDiverge = lane1Items.get(i).getDivergeUp(); lane1Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane1Items.get(i)); if(lane1QueueTaken.size() > 0) lane1QueueTaken.remove(0); lane1Items.remove(i); i--; } } else{ if(lane1Items.get(i).getVY() == 0){ //In the queue if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane1Items.get(i).setY(lane1Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane1Items.get(i).setY(lane1Items.get(i).getY() - vibrationAmplitude); } } } } } // END OF LANE 1 if(lane2PurgeOn){ //If purge is on, empties the nest and destroys items on lane graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends lane2QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } else{ for(int i = 0;i<lane2Items.size();i++){ lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } } if(lane2Items.size() == 0){ lane2PurgeOn = false; //This is where the purge ends lane2QueueTaken.clear(); graphicPanel.purgeTopLaneDone(laneManagerID); } } } } // end of purge statements else{ for(int i = 0;i<lane2Items.size();i++){ //Do the same for lane 2 lane2Items.get(i).setX(lane2Items.get(i).getX() + lane2Items.get(i).getVX()); lane2Items.get(i).setY(lane2Items.get(i).getY() + lane2Items.get(i).getVY()); //Lane items move vertically if(lane2Items.get(i).getVY() == vY || lane2Items.get(i).getVY() == -(vY) ){ if(vibrationCount % 4 == 1){ //Vibration left and right every 2 paint calls if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setX(lane2Items.get(i).getX() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setX(lane2Items.get(i).getX() - vibrationAmplitude); } lane2Items.get(i).setStepY(lane2Items.get(i).getStepY() - 1); if(lane2Items.get(i).getStepY() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(vX); } } //Queue entering Nests if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() < 9){ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepY() > 0){ lane2Items.get(j).setVY(8); } else if(lane2Items.get(j).getStepX() > 0){ lane2Items.get(j).setVX(vX); } } if(lane2Items.get(i).getStepX() == 0){ lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ for(int j = 0; j <lane2Items.size();j++){ if(lane2Items.get(j).getStepX() < lane2QueueTaken.size() + 1){ lane2Items.get(j).setVX(0); } } if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //IT IS THIS LINE TO FIX //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ // To be changed according to size of lane lane2Items.remove(i); i--; continue; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } continue; } } // End of Queue entering nest //Lane items move horizontally if(lane2Items.get(i).getVX() == vX){ if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } lane2Items.get(i).setStepX(lane2Items.get(i).getStepX() - 1); if(lane2PurgeOn){ graphicPanel.getNest().get(laneManagerID * 2 + 1).clearItems(); for(int j = 0; j <lane2Items.size();j++){ lane2Items.get(j).setVX(vX); } if(lane2Items.get(i).getStepX() == 0){ lane2Items.remove(i); i--; } if(lane2Items.size() == 0) lane2PurgeOn = false; } else if(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() >= 9){ if(lane2Items.get(i).getStepX() == lane2QueueTaken.size() + 1){ //Queue is full, delete crashing Items if(lane2QueueTaken.size() > 17){ lane2Items.remove(i); i--; } else{ lane2Items.get(i).setVX(0); lane2QueueTaken.add(new Boolean(true)); } } } else if(lane2Items.get(i).getStepX() == 0){ // reaches Nest //remove from queue or lane item, add to nest lane2Items.get(i).setVY(0); lane2Items.get(i).setVX(0); stabilizationCount[1] = 0; lane2Items.get(i).setX(lane_xPos + 3 + 25 * (int)(graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() / 3)); boolean testDiverge = !lane2Items.get(i).getDivergeUp(); lane2Items.get(i).setY(lane_yPos + 3 + 25 * (graphicPanel.getNest().get(laneManagerID * 2 + 1).getSize() % 3) + 80 * ((testDiverge)?0:1)); graphicPanel.getNest().get(laneManagerID * 2 + 1).addItem(lane2Items.get(i)); if(lane2QueueTaken.size() > 0) lane2QueueTaken.remove(0); lane2Items.remove(i); i--; } } else{ if(lane2Items.get(i).getVY() == 0){ // lane 2 queue stopped moving. needs to vibrate if(vibrationCount % 4 == 1){ //Vibration up and down every 2 paint calls if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); } else if(vibrationCount % 4 == 3){ if(i%2 == 0) lane2Items.get(i).setY(lane2Items.get(i).getY() + vibrationAmplitude); else if(i%2 == 1) lane2Items.get(i).setY(lane2Items.get(i).getY() - vibrationAmplitude); } } } } } }
diff --git a/src/info/yasskin/droidmuni/Compatibility.java b/src/info/yasskin/droidmuni/Compatibility.java index 01e17a7..0f58983 100644 --- a/src/info/yasskin/droidmuni/Compatibility.java +++ b/src/info/yasskin/droidmuni/Compatibility.java @@ -1,91 +1,91 @@ package info.yasskin.droidmuni; import java.lang.reflect.InvocationTargetException; import android.os.Build; import android.util.Log; public class Compatibility { public static void enableStrictMode() { if (Globals.DEVELOPER_MODE) { try { // StrictMode was added in Gingerbread, but I don't want to build // against the Gingerbread APIs, so I set it up with reflection, and // catch the exceptions on earlier platforms. Class<?> StrictMode = Class.forName("android.os.StrictMode"); Class<?> StrictModeThreadPolicy = Class.forName("android.os.StrictMode$ThreadPolicy"); Class<?> StrictModeThreadPolicyBuilder = Class.forName("android.os.StrictMode$ThreadPolicy$Builder"); Object thread_policy_builder = StrictModeThreadPolicyBuilder.newInstance(); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("detectAll").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyLog").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyDeath").invoke( thread_policy_builder); Object thread_policy = StrictModeThreadPolicyBuilder.getMethod("build").invoke( thread_policy_builder); StrictMode.getMethod("setThreadPolicy", StrictModeThreadPolicy).invoke( null, thread_policy); Class<?> StrictModeVmPolicy = Class.forName("android.os.StrictMode$VmPolicy"); Class<?> StrictModeVmPolicyBuilder = Class.forName("android.os.StrictMode$VmPolicy$Builder"); Object vm_policy_builder = StrictModeVmPolicyBuilder.newInstance(); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("detectAll").invoke( vm_policy_builder); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("penaltyLog").invoke( vm_policy_builder); - vm_policy_builder = - StrictModeVmPolicyBuilder.getMethod("penaltyDeath").invoke( - vm_policy_builder); +// vm_policy_builder = +// StrictModeVmPolicyBuilder.getMethod("penaltyDeath").invoke( +// vm_policy_builder); Object vm_policy = StrictModeVmPolicyBuilder.getMethod("build").invoke( vm_policy_builder); StrictMode.getMethod("setVmPolicy", StrictModeVmPolicy).invoke(null, vm_policy); } catch (ClassNotFoundException e) { strictModeNotAvailable(e); return; } catch (IllegalAccessException e) { strictModeNotAvailable(e); return; } catch (InstantiationException e) { strictModeNotAvailable(e); return; } catch (IllegalArgumentException e) { strictModeNotAvailable(e); return; } catch (SecurityException e) { strictModeNotAvailable(e); return; } catch (InvocationTargetException e) { strictModeNotAvailable(e); return; } catch (NoSuchMethodException e) { strictModeNotAvailable(e); return; } } } private static void strictModeNotAvailable(Exception e) { if (Build.VERSION.SDK_INT >= 9) { // Gingerbread added StrictMode support. throw new RuntimeException(e); } Log.d("DroidMuni", "Strict mode not available on this platform."); } }
true
true
public static void enableStrictMode() { if (Globals.DEVELOPER_MODE) { try { // StrictMode was added in Gingerbread, but I don't want to build // against the Gingerbread APIs, so I set it up with reflection, and // catch the exceptions on earlier platforms. Class<?> StrictMode = Class.forName("android.os.StrictMode"); Class<?> StrictModeThreadPolicy = Class.forName("android.os.StrictMode$ThreadPolicy"); Class<?> StrictModeThreadPolicyBuilder = Class.forName("android.os.StrictMode$ThreadPolicy$Builder"); Object thread_policy_builder = StrictModeThreadPolicyBuilder.newInstance(); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("detectAll").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyLog").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyDeath").invoke( thread_policy_builder); Object thread_policy = StrictModeThreadPolicyBuilder.getMethod("build").invoke( thread_policy_builder); StrictMode.getMethod("setThreadPolicy", StrictModeThreadPolicy).invoke( null, thread_policy); Class<?> StrictModeVmPolicy = Class.forName("android.os.StrictMode$VmPolicy"); Class<?> StrictModeVmPolicyBuilder = Class.forName("android.os.StrictMode$VmPolicy$Builder"); Object vm_policy_builder = StrictModeVmPolicyBuilder.newInstance(); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("detectAll").invoke( vm_policy_builder); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("penaltyLog").invoke( vm_policy_builder); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("penaltyDeath").invoke( vm_policy_builder); Object vm_policy = StrictModeVmPolicyBuilder.getMethod("build").invoke( vm_policy_builder); StrictMode.getMethod("setVmPolicy", StrictModeVmPolicy).invoke(null, vm_policy); } catch (ClassNotFoundException e) { strictModeNotAvailable(e); return; } catch (IllegalAccessException e) { strictModeNotAvailable(e); return; } catch (InstantiationException e) { strictModeNotAvailable(e); return; } catch (IllegalArgumentException e) { strictModeNotAvailable(e); return; } catch (SecurityException e) { strictModeNotAvailable(e); return; } catch (InvocationTargetException e) { strictModeNotAvailable(e); return; } catch (NoSuchMethodException e) { strictModeNotAvailable(e); return; } } }
public static void enableStrictMode() { if (Globals.DEVELOPER_MODE) { try { // StrictMode was added in Gingerbread, but I don't want to build // against the Gingerbread APIs, so I set it up with reflection, and // catch the exceptions on earlier platforms. Class<?> StrictMode = Class.forName("android.os.StrictMode"); Class<?> StrictModeThreadPolicy = Class.forName("android.os.StrictMode$ThreadPolicy"); Class<?> StrictModeThreadPolicyBuilder = Class.forName("android.os.StrictMode$ThreadPolicy$Builder"); Object thread_policy_builder = StrictModeThreadPolicyBuilder.newInstance(); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("detectAll").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyLog").invoke( thread_policy_builder); thread_policy_builder = StrictModeThreadPolicyBuilder.getMethod("penaltyDeath").invoke( thread_policy_builder); Object thread_policy = StrictModeThreadPolicyBuilder.getMethod("build").invoke( thread_policy_builder); StrictMode.getMethod("setThreadPolicy", StrictModeThreadPolicy).invoke( null, thread_policy); Class<?> StrictModeVmPolicy = Class.forName("android.os.StrictMode$VmPolicy"); Class<?> StrictModeVmPolicyBuilder = Class.forName("android.os.StrictMode$VmPolicy$Builder"); Object vm_policy_builder = StrictModeVmPolicyBuilder.newInstance(); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("detectAll").invoke( vm_policy_builder); vm_policy_builder = StrictModeVmPolicyBuilder.getMethod("penaltyLog").invoke( vm_policy_builder); // vm_policy_builder = // StrictModeVmPolicyBuilder.getMethod("penaltyDeath").invoke( // vm_policy_builder); Object vm_policy = StrictModeVmPolicyBuilder.getMethod("build").invoke( vm_policy_builder); StrictMode.getMethod("setVmPolicy", StrictModeVmPolicy).invoke(null, vm_policy); } catch (ClassNotFoundException e) { strictModeNotAvailable(e); return; } catch (IllegalAccessException e) { strictModeNotAvailable(e); return; } catch (InstantiationException e) { strictModeNotAvailable(e); return; } catch (IllegalArgumentException e) { strictModeNotAvailable(e); return; } catch (SecurityException e) { strictModeNotAvailable(e); return; } catch (InvocationTargetException e) { strictModeNotAvailable(e); return; } catch (NoSuchMethodException e) { strictModeNotAvailable(e); return; } } }
diff --git a/src/com/turt2live/antishare/worldedit/ASRegion.java b/src/com/turt2live/antishare/worldedit/ASRegion.java index d5e2706a..6bd9403a 100644 --- a/src/com/turt2live/antishare/worldedit/ASRegion.java +++ b/src/com/turt2live/antishare/worldedit/ASRegion.java @@ -1,182 +1,191 @@ package com.turt2live.antishare.worldedit; import java.io.File; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.feildmaster.lib.configuration.EnhancedConfiguration; import com.sk89q.worldedit.bukkit.selections.Selection; import com.turt2live.antishare.ASNotification; import com.turt2live.antishare.ASUtils; import com.turt2live.antishare.AntiShare; import com.turt2live.antishare.enums.NotificationType; import com.turt2live.antishare.storage.ASVirtualInventory; public class ASRegion { private AntiShare plugin; private World world; private String setBy; private GameMode gamemode; private Selection region; private String id; private String name; private boolean showEnterMessage = true; private boolean showExitMessage = true; private HashMap<Integer, ItemStack> inventory; public ASRegion(Selection region, String setBy, GameMode gamemode){ this.region = region; this.setBy = setBy; this.gamemode = gamemode; this.world = region.getWorld(); id = String.valueOf(System.currentTimeMillis()); plugin = (AntiShare) Bukkit.getServer().getPluginManager().getPlugin("AntiShare"); name = id; } public void setUniqueID(String ID){ id = ID; } public void setGameMode(GameMode gamemode){ this.gamemode = gamemode; } public void setName(String name){ this.name = name; } public void setMessageOptions(boolean showEnter, boolean showExit){ showEnterMessage = showEnter; showExitMessage = showExit; } public void setRegion(Selection selection){ region = selection; } public void setInventory(HashMap<Integer, ItemStack> inventory){ this.inventory = inventory; } // TODO: SQL Support public void saveToDisk(){ File saveFolder = new File(plugin.getDataFolder(), "regions"); saveFolder.mkdirs(); File regionFile = new File(saveFolder, id + ".yml"); if(!regionFile.exists()){ try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } }else{ regionFile.delete(); try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } } EnhancedConfiguration regionYAML = new EnhancedConfiguration(regionFile, plugin); regionYAML.load(); regionYAML.set("worldName", world.getName()); regionYAML.set("mi-x", region.getMinimumPoint().getX()); regionYAML.set("mi-y", region.getMinimumPoint().getY()); regionYAML.set("mi-z", region.getMinimumPoint().getZ()); regionYAML.set("ma-x", region.getMaximumPoint().getX()); regionYAML.set("ma-y", region.getMaximumPoint().getY()); regionYAML.set("ma-z", region.getMaximumPoint().getZ()); regionYAML.set("set-by", setBy); regionYAML.set("gamemode", gamemode.name()); regionYAML.set("name", name); regionYAML.set("showEnter", showEnterMessage); regionYAML.set("showExit", showExitMessage); regionYAML.save(); if(inventory != null){ File saveFile = new File(plugin.getDataFolder() + "/region_inventories", id + ".yml"); if(saveFile.exists()){ saveFile.delete(); try{ - saveFile.createNewFile(); + if(inventory.size() > 0){ + saveFile.createNewFile(); + } }catch(Exception e){ e.printStackTrace(); } } - ASVirtualInventory.saveInventoryToFile(saveFile, inventory, plugin); + if(inventory.size() > 0){ + ASVirtualInventory.saveInventoryToFile(saveFile, inventory, plugin); + } + }else{ + File saveFile = new File(plugin.getDataFolder() + "/region_inventories", id + ".yml"); + if(saveFile.exists()){ + saveFile.delete(); + } } } public boolean has(Location location){ return region.contains(location); } public String getName(){ return name; } public boolean isEnterMessageActive(){ return showEnterMessage; } public boolean isExitMessageActive(){ return showExitMessage; } public World getWorld(){ return world; } public String getWhoSet(){ return setBy; } public GameMode getGameModeSwitch(){ return gamemode; } public Selection getSelection(){ return region; } public String getUniqueID(){ return id; } public AntiShare getPlugin(){ return plugin; } public void alertEntry(Player player){ if(showEnterMessage){ ASUtils.sendToPlayer(player, ChatColor.GOLD + "You entered '" + name + "'"); ASNotification.sendNotification(NotificationType.REGION_ENTER, player, name); if(!player.hasPermission("AntiShare.roam") && this.inventory != null){ ASVirtualInventory inventory = plugin.storage.getInventoryManager(player, world); inventory.setTemporaryInventory(this.inventory); inventory.loadToTemporary(); } } } public void alertExit(Player player){ if(showExitMessage){ ASUtils.sendToPlayer(player, ChatColor.GOLD + "You left '" + name + "'"); ASNotification.sendNotification(NotificationType.REGION_EXIT, player, name); if(!player.hasPermission("AntiShare.roam")){ ASVirtualInventory inventory = plugin.storage.getInventoryManager(player, world); if(inventory.isTemp()){ inventory.unloadFromTemporary(); } } } } }
false
true
public void saveToDisk(){ File saveFolder = new File(plugin.getDataFolder(), "regions"); saveFolder.mkdirs(); File regionFile = new File(saveFolder, id + ".yml"); if(!regionFile.exists()){ try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } }else{ regionFile.delete(); try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } } EnhancedConfiguration regionYAML = new EnhancedConfiguration(regionFile, plugin); regionYAML.load(); regionYAML.set("worldName", world.getName()); regionYAML.set("mi-x", region.getMinimumPoint().getX()); regionYAML.set("mi-y", region.getMinimumPoint().getY()); regionYAML.set("mi-z", region.getMinimumPoint().getZ()); regionYAML.set("ma-x", region.getMaximumPoint().getX()); regionYAML.set("ma-y", region.getMaximumPoint().getY()); regionYAML.set("ma-z", region.getMaximumPoint().getZ()); regionYAML.set("set-by", setBy); regionYAML.set("gamemode", gamemode.name()); regionYAML.set("name", name); regionYAML.set("showEnter", showEnterMessage); regionYAML.set("showExit", showExitMessage); regionYAML.save(); if(inventory != null){ File saveFile = new File(plugin.getDataFolder() + "/region_inventories", id + ".yml"); if(saveFile.exists()){ saveFile.delete(); try{ saveFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } } ASVirtualInventory.saveInventoryToFile(saveFile, inventory, plugin); } }
public void saveToDisk(){ File saveFolder = new File(plugin.getDataFolder(), "regions"); saveFolder.mkdirs(); File regionFile = new File(saveFolder, id + ".yml"); if(!regionFile.exists()){ try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } }else{ regionFile.delete(); try{ regionFile.createNewFile(); }catch(Exception e){ e.printStackTrace(); } } EnhancedConfiguration regionYAML = new EnhancedConfiguration(regionFile, plugin); regionYAML.load(); regionYAML.set("worldName", world.getName()); regionYAML.set("mi-x", region.getMinimumPoint().getX()); regionYAML.set("mi-y", region.getMinimumPoint().getY()); regionYAML.set("mi-z", region.getMinimumPoint().getZ()); regionYAML.set("ma-x", region.getMaximumPoint().getX()); regionYAML.set("ma-y", region.getMaximumPoint().getY()); regionYAML.set("ma-z", region.getMaximumPoint().getZ()); regionYAML.set("set-by", setBy); regionYAML.set("gamemode", gamemode.name()); regionYAML.set("name", name); regionYAML.set("showEnter", showEnterMessage); regionYAML.set("showExit", showExitMessage); regionYAML.save(); if(inventory != null){ File saveFile = new File(plugin.getDataFolder() + "/region_inventories", id + ".yml"); if(saveFile.exists()){ saveFile.delete(); try{ if(inventory.size() > 0){ saveFile.createNewFile(); } }catch(Exception e){ e.printStackTrace(); } } if(inventory.size() > 0){ ASVirtualInventory.saveInventoryToFile(saveFile, inventory, plugin); } }else{ File saveFile = new File(plugin.getDataFolder() + "/region_inventories", id + ".yml"); if(saveFile.exists()){ saveFile.delete(); } } }
diff --git a/sonar-server/src/main/java/org/sonar/server/search/SearchIndex.java b/sonar-server/src/main/java/org/sonar/server/search/SearchIndex.java index 622c2048c6..9f2774fa7e 100644 --- a/sonar-server/src/main/java/org/sonar/server/search/SearchIndex.java +++ b/sonar-server/src/main/java/org/sonar/server/search/SearchIndex.java @@ -1,197 +1,198 @@ /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.search; import com.google.common.collect.Lists; import org.apache.commons.io.IOUtils; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.client.IndicesAdminClient; import org.elasticsearch.client.Requests; import org.elasticsearch.common.io.BytesStream; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.SearchHit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.TimeProfiler; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.concurrent.ExecutionException; import static java.lang.String.format; public class SearchIndex { private static final Logger LOG = LoggerFactory.getLogger(SearchIndex.class); private static final Settings INDEX_DEFAULT_SETTINGS = ImmutableSettings.builder() .put("number_of_shards", 1) .put("number_of_replicas", 0) .put("mapper.dynamic", false) .build(); private static final String INDEX_DEFAULT_MAPPING = "{ \"_default_\": { \"dynamic\": \"strict\" } }"; private SearchNode searchNode; private Client client; public SearchIndex(SearchNode searchNode) { this.searchNode = searchNode; } public void start() { this.client = searchNode.client(); } public void stop() { if(client != null) { client.close(); } } public void put(String index, String type, String id, BytesStream source) { internalPut(index, type, id, source, false); } public void putSynchronous(String index, String type, String id, BytesStream source) { internalPut(index, type, id, source, true); } private void internalPut(String index, String type, String id, BytesStream source, boolean refresh) { IndexRequestBuilder builder = client.prepareIndex(index, type, id).setSource(source.bytes()).setRefresh(refresh); TimeProfiler profiler = newDebugProfiler(); profiler.start(format("put document with id '%s' with type '%s' into index '%s'", id, type, index)); builder.execute().actionGet(); profiler.stop(); } public void bulkIndex(String index, String type, String[] ids, BytesStream[] sources) { BulkRequestBuilder builder = new BulkRequestBuilder(client); for (int i=0; i<ids.length; i++) { builder.add(client.prepareIndex(index, type, ids[i]).setSource(sources[i].bytes())); } TimeProfiler profiler = newDebugProfiler(); try { profiler.start(format("bulk index of %d documents with type '%s' into index '%s'", ids.length, type, index)); BulkResponse bulkResponse = client.bulk(builder.setRefresh(true).request()).get(); if (bulkResponse.hasFailures()) { // Retry once per failed doc -- ugly for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) { if(bulkItemResponse.isFailed()) { int itemId = bulkItemResponse.getItemId(); put(index, type, ids[itemId], sources[itemId]); } } } } catch (InterruptedException e) { LOG.error("Interrupted during bulk operation", e); } catch (ExecutionException e) { LOG.error("Execution of bulk operation failed", e); } finally { profiler.stop(); } } public void addMappingFromClasspath(String index, String type, String resourcePath) { try { URL resource = getClass().getResource(resourcePath); if (resource == null) { throw new IllegalArgumentException("Could not load unexisting file at " + resourcePath); } addMapping(index, type, IOUtils.toString(resource)); } catch(IOException ioException) { throw new IllegalArgumentException("Problem loading file at " + resourcePath, ioException); } } private void addMapping(String index, String type, String mapping) { IndicesAdminClient indices = client.admin().indices(); TimeProfiler profiler = newDebugProfiler(); try { if (! indices.exists(new IndicesExistsRequest(index)).get().isExists()) { profiler.start(format("create index '%s'", index)); indices.prepareCreate(index) .setSettings(INDEX_DEFAULT_SETTINGS) .addMapping("_default_", INDEX_DEFAULT_MAPPING) .execute().actionGet(); } } catch (Exception e) { LOG.error("While checking for index existence", e); } finally { profiler.stop(); } profiler.start(format("put mapping on index '%s' for type '%s'", index, type)); try { indices.putMapping(Requests.putMappingRequest(index).type(type).source(mapping)).actionGet(); } catch(ElasticSearchParseException parseException) { throw new IllegalArgumentException("Invalid mapping file", parseException); } finally { profiler.stop(); } } public List<String> findDocumentIds(SearchQuery searchQuery) { List<String> result = Lists.newArrayList(); final int scrollTime = 100; + final String methodName = "findDocumentIds"; SearchRequestBuilder builder = searchQuery.toBuilder(client); - LOG.debug("findDocumentIds" + builder.internalBuilder().toString()); + LOG.debug(methodName + builder.internalBuilder().toString()); TimeProfiler profiler = newDebugProfiler(); - profiler.start("findDocumentIds"); + profiler.start(methodName); SearchResponse scrollResp = builder.addField("_id") .setSearchType(SearchType.SCAN) .setScroll(new TimeValue(scrollTime)) .setSize(searchQuery.scrollSize()).execute().actionGet(); //Scroll until no hits are returned while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(scrollTime)).execute().actionGet(); for (SearchHit hit : scrollResp.getHits()) { result.add(hit.getId()); } //Break condition: No hits are returned if (scrollResp.getHits().getHits().length == 0) { break; } } profiler.stop(); return result; } private TimeProfiler newDebugProfiler() { TimeProfiler profiler = new TimeProfiler(); profiler.setLogger(LOG); return profiler; } }
false
true
public List<String> findDocumentIds(SearchQuery searchQuery) { List<String> result = Lists.newArrayList(); final int scrollTime = 100; SearchRequestBuilder builder = searchQuery.toBuilder(client); LOG.debug("findDocumentIds" + builder.internalBuilder().toString()); TimeProfiler profiler = newDebugProfiler(); profiler.start("findDocumentIds"); SearchResponse scrollResp = builder.addField("_id") .setSearchType(SearchType.SCAN) .setScroll(new TimeValue(scrollTime)) .setSize(searchQuery.scrollSize()).execute().actionGet(); //Scroll until no hits are returned while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(scrollTime)).execute().actionGet(); for (SearchHit hit : scrollResp.getHits()) { result.add(hit.getId()); } //Break condition: No hits are returned if (scrollResp.getHits().getHits().length == 0) { break; } } profiler.stop(); return result; }
public List<String> findDocumentIds(SearchQuery searchQuery) { List<String> result = Lists.newArrayList(); final int scrollTime = 100; final String methodName = "findDocumentIds"; SearchRequestBuilder builder = searchQuery.toBuilder(client); LOG.debug(methodName + builder.internalBuilder().toString()); TimeProfiler profiler = newDebugProfiler(); profiler.start(methodName); SearchResponse scrollResp = builder.addField("_id") .setSearchType(SearchType.SCAN) .setScroll(new TimeValue(scrollTime)) .setSize(searchQuery.scrollSize()).execute().actionGet(); //Scroll until no hits are returned while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(scrollTime)).execute().actionGet(); for (SearchHit hit : scrollResp.getHits()) { result.add(hit.getId()); } //Break condition: No hits are returned if (scrollResp.getHits().getHits().length == 0) { break; } } profiler.stop(); return result; }
diff --git a/src/classifier/ResourceTypeClassify.java b/src/classifier/ResourceTypeClassify.java index 54577fe..ba11a19 100644 --- a/src/classifier/ResourceTypeClassify.java +++ b/src/classifier/ResourceTypeClassify.java @@ -1,74 +1,74 @@ import java.io.*; import java.util.*; import cc.mallet.classify.*; import cc.mallet.pipe.iterator.*; import cc.mallet.types.*; public class ResourceTypeClassify { // Test stage of resource type classifier, uses saved mallet classifier public static void main(String[] args) throws IllegalArgumentException, FileNotFoundException, IOException, ClassNotFoundException{ if(args.length!=3){ throw new IllegalArgumentException("Usage: java ResourceTypeClassify classifier.mallet input-vectors output-file"); }else{ System.out.println("Loading classifier..."); Classifier classifier = loadClassifier(new File(args[0])); System.out.println("Printing class labels..."); printLabelings(classifier, new File(args[1]), args[2]); } } // Loads mallet classifier from serialized file public static Classifier loadClassifier(File serializedFile) throws FileNotFoundException, IOException, ClassNotFoundException, IllegalArgumentException { Classifier classifier; try{ ObjectInputStream ois = new ObjectInputStream (new FileInputStream (serializedFile)); classifier = (Classifier) ois.readObject(); ois.close(); return classifier; }catch (Exception e){ e.printStackTrace(); throw new IllegalArgumentException("Couldn't read classifier "+serializedFile.getName()); } } // classifies documents from "vectorfile", which is in plaintext format, and prints classifier output to file public static void printLabelings(Classifier classifier, File vectorfile, String outputFilename) throws IOException { //format of data in vectorfile is: [name]\t[label]\t[data] CsvIterator reader = new CsvIterator(new FileReader(vectorfile), - "(.+)\\t(.+)\\t(.*)", + "(.+)\\t(.*)\\t(.*)", 3, 2, 1); Iterator<Instance> instances = classifier.getInstancePipe().newIteratorFrom(reader); CsvIterator reader2 = // We need a second reader here because Iterator<Instance> ignores class labels that do not exist in the classifier. new CsvIterator(new FileReader(vectorfile), - "(.+)\\t(.+)\\t(.*)", + "(.+)\\t(.*)\\t(.*)", 3, 2, 1); PrintStream output = new PrintStream(new FileOutputStream(outputFilename)); while (instances.hasNext()) { Instance reader2Instance = reader2.next(); Instance instance = (Instance) instances.next(); Labeling labeling = classifier.classify(instance).getLabeling(); // print the labels with their weights in descending order (ie best first) // System.out.println(instance.getLabeling()+ " " + instance.getSource()); output.print(instance.getName() + "\t"); Object trueLabel = reader2Instance.getTarget(); if(trueLabel!=null) output.print(trueLabel.toString() + "\t"); for (int rank = 0; rank < labeling.numLocations(); rank++){ output.print(labeling.getLabelAtRank(rank) + ":" + labeling.getValueAtRank(rank) + " "); } output.println(); } } }
false
true
public static void printLabelings(Classifier classifier, File vectorfile, String outputFilename) throws IOException { //format of data in vectorfile is: [name]\t[label]\t[data] CsvIterator reader = new CsvIterator(new FileReader(vectorfile), "(.+)\\t(.+)\\t(.*)", 3, 2, 1); Iterator<Instance> instances = classifier.getInstancePipe().newIteratorFrom(reader); CsvIterator reader2 = // We need a second reader here because Iterator<Instance> ignores class labels that do not exist in the classifier. new CsvIterator(new FileReader(vectorfile), "(.+)\\t(.+)\\t(.*)", 3, 2, 1); PrintStream output = new PrintStream(new FileOutputStream(outputFilename)); while (instances.hasNext()) { Instance reader2Instance = reader2.next(); Instance instance = (Instance) instances.next(); Labeling labeling = classifier.classify(instance).getLabeling(); // print the labels with their weights in descending order (ie best first) // System.out.println(instance.getLabeling()+ " " + instance.getSource()); output.print(instance.getName() + "\t"); Object trueLabel = reader2Instance.getTarget(); if(trueLabel!=null) output.print(trueLabel.toString() + "\t"); for (int rank = 0; rank < labeling.numLocations(); rank++){ output.print(labeling.getLabelAtRank(rank) + ":" + labeling.getValueAtRank(rank) + " "); } output.println(); } }
public static void printLabelings(Classifier classifier, File vectorfile, String outputFilename) throws IOException { //format of data in vectorfile is: [name]\t[label]\t[data] CsvIterator reader = new CsvIterator(new FileReader(vectorfile), "(.+)\\t(.*)\\t(.*)", 3, 2, 1); Iterator<Instance> instances = classifier.getInstancePipe().newIteratorFrom(reader); CsvIterator reader2 = // We need a second reader here because Iterator<Instance> ignores class labels that do not exist in the classifier. new CsvIterator(new FileReader(vectorfile), "(.+)\\t(.*)\\t(.*)", 3, 2, 1); PrintStream output = new PrintStream(new FileOutputStream(outputFilename)); while (instances.hasNext()) { Instance reader2Instance = reader2.next(); Instance instance = (Instance) instances.next(); Labeling labeling = classifier.classify(instance).getLabeling(); // print the labels with their weights in descending order (ie best first) // System.out.println(instance.getLabeling()+ " " + instance.getSource()); output.print(instance.getName() + "\t"); Object trueLabel = reader2Instance.getTarget(); if(trueLabel!=null) output.print(trueLabel.toString() + "\t"); for (int rank = 0; rank < labeling.numLocations(); rank++){ output.print(labeling.getLabelAtRank(rank) + ":" + labeling.getValueAtRank(rank) + " "); } output.println(); } }
diff --git a/trunk/org/xbill/DNS/NameSet.java b/trunk/org/xbill/DNS/NameSet.java index b61cce4..4ff7f1e 100644 --- a/trunk/org/xbill/DNS/NameSet.java +++ b/trunk/org/xbill/DNS/NameSet.java @@ -1,221 +1,219 @@ // Copyright (c) 1999-2001 Brian Wellington ([email protected]) package org.xbill.DNS; import java.util.*; import org.xbill.DNS.utils.*; /** * The shared superclass of Zone and Cache. All names are stored in a * map. Each name contains a map indexed by type. * * @author Brian Wellington */ class NameSet { private Map data; private Name origin; private boolean isCache; /** Creates an empty NameSet for use as a Zone or Cache. The origin is set * to the root. */ protected NameSet(boolean isCache) { data = new HashMap(); origin = Name.root; this.isCache = isCache; } /** Sets the origin of the NameSet */ protected void setOrigin(Name origin) { this.origin = origin; } /** Deletes all sets in a NameSet */ protected void clear() { data = new HashMap(); } /** * Finds all matching sets or something that causes the lookup to stop. */ protected Object findSets(Name name, short type) { Object bestns = null; Object o; Name tname; int labels; int olabels; int tlabels; if (!name.subdomain(origin)) return null; labels = name.labels(); olabels = origin.labels(); for (tlabels = olabels; tlabels <= labels; tlabels++) { if (tlabels == olabels) tname = origin; else if (tlabels == labels) tname = name; else tname = new Name(name, labels - tlabels); TypeMap nameInfo = findName(tname); if (nameInfo == null) continue; /* If this is an ANY lookup, return everything. */ if (tlabels == labels && type == Type.ANY) return nameInfo.getAll(); /* Look for an NS */ if (tlabels > olabels || isCache) { o = nameInfo.get(Type.NS); if (o != null) { if (isCache) bestns = o; else return o; } } /* If this is the name, look for the actual type. */ if (tlabels == labels) { o = nameInfo.get(type); if (o != null) return o; } - /* Look for a CNAME */ - o = nameInfo.get(Type.CNAME); - if (o != null) { - if (labels == tlabels) + /* If this is the name, look for a CNAME */ + if (tlabels == labels) { + o = nameInfo.get(Type.CNAME); + if (o != null) return o; - else - return null; } /* Look for a DNAME, unless this is the actual name */ if (tlabels < labels) { o = nameInfo.get(Type.DNAME); if (o != null) return o; } /* * If this is the name and this is a cache, look for an * NXDOMAIN entry. */ if (tlabels == labels && isCache) { o = nameInfo.get((short)0); if (o != null) return o; } /* * If this is the name and we haven't matched anything, * just return the name. */ if (tlabels == labels) return nameInfo; } if (bestns == null) return null; else return bestns; } /** * Finds all sets that exactly match. This does not traverse CNAMEs or handle * Type ANY queries. */ protected Object findExactSet(Name name, short type) { TypeMap nameInfo = findName(name); if (nameInfo == null) return null; return nameInfo.get(type); } /** * Finds all records for a given name, if the name exists. */ protected TypeMap findName(Name name) { return (TypeMap) data.get(name); } /** * Adds a set associated with a name/type. The data contained in the * set is abstract. */ protected void addSet(Name name, short type, Object set) { TypeMap nameInfo = findName(name); if (nameInfo == null) data.put(name, nameInfo = new TypeMap()); synchronized (nameInfo) { nameInfo.put(type, set); } } /** * Removes the given set with the name and type. The data contained in the * set is abstract. */ protected void removeSet(Name name, short type, Object set) { TypeMap nameInfo = findName(name); if (nameInfo == null) return; Object o = nameInfo.get(type); if (o != set && type != Type.CNAME) { type = Type.CNAME; o = nameInfo.get(type); } if (o == set) { synchronized (nameInfo) { nameInfo.remove(type); } if (nameInfo.isEmpty()) data.remove(name); } } /** * Removes all data associated with the given name. */ protected void removeName(Name name) { data.remove(name); } /** * Returns a list of all names stored in this NameSet. */ Iterator names() { return data.keySet().iterator(); } /** Converts the NameSet to a String */ public String toString() { StringBuffer sb = new StringBuffer(); Iterator it = data.values().iterator(); while (it.hasNext()) { TypeMap nameInfo = (TypeMap) it.next(); Object [] elements = nameInfo.getAll(); if (elements == null) continue; for (int i = 0; i < elements.length; i++) sb.append(elements[i]); } return sb.toString(); } }
false
true
protected Object findSets(Name name, short type) { Object bestns = null; Object o; Name tname; int labels; int olabels; int tlabels; if (!name.subdomain(origin)) return null; labels = name.labels(); olabels = origin.labels(); for (tlabels = olabels; tlabels <= labels; tlabels++) { if (tlabels == olabels) tname = origin; else if (tlabels == labels) tname = name; else tname = new Name(name, labels - tlabels); TypeMap nameInfo = findName(tname); if (nameInfo == null) continue; /* If this is an ANY lookup, return everything. */ if (tlabels == labels && type == Type.ANY) return nameInfo.getAll(); /* Look for an NS */ if (tlabels > olabels || isCache) { o = nameInfo.get(Type.NS); if (o != null) { if (isCache) bestns = o; else return o; } } /* If this is the name, look for the actual type. */ if (tlabels == labels) { o = nameInfo.get(type); if (o != null) return o; } /* Look for a CNAME */ o = nameInfo.get(Type.CNAME); if (o != null) { if (labels == tlabels) return o; else return null; } /* Look for a DNAME, unless this is the actual name */ if (tlabels < labels) { o = nameInfo.get(Type.DNAME); if (o != null) return o; } /* * If this is the name and this is a cache, look for an * NXDOMAIN entry. */ if (tlabels == labels && isCache) { o = nameInfo.get((short)0); if (o != null) return o; } /* * If this is the name and we haven't matched anything, * just return the name. */ if (tlabels == labels) return nameInfo; } if (bestns == null) return null; else return bestns; }
protected Object findSets(Name name, short type) { Object bestns = null; Object o; Name tname; int labels; int olabels; int tlabels; if (!name.subdomain(origin)) return null; labels = name.labels(); olabels = origin.labels(); for (tlabels = olabels; tlabels <= labels; tlabels++) { if (tlabels == olabels) tname = origin; else if (tlabels == labels) tname = name; else tname = new Name(name, labels - tlabels); TypeMap nameInfo = findName(tname); if (nameInfo == null) continue; /* If this is an ANY lookup, return everything. */ if (tlabels == labels && type == Type.ANY) return nameInfo.getAll(); /* Look for an NS */ if (tlabels > olabels || isCache) { o = nameInfo.get(Type.NS); if (o != null) { if (isCache) bestns = o; else return o; } } /* If this is the name, look for the actual type. */ if (tlabels == labels) { o = nameInfo.get(type); if (o != null) return o; } /* If this is the name, look for a CNAME */ if (tlabels == labels) { o = nameInfo.get(Type.CNAME); if (o != null) return o; } /* Look for a DNAME, unless this is the actual name */ if (tlabels < labels) { o = nameInfo.get(Type.DNAME); if (o != null) return o; } /* * If this is the name and this is a cache, look for an * NXDOMAIN entry. */ if (tlabels == labels && isCache) { o = nameInfo.get((short)0); if (o != null) return o; } /* * If this is the name and we haven't matched anything, * just return the name. */ if (tlabels == labels) return nameInfo; } if (bestns == null) return null; else return bestns; }
diff --git a/plugins/org.eclipse.gmf.validate/src/org/eclipse/gmf/internal/validate/ocl/OCLExpressionAdapter.java b/plugins/org.eclipse.gmf.validate/src/org/eclipse/gmf/internal/validate/ocl/OCLExpressionAdapter.java index 1d329bd82..876e6dced 100644 --- a/plugins/org.eclipse.gmf.validate/src/org/eclipse/gmf/internal/validate/ocl/OCLExpressionAdapter.java +++ b/plugins/org.eclipse.gmf.validate/src/org/eclipse/gmf/internal/validate/ocl/OCLExpressionAdapter.java @@ -1,231 +1,237 @@ /* * Copyright (c) 2005, 2007 Borland Software Corporation * * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Radek Dvorak (Borland) - initial API and implementation */ package org.eclipse.gmf.internal.validate.ocl; import java.text.MessageFormat; import java.util.HashSet; import org.eclipse.core.runtime.IStatus; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EOperation; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EParameter; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.ETypedElement; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.impl.EPackageRegistryImpl; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.gmf.internal.validate.DebugOptions; import org.eclipse.gmf.internal.validate.DefUtils; import org.eclipse.gmf.internal.validate.EDataTypeConversion; import org.eclipse.gmf.internal.validate.GMFValidationPlugin; import org.eclipse.gmf.internal.validate.Messages; import org.eclipse.gmf.internal.validate.StatusCodes; import org.eclipse.gmf.internal.validate.Trace; import org.eclipse.gmf.internal.validate.expressions.AbstractExpression; import org.eclipse.gmf.internal.validate.expressions.IEvaluationEnvironment; import org.eclipse.gmf.internal.validate.expressions.IParseEnvironment; import org.eclipse.ocl.Environment; import org.eclipse.ocl.ParserException; import org.eclipse.ocl.Query; import org.eclipse.ocl.ecore.CallOperationAction; import org.eclipse.ocl.ecore.CollectionType; import org.eclipse.ocl.ecore.Constraint; import org.eclipse.ocl.ecore.EcoreEnvironmentFactory; import org.eclipse.ocl.ecore.SendSignalAction; import org.eclipse.ocl.ecore.TypeType; import org.eclipse.ocl.expressions.ExpressionsFactory; import org.eclipse.ocl.expressions.Variable; class OCLExpressionAdapter extends AbstractExpression { /** * The OCL language identifier. */ public static final String OCL = "ocl"; //$NON-NLS-1$ private Query<EClassifier, EClass, EObject> query; private Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> env; public OCLExpressionAdapter(String body, EClassifier context, IParseEnvironment extEnv) { super(body, context, extEnv); try { org.eclipse.ocl.ecore.OCL ocl = null; if(extEnv != null) { EcoreEnvironmentFactory factory = EcoreEnvironmentFactory.INSTANCE; if(extEnv.getImportRegistry() != null) { factory = new EcoreEnvironmentFactory(extEnv.getImportRegistry()); } ocl = org.eclipse.ocl.ecore.OCL.newInstance(factory); this.env = ocl.getEnvironment(); for(String varName : extEnv.getVariableNames()) { EClassifier type = extEnv.getTypeOf(varName); Variable<EClassifier, EParameter> varDecl = ExpressionsFactory.eINSTANCE.createVariable(); varDecl.setName(varName); varDecl.setType(type); env.addElement(varDecl.getName(), varDecl, true); } } else { - EPackage.Registry registry = new EPackageRegistryImpl(EPackage.Registry.INSTANCE); - ResourceSet resourceSet = context.eResource().getResourceSet(); - if (resourceSet != null) { + EPackage.Registry registry = new EPackageRegistryImpl(); + for (Object nextRegistryObject : EPackage.Registry.INSTANCE.values()) { + if (nextRegistryObject instanceof EPackage) { + EPackage ePackage = (EPackage) nextRegistryObject; + registry.put(ePackage.getNsURI(), ePackage); + } + } + if (context.eResource() != null && context.eResource().getResourceSet() != null) { + ResourceSet resourceSet = context.eResource().getResourceSet(); EcoreUtil.resolveAll(resourceSet); HashSet<EPackage> ePackages = new HashSet<EPackage>(); for (Resource resource : resourceSet.getResources()) { ePackages.addAll(EcoreUtil.<EPackage> getObjectsByType(resource.getContents(), EcorePackage.Literals.EPACKAGE)); } for (EPackage ePackage : ePackages) { registry.put(ePackage.getNsURI(), ePackage); } } ocl = org.eclipse.ocl.ecore.OCL.newInstance(new EcoreEnvironmentFactory(registry)); this.env = ocl.getEnvironment(); } org.eclipse.ocl.ecore.OCL.Helper helper = ocl.createOCLHelper(); helper.setContext(context); this.query = ocl.createQuery(helper.createQuery(body)); } catch (ParserException e) { setInvalidOclExprStatus(e); } catch (IllegalArgumentException e) { setInvalidOclExprStatus(e); } catch(RuntimeException e) { setStatus(GMFValidationPlugin.createStatus( IStatus.ERROR, StatusCodes.UNEXPECTED_PARSE_ERROR, Messages.unexpectedExprParseError, e)); GMFValidationPlugin.log(getStatus()); Trace.catching(DebugOptions.EXCEPTIONS_CATCHING, e); } } public String getLanguage() { return OCL; } public boolean isLooselyTyped() { return false; } public boolean isAssignableTo(EClassifier ecoreType) { if(env == null) { return false; } EClassifier oclType = env.getUMLReflection().getOCLType(ecoreType); if(oclType == null) { return false; } return isOclConformantTo(oclType); } public boolean isAssignableToElement(ETypedElement typedElement) { if(env == null || typedElement.getEType() == null) { return false; } EClassifier oclType = env.getUMLReflection().getOCLType(typedElement); if(oclType == null) { return false; } return isOclConformantTo(oclType); } public EClassifier getResultType() { return (query != null) ? query.getExpression().getType() : super.getResultType(); } protected Object doEvaluate(Object context) { return filterOCLInvalid((query != null) ? query.evaluate(context) : null); } protected Object doEvaluate(Object context, IEvaluationEnvironment extEnvironment) { if(query != null) { query.getEvaluationEnvironment().clear(); for (String varName : extEnvironment.getVariableNames()) { query.getEvaluationEnvironment().add(varName, extEnvironment.getValueOf(varName)); } } return doEvaluate(context); } private Object filterOCLInvalid(Object object) { return (env != null && object == env.getOCLStandardLibrary().getOclInvalid()) ? null : object; } private boolean isOclConformantTo(EClassifier anotherOclType) { EClassifier thisOclType = getResultType(); boolean isTargetCollection = anotherOclType instanceof CollectionType; if(isTargetCollection) { CollectionType oclCollectionType = (CollectionType)anotherOclType; if(oclCollectionType.getElementType() != null) { anotherOclType = oclCollectionType.getElementType(); } } if(thisOclType instanceof CollectionType) { if(!isTargetCollection) { return false; // can't assign CollectionType to scalar } CollectionType thisOclCollectionType = (CollectionType)thisOclType; if(thisOclCollectionType.getElementType() != null) { thisOclType = thisOclCollectionType.getElementType(); } } // handle OCL TypeType if(thisOclType instanceof TypeType) { EClassifier thisRefferedClassifier = ((TypeType)thisOclType).getReferredType(); if(thisRefferedClassifier != null) { return DefUtils.getCanonicalEClassifier(anotherOclType).isInstance(thisRefferedClassifier); } } // Note: in OCL, Double extends Integer if ((thisOclType.getInstanceClass() == Integer.class || thisOclType.getInstanceClass() == int.class) && (anotherOclType.getInstanceClass() == Double.class || anotherOclType.getInstanceClass() == double.class)) { return true; } if(thisOclType instanceof EDataType && anotherOclType instanceof EDataType) { if(new EDataTypeConversion().isConvertable((EDataType)anotherOclType, (EDataType)thisOclType)) { return true; } } return DefUtils.checkTypeAssignmentCompatibility(anotherOclType, thisOclType); } void setInvalidOclExprStatus(Exception exception) { String message = MessageFormat.format( Messages.invalidExpressionBody, new Object[] { getBody(), exception.getLocalizedMessage() }); setStatus(GMFValidationPlugin.createStatus( IStatus.ERROR, StatusCodes.INVALID_VALUE_EXPRESSION, message, exception)); Trace.catching(DebugOptions.EXCEPTIONS_CATCHING, exception); } }
true
true
public OCLExpressionAdapter(String body, EClassifier context, IParseEnvironment extEnv) { super(body, context, extEnv); try { org.eclipse.ocl.ecore.OCL ocl = null; if(extEnv != null) { EcoreEnvironmentFactory factory = EcoreEnvironmentFactory.INSTANCE; if(extEnv.getImportRegistry() != null) { factory = new EcoreEnvironmentFactory(extEnv.getImportRegistry()); } ocl = org.eclipse.ocl.ecore.OCL.newInstance(factory); this.env = ocl.getEnvironment(); for(String varName : extEnv.getVariableNames()) { EClassifier type = extEnv.getTypeOf(varName); Variable<EClassifier, EParameter> varDecl = ExpressionsFactory.eINSTANCE.createVariable(); varDecl.setName(varName); varDecl.setType(type); env.addElement(varDecl.getName(), varDecl, true); } } else { EPackage.Registry registry = new EPackageRegistryImpl(EPackage.Registry.INSTANCE); ResourceSet resourceSet = context.eResource().getResourceSet(); if (resourceSet != null) { EcoreUtil.resolveAll(resourceSet); HashSet<EPackage> ePackages = new HashSet<EPackage>(); for (Resource resource : resourceSet.getResources()) { ePackages.addAll(EcoreUtil.<EPackage> getObjectsByType(resource.getContents(), EcorePackage.Literals.EPACKAGE)); } for (EPackage ePackage : ePackages) { registry.put(ePackage.getNsURI(), ePackage); } } ocl = org.eclipse.ocl.ecore.OCL.newInstance(new EcoreEnvironmentFactory(registry)); this.env = ocl.getEnvironment(); } org.eclipse.ocl.ecore.OCL.Helper helper = ocl.createOCLHelper(); helper.setContext(context); this.query = ocl.createQuery(helper.createQuery(body)); } catch (ParserException e) { setInvalidOclExprStatus(e); } catch (IllegalArgumentException e) { setInvalidOclExprStatus(e); } catch(RuntimeException e) { setStatus(GMFValidationPlugin.createStatus( IStatus.ERROR, StatusCodes.UNEXPECTED_PARSE_ERROR, Messages.unexpectedExprParseError, e)); GMFValidationPlugin.log(getStatus()); Trace.catching(DebugOptions.EXCEPTIONS_CATCHING, e); } }
public OCLExpressionAdapter(String body, EClassifier context, IParseEnvironment extEnv) { super(body, context, extEnv); try { org.eclipse.ocl.ecore.OCL ocl = null; if(extEnv != null) { EcoreEnvironmentFactory factory = EcoreEnvironmentFactory.INSTANCE; if(extEnv.getImportRegistry() != null) { factory = new EcoreEnvironmentFactory(extEnv.getImportRegistry()); } ocl = org.eclipse.ocl.ecore.OCL.newInstance(factory); this.env = ocl.getEnvironment(); for(String varName : extEnv.getVariableNames()) { EClassifier type = extEnv.getTypeOf(varName); Variable<EClassifier, EParameter> varDecl = ExpressionsFactory.eINSTANCE.createVariable(); varDecl.setName(varName); varDecl.setType(type); env.addElement(varDecl.getName(), varDecl, true); } } else { EPackage.Registry registry = new EPackageRegistryImpl(); for (Object nextRegistryObject : EPackage.Registry.INSTANCE.values()) { if (nextRegistryObject instanceof EPackage) { EPackage ePackage = (EPackage) nextRegistryObject; registry.put(ePackage.getNsURI(), ePackage); } } if (context.eResource() != null && context.eResource().getResourceSet() != null) { ResourceSet resourceSet = context.eResource().getResourceSet(); EcoreUtil.resolveAll(resourceSet); HashSet<EPackage> ePackages = new HashSet<EPackage>(); for (Resource resource : resourceSet.getResources()) { ePackages.addAll(EcoreUtil.<EPackage> getObjectsByType(resource.getContents(), EcorePackage.Literals.EPACKAGE)); } for (EPackage ePackage : ePackages) { registry.put(ePackage.getNsURI(), ePackage); } } ocl = org.eclipse.ocl.ecore.OCL.newInstance(new EcoreEnvironmentFactory(registry)); this.env = ocl.getEnvironment(); } org.eclipse.ocl.ecore.OCL.Helper helper = ocl.createOCLHelper(); helper.setContext(context); this.query = ocl.createQuery(helper.createQuery(body)); } catch (ParserException e) { setInvalidOclExprStatus(e); } catch (IllegalArgumentException e) { setInvalidOclExprStatus(e); } catch(RuntimeException e) { setStatus(GMFValidationPlugin.createStatus( IStatus.ERROR, StatusCodes.UNEXPECTED_PARSE_ERROR, Messages.unexpectedExprParseError, e)); GMFValidationPlugin.log(getStatus()); Trace.catching(DebugOptions.EXCEPTIONS_CATCHING, e); } }
diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java index d0988eaab..9933efa8a 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java @@ -1,6425 +1,6429 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * [email protected] - http://bugs.eclipse.org/bugs/show_bug.cgi?id=29027 * Michel Ishizuka ([email protected]) - http://bugs.eclipse.org/bugs/show_bug.cgi?id=68963 * Genady Beryozkin, [email protected] - https://bugs.eclipse.org/bugs/show_bug.cgi?id=11668 *******************************************************************************/ package org.eclipse.ui.texteditor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import org.osgi.framework.Bundle; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.ST; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Caret; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.commands.operations.IOperationApprover; import org.eclipse.core.commands.operations.IOperationHistory; import org.eclipse.core.commands.operations.IUndoContext; import org.eclipse.core.commands.operations.OperationHistoryFactory; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SafeRunner; import org.eclipse.core.runtime.Status; import org.eclipse.text.undo.DocumentUndoManagerRegistry; import org.eclipse.text.undo.IDocumentUndoManager; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.IShellProvider; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.text.IFindReplaceTargetExtension; import org.eclipse.jface.text.IMarkRegionTarget; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ISelectionValidator; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITextViewerExtension5; import org.eclipse.jface.text.ITextViewerExtension6; import org.eclipse.jface.text.IUndoManager; import org.eclipse.jface.text.IUndoManagerExtension; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; import org.eclipse.jface.text.revisions.RevisionInformation; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.IVerticalRulerColumn; import org.eclipse.jface.text.source.IVerticalRulerExtension; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.jface.text.source.VerticalRuler; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IKeyBindingService; import org.eclipse.ui.IMemento; import org.eclipse.ui.INavigationLocation; import org.eclipse.ui.INavigationLocationProvider; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IPartService; import org.eclipse.ui.IPersistableEditor; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.ISaveablesLifecycleListener; import org.eclipse.ui.ISaveablesSource; import org.eclipse.ui.IWindowListener; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.Saveable; import org.eclipse.ui.SaveablesLifecycleEvent; import org.eclipse.ui.dialogs.PropertyDialogAction; import org.eclipse.ui.dnd.IDragAndDropService; import org.eclipse.ui.internal.EditorPluginAction; import org.eclipse.ui.internal.texteditor.EditPosition; import org.eclipse.ui.internal.texteditor.NLSUtility; import org.eclipse.ui.internal.texteditor.TextEditorPlugin; import org.eclipse.ui.internal.texteditor.rulers.StringSetSerializer; import org.eclipse.ui.operations.LinearUndoViolationUserApprover; import org.eclipse.ui.operations.NonLocalUndoUserApprover; import org.eclipse.ui.operations.OperationHistoryActionHandler; import org.eclipse.ui.operations.RedoActionHandler; import org.eclipse.ui.operations.UndoActionHandler; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.texteditor.rulers.IColumnSupport; import org.eclipse.ui.texteditor.rulers.IContributedRulerColumn; import org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor; import org.eclipse.ui.texteditor.rulers.RulerColumnPreferenceAdapter; import org.eclipse.ui.texteditor.rulers.RulerColumnRegistry; /** * Abstract base implementation of a text editor. * <p> * Subclasses are responsible for configuring the editor appropriately. * The standard text editor, <code>TextEditor</code>, is one such example.</p> * <p> * If a subclass calls {@linkplain #setEditorContextMenuId(String) setEditorContextMenuId} the argument is * used as the id under which the editor's context menu is registered for extensions. * If no id is set, the context menu is registered under <b>[editor_id].EditorContext</b> * whereby [editor_id] is replaced with the editor's part id. If the editor is instructed to * run in version 1.0 context menu registration compatibility mode, the latter form of the * registration even happens if a context menu id has been set via {@linkplain #setEditorContextMenuId(String) setEditorContextMenuId}. * If no id is set while in compatibility mode, the menu is registered under * {@link #DEFAULT_EDITOR_CONTEXT_MENU_ID}.</p> * <p> * If a subclass calls {@linkplain #setRulerContextMenuId(String) setRulerContextMenuId} the argument is * used as the id under which the ruler's context menu is registered for extensions. * If no id is set, the context menu is registered under <b>[editor_id].RulerContext</b> * whereby [editor_id] is replaced with the editor's part id. If the editor is instructed to * run in version 1.0 context menu registration compatibility mode, the latter form of the * registration even happens if a context menu id has been set via {@linkplain #setRulerContextMenuId(String) setRulerContextMenuId}. * If no id is set while in compatibility mode, the menu is registered under * {@link #DEFAULT_RULER_CONTEXT_MENU_ID}.</p> */ public abstract class AbstractTextEditor extends EditorPart implements ITextEditor, IReusableEditor, ITextEditorExtension, ITextEditorExtension2, ITextEditorExtension3, ITextEditorExtension4, INavigationLocationProvider, ISaveablesSource, IPersistableEditor { /** * Tag used in xml configuration files to specify editor action contributions. * Current value: <code>editorContribution</code> * @since 2.0 */ private static final String TAG_CONTRIBUTION_TYPE= "editorContribution"; //$NON-NLS-1$ /** * Tags used in the {@link IMemento} when saving and * restoring editor state. * * @see #saveState(IMemento) * @see #restoreState(IMemento) * @since 3.3 */ protected static final String TAG_SELECTION_OFFSET= "selectionOffset"; //$NON-NLS-1$ protected static final String TAG_SELECTION_LENGTH= "selectionLength"; //$NON-NLS-1$ /** * The caret width for the wide (double) caret. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=21715. * Value: {@value} * @since 3.0 */ private static final int WIDE_CARET_WIDTH= 2; /** * The caret width for the narrow (single) caret. * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=21715. * Value: {@value} * @since 3.0 */ private static final int SINGLE_CARET_WIDTH= 1; /** * The text input listener. * * @see ITextInputListener * @since 2.1 */ private static class TextInputListener implements ITextInputListener { /** Indicates whether the editor input changed during the process of state validation. */ public boolean inputChanged; /* Detectors for editor input changes during the process of state validation. */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {} public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { inputChanged= true; } } /** * Internal element state listener. */ class ElementStateListener implements IElementStateListener, IElementStateListenerExtension { /** * Internal <code>VerifyListener</code> for performing the state validation of the * editor input in case of the first attempted manipulation via typing on the keyboard. * @since 2.0 */ class Validator implements VerifyListener { /* * @see VerifyListener#verifyText(org.eclipse.swt.events.VerifyEvent) */ public void verifyText(VerifyEvent e) { IDocument document= getDocumentProvider().getDocument(getEditorInput()); final boolean[] documentChanged= new boolean[1]; IDocumentListener listener= new IDocumentListener() { public void documentAboutToBeChanged(DocumentEvent event) { } public void documentChanged(DocumentEvent event) { documentChanged[0]= true; } }; try { if (document != null) document.addDocumentListener(listener); if (! validateEditorInputState() || documentChanged[0]) e.doit= false; } finally { if (document != null) document.removeDocumentListener(listener); } } } /** * The listener's validator. * @since 2.0 */ private Validator fValidator; /** * The display used for posting runnable into the UI thread. * @since 3.0 */ private Display fDisplay; /* * @see IElementStateListenerExtension#elementStateValidationChanged(Object, boolean) * @since 2.0 */ public void elementStateValidationChanged(final Object element, final boolean isStateValidated) { if (element != null && element.equals(getEditorInput())) { Runnable r= new Runnable() { public void run() { enableSanityChecking(true); if (isStateValidated && fValidator != null) { ISourceViewer viewer= fSourceViewer; if (viewer != null) { StyledText textWidget= viewer.getTextWidget(); if (textWidget != null && !textWidget.isDisposed()) textWidget.removeVerifyListener(fValidator); fValidator= null; enableStateValidation(false); } } else if (!isStateValidated && fValidator == null) { ISourceViewer viewer= fSourceViewer; if (viewer != null) { StyledText textWidget= viewer.getTextWidget(); if (textWidget != null && !textWidget.isDisposed()) { fValidator= new Validator(); enableStateValidation(true); textWidget.addVerifyListener(fValidator); } } } } }; execute(r, false); } } /* * @see IElementStateListener#elementDirtyStateChanged(Object, boolean) */ public void elementDirtyStateChanged(Object element, boolean isDirty) { if (element != null && element.equals(getEditorInput())) { Runnable r= new Runnable() { public void run() { enableSanityChecking(true); firePropertyChange(PROP_DIRTY); } }; execute(r, false); } } /* * @see IElementStateListener#elementContentAboutToBeReplaced(Object) */ public void elementContentAboutToBeReplaced(Object element) { if (element != null && element.equals(getEditorInput())) { Runnable r= new Runnable() { public void run() { enableSanityChecking(true); rememberSelection(); resetHighlightRange(); } }; execute(r, false); } } /* * @see IElementStateListener#elementContentReplaced(Object) */ public void elementContentReplaced(Object element) { if (element != null && element.equals(getEditorInput())) { Runnable r= new Runnable() { public void run() { enableSanityChecking(true); firePropertyChange(PROP_DIRTY); restoreSelection(); handleElementContentReplaced(); } }; execute(r, false); } } /* * @see IElementStateListener#elementDeleted(Object) */ public void elementDeleted(Object deletedElement) { if (deletedElement != null && deletedElement.equals(getEditorInput())) { Runnable r= new Runnable() { public void run() { enableSanityChecking(true); close(false); } }; execute(r, false); } } /* * @see IElementStateListener#elementMoved(Object, Object) */ public void elementMoved(final Object originalElement, final Object movedElement) { if (originalElement != null && originalElement.equals(getEditorInput())) { final boolean doValidationAsync= Display.getCurrent() != null; Runnable r= new Runnable() { public void run() { enableSanityChecking(true); if (fSourceViewer == null) return; if (!canHandleMove((IEditorInput) originalElement, (IEditorInput) movedElement)) { close(true); return; } if (movedElement == null || movedElement instanceof IEditorInput) { rememberSelection(); final IDocumentProvider d= getDocumentProvider(); final String previousContent; IDocumentUndoManager previousUndoManager=null; IDocument changed= null; boolean wasDirty= isDirty(); changed= d.getDocument(getEditorInput()); if (changed != null) { if (wasDirty) previousContent= changed.get(); else previousContent= null; previousUndoManager= DocumentUndoManagerRegistry.getDocumentUndoManager(changed); if (previousUndoManager != null) previousUndoManager.connect(this); } else previousContent= null; setInput((IEditorInput) movedElement); // The undo manager needs to be replaced with one for the new document. // Transfer the undo history and then disconnect from the old undo manager. if (previousUndoManager != null) { IDocument newDocument= getDocumentProvider().getDocument(movedElement); if (newDocument != null) { IDocumentUndoManager newUndoManager= DocumentUndoManagerRegistry.getDocumentUndoManager(newDocument); if (newUndoManager != null) newUndoManager.transferUndoHistory(previousUndoManager); } previousUndoManager.disconnect(this); } if (wasDirty && changed != null) { Runnable r2= new Runnable() { public void run() { validateState(getEditorInput()); d.getDocument(getEditorInput()).set(previousContent); updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_ELEMENT_STATE); restoreSelection(); } }; execute(r2, doValidationAsync); } else restoreSelection(); } } }; execute(r, false); } } /* * @see IElementStateListenerExtension#elementStateChanging(Object) * @since 2.0 */ public void elementStateChanging(Object element) { if (element != null && element.equals(getEditorInput())) enableSanityChecking(false); } /* * @see IElementStateListenerExtension#elementStateChangeFailed(Object) * @since 2.0 */ public void elementStateChangeFailed(Object element) { if (element != null && element.equals(getEditorInput())) enableSanityChecking(true); } /** * Executes the given runnable in the UI thread. * <p> * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=76765 for details * about why the parameter <code>postAsync</code> has been * introduced in the course of 3.1. * * @param runnable runnable to be executed * @param postAsync <code>true</code> if the runnable must be posted asynchronous, <code>false</code> otherwise * @since 3.0 */ private void execute(Runnable runnable, boolean postAsync) { if (postAsync || Display.getCurrent() == null) { if (fDisplay == null) fDisplay= getSite().getShell().getDisplay(); fDisplay.asyncExec(runnable); } else runnable.run(); } } /** * Internal text listener for updating all content dependent * actions. The updating is done asynchronously. */ class TextListener implements ITextListener, ITextInputListener { /** The posted updater code. */ private Runnable fRunnable= new Runnable() { public void run() { fIsRunnablePosted= false; if (fSourceViewer != null) { updateContentDependentActions(); // remember the last edit position if (isDirty() && fUpdateLastEditPosition) { fUpdateLastEditPosition= false; ISelection sel= getSelectionProvider().getSelection(); IEditorInput input= getEditorInput(); IDocument document= getDocumentProvider().getDocument(input); if (fLocalLastEditPosition != null) { document.removePosition(fLocalLastEditPosition); fLocalLastEditPosition= null; } if (sel instanceof ITextSelection && !sel.isEmpty()) { ITextSelection s= (ITextSelection) sel; fLocalLastEditPosition= new Position(s.getOffset(), s.getLength()); try { document.addPosition(fLocalLastEditPosition); } catch (BadLocationException ex) { fLocalLastEditPosition= null; } } TextEditorPlugin.getDefault().setLastEditPosition(new EditPosition(input, getEditorSite().getId(), fLocalLastEditPosition)); } } } }; /** Display used for posting the updater code. */ private Display fDisplay; /** * The editor's last edit position * @since 3.0 */ private Position fLocalLastEditPosition; /** * Has the runnable been posted? * @since 3.0 */ private boolean fIsRunnablePosted= false; /** * Should the last edit position be updated? * @since 3.0 */ private boolean fUpdateLastEditPosition= false; /* * @see ITextListener#textChanged(TextEvent) */ public void textChanged(TextEvent event) { /* * Also works for text events which do not base on a DocumentEvent. * This way, if the visible document of the viewer changes, all content * dependent actions are updated as well. */ if (fDisplay == null) fDisplay= getSite().getShell().getDisplay(); if (event.getDocumentEvent() != null) fUpdateLastEditPosition= true; if (!fIsRunnablePosted) { fIsRunnablePosted= true; fDisplay.asyncExec(fRunnable); } } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput != null && fLocalLastEditPosition != null) { oldInput.removePosition(fLocalLastEditPosition); fLocalLastEditPosition= null; } } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { } } /** * Internal property change listener for handling changes in the editor's preferences. */ class PropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { handlePreferenceStoreChanged(event); } } /** * Internal property change listener for handling workbench font changes. * @since 2.1 */ class FontPropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fSourceViewer == null) return; String property= event.getProperty(); if (getFontPropertyPreferenceKey().equals(property)) { initializeViewerFont(fSourceViewer); updateCaret(); } } } /** * Internal key verify listener for triggering action activation codes. */ class ActivationCodeTrigger implements VerifyKeyListener { /** Indicates whether this trigger has been installed. */ private boolean fIsInstalled= false; /** * The key binding service to use. * @since 2.0 */ private IKeyBindingService fKeyBindingService; /* * @see VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { ActionActivationCode code= null; int size= fActivationCodes.size(); for (int i= 0; i < size; i++) { code= (ActionActivationCode) fActivationCodes.get(i); if (code.matches(event)) { IAction action= getAction(code.fActionId); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (!action.isEnabled() && action instanceof IReadOnlyDependent) { IReadOnlyDependent dependent= (IReadOnlyDependent) action; boolean writable= dependent.isEnabled(true); if (writable) { event.doit= false; return; } } else if (action.isEnabled()) { event.doit= false; action.run(); return; } } } } } /** * Installs this trigger on the editor's text widget. * @since 2.0 */ public void install() { if (!fIsInstalled) { if (fSourceViewer instanceof ITextViewerExtension) { ITextViewerExtension e= (ITextViewerExtension) fSourceViewer; e.prependVerifyKeyListener(this); } else { StyledText text= fSourceViewer.getTextWidget(); text.addVerifyKeyListener(this); } fKeyBindingService= getEditorSite().getKeyBindingService(); fIsInstalled= true; } } /** * Uninstalls this trigger from the editor's text widget. * @since 2.0 */ public void uninstall() { if (fIsInstalled) { if (fSourceViewer instanceof ITextViewerExtension) { ITextViewerExtension e= (ITextViewerExtension) fSourceViewer; e.removeVerifyKeyListener(this); } else if (fSourceViewer != null) { StyledText text= fSourceViewer.getTextWidget(); if (text != null && !text.isDisposed()) text.removeVerifyKeyListener(fActivationCodeTrigger); } fIsInstalled= false; fKeyBindingService= null; } } /** * Registers the given action for key activation. * @param action the action to be registered * @since 2.0 */ public void registerActionForKeyActivation(IAction action) { if (action.getActionDefinitionId() != null) fKeyBindingService.registerAction(action); } /** * The given action is no longer available for key activation * @param action the action to be unregistered * @since 2.0 */ public void unregisterActionFromKeyActivation(IAction action) { if (action.getActionDefinitionId() != null) fKeyBindingService.unregisterAction(action); } /** * Sets the key binding scopes for this editor. * @param keyBindingScopes the key binding scopes * @since 2.1 */ public void setScopes(String[] keyBindingScopes) { if (keyBindingScopes != null && keyBindingScopes.length > 0) fKeyBindingService.setScopes(keyBindingScopes); } } /** * Representation of action activation codes. */ static class ActionActivationCode { /** The action id. */ public String fActionId; /** The character. */ public char fCharacter; /** The key code. */ public int fKeyCode= -1; /** The state mask. */ public int fStateMask= SWT.DEFAULT; /** * Creates a new action activation code for the given action id. * @param actionId the action id */ public ActionActivationCode(String actionId) { fActionId= actionId; } /** * Returns <code>true</code> if this activation code matches the given verify event. * @param event the event to test for matching * @return whether this activation code matches <code>event</code> */ public boolean matches(VerifyEvent event) { return (event.character == fCharacter && (fKeyCode == -1 || event.keyCode == fKeyCode) && (fStateMask == SWT.DEFAULT || event.stateMask == fStateMask)); } } /** * Internal part and shell activation listener for triggering state validation. * @since 2.0 */ class ActivationListener implements IPartListener, IWindowListener { /** Cache of the active workbench part. */ private IWorkbenchPart fActivePart; /** Indicates whether activation handling is currently be done. */ private boolean fIsHandlingActivation= false; /** * The part service. * @since 3.1 */ private IPartService fPartService; /** * Creates this activation listener. * * @param partService the part service on which to add the part listener * @since 3.1 */ public ActivationListener(IPartService partService) { fPartService= partService; fPartService.addPartListener(this); PlatformUI.getWorkbench().addWindowListener(this); } /** * Disposes this activation listener. * * @since 3.1 */ public void dispose() { fPartService.removePartListener(this); PlatformUI.getWorkbench().removeWindowListener(this); fPartService= null; } /* * @see IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) */ public void partActivated(IWorkbenchPart part) { // Restore the saved state if any if (part == AbstractTextEditor.this && fMementoToRestore != null && containsSavedState(fMementoToRestore)) doRestoreState(fMementoToRestore); fMementoToRestore= null; fActivePart= part; handleActivation(); } /* * @see IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) */ public void partBroughtToTop(IWorkbenchPart part) { } /* * @see IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) */ public void partClosed(IWorkbenchPart part) { } /* * @see IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) */ public void partDeactivated(IWorkbenchPart part) { fActivePart= null; } /* * @see IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) */ public void partOpened(IWorkbenchPart part) { } /** * Handles the activation triggering a element state check in the editor. */ private void handleActivation() { if (fIsHandlingActivation) return; if (fActivePart == AbstractTextEditor.this) { fIsHandlingActivation= true; try { safelySanityCheckState(getEditorInput()); } finally { fIsHandlingActivation= false; } } } /* * @see org.eclipse.ui.IWindowListener#windowActivated(org.eclipse.ui.IWorkbenchWindow) * @since 3.1 */ public void windowActivated(IWorkbenchWindow window) { if (window == getEditorSite().getWorkbenchWindow()) { /* * Workaround for problem described in * http://dev.eclipse.org/bugs/show_bug.cgi?id=11731 * Will be removed when SWT has solved the problem. */ window.getShell().getDisplay().asyncExec(new Runnable() { public void run() { handleActivation(); } }); } } /* * @see org.eclipse.ui.IWindowListener#windowDeactivated(org.eclipse.ui.IWorkbenchWindow) * @since 3.1 */ public void windowDeactivated(IWorkbenchWindow window) { } /* * @see org.eclipse.ui.IWindowListener#windowClosed(org.eclipse.ui.IWorkbenchWindow) * @since 3.1 */ public void windowClosed(IWorkbenchWindow window) { } /* * @see org.eclipse.ui.IWindowListener#windowOpened(org.eclipse.ui.IWorkbenchWindow) * @since 3.1 */ public void windowOpened(IWorkbenchWindow window) { } } /** * Internal interface for a cursor listener. I.e. aggregation * of mouse and key listener. * @since 2.0 */ interface ICursorListener extends MouseListener, KeyListener { } /** * Maps an action definition id to an StyledText action. * @since 2.0 */ protected static final class IdMapEntry { /** The action id. */ private String fActionId; /** The StyledText action. */ private int fAction; /** * Creates a new mapping. * @param actionId the action id * @param action the StyledText action */ public IdMapEntry(String actionId, int action) { fActionId= actionId; fAction= action; } /** * Returns the action id. * @return the action id */ public String getActionId() { return fActionId; } /** * Returns the action. * @return the action */ public int getAction() { return fAction; } } /** * Internal action to scroll the editor's viewer by a specified number of lines. * @since 2.0 */ class ScrollLinesAction extends Action { /** Number of lines to scroll. */ private int fScrollIncrement; /** * Creates a new scroll action that scroll the given number of lines. If the * increment is &lt; 0, it's scrolling up, if &gt; 0 it's scrolling down. * @param scrollIncrement the number of lines to scroll */ public ScrollLinesAction(int scrollIncrement) { fScrollIncrement= scrollIncrement; } /* * @see IAction#run() */ public void run() { if (fSourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) fSourceViewer; StyledText textWidget= fSourceViewer.getTextWidget(); int topIndex= textWidget.getTopIndex(); int newTopIndex= Math.max(0, topIndex + fScrollIncrement); fSourceViewer.setTopIndex(extension.widgetLine2ModelLine(newTopIndex)); } else { int topIndex= fSourceViewer.getTopIndex(); int newTopIndex= Math.max(0, topIndex + fScrollIncrement); fSourceViewer.setTopIndex(newTopIndex); } } } /** * Action to toggle the insert mode. The action is checked if smart mode is * turned on. * * @since 2.1 */ class ToggleInsertModeAction extends ResourceAction { public ToggleInsertModeAction(ResourceBundle bundle, String prefix) { super(bundle, prefix, IAction.AS_CHECK_BOX); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { switchToNextInsertMode(); } /* * @see org.eclipse.jface.action.IAction#isChecked() * @since 3.0 */ public boolean isChecked() { return fInsertMode == SMART_INSERT; } } /** * Action to toggle the overwrite mode. * * @since 3.0 */ class ToggleOverwriteModeAction extends ResourceAction { public ToggleOverwriteModeAction(ResourceBundle bundle, String prefix) { super(bundle, prefix); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { toggleOverwriteMode(); } } /** * This action implements smart end. * Instead of going to the end of a line it does the following: * - if smart home/end is enabled and the caret is before the line's last non-whitespace and then the caret is moved directly after it * - if the caret is after last non-whitespace the caret is moved at the end of the line * - if the caret is at the end of the line the caret is moved directly after the line's last non-whitespace character * @since 2.1 (in 3.3 the access modifier changed from package visibility to protected) */ protected class LineEndAction extends TextNavigationAction { /** boolean flag which tells if the text up to the line end should be selected. */ private boolean fDoSelect; /** * Create a new line end action. * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the line end should be selected */ public LineEndAction(StyledText textWidget, boolean doSelect) { super(textWidget, ST.LINE_END); fDoSelect= doSelect; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { boolean isSmartHomeEndEnabled= false; IPreferenceStore store= getPreferenceStore(); if (store != null) isSmartHomeEndEnabled= store.getBoolean(AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END); StyledText st= fSourceViewer.getTextWidget(); if (st == null || st.isDisposed()) return; int caretOffset= st.getCaretOffset(); int lineNumber= st.getLineAtOffset(caretOffset); int lineOffset= st.getOffsetAtLine(lineNumber); int lineLength; try { int caretOffsetInDocument= widgetOffset2ModelOffset(fSourceViewer, caretOffset); lineLength= fSourceViewer.getDocument().getLineInformationOfOffset(caretOffsetInDocument).getLength(); } catch (BadLocationException ex) { return; } int lineEndOffset= lineOffset + lineLength; int delta= lineEndOffset - st.getCharCount(); if (delta > 0) { lineEndOffset -= delta; lineLength -= delta; } String line= ""; //$NON-NLS-1$ if (lineLength > 0) line= st.getText(lineOffset, lineEndOffset - 1); int i= lineLength - 1; while (i > -1 && Character.isWhitespace(line.charAt(i))) { i--; } i++; // Remember current selection Point oldSelection= st.getSelection(); // Compute new caret position int newCaretOffset= -1; if (isSmartHomeEndEnabled) { if (caretOffset - lineOffset == i) // to end of line newCaretOffset= lineEndOffset; else // to end of text newCaretOffset= lineOffset + i; } else { if (caretOffset < lineEndOffset) // to end of line newCaretOffset= lineEndOffset; } if (newCaretOffset == -1) newCaretOffset= caretOffset; else st.setCaretOffset(newCaretOffset); st.setCaretOffset(newCaretOffset); if (fDoSelect) { if (caretOffset < oldSelection.y) st.setSelection(oldSelection.y, newCaretOffset); else st.setSelection(oldSelection.x, newCaretOffset); } else st.setSelection(newCaretOffset); fireSelectionChanged(oldSelection); } } /** * This action implements smart home. * Instead of going to the start of a line it does the following: * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line the caret is moved directly before the line's first non-whitespace character * @since 2.1 */ protected class LineStartAction extends TextNavigationAction { /** boolean flag which tells if the text up to the beginning of the line should be selected. */ private final boolean fDoSelect; /** * Creates a new line start action. * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public LineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, ST.LINE_START); fDoSelect= doSelect; } /** * Computes the offset of the line start position. * * @param document The document where to compute the line start position * @param line The line to determine the start position of * @param length The length of the line * @param offset The caret position in the document * @return The offset of the line start * @since 3.0 */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { int index= 0; while (index < length && Character.isWhitespace(line.charAt(index))) index++; return index; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { boolean isSmartHomeEndEnabled= false; IPreferenceStore store= getPreferenceStore(); if (store != null) isSmartHomeEndEnabled= store.getBoolean(AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END); StyledText st= fSourceViewer.getTextWidget(); if (st == null || st.isDisposed()) return; int caretOffset= st.getCaretOffset(); int lineNumber= st.getLineAtOffset(caretOffset); int lineOffset= st.getOffsetAtLine(lineNumber); int lineLength; int caretOffsetInDocument; final IDocument document= fSourceViewer.getDocument(); try { caretOffsetInDocument= widgetOffset2ModelOffset(fSourceViewer, caretOffset); lineLength= document.getLineInformationOfOffset(caretOffsetInDocument).getLength(); } catch (BadLocationException ex) { return; } String line= ""; //$NON-NLS-1$ if (lineLength > 0) { int end= lineOffset + lineLength - 1; end= Math.min(end, st.getCharCount() -1); line= st.getText(lineOffset, end); } // Compute the line start offset int index= getLineStartPosition(document, line, lineLength, caretOffsetInDocument); // Remember current selection Point oldSelection= st.getSelection(); // Compute new caret position int newCaretOffset= -1; if (isSmartHomeEndEnabled) { if (caretOffset - lineOffset == index) // to beginning of line newCaretOffset= lineOffset; else // to beginning of text newCaretOffset= lineOffset + index; } else { if (caretOffset > lineOffset) // to beginning of line newCaretOffset= lineOffset; } if (newCaretOffset == -1) newCaretOffset= caretOffset; else st.setCaretOffset(newCaretOffset); if (fDoSelect) { if (caretOffset < oldSelection.y) st.setSelection(oldSelection.y, newCaretOffset); else st.setSelection(oldSelection.x, newCaretOffset); } else st.setSelection(newCaretOffset); fireSelectionChanged(oldSelection); } } /** * Internal action to show the editor's ruler context menu (accessibility). * @since 2.0 */ class ShowRulerContextMenuAction extends Action { /* * @see IAction#run() */ public void run() { if (fSourceViewer == null) return; StyledText text= fSourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; Point location= text.getLocationAtOffset(text.getCaretOffset()); location.x= 0; if (fVerticalRuler instanceof IVerticalRulerExtension) ((IVerticalRulerExtension) fVerticalRuler).setLocationOfLastMouseButtonActivity(location.x, location.y); location= text.toDisplay(location); fRulerContextMenu.setLocation(location.x, location.y); fRulerContextMenu.setVisible(true); } } /** * Editor specific selection provider which wraps the source viewer's selection provider. * @since 2.1 */ class SelectionProvider implements IPostSelectionProvider, ISelectionValidator { /* * @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener) */ public void addSelectionChangedListener(ISelectionChangedListener listener) { if (fSourceViewer != null) fSourceViewer.getSelectionProvider().addSelectionChangedListener(listener); } /* * @see org.eclipse.jface.viewers.ISelectionProvider#getSelection() */ public ISelection getSelection() { return doGetSelection(); } /* * @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener) */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { if (fSourceViewer != null) fSourceViewer.getSelectionProvider().removeSelectionChangedListener(listener); } /* * @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(ISelection) */ public void setSelection(ISelection selection) { doSetSelection(selection); } /* * @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) * @since 3.0 */ public void addPostSelectionChangedListener(ISelectionChangedListener listener) { if (fSourceViewer != null) { if (fSourceViewer.getSelectionProvider() instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) fSourceViewer.getSelectionProvider(); provider.addPostSelectionChangedListener(listener); } } } /* * @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener) * @since 3.0 */ public void removePostSelectionChangedListener(ISelectionChangedListener listener) { if (fSourceViewer != null) { if (fSourceViewer.getSelectionProvider() instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) fSourceViewer.getSelectionProvider(); provider.removePostSelectionChangedListener(listener); } } } /* * @see org.eclipse.jface.text.IPostSelectionValidator#isValid() * @since 3.0 */ public boolean isValid(ISelection postSelection) { return fSelectionListener != null && fSelectionListener.isValid(postSelection); } } /** * Internal implementation class for a change listener. * @since 3.0 */ protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { /** * Installs this selection changed listener with the given selection provider. If * the selection provider is a post selection provider, post selection changed * events are the preferred choice, otherwise normal selection changed events * are requested. * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } } /** * Removes this selection changed listener from the given selection provider. * * @param selectionProvider the selection provider */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.removePostSelectionChangedListener(this); } else { selectionProvider.removeSelectionChangedListener(this); } } } /** * This selection listener allows the SelectionProvider to implement {@link ISelectionValidator}. * * @since 3.0 */ private class SelectionListener extends AbstractSelectionChangedListener implements IDocumentListener { private IDocument fDocument; private final Object INVALID_SELECTION= new Object(); private Object fPostSelection= INVALID_SELECTION; /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public synchronized void selectionChanged(SelectionChangedEvent event) { fPostSelection= event.getSelection(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) * @since 3.0 */ public synchronized void documentAboutToBeChanged(DocumentEvent event) { fPostSelection= INVALID_SELECTION; } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) * @since 3.0 */ public void documentChanged(DocumentEvent event) { } public synchronized boolean isValid(ISelection selection) { return fPostSelection != INVALID_SELECTION && fPostSelection == selection; } public void setDocument(IDocument document) { if (fDocument != null) fDocument.removeDocumentListener(this); fDocument= document; if (fDocument != null) fDocument.addDocumentListener(this); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.AbstractSelectionChangedListener#install(org.eclipse.jface.viewers.ISelectionProvider) * @since 3.0 */ public void install(ISelectionProvider selectionProvider) { super.install(selectionProvider); if (selectionProvider != null) selectionProvider.addSelectionChangedListener(this); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.AbstractSelectionChangedListener#uninstall(org.eclipse.jface.viewers.ISelectionProvider) * @since 3.0 */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider != null) selectionProvider.removeSelectionChangedListener(this); if (fDocument != null) { fDocument.removeDocumentListener(this); fDocument= null; } super.uninstall(selectionProvider); } } /** * Captures the vertical and overview ruler support of an {@link ITextEditor}. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @since 3.3 */ protected static class ColumnSupport implements IColumnSupport { private final AbstractTextEditor fEditor; private final RulerColumnRegistry fRegistry; private final List fColumns; /** * Creates a new column support for the given editor. Only the editor itself should normally * create such an instance. * * @param editor the editor * @param registry the contribution registry to refer to */ public ColumnSupport(AbstractTextEditor editor, RulerColumnRegistry registry) { Assert.isLegal(editor != null); Assert.isLegal(registry != null); fEditor= editor; fRegistry= registry; fColumns= new ArrayList(); } /* * @see org.eclipse.ui.texteditor.IColumnSupport#setColumnVisible(java.lang.String, boolean) */ public final void setColumnVisible(RulerColumnDescriptor descriptor, boolean visible) { Assert.isLegal(descriptor != null); final CompositeRuler ruler= getRuler(); if (ruler == null) return; if (!isColumnSupported(descriptor)) visible= false; if (isColumnVisible(descriptor)) { if (!visible) removeColumn(ruler, descriptor); } else { if (visible) addColumn(ruler, descriptor); } } private void addColumn(final CompositeRuler ruler, final RulerColumnDescriptor descriptor) { final int idx= computeIndex(ruler, descriptor); SafeRunnable runnable= new SafeRunnable() { public void run() throws Exception { IContributedRulerColumn column= descriptor.createColumn(fEditor); fColumns.add(column); initializeColumn(column); ruler.addDecorator(idx, column); } }; SafeRunner.run(runnable); } /** * Hook to let subclasses initialize a newly created column. * <p> * Subclasses may extend this method.</p> * * @param column the created column */ protected void initializeColumn(IContributedRulerColumn column) { } private void removeColumn(final CompositeRuler ruler, final RulerColumnDescriptor descriptor) { removeColumn(ruler, getVisibleColumn(ruler, descriptor)); } private void removeColumn(final CompositeRuler ruler, final IContributedRulerColumn rulerColumn) { if (rulerColumn != null) { SafeRunnable runnable= new SafeRunnable() { public void run() throws Exception { if (ruler != null) ruler.removeDecorator(rulerColumn); rulerColumn.columnRemoved(); } }; SafeRunner.run(runnable); } } /** * Returns the currently visible column matching <code>id</code>, <code>null</code> if * none. * * @param ruler the composite ruler to scan * @param descriptor the descriptor of the column of interest * @return the matching column or <code>null</code> */ private IContributedRulerColumn getVisibleColumn(CompositeRuler ruler, RulerColumnDescriptor descriptor) { for (Iterator it= ruler.getDecoratorIterator(); it.hasNext();) { IVerticalRulerColumn column= (IVerticalRulerColumn)it.next(); if (column instanceof IContributedRulerColumn) { IContributedRulerColumn rulerColumn= (IContributedRulerColumn)column; RulerColumnDescriptor rcd= rulerColumn.getDescriptor(); if (descriptor.equals(rcd)) return rulerColumn; } } return null; } /** * Computes the insertion index for a column contribution into the currently visible columns. * * @param ruler the composite ruler into which to insert the column * @param descriptor the descriptor to compute the index for * @return the insertion index for a new column */ private int computeIndex(CompositeRuler ruler, RulerColumnDescriptor descriptor) { int index= 0; List all= fRegistry.getColumnDescriptors(); int newPos= all.indexOf(descriptor); for (Iterator it= ruler.getDecoratorIterator(); it.hasNext();) { IVerticalRulerColumn column= (IVerticalRulerColumn) it.next(); if (column instanceof IContributedRulerColumn) { RulerColumnDescriptor rcd= ((IContributedRulerColumn)column).getDescriptor(); if (rcd != null && all.indexOf(rcd) > newPos) break; } else if ("org.eclipse.jface.text.source.projection.ProjectionRulerColumn".equals(column.getClass().getName())) { //$NON-NLS-1$ // projection column is always the rightmost column break; } index++; } return index; } /* * @see org.eclipse.ui.texteditor.IColumnSupport#isColumnVisible(java.lang.String) */ public final boolean isColumnVisible(RulerColumnDescriptor descriptor) { Assert.isLegal(descriptor != null); CompositeRuler ruler= getRuler(); return ruler != null && getVisibleColumn(ruler, descriptor) != null; } /* * @see org.eclipse.ui.texteditor.IColumnSupport#isColumnSupported(java.lang.String) */ public final boolean isColumnSupported(RulerColumnDescriptor descriptor) { Assert.isLegal(descriptor != null); if (getRuler() == null) return false; if (descriptor == null) return false; return descriptor.matchesEditor(fEditor); } /** * Returns the editor's vertical ruler, if it is a {@link CompositeRuler}, <code>null</code> * otherwise. * * @return the editor's {@link CompositeRuler} or <code>null</code> */ private CompositeRuler getRuler() { Object ruler= fEditor.getAdapter(IVerticalRulerInfo.class); if (ruler instanceof CompositeRuler) return (CompositeRuler) ruler; return null; } /** * {@inheritDoc} * <p> * Subclasses may extend this method.</p> * */ public void dispose() { for (Iterator iter= new ArrayList(fColumns).iterator(); iter.hasNext();) removeColumn(getRuler(), (IContributedRulerColumn)iter.next()); } } /** * Key used to look up font preference. * Value: <code>"org.eclipse.jface.textfont"</code> * * @deprecated As of 2.1, replaced by {@link JFaceResources#TEXT_FONT} */ public final static String PREFERENCE_FONT= JFaceResources.TEXT_FONT; /** * Key used to look up foreground color preference. * Value: <code>AbstractTextEditor.Color.Foreground</code> * @since 2.0 */ public final static String PREFERENCE_COLOR_FOREGROUND= "AbstractTextEditor.Color.Foreground"; //$NON-NLS-1$ /** * Key used to look up background color preference. * Value: <code>AbstractTextEditor.Color.Background</code> * @since 2.0 */ public final static String PREFERENCE_COLOR_BACKGROUND= "AbstractTextEditor.Color.Background"; //$NON-NLS-1$ /** * Key used to look up foreground color system default preference. * Value: <code>AbstractTextEditor.Color.Foreground.SystemDefault</code> * @since 2.0 */ public final static String PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT= "AbstractTextEditor.Color.Foreground.SystemDefault"; //$NON-NLS-1$ /** * Key used to look up background color system default preference. * Value: <code>AbstractTextEditor.Color.Background.SystemDefault</code> * @since 2.0 */ public final static String PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT= "AbstractTextEditor.Color.Background.SystemDefault"; //$NON-NLS-1$ /** * Key used to look up selection foreground color preference. * Value: <code>AbstractTextEditor.Color.SelectionForeground</code> * @since 3.0 */ public final static String PREFERENCE_COLOR_SELECTION_FOREGROUND= "AbstractTextEditor.Color.SelectionForeground"; //$NON-NLS-1$ /** * Key used to look up selection background color preference. * Value: <code>AbstractTextEditor.Color.SelectionBackground</code> * @since 3.0 */ public final static String PREFERENCE_COLOR_SELECTION_BACKGROUND= "AbstractTextEditor.Color.SelectionBackground"; //$NON-NLS-1$ /** * Key used to look up selection foreground color system default preference. * Value: <code>AbstractTextEditor.Color.SelectionForeground.SystemDefault</code> * @since 3.0 */ public final static String PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT= "AbstractTextEditor.Color.SelectionForeground.SystemDefault"; //$NON-NLS-1$ /** * Key used to look up selection background color system default preference. * Value: <code>AbstractTextEditor.Color.SelectionBackground.SystemDefault</code> * @since 3.0 */ public final static String PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT= "AbstractTextEditor.Color.SelectionBackground.SystemDefault"; //$NON-NLS-1$ /** * Key used to look up find scope background color preference. * Value: <code>AbstractTextEditor.Color.FindScope</code> * @since 2.0 */ public final static String PREFERENCE_COLOR_FIND_SCOPE= "AbstractTextEditor.Color.FindScope"; //$NON-NLS-1$ /** * Key used to look up smart home/end preference. * Value: <code>AbstractTextEditor.Navigation.SmartHomeEnd</code> * @since 2.1 */ public final static String PREFERENCE_NAVIGATION_SMART_HOME_END= "AbstractTextEditor.Navigation.SmartHomeEnd"; //$NON-NLS-1$ /** * Key used to look up the custom caret preference. * Value: {@value} * @since 3.0 */ public final static String PREFERENCE_USE_CUSTOM_CARETS= "AbstractTextEditor.Accessibility.UseCustomCarets"; //$NON-NLS-1$ /** * Key used to look up the caret width preference. * Value: {@value} * @since 3.0 */ public final static String PREFERENCE_WIDE_CARET= "AbstractTextEditor.Accessibility.WideCaret"; //$NON-NLS-1$ /** * A named preference that controls if hyperlinks are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.1 */ public static final String PREFERENCE_HYPERLINKS_ENABLED= "hyperlinksEnabled"; //$NON-NLS-1$ /** * A named preference that controls the key modifier for hyperlinks. * <p> * Value is of type <code>String</code>. * </p> * * @since 3.1 */ public static final String PREFERENCE_HYPERLINK_KEY_MODIFIER= "hyperlinkKeyModifier"; //$NON-NLS-1$ /** * A named preference that controls the key modifier mask for hyperlinks. * The value is only used if the value of <code>PREFERENCE_HYPERLINK_KEY_MODIFIER</code> * cannot be resolved to valid SWT modifier bits. * <p> * Value is of type <code>String</code>. * </p> * * @see #PREFERENCE_HYPERLINK_KEY_MODIFIER * @since 3.1 */ public static final String PREFERENCE_HYPERLINK_KEY_MODIFIER_MASK= "hyperlinkKeyModifierMask"; //$NON-NLS-1$ /** * A named preference that controls the visible ruler column contributions. * <p> * Value is of type <code>String</code> and should be read using a {@link RulerColumnPreferenceAdapter}. * </p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @since 3.3 */ public static final String PREFERENCE_RULER_CONTRIBUTIONS= "rulerContributions"; //$NON-NLS-1$ /** * A named preference that controls the display of whitespace characters. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.3 */ public static final String PREFERENCE_SHOW_WHITESPACE_CHARACTERS= "showWhitespaceCharacters"; //$NON-NLS-1$ /** * A named preference that controls whether text drag and drop is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.3 */ public static final String PREFERENCE_TEXT_DRAG_AND_DROP_ENABLED= "textDragAndDropEnabled"; //$NON-NLS-1$ /** Menu id for the editor context menu. */ public final static String DEFAULT_EDITOR_CONTEXT_MENU_ID= "#EditorContext"; //$NON-NLS-1$ /** Menu id for the ruler context menu. */ public final static String DEFAULT_RULER_CONTEXT_MENU_ID= "#RulerContext"; //$NON-NLS-1$ /** The width of the vertical ruler. */ protected final static int VERTICAL_RULER_WIDTH= 12; /** * The complete mapping between action definition IDs used by eclipse and StyledText actions. * * @since 2.0 */ protected final static IdMapEntry[] ACTION_MAP= new IdMapEntry[] { // navigation new IdMapEntry(ITextEditorActionDefinitionIds.LINE_UP, ST.LINE_UP), new IdMapEntry(ITextEditorActionDefinitionIds.LINE_DOWN, ST.LINE_DOWN), new IdMapEntry(ITextEditorActionDefinitionIds.LINE_START, ST.LINE_START), new IdMapEntry(ITextEditorActionDefinitionIds.LINE_END, ST.LINE_END), new IdMapEntry(ITextEditorActionDefinitionIds.COLUMN_PREVIOUS, ST.COLUMN_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.COLUMN_NEXT, ST.COLUMN_NEXT), new IdMapEntry(ITextEditorActionDefinitionIds.PAGE_UP, ST.PAGE_UP), new IdMapEntry(ITextEditorActionDefinitionIds.PAGE_DOWN, ST.PAGE_DOWN), new IdMapEntry(ITextEditorActionDefinitionIds.WORD_PREVIOUS, ST.WORD_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.WORD_NEXT, ST.WORD_NEXT), new IdMapEntry(ITextEditorActionDefinitionIds.TEXT_START, ST.TEXT_START), new IdMapEntry(ITextEditorActionDefinitionIds.TEXT_END, ST.TEXT_END), new IdMapEntry(ITextEditorActionDefinitionIds.WINDOW_START, ST.WINDOW_START), new IdMapEntry(ITextEditorActionDefinitionIds.WINDOW_END, ST.WINDOW_END), // selection new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_LINE_UP, ST.SELECT_LINE_UP), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_LINE_DOWN, ST.SELECT_LINE_DOWN), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_LINE_START, ST.SELECT_LINE_START), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_LINE_END, ST.SELECT_LINE_END), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_COLUMN_PREVIOUS, ST.SELECT_COLUMN_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_COLUMN_NEXT, ST.SELECT_COLUMN_NEXT), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_PAGE_UP, ST.SELECT_PAGE_UP), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_PAGE_DOWN, ST.SELECT_PAGE_DOWN), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, ST.SELECT_WORD_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, ST.SELECT_WORD_NEXT), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_TEXT_START, ST.SELECT_TEXT_START), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_TEXT_END, ST.SELECT_TEXT_END), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_WINDOW_START, ST.SELECT_WINDOW_START), new IdMapEntry(ITextEditorActionDefinitionIds.SELECT_WINDOW_END, ST.SELECT_WINDOW_END), // modification new IdMapEntry(IWorkbenchActionDefinitionIds.CUT, ST.CUT), new IdMapEntry(IWorkbenchActionDefinitionIds.COPY, ST.COPY), new IdMapEntry(IWorkbenchActionDefinitionIds.PASTE, ST.PASTE), new IdMapEntry(ITextEditorActionDefinitionIds.DELETE_PREVIOUS, ST.DELETE_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.DELETE_NEXT, ST.DELETE_NEXT), new IdMapEntry(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, ST.DELETE_WORD_PREVIOUS), new IdMapEntry(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, ST.DELETE_WORD_NEXT), // miscellaneous new IdMapEntry(ITextEditorActionDefinitionIds.TOGGLE_OVERWRITE, ST.TOGGLE_OVERWRITE) }; private final String fReadOnlyLabel= EditorMessages.Editor_statusline_state_readonly_label; private final String fWritableLabel= EditorMessages.Editor_statusline_state_writable_label; private final String fInsertModeLabel= EditorMessages.Editor_statusline_mode_insert_label; private final String fOverwriteModeLabel= EditorMessages.Editor_statusline_mode_overwrite_label; private final String fSmartInsertModeLabel= EditorMessages.Editor_statusline_mode_smartinsert_label; /** The error message shown in the status line in case of failed information look up. */ protected final String fErrorLabel= EditorMessages.Editor_statusline_error_label; /** * Data structure for the position label value. */ private static class PositionLabelValue { public int fValue; public String toString() { return String.valueOf(fValue); } } /** The pattern used to show the position label in the status line. */ private final String fPositionLabelPattern= EditorMessages.Editor_statusline_position_pattern; /** The position label value of the current line. */ private final PositionLabelValue fLineLabel= new PositionLabelValue(); /** The position label value of the current column. */ private final PositionLabelValue fColumnLabel= new PositionLabelValue(); /** The arguments for the position label pattern. */ private final Object[] fPositionLabelPatternArguments= new Object[] { fLineLabel, fColumnLabel }; /** * The column support of this editor. * @since 3.3 */ private IColumnSupport fColumnSupport; /** The editor's explicit document provider. */ private IDocumentProvider fExplicitDocumentProvider; /** The editor's preference store. */ private IPreferenceStore fPreferenceStore; /** The editor's range indicator. */ private Annotation fRangeIndicator; /** The editor's source viewer configuration. */ private SourceViewerConfiguration fConfiguration; /** The editor's source viewer. */ private ISourceViewer fSourceViewer; /** * The editor's selection provider. * @since 2.1 */ private SelectionProvider fSelectionProvider= new SelectionProvider(); /** * The editor's selection listener. * @since 3.0 */ private SelectionListener fSelectionListener; /** The editor's font. */ private Font fFont; /** * The editor's foreground color. * @since 2.0 */ private Color fForegroundColor; /** * The editor's background color. * @since 2.0 */ private Color fBackgroundColor; /** * The editor's selection foreground color. * @since 3.0 */ private Color fSelectionForegroundColor; /** * The editor's selection background color. * @since 3.0 */ private Color fSelectionBackgroundColor; /** * The find scope's highlight color. * @since 2.0 */ private Color fFindScopeHighlightColor; /** * The editor's status line. * @since 2.1 */ private IEditorStatusLine fEditorStatusLine; /** The editor's vertical ruler. */ private IVerticalRuler fVerticalRuler; /** The editor's context menu id. */ private String fEditorContextMenuId; /** The ruler's context menu id. */ private String fRulerContextMenuId; /** The editor's help context id. */ private String fHelpContextId; /** The editor's presentation mode. */ private boolean fShowHighlightRangeOnly; /** The actions registered with the editor. */ private Map fActions= new HashMap(10); /** The actions marked as selection dependent. */ private List fSelectionActions= new ArrayList(5); /** The actions marked as content dependent. */ private List fContentActions= new ArrayList(5); /** * The actions marked as property dependent. * @since 2.0 */ private List fPropertyActions= new ArrayList(5); /** * The actions marked as state dependent. * @since 2.0 */ private List fStateActions= new ArrayList(5); /** The editor's action activation codes. */ private List fActivationCodes= new ArrayList(2); /** The verify key listener for activation code triggering. */ private ActivationCodeTrigger fActivationCodeTrigger= new ActivationCodeTrigger(); /** Context menu listener. */ private IMenuListener fMenuListener; /** Vertical ruler mouse listener. */ private MouseListener fMouseListener; /** Selection changed listener. */ private ISelectionChangedListener fSelectionChangedListener; /** Title image to be disposed. */ private Image fTitleImage; /** The text context menu to be disposed. */ private Menu fTextContextMenu; /** The ruler context menu to be disposed. */ private Menu fRulerContextMenu; /** The editor's element state listener. */ private IElementStateListener fElementStateListener= new ElementStateListener(); /** * The editor's text input listener. * @since 2.1 */ private TextInputListener fTextInputListener= new TextInputListener(); /** The editor's text listener. */ private TextListener fTextListener= new TextListener(); /** The editor's property change listener. */ private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); /** * The editor's font properties change listener. * @since 2.1 */ private IPropertyChangeListener fFontPropertyChangeListener= new FontPropertyChangeListener(); /** * The editor's activation listener. * @since 2.0 */ private ActivationListener fActivationListener; /** * The map of the editor's status fields. * @since 2.0 */ private Map fStatusFields; /** * The editor's cursor listener. * @since 2.0 */ private ICursorListener fCursorListener; /** * The editor's remembered text selection. * @since 2.0 */ private ISelection fRememberedSelection; /** * Indicates whether the editor runs in 1.0 context menu registration compatibility mode. * @since 2.0 */ private boolean fCompatibilityMode= true; /** * The number of re-entrances into error correction code while saving. * @since 2.0 */ private int fErrorCorrectionOnSave; /** * The delete line target. * @since 2.1 */ private DeleteLineTarget fDeleteLineTarget; /** * The incremental find target. * @since 2.0 */ private IncrementalFindTarget fIncrementalFindTarget; /** * The mark region target. * @since 2.0 */ private IMarkRegionTarget fMarkRegionTarget; /** * Cached modification stamp of the editor's input. * @since 2.0 */ private long fModificationStamp= -1; /** * Ruler context menu listeners. * @since 2.0 */ private List fRulerContextMenuListeners= new ArrayList(); /** * Indicates whether sanity checking in enabled. * @since 2.0 */ private boolean fIsSanityCheckEnabled= true; /** * The find replace target. * @since 2.1 */ private FindReplaceTarget fFindReplaceTarget; /** * Indicates whether state validation is enabled. * @since 2.1 */ private boolean fIsStateValidationEnabled= true; /** * The key binding scopes of this editor. * @since 2.1 */ private String[] fKeyBindingScopes; /** * Whether the overwrite mode can be turned on. * @since 3.0 */ private boolean fIsOverwriteModeEnabled= true; /** * Whether the overwrite mode is currently on. * @since 3.0 */ private boolean fIsOverwriting= false; /** * The editor's insert mode. * @since 3.0 */ private InsertMode fInsertMode= SMART_INSERT; /** * The sequence of legal editor insert modes. * @since 3.0 */ private List fLegalInsertModes= null; /** * The non-default caret. * @since 3.0 */ private Caret fNonDefaultCaret; /** * The image used in non-default caret. * @since 3.0 */ private Image fNonDefaultCaretImage; /** * The styled text's initial caret. * @since 3.0 */ private Caret fInitialCaret; /** * The operation approver used to warn on undoing of non-local operations. * @since 3.1 */ private IOperationApprover fNonLocalOperationApprover; /** * The operation approver used to warn of linear undo violations. * @since 3.1 */ private IOperationApprover fLinearUndoViolationApprover; /** * This editor's memento holding data for restoring it after restart. * @since 3.3 */ private IMemento fMementoToRestore; /** * This editor's savable. * @since 3.3 */ private Saveable fSavable; /** * Tells whether text drag and drop is enabled. * <p> * <strong>Note:</strong> This is only a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=162192. * </p> * @since 3.3 */ private boolean fIsTextDragAndDropEnabled; /** * Creates a new text editor. If not explicitly set, this editor uses * a <code>SourceViewerConfiguration</code> to configure its * source viewer. This viewer does not have a range indicator installed, * nor any menu id set. By default, the created editor runs in 1.0 context * menu registration compatibility mode. */ protected AbstractTextEditor() { super(); fEditorContextMenuId= null; fRulerContextMenuId= null; fHelpContextId= null; } /* * @see ITextEditor#getDocumentProvider() */ public IDocumentProvider getDocumentProvider() { return fExplicitDocumentProvider; } /** * Returns the editor's range indicator. May return <code>null</code> if no * range indicator is installed. * * @return the editor's range indicator which may be <code>null</code> */ protected final Annotation getRangeIndicator() { return fRangeIndicator; } /** * Returns the editor's source viewer configuration. May return <code>null</code> * before the editor's part has been created and after disposal. * * @return the editor's source viewer configuration which may be <code>null</code> */ protected final SourceViewerConfiguration getSourceViewerConfiguration() { return fConfiguration; } /** * Returns the editor's source viewer. May return <code>null</code> before * the editor's part has been created and after disposal. * * @return the editor's source viewer which may be <code>null</code> */ protected final ISourceViewer getSourceViewer() { return fSourceViewer; } /** * Returns the editor's vertical ruler. May return <code>null</code> before * the editor's part has been created and after disposal. * * @return the editor's vertical ruler which may be <code>null</code> */ protected final IVerticalRuler getVerticalRuler() { return fVerticalRuler; } /** * Returns the editor's context menu id. May return <code>null</code> before * the editor's part has been created. * * @return the editor's context menu id which may be <code>null</code> */ protected final String getEditorContextMenuId() { return fEditorContextMenuId; } /** * Returns the ruler's context menu id. May return <code>null</code> before * the editor's part has been created. * * @return the ruler's context menu id which may be <code>null</code> */ protected final String getRulerContextMenuId() { return fRulerContextMenuId; } /** * Returns the editor's help context id or <code>null</code> if none has * been set. * * @return the editor's help context id which may be <code>null</code> */ protected final String getHelpContextId() { return fHelpContextId; } /** * Returns this editor's preference store or <code>null</code> if none has * been set. * * @return this editor's preference store which may be <code>null</code> */ protected final IPreferenceStore getPreferenceStore() { return fPreferenceStore; } /** * Sets this editor's document provider. This method must be * called before the editor's control is created. * * @param provider the document provider */ protected void setDocumentProvider(IDocumentProvider provider) { fExplicitDocumentProvider= provider; } /** * Sets this editor's source viewer configuration used to configure its * internal source viewer. This method must be called before the editor's * control is created. If not, this editor uses a <code>SourceViewerConfiguration</code>. * * @param configuration the source viewer configuration object */ protected void setSourceViewerConfiguration(SourceViewerConfiguration configuration) { Assert.isNotNull(configuration); fConfiguration= configuration; } /** * Sets the annotation which this editor uses to represent the highlight * range if the editor is configured to show the entire document. If the * range indicator is not set, this editor will not show a range indication. * * @param rangeIndicator the annotation */ protected void setRangeIndicator(Annotation rangeIndicator) { Assert.isNotNull(rangeIndicator); fRangeIndicator= rangeIndicator; } /** * Sets this editor's context menu id. * * @param contextMenuId the context menu id */ protected void setEditorContextMenuId(String contextMenuId) { Assert.isNotNull(contextMenuId); fEditorContextMenuId= contextMenuId; } /** * Sets the ruler's context menu id. * * @param contextMenuId the context menu id */ protected void setRulerContextMenuId(String contextMenuId) { Assert.isNotNull(contextMenuId); fRulerContextMenuId= contextMenuId; } /** * Sets the context menu registration 1.0 compatibility mode. (See class * description for more details.) * * @param compatible <code>true</code> if compatibility mode is enabled * @since 2.0 */ protected final void setCompatibilityMode(boolean compatible) { fCompatibilityMode= compatible; } /** * Sets the editor's help context id. * * @param helpContextId the help context id */ protected void setHelpContextId(String helpContextId) { Assert.isNotNull(helpContextId); fHelpContextId= helpContextId; } /** * Sets the key binding scopes for this editor. * * @param scopes a non-empty array of key binding scope identifiers * @since 2.1 */ protected void setKeyBindingScopes(String[] scopes) { Assert.isTrue(scopes != null && scopes.length > 0); fKeyBindingScopes= scopes; } /** * Sets this editor's preference store. This method must be * called before the editor's control is created. * * @param store the preference store or <code>null</code> to remove the * preference store */ protected void setPreferenceStore(IPreferenceStore store) { if (fPreferenceStore != null) fPreferenceStore.removePropertyChangeListener(fPropertyChangeListener); fPreferenceStore= store; if (fPreferenceStore != null) fPreferenceStore.addPropertyChangeListener(fPropertyChangeListener); } /* * @see ITextEditor#isEditable() */ public boolean isEditable() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IDocumentProviderExtension) { IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; return extension.isModifiable(getEditorInput()); } return false; } /** * {@inheritDoc} * <p> * Returns <code>null</code> after disposal. * </p> * * @return the selection provider or <code>null</code> if the editor has * been disposed */ public ISelectionProvider getSelectionProvider() { return fSelectionProvider; } /** * Remembers the current selection of this editor. This method is called when, e.g., * the content of the editor is about to be reverted to the saved state. This method * remembers the selection in a semantic format, i.e., in a format which allows to * restore the selection even if the originally selected text is no longer part of the * editor's content. * <p> * Subclasses should implement this method including all necessary state. This * default implementation remembers the textual range only and is thus purely * syntactic.</p> * * @see #restoreSelection() * @since 2.0 */ protected void rememberSelection() { fRememberedSelection= doGetSelection(); } /** * Returns the current selection. * @return ISelection * @since 2.1 */ protected ISelection doGetSelection() { ISelectionProvider sp= null; if (fSourceViewer != null) sp= fSourceViewer.getSelectionProvider(); return (sp == null ? null : sp.getSelection()); } /** * Restores a selection previously remembered by <code>rememberSelection</code>. * Subclasses may reimplement this method and thereby semantically adapt the * remembered selection. This default implementation just selects the * remembered textual range. * * @see #rememberSelection() * @since 2.0 */ protected void restoreSelection() { if (fRememberedSelection instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection)fRememberedSelection; if (isValidSelection(textSelection.getOffset(), textSelection.getLength())) doSetSelection(fRememberedSelection); } fRememberedSelection= null; } /** * Tells whether the given selection is valid. * * @param offset the offset of the selection * @param length the length of the selection * @return <code>true</code> if the selection is valid * @since 2.1 */ private boolean isValidSelection(int offset, int length) { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) { int end= offset + length; int documentLength= document.getLength(); return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength && length >= 0; } } return false; } /** * Sets the given selection. * @param selection * @since 2.1 */ protected void doSetSelection(ISelection selection) { if (selection instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection) selection; selectAndReveal(textSelection.getOffset(), textSelection.getLength()); } } /** * Creates and returns the listener on this editor's context menus. * * @return the menu listener */ protected final IMenuListener getContextMenuListener() { if (fMenuListener == null) { fMenuListener= new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { String id= menu.getId(); if (getRulerContextMenuId().equals(id)) { setFocus(); rulerContextMenuAboutToShow(menu); } else if (getEditorContextMenuId().equals(id)) { setFocus(); editorContextMenuAboutToShow(menu); } } }; } return fMenuListener; } /** * Creates and returns the listener on this editor's vertical ruler. * * @return the mouse listener */ protected final MouseListener getRulerMouseListener() { if (fMouseListener == null) { fMouseListener= new MouseListener() { private boolean fDoubleClicked= false; private final int fDoubleClickTime= Display.getDefault().getDoubleClickTime(); private long fMouseUpDelta= 0; private void triggerAction(String actionID) { IAction action= getAction(actionID); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) action.run(); } } public void mouseUp(final MouseEvent e) { setFocus(); final int delay= fDoubleClickTime - (int)(System.currentTimeMillis() - fMouseUpDelta); if (1 != e.button) return; Runnable runnable= new Runnable() { public void run() { if (!fDoubleClicked) triggerAction(ITextEditorActionConstants.RULER_CLICK); } }; if (delay <= 0) runnable.run(); else Display.getDefault().timerExec(delay, runnable); } public void mouseDoubleClick(MouseEvent e) { if (1 == e.button) { fDoubleClicked= true; triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK); } } public void mouseDown(MouseEvent e) { fMouseUpDelta= System.currentTimeMillis(); fDoubleClicked= false; StyledText text= fSourceViewer.getTextWidget(); if (text != null && !text.isDisposed()) { Display display= text.getDisplay(); Point location= display.getCursorLocation(); fRulerContextMenu.setLocation(location.x, location.y); } } }; } return fMouseListener; } /** * Returns this editor's selection changed listener to be installed * on the editor's source viewer. * * @return the listener */ protected final ISelectionChangedListener getSelectionChangedListener() { if (fSelectionChangedListener == null) { fSelectionChangedListener= new ISelectionChangedListener() { private Runnable fRunnable= new Runnable() { public void run() { // check whether editor has not been disposed yet if (fSourceViewer != null && fSourceViewer.getDocument() != null) { updateSelectionDependentActions(); } } }; private Display fDisplay; public void selectionChanged(SelectionChangedEvent event) { if (fDisplay == null) fDisplay= getSite().getShell().getDisplay(); fDisplay.asyncExec(fRunnable); handleCursorPositionChanged(); } }; } return fSelectionChangedListener; } /** * Returns this editor's "cursor" listener to be installed on the editor's * source viewer. This listener is listening to key and mouse button events. * It triggers the updating of the status line by calling * <code>handleCursorPositionChanged()</code>. * * @return the listener * @since 2.0 */ protected final ICursorListener getCursorListener() { if (fCursorListener == null) { fCursorListener= new ICursorListener() { public void keyPressed(KeyEvent e) { handleCursorPositionChanged(); } public void keyReleased(KeyEvent e) { } public void mouseDoubleClick(MouseEvent e) { } public void mouseDown(MouseEvent e) { } public void mouseUp(MouseEvent e) { handleCursorPositionChanged(); } }; } return fCursorListener; } /** * Implements the <code>init</code> method of <code>IEditorPart</code>. * Subclasses replacing <code>init</code> may choose to call this method in * their implementation. * * @param window the workbench window * @param site the editor's site * @param input the editor input for the editor being created * @throws PartInitException if {@link #doSetInput(IEditorInput)} fails or gets canceled * * @see org.eclipse.ui.IEditorPart#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) * @since 2.1 */ protected final void internalInit(IWorkbenchWindow window, final IEditorSite site, final IEditorInput input) throws PartInitException { IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (getDocumentProvider() instanceof IDocumentProviderExtension2) { IDocumentProviderExtension2 extension= (IDocumentProviderExtension2) getDocumentProvider(); extension.setProgressMonitor(monitor); } doSetInput(input); } catch (CoreException x) { throw new InvocationTargetException(x); } finally { if (getDocumentProvider() instanceof IDocumentProviderExtension2) { IDocumentProviderExtension2 extension= (IDocumentProviderExtension2) getDocumentProvider(); extension.setProgressMonitor(null); } } } }; try { // When using the progress service always a modal dialog pops up. The site should be asked for a runnable context // which could be the workbench window or the progress service, depending on what the site represents. // getSite().getWorkbenchWindow().getWorkbench().getProgressService().run(false, true, runnable); getSite().getWorkbenchWindow().run(false, true, runnable); } catch (InterruptedException x) { } catch (InvocationTargetException x) { Throwable t= x.getTargetException(); if (t instanceof CoreException) { /* /* XXX: Remove unpacking of CoreException once the following bug is * fixed: https://bugs.eclipse.org/bugs/show_bug.cgi?id=81640 */ CoreException e= (CoreException)t; IStatus status= e.getStatus(); if (status.getException() != null) throw new PartInitException(status); throw new PartInitException(new Status(status.getSeverity(), status.getPlugin(), status.getCode(), status.getMessage(), t)); } throw new PartInitException(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, EditorMessages.Editor_error_init, t)); } } /* * @see IEditorPart#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) */ public void init(final IEditorSite site, final IEditorInput input) throws PartInitException { setSite(site); internalInit(site.getWorkbenchWindow(), site, input); fActivationListener= new ActivationListener(site.getWorkbenchWindow().getPartService()); } /** * Creates the vertical ruler to be used by this editor. * Subclasses may re-implement this method. * * @return the vertical ruler */ protected IVerticalRuler createVerticalRuler() { return new VerticalRuler(VERTICAL_RULER_WIDTH); } /** * Adds enabled ruler contributions to the vertical ruler. Clients may extend or replace. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @param ruler the composite ruler to add contributions to * @since 3.3 */ protected void updateContributedRulerColumns(CompositeRuler ruler) { IColumnSupport support= (IColumnSupport)getAdapter(IColumnSupport.class); if (support == null) return; RulerColumnPreferenceAdapter adapter= null; if (fPreferenceStore != null) adapter= new RulerColumnPreferenceAdapter(getPreferenceStore(), PREFERENCE_RULER_CONTRIBUTIONS); RulerColumnRegistry registry= RulerColumnRegistry.getDefault(); List descriptors= registry.getColumnDescriptors(); for (Iterator it= descriptors.iterator(); it.hasNext();) { final RulerColumnDescriptor descriptor= (RulerColumnDescriptor) it.next(); support.setColumnVisible(descriptor, adapter == null || adapter.isEnabled(descriptor)); } } /** * Creates the column support to be used by this editor to manage the * contributed ruler columns. * Subclasses may re-implement this method using the {@link ColumnSupport}, * e.g. by returning <code>new ColumnSupport(this, RulerColumnRegistry.getDefault());</code>. * <p> * Out of the box this class does not install this support and hence this * implementation always returns <code>null</code>.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @return the column support or <code>null</code> if none * @since 3.3 */ protected IColumnSupport createColumnSupport() { return null; } /** * Creates the source viewer to be used by this editor. * Subclasses may re-implement this method. * * @param parent the parent control * @param ruler the vertical ruler * @param styles style bits, <code>SWT.WRAP</code> is currently not supported * @return the source viewer */ protected ISourceViewer createSourceViewer(Composite parent, IVerticalRuler ruler, int styles) { return new SourceViewer(parent, ruler, styles); } /** * Initializes the drag and drop support for the given viewer based on * provided editor adapter for drop target listeners. * * @param viewer the viewer * @since 3.0 */ protected void initializeDragAndDrop(ISourceViewer viewer) { IDragAndDropService dndService= (IDragAndDropService)getSite().getService(IDragAndDropService.class); if (dndService == null) return; ITextEditorDropTargetListener listener= (ITextEditorDropTargetListener) getAdapter(ITextEditorDropTargetListener.class); if (listener == null) { Object object= Platform.getAdapterManager().loadAdapter(this, "org.eclipse.ui.texteditor.ITextEditorDropTargetListener"); //$NON-NLS-1$ if (object instanceof ITextEditorDropTargetListener) listener= (ITextEditorDropTargetListener)object; } if (listener != null) dndService.addMergedDropTarget(viewer.getTextWidget(), DND.DROP_MOVE | DND.DROP_COPY, listener.getTransfers(), listener); IPreferenceStore store= getPreferenceStore(); if (store != null && store.getBoolean(PREFERENCE_TEXT_DRAG_AND_DROP_ENABLED)) installTextDragAndDrop(viewer); } /** * The <code>AbstractTextEditor</code> implementation of this * <code>IWorkbenchPart</code> method creates the vertical ruler and * source viewer. * <p> * Subclasses may extend this method. Besides extending this method, the * behavior of <code>createPartControl</code> may be customized by * calling, extending or replacing the following methods: <br> * Subclasses may supply customized implementations for some members using * the following methods before <code>createPartControl</code> is invoked: * <ul> * <li> * {@linkplain #setSourceViewerConfiguration(SourceViewerConfiguration) setSourceViewerConfiguration} * to supply a custom source viewer configuration,</li> * <li>{@linkplain #setRangeIndicator(Annotation) setRangeIndicator} to * provide a range indicator,</li> * <li>{@linkplain #setHelpContextId(String) setHelpContextId} to provide a * help context id,</li> * <li>{@linkplain #setEditorContextMenuId(String) setEditorContextMenuId} * to set a custom context menu id,</li> * <li>{@linkplain #setRulerContextMenuId(String) setRulerContextMenuId} to * set a custom ruler context menu id.</li> * </ul> * <br> * Subclasses may replace the following methods called from within * <code>createPartControl</code>: * <ul> * <li>{@linkplain #createVerticalRuler() createVerticalRuler} to supply a * custom vertical ruler,</li> * <li>{@linkplain #createSourceViewer(Composite, IVerticalRuler, int) createSourceViewer} * to supply a custom source viewer,</li> * <li>{@linkplain #getSelectionProvider() getSelectionProvider} to supply * a custom selection provider.</li> * </ul> * <br> * Subclasses may extend the following methods called from within * <code>createPartControl</code>: * <ul> * <li> * {@linkplain #initializeViewerColors(ISourceViewer) initializeViewerColors} * to customize the viewer color scheme (may also be replaced),</li> * <li> * {@linkplain #initializeDragAndDrop(ISourceViewer) initializeDragAndDrop} * to customize drag and drop (may also be replaced),</li> * <li>{@linkplain #createNavigationActions() createNavigationActions} to * add navigation actions,</li> * <li>{@linkplain #createActions() createActions} to add text editor * actions.</li> * </ul> * </p> * * @param parent the parent composite */ public void createPartControl(Composite parent) { fVerticalRuler= createVerticalRuler(); int styles= SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION; fSourceViewer= createSourceViewer(parent, fVerticalRuler, styles); if (fConfiguration == null) fConfiguration= new SourceViewerConfiguration(); fSourceViewer.configure(fConfiguration); if (fRangeIndicator != null) fSourceViewer.setRangeIndicator(fRangeIndicator); fSourceViewer.addTextListener(fTextListener); fSourceViewer.addTextInputListener(fTextListener); getSelectionProvider().addSelectionChangedListener(getSelectionChangedListener()); initializeViewerFont(fSourceViewer); initializeViewerColors(fSourceViewer); initializeFindScopeColor(fSourceViewer); initializeDragAndDrop(fSourceViewer); StyledText styledText= fSourceViewer.getTextWidget(); /* gestures commented out until proper solution (i.e. preference page) can be found * for bug # 28417: * final Map gestureMap= new HashMap(); gestureMap.put("E", "org.eclipse.ui.navigate.forwardHistory"); gestureMap.put("N", "org.eclipse.ui.file.save"); gestureMap.put("NW", "org.eclipse.ui.file.saveAll"); gestureMap.put("S", "org.eclipse.ui.file.close"); gestureMap.put("SW", "org.eclipse.ui.file.closeAll"); gestureMap.put("W", "org.eclipse.ui.navigate.backwardHistory"); gestureMap.put("EN", "org.eclipse.ui.edit.copy"); gestureMap.put("ES", "org.eclipse.ui.edit.paste"); gestureMap.put("EW", "org.eclipse.ui.edit.cut"); Capture capture= Capture.create(); capture.setControl(styledText); capture.addCaptureListener(new CaptureListener() { public void gesture(Gesture gesture) { if (gesture.getPen() == 3) { String actionId= (String) gestureMap.get(Util.recognize(gesture.getPoints(), 20)); if (actionId != null) { IKeyBindingService keyBindingService= getEditorSite().getKeyBindingService(); if (keyBindingService instanceof KeyBindingService) { IAction action= ((KeyBindingService) keyBindingService).getAction(actionId); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); if (action.isEnabled()) action.run(); } } return; } fTextContextMenu.setVisible(true); } }; }); */ styledText.addMouseListener(getCursorListener()); styledText.addKeyListener(getCursorListener()); if (getHelpContextId() != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(styledText, getHelpContextId()); String id= fEditorContextMenuId != null ? fEditorContextMenuId : DEFAULT_EDITOR_CONTEXT_MENU_ID; MenuManager manager= new MenuManager(id, id); manager.setRemoveAllWhenShown(true); manager.addMenuListener(getContextMenuListener()); fTextContextMenu= manager.createContextMenu(styledText); // comment this line if using gestures, above. styledText.setMenu(fTextContextMenu); if (fEditorContextMenuId != null) getEditorSite().registerContextMenu(fEditorContextMenuId, manager, getSelectionProvider(), isEditorInputIncludedInContextMenu()); else if (fCompatibilityMode) getEditorSite().registerContextMenu(DEFAULT_EDITOR_CONTEXT_MENU_ID, manager, getSelectionProvider(), isEditorInputIncludedInContextMenu()); if ((fEditorContextMenuId != null && fCompatibilityMode) || fEditorContextMenuId == null) { String partId= getEditorSite().getId(); if (partId != null) getEditorSite().registerContextMenu(partId + ".EditorContext", manager, getSelectionProvider(), isEditorInputIncludedInContextMenu()); //$NON-NLS-1$ } if (fEditorContextMenuId == null) fEditorContextMenuId= DEFAULT_EDITOR_CONTEXT_MENU_ID; id= fRulerContextMenuId != null ? fRulerContextMenuId : DEFAULT_RULER_CONTEXT_MENU_ID; manager= new MenuManager(id, id); manager.setRemoveAllWhenShown(true); manager.addMenuListener(getContextMenuListener()); Control rulerControl= fVerticalRuler.getControl(); fRulerContextMenu= manager.createContextMenu(rulerControl); rulerControl.setMenu(fRulerContextMenu); rulerControl.addMouseListener(getRulerMouseListener()); if (fRulerContextMenuId != null) getEditorSite().registerContextMenu(fRulerContextMenuId, manager, getSelectionProvider(), false); else if (fCompatibilityMode) getEditorSite().registerContextMenu(DEFAULT_RULER_CONTEXT_MENU_ID, manager, getSelectionProvider(), false); if ((fRulerContextMenuId != null && fCompatibilityMode) || fRulerContextMenuId == null) { String partId= getSite().getId(); if (partId != null) getEditorSite().registerContextMenu(partId + ".RulerContext", manager, getSelectionProvider(), false); //$NON-NLS-1$ } if (fRulerContextMenuId == null) fRulerContextMenuId= DEFAULT_RULER_CONTEXT_MENU_ID; getSite().setSelectionProvider(getSelectionProvider()); fSelectionListener= new SelectionListener(); fSelectionListener.install(getSelectionProvider()); fSelectionListener.setDocument(getDocumentProvider().getDocument(getEditorInput())); initializeActivationCodeTrigger(); createNavigationActions(); createAccessibilityActions(); createActions(); initializeSourceViewer(getEditorInput()); /* since 3.2 - undo redo actions should be created after * the source viewer is initialized, so that the undo manager * can obtain its undo context from its document. */ createUndoRedoActions(); JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener); IVerticalRuler ruler= getVerticalRuler(); if (ruler instanceof CompositeRuler) updateContributedRulerColumns((CompositeRuler) ruler); } /** * Installs text drag and drop. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param viewer the viewer * @since 3.3 */ protected void installTextDragAndDrop(ISourceViewer viewer) { final IDragAndDropService dndService= (IDragAndDropService)getSite().getService(IDragAndDropService.class); if (dndService == null || viewer == null) return; // XXX: This is only a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=162192 fIsTextDragAndDropEnabled= true; final StyledText st= viewer.getTextWidget(); // Install drag source final DragSource source= new DragSource(st, DND.DROP_COPY | DND.DROP_MOVE); source.setTransfer(new Transfer[] {TextTransfer.getInstance()}); source.addDragListener(new DragSourceAdapter() { String selectedText; Point selection; public void dragStart(DragSourceEvent event) { // XXX: This is only a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=162192 if (!fIsTextDragAndDropEnabled) { event.doit= false; event.feedback= DND.FEEDBACK_NONE; return; } try { selection= st.getSelection(); int offset= st.getOffsetAtLocation(new Point(event.x, event.y)); Point p= st.getLocationAtOffset(offset); if (p.x > event.x) offset--; event.doit= offset > selection.x && offset < selection.y; selectedText= st.getSelectionText(); } catch (IllegalArgumentException ex) { event.doit= false; } } public void dragSetData(DragSourceEvent event) { event.data= selectedText; } public void dragFinished(DragSourceEvent event) { if (event.detail == DND.DROP_MOVE) { Point newSelection= st.getSelection(); int length= selection.y - selection.x; int delta= 0; if (newSelection.x < selection.x) delta= length; st.replaceTextRange(selection.x + delta, length, ""); //$NON-NLS-1$ } } }); // Install drag target DropTargetListener dropTargetListener= new DropTargetAdapter() { public void dragEnter(DropTargetEvent event) { // XXX: This is only a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=162192 if (!fIsTextDragAndDropEnabled) { event.detail= DND.DROP_NONE; event.feedback= DND.FEEDBACK_NONE; return; } if (event.detail == DND.DROP_DEFAULT) event.detail= DND.DROP_MOVE; } public void dragOperationChanged(DropTargetEvent event) { if (!fIsTextDragAndDropEnabled) { event.detail= DND.DROP_NONE; event.feedback= DND.FEEDBACK_NONE; return; } if (event.detail == DND.DROP_DEFAULT) event.detail= DND.DROP_MOVE; } public void dragOver(DropTargetEvent event) { // XXX: This is only a workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=162192 if (!fIsTextDragAndDropEnabled) { event.feedback= DND.FEEDBACK_NONE; return; } event.feedback |= DND.FEEDBACK_SCROLL; } public void drop(DropTargetEvent event) { if (!fIsTextDragAndDropEnabled) return; String text= (String)event.data; Point newSelection= st.getSelection(); st.insert(text); st.setSelectionRange(newSelection.x, text.length()); } }; dndService.addMergedDropTarget(st, DND.DROP_MOVE | DND.DROP_COPY, new Transfer[] {TextTransfer.getInstance()}, dropTargetListener); } /** * Uninstalls text drag and drop. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param viewer the viewer * @since 3.3 */ protected void uninstallTextDragAndDrop(ISourceViewer viewer) { fIsTextDragAndDropEnabled= false; } /** * Tells whether the editor input should be included when adding object * contributions to this editor's context menu. * <p> * This implementation always returns <code>true</code>. * </p> * * @return <code>true</code> if the editor input should be considered * @since 3.2 */ protected boolean isEditorInputIncludedInContextMenu() { return true; } /** * Initializes the activation code trigger. * * @since 2.1 */ private void initializeActivationCodeTrigger() { fActivationCodeTrigger.install(); fActivationCodeTrigger.setScopes(fKeyBindingScopes); } /** * Initializes the given viewer's font. * * @param viewer the viewer * @since 2.0 */ private void initializeViewerFont(ISourceViewer viewer) { boolean isSharedFont= true; Font font= null; String symbolicFontName= getSymbolicFontName(); if (symbolicFontName != null) font= JFaceResources.getFont(symbolicFontName); else if (fPreferenceStore != null) { // Backward compatibility if (fPreferenceStore.contains(JFaceResources.TEXT_FONT) && !fPreferenceStore.isDefault(JFaceResources.TEXT_FONT)) { FontData data= PreferenceConverter.getFontData(fPreferenceStore, JFaceResources.TEXT_FONT); if (data != null) { isSharedFont= false; font= new Font(viewer.getTextWidget().getDisplay(), data); } } } if (font == null) font= JFaceResources.getTextFont(); setFont(viewer, font); if (fFont != null) { fFont.dispose(); fFont= null; } if (!isSharedFont) fFont= font; } /** * Sets the font for the given viewer sustaining selection and scroll position. * * @param sourceViewer the source viewer * @param font the font * @since 2.0 */ private void setFont(ISourceViewer sourceViewer, Font font) { if (sourceViewer.getDocument() != null) { Point selection= sourceViewer.getSelectedRange(); int topIndex= sourceViewer.getTopIndex(); StyledText styledText= sourceViewer.getTextWidget(); Control parent= styledText; if (sourceViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) sourceViewer; parent= extension.getControl(); } parent.setRedraw(false); styledText.setFont(font); if (fVerticalRuler instanceof IVerticalRulerExtension) { IVerticalRulerExtension e= (IVerticalRulerExtension) fVerticalRuler; e.setFont(font); } sourceViewer.setSelectedRange(selection.x , selection.y); sourceViewer.setTopIndex(topIndex); if (parent instanceof Composite) { Composite composite= (Composite) parent; composite.layout(true); } parent.setRedraw(true); } else { StyledText styledText= sourceViewer.getTextWidget(); styledText.setFont(font); if (fVerticalRuler instanceof IVerticalRulerExtension) { IVerticalRulerExtension e= (IVerticalRulerExtension) fVerticalRuler; e.setFont(font); } } } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. * * @param store the store to read from * @param key the key used for the lookup in the preference store * @param display the display used create the color * @return the created color according to the specification in the preference store * @since 2.0 */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } /** * Initializes the fore- and background colors of the given viewer for both * normal and selected text. * * @param viewer the viewer to be initialized * @since 2.0 */ protected void initializeViewerColors(ISourceViewer viewer) { IPreferenceStore store= getPreferenceStore(); if (store != null) { StyledText styledText= viewer.getTextWidget(); // ----------- foreground color -------------------- Color color= store.getBoolean(PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT) ? null : createColor(store, PREFERENCE_COLOR_FOREGROUND, styledText.getDisplay()); styledText.setForeground(color); if (fForegroundColor != null) fForegroundColor.dispose(); fForegroundColor= color; // ---------- background color ---------------------- color= store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) ? null : createColor(store, PREFERENCE_COLOR_BACKGROUND, styledText.getDisplay()); styledText.setBackground(color); if (fBackgroundColor != null) fBackgroundColor.dispose(); fBackgroundColor= color; // ----------- selection foreground color -------------------- color= store.getBoolean(PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT) ? null : createColor(store, PREFERENCE_COLOR_SELECTION_FOREGROUND, styledText.getDisplay()); styledText.setSelectionForeground(color); if (fSelectionForegroundColor != null) fSelectionForegroundColor.dispose(); fSelectionForegroundColor= color; // ---------- selection background color ---------------------- color= store.getBoolean(PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT) ? null : createColor(store, PREFERENCE_COLOR_SELECTION_BACKGROUND, styledText.getDisplay()); styledText.setSelectionBackground(color); if (fSelectionBackgroundColor != null) fSelectionBackgroundColor.dispose(); fSelectionBackgroundColor= color; } } /** * Initializes the background color used for highlighting the document ranges * defining search scopes. * * @param viewer the viewer to initialize * @since 2.0 */ private void initializeFindScopeColor(ISourceViewer viewer) { IPreferenceStore store= getPreferenceStore(); if (store != null) { StyledText styledText= viewer.getTextWidget(); Color color= createColor(store, PREFERENCE_COLOR_FIND_SCOPE, styledText.getDisplay()); IFindReplaceTarget target= viewer.getFindReplaceTarget(); if (target != null && target instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) target).setScopeHighlightColor(color); if (fFindScopeHighlightColor != null) fFindScopeHighlightColor.dispose(); fFindScopeHighlightColor= color; } } /** * Initializes the editor's source viewer based on the given editor input. * * @param input the editor input to be used to initialize the source viewer */ private void initializeSourceViewer(IEditorInput input) { IAnnotationModel model= getDocumentProvider().getAnnotationModel(input); IDocument document= getDocumentProvider().getDocument(input); if (document != null) { fSourceViewer.setDocument(document, model); fSourceViewer.setEditable(isEditable()); fSourceViewer.showAnnotations(model != null); } if (fElementStateListener instanceof IElementStateListenerExtension) { IElementStateListenerExtension extension= (IElementStateListenerExtension) fElementStateListener; extension.elementStateValidationChanged(input, false); } if (fInitialCaret == null) fInitialCaret= fSourceViewer.getTextWidget().getCaret(); if (fIsOverwriting) fSourceViewer.getTextWidget().invokeAction(ST.TOGGLE_OVERWRITE); handleInsertModeChanged(); } /** * Initializes the editor's title based on the given editor input. * * @param input the editor input to be used */ private void initializeTitle(IEditorInput input) { Image oldImage= fTitleImage; fTitleImage= null; String title= ""; //$NON-NLS-1$ if (input != null) { IEditorRegistry editorRegistry= PlatformUI.getWorkbench().getEditorRegistry(); IEditorDescriptor editorDesc= editorRegistry.findEditor(getSite().getId()); ImageDescriptor imageDesc= editorDesc != null ? editorDesc.getImageDescriptor() : null; fTitleImage= imageDesc != null ? imageDesc.createImage() : null; title= input.getName(); } setTitleImage(fTitleImage); setPartName(title); firePropertyChange(PROP_DIRTY); if (oldImage != null && !oldImage.isDisposed()) oldImage.dispose(); } /** * Hook method for setting the document provider for the given input. * This default implementation does nothing. Clients may * reimplement. * * @param input the input of this editor. * @since 3.0 */ protected void setDocumentProvider(IEditorInput input) { } /** * If there is no explicit document provider set, the implicit one is * re-initialized based on the given editor input. * * @param input the editor input. */ private void updateDocumentProvider(IEditorInput input) { IProgressMonitor rememberedProgressMonitor= null; IDocumentProvider provider= getDocumentProvider(); if (provider != null) { provider.removeElementStateListener(fElementStateListener); if (provider instanceof IDocumentProviderExtension2) { IDocumentProviderExtension2 extension= (IDocumentProviderExtension2) provider; rememberedProgressMonitor= extension.getProgressMonitor(); extension.setProgressMonitor(null); } } setDocumentProvider(input); provider= getDocumentProvider(); if (provider != null) { provider.addElementStateListener(fElementStateListener); if (provider instanceof IDocumentProviderExtension2) { IDocumentProviderExtension2 extension= (IDocumentProviderExtension2) provider; extension.setProgressMonitor(rememberedProgressMonitor); } } } /** * Called directly from <code>setInput</code> and from within a workspace * runnable from <code>init</code>, this method does the actual setting * of the editor input. Closes the editor if <code>input</code> is * <code>null</code>. Disconnects from any previous editor input and its * document provider and connects to the new one. * <p> * Subclasses may extend. * </p> * * @param input the input to be set * @exception CoreException if input cannot be connected to the document * provider */ protected void doSetInput(IEditorInput input) throws CoreException { ISaveablesLifecycleListener listener= (ISaveablesLifecycleListener)getSite().getService(ISaveablesLifecycleListener.class); if (listener == null) fSavable= null; if (input == null) { close(isSaveOnCloseNeeded()); if (fSavable != null) { listener.handleLifecycleEvent(new SaveablesLifecycleEvent(this, SaveablesLifecycleEvent.POST_CLOSE, getSaveables(), false)); fSavable= null; } } else { if (fSavable != null) { listener.handleLifecycleEvent(new SaveablesLifecycleEvent(this, SaveablesLifecycleEvent.POST_CLOSE, getSaveables(), false)); fSavable= null; } IEditorInput oldInput= getEditorInput(); if (oldInput != null) getDocumentProvider().disconnect(oldInput); super.setInput(input); updateDocumentProvider(input); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { IStatus s= new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.OK, EditorMessages.Editor_error_no_provider, null); throw new CoreException(s); } provider.connect(input); initializeTitle(input); if (fSourceViewer != null) { initializeSourceViewer(input); // Reset the undo context for the undo and redo action handlers IAction undoAction= getAction(ITextEditorActionConstants.UNDO); IAction redoAction= getAction(ITextEditorActionConstants.REDO); boolean areOperationActionHandlersInstalled= undoAction instanceof OperationHistoryActionHandler && redoAction instanceof OperationHistoryActionHandler; IUndoContext undoContext= getUndoContext(); if (undoContext != null && areOperationActionHandlersInstalled) { ((OperationHistoryActionHandler)undoAction).setContext(undoContext); ((OperationHistoryActionHandler)redoAction).setContext(undoContext); } else { createUndoRedoActions(); } } if (fIsOverwriting) toggleOverwriteMode(); setInsertMode((InsertMode) getLegalInsertModes().get(0)); updateCaret(); updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_ELEMENT_STATE); if (fSelectionListener != null) fSelectionListener.setDocument(getDocumentProvider().getDocument(input)); IVerticalRuler ruler= getVerticalRuler(); if (ruler instanceof CompositeRuler) updateContributedRulerColumns((CompositeRuler) ruler); // Send savable life-cycle event if (listener != null) listener.handleLifecycleEvent(new SaveablesLifecycleEvent(this, SaveablesLifecycleEvent.POST_OPEN, getSaveables(), false)); } } /** * Returns this editor's viewer's undo manager undo context. * * @return the undo context or <code>null</code> if not available * @since 3.1 */ private IUndoContext getUndoContext() { if (fSourceViewer instanceof ITextViewerExtension6) { IUndoManager undoManager= ((ITextViewerExtension6)fSourceViewer).getUndoManager(); if (undoManager instanceof IUndoManagerExtension) return ((IUndoManagerExtension)undoManager).getUndoContext(); } return null; } /* * @see org.eclipse.ui.part.EditorPart#setInputWithNotify(org.eclipse.ui.IEditorInput) * @since 3.2 */ protected final void setInputWithNotify(IEditorInput input) { try { doSetInput(input); /* * The following bugs explain why we fire this property change: * https://bugs.eclipse.org/bugs/show_bug.cgi?id=90283 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=92049 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=92286 */ firePropertyChange(IEditorPart.PROP_INPUT); } catch (CoreException x) { String title= EditorMessages.Editor_error_setinput_title; String msg= EditorMessages.Editor_error_setinput_message; Shell shell= getSite().getShell(); ErrorDialog.openError(shell, title, msg, x.getStatus()); } } /* * @see EditorPart#setInput(org.eclipse.ui.IEditorInput) */ public final void setInput(IEditorInput input) { setInputWithNotify(input); } /* * @see ITextEditor#close */ public void close(final boolean save) { enableSanityChecking(false); Display display= getSite().getShell().getDisplay(); display.asyncExec(new Runnable() { public void run() { if (fSourceViewer != null) getSite().getPage().closeEditor(AbstractTextEditor.this, save); } }); } /** * The <code>AbstractTextEditor</code> implementation of this * <code>IWorkbenchPart</code> method may be extended by subclasses. * Subclasses must call <code>super.dispose()</code>. * <p> * Note that many methods may return <code>null</code> after the editor is * disposed. * </p> */ public void dispose() { if (fActivationListener != null) { fActivationListener.dispose(); fActivationListener= null; } if (fTitleImage != null) { fTitleImage.dispose(); fTitleImage= null; } if (fFont != null) { fFont.dispose(); fFont= null; } disposeNonDefaultCaret(); fInitialCaret= null; if (fForegroundColor != null) { fForegroundColor.dispose(); fForegroundColor= null; } if (fBackgroundColor != null) { fBackgroundColor.dispose(); fBackgroundColor= null; } if (fSelectionForegroundColor != null) { fSelectionForegroundColor.dispose(); fSelectionForegroundColor= null; } if (fSelectionBackgroundColor != null) { fSelectionBackgroundColor.dispose(); fSelectionBackgroundColor= null; } if (fFindScopeHighlightColor != null) { fFindScopeHighlightColor.dispose(); fFindScopeHighlightColor= null; } if (fFontPropertyChangeListener != null) { JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); fFontPropertyChangeListener= null; } if (fPropertyChangeListener != null) { if (fPreferenceStore != null) { fPreferenceStore.removePropertyChangeListener(fPropertyChangeListener); fPreferenceStore= null; } fPropertyChangeListener= null; } if (fActivationCodeTrigger != null) { fActivationCodeTrigger.uninstall(); fActivationCodeTrigger= null; } if (fSelectionListener != null) { fSelectionListener.uninstall(getSelectionProvider()); fSelectionListener= null; } if (fSavable != null) { ISaveablesLifecycleListener listener= (ISaveablesLifecycleListener)getSite().getService(ISaveablesLifecycleListener.class); if (listener != null) listener.handleLifecycleEvent(new SaveablesLifecycleEvent(this, SaveablesLifecycleEvent.POST_CLOSE, getSaveables(), false)); fSavable= null; } disposeDocumentProvider(); if (fSourceViewer != null) { if (fTextListener != null) { fSourceViewer.removeTextListener(fTextListener); fSourceViewer.removeTextInputListener(fTextListener); fTextListener= null; } fTextInputListener= null; fSelectionProvider= null; fSourceViewer= null; } if (fTextContextMenu != null) { fTextContextMenu.dispose(); fTextContextMenu= null; } if (fRulerContextMenu != null) { fRulerContextMenu.dispose(); fRulerContextMenu= null; } if (fActions != null) { fActions.clear(); fActions= null; } if (fSelectionActions != null) { fSelectionActions.clear(); fSelectionActions= null; } if (fContentActions != null) { fContentActions.clear(); fContentActions= null; } if (fPropertyActions != null) { fPropertyActions.clear(); fPropertyActions= null; } if (fStateActions != null) { fStateActions.clear(); fStateActions= null; } if (fActivationCodes != null) { fActivationCodes.clear(); fActivationCodes= null; } if (fEditorStatusLine != null) fEditorStatusLine= null; if (fConfiguration != null) fConfiguration= null; if (fColumnSupport != null) { fColumnSupport.dispose(); fColumnSupport= null; } if (fVerticalRuler != null) fVerticalRuler= null; IOperationHistory history= OperationHistoryFactory.getOperationHistory(); if (history != null) { if (fNonLocalOperationApprover != null) history.removeOperationApprover(fNonLocalOperationApprover); if (fLinearUndoViolationApprover != null) history.removeOperationApprover(fLinearUndoViolationApprover); } fNonLocalOperationApprover= null; fLinearUndoViolationApprover= null; super.dispose(); } /** * Disposes of the connection with the document provider. Subclasses * may extend. * * @since 3.0 */ protected void disposeDocumentProvider() { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IEditorInput input= getEditorInput(); if (input != null) provider.disconnect(input); if (fElementStateListener != null) { provider.removeElementStateListener(fElementStateListener); fElementStateListener= null; } } fExplicitDocumentProvider= null; } /** * Determines whether the given preference change affects the editor's * presentation. This implementation always returns <code>false</code>. * May be reimplemented by subclasses. * * @param event the event which should be investigated * @return <code>true</code> if the event describes a preference change affecting the editor's presentation * @since 2.0 */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { return false; } /** * Returns the symbolic font name for this editor as defined in XML. * * @return a String with the symbolic font name or <code>null</code> if * none is defined * @since 2.1 */ private String getSymbolicFontName() { if (getConfigurationElement() != null) return getConfigurationElement().getAttribute("symbolicFontName"); //$NON-NLS-1$ return null; } /** * Returns the property preference key for the editor font. Subclasses may * replace this method. * * @return a String with the key * @since 2.1 */ protected final String getFontPropertyPreferenceKey() { String symbolicFontName= getSymbolicFontName(); if (symbolicFontName != null) return symbolicFontName; return JFaceResources.TEXT_FONT; } /** * Handles a property change event describing a change of the editor's * preference store and updates the preference related editor properties. * <p> * Subclasses may extend. * </p> * * @param event the property change event */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { if (fSourceViewer == null) return; String property= event.getProperty(); if (getFontPropertyPreferenceKey().equals(property)) // There is a separate handler for font preference changes return; if (PREFERENCE_COLOR_FOREGROUND.equals(property) || PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_BACKGROUND.equals(property) || PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_SELECTION_FOREGROUND.equals(property) || PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT.equals(property) || PREFERENCE_COLOR_SELECTION_BACKGROUND.equals(property) || PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT.equals(property)) { initializeViewerColors(fSourceViewer); } else if (PREFERENCE_COLOR_FIND_SCOPE.equals(property)) { initializeFindScopeColor(fSourceViewer); } else if (PREFERENCE_USE_CUSTOM_CARETS.equals(property)) { updateCaret(); } else if (PREFERENCE_WIDE_CARET.equals(property)) { updateCaret(); } if (affectsTextPresentation(event)) fSourceViewer.invalidateTextPresentation(); if (PREFERENCE_HYPERLINKS_ENABLED.equals(property)) { if (fSourceViewer instanceof ITextViewerExtension6) { IHyperlinkDetector[] detectors= getSourceViewerConfiguration().getHyperlinkDetectors(fSourceViewer); int stateMask= getSourceViewerConfiguration().getHyperlinkStateMask(fSourceViewer); ITextViewerExtension6 textViewer6= (ITextViewerExtension6)fSourceViewer; textViewer6.setHyperlinkDetectors(detectors, stateMask); } return; } if (PREFERENCE_HYPERLINK_KEY_MODIFIER.equals(property)) { if (fSourceViewer instanceof ITextViewerExtension6) { ITextViewerExtension6 textViewer6= (ITextViewerExtension6)fSourceViewer; IHyperlinkDetector[] detectors= getSourceViewerConfiguration().getHyperlinkDetectors(fSourceViewer); int stateMask= getSourceViewerConfiguration().getHyperlinkStateMask(fSourceViewer); textViewer6.setHyperlinkDetectors(detectors, stateMask); } return; } if (PREFERENCE_RULER_CONTRIBUTIONS.equals(property)) { String[] difference= StringSetSerializer.getDifference((String) event.getOldValue(), (String) event.getNewValue()); IColumnSupport support= (IColumnSupport) getAdapter(IColumnSupport.class); for (int i= 0; i < difference.length; i++) { RulerColumnDescriptor desc= RulerColumnRegistry.getDefault().getColumnDescriptor(difference[i]); if (desc != null && support.isColumnSupported(desc)) { boolean newState= !support.isColumnVisible(desc); support.setColumnVisible(desc, newState); } } return; } if (PREFERENCE_SHOW_WHITESPACE_CHARACTERS.equals(property)) { IAction action= getAction(ITextEditorActionConstants.SHOW_WHITESPACE_CHARACTERS); if (action instanceof IUpdate) ((IUpdate)action).update(); return; } if (PREFERENCE_TEXT_DRAG_AND_DROP_ENABLED.equals(property)) { IPreferenceStore store= getPreferenceStore(); if (store != null && store.getBoolean(PREFERENCE_TEXT_DRAG_AND_DROP_ENABLED)) installTextDragAndDrop(getSourceViewer()); else uninstallTextDragAndDrop(getSourceViewer()); return; } } /** * Returns the progress monitor related to this editor. It should not be * necessary to extend this method. * * @return the progress monitor related to this editor * @since 2.1 */ protected IProgressMonitor getProgressMonitor() { IProgressMonitor pm= null; IStatusLineManager manager= getStatusLineManager(); if (manager != null) pm= manager.getProgressMonitor(); return pm != null ? pm : new NullProgressMonitor(); } /** * Handles an external change of the editor's input element. Subclasses may * extend. */ protected void handleEditorInputChanged() { String title; String msg; Shell shell= getSite().getShell(); final IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=15066 close(false); return; } final IEditorInput input= getEditorInput(); if (provider.isDeleted(input)) { if (isSaveAsAllowed()) { title= EditorMessages.Editor_error_activated_deleted_save_title; msg= EditorMessages.Editor_error_activated_deleted_save_message; String[] buttons= { EditorMessages.Editor_error_activated_deleted_save_button_save, EditorMessages.Editor_error_activated_deleted_save_button_close, }; MessageDialog dialog= new MessageDialog(shell, title, null, msg, MessageDialog.QUESTION, buttons, 0); if (dialog.open() == 0) { IProgressMonitor pm= getProgressMonitor(); performSaveAs(pm); if (pm.isCanceled()) handleEditorInputChanged(); } else { close(false); } } else { title= EditorMessages.Editor_error_activated_deleted_close_title; msg= EditorMessages.Editor_error_activated_deleted_close_message; if (MessageDialog.openConfirm(shell, title, msg)) close(false); } } else { title= EditorMessages.Editor_error_activated_outofsync_title; msg= EditorMessages.Editor_error_activated_outofsync_message; if (MessageDialog.openQuestion(shell, title, msg)) { try { if (provider instanceof IDocumentProviderExtension) { IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; extension.synchronize(input); } else { doSetInput(input); } } catch (CoreException x) { IStatus status= x.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL) { title= EditorMessages.Editor_error_refresh_outofsync_title; msg= EditorMessages.Editor_error_refresh_outofsync_message; ErrorDialog.openError(shell, title, msg, x.getStatus()); } } } } } /** * The <code>AbstractTextEditor</code> implementation of this * <code>IEditorPart</code> method calls <code>performSaveAs</code>. * Subclasses may reimplement. */ public void doSaveAs() { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(getProgressMonitor()); } /** * Performs a save as and reports the result state back to the * given progress monitor. This default implementation does nothing. * Subclasses may reimplement. * * @param progressMonitor the progress monitor for communicating result state or <code>null</code> */ protected void performSaveAs(IProgressMonitor progressMonitor) { } /** * The <code>AbstractTextEditor</code> implementation of this * <code>IEditorPart</code> method may be extended by subclasses. * * @param progressMonitor the progress monitor for communicating result state or <code>null</code> */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) return; if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { Shell shell= getSite().getShell(); String title= EditorMessages.Editor_error_save_deleted_title; String msg= EditorMessages.Editor_error_save_deleted_message; MessageDialog.openError(shell, title, msg); } } else { updateState(getEditorInput()); validateState(getEditorInput()); performSave(false, progressMonitor); } } /** * Enables/disables sanity checking. * @param enable <code>true</code> if sanity checking should be enabled, <code>false</code> otherwise * @since 2.0 */ protected void enableSanityChecking(boolean enable) { synchronized (this) { fIsSanityCheckEnabled= enable; } } /** * Checks the state of the given editor input if sanity checking is enabled. * @param input the editor input whose state is to be checked * @since 2.0 */ protected void safelySanityCheckState(IEditorInput input) { boolean enabled= false; synchronized (this) { enabled= fIsSanityCheckEnabled; } if (enabled) sanityCheckState(input); } /** * Checks the state of the given editor input. * @param input the editor input whose state is to be checked * @since 2.0 */ protected void sanityCheckState(IEditorInput input) { IDocumentProvider p= getDocumentProvider(); if (p == null) return; if (p instanceof IDocumentProviderExtension3) { IDocumentProviderExtension3 p3= (IDocumentProviderExtension3) p; long stamp= p.getModificationStamp(input); if (stamp != fModificationStamp) { fModificationStamp= stamp; if (!p3.isSynchronized(input)) handleEditorInputChanged(); } } else { if (fModificationStamp == -1) fModificationStamp= p.getSynchronizationStamp(input); long stamp= p.getModificationStamp(input); if (stamp != fModificationStamp) { fModificationStamp= stamp; if (stamp != p.getSynchronizationStamp(input)) handleEditorInputChanged(); } } updateState(getEditorInput()); updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_ELEMENT_STATE); } /** * Enables/disables state validation. * @param enable <code>true</code> if state validation should be enabled, <code>false</code> otherwise * @since 2.1 */ protected void enableStateValidation(boolean enable) { synchronized (this) { fIsStateValidationEnabled= enable; } } /** * Validates the state of the given editor input. The predominate intent * of this method is to take any action probably necessary to ensure that * the input can persistently be changed. * * @param input the input to be validated * @since 2.0 */ protected void validateState(IEditorInput input) { IDocumentProvider provider= getDocumentProvider(); if (! (provider instanceof IDocumentProviderExtension)) return; IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; try { extension.validateState(input, getSite().getShell()); } catch (CoreException x) { IStatus status= x.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL) { Bundle bundle= Platform.getBundle(PlatformUI.PLUGIN_ID); ILog log= Platform.getLog(bundle); log.log(x.getStatus()); Shell shell= getSite().getShell(); String title= EditorMessages.Editor_error_validateEdit_title; String msg= EditorMessages.Editor_error_validateEdit_message; ErrorDialog.openError(shell, title, msg, x.getStatus()); } return; } if (fSourceViewer != null) fSourceViewer.setEditable(isEditable()); updateStateDependentActions(); } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension2#validateEditorInputState() * @since 2.1 */ public boolean validateEditorInputState() { boolean enabled= false; synchronized (this) { enabled= fIsStateValidationEnabled; } if (enabled) { ISourceViewer viewer= fSourceViewer; if (viewer == null) return false; fTextInputListener.inputChanged= false; viewer.addTextInputListener(fTextInputListener); try { final IEditorInput input= getEditorInput(); BusyIndicator.showWhile(getSite().getShell().getDisplay(), new Runnable() { /* * @see java.lang.Runnable#run() */ public void run() { validateState(input); } }); sanityCheckState(input); return !isEditorInputReadOnly() && !fTextInputListener.inputChanged; } finally { viewer.removeTextInputListener(fTextInputListener); } } return !isEditorInputReadOnly(); } /** * Updates the state of the given editor input such as read-only flag. * * @param input the input to be validated * @since 2.0 */ protected void updateState(IEditorInput input) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IDocumentProviderExtension) { IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; try { boolean wasReadOnly= isEditorInputReadOnly(); extension.updateStateCache(input); if (fSourceViewer != null) fSourceViewer.setEditable(isEditable()); if (wasReadOnly != isEditorInputReadOnly()) updateStateDependentActions(); } catch (CoreException x) { Bundle bundle= Platform.getBundle(PlatformUI.PLUGIN_ID); ILog log= Platform.getLog(bundle); log.log(x.getStatus()); } } } /** * Performs the save and handles errors appropriately. * * @param overwrite indicates whether or not overwriting is allowed * @param progressMonitor the monitor in which to run the operation * @since 3.0 */ protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) { IDocumentProvider provider= getDocumentProvider(); if (provider == null) return; try { provider.aboutToChange(getEditorInput()); IEditorInput input= getEditorInput(); provider.saveDocument(progressMonitor, input, getDocumentProvider().getDocument(input), overwrite); editorSaved(); } catch (CoreException x) { IStatus status= x.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL) handleExceptionOnSave(x, progressMonitor); } finally { provider.changed(getEditorInput()); } } /** * Handles the given exception. If the exception reports an out-of-sync * situation, this is reported to the user. Otherwise, the exception * is generically reported. * * @param exception the exception to handle * @param progressMonitor the progress monitor */ protected void handleExceptionOnSave(CoreException exception, IProgressMonitor progressMonitor) { try { ++ fErrorCorrectionOnSave; boolean isSynchronized= false; IDocumentProvider p= getDocumentProvider(); if (p instanceof IDocumentProviderExtension3) { IDocumentProviderExtension3 p3= (IDocumentProviderExtension3) p; isSynchronized= p3.isSynchronized(getEditorInput()); } else { long modifiedStamp= p.getModificationStamp(getEditorInput()); long synchStamp= p.getSynchronizationStamp(getEditorInput()); isSynchronized= (modifiedStamp == synchStamp); } if (isNotSynchronizedException(exception) && fErrorCorrectionOnSave == 1 && !isSynchronized) { String title= EditorMessages.Editor_error_save_outofsync_title; String msg= NLSUtility.format(EditorMessages.Editor_error_save_outofsync_message, getEditorInput().getToolTipText()); if (MessageDialog.openQuestion(getSite().getShell(), title, msg)) performSave(true, progressMonitor); else { /* * 1GEUPKR: ITPJUI:ALL - Loosing work with simultaneous edits * Set progress monitor to canceled in order to report back * to enclosing operations. */ if (progressMonitor != null) progressMonitor.setCanceled(true); } } else { String title= EditorMessages.Editor_error_save_title; String msg= EditorMessages.Editor_error_save_message; openSaveErrorDialog(title, msg, exception); /* * 1GEUPKR: ITPJUI:ALL - Loosing work with simultaneous edits * Set progress monitor to canceled in order to report back * to enclosing operations. */ if (progressMonitor != null) progressMonitor.setCanceled(true); } } finally { -- fErrorCorrectionOnSave; } } /** * Presents an error dialog to the user when a problem * happens during save. * <p> * Subclasses can decide to override the given title and message. * </p> * * @param title the dialog title * @param message the message to display * @param exception the exception to handle * @since 3.3 */ protected void openSaveErrorDialog(String title, String message, CoreException exception) { ErrorDialog.openError(getSite().getShell(), title, message, exception.getStatus()); } /** * Tells whether the given core exception is exactly the * exception which is thrown for a non-synchronized element. * * @param ex the core exception * @return <code>true</code> iff the given core exception is exactly the * exception which is thrown for a non-synchronized element * @since 3.1 */ private boolean isNotSynchronizedException(CoreException ex) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IDocumentProviderExtension5) return ((IDocumentProviderExtension5)provider).isNotSynchronizedException(getEditorInput(), ex); return false; } /** * The <code>AbstractTextEditor</code> implementation of this * <code>IEditorPart</code> method returns <code>false</code>. * Subclasses may override. * * @return <code>false</code> */ public boolean isSaveAsAllowed() { return false; } /* * @see EditorPart#isDirty() */ public boolean isDirty() { IDocumentProvider p= getDocumentProvider(); return p == null ? false : p.canSaveDocument(getEditorInput()); } /** * The <code>AbstractTextEditor</code> implementation of this * <code>ITextEditor</code> method may be extended by subclasses. */ public void doRevertToSaved() { IDocumentProvider p= getDocumentProvider(); if (p == null) return; performRevert(); } /** * Performs revert and handles errors appropriately. * <p> * Subclasses may extend. * </p> * * @since 3.0 */ protected void performRevert() { IDocumentProvider provider= getDocumentProvider(); if (provider == null) return; try { provider.aboutToChange(getEditorInput()); provider.resetDocument(getEditorInput()); editorSaved(); } catch (CoreException x) { IStatus status= x.getStatus(); if (status == null || status.getSeverity() != IStatus.CANCEL ) { Shell shell= getSite().getShell(); String title= EditorMessages.Editor_error_revert_title; String msg= EditorMessages.Editor_error_revert_message; ErrorDialog.openError(shell, title, msg, x.getStatus()); } } finally { provider.changed(getEditorInput()); } } /** * Performs any additional action necessary to perform after the input * document's content has been replaced. * <p> * Clients may extended this method. * * @since 3.0 */ protected void handleElementContentReplaced() { } /* * @see ITextEditor#setAction(String, IAction) */ public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) { action= (IAction) fActions.remove(actionID); if (action != null) fActivationCodeTrigger.unregisterActionFromKeyActivation(action); } else { fActions.put(actionID, action); fActivationCodeTrigger.registerActionForKeyActivation(action); } } /* * @see ITextEditor#setActionActivationCode(String, char, int, int) */ public void setActionActivationCode(String actionID, char activationCharacter, int activationKeyCode, int activationStateMask) { Assert.isNotNull(actionID); ActionActivationCode found= findActionActivationCode(actionID); if (found == null) { found= new ActionActivationCode(actionID); fActivationCodes.add(found); } found.fCharacter= activationCharacter; found.fKeyCode= activationKeyCode; found.fStateMask= activationStateMask; } /** * Returns the activation code registered for the specified action. * * @param actionID the action id * @return the registered activation code or <code>null</code> if no code has been installed */ private ActionActivationCode findActionActivationCode(String actionID) { int size= fActivationCodes.size(); for (int i= 0; i < size; i++) { ActionActivationCode code= (ActionActivationCode) fActivationCodes.get(i); if (actionID.equals(code.fActionId)) return code; } return null; } /* * @see ITextEditor#removeActionActivationCode(String) */ public void removeActionActivationCode(String actionID) { Assert.isNotNull(actionID); ActionActivationCode code= findActionActivationCode(actionID); if (code != null) fActivationCodes.remove(code); } /* * @see ITextEditor#getAction(String) */ public IAction getAction(String actionID) { Assert.isNotNull(actionID); IAction action= (IAction) fActions.get(actionID); if (action == null) { action= findContributedAction(actionID); if (action != null) setAction(actionID, action); } return action; } /** * Returns the action with the given action id that has been contributed via XML to this editor. * The lookup honors the dependencies of plug-ins. * * @param actionID the action id to look up * @return the action that has been contributed * @since 2.0 */ private IAction findContributedAction(String actionID) { List actions= new ArrayList(); IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(PlatformUI.PLUGIN_ID, "editorActions"); //$NON-NLS-1$ for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; if (TAG_CONTRIBUTION_TYPE.equals(element.getName())) { if (!getSite().getId().equals(element.getAttribute("targetID"))) //$NON-NLS-1$ continue; IConfigurationElement[] children= element.getChildren("action"); //$NON-NLS-1$ for (int j= 0; j < children.length; j++) { IConfigurationElement child= children[j]; if (actionID.equals(child.getAttribute("actionID"))) //$NON-NLS-1$ actions.add(child); } } } int actionSize= actions.size(); if (actionSize > 0) { IConfigurationElement element; if (actionSize > 1) { IConfigurationElement[] actionArray= (IConfigurationElement[])actions.toArray(new IConfigurationElement[actionSize]); ConfigurationElementSorter sorter= new ConfigurationElementSorter() { /* * @see org.eclipse.ui.texteditor.ConfigurationElementSorter#getConfigurationElement(java.lang.Object) */ public IConfigurationElement getConfigurationElement(Object object) { return (IConfigurationElement)object; } }; sorter.sort(actionArray); element= actionArray[0]; } else element= (IConfigurationElement)actions.get(0); // FIXME: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=82256 final String ATT_DEFINITION_ID= "definitionId";//$NON-NLS-1$ String defId= element.getAttribute(ATT_DEFINITION_ID); return new EditorPluginAction(element, this, defId, IAction.AS_UNSPECIFIED); } return null; } /** * Updates the specified action by calling <code>IUpdate.update</code> * if applicable. * * @param actionId the action id */ private void updateAction(String actionId) { Assert.isNotNull(actionId); if (fActions != null) { IAction action= (IAction) fActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } } /** * Marks or unmarks the given action to be updated on text selection changes. * * @param actionId the action id * @param mark <code>true</code> if the action is selection dependent */ public void markAsSelectionDependentAction(String actionId, boolean mark) { Assert.isNotNull(actionId); if (mark) { if (!fSelectionActions.contains(actionId)) fSelectionActions.add(actionId); } else fSelectionActions.remove(actionId); } /** * Marks or unmarks the given action to be updated on content changes. * * @param actionId the action id * @param mark <code>true</code> if the action is content dependent */ public void markAsContentDependentAction(String actionId, boolean mark) { Assert.isNotNull(actionId); if (mark) { if (!fContentActions.contains(actionId)) fContentActions.add(actionId); } else fContentActions.remove(actionId); } /** * Marks or unmarks the given action to be updated on property changes. * * @param actionId the action id * @param mark <code>true</code> if the action is property dependent * @since 2.0 */ public void markAsPropertyDependentAction(String actionId, boolean mark) { Assert.isNotNull(actionId); if (mark) { if (!fPropertyActions.contains(actionId)) fPropertyActions.add(actionId); } else fPropertyActions.remove(actionId); } /** * Marks or unmarks the given action to be updated on state changes. * * @param actionId the action id * @param mark <code>true</code> if the action is state dependent * @since 2.0 */ public void markAsStateDependentAction(String actionId, boolean mark) { Assert.isNotNull(actionId); if (mark) { if (!fStateActions.contains(actionId)) fStateActions.add(actionId); } else fStateActions.remove(actionId); } /** * Updates all selection dependent actions. */ protected void updateSelectionDependentActions() { if (fSelectionActions != null) { Iterator e= fSelectionActions.iterator(); while (e.hasNext()) updateAction((String) e.next()); } } /** * Updates all content dependent actions. */ protected void updateContentDependentActions() { if (fContentActions != null) { Iterator e= fContentActions.iterator(); while (e.hasNext()) updateAction((String) e.next()); } } /** * Updates all property dependent actions. * @since 2.0 */ protected void updatePropertyDependentActions() { if (fPropertyActions != null) { Iterator e= fPropertyActions.iterator(); while (e.hasNext()) updateAction((String) e.next()); } } /** * Updates all state dependent actions. * @since 2.0 */ protected void updateStateDependentActions() { if (fStateActions != null) { Iterator e= fStateActions.iterator(); while (e.hasNext()) updateAction((String) e.next()); } } /** * Creates action entries for all SWT StyledText actions as defined in * <code>org.eclipse.swt.custom.ST</code>. Overwrites and * extends the list of these actions afterwards. * <p> * Subclasses may extend. * </p> * @since 2.0 */ protected void createNavigationActions() { IAction action; StyledText textWidget= fSourceViewer.getTextWidget(); for (int i= 0; i < ACTION_MAP.length; i++) { IdMapEntry entry= ACTION_MAP[i]; action= new TextNavigationAction(textWidget, entry.getAction()); action.setActionDefinitionId(entry.getActionId()); setAction(entry.getActionId(), action); } action= new ToggleOverwriteModeAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ToggleOverwriteMode."); //$NON-NLS-1$ action.setActionDefinitionId(ITextEditorActionDefinitionIds.TOGGLE_OVERWRITE); setAction(ITextEditorActionDefinitionIds.TOGGLE_OVERWRITE, action); textWidget.setKeyBinding(SWT.INSERT, SWT.NULL); action= new ScrollLinesAction(-1); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SCROLL_LINE_UP); setAction(ITextEditorActionDefinitionIds.SCROLL_LINE_UP, action); action= new ScrollLinesAction(1); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SCROLL_LINE_DOWN); setAction(ITextEditorActionDefinitionIds.SCROLL_LINE_DOWN, action); action= new LineEndAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_END); setAction(ITextEditorActionDefinitionIds.LINE_END, action); action= new LineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new LineEndAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_END); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_END, action); action= new LineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); // to accommodate https://bugs.eclipse.org/bugs/show_bug.cgi?id=51516 // nullify handling of DELETE key by StyledText textWidget.setKeyBinding(SWT.DEL, SWT.NULL); } /** * Creates this editor's accessibility actions. * @since 2.0 */ private void createAccessibilityActions() { IAction action= new ShowRulerContextMenuAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_RULER_CONTEXT_MENU); setAction(ITextEditorActionDefinitionIds.SHOW_RULER_CONTEXT_MENU, action); } /** * Creates this editor's undo/redo actions. * <p> * Subclasses may override or extend.</p> * * @since 3.1 */ protected void createUndoRedoActions() { IUndoContext undoContext= getUndoContext(); if (undoContext != null) { // Use actions provided by global undo/redo // Create the undo action OperationHistoryActionHandler undoAction= new UndoActionHandler(getEditorSite(), undoContext); PlatformUI.getWorkbench().getHelpSystem().setHelp(undoAction, IAbstractTextEditorHelpContextIds.UNDO_ACTION); undoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.UNDO); registerUndoRedoAction(ITextEditorActionConstants.UNDO, undoAction); // Create the redo action. OperationHistoryActionHandler redoAction= new RedoActionHandler(getEditorSite(), undoContext); PlatformUI.getWorkbench().getHelpSystem().setHelp(redoAction, IAbstractTextEditorHelpContextIds.REDO_ACTION); redoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.REDO); registerUndoRedoAction(ITextEditorActionConstants.REDO, redoAction); // Install operation approvers IOperationHistory history= OperationHistoryFactory.getOperationHistory(); // The first approver will prompt when operations affecting outside elements are to be undone or redone. if (fNonLocalOperationApprover != null) history.removeOperationApprover(fNonLocalOperationApprover); fNonLocalOperationApprover= getUndoRedoOperationApprover(undoContext); history.addOperationApprover(fNonLocalOperationApprover); // The second approver will prompt from this editor when an undo is attempted on an operation // and it is not the most recent operation in the editor. if (fLinearUndoViolationApprover != null) history.removeOperationApprover(fLinearUndoViolationApprover); fLinearUndoViolationApprover= new LinearUndoViolationUserApprover(undoContext, this); history.addOperationApprover(fLinearUndoViolationApprover); } else { // Use text operation actions (pre 3.1 style) ResourceAction action; if (getAction(ITextEditorActionConstants.UNDO) == null) { action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Undo.", this, ITextOperationTarget.UNDO); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.UNDO_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.UNDO); setAction(ITextEditorActionConstants.UNDO, action); } if (getAction(ITextEditorActionConstants.REDO) == null) { action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Redo.", this, ITextOperationTarget.REDO); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.REDO_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.REDO); setAction(ITextEditorActionConstants.REDO, action); } } } /** * Registers the given undo/redo action under the given ID and * ensures that previously installed actions get disposed. It * also takes care of re-registering the new action with the * global action handler. * * @param actionId the action id under which to register the action * @param action the action to register * @since 3.1 */ private void registerUndoRedoAction(String actionId, OperationHistoryActionHandler action) { IAction oldAction= getAction(actionId); if (oldAction instanceof OperationHistoryActionHandler) ((OperationHistoryActionHandler)oldAction).dispose(); setAction(actionId, action); IActionBars actionBars= getEditorSite().getActionBars(); if (actionBars != null) actionBars.setGlobalActionHandler(actionId, action); } /** * Return an {@link IOperationApprover} appropriate for approving the undo and * redo of operations that have the specified undo context. * <p> * Subclasses may override. * </p> * @param undoContext the IUndoContext of operations that should be examined * by the operation approver * @return the <code>IOperationApprover</code> appropriate for approving undo * and redo operations inside this editor, or <code>null</code> if no * approval is needed * @since 3.1 */ protected IOperationApprover getUndoRedoOperationApprover(IUndoContext undoContext) { return new NonLocalUndoUserApprover(undoContext, this, new Object [] { getEditorInput() }, Object.class); } /** * Creates this editor's standard actions and connects them with the global * workbench actions. * <p> * Subclasses may extend.</p> */ protected void createActions() { ResourceAction action; action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT); setAction(ITextEditorActionConstants.CUT, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Copy.", this, ITextOperationTarget.COPY, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); setAction(ITextEditorActionConstants.COPY, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE); setAction(ITextEditorActionConstants.PASTE, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Delete.", this, ITextOperationTarget.DELETE); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.DELETE_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.DELETE); setAction(ITextEditorActionConstants.DELETE, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.DeleteLine.", this, DeleteLineAction.WHOLE, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.DELETE_LINE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_LINE); setAction(ITextEditorActionConstants.DELETE_LINE, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.CutLine.", this, DeleteLineAction.WHOLE, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_LINE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.CUT_LINE); setAction(ITextEditorActionConstants.CUT_LINE, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.DeleteLineToBeginning.", this, DeleteLineAction.TO_BEGINNING, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.DELETE_LINE_TO_BEGINNING_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_LINE_TO_BEGINNING); setAction(ITextEditorActionConstants.DELETE_LINE_TO_BEGINNING, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.CutLineToBeginning.", this, DeleteLineAction.TO_BEGINNING, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_LINE_TO_BEGINNING_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.CUT_LINE_TO_BEGINNING); setAction(ITextEditorActionConstants.CUT_LINE_TO_BEGINNING, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.DeleteLineToEnd.", this, DeleteLineAction.TO_END, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.DELETE_LINE_TO_END_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_LINE_TO_END); setAction(ITextEditorActionConstants.DELETE_LINE_TO_END, action); action= new DeleteLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.CutLineToEnd.", this, DeleteLineAction.TO_END, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_LINE_TO_END_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.CUT_LINE_TO_END); setAction(ITextEditorActionConstants.CUT_LINE_TO_END, action); action= new MarkAction(EditorMessages.getBundleForConstructedKeys(), "Editor.SetMark.", this, MarkAction.SET_MARK); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SET_MARK_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SET_MARK); setAction(ITextEditorActionConstants.SET_MARK, action); action= new MarkAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ClearMark.", this, MarkAction.CLEAR_MARK); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.CLEAR_MARK_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.CLEAR_MARK); setAction(ITextEditorActionConstants.CLEAR_MARK, action); action= new MarkAction(EditorMessages.getBundleForConstructedKeys(), "Editor.SwapMark.", this, MarkAction.SWAP_MARK); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SWAP_MARK_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SWAP_MARK); setAction(ITextEditorActionConstants.SWAP_MARK, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.SelectAll.", this, ITextOperationTarget.SELECT_ALL, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); setAction(ITextEditorActionConstants.SELECT_ALL, action); action= new ShiftAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ShiftRight.", this, ITextOperationTarget.SHIFT_RIGHT); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SHIFT_RIGHT_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_RIGHT); setAction(ITextEditorActionConstants.SHIFT_RIGHT, action); action= new ShiftAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ShiftRight.", this, ITextOperationTarget.SHIFT_RIGHT) { //$NON-NLS-1$ public void update() { updateForTab(); } }; setAction(ITextEditorActionConstants.SHIFT_RIGHT_TAB, action); action= new ShiftAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ShiftLeft.", this, ITextOperationTarget.SHIFT_LEFT); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SHIFT_LEFT_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SHIFT_LEFT); setAction(ITextEditorActionConstants.SHIFT_LEFT, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Print.", this, ITextOperationTarget.PRINT, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.PRINT_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.PRINT); setAction(ITextEditorActionConstants.PRINT, action); action= new FindReplaceAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindReplace.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_REPLACE); setAction(ITextEditorActionConstants.FIND, action); action= new FindNextAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindNext.", this, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_NEXT_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_NEXT); setAction(ITextEditorActionConstants.FIND_NEXT, action); action= new FindNextAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindPrevious.", this, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_PREVIOUS_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_PREVIOUS); setAction(ITextEditorActionConstants.FIND_PREVIOUS, action); action= new IncrementalFindAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindIncremental.", this, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_INCREMENTAL_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_INCREMENTAL); setAction(ITextEditorActionConstants.FIND_INCREMENTAL, action); action= new IncrementalFindAction(EditorMessages.getBundleForConstructedKeys(), "Editor.FindIncrementalReverse.", this, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.FIND_INCREMENTAL_REVERSE_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_INCREMENTAL_REVERSE); setAction(ITextEditorActionConstants.FIND_INCREMENTAL_REVERSE, action); action= new SaveAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Save.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SAVE_ACTION); /* * if the line below is uncommented then the key binding does not work any more * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=53417 */ // action.setActionDefinitionId(ITextEditorActionDefinitionIds.SAVE); setAction(ITextEditorActionConstants.SAVE, action); action= new RevertToSavedAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Revert.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.REVERT_TO_SAVED_ACTION); action.setActionDefinitionId(IWorkbenchActionDefinitionIds.REVERT_TO_SAVED); setAction(ITextEditorActionConstants.REVERT_TO_SAVED, action); action= new GotoLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.GotoLine.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.GOTO_LINE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_GOTO); setAction(ITextEditorActionConstants.GOTO_LINE, action); action= new MoveLinesAction(EditorMessages.getBundleForConstructedKeys(), "Editor.MoveLinesUp.", this, true, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.MOVE_LINES_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.MOVE_LINES_UP); setAction(ITextEditorActionConstants.MOVE_LINE_UP, action); action= new MoveLinesAction(EditorMessages.getBundleForConstructedKeys(), "Editor.MoveLinesDown.", this, false, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.MOVE_LINES_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.MOVE_LINES_DOWN); setAction(ITextEditorActionConstants.MOVE_LINE_DOWN, action); action= new MoveLinesAction(EditorMessages.getBundleForConstructedKeys(), "Editor.CopyLineUp.", this, true, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_LINES_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.COPY_LINES_UP); setAction(ITextEditorActionConstants.COPY_LINE_UP, action); action= new MoveLinesAction(EditorMessages.getBundleForConstructedKeys(), "Editor.CopyLineDown.", this, false, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_LINES_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.COPY_LINES_DOWN); setAction(ITextEditorActionConstants.COPY_LINE_DOWN, action); action= new CaseAction(EditorMessages.getBundleForConstructedKeys(), "Editor.UpperCase.", this, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.UPPER_CASE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.UPPER_CASE); setAction(ITextEditorActionConstants.UPPER_CASE, action); action= new CaseAction(EditorMessages.getBundleForConstructedKeys(), "Editor.LowerCase.", this, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.LOWER_CASE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LOWER_CASE); setAction(ITextEditorActionConstants.LOWER_CASE, action); action= new InsertLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.SmartEnter.", this, false); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SMART_ENTER_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SMART_ENTER); setAction(ITextEditorActionConstants.SMART_ENTER, action); action= new InsertLineAction(EditorMessages.getBundleForConstructedKeys(), "Editor.SmartEnterInverse.", this, true); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SMART_ENTER_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SMART_ENTER_INVERSE); setAction(ITextEditorActionConstants.SMART_ENTER_INVERSE, action); action= new ToggleInsertModeAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ToggleInsertMode."); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.TOGGLE_INSERT_MODE_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.TOGGLE_INSERT_MODE); setAction(ITextEditorActionConstants.TOGGLE_INSERT_MODE, action); action= new HippieCompleteAction(EditorMessages.getBundleForConstructedKeys(), "Editor.HippieCompletion.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.HIPPIE_COMPLETION_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.HIPPIE_COMPLETION); setAction(ITextEditorActionConstants.HIPPIE_COMPLETION, action); action= new TextOperationAction(EditorMessages.getBundleForConstructedKeys(), "Editor.QuickAssist.", this, ISourceViewer.QUICK_ASSIST); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.QUICK_ASSIST_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICK_ASSIST); setAction(ITextEditorActionConstants.QUICK_ASSIST, action); markAsStateDependentAction(ITextEditorActionConstants.QUICK_ASSIST, true); action= new GotoAnnotationAction(this, true); setAction(ITextEditorActionConstants.NEXT, action); action= new GotoAnnotationAction(this, false); setAction(ITextEditorActionConstants.PREVIOUS, action); action= new RecenterAction(EditorMessages.getBundleForConstructedKeys(), "Editor.Recenter.", this); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.RECENTER_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.RECENTER); setAction(ITextEditorActionConstants.RECENTER, action); action= new ShowWhitespaceCharactersAction(EditorMessages.getBundleForConstructedKeys(), "Editor.ShowWhitespaceCharacters.", this, getPreferenceStore()); //$NON-NLS-1$ action.setHelpContextId(IAbstractTextEditorHelpContextIds.SHOW_WHITESPACE_CHARACTERS_ACTION); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SHOW_WHITESPACE_CHARACTERS); setAction(ITextEditorActionConstants.SHOW_WHITESPACE_CHARACTERS, action); PropertyDialogAction openProperties= new PropertyDialogAction( new IShellProvider() { public Shell getShell() { return getSite().getShell(); } }, new ISelectionProvider() { public void addSelectionChangedListener(ISelectionChangedListener listener) { } public ISelection getSelection() { return new StructuredSelection(getEditorInput()); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { } public void setSelection(ISelection selection) { } }); openProperties.setActionDefinitionId(IWorkbenchActionDefinitionIds.PROPERTIES); setAction(ITextEditorActionConstants.PROPERTIES, openProperties); markAsContentDependentAction(ITextEditorActionConstants.UNDO, true); markAsContentDependentAction(ITextEditorActionConstants.REDO, true); markAsContentDependentAction(ITextEditorActionConstants.FIND, true); markAsContentDependentAction(ITextEditorActionConstants.FIND_NEXT, true); markAsContentDependentAction(ITextEditorActionConstants.FIND_PREVIOUS, true); markAsContentDependentAction(ITextEditorActionConstants.FIND_INCREMENTAL, true); markAsContentDependentAction(ITextEditorActionConstants.FIND_INCREMENTAL_REVERSE, true); markAsSelectionDependentAction(ITextEditorActionConstants.CUT, true); markAsSelectionDependentAction(ITextEditorActionConstants.COPY, true); markAsSelectionDependentAction(ITextEditorActionConstants.PASTE, true); markAsSelectionDependentAction(ITextEditorActionConstants.DELETE, true); markAsSelectionDependentAction(ITextEditorActionConstants.SHIFT_RIGHT, true); markAsSelectionDependentAction(ITextEditorActionConstants.SHIFT_RIGHT_TAB, true); markAsSelectionDependentAction(ITextEditorActionConstants.UPPER_CASE, true); markAsSelectionDependentAction(ITextEditorActionConstants.LOWER_CASE, true); markAsPropertyDependentAction(ITextEditorActionConstants.UNDO, true); markAsPropertyDependentAction(ITextEditorActionConstants.REDO, true); markAsPropertyDependentAction(ITextEditorActionConstants.REVERT_TO_SAVED, true); markAsStateDependentAction(ITextEditorActionConstants.UNDO, true); markAsStateDependentAction(ITextEditorActionConstants.REDO, true); markAsStateDependentAction(ITextEditorActionConstants.CUT, true); markAsStateDependentAction(ITextEditorActionConstants.PASTE, true); markAsStateDependentAction(ITextEditorActionConstants.DELETE, true); markAsStateDependentAction(ITextEditorActionConstants.SHIFT_RIGHT, true); markAsStateDependentAction(ITextEditorActionConstants.SHIFT_RIGHT_TAB, true); markAsStateDependentAction(ITextEditorActionConstants.SHIFT_LEFT, true); markAsStateDependentAction(ITextEditorActionConstants.FIND, true); markAsStateDependentAction(ITextEditorActionConstants.DELETE_LINE, true); markAsStateDependentAction(ITextEditorActionConstants.DELETE_LINE_TO_BEGINNING, true); markAsStateDependentAction(ITextEditorActionConstants.DELETE_LINE_TO_END, true); markAsStateDependentAction(ITextEditorActionConstants.MOVE_LINE_UP, true); markAsStateDependentAction(ITextEditorActionConstants.MOVE_LINE_DOWN, true); markAsStateDependentAction(ITextEditorActionConstants.CUT_LINE, true); markAsStateDependentAction(ITextEditorActionConstants.CUT_LINE_TO_BEGINNING, true); markAsStateDependentAction(ITextEditorActionConstants.CUT_LINE_TO_END, true); setActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT_TAB,'\t', -1, SWT.NONE); setActionActivationCode(ITextEditorActionConstants.SHIFT_LEFT, '\t', -1, SWT.SHIFT); } /** * Convenience method to add the action installed under the given action id to the given menu. * @param menu the menu to add the action to * @param actionId the id of the action to be added */ protected final void addAction(IMenuManager menu, String actionId) { IAction action= getAction(actionId); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); menu.add(action); } } /** * Convenience method to add the action installed under the given action id to the specified group of the menu. * @param menu the menu to add the action to * @param group the group in the menu * @param actionId the id of the action to add */ protected final void addAction(IMenuManager menu, String group, String actionId) { IAction action= getAction(actionId); if (action != null) { if (action instanceof IUpdate) ((IUpdate) action).update(); IMenuManager subMenu= menu.findMenuUsingPath(group); if (subMenu != null) subMenu.add(action); else menu.appendToGroup(group, action); } } /** * Convenience method to add a new group after the specified group. * @param menu the menu to add the new group to * @param existingGroup the group after which to insert the new group * @param newGroup the new group */ protected final void addGroup(IMenuManager menu, String existingGroup, String newGroup) { IMenuManager subMenu= menu.findMenuUsingPath(existingGroup); if (subMenu != null) subMenu.add(new Separator(newGroup)); else menu.appendToGroup(existingGroup, new Separator(newGroup)); } /** * Sets up the ruler context menu before it is made visible. * <p> * Subclasses may extend to add other actions.</p> * * @param menu the menu */ protected void rulerContextMenuAboutToShow(IMenuManager menu) { menu.add(new Separator(ITextEditorActionConstants.GROUP_REST)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); for (Iterator i= fRulerContextMenuListeners.iterator(); i.hasNext();) ((IMenuListener) i.next()).menuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS); addAction(menu, ITextEditorActionConstants.RULER_MANAGE_TASKS); } /** * Sets up this editor's context menu before it is made visible. * <p> * Subclasses may extend to add other actions.</p> * * @param menu the menu */ protected void editorContextMenuAboutToShow(IMenuManager menu) { menu.add(new Separator(ITextEditorActionConstants.GROUP_UNDO)); menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_SAVE)); menu.add(new Separator(ITextEditorActionConstants.GROUP_COPY)); menu.add(new Separator(ITextEditorActionConstants.GROUP_PRINT)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); menu.add(new Separator(ITextEditorActionConstants.GROUP_FIND)); menu.add(new Separator(IWorkbenchActionConstants.GROUP_ADD)); menu.add(new Separator(ITextEditorActionConstants.GROUP_REST)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); if (isEditable()) { addAction(menu, ITextEditorActionConstants.GROUP_UNDO, ITextEditorActionConstants.UNDO); addAction(menu, ITextEditorActionConstants.GROUP_UNDO, ITextEditorActionConstants.REVERT_TO_SAVED); addAction(menu, ITextEditorActionConstants.GROUP_SAVE, ITextEditorActionConstants.SAVE); addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.CUT); addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.COPY); addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.PASTE); } else { addAction(menu, ITextEditorActionConstants.GROUP_COPY, ITextEditorActionConstants.COPY); } } /** * Returns the status line manager of this editor. * * @return the status line manager of this editor * @since 2.0, protected since 3.3 */ protected IStatusLineManager getStatusLineManager() { return getEditorSite().getActionBars().getStatusLineManager(); } /* * @see IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class required) { if (IEditorStatusLine.class.equals(required)) { if (fEditorStatusLine == null) { IStatusLineManager statusLineManager= getStatusLineManager(); ISelectionProvider selectionProvider= getSelectionProvider(); if (statusLineManager != null && selectionProvider != null) fEditorStatusLine= new EditorStatusLine(statusLineManager, selectionProvider); } return fEditorStatusLine; } if (IVerticalRulerInfo.class.equals(required)) { if (fVerticalRuler != null) return fVerticalRuler; } if (IMarkRegionTarget.class.equals(required)) { if (fMarkRegionTarget == null) { IStatusLineManager manager= getStatusLineManager(); if (manager != null) fMarkRegionTarget= (fSourceViewer == null ? null : new MarkRegionTarget(fSourceViewer, manager)); } return fMarkRegionTarget; } if (DeleteLineTarget.class.equals(required)){ if (fDeleteLineTarget == null) { fDeleteLineTarget= new DeleteLineTarget(fSourceViewer); } return fDeleteLineTarget; } if (IncrementalFindTarget.class.equals(required)) { if (fIncrementalFindTarget == null) { IStatusLineManager manager= getStatusLineManager(); if (manager != null) fIncrementalFindTarget= (fSourceViewer == null ? null : new IncrementalFindTarget(fSourceViewer, manager)); } return fIncrementalFindTarget; } if (IFindReplaceTarget.class.equals(required)) { if (fFindReplaceTarget == null) { IFindReplaceTarget target= (fSourceViewer == null ? null : fSourceViewer.getFindReplaceTarget()); if (target != null) { fFindReplaceTarget= new FindReplaceTarget(this, target); if (fFindScopeHighlightColor != null) fFindReplaceTarget.setScopeHighlightColor(fFindScopeHighlightColor); } } return fFindReplaceTarget; } if (ITextOperationTarget.class.equals(required)) return (fSourceViewer == null ? null : fSourceViewer.getTextOperationTarget()); if (IRewriteTarget.class.equals(required)) { if (fSourceViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) fSourceViewer; return extension.getRewriteTarget(); } return null; } if (Control.class.equals(required)) return fSourceViewer != null ? fSourceViewer.getTextWidget() : null; if (IColumnSupport.class.equals(required)) { if (fColumnSupport == null) fColumnSupport= createColumnSupport(); return fColumnSupport; } return super.getAdapter(required); } /* * @see IWorkbenchPart#setFocus() */ public void setFocus() { if (fSourceViewer != null && fSourceViewer.getTextWidget() != null) fSourceViewer.getTextWidget().setFocus(); } /* * @see ITextEditor#showsHighlightRangeOnly() */ public boolean showsHighlightRangeOnly() { return fShowHighlightRangeOnly; } /* * @see ITextEditor#showHighlightRangeOnly(boolean) */ public void showHighlightRangeOnly(boolean showHighlightRangeOnly) { fShowHighlightRangeOnly= showHighlightRangeOnly; } /* * @see ITextEditor#setHighlightRange(int, int, boolean) */ public void setHighlightRange(int offset, int length, boolean moveCursor) { if (fSourceViewer == null) return; if (fShowHighlightRangeOnly) { if (moveCursor) fSourceViewer.setVisibleRegion(offset, length); } else { IRegion rangeIndication= fSourceViewer.getRangeIndication(); if (rangeIndication == null || offset != rangeIndication.getOffset() || length != rangeIndication.getLength()) fSourceViewer.setRangeIndication(offset, length, moveCursor); } } /* * @see ITextEditor#getHighlightRange() */ public IRegion getHighlightRange() { if (fSourceViewer == null) return null; if (fShowHighlightRangeOnly) return getCoverage(fSourceViewer); return fSourceViewer.getRangeIndication(); } /* * @see ITextEditor#resetHighlightRange */ public void resetHighlightRange() { if (fSourceViewer == null) return; if (fShowHighlightRangeOnly) fSourceViewer.resetVisibleRegion(); else fSourceViewer.removeRangeIndication(); } /** * Adjusts the highlight range so that at least the specified range * is highlighted. * <p> * Subclasses may re-implement this method.</p> * * @param offset the offset of the range which at least should be highlighted * @param length the length of the range which at least should be highlighted */ protected void adjustHighlightRange(int offset, int length) { if (fSourceViewer == null) return; if (fSourceViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) fSourceViewer; extension.exposeModelRange(new Region(offset, length)); } else if (!isVisible(fSourceViewer, offset, length)) { fSourceViewer.resetVisibleRegion(); } } /* * @see ITextEditor#selectAndReveal(int, int) */ public void selectAndReveal(int start, int length) { selectAndReveal(start, length, start, length); } /** * Selects and reveals the specified ranges in this text editor. * * @param selectionStart the offset of the selection * @param selectionLength the length of the selection * @param revealStart the offset of the revealed range * @param revealLength the length of the revealed range * @since 3.0 */ protected void selectAndReveal(int selectionStart, int selectionLength, int revealStart, int revealLength) { if (fSourceViewer == null) return; ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection) selection; if (textSelection.getOffset() != 0 || textSelection.getLength() != 0) markInNavigationHistory(); } StyledText widget= fSourceViewer.getTextWidget(); widget.setRedraw(false); { adjustHighlightRange(revealStart, revealLength); fSourceViewer.revealRange(revealStart, revealLength); fSourceViewer.setSelectedRange(selectionStart, selectionLength); markInNavigationHistory(); } widget.setRedraw(true); } /* * @see org.eclipse.ui.INavigationLocationProvider#createNavigationLocation() * @since 2.1 */ public INavigationLocation createEmptyNavigationLocation() { return new TextSelectionNavigationLocation(this, false); } /* * @see org.eclipse.ui.INavigationLocationProvider#createNavigationLocation() */ public INavigationLocation createNavigationLocation() { return new TextSelectionNavigationLocation(this, true); } /** * Writes a check mark of the given situation into the navigation history. * @since 2.1 */ protected void markInNavigationHistory() { getSite().getPage().getNavigationHistory().markLocation(this); } /** * Hook which gets called when the editor has been saved. * Subclasses may extend. * @since 2.1 */ protected void editorSaved() { INavigationLocation[] locations= getSite().getPage().getNavigationHistory().getLocations(); IEditorInput input= getEditorInput(); for (int i= 0; i < locations.length; i++) { if (locations[i] instanceof TextSelectionNavigationLocation) { if(input.equals(locations[i].getInput())) { TextSelectionNavigationLocation location= (TextSelectionNavigationLocation) locations[i]; location.partSaved(this); } } } } /* * @see WorkbenchPart#firePropertyChange(int) */ protected void firePropertyChange(int property) { super.firePropertyChange(property); updatePropertyDependentActions(); } /* * @see ITextEditorExtension#setStatusField(IStatusField, String) * @since 2.0 */ public void setStatusField(IStatusField field, String category) { Assert.isNotNull(category); if (field != null) { if (fStatusFields == null) fStatusFields= new HashMap(3); fStatusFields.put(category, field); updateStatusField(category); } else if (fStatusFields != null) fStatusFields.remove(category); if (fIncrementalFindTarget != null && ITextEditorActionConstants.STATUS_CATEGORY_FIND_FIELD.equals(category)) fIncrementalFindTarget.setStatusField(field); } /** * Returns the current status field for the given status category. * * @param category the status category * @return the current status field for the given status category * @since 2.0 */ protected IStatusField getStatusField(String category) { if (category != null && fStatusFields != null) return (IStatusField) fStatusFields.get(category); return null; } /** * Returns whether this editor is in overwrite or insert mode. * * @return <code>true</code> if in insert mode, <code>false</code> for overwrite mode * @since 2.0 */ protected boolean isInInsertMode() { return !fIsOverwriting; } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension3#getInsertMode() * @since 3.0 */ public InsertMode getInsertMode() { return fInsertMode; } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension3#setInsertMode(org.eclipse.ui.texteditor.ITextEditorExtension3.InsertMode) * @since 3.0 */ public void setInsertMode(InsertMode newMode) { List legalModes= getLegalInsertModes(); if (!legalModes.contains(newMode)) throw new IllegalArgumentException(); fInsertMode= newMode; handleInsertModeChanged(); } /** * Returns the set of legal insert modes. If insert modes are configured all defined insert modes * are legal. * * @return the set of legal insert modes * @since 3.0 */ protected List getLegalInsertModes() { if (fLegalInsertModes == null) { fLegalInsertModes= new ArrayList(); fLegalInsertModes.add(SMART_INSERT); fLegalInsertModes.add(INSERT); } return fLegalInsertModes; } private void switchToNextInsertMode() { InsertMode mode= getInsertMode(); List legalModes= getLegalInsertModes(); int i= 0; while (i < legalModes.size()) { if (legalModes.get(i) == mode) break; ++ i; } i= (i + 1) % legalModes.size(); InsertMode newMode= (InsertMode) legalModes.get(i); setInsertMode(newMode); } private void toggleOverwriteMode() { if (fIsOverwriteModeEnabled) { fIsOverwriting= !fIsOverwriting; fSourceViewer.getTextWidget().invokeAction(ST.TOGGLE_OVERWRITE); handleInsertModeChanged(); } } /** * Configures the given insert mode as legal or illegal. This call is ignored if the set of legal * input modes would be empty after the call. * * @param mode the insert mode to be configured * @param legal <code>true</code> if the given mode is legal, <code>false</code> otherwise * @since 3.0 */ protected void configureInsertMode(InsertMode mode, boolean legal) { List legalModes= getLegalInsertModes(); if (legal) { if (!legalModes.contains(mode)) legalModes.add(mode); } else if (legalModes.size() > 1) { if (getInsertMode() == mode) switchToNextInsertMode(); legalModes.remove(mode); } } /** * Sets the overwrite mode enablement. * * @param enable <code>true</code> to enable new overwrite mode, * <code>false</code> to disable * @since 3.0 */ protected void enableOverwriteMode(boolean enable) { if (fIsOverwriting && !enable) toggleOverwriteMode(); fIsOverwriteModeEnabled= enable; } private Caret createOverwriteCaret(StyledText styledText) { Caret caret= new Caret(styledText, SWT.NULL); GC gc= new GC(styledText); // XXX this overwrite box is not proportional-font aware // take 'a' as a medium sized character Point charSize= gc.stringExtent("a"); //$NON-NLS-1$ // XXX: Filed request to get a caret with auto-height: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118612 caret.setSize(charSize.x, styledText.getLineHeight()); caret.setFont(styledText.getFont()); gc.dispose(); return caret; } private Caret createInsertCaret(StyledText styledText) { Caret caret= new Caret(styledText, SWT.NULL); // XXX: Filed request to get a caret with auto-height: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118612 caret.setSize(getCaretWidthPreference(), styledText.getLineHeight()); caret.setFont(styledText.getFont()); return caret; } private Image createRawInsertModeCaretImage(StyledText styledText) { PaletteData caretPalette= new PaletteData(new RGB[] {new RGB (0,0,0), new RGB (255,255,255)}); int width= getCaretWidthPreference(); int widthOffset= width - 1; // XXX: Filed request to get a caret with auto-height: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118612 ImageData imageData= new ImageData(4 + widthOffset, styledText.getLineHeight(), 1, caretPalette); Display display= styledText.getDisplay(); Image bracketImage= new Image(display, imageData); GC gc= new GC (bracketImage); gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE)); gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance int height= imageData.height / 3; // gap between two bars of one third of the height // draw boxes using lines as drawing a line of a certain width produces // rounded corners. for (int i= 0; i < width ; i++) { gc.drawLine(i, 0, i, height - 1); gc.drawLine(i, imageData.height - height, i, imageData.height - 1); } gc.dispose(); return bracketImage; } private Caret createRawInsertModeCaret(StyledText styledText) { // don't draw special raw caret if no smart mode is enabled if (!getLegalInsertModes().contains(SMART_INSERT)) return createInsertCaret(styledText); Caret caret= new Caret(styledText, SWT.NULL); Image image= createRawInsertModeCaretImage(styledText); if (image != null) caret.setImage(image); else { // XXX: Filed request to get a caret with auto-height: https://bugs.eclipse.org/bugs/show_bug.cgi?id=118612 caret.setSize(getCaretWidthPreference(), styledText.getLineHeight()); } caret.setFont(styledText.getFont()); return caret; } private int getCaretWidthPreference() { if (getPreferenceStore() != null && getPreferenceStore().getBoolean(PREFERENCE_WIDE_CARET)) return WIDE_CARET_WIDTH; return SINGLE_CARET_WIDTH; } private void updateCaret() { if (fSourceViewer == null) return; StyledText styledText= fSourceViewer.getTextWidget(); InsertMode mode= getInsertMode(); styledText.setCaret(null); disposeNonDefaultCaret(); if (getPreferenceStore() == null || !getPreferenceStore().getBoolean(PREFERENCE_USE_CUSTOM_CARETS)) Assert.isTrue(fNonDefaultCaret == null); else if (fIsOverwriting) fNonDefaultCaret= createOverwriteCaret(styledText); else if (SMART_INSERT == mode) fNonDefaultCaret= createInsertCaret(styledText); else if (INSERT == mode) fNonDefaultCaret= createRawInsertModeCaret(styledText); if (fNonDefaultCaret != null) { styledText.setCaret(fNonDefaultCaret); fNonDefaultCaretImage= fNonDefaultCaret.getImage(); } else if (fInitialCaret != styledText.getCaret()) styledText.setCaret(fInitialCaret); } private void disposeNonDefaultCaret() { if (fNonDefaultCaretImage != null) { fNonDefaultCaretImage.dispose(); fNonDefaultCaretImage= null; } if (fNonDefaultCaret != null) { fNonDefaultCaret.dispose(); fNonDefaultCaret= null; } } /** * Handles a change of the editor's insert mode. * Subclasses may extend. * * @since 2.0 */ protected void handleInsertModeChanged() { updateInsertModeAction(); updateCaret(); updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_INPUT_MODE); } private void updateInsertModeAction() { // this may be called before the part is fully initialized (see configureInsertMode) // drop out in this case. if (getSite() == null) return; IAction action= getAction(ITextEditorActionConstants.TOGGLE_INSERT_MODE); if (action != null) { action.setEnabled(!fIsOverwriting); action.setChecked(fInsertMode == SMART_INSERT); } } /** * Handles a potential change of the cursor position. * Subclasses may extend. * * @since 2.0 */ protected void handleCursorPositionChanged() { updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_INPUT_POSITION); } /** * Updates the status fields for the given category. * * @param category * @since 2.0 */ protected void updateStatusField(String category) { if (category == null) return; IStatusField field= getStatusField(category); if (field != null) { String text= null; if (ITextEditorActionConstants.STATUS_CATEGORY_INPUT_POSITION.equals(category)) text= getCursorPosition(); else if (ITextEditorActionConstants.STATUS_CATEGORY_ELEMENT_STATE.equals(category)) text= isEditorInputReadOnly() ? fReadOnlyLabel : fWritableLabel; else if (ITextEditorActionConstants.STATUS_CATEGORY_INPUT_MODE.equals(category)) { InsertMode mode= getInsertMode(); if (fIsOverwriting) text= fOverwriteModeLabel; else if (INSERT == mode) text= fInsertModeLabel; else if (SMART_INSERT == mode) text= fSmartInsertModeLabel; } field.setText(text == null ? fErrorLabel : text); } } /** * Updates all status fields. * * @since 2.0 */ protected void updateStatusFields() { if (fStatusFields != null) { Iterator e= fStatusFields.keySet().iterator(); while (e.hasNext()) updateStatusField((String) e.next()); } } /** * Returns a description of the cursor position. * * @return a description of the cursor position * @since 2.0 */ protected String getCursorPosition() { if (fSourceViewer == null) return fErrorLabel; StyledText styledText= fSourceViewer.getTextWidget(); int caret= widgetOffset2ModelOffset(fSourceViewer, styledText.getCaretOffset()); IDocument document= fSourceViewer.getDocument(); if (document == null) return fErrorLabel; try { int line= document.getLineOfOffset(caret); int lineOffset= document.getLineOffset(line); int tabWidth= styledText.getTabs(); int column= 0; for (int i= lineOffset; i < caret; i++) if ('\t' == document.getChar(i)) column += tabWidth - (tabWidth == 0 ? 0 : column % tabWidth); else column++; fLineLabel.fValue= line + 1; fColumnLabel.fValue= column + 1; return NLSUtility.format(fPositionLabelPattern, fPositionLabelPatternArguments); } catch (BadLocationException x) { return fErrorLabel; } } /* * @see ITextEditorExtension#isEditorInputReadOnly() * @since 2.0 */ public boolean isEditorInputReadOnly() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IDocumentProviderExtension) { IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; return extension.isReadOnly(getEditorInput()); } return true; } /* * @see ITextEditorExtension2#isEditorInputModifiable() * @since 2.1 */ public boolean isEditorInputModifiable() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IDocumentProviderExtension) { IDocumentProviderExtension extension= (IDocumentProviderExtension) provider; return extension.isModifiable(getEditorInput()); } return true; } /* * @see ITextEditorExtension#addRulerContextMenuListener(IMenuListener) * @since 2.0 */ public void addRulerContextMenuListener(IMenuListener listener) { fRulerContextMenuListeners.add(listener); } /* * @see ITextEditorExtension#removeRulerContextMenuListener(IMenuListener) * @since 2.0 */ public void removeRulerContextMenuListener(IMenuListener listener) { fRulerContextMenuListeners.remove(listener); } /** * Returns whether this editor can handle the move of the original element * so that it ends up being the moved element. By default this method * returns <code>true</code>. Subclasses may reimplement. * * @param originalElement the original element * @param movedElement the moved element * @return whether this editor can handle the move of the original element * so that it ends up being the moved element * @since 2.0 */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { return true; } /** * Returns the offset of the given source viewer's document that corresponds * to the given widget offset or <code>-1</code> if there is no such offset. * * @param viewer the source viewer * @param widgetOffset the widget offset * @return the corresponding offset in the source viewer's document or <code>-1</code> * @since 2.1 */ protected final static int widgetOffset2ModelOffset(ISourceViewer viewer, int widgetOffset) { if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) viewer; return extension.widgetOffset2ModelOffset(widgetOffset); } return widgetOffset + viewer.getVisibleRegion().getOffset(); } /** * Returns the offset of the given source viewer's text widget that corresponds * to the given model offset or <code>-1</code> if there is no such offset. * * @param viewer the source viewer * @param modelOffset the model offset * @return the corresponding offset in the source viewer's text widget or <code>-1</code> * @since 3.0 */ protected final static int modelOffset2WidgetOffset(ISourceViewer viewer, int modelOffset) { if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) viewer; return extension.modelOffset2WidgetOffset(modelOffset); } return modelOffset - viewer.getVisibleRegion().getOffset(); } /** * Returns the minimal region of the given source viewer's document that completely * comprises everything that is visible in the viewer's widget. * * @param viewer the viewer go return the coverage for * @return the minimal region of the source viewer's document comprising the contents of the viewer's widget * @since 2.1 */ protected final static IRegion getCoverage(ISourceViewer viewer) { if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) viewer; return extension.getModelCoverage(); } return viewer.getVisibleRegion(); } /** * Tells whether the given region is visible in the given source viewer. * * @param viewer the source viewer * @param offset the offset of the region * @param length the length of the region * @return <code>true</code> if visible * @since 2.1 */ protected final static boolean isVisible(ISourceViewer viewer, int offset, int length) { if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) viewer; IRegion overlap= extension.modelRange2WidgetRange(new Region(offset, length)); return overlap != null; } return viewer.overlapsWithVisibleRegion(offset, length); } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean) * @since 3.0 */ public void showChangeInformation(boolean show) { // do nothing } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing() * @since 3.0 */ public boolean isChangeInformationShowing() { return false; } /** * Sets the given message as error message to this editor's status line. * * @param message message to be set * @since 3.2 */ protected void setStatusLineErrorMessage(String message) { IEditorStatusLine statusLine= (IEditorStatusLine)getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, message, null); } /** * Sets the given message as message to this editor's status line. * * @param message message to be set * @since 3.2 */ protected void setStatusLineMessage(String message) { IEditorStatusLine statusLine= (IEditorStatusLine)getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(false, message, null); } /** * Jumps to the next annotation according to the given direction. * * @param forward <code>true</code> if search direction is forward, <code>false</code> if backward * @return the selected annotation or <code>null</code> if none * @see #isNavigationTarget(Annotation) * @see #findAnnotation(int, int, boolean, Position) * @since 3.2 */ public Annotation gotoAnnotation(boolean forward) { ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); Position position= new Position(0, 0); Annotation annotation= findAnnotation(selection.getOffset(), selection.getLength(), forward, position); setStatusLineErrorMessage(null); setStatusLineMessage(null); if (annotation != null) { selectAndReveal(position.getOffset(), position.getLength()); setStatusLineMessage(annotation.getText()); } return annotation; } /** * Returns the annotation closest to the given range respecting the given * direction. If an annotation is found, the annotations current position * is copied into the provided annotation position. * * @param offset the region offset * @param length the region length * @param forward <code>true</code> for forwards, <code>false</code> for backward * @param annotationPosition the position of the found annotation * @return the found annotation * @since 3.2 */ protected Annotation findAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= Integer.MAX_VALUE; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= model.getAnnotationIterator(); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (!isNavigationTarget(a)) continue; Position p= model.getPosition(a); if (p == null) continue; if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) { if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { containingAnnotation= a; containingAnnotationPosition= p; currentAnnotation= p.length == length; } } else { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } else { currentDistance= offset + length - (p.getOffset() + p.length); if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } } } if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { annotationPosition.setOffset(containingAnnotationPosition.getOffset()); annotationPosition.setLength(containingAnnotationPosition.getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { annotationPosition.setOffset(nextAnnotationPosition.getOffset()); annotationPosition.setLength(nextAnnotationPosition.getLength()); } return nextAnnotation; } /** * Returns whether the given annotation is configured as a target for the * "Go to Next/Previous Annotation" actions. * <p> * Per default every annotation is a target. * </p> * * @param annotation the annotation * @return <code>true</code> if this is a target, <code>false</code> otherwise * @since 3.2 */ protected boolean isNavigationTarget(Annotation annotation) { return true; } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension4#showRevisionInformation(org.eclipse.jface.text.revisions.RevisionInformation, java.lang.String) * @since 3.2 */ public void showRevisionInformation(RevisionInformation info, String quickDiffProviderId) { // no implementation } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IEditorPersistable#restoreState(org.eclipse.ui.IMemento) * @since 3.3 */ public void restoreState(IMemento memento) { fMementoToRestore= memento; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento) * @since 3.3 */ public void saveState(IMemento memento) { ISelection selection= doGetSelection(); if (selection instanceof ITextSelection) { memento.putInteger(TAG_SELECTION_OFFSET, ((ITextSelection)selection).getOffset()); memento.putInteger(TAG_SELECTION_LENGTH, ((ITextSelection)selection).getLength()); } } /** * Returns whether the given memento contains saved state * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @return <code>true</code> if the given memento contains saved state * @since 3.3 */ protected boolean containsSavedState(IMemento memento) { return memento.getInteger(TAG_SELECTION_OFFSET) != null && memento.getInteger(TAG_SELECTION_LENGTH) != null; } /** * Restores this editor's state using the given memento. * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @since 3.3 */ protected void doRestoreState(IMemento memento) { Integer offset= memento.getInteger(TAG_SELECTION_OFFSET); if (offset == null) return; Integer length= memento.getInteger(TAG_SELECTION_LENGTH); if (length == null) return; doSetSelection(new TextSelection(offset.intValue(), length.intValue())); } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getSaveables() * @since 3.3 */ public Saveable[] getSaveables() { if (fSavable == null) fSavable= new TextEditorSavable(); return new Saveable[] { fSavable }; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getActiveSaveables() * @since 3.3 */ public Saveable[] getActiveSaveables() { return getSaveables(); } /** * This text editor's savable. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @since 3.3 */ protected class TextEditorSavable extends Saveable { /** The cached editor input. */ private IEditorInput fEditorInput; + /** The cached document. */ + private IDocument fDocument; /** * Creates a new savable for this text editor. */ public TextEditorSavable() { fEditorInput= getEditorInput(); Assert.isLegal(fEditorInput != null); } /* * @see org.eclipse.ui.Saveable#getName() */ public String getName() { return fEditorInput.getName(); } /* * @see org.eclipse.ui.Saveable#getToolTipText() */ public String getToolTipText() { return fEditorInput.getToolTipText(); } /* * @see org.eclipse.ui.Saveable#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { return fEditorInput.getImageDescriptor(); } /* * @see org.eclipse.ui.Saveable#doSave(org.eclipse.core.runtime.IProgressMonitor) * @since 3.3 */ public void doSave(IProgressMonitor monitor) throws CoreException { AbstractTextEditor.this.doSave(monitor); } public boolean isDirty() { return AbstractTextEditor.this.isDirty(); } /* * @see org.eclipse.ui.Saveable#supportsBackgroundSave() */ public boolean supportsBackgroundSave() { return false; } /* * @see org.eclipse.ui.Saveable#hashCode() */ public int hashCode() { Object document= getAdapter(IDocument.class); if (document == null) return 0; return document.hashCode(); } /* * @see org.eclipse.ui.Saveable#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Saveable)) return false; Object thisDocument= getAdapter(IDocument.class); Object otherDocument= ((Saveable)obj).getAdapter(IDocument.class); if (thisDocument == null && otherDocument == null) return true; return thisDocument != null && thisDocument.equals(otherDocument); } /** * Explicit comment needed to suppress wrong waning caused * by http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4848177 * * @see org.eclipse.ui.Saveable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (adapter == IDocument.class) { - IDocumentProvider documentProvider= getDocumentProvider(); - if (documentProvider == null) - return null; - return documentProvider.getDocument(fEditorInput); + if (fDocument == null) { + IDocumentProvider documentProvider= getDocumentProvider(); + if (documentProvider != null) + fDocument= documentProvider.getDocument(fEditorInput); + } + return fDocument; } return super.getAdapter(adapter); } } }
false
true
protected Annotation findAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= Integer.MAX_VALUE; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= model.getAnnotationIterator(); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (!isNavigationTarget(a)) continue; Position p= model.getPosition(a); if (p == null) continue; if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) { if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { containingAnnotation= a; containingAnnotationPosition= p; currentAnnotation= p.length == length; } } else { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } else { currentDistance= offset + length - (p.getOffset() + p.length); if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } } } if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { annotationPosition.setOffset(containingAnnotationPosition.getOffset()); annotationPosition.setLength(containingAnnotationPosition.getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { annotationPosition.setOffset(nextAnnotationPosition.getOffset()); annotationPosition.setLength(nextAnnotationPosition.getLength()); } return nextAnnotation; } /** * Returns whether the given annotation is configured as a target for the * "Go to Next/Previous Annotation" actions. * <p> * Per default every annotation is a target. * </p> * * @param annotation the annotation * @return <code>true</code> if this is a target, <code>false</code> otherwise * @since 3.2 */ protected boolean isNavigationTarget(Annotation annotation) { return true; } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension4#showRevisionInformation(org.eclipse.jface.text.revisions.RevisionInformation, java.lang.String) * @since 3.2 */ public void showRevisionInformation(RevisionInformation info, String quickDiffProviderId) { // no implementation } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IEditorPersistable#restoreState(org.eclipse.ui.IMemento) * @since 3.3 */ public void restoreState(IMemento memento) { fMementoToRestore= memento; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento) * @since 3.3 */ public void saveState(IMemento memento) { ISelection selection= doGetSelection(); if (selection instanceof ITextSelection) { memento.putInteger(TAG_SELECTION_OFFSET, ((ITextSelection)selection).getOffset()); memento.putInteger(TAG_SELECTION_LENGTH, ((ITextSelection)selection).getLength()); } } /** * Returns whether the given memento contains saved state * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @return <code>true</code> if the given memento contains saved state * @since 3.3 */ protected boolean containsSavedState(IMemento memento) { return memento.getInteger(TAG_SELECTION_OFFSET) != null && memento.getInteger(TAG_SELECTION_LENGTH) != null; } /** * Restores this editor's state using the given memento. * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @since 3.3 */ protected void doRestoreState(IMemento memento) { Integer offset= memento.getInteger(TAG_SELECTION_OFFSET); if (offset == null) return; Integer length= memento.getInteger(TAG_SELECTION_LENGTH); if (length == null) return; doSetSelection(new TextSelection(offset.intValue(), length.intValue())); } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getSaveables() * @since 3.3 */ public Saveable[] getSaveables() { if (fSavable == null) fSavable= new TextEditorSavable(); return new Saveable[] { fSavable }; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getActiveSaveables() * @since 3.3 */ public Saveable[] getActiveSaveables() { return getSaveables(); } /** * This text editor's savable. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @since 3.3 */ protected class TextEditorSavable extends Saveable { /** The cached editor input. */ private IEditorInput fEditorInput; /** * Creates a new savable for this text editor. */ public TextEditorSavable() { fEditorInput= getEditorInput(); Assert.isLegal(fEditorInput != null); } /* * @see org.eclipse.ui.Saveable#getName() */ public String getName() { return fEditorInput.getName(); } /* * @see org.eclipse.ui.Saveable#getToolTipText() */ public String getToolTipText() { return fEditorInput.getToolTipText(); } /* * @see org.eclipse.ui.Saveable#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { return fEditorInput.getImageDescriptor(); } /* * @see org.eclipse.ui.Saveable#doSave(org.eclipse.core.runtime.IProgressMonitor) * @since 3.3 */ public void doSave(IProgressMonitor monitor) throws CoreException { AbstractTextEditor.this.doSave(monitor); } public boolean isDirty() { return AbstractTextEditor.this.isDirty(); } /* * @see org.eclipse.ui.Saveable#supportsBackgroundSave() */ public boolean supportsBackgroundSave() { return false; } /* * @see org.eclipse.ui.Saveable#hashCode() */ public int hashCode() { Object document= getAdapter(IDocument.class); if (document == null) return 0; return document.hashCode(); } /* * @see org.eclipse.ui.Saveable#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Saveable)) return false; Object thisDocument= getAdapter(IDocument.class); Object otherDocument= ((Saveable)obj).getAdapter(IDocument.class); if (thisDocument == null && otherDocument == null) return true; return thisDocument != null && thisDocument.equals(otherDocument); } /** * Explicit comment needed to suppress wrong waning caused * by http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4848177 * * @see org.eclipse.ui.Saveable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (adapter == IDocument.class) { IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider == null) return null; return documentProvider.getDocument(fEditorInput); } return super.getAdapter(adapter); } } }
protected Annotation findAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= Integer.MAX_VALUE; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= model.getAnnotationIterator(); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (!isNavigationTarget(a)) continue; Position p= model.getPosition(a); if (p == null) continue; if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) { if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { containingAnnotation= a; containingAnnotationPosition= p; currentAnnotation= p.length == length; } } else { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } else { currentDistance= offset + length - (p.getOffset() + p.length); if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } } } if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { annotationPosition.setOffset(containingAnnotationPosition.getOffset()); annotationPosition.setLength(containingAnnotationPosition.getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { annotationPosition.setOffset(nextAnnotationPosition.getOffset()); annotationPosition.setLength(nextAnnotationPosition.getLength()); } return nextAnnotation; } /** * Returns whether the given annotation is configured as a target for the * "Go to Next/Previous Annotation" actions. * <p> * Per default every annotation is a target. * </p> * * @param annotation the annotation * @return <code>true</code> if this is a target, <code>false</code> otherwise * @since 3.2 */ protected boolean isNavigationTarget(Annotation annotation) { return true; } /* * @see org.eclipse.ui.texteditor.ITextEditorExtension4#showRevisionInformation(org.eclipse.jface.text.revisions.RevisionInformation, java.lang.String) * @since 3.2 */ public void showRevisionInformation(RevisionInformation info, String quickDiffProviderId) { // no implementation } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IEditorPersistable#restoreState(org.eclipse.ui.IMemento) * @since 3.3 */ public void restoreState(IMemento memento) { fMementoToRestore= memento; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento) * @since 3.3 */ public void saveState(IMemento memento) { ISelection selection= doGetSelection(); if (selection instanceof ITextSelection) { memento.putInteger(TAG_SELECTION_OFFSET, ((ITextSelection)selection).getOffset()); memento.putInteger(TAG_SELECTION_LENGTH, ((ITextSelection)selection).getLength()); } } /** * Returns whether the given memento contains saved state * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @return <code>true</code> if the given memento contains saved state * @since 3.3 */ protected boolean containsSavedState(IMemento memento) { return memento.getInteger(TAG_SELECTION_OFFSET) != null && memento.getInteger(TAG_SELECTION_LENGTH) != null; } /** * Restores this editor's state using the given memento. * <p> * Subclasses may extend or override this method.</p> * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @param memento the saved state of this editor * @since 3.3 */ protected void doRestoreState(IMemento memento) { Integer offset= memento.getInteger(TAG_SELECTION_OFFSET); if (offset == null) return; Integer length= memento.getInteger(TAG_SELECTION_LENGTH); if (length == null) return; doSetSelection(new TextSelection(offset.intValue(), length.intValue())); } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getSaveables() * @since 3.3 */ public Saveable[] getSaveables() { if (fSavable == null) fSavable= new TextEditorSavable(); return new Saveable[] { fSavable }; } /* * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * @see org.eclipse.ui.ISaveablesSource#getActiveSaveables() * @since 3.3 */ public Saveable[] getActiveSaveables() { return getSaveables(); } /** * This text editor's savable. * <p> * <em>This API is provisional and may change any time before the 3.3 API freeze.</em> * </p> * * @since 3.3 */ protected class TextEditorSavable extends Saveable { /** The cached editor input. */ private IEditorInput fEditorInput; /** The cached document. */ private IDocument fDocument; /** * Creates a new savable for this text editor. */ public TextEditorSavable() { fEditorInput= getEditorInput(); Assert.isLegal(fEditorInput != null); } /* * @see org.eclipse.ui.Saveable#getName() */ public String getName() { return fEditorInput.getName(); } /* * @see org.eclipse.ui.Saveable#getToolTipText() */ public String getToolTipText() { return fEditorInput.getToolTipText(); } /* * @see org.eclipse.ui.Saveable#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { return fEditorInput.getImageDescriptor(); } /* * @see org.eclipse.ui.Saveable#doSave(org.eclipse.core.runtime.IProgressMonitor) * @since 3.3 */ public void doSave(IProgressMonitor monitor) throws CoreException { AbstractTextEditor.this.doSave(monitor); } public boolean isDirty() { return AbstractTextEditor.this.isDirty(); } /* * @see org.eclipse.ui.Saveable#supportsBackgroundSave() */ public boolean supportsBackgroundSave() { return false; } /* * @see org.eclipse.ui.Saveable#hashCode() */ public int hashCode() { Object document= getAdapter(IDocument.class); if (document == null) return 0; return document.hashCode(); } /* * @see org.eclipse.ui.Saveable#equals(java.lang.Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Saveable)) return false; Object thisDocument= getAdapter(IDocument.class); Object otherDocument= ((Saveable)obj).getAdapter(IDocument.class); if (thisDocument == null && otherDocument == null) return true; return thisDocument != null && thisDocument.equals(otherDocument); } /** * Explicit comment needed to suppress wrong waning caused * by http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4848177 * * @see org.eclipse.ui.Saveable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { if (adapter == IDocument.class) { if (fDocument == null) { IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider != null) fDocument= documentProvider.getDocument(fEditorInput); } return fDocument; } return super.getAdapter(adapter); } } }
diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.java index 14c6a42c3..b31e5643a 100644 --- a/htroot/yacysearchitem.java +++ b/htroot/yacysearchitem.java @@ -1,206 +1,208 @@ // yacysearchitem.java // (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 28.08.2007 on http://yacy.net // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $ // $LastChangedRevision: 1986 $ // $LastChangedBy: orbiter $ // // LICENSE // // 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 import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.TreeSet; import de.anomic.http.httpRequestHeader; import de.anomic.plasma.plasmaProfiling; import de.anomic.plasma.plasmaSearchEvent; import de.anomic.plasma.plasmaSearchQuery; import de.anomic.plasma.plasmaSearchRankingProcess; import de.anomic.plasma.plasmaSnippetCache; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverObjects; import de.anomic.server.serverProfiling; import de.anomic.server.serverSwitch; import de.anomic.tools.crypt; import de.anomic.tools.nxTools; import de.anomic.tools.yFormatter; import de.anomic.yacy.yacyNewsPool; import de.anomic.yacy.yacySeed; import de.anomic.yacy.yacyURL; public class yacysearchitem { private static boolean col = true; private static final int namelength = 60; private static final int urllength = 120; public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; final serverObjects prop = new serverObjects(); final String eventID = post.get("eventID", ""); final boolean authenticated = sb.adminAuthenticated(header) >= 2; final int item = post.getInt("item", -1); final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); final int display = (post == null) ? 0 : post.getInt("display", 0); // default settings for blank item prop.put("content", "0"); prop.put("rss", "0"); prop.put("references", "0"); prop.put("rssreferences", "0"); prop.put("dynamic", "0"); // find search event final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID); if (theSearch == null) { // the event does not exist, show empty page return prop; } final plasmaSearchQuery theQuery = theSearch.getQuery(); // dynamically update count values final int offset = theQuery.neededResults() - theQuery.displayResults() + 1; prop.put("offset", offset); prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1); prop.put("totalcount", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("localResourceSize", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("remoteResourceSize", yFormatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("remoteIndexCount", yFormatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("remotePeerCount", yFormatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) { // text search // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content final int port=result.url().getPort(); yacyURL faviconURL; try { faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null); } catch (final MalformedURLException e1) { faviconURL = null; } prop.put("content", 1); // switch on specific content prop.put("content_authorized", authenticated ? "1" : "0"); prop.put("content_authorized_recommend", (sb.webIndex.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0"); prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*"); prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*"); prop.put("content_authorized_urlhash", result.hash()); prop.putHTML("content_title", result.title()); + prop.putXML("content_title-xml", result.title()); prop.putHTML("content_link", result.urlstring()); prop.put("content_display", display); prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading prop.put("content_urlhash", result.hash()); prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash())); prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength)); prop.put("content_date", plasmaSwitchboard.dateString(result.modified())); prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified())); prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash())); prop.putNum("content_size", result.filesize()); prop.put("content_nl", (item == 0) ? 0 : 1); final TreeSet<String>[] query = theQuery.queryWords(); yacyURL wordURL = null; try { prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8")); } catch (final UnsupportedEncodingException e) {} prop.putHTML("content_former", theQuery.queryString); prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) + ((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") + (((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : "")); final plasmaSnippetCache.TextSnippet snippet = result.textSnippet(); prop.put("content_description", (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes)); + prop.putXML("content_description", (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0)); return prop; } if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) { // image search; shows thumbnails prop.put("content", theQuery.contentdom + 1); // switch on specific content final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item); if (ms == null) { prop.put("content_items", "0"); } else { prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false)); prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false)); prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href)); prop.putHTML("content_items_0_name", shorten(ms.name, namelength)); prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image prop.put("content_items_0_source", ms.source.toNormalform(true, false)); prop.put("content_items_0_sourcedom", ms.source.getHost()); prop.put("content_items", 1); } return prop; } if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) { // any other media content // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content prop.put("content", theQuery.contentdom + 1); // switch on specific content final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets(); if (item == 0) col = true; if (media != null) { plasmaSnippetCache.MediaSnippet ms; int c = 0; for (int i = 0; i < media.size(); i++) { ms = media.get(i); prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false)); prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength)); prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength)); prop.put("content_items_" + i + "_col", (col) ? "0" : "1"); c++; col = !col; } prop.put("content_items", c); } else { prop.put("content_items", "0"); } return prop; } return prop; } private static String shorten(final String s, final int length) { if (s.length() <= length) return s; final int p = s.lastIndexOf('.'); if (p < 0) return s.substring(0, length - 3) + "..."; return s.substring(0, length - (s.length() - p) - 3) + "..." + s.substring(p); } }
false
true
public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; final serverObjects prop = new serverObjects(); final String eventID = post.get("eventID", ""); final boolean authenticated = sb.adminAuthenticated(header) >= 2; final int item = post.getInt("item", -1); final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); final int display = (post == null) ? 0 : post.getInt("display", 0); // default settings for blank item prop.put("content", "0"); prop.put("rss", "0"); prop.put("references", "0"); prop.put("rssreferences", "0"); prop.put("dynamic", "0"); // find search event final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID); if (theSearch == null) { // the event does not exist, show empty page return prop; } final plasmaSearchQuery theQuery = theSearch.getQuery(); // dynamically update count values final int offset = theQuery.neededResults() - theQuery.displayResults() + 1; prop.put("offset", offset); prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1); prop.put("totalcount", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("localResourceSize", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("remoteResourceSize", yFormatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("remoteIndexCount", yFormatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("remotePeerCount", yFormatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) { // text search // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content final int port=result.url().getPort(); yacyURL faviconURL; try { faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null); } catch (final MalformedURLException e1) { faviconURL = null; } prop.put("content", 1); // switch on specific content prop.put("content_authorized", authenticated ? "1" : "0"); prop.put("content_authorized_recommend", (sb.webIndex.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0"); prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*"); prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*"); prop.put("content_authorized_urlhash", result.hash()); prop.putHTML("content_title", result.title()); prop.putHTML("content_link", result.urlstring()); prop.put("content_display", display); prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading prop.put("content_urlhash", result.hash()); prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash())); prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength)); prop.put("content_date", plasmaSwitchboard.dateString(result.modified())); prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified())); prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash())); prop.putNum("content_size", result.filesize()); prop.put("content_nl", (item == 0) ? 0 : 1); final TreeSet<String>[] query = theQuery.queryWords(); yacyURL wordURL = null; try { prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8")); } catch (final UnsupportedEncodingException e) {} prop.putHTML("content_former", theQuery.queryString); prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) + ((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") + (((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : "")); final plasmaSnippetCache.TextSnippet snippet = result.textSnippet(); prop.put("content_description", (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0)); return prop; } if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) { // image search; shows thumbnails prop.put("content", theQuery.contentdom + 1); // switch on specific content final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item); if (ms == null) { prop.put("content_items", "0"); } else { prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false)); prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false)); prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href)); prop.putHTML("content_items_0_name", shorten(ms.name, namelength)); prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image prop.put("content_items_0_source", ms.source.toNormalform(true, false)); prop.put("content_items_0_sourcedom", ms.source.getHost()); prop.put("content_items", 1); } return prop; } if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) { // any other media content // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content prop.put("content", theQuery.contentdom + 1); // switch on specific content final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets(); if (item == 0) col = true; if (media != null) { plasmaSnippetCache.MediaSnippet ms; int c = 0; for (int i = 0; i < media.size(); i++) { ms = media.get(i); prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false)); prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength)); prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength)); prop.put("content_items_" + i + "_col", (col) ? "0" : "1"); c++; col = !col; } prop.put("content_items", c); } else { prop.put("content_items", "0"); } return prop; } return prop; }
public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) { final plasmaSwitchboard sb = (plasmaSwitchboard) env; final serverObjects prop = new serverObjects(); final String eventID = post.get("eventID", ""); final boolean authenticated = sb.adminAuthenticated(header) >= 2; final int item = post.getInt("item", -1); final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true); final int display = (post == null) ? 0 : post.getInt("display", 0); // default settings for blank item prop.put("content", "0"); prop.put("rss", "0"); prop.put("references", "0"); prop.put("rssreferences", "0"); prop.put("dynamic", "0"); // find search event final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID); if (theSearch == null) { // the event does not exist, show empty page return prop; } final plasmaSearchQuery theQuery = theSearch.getQuery(); // dynamically update count values final int offset = theQuery.neededResults() - theQuery.displayResults() + 1; prop.put("offset", offset); prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1); prop.put("totalcount", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("localResourceSize", yFormatter.number(theSearch.getRankingResult().getLocalResourceSize(), true)); prop.put("remoteResourceSize", yFormatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true)); prop.put("remoteIndexCount", yFormatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true)); prop.put("remotePeerCount", yFormatter.number(theSearch.getRankingResult().getRemotePeerCount(), true)); if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) { // text search // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content final int port=result.url().getPort(); yacyURL faviconURL; try { faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null); } catch (final MalformedURLException e1) { faviconURL = null; } prop.put("content", 1); // switch on specific content prop.put("content_authorized", authenticated ? "1" : "0"); prop.put("content_authorized_recommend", (sb.webIndex.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0"); prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*"); prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*"); prop.put("content_authorized_urlhash", result.hash()); prop.putHTML("content_title", result.title()); prop.putXML("content_title-xml", result.title()); prop.putHTML("content_link", result.urlstring()); prop.put("content_display", display); prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading prop.put("content_urlhash", result.hash()); prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash())); prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength)); prop.put("content_date", plasmaSwitchboard.dateString(result.modified())); prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified())); prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash())); prop.putNum("content_size", result.filesize()); prop.put("content_nl", (item == 0) ? 0 : 1); final TreeSet<String>[] query = theQuery.queryWords(); yacyURL wordURL = null; try { prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8")); } catch (final UnsupportedEncodingException e) {} prop.putHTML("content_former", theQuery.queryString); prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) + ((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") + (((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : "")); final plasmaSnippetCache.TextSnippet snippet = result.textSnippet(); prop.put("content_description", (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes)); prop.putXML("content_description", (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes)); serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0)); return prop; } if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) { // image search; shows thumbnails prop.put("content", theQuery.contentdom + 1); // switch on specific content final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item); if (ms == null) { prop.put("content_items", "0"); } else { prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false)); prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false)); prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href)); prop.putHTML("content_items_0_name", shorten(ms.name, namelength)); prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image prop.put("content_items_0_source", ms.source.toNormalform(true, false)); prop.put("content_items_0_sourcedom", ms.source.getHost()); prop.put("content_items", 1); } return prop; } if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) || (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) { // any other media content // generate result object final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item); if (result == null) return prop; // no content prop.put("content", theQuery.contentdom + 1); // switch on specific content final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets(); if (item == 0) col = true; if (media != null) { plasmaSnippetCache.MediaSnippet ms; int c = 0; for (int i = 0; i < media.size(); i++) { ms = media.get(i); prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false)); prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength)); prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength)); prop.put("content_items_" + i + "_col", (col) ? "0" : "1"); c++; col = !col; } prop.put("content_items", c); } else { prop.put("content_items", "0"); } return prop; } return prop; }
diff --git a/alchemy-midlet/src/alchemy/libs/LibUI1Func.java b/alchemy-midlet/src/alchemy/libs/LibUI1Func.java index 913660a..c7d582c 100644 --- a/alchemy-midlet/src/alchemy/libs/LibUI1Func.java +++ b/alchemy-midlet/src/alchemy/libs/LibUI1Func.java @@ -1,387 +1,387 @@ /* * This file is a part of Alchemy OS project. * Copyright (C) 2011-2012, Sergey Basalaev <[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 alchemy.libs; import alchemy.libs.ui.UICanvas; import alchemy.core.Context; import alchemy.core.Int; import alchemy.midlet.UIServer; import alchemy.nlib.NativeFunction; import java.io.InputStream; import java.util.Date; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.ChoiceGroup; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.DateField; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Gauge; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.ImageItem; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.List; import javax.microedition.lcdui.StringItem; import javax.microedition.lcdui.TextBox; import javax.microedition.lcdui.TextField; /** * libui.1.so functions. * @author Sergey Basalaev */ class LibUI1Func extends NativeFunction { public LibUI1Func(String name, int index) { super(name, index); } protected Object execNative(Context c, Object[] args) throws Exception { switch (index) { case 0: // new_image(w: Int, h: Int): Image return Image.createImage(ival(args[0]), ival(args[1])); case 1: // Image.graphics(): Graphics return ((Image)args[0]).getGraphics(); case 2: { // image_from_argb(argb: Array, w: Int, h: Int, alpha: Bool): Image Object[] data = (Object[])args[0]; final int[] argb = new int[data.length]; for (int i=argb.length-1; i>=0; i--) { argb[i] = ival(data[i]); } return Image.createRGBImage(argb, ival(args[1]), ival(args[2]), true); } case 3: // image_from_stream(in: IStream): Image return Image.createImage((InputStream)args[0]); case 4: { // image_from_data(data: BArray): Image final byte[] data = (byte[])args[0]; return Image.createImage(data, 0, data.length); } case 5: // image_from_image(im: Image, x: Int, y: Int, w: Int, h: Int): Image return Image.createImage((Image)args[0], ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), 0); case 6: { // Image.get_argb(argb: Array, ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int) Object[] data = (Object[])args[1]; int ofs = ival(args[2]); int scanlen = ival(args[3]); int x = ival(args[4]); int y = ival(args[5]); int w = ival(args[6]); int h = ival(args[7]); int[] argb = new int[scanlen * h]; ((Image)args[0]).getRGB(argb, 0, scanlen, x, y, w, h); for (int i=argb.length-1; i>=0; i--) { data[ofs+i] = Ival(argb[i]); } return null; } case 7: // Graphics.get_color(): Int return Ival(((Graphics)args[0]).getColor()); case 8: // Graphics.set_color(rgb: Int) ((Graphics)args[0]).setColor(ival(args[1])); return null; case 9: // Graphics.get_font(): Int return Ival(font2int(((Graphics)args[0]).getFont())); case 10: // Graphics.set_font(font: Int) ((Graphics)args[0]).setFont(int2font(ival(args[1]))); return null; case 11: // str_width(font: Int, str: String): Int return Ival(int2font(ival(args[0])).stringWidth((String)args[1])); case 12: // font_height(font: Int): Int return Ival(int2font(ival(args[0])).getHeight()); case 13: // Graphics.draw_line(x1: Int, y1: Int, x2: Int, y2: Int) ((Graphics)args[0]).drawLine(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 14: // Graphics.draw_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).drawRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 15: // Graphics.fill_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).fillRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 16: // Graphics.draw_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).drawRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 17: // Graphics.fill_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).fillRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 18: // Graphics.draw_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).drawArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 19: // Graphics.fill_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).fillArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 20: // Graphics.fill_triangle(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int) ((Graphics)args[0]).fillTriangle(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 21: // Graphics.draw_string(str: String, x: Int, y: Int) ((Graphics)args[0]).drawString((String)args[1], ival(args[2]), ival(args[3]), 0); return null; case 22: // Graphics.draw_image(im: Image, x: Int, y: Int) ((Graphics)args[0]).drawImage((Image)args[1], ival(args[2]), ival(args[3]), 0); return null; case 23: // Graphics.copy_area(xsrc: Int, ysrc: Int, w: Int, h: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).copyArea(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), 0); return null; case 24: // new_canvas(full: Bool): Canvas return new UICanvas(bval(args[0])); case 25: { // Canvas.graphics(): Graphics return ((UICanvas)args[0]).getGraphics(); } case 26: { // Canvas.read_key(): Int // compatibility function with previous non-event canvas behavior Object[] event = (Object[])UIServer.readEvent(c, false); if (event != null && event[0] == UIServer.EVENT_KEY_PRESS && event[1] == args[0]) { return event[2]; } else { return Int.ZERO; } } case 27: { // ui_set_screen(scr: Screen) if (args[0] != null) { UIServer.setScreen(c, (Displayable)args[0]); } else { UIServer.removeScreen(c); } return null; } case 28: // Screen.get_height(): Int return Ival(((Displayable)args[0]).getHeight()); case 29: // Screen.get_width(): Int return Ival(((Displayable)args[0]).getWidth()); case 30: // Screen.get_title(): String return ((Displayable)args[0]).getTitle(); case 31: { // Screen.set_title(title: String) ((Displayable)args[0]).setTitle((String)args[1]); return null; } case 32: // Screen.is_shown(): Bool return Ival(((Displayable)args[0]).isShown()); case 33: // Canvas.refresh() ((UICanvas)args[0]).repaint(); return null; case 34: // ui_read_event(): UIEvent return UIServer.readEvent(c, false); case 35: // ui_wait_event(): UIEvent return UIServer.readEvent(c, true); case 36: // new_editbox(mode: Int): EditBox return new TextBox(null, null, Short.MAX_VALUE, ival(args[0])); case 37: // EditBox.get_text(): String return ((TextBox)args[0]).getString(); case 38: // EditBox.set_text(text: String) ((TextBox)args[0]).setString((String)args[1]); return null; case 39: { // new_listbox(strings: [String], images: [Image], select: Menu): ListBox Object[] str = (Object[])args[0]; String[] strings = new String[str.length]; System.arraycopy(str, 0, strings, 0, str.length); Object[] img = (Object[])args[1]; Image[] images = null; if (img != null) { images = new Image[img.length]; System.arraycopy(img, 0, images, 0, img.length); } List list = new List(null, Choice.IMPLICIT, strings, images); list.setSelectCommand((Command)args[2]); return list; } case 40: // ListBox.get_index(): Int return Ival(((List)args[0]).getSelectedIndex()); case 41: // ListBox.set_index(index: Int) ((List)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 42: // ui_get_screen(): Screen return UIServer.getScreen(c); case 43: // new_menu(text: String, priority: Int): Menu return new Command((String)args[0], Command.SCREEN, ival(args[1])); case 44: // Menu.get_text(): String return ((Command)args[0]).getLabel(); case 45: // Menu.get_priority(): Int return Ival(((Command)args[0]).getPriority()); case 46: // Screen.add_menu(menu: Menu) ((Displayable)args[0]).addCommand((Command)args[1]); return null; case 47: // Screen.remove_menu(menu: Menu) ((Displayable)args[0]).removeCommand((Command)args[1]); return null; case 48: // new_form(): Form return new Form(null); case 49: // Form.add(item: Item) ((Form)args[0]).append((Item)args[1]); return null; case 50: // Form.get(at: Int): Item return ((Form)args[0]).get(ival(args[1])); case 51: // Form.set(at: Int, item: Item) ((Form)args[0]).set(ival(args[1]), (Item)args[2]); return null; case 52: // Form.insert(at: Int, item: Item) ((Form)args[0]).insert(ival(args[1]), (Item)args[2]); return null; case 53: // Form.remove(at: Int) ((Form)args[0]).delete(ival(args[1])); return null; case 54: // Form.size(): Int return Ival(((Form)args[0]).size()); case 55: // Form.clear() ((Form)args[0]).deleteAll(); return null; case 56: // Item.get_label(): String return ((Item)args[0]).getLabel(); case 57: // Item.set_label(label: String) ((Item)args[0]).setLabel((String)args[1]); return null; case 58: // new_textitem(label: String, text: String): TextItem return new StringItem((String)args[0], String.valueOf(args[1])+'\n'); case 59: // TextItem.get_text(): String return ((StringItem)args[0]).getText(); case 60: // TextItem.set_text(text: String) ((StringItem)args[0]).setText(String.valueOf(args[1])+'\n'); return null; case 61: // TextItem.get_font(): Int return Ival(font2int(((StringItem)args[0]).getFont())); case 62: // TextItem.set_font(font: Int) ((StringItem)args[0]).setFont(int2font(ival(args[1]))); return null; case 63: // new_imageitem(label: String, img: Image): ImageItem return new ImageItem((String)args[0], (Image)args[1], Item.LAYOUT_NEWLINE_AFTER, null); case 64: // ImageItem.get_image(): Image return ((ImageItem)args[0]).getImage(); case 65: // ImageItem.set_image(img: Image) ((ImageItem)args[0]).setImage((Image)args[1]); return null; case 66: // new_edititem(label: String, text: String, mode: Int, size: Int): EditItem return new TextField((String)args[0], (String)args[1], ival(args[3]), ival(args[2])); case 67: // EditItem.get_text(): String return ((TextField)args[0]).getString(); case 68: // EditItem.set_text(text: String) - ((TextField)args[0]).setString((String)args[0]); + ((TextField)args[0]).setString((String)args[1]); return null; case 69: // new_gaugeitem(label: String, max: Int, init: Int): GaugeItem return new Gauge((String)args[0], true, ival(args[1]), ival(args[2])); case 70: // GaugeItem.get_value(): Int return Ival(((Gauge)args[0]).getValue()); case 71: // GaugeItem.set_value(val: Int) ((Gauge)args[0]).setValue(ival(args[1])); return null; case 72: // GaugeItem.get_maxvalue(): Int return Ival(((Gauge)args[0]).getMaxValue()); case 73: // GaugeItem.set_maxvalue(val: Int) ((Gauge)args[0]).setMaxValue(ival(args[1])); return null; case 74: // new_dateitem(label: String, mode: Int): DateItem return new DateField((String)args[0], ival(args[1])); case 75: { // DateItem.get_date(item: Item): Long Date date = ((DateField)args[0]).getDate(); return (date == null) ? null : Lval(date.getTime()); } case 76: // DateItem.set_date(date: Long) ((DateField)args[0]).setDate(new Date(lval(args[1]))); return null; case 77: { // new_checkitem(label: String, text: String, checked: Bool): CheckItem ChoiceGroup check = new ChoiceGroup((String)args[0], Choice.MULTIPLE); check.append((String)args[1], null); check.setSelectedIndex(0, bval(args[2])); return check; } case 78: { // CheckItem.get_checked(): Bool boolean[] checked = new boolean[1]; ((ChoiceGroup)args[0]).getSelectedFlags(checked); return Ival(checked[0]); } case 79: // CheckItem.set_checked(checked: Bool) ((ChoiceGroup)args[0]).setSelectedIndex(0, bval(args[1])); return null; case 80: // CheckItem.get_text(): String return ((ChoiceGroup)args[0]).getString(0); case 81: // CheckItem.set_text(text: String) ((ChoiceGroup)args[0]).set(0, (String)args[1], null); return null; case 82: { // new_radioitem(label: String, strings: [String]): RadioItem Object[] array = (Object[])args[1]; String[] strings = new String[array.length]; System.arraycopy(array, 0, strings, 0, array.length); return new ChoiceGroup((String)args[0], Choice.EXCLUSIVE, strings, null); } case 83: // RadioItem.get_index(): Int return Ival(((ChoiceGroup)args[0]).getSelectedIndex()); case 84: // RadioItem.set_index(index: String) ((ChoiceGroup)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 85: { // new_textbox(text: String): TextBox Form box = new Form(null); box.append(new StringItem(null, (String)args[0])); return box; } case 86: // TextBox.get_text(): String return ((StringItem)((Form)args[0]).get(0)).getText(); case 87: // TextBox.set_text(text: String) ((StringItem)((Form)args[0]).get(0)).setText((String)args[1]); return null; case 88: // font_baseline(font: Int): Int return Ival(int2font(ival(args[0])).getBaselinePosition()); case 89: // Graphics.get_stroke(): Int return Ival(((Graphics)args[0]).getStrokeStyle()); case 90: // Graphics.set_stroke(stroke: Int) ((Graphics)args[0]).setStrokeStyle(ival(args[1])); return null; case 91: // Graphics.draw_region(im: Image, xsrc: Int, ysrc: Int, w: Int, h: Int, trans: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).drawRegion((Image)args[1], ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), ival(args[8]), 0); return null; case 92: { // Graphics.draw_rgb(rgb: [Int], ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int, alpha: Bool) Object[] rgbInts = (Object[])args[1]; int[] rgb = new int[rgbInts.length]; for (int i=rgb.length-1; i>=0; i--) { rgb[i] = ival(rgbInts[i]); } ((Graphics)args[0]).drawRGB(rgb, ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), bval(args[8])); return null; } case 93: // Canvas.action_code(key: Int): Int return Ival(((UICanvas)args[0]).getGameAction(ival(args[1]))); case 94: // Canvas.has_ptr_events(): Bool return Ival(((UICanvas)args[0]).hasPointerEvents()); case 95: // Canvas.has_ptrdrag_event(): Bool return Ival(((UICanvas)args[0]).hasPointerMotionEvents()); case 96: { // image_from_file(file: String): Image InputStream in = c.fs().read(c.toFile((String)args[0])); c.addStream(in); Image img = Image.createImage(in); in.close(); c.removeStream(in); return img; } default: return null; } } private static int font2int(Font f) { return f.getFace() | f.getSize() | f.getStyle(); } private static Font int2font(int mask) { return Font.getFont(mask & 0x60, mask & 0x7, mask & 0x18); } private static String titleFor(Context c) { Object title = String.valueOf(c.get("ui.title")); return (title != null) ? title.toString() : c.getName(); } public String soname() { return "libui.1.so"; } }
true
true
protected Object execNative(Context c, Object[] args) throws Exception { switch (index) { case 0: // new_image(w: Int, h: Int): Image return Image.createImage(ival(args[0]), ival(args[1])); case 1: // Image.graphics(): Graphics return ((Image)args[0]).getGraphics(); case 2: { // image_from_argb(argb: Array, w: Int, h: Int, alpha: Bool): Image Object[] data = (Object[])args[0]; final int[] argb = new int[data.length]; for (int i=argb.length-1; i>=0; i--) { argb[i] = ival(data[i]); } return Image.createRGBImage(argb, ival(args[1]), ival(args[2]), true); } case 3: // image_from_stream(in: IStream): Image return Image.createImage((InputStream)args[0]); case 4: { // image_from_data(data: BArray): Image final byte[] data = (byte[])args[0]; return Image.createImage(data, 0, data.length); } case 5: // image_from_image(im: Image, x: Int, y: Int, w: Int, h: Int): Image return Image.createImage((Image)args[0], ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), 0); case 6: { // Image.get_argb(argb: Array, ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int) Object[] data = (Object[])args[1]; int ofs = ival(args[2]); int scanlen = ival(args[3]); int x = ival(args[4]); int y = ival(args[5]); int w = ival(args[6]); int h = ival(args[7]); int[] argb = new int[scanlen * h]; ((Image)args[0]).getRGB(argb, 0, scanlen, x, y, w, h); for (int i=argb.length-1; i>=0; i--) { data[ofs+i] = Ival(argb[i]); } return null; } case 7: // Graphics.get_color(): Int return Ival(((Graphics)args[0]).getColor()); case 8: // Graphics.set_color(rgb: Int) ((Graphics)args[0]).setColor(ival(args[1])); return null; case 9: // Graphics.get_font(): Int return Ival(font2int(((Graphics)args[0]).getFont())); case 10: // Graphics.set_font(font: Int) ((Graphics)args[0]).setFont(int2font(ival(args[1]))); return null; case 11: // str_width(font: Int, str: String): Int return Ival(int2font(ival(args[0])).stringWidth((String)args[1])); case 12: // font_height(font: Int): Int return Ival(int2font(ival(args[0])).getHeight()); case 13: // Graphics.draw_line(x1: Int, y1: Int, x2: Int, y2: Int) ((Graphics)args[0]).drawLine(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 14: // Graphics.draw_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).drawRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 15: // Graphics.fill_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).fillRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 16: // Graphics.draw_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).drawRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 17: // Graphics.fill_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).fillRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 18: // Graphics.draw_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).drawArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 19: // Graphics.fill_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).fillArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 20: // Graphics.fill_triangle(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int) ((Graphics)args[0]).fillTriangle(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 21: // Graphics.draw_string(str: String, x: Int, y: Int) ((Graphics)args[0]).drawString((String)args[1], ival(args[2]), ival(args[3]), 0); return null; case 22: // Graphics.draw_image(im: Image, x: Int, y: Int) ((Graphics)args[0]).drawImage((Image)args[1], ival(args[2]), ival(args[3]), 0); return null; case 23: // Graphics.copy_area(xsrc: Int, ysrc: Int, w: Int, h: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).copyArea(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), 0); return null; case 24: // new_canvas(full: Bool): Canvas return new UICanvas(bval(args[0])); case 25: { // Canvas.graphics(): Graphics return ((UICanvas)args[0]).getGraphics(); } case 26: { // Canvas.read_key(): Int // compatibility function with previous non-event canvas behavior Object[] event = (Object[])UIServer.readEvent(c, false); if (event != null && event[0] == UIServer.EVENT_KEY_PRESS && event[1] == args[0]) { return event[2]; } else { return Int.ZERO; } } case 27: { // ui_set_screen(scr: Screen) if (args[0] != null) { UIServer.setScreen(c, (Displayable)args[0]); } else { UIServer.removeScreen(c); } return null; } case 28: // Screen.get_height(): Int return Ival(((Displayable)args[0]).getHeight()); case 29: // Screen.get_width(): Int return Ival(((Displayable)args[0]).getWidth()); case 30: // Screen.get_title(): String return ((Displayable)args[0]).getTitle(); case 31: { // Screen.set_title(title: String) ((Displayable)args[0]).setTitle((String)args[1]); return null; } case 32: // Screen.is_shown(): Bool return Ival(((Displayable)args[0]).isShown()); case 33: // Canvas.refresh() ((UICanvas)args[0]).repaint(); return null; case 34: // ui_read_event(): UIEvent return UIServer.readEvent(c, false); case 35: // ui_wait_event(): UIEvent return UIServer.readEvent(c, true); case 36: // new_editbox(mode: Int): EditBox return new TextBox(null, null, Short.MAX_VALUE, ival(args[0])); case 37: // EditBox.get_text(): String return ((TextBox)args[0]).getString(); case 38: // EditBox.set_text(text: String) ((TextBox)args[0]).setString((String)args[1]); return null; case 39: { // new_listbox(strings: [String], images: [Image], select: Menu): ListBox Object[] str = (Object[])args[0]; String[] strings = new String[str.length]; System.arraycopy(str, 0, strings, 0, str.length); Object[] img = (Object[])args[1]; Image[] images = null; if (img != null) { images = new Image[img.length]; System.arraycopy(img, 0, images, 0, img.length); } List list = new List(null, Choice.IMPLICIT, strings, images); list.setSelectCommand((Command)args[2]); return list; } case 40: // ListBox.get_index(): Int return Ival(((List)args[0]).getSelectedIndex()); case 41: // ListBox.set_index(index: Int) ((List)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 42: // ui_get_screen(): Screen return UIServer.getScreen(c); case 43: // new_menu(text: String, priority: Int): Menu return new Command((String)args[0], Command.SCREEN, ival(args[1])); case 44: // Menu.get_text(): String return ((Command)args[0]).getLabel(); case 45: // Menu.get_priority(): Int return Ival(((Command)args[0]).getPriority()); case 46: // Screen.add_menu(menu: Menu) ((Displayable)args[0]).addCommand((Command)args[1]); return null; case 47: // Screen.remove_menu(menu: Menu) ((Displayable)args[0]).removeCommand((Command)args[1]); return null; case 48: // new_form(): Form return new Form(null); case 49: // Form.add(item: Item) ((Form)args[0]).append((Item)args[1]); return null; case 50: // Form.get(at: Int): Item return ((Form)args[0]).get(ival(args[1])); case 51: // Form.set(at: Int, item: Item) ((Form)args[0]).set(ival(args[1]), (Item)args[2]); return null; case 52: // Form.insert(at: Int, item: Item) ((Form)args[0]).insert(ival(args[1]), (Item)args[2]); return null; case 53: // Form.remove(at: Int) ((Form)args[0]).delete(ival(args[1])); return null; case 54: // Form.size(): Int return Ival(((Form)args[0]).size()); case 55: // Form.clear() ((Form)args[0]).deleteAll(); return null; case 56: // Item.get_label(): String return ((Item)args[0]).getLabel(); case 57: // Item.set_label(label: String) ((Item)args[0]).setLabel((String)args[1]); return null; case 58: // new_textitem(label: String, text: String): TextItem return new StringItem((String)args[0], String.valueOf(args[1])+'\n'); case 59: // TextItem.get_text(): String return ((StringItem)args[0]).getText(); case 60: // TextItem.set_text(text: String) ((StringItem)args[0]).setText(String.valueOf(args[1])+'\n'); return null; case 61: // TextItem.get_font(): Int return Ival(font2int(((StringItem)args[0]).getFont())); case 62: // TextItem.set_font(font: Int) ((StringItem)args[0]).setFont(int2font(ival(args[1]))); return null; case 63: // new_imageitem(label: String, img: Image): ImageItem return new ImageItem((String)args[0], (Image)args[1], Item.LAYOUT_NEWLINE_AFTER, null); case 64: // ImageItem.get_image(): Image return ((ImageItem)args[0]).getImage(); case 65: // ImageItem.set_image(img: Image) ((ImageItem)args[0]).setImage((Image)args[1]); return null; case 66: // new_edititem(label: String, text: String, mode: Int, size: Int): EditItem return new TextField((String)args[0], (String)args[1], ival(args[3]), ival(args[2])); case 67: // EditItem.get_text(): String return ((TextField)args[0]).getString(); case 68: // EditItem.set_text(text: String) ((TextField)args[0]).setString((String)args[0]); return null; case 69: // new_gaugeitem(label: String, max: Int, init: Int): GaugeItem return new Gauge((String)args[0], true, ival(args[1]), ival(args[2])); case 70: // GaugeItem.get_value(): Int return Ival(((Gauge)args[0]).getValue()); case 71: // GaugeItem.set_value(val: Int) ((Gauge)args[0]).setValue(ival(args[1])); return null; case 72: // GaugeItem.get_maxvalue(): Int return Ival(((Gauge)args[0]).getMaxValue()); case 73: // GaugeItem.set_maxvalue(val: Int) ((Gauge)args[0]).setMaxValue(ival(args[1])); return null; case 74: // new_dateitem(label: String, mode: Int): DateItem return new DateField((String)args[0], ival(args[1])); case 75: { // DateItem.get_date(item: Item): Long Date date = ((DateField)args[0]).getDate(); return (date == null) ? null : Lval(date.getTime()); } case 76: // DateItem.set_date(date: Long) ((DateField)args[0]).setDate(new Date(lval(args[1]))); return null; case 77: { // new_checkitem(label: String, text: String, checked: Bool): CheckItem ChoiceGroup check = new ChoiceGroup((String)args[0], Choice.MULTIPLE); check.append((String)args[1], null); check.setSelectedIndex(0, bval(args[2])); return check; } case 78: { // CheckItem.get_checked(): Bool boolean[] checked = new boolean[1]; ((ChoiceGroup)args[0]).getSelectedFlags(checked); return Ival(checked[0]); } case 79: // CheckItem.set_checked(checked: Bool) ((ChoiceGroup)args[0]).setSelectedIndex(0, bval(args[1])); return null; case 80: // CheckItem.get_text(): String return ((ChoiceGroup)args[0]).getString(0); case 81: // CheckItem.set_text(text: String) ((ChoiceGroup)args[0]).set(0, (String)args[1], null); return null; case 82: { // new_radioitem(label: String, strings: [String]): RadioItem Object[] array = (Object[])args[1]; String[] strings = new String[array.length]; System.arraycopy(array, 0, strings, 0, array.length); return new ChoiceGroup((String)args[0], Choice.EXCLUSIVE, strings, null); } case 83: // RadioItem.get_index(): Int return Ival(((ChoiceGroup)args[0]).getSelectedIndex()); case 84: // RadioItem.set_index(index: String) ((ChoiceGroup)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 85: { // new_textbox(text: String): TextBox Form box = new Form(null); box.append(new StringItem(null, (String)args[0])); return box; } case 86: // TextBox.get_text(): String return ((StringItem)((Form)args[0]).get(0)).getText(); case 87: // TextBox.set_text(text: String) ((StringItem)((Form)args[0]).get(0)).setText((String)args[1]); return null; case 88: // font_baseline(font: Int): Int return Ival(int2font(ival(args[0])).getBaselinePosition()); case 89: // Graphics.get_stroke(): Int return Ival(((Graphics)args[0]).getStrokeStyle()); case 90: // Graphics.set_stroke(stroke: Int) ((Graphics)args[0]).setStrokeStyle(ival(args[1])); return null; case 91: // Graphics.draw_region(im: Image, xsrc: Int, ysrc: Int, w: Int, h: Int, trans: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).drawRegion((Image)args[1], ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), ival(args[8]), 0); return null; case 92: { // Graphics.draw_rgb(rgb: [Int], ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int, alpha: Bool) Object[] rgbInts = (Object[])args[1]; int[] rgb = new int[rgbInts.length]; for (int i=rgb.length-1; i>=0; i--) { rgb[i] = ival(rgbInts[i]); } ((Graphics)args[0]).drawRGB(rgb, ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), bval(args[8])); return null; } case 93: // Canvas.action_code(key: Int): Int return Ival(((UICanvas)args[0]).getGameAction(ival(args[1]))); case 94: // Canvas.has_ptr_events(): Bool return Ival(((UICanvas)args[0]).hasPointerEvents()); case 95: // Canvas.has_ptrdrag_event(): Bool return Ival(((UICanvas)args[0]).hasPointerMotionEvents()); case 96: { // image_from_file(file: String): Image InputStream in = c.fs().read(c.toFile((String)args[0])); c.addStream(in); Image img = Image.createImage(in); in.close(); c.removeStream(in); return img; } default: return null; } }
protected Object execNative(Context c, Object[] args) throws Exception { switch (index) { case 0: // new_image(w: Int, h: Int): Image return Image.createImage(ival(args[0]), ival(args[1])); case 1: // Image.graphics(): Graphics return ((Image)args[0]).getGraphics(); case 2: { // image_from_argb(argb: Array, w: Int, h: Int, alpha: Bool): Image Object[] data = (Object[])args[0]; final int[] argb = new int[data.length]; for (int i=argb.length-1; i>=0; i--) { argb[i] = ival(data[i]); } return Image.createRGBImage(argb, ival(args[1]), ival(args[2]), true); } case 3: // image_from_stream(in: IStream): Image return Image.createImage((InputStream)args[0]); case 4: { // image_from_data(data: BArray): Image final byte[] data = (byte[])args[0]; return Image.createImage(data, 0, data.length); } case 5: // image_from_image(im: Image, x: Int, y: Int, w: Int, h: Int): Image return Image.createImage((Image)args[0], ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), 0); case 6: { // Image.get_argb(argb: Array, ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int) Object[] data = (Object[])args[1]; int ofs = ival(args[2]); int scanlen = ival(args[3]); int x = ival(args[4]); int y = ival(args[5]); int w = ival(args[6]); int h = ival(args[7]); int[] argb = new int[scanlen * h]; ((Image)args[0]).getRGB(argb, 0, scanlen, x, y, w, h); for (int i=argb.length-1; i>=0; i--) { data[ofs+i] = Ival(argb[i]); } return null; } case 7: // Graphics.get_color(): Int return Ival(((Graphics)args[0]).getColor()); case 8: // Graphics.set_color(rgb: Int) ((Graphics)args[0]).setColor(ival(args[1])); return null; case 9: // Graphics.get_font(): Int return Ival(font2int(((Graphics)args[0]).getFont())); case 10: // Graphics.set_font(font: Int) ((Graphics)args[0]).setFont(int2font(ival(args[1]))); return null; case 11: // str_width(font: Int, str: String): Int return Ival(int2font(ival(args[0])).stringWidth((String)args[1])); case 12: // font_height(font: Int): Int return Ival(int2font(ival(args[0])).getHeight()); case 13: // Graphics.draw_line(x1: Int, y1: Int, x2: Int, y2: Int) ((Graphics)args[0]).drawLine(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 14: // Graphics.draw_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).drawRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 15: // Graphics.fill_rect(x: Int, y: Int, w: Int, h: Int) ((Graphics)args[0]).fillRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4])); return null; case 16: // Graphics.draw_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).drawRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 17: // Graphics.fill_roundrect(x: Int, y: Int, w: Int, h: Int, arcw: Int, arch: Int) ((Graphics)args[0]).fillRoundRect(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 18: // Graphics.draw_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).drawArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 19: // Graphics.fill_arc(x: Int, y: Int, w: Int, h: Int, sta: Int, a: Int) ((Graphics)args[0]).fillArc(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 20: // Graphics.fill_triangle(x1: Int, y1: Int, x2: Int, y2: Int, x3: Int, y3: Int) ((Graphics)args[0]).fillTriangle(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6])); return null; case 21: // Graphics.draw_string(str: String, x: Int, y: Int) ((Graphics)args[0]).drawString((String)args[1], ival(args[2]), ival(args[3]), 0); return null; case 22: // Graphics.draw_image(im: Image, x: Int, y: Int) ((Graphics)args[0]).drawImage((Image)args[1], ival(args[2]), ival(args[3]), 0); return null; case 23: // Graphics.copy_area(xsrc: Int, ysrc: Int, w: Int, h: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).copyArea(ival(args[1]), ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), 0); return null; case 24: // new_canvas(full: Bool): Canvas return new UICanvas(bval(args[0])); case 25: { // Canvas.graphics(): Graphics return ((UICanvas)args[0]).getGraphics(); } case 26: { // Canvas.read_key(): Int // compatibility function with previous non-event canvas behavior Object[] event = (Object[])UIServer.readEvent(c, false); if (event != null && event[0] == UIServer.EVENT_KEY_PRESS && event[1] == args[0]) { return event[2]; } else { return Int.ZERO; } } case 27: { // ui_set_screen(scr: Screen) if (args[0] != null) { UIServer.setScreen(c, (Displayable)args[0]); } else { UIServer.removeScreen(c); } return null; } case 28: // Screen.get_height(): Int return Ival(((Displayable)args[0]).getHeight()); case 29: // Screen.get_width(): Int return Ival(((Displayable)args[0]).getWidth()); case 30: // Screen.get_title(): String return ((Displayable)args[0]).getTitle(); case 31: { // Screen.set_title(title: String) ((Displayable)args[0]).setTitle((String)args[1]); return null; } case 32: // Screen.is_shown(): Bool return Ival(((Displayable)args[0]).isShown()); case 33: // Canvas.refresh() ((UICanvas)args[0]).repaint(); return null; case 34: // ui_read_event(): UIEvent return UIServer.readEvent(c, false); case 35: // ui_wait_event(): UIEvent return UIServer.readEvent(c, true); case 36: // new_editbox(mode: Int): EditBox return new TextBox(null, null, Short.MAX_VALUE, ival(args[0])); case 37: // EditBox.get_text(): String return ((TextBox)args[0]).getString(); case 38: // EditBox.set_text(text: String) ((TextBox)args[0]).setString((String)args[1]); return null; case 39: { // new_listbox(strings: [String], images: [Image], select: Menu): ListBox Object[] str = (Object[])args[0]; String[] strings = new String[str.length]; System.arraycopy(str, 0, strings, 0, str.length); Object[] img = (Object[])args[1]; Image[] images = null; if (img != null) { images = new Image[img.length]; System.arraycopy(img, 0, images, 0, img.length); } List list = new List(null, Choice.IMPLICIT, strings, images); list.setSelectCommand((Command)args[2]); return list; } case 40: // ListBox.get_index(): Int return Ival(((List)args[0]).getSelectedIndex()); case 41: // ListBox.set_index(index: Int) ((List)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 42: // ui_get_screen(): Screen return UIServer.getScreen(c); case 43: // new_menu(text: String, priority: Int): Menu return new Command((String)args[0], Command.SCREEN, ival(args[1])); case 44: // Menu.get_text(): String return ((Command)args[0]).getLabel(); case 45: // Menu.get_priority(): Int return Ival(((Command)args[0]).getPriority()); case 46: // Screen.add_menu(menu: Menu) ((Displayable)args[0]).addCommand((Command)args[1]); return null; case 47: // Screen.remove_menu(menu: Menu) ((Displayable)args[0]).removeCommand((Command)args[1]); return null; case 48: // new_form(): Form return new Form(null); case 49: // Form.add(item: Item) ((Form)args[0]).append((Item)args[1]); return null; case 50: // Form.get(at: Int): Item return ((Form)args[0]).get(ival(args[1])); case 51: // Form.set(at: Int, item: Item) ((Form)args[0]).set(ival(args[1]), (Item)args[2]); return null; case 52: // Form.insert(at: Int, item: Item) ((Form)args[0]).insert(ival(args[1]), (Item)args[2]); return null; case 53: // Form.remove(at: Int) ((Form)args[0]).delete(ival(args[1])); return null; case 54: // Form.size(): Int return Ival(((Form)args[0]).size()); case 55: // Form.clear() ((Form)args[0]).deleteAll(); return null; case 56: // Item.get_label(): String return ((Item)args[0]).getLabel(); case 57: // Item.set_label(label: String) ((Item)args[0]).setLabel((String)args[1]); return null; case 58: // new_textitem(label: String, text: String): TextItem return new StringItem((String)args[0], String.valueOf(args[1])+'\n'); case 59: // TextItem.get_text(): String return ((StringItem)args[0]).getText(); case 60: // TextItem.set_text(text: String) ((StringItem)args[0]).setText(String.valueOf(args[1])+'\n'); return null; case 61: // TextItem.get_font(): Int return Ival(font2int(((StringItem)args[0]).getFont())); case 62: // TextItem.set_font(font: Int) ((StringItem)args[0]).setFont(int2font(ival(args[1]))); return null; case 63: // new_imageitem(label: String, img: Image): ImageItem return new ImageItem((String)args[0], (Image)args[1], Item.LAYOUT_NEWLINE_AFTER, null); case 64: // ImageItem.get_image(): Image return ((ImageItem)args[0]).getImage(); case 65: // ImageItem.set_image(img: Image) ((ImageItem)args[0]).setImage((Image)args[1]); return null; case 66: // new_edititem(label: String, text: String, mode: Int, size: Int): EditItem return new TextField((String)args[0], (String)args[1], ival(args[3]), ival(args[2])); case 67: // EditItem.get_text(): String return ((TextField)args[0]).getString(); case 68: // EditItem.set_text(text: String) ((TextField)args[0]).setString((String)args[1]); return null; case 69: // new_gaugeitem(label: String, max: Int, init: Int): GaugeItem return new Gauge((String)args[0], true, ival(args[1]), ival(args[2])); case 70: // GaugeItem.get_value(): Int return Ival(((Gauge)args[0]).getValue()); case 71: // GaugeItem.set_value(val: Int) ((Gauge)args[0]).setValue(ival(args[1])); return null; case 72: // GaugeItem.get_maxvalue(): Int return Ival(((Gauge)args[0]).getMaxValue()); case 73: // GaugeItem.set_maxvalue(val: Int) ((Gauge)args[0]).setMaxValue(ival(args[1])); return null; case 74: // new_dateitem(label: String, mode: Int): DateItem return new DateField((String)args[0], ival(args[1])); case 75: { // DateItem.get_date(item: Item): Long Date date = ((DateField)args[0]).getDate(); return (date == null) ? null : Lval(date.getTime()); } case 76: // DateItem.set_date(date: Long) ((DateField)args[0]).setDate(new Date(lval(args[1]))); return null; case 77: { // new_checkitem(label: String, text: String, checked: Bool): CheckItem ChoiceGroup check = new ChoiceGroup((String)args[0], Choice.MULTIPLE); check.append((String)args[1], null); check.setSelectedIndex(0, bval(args[2])); return check; } case 78: { // CheckItem.get_checked(): Bool boolean[] checked = new boolean[1]; ((ChoiceGroup)args[0]).getSelectedFlags(checked); return Ival(checked[0]); } case 79: // CheckItem.set_checked(checked: Bool) ((ChoiceGroup)args[0]).setSelectedIndex(0, bval(args[1])); return null; case 80: // CheckItem.get_text(): String return ((ChoiceGroup)args[0]).getString(0); case 81: // CheckItem.set_text(text: String) ((ChoiceGroup)args[0]).set(0, (String)args[1], null); return null; case 82: { // new_radioitem(label: String, strings: [String]): RadioItem Object[] array = (Object[])args[1]; String[] strings = new String[array.length]; System.arraycopy(array, 0, strings, 0, array.length); return new ChoiceGroup((String)args[0], Choice.EXCLUSIVE, strings, null); } case 83: // RadioItem.get_index(): Int return Ival(((ChoiceGroup)args[0]).getSelectedIndex()); case 84: // RadioItem.set_index(index: String) ((ChoiceGroup)args[0]).setSelectedIndex(ival(args[1]), true); return null; case 85: { // new_textbox(text: String): TextBox Form box = new Form(null); box.append(new StringItem(null, (String)args[0])); return box; } case 86: // TextBox.get_text(): String return ((StringItem)((Form)args[0]).get(0)).getText(); case 87: // TextBox.set_text(text: String) ((StringItem)((Form)args[0]).get(0)).setText((String)args[1]); return null; case 88: // font_baseline(font: Int): Int return Ival(int2font(ival(args[0])).getBaselinePosition()); case 89: // Graphics.get_stroke(): Int return Ival(((Graphics)args[0]).getStrokeStyle()); case 90: // Graphics.set_stroke(stroke: Int) ((Graphics)args[0]).setStrokeStyle(ival(args[1])); return null; case 91: // Graphics.draw_region(im: Image, xsrc: Int, ysrc: Int, w: Int, h: Int, trans: Int, xdst: Int, ydst: Int) ((Graphics)args[0]).drawRegion((Image)args[1], ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), ival(args[8]), 0); return null; case 92: { // Graphics.draw_rgb(rgb: [Int], ofs: Int, scanlen: Int, x: Int, y: Int, w: Int, h: Int, alpha: Bool) Object[] rgbInts = (Object[])args[1]; int[] rgb = new int[rgbInts.length]; for (int i=rgb.length-1; i>=0; i--) { rgb[i] = ival(rgbInts[i]); } ((Graphics)args[0]).drawRGB(rgb, ival(args[2]), ival(args[3]), ival(args[4]), ival(args[5]), ival(args[6]), ival(args[7]), bval(args[8])); return null; } case 93: // Canvas.action_code(key: Int): Int return Ival(((UICanvas)args[0]).getGameAction(ival(args[1]))); case 94: // Canvas.has_ptr_events(): Bool return Ival(((UICanvas)args[0]).hasPointerEvents()); case 95: // Canvas.has_ptrdrag_event(): Bool return Ival(((UICanvas)args[0]).hasPointerMotionEvents()); case 96: { // image_from_file(file: String): Image InputStream in = c.fs().read(c.toFile((String)args[0])); c.addStream(in); Image img = Image.createImage(in); in.close(); c.removeStream(in); return img; } default: return null; } }
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java index 1a8e046d9..3b42fbae9 100644 --- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java +++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/model/JDIThread.java @@ -1,2491 +1,2497 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.core.model; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IStatusHandler; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IStackFrame; import org.eclipse.debug.core.model.ITerminate; import org.eclipse.jdt.debug.core.IEvaluationRunnable; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaObject; import org.eclipse.jdt.debug.core.IJavaStackFrame; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.core.IJavaVariable; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.debug.core.IJDIEventListener; import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin; import org.eclipse.jdt.internal.debug.core.StringMatcher; import org.eclipse.jdt.internal.debug.core.breakpoints.JavaBreakpoint; import com.sun.jdi.ClassNotLoadedException; import com.sun.jdi.ClassType; import com.sun.jdi.Field; import com.sun.jdi.IncompatibleThreadStateException; import com.sun.jdi.IntegerValue; import com.sun.jdi.InvalidStackFrameException; import com.sun.jdi.InvalidTypeException; import com.sun.jdi.InvocationException; import com.sun.jdi.Location; import com.sun.jdi.Method; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import com.sun.jdi.StackFrame; import com.sun.jdi.ThreadGroupReference; import com.sun.jdi.ThreadReference; import com.sun.jdi.VMDisconnectedException; import com.sun.jdi.Value; import com.sun.jdi.event.Event; import com.sun.jdi.event.StepEvent; import com.sun.jdi.request.EventRequest; import com.sun.jdi.request.EventRequestManager; import com.sun.jdi.request.StepRequest; /** * Model thread implementation for an underlying * thread on a VM. */ public class JDIThread extends JDIDebugElement implements IJavaThread { /** * Constant for the name of the main thread group. */ private static final String MAIN_THREAD_GROUP = "main"; //$NON-NLS-1$ /** * Status code indicating that a request to suspend this thread has timed out */ public static final int SUSPEND_TIMEOUT= 161; /** * Underlying thread. */ private ThreadReference fThread; /** * Cache of previous name, used in case thread is garbage collected. */ private String fPreviousName; /** * Collection of stack frames */ private List fStackFrames; /** * Underlying thread group, cached on first access. */ private ThreadGroupReference fThreadGroup; /** * Name of underlying thread group, cached on first access. */ private String fThreadGroupName; /** * Whether children need to be refreshed. Set to * <code>true</code> when stack frames are re-used * on the next suspend. */ private boolean fRefreshChildren = true; /** * Currently pending step handler, <code>null</code> * when not performing a step. */ private StepHandler fStepHandler= null; /** * Whether running. */ private boolean fRunning; /** * Whether terminated. */ private boolean fTerminated; /** * whether suspended but without firing the equivalent events. */ private boolean fSuspendedQuiet; /** * Whether this thread is a system thread. */ private boolean fIsSystemThread; /** * The collection of breakpoints that caused the last suspend, or * an empty collection if the thread is not suspended or was not * suspended by any breakpoint(s). */ private List fCurrentBreakpoints = new ArrayList(2); /** * Whether this thread is currently performing * an evaluation. An evaluation may involve a series * of method invocations. */ private boolean fIsPerformingEvaluation= false; private IEvaluationRunnable fEvaluationRunnable; /** * Whether this thread was manually suspended during an * evaluation. */ private boolean fEvaluationInterrupted = false; /** * Whether this thread is currently invoking a method. * Nested method invocations cannot be performed. */ private boolean fIsInvokingMethod = false; /** * Whether or not this thread is currently honoring * breakpoints. This flag allows breakpoints to be * disabled during evaluations. */ private boolean fHonorBreakpoints= true; /** * The kind of step that was originally requested. Zero or * more 'secondary steps' may be performed programmatically after * the original user-requested step, and this field tracks the * type (step into, over, return) of the original step. */ private int fOriginalStepKind; /** * The JDI Location from which an original user-requested step began. */ private Location fOriginalStepLocation; /** * The total stack depth at the time an original (user-requested) step * is initiated. This is used along with the original step Location * to determine if a step into comes back to the starting location and * needs to be 'nudged' forward. Checking the stack depth eliminates * undesired 'nudging' in recursive methods. */ private int fOriginalStepStackDepth; /** * Whether step filters should be used for the next step request. */ private boolean fUseStepFilters = false; /** * Whether or not this thread is currently suspending (user-requested). */ private boolean fIsSuspending= false; private AsyncThread fAsyncThread; /** * Creates a new thread on the underlying thread reference * in the given debug target. * * @param target the debug target in which this thread is contained * @param thread the underlying thread on the VM * @exception ObjectCollectedException if the underlying thread has been * garbage collected and cannot be properly initialized */ public JDIThread(JDIDebugTarget target, ThreadReference thread) throws ObjectCollectedException { super(target); setUnderlyingThread(thread); initialize(); } /** * Thread initialization:<ul> * <li>Determines if this thread is a system thread</li> * <li>Sets terminated state to <code>false</code></li> * <li>Determines suspended state from underlying thread</li> * <li>Sets this threads stack frames to an empty collection</li> * </ul> * @exception ObjectCollectedException if the thread has been garbage * collected and cannot be initialized */ protected void initialize() throws ObjectCollectedException { fStackFrames= Collections.EMPTY_LIST; // system thread try { determineIfSystemThread(); } catch (DebugException e) { Throwable underlyingException= e.getStatus().getException(); if (underlyingException instanceof VMDisconnectedException) { // Threads may be created by the VM at shutdown // as finalizers. The VM may be disconnected by // the time we hear about the thread creation. disconnected(); return; } if (underlyingException instanceof ObjectCollectedException) { throw (ObjectCollectedException)underlyingException; } logError(e); } // state setTerminated(false); setRunning(false); try { setRunning(!getUnderlyingThread().isSuspended()); } catch (VMDisconnectedException e) { disconnected(); return; } catch (ObjectCollectedException e){ throw e; } catch (RuntimeException e) { logError(e); } } /** * Adds the given breakpoint to the list of breakpoints * this thread is suspended at */ protected void addCurrentBreakpoint(IBreakpoint bp) { fCurrentBreakpoints.add(bp); } /** * Removes the given breakpoint from the list of breakpoints * this thread is suspended at (called when a breakpoint is * deleted, in case we are suspended at that breakpoint) */ protected void removeCurrentBreakpoint(IBreakpoint bp) { fCurrentBreakpoints.remove(bp); } /** * @see org.eclipse.debug.core.model.IThread#getBreakpoints() */ public IBreakpoint[] getBreakpoints() { return (IBreakpoint[])fCurrentBreakpoints.toArray(new IBreakpoint[fCurrentBreakpoints.size()]); } /** * @see ISuspendResume#canResume() */ public boolean canResume() { return isSuspended() && !isSuspendedQuiet() && (!isPerformingEvaluation() || isInvokingMethod()) && !getDebugTarget().isSuspended(); } /** * @see ISuspendResume#canSuspend() */ public boolean canSuspend() { return !isSuspended() || isSuspendedQuiet() || (isPerformingEvaluation() && !isInvokingMethod()); } /** * @see ITerminate#canTerminate() */ public boolean canTerminate() { return getDebugTarget().canTerminate(); } /** * @see IStep#canStepInto() */ public boolean canStepInto() { return canStep(); } /** * @see IStep#canStepOver() */ public boolean canStepOver() { return canStep(); } /** * @see IStep#canStepReturn() */ public boolean canStepReturn() { return canStep(); } /** * Returns whether this thread is in a valid state to * step. * * @return whether this thread is in a valid state to * step */ protected boolean canStep() { try { return isSuspended() && !isSuspendedQuiet() && (!isPerformingEvaluation() || isInvokingMethod()) && !isStepping() && getTopStackFrame() != null && !getJavaDebugTarget().isPerformingHotCodeReplace(); } catch (DebugException e) { return false; } } /** * Determines and sets whether this thread represents a system thread. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void determineIfSystemThread() throws DebugException { fIsSystemThread= false; ThreadGroupReference tgr= getUnderlyingThreadGroup(); fIsSystemThread = tgr != null; while (tgr != null) { String tgn= null; try { tgn= tgr.name(); tgr= tgr.parent(); } catch (UnsupportedOperationException e) { fIsSystemThread = false; break; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_determining_if_system_thread"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will throw an exception return; } if (tgn != null && tgn.equals(MAIN_THREAD_GROUP)) { fIsSystemThread= false; break; } } } /** * NOTE: this method returns a copy of this thread's stack frames. * * @see IThread#getStackFrames() */ public IStackFrame[] getStackFrames() throws DebugException { if (isSuspendedQuiet()) { return new IStackFrame[0]; } List list = computeStackFrames(); return (IStackFrame[])list.toArray(new IStackFrame[list.size()]); } /** * @see computeStackFrames() * * @param refreshChildren whether or not this method should request new stack * frames from the VM */ protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException { if (isSuspended()) { if (isTerminated()) { fStackFrames = Collections.EMPTY_LIST; } else if (refreshChildren) { if (fStackFrames.isEmpty()) { fStackFrames = createAllStackFrames(); if (fStackFrames.isEmpty()) { //leave fRefreshChildren == true //bug 6393 return fStackFrames; } } int stackSize = getUnderlyingFrameCount(); boolean topDown = false; // what was the last method on the top of the stack Method lastMethod = ((JDIStackFrame)fStackFrames.get(0)).getLastMethod(); // what is the method on top of the stack now if (stackSize > 0) { Method currMethod = getUnderlyingFrame(0).location().method(); if (currMethod.equals(lastMethod)) { // preserve frames top down topDown = true; } } // compute new or removed stack frames int offset= 0, length= stackSize; if (length > fStackFrames.size()) { if (topDown) { // add new (empty) frames to the bottom of the stack to preserve frames top-down int num = length - fStackFrames.size(); for (int i = 0; i < num; i++) { fStackFrames.add(new JDIStackFrame(this, 0)); } } else { // add new frames to the top of the stack, preserve bottom up offset= length - fStackFrames.size(); for (int i= offset - 1; i >= 0; i--) { JDIStackFrame newStackFrame= new JDIStackFrame(this, 0); fStackFrames.add(0, newStackFrame); } length= fStackFrames.size() - offset; } } else if (length < fStackFrames.size()) { int removed= fStackFrames.size() - length; if (topDown) { // remove frames from the bottom of the stack, preserve top-down for (int i = 0; i < removed; i++) { fStackFrames.remove(fStackFrames.size() - 1); } } else { // remove frames from the top of the stack, preserve bottom up for (int i= 0; i < removed; i++) { fStackFrames.remove(0); } } } else if (length == 0) { fStackFrames = Collections.EMPTY_LIST; + } else if (length == fStackFrames.size()) { + if (!topDown) { + // replace stack frames with new objects such that equality + // is not preserved (i.e. the top stack frame is different) + fStackFrames = createAllStackFrames(); + } } // update frame indicies for (int i= 0; i < stackSize; i++) { ((JDIStackFrame)fStackFrames.get(i)).setDepth(i); } } fRefreshChildren = false; } else { return Collections.EMPTY_LIST; } return fStackFrames; } /** * Returns this thread's current stack frames as a list, computing * them if required. Returns an empty collection if this thread is * not currently suspended, or this thread is terminated. This * method should be used internally to get the current stack frames, * instead of calling <code>#getStackFrames()</code>, which makes a * copy of the current list. * <p> * Before a thread is resumed a call must be made to one of:<ul> * <li><code>preserveStackFrames()</code></li> * <li><code>disposeStackFrames()</code></li> * </ul> * If stack frames are disposed before a thread is resumed, stack frames * are completely re-computed on the next call to this method. If stack * frames are to be preserved, this method will attempt to re-use any stack * frame objects which represent the same stack frame as on the previous * suspend. Stack frames are cached until a subsequent call to preserve * or dispose stack frames. * </p> * * @return list of <code>IJavaStackFrame</code> * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ public List computeStackFrames() throws DebugException { return computeStackFrames(fRefreshChildren); } /** * @see JDIThread#computeStackFrames() * * This method differs from computeStackFrames() in that it * always requests new stack frames from the VM. As this is * an expensive operation, this method should only be used * by clients who know for certain that the stack frames * on the VM have changed. */ public List computeNewStackFrames() throws DebugException { return computeStackFrames(true); } /** * Helper method for <code>#computeStackFrames()</code> to create all * underlying stack frames. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected List createAllStackFrames() throws DebugException { int stackSize= getUnderlyingFrameCount(); List list= new ArrayList(stackSize); for (int i = 0; i < stackSize; i++) { JDIStackFrame newStackFrame= new JDIStackFrame(this, i); list.add(newStackFrame); } return list; } /** * Retrieves and returns the underlying stack frame at the specified depth * * @return stack frame * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected StackFrame getUnderlyingFrame(int depth) throws DebugException { try { return getUnderlyingThread().frame(depth); } catch (IncompatibleThreadStateException e) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_retrieve_stack_frame_-_thread_not_suspended._1"), e, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will thrown an exception return null; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_stack_frames_2"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will thrown an exception return null; } catch (InternalError e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_stack_frames_2"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will thrown an exception return null; } } /** * Returns the underlying method for the given stack frame * * @param frame an underlying JDI stack frame * @return underlying method * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected Method getUnderlyingMethod(StackFrame frame) throws DebugException { try { return frame.location().method(); } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_method"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will thrown an exception return null; } } /** * Returns the number of frames on the stack from the * underlying thread. * * @return number of frames on the stack * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * <li>This thread is not suspended</li> * </ul> */ protected int getUnderlyingFrameCount() throws DebugException { try { return getUnderlyingThread().frameCount(); } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_frame_count"), new String[] {e.toString()}), e); //$NON-NLS-1$ } catch (IncompatibleThreadStateException e) { requestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_frame_count"), new String[] {e.toString()}), e, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$ } // execution will not reach here - try block will either // return or exception will be thrown return -1; } /** * @see IJavaThread#runEvaluation(IEvaluationRunnable, IProgressMonitor, int) */ public void runEvaluation(IEvaluationRunnable evaluation, IProgressMonitor monitor, int evaluationDetail, boolean hitBreakpoints) throws DebugException { if (isPerformingEvaluation()) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations"), null, IJavaThread.ERR_NESTED_METHOD_INVOCATION); //$NON-NLS-1$ } if (!canRunEvaluation()) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Evaluation_failed_-_thread_not_suspended"), null, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$ } fIsPerformingEvaluation = true; fEvaluationRunnable= evaluation; fHonorBreakpoints= hitBreakpoints; fireResumeEvent(evaluationDetail); //save and restore current breakpoint information - bug 30837 IBreakpoint[] breakpoints = getBreakpoints(); try { evaluation.run(this, monitor); } catch (DebugException e) { throw e; } finally { fIsPerformingEvaluation = false; fEvaluationRunnable= null; fHonorBreakpoints= true; if (getBreakpoints().length == 0 && breakpoints.length > 0) { for (int i = 0; i < breakpoints.length; i++) { addCurrentBreakpoint(breakpoints[i]); } } fireSuspendEvent(evaluationDetail); if (fEvaluationInterrupted && (fAsyncThread == null || fAsyncThread.isEmpty())) { // @see bug 31585: // When an evaluation was interrupted & resumed, the launch view does // not update properly. It cannot know when it is safe to display frames // since it does not know about queued evaluations. Thus, when the queue // is empty, we fire a change event to force the view to update. fEvaluationInterrupted = false; fireChangeEvent(DebugEvent.CONTENT); } } } /** * Returns whether this thread is in a valid state to * run an evaluation. * * @return whether this thread is in a valid state to * run an evaluation */ protected boolean canRunEvaluation() { // NOTE similar to #canStep, except a quiet suspend state is OK try { return isSuspendedQuiet() || (isSuspended() && !(isPerformingEvaluation() || isInvokingMethod()) && !isStepping() && getTopStackFrame() != null && !getJavaDebugTarget().isPerformingHotCodeReplace()); } catch (DebugException e) { return false; } } /** * @see org.eclipse.jdt.debug.core.IJavaThread#queueRunnable(Runnable) */ public void queueRunnable(Runnable evaluation) { if (fAsyncThread == null) { fAsyncThread= new AsyncThread(); } fAsyncThread.addRunnable(evaluation); } /** * @see IJavaThread#terminateEvaluation() */ public void terminateEvaluation() throws DebugException { if (canTerminateEvaluation()) { ((ITerminate) fEvaluationRunnable).terminate(); } } /** * @see IJavaThread#canTerminateEvaluation() */ public boolean canTerminateEvaluation() { return fEvaluationRunnable instanceof ITerminate; } /** * Invokes a method on the target, in this thread, and returns the result. Only * one receiver may be specified - either a class or an object, the other must * be <code>null</code>. This thread is left suspended after the invocation * is complete, unless a call is made to <code>abortEvaluation<code> while * performing a method invocation. In that case, this thread is automatically * resumed when/if this invocation (eventually) completes. * <p> * Method invocations cannot be nested. That is, this method must * return before another call to this method can be made. This * method does not return until the invocation is complete. * Breakpoints can suspend a method invocation, and it is possible * that an invocation will not complete due to an infinite loop * or deadlock. * </p> * <p> * Stack frames are preserved during method invocations, unless * a timeout occurs. Although this thread's state is updated to * running while performing an evaluation, no debug events are * fired unless this invocation is interrupted by a breakpoint, * or the invocation times out. * </p> * <p> * When performing an invocation, the communication timeout with * the target VM is set to infinite, as the invocation may not * complete in a timely fashion, if at all. The timeout value * is reset to its original value when the invocation completes. * </p> * * @param receiverClass the class in the target representing the receiver * of a static message send, or <code>null</code> * @param receiverObject the object in the target to be the receiver of * the message send, or <code>null</code> * @param method the underlying method to be invoked * @param args the arguments to invoke the method with (an empty list * if none) * @return the result of the method, as an underlying value * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * <li>This thread is not suspended * (status code <code>IJavaThread.ERR_THREAD_NOT_SUSPENDED</code>)</li> * <li>This thread is already invoking a method * (status code <code>IJavaThread.ERR_NESTED_METHOD_INVOCATION</code>)</li> * <li>This thread is not suspended by a JDI request * (status code <code>IJavaThread.ERR_INCOMPATIBLE_THREAD_STATE</code>)</li> * </ul> */ protected Value invokeMethod(ClassType receiverClass, ObjectReference receiverObject, Method method, List args, boolean invokeNonvirtual) throws DebugException { if (receiverClass != null && receiverObject != null) { throw new IllegalArgumentException(JDIDebugModelMessages.getString("JDIThread.can_only_specify_one_receiver_for_a_method_invocation")); //$NON-NLS-1$ } Value result= null; int timeout= getRequestTimeout(); try { // this is synchronized such that any other operation that // might be resuming this thread has a chance to complete before // we determine if it is safe to continue with a method invocation. // See bugs 6518, 14069 synchronized (this) { if (!isSuspended()) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Evaluation_failed_-_thread_not_suspended"), null, IJavaThread.ERR_THREAD_NOT_SUSPENDED); //$NON-NLS-1$ } if (isInvokingMethod()) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations"), null, IJavaThread.ERR_NESTED_METHOD_INVOCATION); //$NON-NLS-1$ } // set the request timeout to be infinite setRequestTimeout(Integer.MAX_VALUE); setRunning(true); setInvokingMethod(true); } preserveStackFrames(); int flags= ClassType.INVOKE_SINGLE_THREADED; if (invokeNonvirtual) { // Superclass method invocation must be performed nonvirtual. flags |= ObjectReference.INVOKE_NONVIRTUAL; } if (receiverClass == null) { result= receiverObject.invokeMethod(getUnderlyingThread(), method, args, flags); } else { result= receiverClass.invokeMethod(getUnderlyingThread(), method, args, flags); } } catch (InvalidTypeException e) { invokeFailed(e, timeout); } catch (ClassNotLoadedException e) { invokeFailed(e, timeout); } catch (IncompatibleThreadStateException e) { invokeFailed(JDIDebugModelMessages.getString("JDIThread.Thread_must_be_suspended_by_step_or_breakpoint_to_perform_method_invocation_1"), IJavaThread.ERR_INCOMPATIBLE_THREAD_STATE, e, timeout); //$NON-NLS-1$ } catch (InvocationException e) { invokeFailed(e, timeout); } catch (RuntimeException e) { invokeFailed(e, timeout); } invokeComplete(timeout); return result; } /** * Invokes a constructor in this thread, creating a new instance of the given * class, and returns the result as an object reference. * This thread is left suspended after the invocation * is complete. * <p> * Method invocations cannot be nested. That is, this method must * return before another call to this method can be made. This * method does not return until the invocation is complete. * Breakpoints can suspend a method invocation, and it is possible * that an invocation will not complete due to an infinite loop * or deadlock. * </p> * <p> * Stack frames are preserved during method invocations, unless * a timeout occurs. Although this thread's state is updated to * running while performing an evaluation, no debug events are * fired unless this invocation is interrupted by a breakpoint, * or the invocation times out. * </p> * <p> * When performing an invocation, the communication timeout with * the target VM is set to infinite, as the invocation may not * complete in a timely fashion, if at all. The timeout value * is reset to its original value when the invocation completes. * </p> * * @param receiverClass the class in the target representing the receiver * of the 'new' message send * @param constructor the underlying constructor to be invoked * @param args the arguments to invoke the constructor with (an empty list * if none) * @return a new object reference * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected ObjectReference newInstance(ClassType receiverClass, Method constructor, List args) throws DebugException { if (isInvokingMethod()) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Cannot_perform_nested_evaluations_2"), null); //$NON-NLS-1$ } ObjectReference result= null; int timeout= getRequestTimeout(); try { // set the request timeout to be infinite setRequestTimeout(Integer.MAX_VALUE); setRunning(true); setInvokingMethod(true); preserveStackFrames(); result= receiverClass.newInstance(getUnderlyingThread(), constructor, args, ClassType.INVOKE_SINGLE_THREADED); } catch (InvalidTypeException e) { invokeFailed(e, timeout); } catch (ClassNotLoadedException e) { invokeFailed(e, timeout); } catch (IncompatibleThreadStateException e) { invokeFailed(e, timeout); } catch (InvocationException e) { invokeFailed(e, timeout); } catch (RuntimeException e) { invokeFailed(e, timeout); } invokeComplete(timeout); return result; } /** * Called when an invocation fails. Performs cleanup * and throws an exception. * * @param e the exception that caused the failure * @param restoreTimeout the communication timeout value, * in milliseconds, that should be reset * @see #invokeComplete(int) * @exception DebugException. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void invokeFailed(Throwable e, int restoreTimeout) throws DebugException { invokeFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_invoking_method"), new String[] {e.toString()}), DebugException.TARGET_REQUEST_FAILED, e, restoreTimeout); //$NON-NLS-1$ } /** * Called when an invocation fails. Performs cleanup * and throws an exception. * * @param message error message * @param code status code * @param e the exception that caused the failure * @param restoreTimeout the communication timeout value, * in milliseconds, that should be reset * @see #invokeComplete(int) * @exception DebugException. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void invokeFailed(String message, int code, Throwable e, int restoreTimeout) throws DebugException { invokeComplete(restoreTimeout); requestFailed(message, e, code); } /** * Called when a method invocation has returned, successfully * or not. This method performs cleanup:<ul> * <li>Resets the state of this thread to suspended</li> * <li>Restores the communication timeout value</li> * <li>Computes the new set of stack frames for this thread</code> * </ul> * * @param restoreTimeout the communication timeout value, * in milliseconds, that should be reset * @see #invokeMethod(ClassType, ObjectReference, Method, List) * @see #newInstance(ClassType, Method, List) */ protected void invokeComplete(int restoreTimeout) { abortStep(); setInvokingMethod(false); setRunning(false); setRequestTimeout(restoreTimeout); // update preserved stack frames try { computeStackFrames(); } catch (DebugException e) { logError(e); } } /** * @see IThread#getName() */ public String getName() throws DebugException { try { fPreviousName = getUnderlyingThread().name(); return fPreviousName; } catch (RuntimeException e) { // Don't bother reporting the exception when retrieving the name (bug 30785 & bug 33276) if (e instanceof ObjectCollectedException) { if (fPreviousName == null) { return JDIDebugModelMessages.getString("JDIThread.garbage_collected_1"); //$NON-NLS-1$ } else { return fPreviousName; } } targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_name"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not fall through, as // #targetRequestFailed will thrown an exception } return null; } /** * @see IThread#getPriority */ public int getPriority() throws DebugException { // to get the priority, we must get the value from the "priority" field Field p= null; try { p= getUnderlyingThread().referenceType().fieldByName("priority"); //$NON-NLS-1$ if (p == null) { requestFailed(JDIDebugModelMessages.getString("JDIThread.no_priority_field"), null); //$NON-NLS-1$ } Value v= getUnderlyingThread().getValue(p); if (v instanceof IntegerValue) { return ((IntegerValue)v).value(); } else { requestFailed(JDIDebugModelMessages.getString("JDIThread.priority_not_an_integer"), null); //$NON-NLS-1$ } } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_priority"), new String[] {e.toString()}), e); //$NON-NLS-1$ } // execution will not fall through to this line, as // #targetRequestFailed or #requestFailed will throw // an exception return -1; } /** * @see IThread#getTopStackFrame() */ public IStackFrame getTopStackFrame() throws DebugException { List c= computeStackFrames(); if (c.isEmpty()) { return null; } else { return (IStackFrame) c.get(0); } } /** * A breakpoint has suspended execution of this thread. * Aborts any step currently in process and fires a * suspend event. * * @param breakpoint the breakpoint that caused the suspend * @return whether this thread suspended */ public boolean handleSuspendForBreakpoint(JavaBreakpoint breakpoint, boolean queueEvent) { addCurrentBreakpoint(breakpoint); setSuspendedQuiet(false); try { // update state to suspended but don't actually // suspend unless a registered listener agrees if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) { ((JDIDebugTarget)getDebugTarget()).prepareToSuspendByBreakpoint(breakpoint); } else { setRunning(false); } // poll listeners boolean suspend = JDIDebugPlugin.getDefault().fireBreakpointHit(this, breakpoint); // suspend or resume if (suspend) { if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) { ((JDIDebugTarget)getDebugTarget()).suspendedByBreakpoint(breakpoint, queueEvent); } abortStep(); if (queueEvent) { queueSuspendEvent(DebugEvent.BREAKPOINT); } else { fireSuspendEvent(DebugEvent.BREAKPOINT); } } else { if (breakpoint.getSuspendPolicy() == IJavaBreakpoint.SUSPEND_VM) { ((JDIDebugTarget)getDebugTarget()).cancelSuspendByBreakpoint(breakpoint); } else { setRunning(true); // dispose cached stack frames so we re-retrieve on the next breakpoint preserveStackFrames(); } } return suspend; } catch (CoreException e) { logError(e); return true; } } /** * Updates the state of this thread to suspend for * the given breakpoint but does not fire notification * of the suspend. Do no abort the current step as the program * may be resumed quietly and the step may still finish. */ public boolean handleSuspendForBreakpointQuiet(JavaBreakpoint breakpoint) { addCurrentBreakpoint(breakpoint); setSuspendedQuiet(true); setRunning(false); return true; } /** * @see IStep#isStepping() */ public boolean isStepping() { return getPendingStepHandler() != null; } /** * @see ISuspendResume#isSuspended() */ public boolean isSuspended() { return !fRunning && !fTerminated; } /** * @see ISuspendResume#isSuspended() */ public boolean isSuspendedQuiet() { return fSuspendedQuiet; } /** * @see IJavaThread#isSystemThread() */ public boolean isSystemThread() { return fIsSystemThread; } /** * @see IJavaThread#getThreadGroupName() */ public String getThreadGroupName() throws DebugException { if (fThreadGroupName == null) { ThreadGroupReference tgr= getUnderlyingThreadGroup(); // bug# 20370 if (tgr == null) { return null; } try { fThreadGroupName = tgr.name(); } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group_name"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will thrown an exception return null; } } return fThreadGroupName; } /** * @see ITerminate#isTerminated() */ public boolean isTerminated() { return fTerminated; } public boolean isOutOfSynch() throws DebugException { if (isSuspended() && ((JDIDebugTarget)getDebugTarget()).hasHCRFailed()) { List frames= computeStackFrames(); Iterator iter= frames.iterator(); while (iter.hasNext()) { if (((JDIStackFrame) iter.next()).isOutOfSynch()) { return true; } } return false; } else { // If the thread is not suspended, there's no way to // say for certain that it is running out of synch code return false; } } public boolean mayBeOutOfSynch() throws DebugException { if (!isSuspended()) { return ((JDIDebugTarget)getDebugTarget()).hasHCRFailed(); } return false; } /** * Sets whether this thread is terminated * * @param terminated whether this thread is terminated */ protected void setTerminated(boolean terminated) { fTerminated= terminated; } /** * @see ISuspendResume#resume() */ public void resume() throws DebugException { resumeThread(true); } /** * @see ISuspendResume#resume() * * Updates the state of this thread to resumed, * but does not fire notification of the resumption. */ public void resumeQuiet() throws DebugException { resumeThread(false); } /** * @see ISuspendResume#resume() * * Updates the state of this thread, but only fires * notification to listeners if <code>fireNotification</code> * is <code>true</code>. */ private void resumeThread(boolean fireNotification) throws DebugException { if (!isSuspended() || (isPerformingEvaluation() && !isInvokingMethod())) { return; } try { setRunning(true); setSuspendedQuiet(false); preserveStackFrames(); if (fireNotification) { fireResumeEvent(DebugEvent.CLIENT_REQUEST); } getUnderlyingThread().resume(); } catch (VMDisconnectedException e) { disconnected(); } catch (RuntimeException e) { setRunning(false); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_resuming"), new String[] {e.toString()}), e); //$NON-NLS-1$ } } /** * Sets whether this thread is currently executing. * When set to <code>true</code>, this thread's current * breakpoints are cleared. * * @param running whether this thread is executing */ protected void setRunning(boolean running) { fRunning = running; if (running) { fCurrentBreakpoints.clear(); } } protected void setSuspendedQuiet(boolean suspendedQuiet) { fSuspendedQuiet= suspendedQuiet; } /** * Preserves stack frames to be used on the next suspend event. * Iterates through all current stack frames, setting their * state as invalid. This method should be called before this thread * is resumed, when stack frames are to be re-used when it later * suspends. * * @see computeStackFrames() */ protected synchronized void preserveStackFrames() { fRefreshChildren = true; Iterator frames = fStackFrames.iterator(); while (frames.hasNext()) { ((JDIStackFrame)frames.next()).setUnderlyingStackFrame(null); } } /** * Disposes stack frames, to be completely re-computed on * the next suspend event. This method should be called before * this thread is resumed when stack frames are not to be re-used * on the next suspend. * * @see computeStackFrames() */ protected synchronized void disposeStackFrames() { fStackFrames= Collections.EMPTY_LIST; fRefreshChildren = true; } /** * This method is synchronized, such that the step request * begins before a background evaluation can be performed. * * @see IStep#stepInto() */ public synchronized void stepInto() throws DebugException { if (!canStepInto()) { return; } StepHandler handler = new StepIntoHandler(); handler.step(); } /** * This method is synchronized, such that the step request * begins before a background evaluation can be performed. * * @see IStep#stepOver() */ public synchronized void stepOver() throws DebugException { if (!canStepOver()) { return; } StepHandler handler = new StepOverHandler(); handler.step(); } /** * This method is synchronized, such that the step request * begins before a background evaluation can be performed. * * @see IStep#stepReturn() */ public synchronized void stepReturn() throws DebugException { if (!canStepReturn()) { return; } StepHandler handler = new StepReturnHandler(); handler.step(); } protected void setOriginalStepKind(int stepKind) { fOriginalStepKind = stepKind; } protected int getOriginalStepKind() { return fOriginalStepKind; } protected void setOriginalStepLocation(Location location) { fOriginalStepLocation = location; } protected Location getOriginalStepLocation() { return fOriginalStepLocation; } protected void setOriginalStepStackDepth(int depth) { fOriginalStepStackDepth = depth; } protected int getOriginalStepStackDepth() { return fOriginalStepStackDepth; } /** * In cases where a user-requested step into encounters nothing but filtered code * (static initializers, synthetic methods, etc.), the default JDI behavior is to * put the instruction pointer back where it was before the step into. This requires * a second step to move forward. Since this is confusing to the user, we do an * extra step into in such situations. This method determines when such an extra * step into is necessary. It compares the current Location to the original * Location when the user step into was initiated. It also makes sure the stack depth * now is the same as when the step was initiated. */ protected boolean shouldDoExtraStepInto(Location location) throws DebugException { if (getOriginalStepKind() != StepRequest.STEP_INTO) { return false; } if (getOriginalStepStackDepth() != getUnderlyingFrameCount()) { return false; } Location origLocation = getOriginalStepLocation(); if (origLocation == null) { return false; } // We cannot simply check if the two Locations are equal using the equals() // method, since this checks the code index within the method. Even if the // code indices are different, the line numbers may be the same, in which case // we need to do the extra step into. Method origMethod = origLocation.method(); Method currMethod = location.method(); if (!origMethod.equals(currMethod)) { return false; } if (origLocation.lineNumber() != location.lineNumber()) { return false; } return true; } /** * @see ISuspendResume#suspend() */ public void suspend() throws DebugException { try { // Abort any pending step request abortStep(); setSuspendedQuiet(false); fEvaluationInterrupted = isPerformingEvaluation(); suspendUnderlyingThread(); } catch (RuntimeException e) { setRunning(true); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_suspending"), new String[] {e.toString()}), e); //$NON-NLS-1$ } } /** * Suspends the underlying thread asynchronously and fires notification when * the underlying thread is suspended. */ protected void suspendUnderlyingThread() { if (fIsSuspending) { return; } fIsSuspending= true; Thread thread= new Thread(new Runnable() { public void run() { try { getUnderlyingThread().suspend(); int timeout= JDIDebugModel.getPreferences().getInt(JDIDebugModel.PREF_REQUEST_TIMEOUT); long stop= System.currentTimeMillis() + timeout; boolean suspended= isUnderlyingThreadSuspended(); while (System.currentTimeMillis() < stop && !suspended) { try { Thread.sleep(50); } catch (InterruptedException e) { } suspended= isUnderlyingThreadSuspended(); if (suspended) { break; } } if (!suspended) { IStatus status= new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), SUSPEND_TIMEOUT, MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.suspend_timeout"), new String[] {new Integer(timeout).toString()}), null); //$NON-NLS-1$ IStatusHandler handler= DebugPlugin.getDefault().getStatusHandler(status); if (handler != null) { try { handler.handleStatus(status, JDIThread.this); } catch (CoreException e) { } } } setRunning(false); fireSuspendEvent(DebugEvent.CLIENT_REQUEST); } catch (RuntimeException exception) { } finally { fIsSuspending= false; } } }); thread.start(); } public boolean isUnderlyingThreadSuspended() { return getUnderlyingThread().isSuspended(); } /** * Notifies this thread that it has been suspended due * to a VM suspend. */ protected void suspendedByVM() { setRunning(false); setSuspendedQuiet(false); } /** * Notifies this thread that is about to be resumed due * to a VM resume. */ protected void resumedByVM() { setRunning(true); preserveStackFrames(); // This method is called *before* the VM is actually resumed. // To ensure that all threads will fully resume when the VM // is resumed, make sure the suspend count of each thread // is no greater than 1. @see Bugs 23328 and 27622 ThreadReference thread= getUnderlyingThread(); while (thread.suspendCount() > 1) { thread.resume(); } } /** * @see ITerminate#terminate() */ public void terminate() throws DebugException { terminateEvaluation(); getDebugTarget().terminate(); } /** * Drops to the given stack frame * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void dropToFrame(IStackFrame frame) throws DebugException { JDIDebugTarget target= (JDIDebugTarget) getDebugTarget(); if (target.canPopFrames()) { // JDK 1.4 support try { // Pop the drop frame and all frames above it popFrame(frame); stepInto(); } catch (RuntimeException exception) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_dropping_to_frame"), new String[] {exception.toString()}),exception); //$NON-NLS-1$ } } else { // J9 support // This block is synchronized, such that the step request // begins before a background evaluation can be performed. synchronized (this) { StepHandler handler = new DropToFrameHandler(frame); handler.step(); } } } protected void popFrame(IStackFrame frame) throws DebugException { JDIDebugTarget target= (JDIDebugTarget)getDebugTarget(); if (target.canPopFrames()) { // JDK 1.4 support try { // Pop the frame and all frames above it StackFrame jdiFrame= null; int desiredSize= fStackFrames.size() - fStackFrames.indexOf(frame) - 1; int lastSize= fStackFrames.size() + 1; // Set up to pass the first test int size= fStackFrames.size(); while (size < lastSize && size > desiredSize) { // Keep popping frames until the stack stops getting smaller // or popFrame is gone. // see Bug 8054 jdiFrame = ((JDIStackFrame) frame).getUnderlyingStackFrame(); preserveStackFrames(); fThread.popFrames(jdiFrame); lastSize= size; size= computeStackFrames().size(); } } catch (IncompatibleThreadStateException exception) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_popping"), new String[] {exception.toString()}),exception); //$NON-NLS-1$ } catch (InvalidStackFrameException exception) { // InvalidStackFrameException can be thrown when all but the // deepest frame were popped. Fire a changed notification // in case this has occured. fireChangeEvent(DebugEvent.CONTENT); targetRequestFailed(exception.toString(),exception); //$NON-NLS-1$ } catch (RuntimeException exception) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_popping"), new String[] {exception.toString()}),exception); //$NON-NLS-1$ } } } /** * Steps until the specified stack frame is the top frame. Provides * ability to step over/return in the non-top stack frame. * This method is synchronized, such that the step request * begins before a background evaluation can be performed. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected synchronized void stepToFrame(IStackFrame frame) throws DebugException { if (!canStepReturn()) { return; } StepHandler handler = new StepToFrameHandler(frame); handler.step(); } /** * Aborts the current step, if any. */ protected void abortStep() { StepHandler handler = getPendingStepHandler(); if (handler != null) { handler.abort(); } } /** * @see IJavaThread#findVariable(String) */ public IJavaVariable findVariable(String varName) throws DebugException { if (isSuspended()) { try { IStackFrame[] stackFrames= getStackFrames(); for (int i = 0; i < stackFrames.length; i++) { IJavaStackFrame sf= (IJavaStackFrame)stackFrames[i]; IJavaVariable var= sf.findVariable(varName); if (var != null) { return var; } } } catch (DebugException e) { // if the thread has since reusmed, return null (no need to report error) if (e.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) { throw e; } } } return null; } /** * Notification this thread has terminated - update state * and fire a terminate event. */ protected void terminated() { setTerminated(true); setRunning(false); fireTerminateEvent(); } /** * Returns this thread on the underlying VM which this * model thread is a proxy to. * * @return underlying thread */ public ThreadReference getUnderlyingThread() { return fThread; } /** * Sets the underlying thread that this model object * is a proxy to. * * @param thread underlying thread on target VM */ protected void setUnderlyingThread(ThreadReference thread) { fThread = thread; } /** * Returns this thread's underlying thread group. * * @return thread group * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * <li>Retrieving the underlying thread group is not supported * on the underlying VM</li> * </ul> */ protected ThreadGroupReference getUnderlyingThreadGroup() throws DebugException { if (fThreadGroup == null) { try { fThreadGroup = getUnderlyingThread().threadGroup(); } catch (UnsupportedOperationException e) { requestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #requestFailed will throw an exception return null; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_retrieving_thread_group"), new String[] {e.toString()}), e); //$NON-NLS-1$ // execution will not reach this line, as // #targetRequestFailed will throw an exception return null; } } return fThreadGroup; } /** * @see IJavaThread#isPerformingEvaluation() */ public boolean isPerformingEvaluation() { return fIsPerformingEvaluation; } /** * Returns whether this thread is currently performing * a method invokation */ public boolean isInvokingMethod() { return fIsInvokingMethod; } /** * Returns whether this thread is currently ignoring * breakpoints. */ public boolean isIgnoringBreakpoints() { return !fHonorBreakpoints; } /** * Sets whether this thread is currently invoking a method * * @param evaluating whether this thread is currently * invoking a method */ protected void setInvokingMethod(boolean invoking) { fIsInvokingMethod= invoking; } /** * Sets the step handler currently handling a step * request. * * @param handler the current step handler, or <code>null</code> * if none */ protected void setPendingStepHandler(StepHandler handler) { fStepHandler = handler; } /** * Returns the step handler currently handling a step * request, or <code>null</code> if none. * * @return step handler, or <code>null</code> if none */ protected StepHandler getPendingStepHandler() { return fStepHandler; } /** * Helper class to perform stepping an a thread. */ abstract class StepHandler implements IJDIEventListener { /** * Request for stepping in the underlying VM */ private StepRequest fStepRequest; /** * Initiates a step in the underlying VM by creating a step * request of the appropriate kind (over, into, return), * and resuming this thread. When a step is initiated it * is registered with its thread as a pending step. A pending * step could be cancelled if a breakpoint suspends execution * during the step. * <p> * This thread's state is set to running and stepping, and * stack frames are invalidated (but preserved to be re-used * when the step completes). A resume event with a step detail * is fired for this thread. * </p> * Note this method does nothing if this thread has no stack frames. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void step() throws DebugException { JDIStackFrame top = (JDIStackFrame)getTopStackFrame(); if (top == null) { return; } setOriginalStepKind(getStepKind()); Location location = top.getUnderlyingStackFrame().location(); setOriginalStepLocation(location); setOriginalStepStackDepth(computeStackFrames().size()); setStepRequest(createStepRequest()); setPendingStepHandler(this); addJDIEventListener(this, getStepRequest()); setRunning(true); preserveStackFrames(); fireResumeEvent(getStepDetail()); invokeThread(); } /** * Resumes the underlying thread to initiate the step. * By default the thread is resumed. Step handlers that * require other actions can override this method. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void invokeThread() throws DebugException { try { getUnderlyingThread().resume(); } catch (RuntimeException e) { stepEnd(); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_stepping"), new String[] {e.toString()}), e); //$NON-NLS-1$ } } /** * Creates and returns a step request specific to this step * handler. Subclasses must override <code>getStepKind()</code> * to return the kind of step it implements. * * @return step request * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected StepRequest createStepRequest() throws DebugException { EventRequestManager manager = getEventRequestManager(); if (manager == null) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_create_step_request_-_VM_disconnected._1"), null); //$NON-NLS-1$ } try { StepRequest request = manager.createStepRequest(getUnderlyingThread(), StepRequest.STEP_LINE, getStepKind()); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.addCountFilter(1); attachFiltersToStepRequest(request); request.enable(); return request; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$ } // this line will never be executed, as the try block // will either return, or the catch block will throw // an exception return null; } /** * Returns the kind of step this handler implements. * * @return one of <code>StepRequest.STEP_INTO</code>, * <code>StepRequest.STEP_OVER</code>, <code>StepRequest.STEP_OUT</code> */ protected abstract int getStepKind(); /** * Returns the detail for this step event. * * @return one of <code>DebugEvent.STEP_INTO</code>, * <code>DebugEvent.STEP_OVER</code>, <code>DebugEvent.STEP_RETURN</code> */ protected abstract int getStepDetail(); /** * Sets the step request created by this handler in * the underlying VM. Set to <code>null<code> when * this handler deletes its request. * * @param request step request */ protected void setStepRequest(StepRequest request) { fStepRequest = request; } /** * Returns the step request created by this handler in * the underlying VM. * * @return step request */ protected StepRequest getStepRequest() { return fStepRequest; } /** * Deletes this handler's step request from the underlying VM * and removes this handler as an event listener. */ protected void deleteStepRequest() { removeJDIEventListener(this, getStepRequest()); try { EventRequestManager manager = getEventRequestManager(); if (manager != null) { manager.deleteEventRequest(getStepRequest()); } setStepRequest(null); } catch (RuntimeException e) { logError(e); } } /** * If step filters are currently switched on and the current location is not a filtered * location, set all active filters on the step request. */ protected void attachFiltersToStepRequest(StepRequest request) { if (applyStepFilters() && (getJavaDebugTarget().isStepFiltersEnabled() || fUseStepFilters)) { Location currentLocation= getOriginalStepLocation(); if (currentLocation == null) { return; } //check if the user has already stopped in a filtered location //is so do not filter @see bug 5587 ReferenceType type= currentLocation.declaringType(); String typeName= type.name(); String[] activeFilters = getJavaDebugTarget().getStepFilters(); for (int i = 0; i < activeFilters.length; i++) { StringMatcher matcher = new StringMatcher(activeFilters[i], false, false); if (matcher.match(typeName)) { return; } } for (int i = 0; i < activeFilters.length; i++) { request.addClassExclusionFilter(activeFilters[i]); } } } /** * Returns whether this step handler should use step * filters when creating its step request. By default, * step filters are not used. Subclasses must override * if/when required. * * @return whether this step handler should use step * filters when creating its step request */ protected boolean applyStepFilters() { return false; } /** * Notification the step request has completed. * If the current location matches one of the user-specified * step filter criteria (e.g., synthetic methods, static initializers), * then continue stepping. * * @see IJDIEventListener#handleEvent(Event, JDIDebugTarget) */ public boolean handleEvent(Event event, JDIDebugTarget target) { try { StepEvent stepEvent = (StepEvent) event; Location currentLocation = stepEvent.location(); // if the ending step location is filtered and we did not start from // a filtered location, or if we're back where // we started on a step into, do another step of the same kind if (locationShouldBeFiltered(currentLocation) || shouldDoExtraStepInto(currentLocation)) { setRunning(true); deleteStepRequest(); createSecondaryStepRequest(); return true; // otherwise, we're done stepping } else { stepEnd(); return false; } } catch (DebugException e) { logError(e); stepEnd(); return false; } } /** * Returns <code>true</code> if the StepEvent's Location is a Method that the * user has indicated (via the step filter preferences) should be * filtered and the step was not initiated from a filtered location. * Returns <code>false</code> otherwise. */ protected boolean locationShouldBeFiltered(Location location) throws DebugException { if (applyStepFilters()) { Location origLocation= getOriginalStepLocation(); if (origLocation != null) { return !locationIsFiltered(origLocation.method()) && locationIsFiltered(location.method()); } } return false; } /** * Returns <code>true</code> if the StepEvent's Location is a Method that the * user has indicated (via the step filter preferences) should be * filtered. Returns <code>false</code> otherwise. */ protected boolean locationIsFiltered(Method method) { if (getJavaDebugTarget().isStepFiltersEnabled() || fUseStepFilters) { boolean filterStatics = getJavaDebugTarget().isFilterStaticInitializers(); boolean filterSynthetics = getJavaDebugTarget().isFilterSynthetics(); boolean filterConstructors = getJavaDebugTarget().isFilterConstructors(); if (!(filterStatics || filterSynthetics || filterConstructors)) { return false; } if ((filterStatics && method.isStaticInitializer()) || (filterSynthetics && method.isSynthetic()) || (filterConstructors && method.isConstructor()) ) { return true; } } return false; } /** * Cleans up when a step completes.<ul> * <li>Thread state is set to suspended.</li> * <li>Stepping state is set to false</li> * <li>Stack frames and variables are incrementally updated</li> * <li>The step request is deleted and removed as * and event listener</li> * <li>A suspend event is fired</li> * </ul> */ protected void stepEnd() { fUseStepFilters = false; setRunning(false); deleteStepRequest(); setPendingStepHandler(null); queueSuspendEvent(DebugEvent.STEP_END); } /** * Creates another step request in the underlying thread of the * appropriate kind (over, into, return). This thread will * be resumed by the event dispatcher as this event handler * will vote to resume suspended threads. When a step is * initiated it is registered with its thread as a pending * step. A pending step could be cancelled if a breakpoint * suspends execution during the step. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void createSecondaryStepRequest() throws DebugException { setStepRequest(createStepRequest()); setPendingStepHandler(this); addJDIEventListener(this, getStepRequest()); } /** * Aborts this step request if active. The step event * request is deleted from the underlying VM. */ protected void abort() { if (getStepRequest() != null) { deleteStepRequest(); setPendingStepHandler(null); } } } /** * Handler for step over requests. */ class StepOverHandler extends StepHandler { /** * @see StepHandler#getStepKind() */ protected int getStepKind() { return StepRequest.STEP_OVER; } /** * @see StepHandler#getStepDetail() */ protected int getStepDetail() { return DebugEvent.STEP_OVER; } } /** * Handler for step into requests. */ class StepIntoHandler extends StepHandler { /** * @see StepHandler#getStepKind() */ protected int getStepKind() { return StepRequest.STEP_INTO; } /** * @see StepHandler#getStepDetail() */ protected int getStepDetail() { return DebugEvent.STEP_INTO; } /** * Returns <code>true</code>. Step filters are applied for * stepping into new frames. * * @see StepHandler#applyStepFilters() */ protected boolean applyStepFilters() { return true; } } /** * Handler for step return requests. */ class StepReturnHandler extends StepHandler { /** * @see StepHandler#getStepKind() */ protected int getStepKind() { return StepRequest.STEP_OUT; } /** * @see StepHandler#getStepDetail() */ protected int getStepDetail() { return DebugEvent.STEP_RETURN; } } /** * Handler for stepping to a specific stack frame * (stepping in the non-top stack frame). Step returns * are performed until a specified stack frame is reached * or the thread is suspended (explicitly, or by a * breakpoint). */ class StepToFrameHandler extends StepReturnHandler { /** * The number of frames that should be left on the stack */ private int fRemainingFrames; /** * Constructs a step handler to step until the specified * stack frame is reached. * * @param frame the stack frame to step to * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected StepToFrameHandler(IStackFrame frame) throws DebugException { List frames = computeStackFrames(); setRemainingFrames(frames.size() - frames.indexOf(frame)); } /** * Sets the number of frames that should be * remaining on the stack when done. * * @param num number of remaining frames */ protected void setRemainingFrames(int num) { fRemainingFrames = num; } /** * Returns number of frames that should be * remaining on the stack when done * * @return number of frames that should be left */ protected int getRemainingFrames() { return fRemainingFrames; } /** * Notification the step request has completed. * If in the desired frame, complete the step * request normally. If not in the desired frame, * another step request is created and this thread * is resumed. * * @see IJDIEventListener#handleEvent(Event, JDIDebugTarget) */ public boolean handleEvent(Event event, JDIDebugTarget target) { try { int numFrames = getUnderlyingFrameCount(); // tos should not be null if (numFrames <= getRemainingFrames()) { stepEnd(); return false; } else { // reset running state and keep going setRunning(true); deleteStepRequest(); createSecondaryStepRequest(); return true; } } catch (DebugException e) { logError(e); stepEnd(); return false; } } } /** * Handles dropping to a specified frame. */ class DropToFrameHandler extends StepReturnHandler { /** * The number of frames to drop off the * stack. */ private int fFramesToDrop; /** * Constructs a handler to drop to the specified * stack frame. * * @param frame the stack frame to drop to * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected DropToFrameHandler(IStackFrame frame) throws DebugException { List frames = computeStackFrames(); setFramesToDrop(frames.indexOf(frame)); } /** * Sets the number of frames to pop off the stack. * * @param num number of frames to pop */ protected void setFramesToDrop(int num) { fFramesToDrop = num; } /** * Returns the number of frames to pop off the stack. * * @return remaining number of frames to pop */ protected int getFramesToDrop() { return fFramesToDrop; } /** * To drop a frame or re-enter, the underlying thread is instructed * to do a return. When the frame count is less than zero, the * step being performed is a "step return", so a regular invocation * is performed. * * @see StepHandler#invokeThread() */ protected void invokeThread() throws DebugException { if (getFramesToDrop() < 0) { super.invokeThread(); } else { try { org.eclipse.jdi.hcr.ThreadReference hcrThread= (org.eclipse.jdi.hcr.ThreadReference) getUnderlyingThread(); hcrThread.doReturn(null, true); } catch (RuntimeException e) { stepEnd(); targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString(JDIDebugModelMessages.getString("JDIThread.exception_while_popping_stack_frame")), new String[] {e.toString()}), e); //$NON-NLS-1$ } } } /** * Notification that the pop has completed. If there are * more frames to pop, keep going, otherwise re-enter the * top frame. Returns false, as this handler will resume this * thread with a special invocation (<code>doReturn</code>). * * @see IJDIEventListener#handleEvent(Event, JDIDebugTarget) * @see #invokeThread() */ public boolean handleEvent(Event event, JDIDebugTarget target) { // pop is complete, update number of frames to drop setFramesToDrop(getFramesToDrop() - 1); try { if (getFramesToDrop() >= -1) { deleteStepRequest(); doSecondaryStep(); } else { stepEnd(); } } catch (DebugException e) { stepEnd(); logError(e); } return false; } /** * Pops a secondary frame off the stack, does a re-enter, * or a step-into. * * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected void doSecondaryStep() throws DebugException { setStepRequest(createStepRequest()); setPendingStepHandler(this); addJDIEventListener(this, getStepRequest()); invokeThread(); } /** * Creates and returns a step request. If there * are no more frames to drop, a re-enter request * is made. If the re-enter is complete, a step-into * request is created. * * @return step request * @exception DebugException if this method fails. Reasons include: * <ul> * <li>Failure communicating with the VM. The DebugException's * status code contains the underlying exception responsible for * the failure.</li> * </ul> */ protected StepRequest createStepRequest() throws DebugException { EventRequestManager manager = getEventRequestManager(); if (manager == null) { requestFailed(JDIDebugModelMessages.getString("JDIThread.Unable_to_create_step_request_-_VM_disconnected._2"), null); //$NON-NLS-1$ } int num = getFramesToDrop(); if (num > 0) { return super.createStepRequest(); } else if (num == 0) { try { StepRequest request = ((org.eclipse.jdi.hcr.EventRequestManager) manager).createReenterStepRequest(getUnderlyingThread()); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.addCountFilter(1); request.enable(); return request; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$ } } else if (num == -1) { try { StepRequest request = manager.createStepRequest(getUnderlyingThread(), StepRequest.STEP_LINE, StepRequest.STEP_INTO); request.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); request.addCountFilter(1); request.enable(); return request; } catch (RuntimeException e) { targetRequestFailed(MessageFormat.format(JDIDebugModelMessages.getString("JDIThread.exception_creating_step_request"), new String[] {e.toString()}), e); //$NON-NLS-1$ } } // this line will never be executed, as the try block // will either return, or the catch block with throw // an exception return null; } } /** * @see IThread#hasStackFrames() */ public boolean hasStackFrames() throws DebugException { try { return computeStackFrames().size() > 0; } catch (DebugException e) { // do not throw an exception if the thread resumed while determining // whether stack frames are present if (e.getStatus().getCode() != IJavaThread.ERR_THREAD_NOT_SUSPENDED) { throw e; } } return false; } /** * @see IAdaptable#getAdapter(Class) */ public Object getAdapter(Class adapter) { if (adapter == IJavaThread.class) { return this; } if (adapter == IJavaStackFrame.class) { try { return (IJavaStackFrame)getTopStackFrame(); } catch (DebugException e) { // do nothing if not able to get frame } } return super.getAdapter(adapter); } /** * @see org.eclipse.jdt.debug.core.IJavaThread#hasOwnedMonitors() */ public boolean hasOwnedMonitors() throws DebugException { return isSuspended() && getOwnedMonitors().length > 0; } /** * @see org.eclipse.jdt.debug.core.IJavaThread#getOwnedMonitors() */ public IJavaObject[] getOwnedMonitors() throws DebugException { try { JDIDebugTarget target= (JDIDebugTarget)getDebugTarget(); List ownedMonitors= getUnderlyingThread().ownedMonitors(); IJavaObject[] javaOwnedMonitors= new IJavaObject[ownedMonitors.size()]; Iterator itr= ownedMonitors.iterator(); int i= 0; while (itr.hasNext()) { ObjectReference element = (ObjectReference) itr.next(); javaOwnedMonitors[i]= new JDIObjectValue(target, element); i++; } return javaOwnedMonitors; } catch (IncompatibleThreadStateException e) { } return null; } /** * @see org.eclipse.jdt.debug.core.IJavaThread#getContendedMonitor() */ public IJavaObject getContendedMonitor() throws DebugException { try { ObjectReference monitor= getUnderlyingThread().currentContendedMonitor(); if (monitor != null) { return new JDIObjectValue((JDIDebugTarget)getDebugTarget(), monitor); } } catch (IncompatibleThreadStateException e) { } return null; } /** * @see org.eclipse.debug.core.model.IFilteredStep#canStepWithFilters() */ public boolean canStepWithFilters() { if (canStepInto()) { String[] filters = getJavaDebugTarget().getStepFilters(); return filters != null && filters.length > 0; } return false; } /** * @see org.eclipse.debug.core.model.IFilteredStep#stepWithFilters() */ public void stepWithFilters() throws DebugException { if (!canStepWithFilters()) { return; } fUseStepFilters = true; stepInto(); } /** * Class which managed the queue of runnable associated with this thread. */ private class AsyncThread implements Runnable { private ArrayList fRunnables; private Thread fThread; public AsyncThread() { fRunnables= new ArrayList(); } public void addRunnable(Runnable runnable) { synchronized (this) { fRunnables.add(runnable); if (fThread == null) { try { fThread= new Thread(this, "JDI async thread - " + getName()); //$NON-NLS-1$ } catch (DebugException e) { JDIDebugPlugin.log(e); return; } fThread.start(); } else { notify(); } } } /** * Returns whether the queue is empty * * @return boolean */ public boolean isEmpty() { return fRunnables.isEmpty(); } public void clearQueue() { synchronized (this) { fRunnables.clear(); } } public void run() { while (true) { Runnable nextRunnable= null; synchronized (this) { if (fRunnables.isEmpty()) { try { wait(5000); } catch (InterruptedException e1) { } } if (fRunnables.isEmpty()) { fThread= null; return; } else { nextRunnable= (Runnable)fRunnables.remove(0); } } try { nextRunnable.run(); } catch (Throwable e) { JDIDebugPlugin.log(e); } } } } }
true
true
protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException { if (isSuspended()) { if (isTerminated()) { fStackFrames = Collections.EMPTY_LIST; } else if (refreshChildren) { if (fStackFrames.isEmpty()) { fStackFrames = createAllStackFrames(); if (fStackFrames.isEmpty()) { //leave fRefreshChildren == true //bug 6393 return fStackFrames; } } int stackSize = getUnderlyingFrameCount(); boolean topDown = false; // what was the last method on the top of the stack Method lastMethod = ((JDIStackFrame)fStackFrames.get(0)).getLastMethod(); // what is the method on top of the stack now if (stackSize > 0) { Method currMethod = getUnderlyingFrame(0).location().method(); if (currMethod.equals(lastMethod)) { // preserve frames top down topDown = true; } } // compute new or removed stack frames int offset= 0, length= stackSize; if (length > fStackFrames.size()) { if (topDown) { // add new (empty) frames to the bottom of the stack to preserve frames top-down int num = length - fStackFrames.size(); for (int i = 0; i < num; i++) { fStackFrames.add(new JDIStackFrame(this, 0)); } } else { // add new frames to the top of the stack, preserve bottom up offset= length - fStackFrames.size(); for (int i= offset - 1; i >= 0; i--) { JDIStackFrame newStackFrame= new JDIStackFrame(this, 0); fStackFrames.add(0, newStackFrame); } length= fStackFrames.size() - offset; } } else if (length < fStackFrames.size()) { int removed= fStackFrames.size() - length; if (topDown) { // remove frames from the bottom of the stack, preserve top-down for (int i = 0; i < removed; i++) { fStackFrames.remove(fStackFrames.size() - 1); } } else { // remove frames from the top of the stack, preserve bottom up for (int i= 0; i < removed; i++) { fStackFrames.remove(0); } } } else if (length == 0) { fStackFrames = Collections.EMPTY_LIST; } // update frame indicies for (int i= 0; i < stackSize; i++) { ((JDIStackFrame)fStackFrames.get(i)).setDepth(i); } } fRefreshChildren = false; } else { return Collections.EMPTY_LIST; } return fStackFrames; }
protected synchronized List computeStackFrames(boolean refreshChildren) throws DebugException { if (isSuspended()) { if (isTerminated()) { fStackFrames = Collections.EMPTY_LIST; } else if (refreshChildren) { if (fStackFrames.isEmpty()) { fStackFrames = createAllStackFrames(); if (fStackFrames.isEmpty()) { //leave fRefreshChildren == true //bug 6393 return fStackFrames; } } int stackSize = getUnderlyingFrameCount(); boolean topDown = false; // what was the last method on the top of the stack Method lastMethod = ((JDIStackFrame)fStackFrames.get(0)).getLastMethod(); // what is the method on top of the stack now if (stackSize > 0) { Method currMethod = getUnderlyingFrame(0).location().method(); if (currMethod.equals(lastMethod)) { // preserve frames top down topDown = true; } } // compute new or removed stack frames int offset= 0, length= stackSize; if (length > fStackFrames.size()) { if (topDown) { // add new (empty) frames to the bottom of the stack to preserve frames top-down int num = length - fStackFrames.size(); for (int i = 0; i < num; i++) { fStackFrames.add(new JDIStackFrame(this, 0)); } } else { // add new frames to the top of the stack, preserve bottom up offset= length - fStackFrames.size(); for (int i= offset - 1; i >= 0; i--) { JDIStackFrame newStackFrame= new JDIStackFrame(this, 0); fStackFrames.add(0, newStackFrame); } length= fStackFrames.size() - offset; } } else if (length < fStackFrames.size()) { int removed= fStackFrames.size() - length; if (topDown) { // remove frames from the bottom of the stack, preserve top-down for (int i = 0; i < removed; i++) { fStackFrames.remove(fStackFrames.size() - 1); } } else { // remove frames from the top of the stack, preserve bottom up for (int i= 0; i < removed; i++) { fStackFrames.remove(0); } } } else if (length == 0) { fStackFrames = Collections.EMPTY_LIST; } else if (length == fStackFrames.size()) { if (!topDown) { // replace stack frames with new objects such that equality // is not preserved (i.e. the top stack frame is different) fStackFrames = createAllStackFrames(); } } // update frame indicies for (int i= 0; i < stackSize; i++) { ((JDIStackFrame)fStackFrames.get(i)).setDepth(i); } } fRefreshChildren = false; } else { return Collections.EMPTY_LIST; } return fStackFrames; }
diff --git a/src/cytoscape/util/CyFileFilter.java b/src/cytoscape/util/CyFileFilter.java index a4f51f150..f88e6b329 100644 --- a/src/cytoscape/util/CyFileFilter.java +++ b/src/cytoscape/util/CyFileFilter.java @@ -1,280 +1,280 @@ // CyFileFilter.java /** Copyright (c) 2002 Institute for Systems Biology and the Whitehead Institute ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the GNU Lesser General Public License as published ** by the Free Software Foundation; either version 2.1 of the License, or ** any later version. ** ** This library is distributed in the hope that it will be useful, but ** WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF ** MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and ** documentation provided hereunder is on an "as is" basis, and the ** Institute for Systems Biology and the Whitehead Institute ** have no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall the ** Institute for Systems Biology and the Whitehead Institute ** be liable to any party for direct, indirect, special, ** incidental or consequential damages, including lost profits, arising ** out of the use of this software and its documentation, even if the ** Institute for Systems Biology and the Whitehead Institute ** have been advised of the possibility of such damage. See ** the GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this library; if not, write to the Free Software Foundation, ** Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. **/ package cytoscape.util; //--------------------------------------------------------------------------- import java.lang.Runtime; import java.io.File; import java.util.Hashtable; import java.util.Enumeration; import java.io.FilenameFilter; import javax.swing.*; import javax.swing.filechooser.*; /** * A convenience implementation of FileFilter that filters out * all files except for those type extensions that it knows about. * * Extensions are of the type ".foo", which is typically found on * Windows and Unix boxes, but not on Macinthosh. Case is ignored. * * @version 1.0 05/02/03 * @author Larissa Kamenkovich */ public class CyFileFilter extends FileFilter implements FilenameFilter { private static String TYPE_UNKNOWN = "Type Unknown"; private static String HIDDEN_FILE = "Hidden File"; private Hashtable filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true; /** * Creates a file filter. If no filters are added, then all * files are accepted. * * @see #addExtension */ public CyFileFilter() { this.filters = new Hashtable(); } /** * Creates a file filter that accepts files with the given extension. * Example: new ExampleFileFilter("jpg"); * * @see #addExtension */ public CyFileFilter(String extension) { this(extension,null); } /** * Creates a file filter that accepts the given file type. * Example: new ExampleFileFilter("jpg", "JPEG Image Images"); * * Note that the "." before the extension is not needed. If * provided, it will be ignored. * * @see #addExtension */ public CyFileFilter(String extension, String description) { this(); if(extension!=null) addExtension(extension); if(description!=null) setDescription(description); } /** * Creates a file filter from the given string array. * Example: new ExampleFileFilter(String {"gif", "jpg"}); * * Note that the "." before the extension is not needed adn * will be ignored. * * @see #addExtension */ public CyFileFilter(String[] filters) { this(filters, null); } /** * Creates a file filter from the given string array and description. * Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images"); * * Note that the "." before the extension is not needed and will be ignored. * * @see #addExtension */ public CyFileFilter(String[] filters, String description) { this(); for (int i = 0; i < filters.length; i++) { // add filters one by one addExtension(filters[i]); } if(description!=null) setDescription(description); } /** * Return true if this file should be shown in the directory pane, * false if it shouldn't. * * Files that begin with "." are ignored. * * @see #getExtension * @see FileFilter#accepts */ public boolean accept(File f) { if(f != null) { // If there are no filters, always accept if (filters.size()==0) { return true; } if(f.isDirectory()) { return true; } String extension = getExtension(f); if(extension != null && filters.get(getExtension(f)) != null) { return true; }; } return false; } /** * In order to implement the AWT version of this class * "FileNameFilter", the following method must also be * implemented. * */ public boolean accept ( File dir, String name ) { return accept( new File( name ) ); } /** * Return the extension portion of the file's name . * * @see #getExtension * @see FileFilter#accept */ public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); }; } return null; } /** * Adds a filetype "dot" extension to filter against. * * For example: the following code will create a filter that filters * out all files except those that end in ".jpg" and ".tif": * * ExampleFileFilter filter = new ExampleFileFilter(); * filter.addExtension("jpg"); * filter.addExtension("tif"); * * Note that the "." before the extension is not needed and will be ignored. */ public void addExtension(String extension) { if(filters == null) { filters = new Hashtable(5); } filters.put(extension.toLowerCase(), this); fullDescription = null; } /** * Returns the human readable description of this filter. For * example: "JPEG and GIF Image Files (*.jpg, *.gif)" * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription * @see FileFilter#getDescription */ public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if(extensions != null) { - fullDescription += "*." + (String) (extensions.hasMoreElements() ? extensions.nextElement() : "foo"); + fullDescription += "*." + (String) (extensions.hasMoreElements() ? extensions.nextElement() : "*"); while (extensions.hasMoreElements()) { fullDescription += ", *." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; } /** * Sets the human readable description of this filter. For * example: filter.setDescription("Gif and JPG Images"); * * @see setDescription * @see setExtensionListInDescription * @see isExtensionListInDescription */ public void setDescription(String description) { this.description = description; fullDescription = null; } /** * Determines whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see isExtensionListInDescription */ public void setExtensionListInDescription(boolean b) { useExtensionsInDescription = b; fullDescription = null; } /** * Returns whether the extension list (.jpg, .gif, etc) should * show up in the human readable description. * * Only relevent if a description was provided in the constructor * or using setDescription(); * * @see getDescription * @see setDescription * @see setExtensionListInDescription */ public boolean isExtensionListInDescription() { return useExtensionsInDescription; } }
true
true
public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if(extensions != null) { fullDescription += "*." + (String) (extensions.hasMoreElements() ? extensions.nextElement() : "foo"); while (extensions.hasMoreElements()) { fullDescription += ", *." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; }
public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; // build the description from the extension list Enumeration extensions = filters.keys(); if(extensions != null) { fullDescription += "*." + (String) (extensions.hasMoreElements() ? extensions.nextElement() : "*"); while (extensions.hasMoreElements()) { fullDescription += ", *." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; }
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/values/TransactionValue.java b/core/vdmj/src/main/java/org/overturetool/vdmj/values/TransactionValue.java index 2b1eae0760..781925aaf1 100644 --- a/core/vdmj/src/main/java/org/overturetool/vdmj/values/TransactionValue.java +++ b/core/vdmj/src/main/java/org/overturetool/vdmj/values/TransactionValue.java @@ -1,344 +1,344 @@ /******************************************************************************* * * Copyright (C) 2008 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ 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. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ package org.overturetool.vdmj.values; import java.util.List; import java.util.ListIterator; import java.util.Vector; import org.overturetool.vdmj.lex.LexLocation; import org.overturetool.vdmj.runtime.Context; import org.overturetool.vdmj.runtime.ContextException; import org.overturetool.vdmj.runtime.ValueException; import org.overturetool.vdmj.scheduler.BasicSchedulableThread; import org.overturetool.vdmj.types.Type; /** * A class to hold an updatable value that can be modified by VDM-RT * threads in transactions, committed at a duration point. */ public class TransactionValue extends UpdatableValue { private static final long serialVersionUID = 1L; private static List<TransactionValue> commitList = new Vector<TransactionValue>(); private Value newvalue = null; // The pending value before a commit private long newthreadid = -1; // The thread that made the change protected TransactionValue(Value value, ValueListenerList listeners) { super(value, listeners); newvalue = value; } protected TransactionValue(ValueListenerList listeners) { super(listeners); newvalue = value; } private Value select() { if (newthreadid > 0 && BasicSchedulableThread.getThread(Thread.currentThread()) != null && BasicSchedulableThread.getThread(Thread.currentThread()).getId() == newthreadid) { return newvalue; } else { return value; } } @Override public synchronized Value getUpdatable(ValueListenerList watch) { return new TransactionValue(select(), watch); } @Override public synchronized Value convertValueTo(Type to, Context ctxt) throws ValueException { return select().convertValueTo(to, ctxt).getUpdatable(listeners); } @Override public void set(LexLocation location, Value newval, Context ctxt) { long current = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); if (newthreadid > 0 && current != newthreadid) { throw new ContextException( 4142, "Value already updated by thread " + newthreadid, location, ctxt); } synchronized (this) { if (newval instanceof UpdatableValue) { - value = newval; + newvalue = newval; } else { - value = newval.getUpdatable(listeners); + newvalue = newval.getUpdatable(listeners); } - value = ((UpdatableValue)value).value; // To avoid nested updatables + newvalue = ((UpdatableValue)newvalue).value; // To avoid nested updatables } if (newthreadid < 0) { synchronized (commitList) { newthreadid = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); commitList.add(this); } } if (listeners != null) { listeners.changedValue(location, newvalue, ctxt); } } public static void commitAll() { synchronized (commitList) { for (TransactionValue v: commitList) { v.commit(); } commitList.clear(); } } public static void commitOne(long tid) { synchronized (commitList) { ListIterator<TransactionValue> it = commitList.listIterator(); while (it.hasNext()) { TransactionValue v = it.next(); if (v.newthreadid == tid) { v.commit(); it.remove(); } } } } private void commit() { if (newthreadid > 0) { value = newvalue; // Listener called for original "set" newthreadid = -1; } } @Override public synchronized Object clone() { return new TransactionValue((Value)select().clone(), listeners); } @Override public synchronized boolean isType(Class<? extends Value> valueclass) { return valueclass.isInstance(select()); } @Override public synchronized Value deref() { return select().deref(); } @Override public synchronized Value getConstant() { return select().getConstant(); } @Override public synchronized boolean isUndefined() { return select().isUndefined(); } @Override public synchronized boolean isVoid() { return select().isVoid(); } @Override public synchronized double realValue(Context ctxt) throws ValueException { return select().realValue(ctxt); } @Override public synchronized long intValue(Context ctxt) throws ValueException { return select().intValue(ctxt); } @Override public synchronized long natValue(Context ctxt) throws ValueException { return select().nat1Value(ctxt); } @Override public synchronized long nat1Value(Context ctxt) throws ValueException { return select().nat1Value(ctxt); } @Override public synchronized boolean boolValue(Context ctxt) throws ValueException { return select().boolValue(ctxt); } @Override public synchronized char charValue(Context ctxt) throws ValueException { return select().charValue(ctxt); } @Override public synchronized ValueList tupleValue(Context ctxt) throws ValueException { return select().tupleValue(ctxt); } @Override public synchronized RecordValue recordValue(Context ctxt) throws ValueException { return select().recordValue(ctxt); } @Override public synchronized ObjectValue objectValue(Context ctxt) throws ValueException { return select().objectValue(ctxt); } @Override public synchronized String quoteValue(Context ctxt) throws ValueException { return select().quoteValue(ctxt); } @Override public synchronized ValueList seqValue(Context ctxt) throws ValueException { return select().seqValue(ctxt); } @Override public synchronized ValueSet setValue(Context ctxt) throws ValueException { return select().setValue(ctxt); } @Override public synchronized String stringValue(Context ctxt) throws ValueException { return select().stringValue(ctxt); } @Override public synchronized ValueMap mapValue(Context ctxt) throws ValueException { return select().mapValue(ctxt); } @Override public synchronized FunctionValue functionValue(Context ctxt) throws ValueException { return select().functionValue(ctxt); } @Override public synchronized OperationValue operationValue(Context ctxt) throws ValueException { return select().operationValue(ctxt); } @Override public synchronized boolean equals(Object other) { if (other instanceof Value) { Value val = ((Value)other).deref(); if (val instanceof TransactionValue) { TransactionValue tvo = (TransactionValue)val; return select().equals(tvo.select()); } else if (val instanceof ReferenceValue) { ReferenceValue rvo = (ReferenceValue)val; return select().equals(rvo.value); } else { return select().equals(other); } } return false; } @Override public synchronized String kind() { return select().kind(); } @Override public synchronized int hashCode() { return select().hashCode(); } @Override public synchronized String toString() { return select().toString(); } }
false
true
public void set(LexLocation location, Value newval, Context ctxt) { long current = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); if (newthreadid > 0 && current != newthreadid) { throw new ContextException( 4142, "Value already updated by thread " + newthreadid, location, ctxt); } synchronized (this) { if (newval instanceof UpdatableValue) { value = newval; } else { value = newval.getUpdatable(listeners); } value = ((UpdatableValue)value).value; // To avoid nested updatables } if (newthreadid < 0) { synchronized (commitList) { newthreadid = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); commitList.add(this); } } if (listeners != null) { listeners.changedValue(location, newvalue, ctxt); } }
public void set(LexLocation location, Value newval, Context ctxt) { long current = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); if (newthreadid > 0 && current != newthreadid) { throw new ContextException( 4142, "Value already updated by thread " + newthreadid, location, ctxt); } synchronized (this) { if (newval instanceof UpdatableValue) { newvalue = newval; } else { newvalue = newval.getUpdatable(listeners); } newvalue = ((UpdatableValue)newvalue).value; // To avoid nested updatables } if (newthreadid < 0) { synchronized (commitList) { newthreadid = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); commitList.add(this); } } if (listeners != null) { listeners.changedValue(location, newvalue, ctxt); } }
diff --git a/jOOQ-test/src/org/jooq/test/_/testcases/ResultSetTests.java b/jOOQ-test/src/org/jooq/test/_/testcases/ResultSetTests.java index d0f827176..5de0e9a23 100644 --- a/jOOQ-test/src/org/jooq/test/_/testcases/ResultSetTests.java +++ b/jOOQ-test/src/org/jooq/test/_/testcases/ResultSetTests.java @@ -1,182 +1,186 @@ /** * Copyright (c) 2009-2013, Lukas Eder, [email protected] * All rights reserved. * * This software is licensed to you under the Apache License, Version 2.0 * (the "License"); You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * . Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * . Neither the name "jOOQ" nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.jooq.test._.testcases; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.jooq.SQLDialect.SQLITE; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import org.jooq.ExecuteContext; import org.jooq.Record1; import org.jooq.Record2; import org.jooq.Record3; import org.jooq.Record6; import org.jooq.TableRecord; import org.jooq.UpdatableRecord; import org.jooq.exception.DataAccessException; import org.jooq.impl.DefaultExecuteListener; import org.jooq.test.BaseTest; import org.jooq.test.jOOQAbstractTest; import org.junit.Test; public class ResultSetTests< A extends UpdatableRecord<A> & Record6<Integer, String, String, Date, Integer, ?>, AP, B extends UpdatableRecord<B>, S extends UpdatableRecord<S> & Record1<String>, B2S extends UpdatableRecord<B2S> & Record3<String, Integer, Integer>, BS extends UpdatableRecord<BS>, L extends TableRecord<L> & Record2<String, String>, X extends TableRecord<X>, DATE extends UpdatableRecord<DATE>, BOOL extends UpdatableRecord<BOOL>, D extends UpdatableRecord<D>, T extends UpdatableRecord<T>, U extends TableRecord<U>, UU extends UpdatableRecord<UU>, I extends TableRecord<I>, IPK extends UpdatableRecord<IPK>, T725 extends UpdatableRecord<T725>, T639 extends UpdatableRecord<T639>, T785 extends TableRecord<T785>> extends BaseTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> { public ResultSetTests(jOOQAbstractTest<A, AP, B, S, B2S, BS, L, X, DATE, BOOL, D, T, U, UU, I, IPK, T725, T639, T785> delegate) { super(delegate); } @Test public void testResultSetType() throws Exception { if (asList(SQLITE).contains(dialect())) { log.info("SKIPPING", "ResultSet type tests"); return; } ResultSet rs = create().select(TBook_ID()) .from(TBook()) .where(TBook_ID().in(1, 2)) .orderBy(TBook_ID()) .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .fetchResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertTrue(rs.previous()); assertEquals(1, rs.getInt(1)); assertTrue(rs.last()); assertEquals(2, rs.getInt(1)); rs.close(); } @SuppressWarnings("serial") @Test public void testResultSetTypeWithListener() throws Exception { if (asList(SQLITE).contains(dialect())) { log.info("SKIPPING", "ResultSet type tests"); return; } assertEquals( asList(1, 1, 1, 2), create(new DefaultExecuteListener() { int repeat; @Override public void recordEnd(ExecuteContext ctx) { try { // Rewind the first record three times if (++repeat < 3) ctx.resultSet().previous(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID()) .from(TBook()) .where(TBook_ID().in(1, 2)) .orderBy(TBook_ID()) .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .fetch(TBook_ID())); } @SuppressWarnings("serial") @Test public void testResultSetConcurrency() throws Exception { - if (asList(SQLITE).contains(dialect())) { - log.info("SKIPPING", "ResultSet concurrency tests"); - return; + switch (dialect()) { + case SQLITE: + log.info("SKIPPING", "ResultSet concurrency tests"); + return; } jOOQAbstractTest.reset = false; assertEquals( asList("Title 1", "Title 2", "Title 3", "Title 4"), create(new DefaultExecuteListener() { int repeat; @Override public void recordStart(ExecuteContext ctx) { try { // Change values before reading a record ctx.resultSet().updateString(TBook_TITLE().getName(), "Title " + (++repeat)); ctx.resultSet().updateRow(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID(), TBook_TITLE()) .from(TBook()) - .orderBy(TBook_ID()) + // Derby doesn't support ORDER BY when using CONCUR_UPDATABLE + // https://issues.apache.org/jira/browse/DERBY-4138 + // .orderBy(TBook_ID()) + .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .resultSetConcurrency(ResultSet.CONCUR_UPDATABLE) .fetch(TBook_TITLE())); } }
false
true
public void testResultSetConcurrency() throws Exception { if (asList(SQLITE).contains(dialect())) { log.info("SKIPPING", "ResultSet concurrency tests"); return; } jOOQAbstractTest.reset = false; assertEquals( asList("Title 1", "Title 2", "Title 3", "Title 4"), create(new DefaultExecuteListener() { int repeat; @Override public void recordStart(ExecuteContext ctx) { try { // Change values before reading a record ctx.resultSet().updateString(TBook_TITLE().getName(), "Title " + (++repeat)); ctx.resultSet().updateRow(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID(), TBook_TITLE()) .from(TBook()) .orderBy(TBook_ID()) .resultSetConcurrency(ResultSet.CONCUR_UPDATABLE) .fetch(TBook_TITLE())); }
public void testResultSetConcurrency() throws Exception { switch (dialect()) { case SQLITE: log.info("SKIPPING", "ResultSet concurrency tests"); return; } jOOQAbstractTest.reset = false; assertEquals( asList("Title 1", "Title 2", "Title 3", "Title 4"), create(new DefaultExecuteListener() { int repeat; @Override public void recordStart(ExecuteContext ctx) { try { // Change values before reading a record ctx.resultSet().updateString(TBook_TITLE().getName(), "Title " + (++repeat)); ctx.resultSet().updateRow(); } catch (SQLException e) { throw new DataAccessException("Exception", e); } } }) .select(TBook_ID(), TBook_TITLE()) .from(TBook()) // Derby doesn't support ORDER BY when using CONCUR_UPDATABLE // https://issues.apache.org/jira/browse/DERBY-4138 // .orderBy(TBook_ID()) .resultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE) .resultSetConcurrency(ResultSet.CONCUR_UPDATABLE) .fetch(TBook_TITLE())); }
diff --git a/src/com/orangeleap/tangerine/json/controller/PostbatchGiftListController.java b/src/com/orangeleap/tangerine/json/controller/PostbatchGiftListController.java index e2770d48..413aeb14 100644 --- a/src/com/orangeleap/tangerine/json/controller/PostbatchGiftListController.java +++ b/src/com/orangeleap/tangerine/json/controller/PostbatchGiftListController.java @@ -1,104 +1,108 @@ /* * Copyright (c) 2009. Orange Leap Inc. Active Constituent * Relationship Management Platform. * * 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.orangeleap.tangerine.json.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.orangeleap.tangerine.domain.PostBatch; import com.orangeleap.tangerine.service.PostBatchService; import com.orangeleap.tangerine.util.OLLogger; import com.orangeleap.tangerine.web.common.PaginatedResult; import com.orangeleap.tangerine.web.common.SortInfo; /** * This controller handles JSON requests for populating * the grid of gifts. * * @version 1.0 */ @Controller public class PostbatchGiftListController { /** * Logger for this class and subclasses */ protected final Log logger = OLLogger.getLog(getClass()); private final static Map<String, Object> GIFT_NAME_MAP = new HashMap<String, Object>(); private final static Map<String, Object> ADJUSTED_GIFT_NAME_MAP = new HashMap<String, Object>(); static { GIFT_NAME_MAP.put("id", "g.GIFT_ID"); GIFT_NAME_MAP.put("createdate", "g.CREATE_DATE"); GIFT_NAME_MAP.put("donationdate", "g.DONATION_DATE"); GIFT_NAME_MAP.put("amount", "g.AMOUNT"); GIFT_NAME_MAP.put("currencycode", "g.CURRENCY_CODE"); GIFT_NAME_MAP.put("paymenttype", "g.PAYMENT_TYPE"); GIFT_NAME_MAP.put("status", "g.GIFT_STATUS"); } @Resource(name = "postBatchService") private PostBatchService postBatchService; @SuppressWarnings("unchecked") @RequestMapping("/postbatchGiftList.json") public ModelMap getPostbatchGiftList(HttpServletRequest request, SortInfo sortInfo) { List<Map> rows = new ArrayList<Map>(); + ModelMap map = new ModelMap("rows", rows); + map.put("totalRows", 0); try { String sid = request.getParameter("id"); - if (sid == null || sid.trim().length() == 0) return new ModelMap("rows", rows); + if (sid == null || sid.trim().length() == 0) { + return map; + } long postbatchId = Long.valueOf(sid); PostBatch postbatch = postBatchService.readBatch(postbatchId); Map namemap = postbatch.getEntity().equals("gift")?GIFT_NAME_MAP:ADJUSTED_GIFT_NAME_MAP; // if we're not getting back a valid column name, possible SQL injection, // so send back an empty list. if (!sortInfo.validateSortField(namemap.keySet())) { - return new ModelMap("rows", rows); + return map; } // set the sort to the valid column name, based on the map sortInfo.setSort((String) namemap.get(sortInfo.getSort())); PaginatedResult result = postBatchService.getBatchSelectionList(postbatchId, sortInfo); - ModelMap map = new ModelMap("rows", result.getRows()); + map = new ModelMap("rows", result.getRows()); map.put("totalRows", result.getRowCount()); return map; } catch (Exception e) { logger.error(e); - return new ModelMap("rows", rows); + return map; } } }
false
true
public ModelMap getPostbatchGiftList(HttpServletRequest request, SortInfo sortInfo) { List<Map> rows = new ArrayList<Map>(); try { String sid = request.getParameter("id"); if (sid == null || sid.trim().length() == 0) return new ModelMap("rows", rows); long postbatchId = Long.valueOf(sid); PostBatch postbatch = postBatchService.readBatch(postbatchId); Map namemap = postbatch.getEntity().equals("gift")?GIFT_NAME_MAP:ADJUSTED_GIFT_NAME_MAP; // if we're not getting back a valid column name, possible SQL injection, // so send back an empty list. if (!sortInfo.validateSortField(namemap.keySet())) { return new ModelMap("rows", rows); } // set the sort to the valid column name, based on the map sortInfo.setSort((String) namemap.get(sortInfo.getSort())); PaginatedResult result = postBatchService.getBatchSelectionList(postbatchId, sortInfo); ModelMap map = new ModelMap("rows", result.getRows()); map.put("totalRows", result.getRowCount()); return map; } catch (Exception e) { logger.error(e); return new ModelMap("rows", rows); } }
public ModelMap getPostbatchGiftList(HttpServletRequest request, SortInfo sortInfo) { List<Map> rows = new ArrayList<Map>(); ModelMap map = new ModelMap("rows", rows); map.put("totalRows", 0); try { String sid = request.getParameter("id"); if (sid == null || sid.trim().length() == 0) { return map; } long postbatchId = Long.valueOf(sid); PostBatch postbatch = postBatchService.readBatch(postbatchId); Map namemap = postbatch.getEntity().equals("gift")?GIFT_NAME_MAP:ADJUSTED_GIFT_NAME_MAP; // if we're not getting back a valid column name, possible SQL injection, // so send back an empty list. if (!sortInfo.validateSortField(namemap.keySet())) { return map; } // set the sort to the valid column name, based on the map sortInfo.setSort((String) namemap.get(sortInfo.getSort())); PaginatedResult result = postBatchService.getBatchSelectionList(postbatchId, sortInfo); map = new ModelMap("rows", result.getRows()); map.put("totalRows", result.getRowCount()); return map; } catch (Exception e) { logger.error(e); return map; } }
diff --git a/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java b/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java index 6cf53f746..967f46e80 100644 --- a/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java +++ b/src/scratchpad/src/org/apache/poi/hwpf/model/UnhandledDataStructure.java @@ -1,56 +1,58 @@ /* ==================================================================== 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.poi.hwpf.model; import java.util.Arrays; import org.apache.poi.util.Internal; /** * A data structure used to hold some data we don't * understand / can't handle, so we have it available * for when we come to write back out again */ @Internal public final class UnhandledDataStructure { byte[] _buf; public UnhandledDataStructure(byte[] buf, int offset, int length) { // Sanity check the size they've asked for - if (offset + length > buf.length) + int offsetEnd = offset + length; + if (offsetEnd > buf.length || offsetEnd < 0) { throw new IndexOutOfBoundsException("Buffer Length is " + buf.length + " " + - "but code is tried to read " + length + " from offset " + offset); + "but code is tried to read " + length + " " + + "from offset " + offset + " to " + offsetEnd); } if (offset < 0 || length < 0) { throw new IndexOutOfBoundsException("Offset and Length must both be >= 0, negative " + "indicies are not permitted - code is tried to read " + length + " from offset " + offset); } // Save that requested portion of the data - _buf = Arrays.copyOfRange(buf, offset, offset + length); + _buf = Arrays.copyOfRange(buf, offset, offsetEnd); } byte[] getBuf() { return _buf; } }
false
true
public UnhandledDataStructure(byte[] buf, int offset, int length) { // Sanity check the size they've asked for if (offset + length > buf.length) { throw new IndexOutOfBoundsException("Buffer Length is " + buf.length + " " + "but code is tried to read " + length + " from offset " + offset); } if (offset < 0 || length < 0) { throw new IndexOutOfBoundsException("Offset and Length must both be >= 0, negative " + "indicies are not permitted - code is tried to read " + length + " from offset " + offset); } // Save that requested portion of the data _buf = Arrays.copyOfRange(buf, offset, offset + length); }
public UnhandledDataStructure(byte[] buf, int offset, int length) { // Sanity check the size they've asked for int offsetEnd = offset + length; if (offsetEnd > buf.length || offsetEnd < 0) { throw new IndexOutOfBoundsException("Buffer Length is " + buf.length + " " + "but code is tried to read " + length + " " + "from offset " + offset + " to " + offsetEnd); } if (offset < 0 || length < 0) { throw new IndexOutOfBoundsException("Offset and Length must both be >= 0, negative " + "indicies are not permitted - code is tried to read " + length + " from offset " + offset); } // Save that requested portion of the data _buf = Arrays.copyOfRange(buf, offset, offsetEnd); }
diff --git a/src/main/java/org/dynmap/hdmap/IsoHDPerspective.java b/src/main/java/org/dynmap/hdmap/IsoHDPerspective.java index d9e7c388..4f44bcf9 100644 --- a/src/main/java/org/dynmap/hdmap/IsoHDPerspective.java +++ b/src/main/java/org/dynmap/hdmap/IsoHDPerspective.java @@ -1,1365 +1,1368 @@ package org.dynmap.hdmap; import static org.dynmap.JSONUtils.s; import org.dynmap.DynmapWorld; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.dynmap.Client; import org.dynmap.Color; import org.dynmap.ConfigurationNode; import org.dynmap.DynmapChunk; import org.dynmap.DynmapCore; import org.dynmap.DynmapCore.CompassMode; import org.dynmap.Log; import org.dynmap.MapManager; import org.dynmap.MapTile; import org.dynmap.MapType; import org.dynmap.MapType.ImageFormat; import org.dynmap.TileHashManager; import org.dynmap.debug.Debug; import org.dynmap.utils.MapIterator.BlockStep; import org.dynmap.hdmap.TexturePack.BlockTransparency; import org.dynmap.hdmap.TexturePack.HDTextureMap; import org.dynmap.utils.DynmapBufferedImage; import org.dynmap.utils.FileLockManager; import org.dynmap.utils.MapChunkCache; import org.dynmap.utils.MapIterator; import org.dynmap.utils.Matrix3D; import org.dynmap.utils.Vector3D; import org.json.simple.JSONObject; public class IsoHDPerspective implements HDPerspective { private String name; /* View angles */ public double azimuth; /* Angle in degrees from looking north (0), east (90), south (180), or west (270) */ public double inclination; /* Angle in degrees from horizontal (0) to vertical (90) */ public double scale; /* Scale - tile pixel widths per block */ public double maxheight; public double minheight; private boolean fencejoin; /* Coordinate space for tiles consists of a plane (X, Y), corresponding to the projection of each tile on to the * plane of the bottom of the world (X positive to the right, Y positive to the top), with Z+ corresponding to the * height above this plane on a vector towards the viewer). Logically, this makes the parallelogram representing the * space contributing to the tile have consistent tile-space X,Y coordinate pairs for both the top and bottom faces * Note that this is a classic right-hand coordinate system, while minecraft's world coordinates are left handed * (X+ is south, Y+ is up, Z+ is east). */ /* Transformation matrix for taking coordinate in world-space (x, y, z) and finding coordinate in tile space (x, y, z) */ private Matrix3D world_to_map; private Matrix3D map_to_world; /* Scaled models for non-cube blocks */ private HDBlockModels.HDScaledBlockModels scalemodels; private int modscale; /* dimensions of a map tile */ public static final int tileWidth = 128; public static final int tileHeight = 128; /* Maximum and minimum inclinations */ public static final double MAX_INCLINATION = 90.0; public static final double MIN_INCLINATION = 20.0; /* Maximum and minimum scale */ public static final double MAX_SCALE = 64; public static final double MIN_SCALE = 1; private boolean need_biomedata = false; private boolean need_rawbiomedata = false; private static final int CHEST_BLKTYPEID = 54; private static final int REDSTONE_BLKTYPEID = 55; private static final int FENCEGATE_BLKTYPEID = 107; private enum ChestData { SINGLE_WEST, SINGLE_SOUTH, SINGLE_EAST, SINGLE_NORTH, LEFT_WEST, LEFT_SOUTH, LEFT_EAST, LEFT_NORTH, RIGHT_WEST, RIGHT_SOUTH, RIGHT_EAST, RIGHT_NORTH }; /* Orientation lookup for single chest - index bits: occupied blocks NESW */ private static final ChestData[] SINGLE_LOOKUP = { ChestData.SINGLE_WEST, ChestData.SINGLE_EAST, ChestData.SINGLE_NORTH, ChestData.SINGLE_NORTH, ChestData.SINGLE_WEST, ChestData.SINGLE_WEST, ChestData.SINGLE_NORTH, ChestData.SINGLE_NORTH, ChestData.SINGLE_SOUTH, ChestData.SINGLE_SOUTH, ChestData.SINGLE_WEST, ChestData.SINGLE_EAST, ChestData.SINGLE_SOUTH, ChestData.SINGLE_SOUTH, ChestData.SINGLE_WEST, ChestData.SINGLE_EAST }; private class OurPerspectiveState implements HDPerspectiveState { int blocktypeid = 0; int blockdata = 0; int blockrenderdata = -1; int lastblocktypeid = 0; Vector3D top, bottom; int px, py; BlockStep laststep = BlockStep.Y_MINUS; BlockStep stepx, stepy, stepz; /* Section-level raytrace variables */ int sx, sy, sz; double sdt_dx, sdt_dy, sdt_dz, st; double st_next_x, st_next_y, st_next_z; /* Raytrace state variables */ double dx, dy, dz; int x, y, z; double dt_dx, dt_dy, dt_dz, t; int n; int x_inc, y_inc, z_inc; double t_next_y, t_next_x, t_next_z; boolean nonairhit; /* Subblock tracer state */ int mx, my, mz; double xx, yy, zz; double mdt_dx; double mdt_dy; double mdt_dz; double togo; double mt_next_x, mt_next_y, mt_next_z; int subalpha; double mt; double mtend; int mxout, myout, mzout; int[] subblock_xyz = new int[3]; MapIterator mapiter; boolean isnether; boolean skiptoair; int worldheight; int heightmask; public OurPerspectiveState(MapIterator mi, boolean isnether) { mapiter = mi; this.isnether = isnether; worldheight = mapiter.getWorldHeight(); int shift; for(shift = 0; (1<<shift) < worldheight; shift++) {} heightmask = (1<<shift) - 1; } private final LightLevels updateSemitransparentLight() { BlockStep [] steps = { BlockStep.Y_PLUS, BlockStep.X_MINUS, BlockStep.X_PLUS, BlockStep.Z_MINUS, BlockStep.Z_PLUS }; int emitted = 0, sky = 0; for(int i = 0; i < steps.length; i++) { BlockStep s = steps[i]; mapiter.stepPosition(s); int v = mapiter.getBlockEmittedLight(); if(v > emitted) emitted = v; v = mapiter.getBlockSkyLight(); if(v > sky) sky = v; mapiter.unstepPosition(s); } return new LightLevels(sky,emitted); } /** * Update sky and emitted light */ private final LightLevels updateLightLevel(int blktypeid) { LightLevels ll; /* Look up transparency for current block */ BlockTransparency bt = HDTextureMap.getTransparency(blktypeid); switch(bt) { case TRANSPARENT: ll = new LightLevels( mapiter.getBlockSkyLight(), mapiter.getBlockEmittedLight()); break; case OPAQUE: if(HDTextureMap.getTransparency(lastblocktypeid) != BlockTransparency.SEMITRANSPARENT) { mapiter.unstepPosition(laststep); /* Back up to block we entered on */ if(mapiter.getY() < worldheight) { ll = new LightLevels(mapiter.getBlockSkyLight(), mapiter.getBlockEmittedLight()); } else { ll = new LightLevels(15, 0); } mapiter.stepPosition(laststep); } else { mapiter.unstepPosition(laststep); /* Back up to block we entered on */ ll = updateSemitransparentLight(); mapiter.stepPosition(laststep); } break; case SEMITRANSPARENT: ll = updateSemitransparentLight(); break; default: ll = new LightLevels( mapiter.getBlockSkyLight(), mapiter.getBlockEmittedLight()); break; } return ll; } /** * Get light level - only available if shader requested it */ public final LightLevels getLightLevels() { return updateLightLevel(blocktypeid); } /** * Get sky light level - only available if shader requested it */ public final LightLevels getLightLevelsAtStep(BlockStep step) { if(((step == BlockStep.Y_MINUS) && (y == 0)) || ((step == BlockStep.Y_PLUS) && (y == worldheight))) { return getLightLevels(); } BlockStep blast = laststep; mapiter.stepPosition(step); laststep = blast; LightLevels ll = updateLightLevel(mapiter.getBlockTypeID()); mapiter.unstepPosition(step); laststep = blast; return ll; } /** * Get current block type ID */ public final int getBlockTypeID() { return blocktypeid; } /** * Get current block data */ public final int getBlockData() { return blockdata; } /** * Get current block render data */ public final int getBlockRenderData() { return blockrenderdata; } /** * Get direction of last block step */ public final BlockStep getLastBlockStep() { return laststep; } /** * Get perspective scale */ public final double getScale() { return scale; } /** * Get start of current ray, in world coordinates */ public final Vector3D getRayStart() { return top; } /** * Get end of current ray, in world coordinates */ public final Vector3D getRayEnd() { return bottom; } /** * Get pixel X coordinate */ public final int getPixelX() { return px; } /** * Get pixel Y coordinate */ public final int getPixelY() { return py; } /** * Get map iterator */ public final MapIterator getMapIterator() { return mapiter; } /** * Return submodel alpha value (-1 if no submodel rendered) */ public int getSubmodelAlpha() { return subalpha; } /** * Initialize raytrace state variables */ private void raytrace_init() { /* Compute total delta on each axis */ dx = Math.abs(bottom.x - top.x); dy = Math.abs(bottom.y - top.y); dz = Math.abs(bottom.z - top.z); /* Compute parametric step (dt) per step on each axis */ dt_dx = 1.0 / dx; dt_dy = 1.0 / dy; dt_dz = 1.0 / dz; /* Initialize parametric value to 0 (and we're stepping towards 1) */ t = 0; /* Compute number of steps and increments for each */ n = 1; /* Initial section coord */ sx = fastFloor(top.x/16.0); sy = fastFloor(top.y/16.0); sz = fastFloor(top.z/16.0); /* Compute parametric step (dt) per step on each axis */ sdt_dx = 16.0 / dx; sdt_dy = 16.0 / dy; sdt_dz = 16.0 / dz; /* If perpendicular to X axis */ if (dx == 0) { x_inc = 0; st_next_x = Double.MAX_VALUE; stepx = BlockStep.X_PLUS; mxout = modscale; } /* If bottom is right of top */ else if (bottom.x > top.x) { x_inc = 1; n += fastFloor(bottom.x) - x; st_next_x = (fastFloor(top.x/16.0) + 1 - (top.x/16.0)) * sdt_dx; stepx = BlockStep.X_PLUS; mxout = modscale; } /* Top is right of bottom */ else { x_inc = -1; n += x - fastFloor(bottom.x); st_next_x = ((top.x/16.0) - fastFloor(top.x/16.0)) * sdt_dx; stepx = BlockStep.X_MINUS; mxout = -1; } /* If perpendicular to Y axis */ if (dy == 0) { y_inc = 0; st_next_y = Double.MAX_VALUE; stepy = BlockStep.Y_PLUS; myout = modscale; } /* If bottom is above top */ else if (bottom.y > top.y) { y_inc = 1; n += fastFloor(bottom.y) - y; st_next_y = (fastFloor(top.y/16.0) + 1 - (top.y/16.0)) * sdt_dy; stepy = BlockStep.Y_PLUS; myout = modscale; } /* If top is above bottom */ else { y_inc = -1; n += y - fastFloor(bottom.y); st_next_y = ((top.y/16.0) - fastFloor(top.y/16.0)) * sdt_dy; stepy = BlockStep.Y_MINUS; myout = -1; } /* If perpendicular to Z axis */ if (dz == 0) { z_inc = 0; st_next_z = Double.MAX_VALUE; stepz = BlockStep.Z_PLUS; mzout = modscale; } /* If bottom right of top */ else if (bottom.z > top.z) { z_inc = 1; n += fastFloor(bottom.z) - z; st_next_z = (fastFloor(top.z/16.0) + 1 - (top.z/16.0)) * sdt_dz; stepz = BlockStep.Z_PLUS; mzout = modscale; } /* If bottom left of top */ else { z_inc = -1; n += z - fastFloor(bottom.z); st_next_z = ((top.z/16.0) - fastFloor(top.z/16.0)) * sdt_dz; stepz = BlockStep.Z_MINUS; mzout = -1; } /* Walk through scene */ laststep = BlockStep.Y_MINUS; /* Last step is down into map */ nonairhit = false; skiptoair = isnether; } private int generateFenceBlockData(MapIterator mapiter, int blkid) { int blockdata = 0; int id; /* Check north */ id = mapiter.getBlockTypeIDAt(BlockStep.X_MINUS); if((id == blkid) || (id == FENCEGATE_BLKTYPEID) || (fencejoin && (id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { /* Fence? */ blockdata |= 1; } /* Look east */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_MINUS); if((id == blkid) || (id == FENCEGATE_BLKTYPEID) || (fencejoin && (id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { /* Fence? */ blockdata |= 2; } /* Look south */ id = mapiter.getBlockTypeIDAt(BlockStep.X_PLUS); if((id == blkid) || (id == FENCEGATE_BLKTYPEID) || (fencejoin && (id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { /* Fence? */ blockdata |= 4; } /* Look west */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_PLUS); if((id == blkid) || (id == FENCEGATE_BLKTYPEID) || (fencejoin && (id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { /* Fence? */ blockdata |= 8; } return blockdata; } /** * Generate chest block to drive model selection: * 0 = single facing west * 1 = single facing south * 2 = single facing east * 3 = single facing north * 4 = left side facing west * 5 = left side facing south * 6 = left side facing east * 7 = left side facing north * 8 = right side facing west * 9 = right side facing south * 10 = right side facing east * 11 = right side facing north * @param mapiter * @return */ private int generateChestBlockData(MapIterator mapiter) { ChestData cd = ChestData.SINGLE_WEST; /* Default to single facing west */ /* Check adjacent block IDs */ int ids[] = { mapiter.getBlockTypeIDAt(BlockStep.Z_PLUS), /* To west */ mapiter.getBlockTypeIDAt(BlockStep.X_PLUS), /* To south */ mapiter.getBlockTypeIDAt(BlockStep.Z_MINUS), /* To east */ mapiter.getBlockTypeIDAt(BlockStep.X_MINUS) }; /* To north */ /* First, check if we're a double - see if any adjacent chests */ if(ids[0] == CHEST_BLKTYPEID) { /* Another to west - assume we face south */ cd = ChestData.RIGHT_SOUTH; /* We're right side */ } else if(ids[1] == CHEST_BLKTYPEID) { /* Another to south - assume west facing */ cd = ChestData.LEFT_WEST; /* We're left side */ } else if(ids[2] == CHEST_BLKTYPEID) { /* Another to east - assume south facing */ cd = ChestData.LEFT_SOUTH; /* We're left side */ } else if(ids[3] == CHEST_BLKTYPEID) { /* Another to north - assume west facing */ cd = ChestData.RIGHT_WEST; /* We're right side */ } else { /* Else, single - build index into lookup table */ int idx = 0; for(int i = 0; i < ids.length; i++) { if((ids[i] != 0) && (HDTextureMap.getTransparency(ids[i]) != BlockTransparency.TRANSPARENT)) { idx |= (1<<i); } } cd = SINGLE_LOOKUP[idx]; } return cd.ordinal(); } /** * Generate redstone wire model data: * 0 = NSEW wire * 1 = NS wire * 2 = EW wire * 3 = NE wire * 4 = NW wire * 5 = SE wire * 6 = SW wire * 7 = NSE wire * 8 = NSW wire * 9 = NEW wire * 10 = SEW wire * @param mapiter * @return */ private int generateRedstoneWireBlockData(MapIterator mapiter) { /* Check adjacent block IDs */ int ids[] = { mapiter.getBlockTypeIDAt(BlockStep.Z_PLUS), /* To west */ mapiter.getBlockTypeIDAt(BlockStep.X_PLUS), /* To south */ mapiter.getBlockTypeIDAt(BlockStep.Z_MINUS), /* To east */ mapiter.getBlockTypeIDAt(BlockStep.X_MINUS) }; /* To north */ int flags = 0; for(int i = 0; i < 4; i++) if(ids[i] == REDSTONE_BLKTYPEID) flags |= (1<<i); switch(flags) { case 0: /* Nothing nearby */ case 15: /* NSEW */ return 0; /* NSEW graphic */ case 2: /* S */ case 8: /* N */ case 10: /* NS */ return 1; /* NS graphic */ case 1: /* W */ case 4: /* E */ case 5: /* EW */ return 2; /* EW graphic */ case 12: /* NE */ return 3; case 9: /* NW */ return 4; case 6: /* SE */ return 5; case 3: /* SW */ return 6; case 14: /* NSE */ return 7; case 11: /* NSW */ return 8; case 13: /* NEW */ return 9; case 7: /* SEW */ return 10; } return 0; } /** * Generate block render data for glass pane and iron fence. * - bit 0 = X-minus axis * - bit 1 = Z-minus axis * - bit 2 = X-plus axis * - bit 3 = Z-plus axis * * @param mapiter - iterator * @param typeid - ID of our material (test is for adjacent material OR nontransparent) * @return */ private int generateIronFenceGlassBlockData(MapIterator mapiter, int typeid) { int blockdata = 0; int id; /* Check north */ id = mapiter.getBlockTypeIDAt(BlockStep.X_MINUS); if((id == typeid) || ((id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { blockdata |= 1; } /* Look east */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_MINUS); if((id == typeid) || ((id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { blockdata |= 2; } /* Look south */ id = mapiter.getBlockTypeIDAt(BlockStep.X_PLUS); if((id == typeid) || ((id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { blockdata |= 4; } /* Look west */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_PLUS); if((id == typeid) || ((id > 0) && (HDTextureMap.getTransparency(id) == BlockTransparency.OPAQUE))) { blockdata |= 8; } return blockdata; } private final boolean containsID(int id, int[] linkids) { for(int i = 0; i < linkids.length; i++) if(id == linkids[i]) return true; return false; } private int generateWireBlockData(MapIterator mapiter, int[] linkids) { int blockdata = 0; int id; /* Check north */ id = mapiter.getBlockTypeIDAt(BlockStep.X_MINUS); if(containsID(id, linkids)) { blockdata |= 1; } /* Look east */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_MINUS); if(containsID(id, linkids)) { blockdata |= 2; } /* Look south */ id = mapiter.getBlockTypeIDAt(BlockStep.X_PLUS); if(containsID(id, linkids)) { blockdata |= 4; } /* Look west */ id = mapiter.getBlockTypeIDAt(BlockStep.Z_PLUS); if(containsID(id, linkids)) { blockdata |= 8; } return blockdata; } private final boolean handleSubModel(short[] model, HDShaderState[] shaderstate, boolean[] shaderdone) { boolean firststep = true; while(!raytraceSubblock(model, firststep)) { boolean done = true; for(int i = 0; i < shaderstate.length; i++) { if(!shaderdone[i]) shaderdone[i] = shaderstate[i].processBlock(this); done = done && shaderdone[i]; } /* If all are done, we're out */ if(done) return true; nonairhit = true; firststep = false; } return false; } private static final int FENCE_ALGORITHM = 1; private static final int CHEST_ALGORITHM = 2; private static final int REDSTONE_ALGORITHM = 3; private static final int GLASS_IRONFENCE_ALG = 4; private static final int WIRE_ALGORITHM = 5; /** * Process visit of ray to block */ private final boolean visit_block(MapIterator mapiter, HDShaderState[] shaderstate, boolean[] shaderdone) { lastblocktypeid = blocktypeid; blocktypeid = mapiter.getBlockTypeID(); if(skiptoair) { /* If skipping until we see air */ if(blocktypeid == 0) /* If air, we're done */ skiptoair = false; } else if(nonairhit || (blocktypeid != 0)) { blockdata = mapiter.getBlockData(); switch(HDBlockModels.getLinkAlgID(blocktypeid)) { case FENCE_ALGORITHM: /* Fence algorithm */ blockrenderdata = generateFenceBlockData(mapiter, blocktypeid); break; case CHEST_ALGORITHM: blockrenderdata = generateChestBlockData(mapiter); break; case REDSTONE_ALGORITHM: blockrenderdata = generateRedstoneWireBlockData(mapiter); break; case GLASS_IRONFENCE_ALG: blockrenderdata = generateIronFenceGlassBlockData(mapiter, blocktypeid); break; case WIRE_ALGORITHM: blockrenderdata = generateWireBlockData(mapiter, HDBlockModels.getLinkIDs(blocktypeid)); break; case 0: default: blockrenderdata = -1; break; } /* Look up to see if block is modelled */ short[] model = scalemodels.getScaledModel(blocktypeid, blockdata, blockrenderdata); if(model != null) { return handleSubModel(model, shaderstate, shaderdone); } else { boolean done = true; subalpha = -1; for(int i = 0; i < shaderstate.length; i++) { if(!shaderdone[i]) shaderdone[i] = shaderstate[i].processBlock(this); done = done && shaderdone[i]; } /* If all are done, we're out */ if(done) return true; nonairhit = true; } } return false; } /** * Trace ray, based on "Voxel Tranversal along a 3D line" */ private void raytrace(MapChunkCache cache, MapIterator mapiter, HDShaderState[] shaderstate, boolean[] shaderdone) { /* Initialize raytrace state variables */ raytrace_init(); /* Skip sections until we hit a non-empty one */ while(cache.isEmptySection(sx, sy, sz)) { /* If Y step is next best */ if((st_next_y <= st_next_x) && (st_next_y <= st_next_z)) { sy += y_inc; t = st_next_y; st_next_y += sdt_dy; laststep = stepy; if(sy < 0) return; } /* If X step is next best */ else if((st_next_x <= st_next_y) && (st_next_x <= st_next_z)) { sx += x_inc; t = st_next_x; st_next_x += sdt_dx; laststep = stepx; } /* Else, Z step is next best */ else { sz += z_inc; t = st_next_z; st_next_z += sdt_dz; laststep = stepz; } } raytrace_section_init(); if(y < 0) return; mapiter.initialize(x, y, z); // System.out.println("xyz=" + x + ',' + y +',' + z + " t=" + t + ", tnext=" + t_next_x + ","+ t_next_y + "," + t_next_z); for (; n > 0; --n) { if(visit_block(mapiter, shaderstate, shaderdone)) { return; } /* If Y step is next best */ if((t_next_y <= t_next_x) && (t_next_y <= t_next_z)) { y += y_inc; t = t_next_y; t_next_y += dt_dy; laststep = stepy; mapiter.stepPosition(laststep); /* If outside 0-(height-1) range */ if((y & (~heightmask)) != 0) return; } /* If X step is next best */ else if((t_next_x <= t_next_y) && (t_next_x <= t_next_z)) { x += x_inc; t = t_next_x; t_next_x += dt_dx; laststep = stepx; mapiter.stepPosition(laststep); } /* Else, Z step is next best */ else { z += z_inc; t = t_next_z; t_next_z += dt_dz; laststep = stepz; mapiter.stepPosition(laststep); } } } private void raytrace_section_init() { t = t - 0.000001; double xx = top.x + t *(bottom.x - top.x); double yy = top.y + t *(bottom.y - top.y); double zz = top.z + t *(bottom.z - top.z); x = fastFloor(xx); y = fastFloor(yy); z = fastFloor(zz); t_next_x = st_next_x; t_next_y = st_next_y; t_next_z = st_next_z; n = 1; if(t_next_x != Double.MAX_VALUE) { if(stepx == BlockStep.X_PLUS) { t_next_x = t + (x + 1 - xx) * dt_dx; n += fastFloor(bottom.x) - x; } else { t_next_x = t + (xx - x) * dt_dx; n += x - fastFloor(bottom.x); } } if(t_next_y != Double.MAX_VALUE) { if(stepy == BlockStep.Y_PLUS) { t_next_y = t + (y + 1 - yy) * dt_dy; n += fastFloor(bottom.y) - y; } else { t_next_y = t + (yy - y) * dt_dy; n += y - fastFloor(bottom.y); } } if(t_next_z != Double.MAX_VALUE) { if(stepz == BlockStep.Z_PLUS) { t_next_z = t + (z + 1 - zz) * dt_dz; n += fastFloor(bottom.z) - z; } else { t_next_z = t + (zz - z) * dt_dz; n += z - fastFloor(bottom.z); } } } private boolean raytraceSubblock(short[] model, boolean firsttime) { if(firsttime) { mt = t + 0.00000001; xx = top.x + mt *(bottom.x - top.x); yy = top.y + mt *(bottom.y - top.y); zz = top.z + mt *(bottom.z - top.z); mx = (int)((xx - fastFloor(xx)) * modscale); my = (int)((yy - fastFloor(yy)) * modscale); mz = (int)((zz - fastFloor(zz)) * modscale); mdt_dx = dt_dx / modscale; mdt_dy = dt_dy / modscale; mdt_dz = dt_dz / modscale; mt_next_x = t_next_x; mt_next_y = t_next_y; mt_next_z = t_next_z; if(mt_next_x != Double.MAX_VALUE) { togo = ((t_next_x - t) / mdt_dx); mt_next_x = mt + (togo - fastFloor(togo)) * mdt_dx; } if(mt_next_y != Double.MAX_VALUE) { togo = ((t_next_y - t) / mdt_dy); mt_next_y = mt + (togo - fastFloor(togo)) * mdt_dy; } if(mt_next_z != Double.MAX_VALUE) { togo = ((t_next_z - t) / mdt_dz); mt_next_z = mt + (togo - fastFloor(togo)) * mdt_dz; } mtend = Math.min(t_next_x, Math.min(t_next_y, t_next_z)); } subalpha = -1; boolean skip = !firsttime; /* Skip first block on continue */ while(mt <= mtend) { if(!skip) { try { int blkalpha = model[modscale*modscale*my + modscale*mz + mx]; if(blkalpha > 0) { subalpha = blkalpha; return false; } } catch (ArrayIndexOutOfBoundsException aioobx) { /* We're outside the model, so miss */ return true; } } else { skip = false; } /* If X step is next best */ if((mt_next_x <= mt_next_y) && (mt_next_x <= mt_next_z)) { mx += x_inc; mt = mt_next_x; mt_next_x += mdt_dx; laststep = stepx; if(mx == mxout) { return true; } } /* If Y step is next best */ else if((mt_next_y <= mt_next_x) && (mt_next_y <= mt_next_z)) { my += y_inc; mt = mt_next_y; mt_next_y += mdt_dy; laststep = stepy; if(my == myout) { return true; } } /* Else, Z step is next best */ else { mz += z_inc; mt = mt_next_z; mt_next_z += mdt_dz; laststep = stepz; if(mz == mzout) { return true; } } } return true; } public final int[] getSubblockCoord() { if(subalpha < 0) { double tt = t + 0.0000001; double xx = top.x + tt * (bottom.x - top.x); double yy = top.y + tt * (bottom.y - top.y); double zz = top.z + tt * (bottom.z - top.z); subblock_xyz[0] = (int)((xx - fastFloor(xx)) * modscale); subblock_xyz[1] = (int)((yy - fastFloor(yy)) * modscale); subblock_xyz[2] = (int)((zz - fastFloor(zz)) * modscale); } else { subblock_xyz[0] = mx; subblock_xyz[1] = my; subblock_xyz[2] = mz; } return subblock_xyz; } } public IsoHDPerspective(DynmapCore core, ConfigurationNode configuration) { name = configuration.getString("name", null); if(name == null) { Log.severe("Perspective definition missing name - must be defined and unique"); return; } azimuth = configuration.getDouble("azimuth", 135.0); /* Get azimuth (default to classic kzed POV */ /* Fix azimuth so that we respect new north, if that is requested (newnorth = oldeast) */ if(MapManager.mapman.getCompassMode() == CompassMode.NEWNORTH) { azimuth = (azimuth + 90.0); if(azimuth >= 360.0) azimuth = azimuth - 360.0; } inclination = configuration.getDouble("inclination", 60.0); if(inclination > MAX_INCLINATION) inclination = MAX_INCLINATION; if(inclination < MIN_INCLINATION) inclination = MIN_INCLINATION; scale = configuration.getDouble("scale", MIN_SCALE); if(scale < MIN_SCALE) scale = MIN_SCALE; if(scale > MAX_SCALE) scale = MAX_SCALE; /* Get max and min height */ maxheight = configuration.getInteger("maximumheight", -1); minheight = configuration.getInteger("minimumheight", 0); if(minheight < 0) minheight = 0; /* Fence-to-block-join setting */ fencejoin = configuration.getBoolean("fence-to-block-join", MapManager.mapman.getFenceJoin()); /* Generate transform matrix for world-to-tile coordinate mapping */ /* First, need to fix basic coordinate mismatches before rotation - we want zero azimuth to have north to top * (world -X -> tile +Y) and east to right (world -Z to tile +X), with height being up (world +Y -> tile +Z) */ Matrix3D transform = new Matrix3D(0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0); /* Next, rotate world counterclockwise around Z axis by azumuth angle */ transform.rotateXY(180-azimuth); /* Next, rotate world by (90-inclination) degrees clockwise around +X axis */ transform.rotateYZ(90.0-inclination); /* Finally, shear along Z axis to normalize Z to be height above map plane */ transform.shearZ(0, Math.tan(Math.toRadians(90.0-inclination))); /* And scale Z to be same scale as world coordinates, and scale X and Y based on setting */ transform.scale(scale, scale, Math.sin(Math.toRadians(inclination))); world_to_map = transform; /* Now, generate map to world tranform, by doing opposite actions in reverse order */ transform = new Matrix3D(); transform.scale(1.0/scale, 1.0/scale, 1/Math.sin(Math.toRadians(inclination))); transform.shearZ(0, -Math.tan(Math.toRadians(90.0-inclination))); transform.rotateYZ(-(90.0-inclination)); transform.rotateXY(-180+azimuth); Matrix3D coordswap = new Matrix3D(0.0, -1.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0); transform.multiply(coordswap); map_to_world = transform; /* Scaled models for non-cube blocks */ modscale = (int)Math.ceil(scale); scalemodels = HDBlockModels.getModelsForScale(modscale);; } @Override public MapTile[] getTiles(DynmapWorld world, int x, int y, int z) { HashSet<MapTile> tiles = new HashSet<MapTile>(); Vector3D block = new Vector3D(); block.x = x; block.y = y; block.z = z; Vector3D corner = new Vector3D(); /* Loop through corners of the cube */ for(int i = 0; i < 2; i++) { double inity = block.y; for(int j = 0; j < 2; j++) { double initz = block.z; for(int k = 0; k < 2; k++) { world_to_map.transform(block, corner); /* Get map coordinate of corner */ addTile(tiles, world, fastFloor(corner.x/tileWidth), fastFloor(corner.y/tileHeight)); block.z += 1; } block.z = initz; block.y += 1; } block.y = inity; block.x += 1; } return tiles.toArray(new MapTile[tiles.size()]); } @Override public MapTile[] getTiles(DynmapWorld world, int minx, int miny, int minz, int maxx, int maxy, int maxz) { HashSet<MapTile> tiles = new HashSet<MapTile>(); Vector3D blocks[] = new Vector3D[] { new Vector3D(), new Vector3D() }; blocks[0].x = minx - 1; blocks[0].y = miny - 1; blocks[0].z = minz - 1; blocks[1].x = maxx + 1; blocks[1].y = maxy + 1; blocks[1].z = maxz + 1; Vector3D corner = new Vector3D(); Vector3D tcorner = new Vector3D(); int mintilex = Integer.MAX_VALUE; int maxtilex = Integer.MIN_VALUE; int mintiley = Integer.MAX_VALUE; int maxtiley = Integer.MIN_VALUE; /* Loop through corners of the prism */ for(int i = 0; i < 2; i++) { corner.x = blocks[i].x; for(int j = 0; j < 2; j++) { corner.y = blocks[j].y; for(int k = 0; k < 2; k++) { corner.z = blocks[k].z; world_to_map.transform(corner, tcorner); /* Get map coordinate of corner */ int tx = fastFloor(tcorner.x/tileWidth); int ty = fastFloor(tcorner.y/tileWidth); if(mintilex > tx) mintilex = tx; if(maxtilex < tx) maxtilex = tx; if(mintiley > ty) mintiley = ty; if(maxtiley < ty) maxtiley = ty; } } } /* Now, add the tiles for the ranges - not perfect, but it works (some extra tiles on corners possible) */ for(int i = mintilex; i <= maxtilex; i++) { for(int j = mintiley-1; j <= maxtiley; j++) { /* Extra 1 - TODO: figure out why needed... */ addTile(tiles, world, i, j); } } return tiles.toArray(new MapTile[tiles.size()]); } @Override public MapTile[] getAdjecentTiles(MapTile tile) { HDMapTile t = (HDMapTile) tile; DynmapWorld w = t.getDynmapWorld(); int x = t.tx; int y = t.ty; return new MapTile[] { new HDMapTile(w, this, x - 1, y - 1), new HDMapTile(w, this, x + 1, y - 1), new HDMapTile(w, this, x - 1, y + 1), new HDMapTile(w, this, x + 1, y + 1), new HDMapTile(w, this, x, y - 1), new HDMapTile(w, this, x + 1, y), new HDMapTile(w, this, x, y + 1), new HDMapTile(w, this, x - 1, y) }; } public void addTile(HashSet<MapTile> tiles, DynmapWorld world, int tx, int ty) { tiles.add(new HDMapTile(world, this, tx, ty)); } private static class Rectangle { double r0x, r0z; /* Coord of corner of rectangle */ double s1x, s1z; /* Side vector for one edge */ double s2x, s2z; /* Side vector for other edge */ public Rectangle(Vector3D v1, Vector3D v2, Vector3D v3) { r0x = v1.x; r0z = v1.z; s1x = v2.x - v1.x; s1z = v2.z - v1.z; s2x = v3.x - v1.x; s2z = v3.z - v1.z; } public Rectangle() { } public void setSquare(double rx, double rz, double s) { this.r0x = rx; this.r0z = rz; this.s1x = s; this.s1z = 0; this.s2x = 0; this.s2z = s; } double getX(int idx) { return r0x + (((idx & 1) == 0)?0:s1x) + (((idx & 2) != 0)?0:s2x); } double getZ(int idx) { return r0z + (((idx & 1) == 0)?0:s1z) + (((idx & 2) != 0)?0:s2z); } /** * Test for overlap of projection of one vector on to anoter */ boolean testoverlap(double rx, double rz, double sx, double sz, Rectangle r) { double rmin_dot_s0 = Double.MAX_VALUE; double rmax_dot_s0 = Double.MIN_VALUE; /* Project each point from rectangle on to vector: find lowest and highest */ for(int i = 0; i < 4; i++) { double r_x = r.getX(i) - rx; /* Get relative positon of second vector start to origin */ double r_z = r.getZ(i) - rz; double r_dot_s0 = r_x*sx + r_z*sz; /* Projection of start of vector */ if(r_dot_s0 < rmin_dot_s0) rmin_dot_s0 = r_dot_s0; if(r_dot_s0 > rmax_dot_s0) rmax_dot_s0 = r_dot_s0; } /* Compute dot products */ double s0_dot_s0 = sx*sx + sz*sz; /* End of our side */ if((rmax_dot_s0 < 0.0) || (rmin_dot_s0 > s0_dot_s0)) return false; else return true; } /** * Test if two rectangles intersect * Based on separating axis theorem */ boolean testRectangleIntesectsRectangle(Rectangle r) { /* Test if projection of each edge of one rectangle on to each edge of the other yields overlap */ if(testoverlap(r0x, r0z, s1x, s1z, r) && testoverlap(r0x, r0z, s2x, s2z, r) && testoverlap(r0x+s1x, r0z+s1z, s2x, s2z, r) && testoverlap(r0x+s2x, r0z+s2z, s1x, s1z, r) && r.testoverlap(r.r0x, r.r0z, r.s1x, r.s1z, this) && r.testoverlap(r.r0x, r.r0z, r.s2x, r.s2z, this) && r.testoverlap(r.r0x+r.s1x, r.r0z+r.s1z, r.s2x, r.s2z, this) && r.testoverlap(r.r0x+r.s2x, r.r0z+r.s2z, r.s1x, r.s1z, this)) { return true; } else { return false; } } public String toString() { return "{ " + r0x + "," + r0z + "}x{" + (r0x+s1x) + ","+ + (r0z+s1z) + "}x{" + (r0x+s2x) + "," + (r0z+s2z) + "}"; } } @Override public List<DynmapChunk> getRequiredChunks(MapTile tile) { if (!(tile instanceof HDMapTile)) return Collections.emptyList(); HDMapTile t = (HDMapTile) tile; int min_chunk_x = Integer.MAX_VALUE; int max_chunk_x = Integer.MIN_VALUE; int min_chunk_z = Integer.MAX_VALUE; int max_chunk_z = Integer.MIN_VALUE; /* Make corners for volume: 0 = bottom-lower-left, 1 = top-lower-left, 2=bottom-upper-left, 3=top-upper-left * 4 = bottom-lower-right, 5 = top-lower-right, 6 = bottom-upper-right, 7 = top-upper-right */ Vector3D corners[] = new Vector3D[8]; double dx = -scale, dy = -scale; /* Add 1 block on each axis */ for(int x = t.tx, idx = 0; x <= (t.tx+1); x++) { dy = -scale; for(int y = t.ty; y <= (t.ty+1); y++) { for(int z = 0; z <= 1; z++) { corners[idx] = new Vector3D(); corners[idx].x = x*tileWidth + dx; corners[idx].y = y*tileHeight + dy; corners[idx].z = z*t.getDynmapWorld().worldheight; map_to_world.transform(corners[idx]); /* Compute chunk coordinates of corner */ int cx = fastFloor(corners[idx].x / 16); int cz = fastFloor(corners[idx].z / 16); /* Compute min/max of chunk coordinates */ if(min_chunk_x > cx) min_chunk_x = cx; if(max_chunk_x < cx) max_chunk_x = cx; if(min_chunk_z > cz) min_chunk_z = cz; if(max_chunk_z < cz) max_chunk_z = cz; idx++; } dy = scale; } dx = scale; } /* Make rectangles of X-Z projection of each side of the tile volume, 0 = top, 1 = bottom, 2 = left, 3 = right, * 4 = upper, 5 = lower */ Rectangle rect[] = new Rectangle[6]; rect[0] = new Rectangle(corners[1], corners[3], corners[5]); rect[1] = new Rectangle(corners[0], corners[2], corners[4]); rect[2] = new Rectangle(corners[0], corners[1], corners[2]); rect[3] = new Rectangle(corners[4], corners[5], corners[6]); rect[4] = new Rectangle(corners[2], corners[3], corners[6]); rect[5] = new Rectangle(corners[0], corners[1], corners[4]); /* Now, need to walk through the min/max range to see which chunks are actually needed */ ArrayList<DynmapChunk> chunks = new ArrayList<DynmapChunk>(); Rectangle chunkrect = new Rectangle(); int misscnt = 0; for(int x = min_chunk_x; x <= max_chunk_x; x++) { for(int z = min_chunk_z; z <= max_chunk_z; z++) { chunkrect.setSquare(x*16, z*16, 16); boolean hit = false; /* Check to see if square of chunk intersects any of our rectangle sides */ for(int rctidx = 0; (!hit) && (rctidx < rect.length); rctidx++) { if(chunkrect.testRectangleIntesectsRectangle(rect[rctidx])) { hit = true; } } if(hit) { DynmapChunk chunk = new DynmapChunk(x, z); chunks.add(chunk); } else { misscnt++; } } } return chunks; } @Override public boolean render(MapChunkCache cache, HDMapTile tile, String mapname) { Color rslt = new Color(); MapIterator mapiter = cache.getIterator(0, 0, 0); /* Build shader state object for each shader */ HDShaderState[] shaderstate = MapManager.mapman.hdmapman.getShaderStateForTile(tile, cache, mapiter, mapname); int numshaders = shaderstate.length; if(numshaders == 0) return false; /* Check if nether world */ boolean isnether = tile.getDynmapWorld().isNether(); /* Create buffered image for each */ DynmapBufferedImage im[] = new DynmapBufferedImage[numshaders]; DynmapBufferedImage dayim[] = new DynmapBufferedImage[numshaders]; int[][] argb_buf = new int[numshaders][]; int[][] day_argb_buf = new int[numshaders][]; boolean isjpg[] = new boolean[numshaders]; int bgday[] = new int[numshaders]; int bgnight[] = new int[numshaders]; for(int i = 0; i < numshaders; i++) { HDLighting lighting = shaderstate[i].getLighting(); im[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); argb_buf[i] = im[i].argb_buf; if(lighting.isNightAndDayEnabled()) { dayim[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); day_argb_buf[i] = dayim[i].argb_buf; } isjpg[i] = shaderstate[i].getMap().getImageFormat() != ImageFormat.FORMAT_PNG; bgday[i] = shaderstate[i].getMap().getBackgroundARGBDay(); bgnight[i] = shaderstate[i].getMap().getBackgroundARGBNight(); } /* Create perspective state object */ OurPerspectiveState ps = new OurPerspectiveState(mapiter, isnether); ps.top = new Vector3D(); ps.bottom = new Vector3D(); double xbase = tile.tx * tileWidth; double ybase = tile.ty * tileHeight; boolean shaderdone[] = new boolean[numshaders]; boolean rendered[] = new boolean[numshaders]; double height = maxheight; if(height < 0) { /* Not set - assume world height - 1 */ height = tile.getDynmapWorld().worldheight - 1; } + if(isnether && (height > 128)) { + height = 127; + } for(int x = 0; x < tileWidth; x++) { ps.px = x; for(int y = 0; y < tileHeight; y++) { ps.top.x = ps.bottom.x = xbase + x + 0.5; /* Start at center of pixel at Y=height+0.5, bottom at Y=-0.5 */ ps.top.y = ps.bottom.y = ybase + y + 0.5; ps.top.z = height + 0.5; ps.bottom.z = minheight - 0.5; map_to_world.transform(ps.top); /* Transform to world coordinates */ map_to_world.transform(ps.bottom); ps.py = y; for(int i = 0; i < numshaders; i++) { shaderstate[i].reset(ps); } ps.raytrace(cache, mapiter, shaderstate, shaderdone); for(int i = 0; i < numshaders; i++) { if(shaderdone[i] == false) { shaderstate[i].rayFinished(ps); } else { shaderdone[i] = false; rendered[i] = true; } shaderstate[i].getRayColor(rslt, 0); int c_argb = rslt.getARGB(); if(c_argb != 0) rendered[i] = true; if(isjpg[i] && (c_argb == 0)) { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgnight[i]; } else { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } if(day_argb_buf[i] != null) { shaderstate[i].getRayColor(rslt, 1); c_argb = rslt.getARGB(); if(isjpg[i] && (c_argb == 0)) { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgday[i]; } else { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } } } } } boolean renderone = false; /* Test to see if we're unchanged from older tile */ TileHashManager hashman = MapManager.mapman.hashman; for(int i = 0; i < numshaders; i++) { long crc = hashman.calculateTileHash(argb_buf[i]); boolean tile_update = false; String prefix = shaderstate[i].getMap().getPrefix(); MapType.ImageFormat fmt = shaderstate[i].getMap().getImageFormat(); String fname = tile.getFilename(prefix, fmt); File f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), null, tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(im[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), null, tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(im[i]); } MapManager.mapman.updateStatistics(tile, prefix, true, tile_update, !rendered[i]); /* Handle day image, if needed */ if(dayim[i] != null) { fname = tile.getDayFilename(prefix, fmt); f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); tile_update = false; try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(dayim[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(dayim[i]); } MapManager.mapman.updateStatistics(tile, prefix+"_day", true, tile_update, !rendered[i]); } } return renderone; } @Override public boolean isBiomeDataNeeded() { return need_biomedata; } @Override public boolean isRawBiomeDataNeeded() { return need_rawbiomedata; } public boolean isHightestBlockYDataNeeded() { return false; } public boolean isBlockTypeDataNeeded() { return true; } public double getScale() { return scale; } public int getModelScale() { return modscale; } @Override public String getName() { return name; } private static String[] directions = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; @Override public void addClientConfiguration(JSONObject mapObject) { s(mapObject, "perspective", name); s(mapObject, "azimuth", azimuth); s(mapObject, "inclination", inclination); s(mapObject, "scale", scale); s(mapObject, "worldtomap", world_to_map.toJSON()); s(mapObject, "maptoworld", map_to_world.toJSON()); int dir = ((360 + (int)(22.5+azimuth)) / 45) % 8; if(MapManager.mapman.getCompassMode() != CompassMode.PRE19) dir = (dir + 6) % 8; s(mapObject, "compassview", directions[dir]); } private static final int fastFloor(double f) { return ((int)(f + 1000000000.0)) - 1000000000; } }
true
true
public boolean render(MapChunkCache cache, HDMapTile tile, String mapname) { Color rslt = new Color(); MapIterator mapiter = cache.getIterator(0, 0, 0); /* Build shader state object for each shader */ HDShaderState[] shaderstate = MapManager.mapman.hdmapman.getShaderStateForTile(tile, cache, mapiter, mapname); int numshaders = shaderstate.length; if(numshaders == 0) return false; /* Check if nether world */ boolean isnether = tile.getDynmapWorld().isNether(); /* Create buffered image for each */ DynmapBufferedImage im[] = new DynmapBufferedImage[numshaders]; DynmapBufferedImage dayim[] = new DynmapBufferedImage[numshaders]; int[][] argb_buf = new int[numshaders][]; int[][] day_argb_buf = new int[numshaders][]; boolean isjpg[] = new boolean[numshaders]; int bgday[] = new int[numshaders]; int bgnight[] = new int[numshaders]; for(int i = 0; i < numshaders; i++) { HDLighting lighting = shaderstate[i].getLighting(); im[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); argb_buf[i] = im[i].argb_buf; if(lighting.isNightAndDayEnabled()) { dayim[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); day_argb_buf[i] = dayim[i].argb_buf; } isjpg[i] = shaderstate[i].getMap().getImageFormat() != ImageFormat.FORMAT_PNG; bgday[i] = shaderstate[i].getMap().getBackgroundARGBDay(); bgnight[i] = shaderstate[i].getMap().getBackgroundARGBNight(); } /* Create perspective state object */ OurPerspectiveState ps = new OurPerspectiveState(mapiter, isnether); ps.top = new Vector3D(); ps.bottom = new Vector3D(); double xbase = tile.tx * tileWidth; double ybase = tile.ty * tileHeight; boolean shaderdone[] = new boolean[numshaders]; boolean rendered[] = new boolean[numshaders]; double height = maxheight; if(height < 0) { /* Not set - assume world height - 1 */ height = tile.getDynmapWorld().worldheight - 1; } for(int x = 0; x < tileWidth; x++) { ps.px = x; for(int y = 0; y < tileHeight; y++) { ps.top.x = ps.bottom.x = xbase + x + 0.5; /* Start at center of pixel at Y=height+0.5, bottom at Y=-0.5 */ ps.top.y = ps.bottom.y = ybase + y + 0.5; ps.top.z = height + 0.5; ps.bottom.z = minheight - 0.5; map_to_world.transform(ps.top); /* Transform to world coordinates */ map_to_world.transform(ps.bottom); ps.py = y; for(int i = 0; i < numshaders; i++) { shaderstate[i].reset(ps); } ps.raytrace(cache, mapiter, shaderstate, shaderdone); for(int i = 0; i < numshaders; i++) { if(shaderdone[i] == false) { shaderstate[i].rayFinished(ps); } else { shaderdone[i] = false; rendered[i] = true; } shaderstate[i].getRayColor(rslt, 0); int c_argb = rslt.getARGB(); if(c_argb != 0) rendered[i] = true; if(isjpg[i] && (c_argb == 0)) { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgnight[i]; } else { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } if(day_argb_buf[i] != null) { shaderstate[i].getRayColor(rslt, 1); c_argb = rslt.getARGB(); if(isjpg[i] && (c_argb == 0)) { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgday[i]; } else { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } } } } } boolean renderone = false; /* Test to see if we're unchanged from older tile */ TileHashManager hashman = MapManager.mapman.hashman; for(int i = 0; i < numshaders; i++) { long crc = hashman.calculateTileHash(argb_buf[i]); boolean tile_update = false; String prefix = shaderstate[i].getMap().getPrefix(); MapType.ImageFormat fmt = shaderstate[i].getMap().getImageFormat(); String fname = tile.getFilename(prefix, fmt); File f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), null, tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(im[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), null, tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(im[i]); } MapManager.mapman.updateStatistics(tile, prefix, true, tile_update, !rendered[i]); /* Handle day image, if needed */ if(dayim[i] != null) { fname = tile.getDayFilename(prefix, fmt); f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); tile_update = false; try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(dayim[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(dayim[i]); } MapManager.mapman.updateStatistics(tile, prefix+"_day", true, tile_update, !rendered[i]); } } return renderone; }
public boolean render(MapChunkCache cache, HDMapTile tile, String mapname) { Color rslt = new Color(); MapIterator mapiter = cache.getIterator(0, 0, 0); /* Build shader state object for each shader */ HDShaderState[] shaderstate = MapManager.mapman.hdmapman.getShaderStateForTile(tile, cache, mapiter, mapname); int numshaders = shaderstate.length; if(numshaders == 0) return false; /* Check if nether world */ boolean isnether = tile.getDynmapWorld().isNether(); /* Create buffered image for each */ DynmapBufferedImage im[] = new DynmapBufferedImage[numshaders]; DynmapBufferedImage dayim[] = new DynmapBufferedImage[numshaders]; int[][] argb_buf = new int[numshaders][]; int[][] day_argb_buf = new int[numshaders][]; boolean isjpg[] = new boolean[numshaders]; int bgday[] = new int[numshaders]; int bgnight[] = new int[numshaders]; for(int i = 0; i < numshaders; i++) { HDLighting lighting = shaderstate[i].getLighting(); im[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); argb_buf[i] = im[i].argb_buf; if(lighting.isNightAndDayEnabled()) { dayim[i] = DynmapBufferedImage.allocateBufferedImage(tileWidth, tileHeight); day_argb_buf[i] = dayim[i].argb_buf; } isjpg[i] = shaderstate[i].getMap().getImageFormat() != ImageFormat.FORMAT_PNG; bgday[i] = shaderstate[i].getMap().getBackgroundARGBDay(); bgnight[i] = shaderstate[i].getMap().getBackgroundARGBNight(); } /* Create perspective state object */ OurPerspectiveState ps = new OurPerspectiveState(mapiter, isnether); ps.top = new Vector3D(); ps.bottom = new Vector3D(); double xbase = tile.tx * tileWidth; double ybase = tile.ty * tileHeight; boolean shaderdone[] = new boolean[numshaders]; boolean rendered[] = new boolean[numshaders]; double height = maxheight; if(height < 0) { /* Not set - assume world height - 1 */ height = tile.getDynmapWorld().worldheight - 1; } if(isnether && (height > 128)) { height = 127; } for(int x = 0; x < tileWidth; x++) { ps.px = x; for(int y = 0; y < tileHeight; y++) { ps.top.x = ps.bottom.x = xbase + x + 0.5; /* Start at center of pixel at Y=height+0.5, bottom at Y=-0.5 */ ps.top.y = ps.bottom.y = ybase + y + 0.5; ps.top.z = height + 0.5; ps.bottom.z = minheight - 0.5; map_to_world.transform(ps.top); /* Transform to world coordinates */ map_to_world.transform(ps.bottom); ps.py = y; for(int i = 0; i < numshaders; i++) { shaderstate[i].reset(ps); } ps.raytrace(cache, mapiter, shaderstate, shaderdone); for(int i = 0; i < numshaders; i++) { if(shaderdone[i] == false) { shaderstate[i].rayFinished(ps); } else { shaderdone[i] = false; rendered[i] = true; } shaderstate[i].getRayColor(rslt, 0); int c_argb = rslt.getARGB(); if(c_argb != 0) rendered[i] = true; if(isjpg[i] && (c_argb == 0)) { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgnight[i]; } else { argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } if(day_argb_buf[i] != null) { shaderstate[i].getRayColor(rslt, 1); c_argb = rslt.getARGB(); if(isjpg[i] && (c_argb == 0)) { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = bgday[i]; } else { day_argb_buf[i][(tileHeight-y-1)*tileWidth + x] = c_argb; } } } } } boolean renderone = false; /* Test to see if we're unchanged from older tile */ TileHashManager hashman = MapManager.mapman.hashman; for(int i = 0; i < numshaders; i++) { long crc = hashman.calculateTileHash(argb_buf[i]); boolean tile_update = false; String prefix = shaderstate[i].getMap().getPrefix(); MapType.ImageFormat fmt = shaderstate[i].getMap().getImageFormat(); String fname = tile.getFilename(prefix, fmt); File f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), null, tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(im[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), null, tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(im[i]); } MapManager.mapman.updateStatistics(tile, prefix, true, tile_update, !rendered[i]); /* Handle day image, if needed */ if(dayim[i] != null) { fname = tile.getDayFilename(prefix, fmt); f = new File(tile.getDynmapWorld().worldtilepath, fname); FileLockManager.getWriteLock(f); tile_update = false; try { if((!f.exists()) || (crc != hashman.getImageHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty))) { /* Wrap buffer as buffered image */ Debug.debug("saving image " + f.getPath()); if(!f.getParentFile().exists()) f.getParentFile().mkdirs(); try { FileLockManager.imageIOWrite(dayim[i].buf_img, fmt, f); } catch (IOException e) { Debug.error("Failed to save image: " + f.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + f.getPath(), e); } MapManager.mapman.pushUpdate(tile.getDynmapWorld(), new Client.Tile(fname)); hashman.updateHashCode(tile.getKey(prefix), "day", tile.tx, tile.ty, crc); tile.getDynmapWorld().enqueueZoomOutUpdate(f); tile_update = true; renderone = true; } else { Debug.debug("skipping image " + f.getPath() + " - hash match"); } } finally { FileLockManager.releaseWriteLock(f); DynmapBufferedImage.freeBufferedImage(dayim[i]); } MapManager.mapman.updateStatistics(tile, prefix+"_day", true, tile_update, !rendered[i]); } } return renderone; }
diff --git a/src/com/matejdro/bukkit/portalstick/listeners/PortalStickEntityListener.java b/src/com/matejdro/bukkit/portalstick/listeners/PortalStickEntityListener.java index 50536be..3385bf8 100644 --- a/src/com/matejdro/bukkit/portalstick/listeners/PortalStickEntityListener.java +++ b/src/com/matejdro/bukkit/portalstick/listeners/PortalStickEntityListener.java @@ -1,192 +1,194 @@ package com.matejdro.bukkit.portalstick.listeners; import java.util.ArrayList; import java.util.Iterator; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import com.bergerkiller.bukkit.common.events.EntityAddEvent; import com.bergerkiller.bukkit.common.events.EntityRemoveEvent; import com.matejdro.bukkit.portalstick.Grill; import com.matejdro.bukkit.portalstick.Portal; import com.matejdro.bukkit.portalstick.PortalStick; import com.matejdro.bukkit.portalstick.Region; import com.matejdro.bukkit.portalstick.User; import com.matejdro.bukkit.portalstick.util.RegionSetting; import de.V10lator.PortalStick.BlockHolder; import de.V10lator.PortalStick.V10Location; public class PortalStickEntityListener implements Listener { private final PortalStick plugin; public PortalStickEntityListener(PortalStick plugin) { this.plugin = plugin; } @EventHandler(ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { if(plugin.config.DisabledWorlds.contains(event.getEntity().getLocation().getWorld().getName())) return; if (event.getEntity() instanceof Player) { Player player = (Player)event.getEntity(); if (!plugin.hasPermission(player, plugin.PERM_DAMAGE_BOOTS)) return; Region region = plugin.regionManager.getRegion(new V10Location(player.getLocation())); ItemStack is = player.getInventory().getBoots(); if (event.getCause() == DamageCause.FALL && region.getBoolean(RegionSetting.ENABLE_FALL_DAMAGE_BOOTS)) { boolean ok; if(is == null) ok = false; else ok = region.getInt(RegionSetting.FALL_DAMAGE_BOOTS) == is.getTypeId(); if(ok) event.setCancelled(true); } } } @EventHandler(ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent event) { if(plugin.config.DisabledWorlds.contains(event.getLocation().getWorld().getName())) return; Region region = plugin.regionManager.getRegion(new V10Location(event.getLocation())); Iterator<Block> iter = event.blockList().iterator(); Block block; V10Location loc; Portal portal; while(iter.hasNext()) { block = iter.next(); loc = new V10Location(block.getLocation()); if (block.getType() == Material.WOOL) { portal = plugin.portalManager.borderBlocks.get(loc); if (portal == null) portal = plugin.portalManager.insideBlocks.get(loc); if (portal == null) portal = plugin.portalManager.behindBlocks.get(loc); if (portal != null) { if (region.getBoolean(RegionSetting.PROTECT_PORTALS_FROM_TNT)) iter.remove(); else { portal.delete(); return; } } } else if (plugin.blockUtil.compareBlockToString(block, region.getString(RegionSetting.GRILL_MATERIAL))) { Grill grill = plugin.grillManager.insideBlocks.get(loc); if (grill == null) grill = plugin.grillManager.borderBlocks.get(loc); if (grill != null ) { event.setCancelled(true); return; } } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void spawn(EntityAddEvent event) { Entity entity = event.getEntity(); if(plugin.config.DisabledWorlds.contains(entity.getLocation().getWorld().getName())) return; // System.out.print("Spawned: "+entity.getType()); plugin.userManager.createUser(entity); User user = plugin.userManager.getUser(entity); Region region = plugin.regionManager.getRegion(new V10Location(entity.getLocation())); if(entity instanceof InventoryHolder && !region.name.equals("global") && region.getBoolean(RegionSetting.UNIQUE_INVENTORY)) user.saveInventory((InventoryHolder)entity); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void despawn(EntityRemoveEvent event) { Entity entity = event.getEntity(); if(plugin.config.DisabledWorlds.contains(entity.getLocation().getWorld().getName())) return; if(plugin.gelManager.flyingGels.containsKey(entity.getUniqueId())) { V10Location from = plugin.gelManager.flyingGels.get(entity.getUniqueId()); Location loc = entity.getLocation(); V10Location vloc = new V10Location(loc); Block b = loc.getBlock(); if(!plugin.grillManager.insideBlocks.containsKey(vloc)) b.setType(Material.AIR); FallingBlock fb = (FallingBlock)entity; Block b2; int mat = fb.getBlockId(); byte data = fb.getBlockData(); ArrayList<BlockHolder> blocks; if(plugin.gelManager.gels.containsKey(from)) blocks = plugin.gelManager.gels.get(from); else { blocks = new ArrayList<BlockHolder>(); plugin.gelManager.gels.put(from, blocks); } BlockHolder bh; for(BlockFace face: new BlockFace[] {BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP}) { b2 = b.getRelative(face); if(b2.getType() != Material.AIR && !b2.isLiquid()) { vloc = new V10Location(b2); if(plugin.portalManager.borderBlocks.containsKey(vloc) || plugin.portalManager.insideBlocks.containsKey(vloc) || plugin.portalManager.behindBlocks.containsKey(vloc) || plugin.grillManager.borderBlocks.containsKey(vloc) || plugin.grillManager.insideBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeMachineBlocks.containsKey(vloc)) continue; bh = new BlockHolder(b2); if(!blocks.contains(bh)) { if(plugin.gelManager.gelMap.containsKey(bh)) bh = plugin.gelManager.gelMap.get(bh); else plugin.gelManager.gelMap.put(bh, bh); blocks.add(bh); b2.setTypeIdAndData(mat, data, true); } } } } User user = plugin.userManager.getUser(entity); + if(user == null) //TODO: This shouldn't happen. Bug in BKCommonLib. + return; // System.out.print("Despawned: "+entity.getType()); Region region = plugin.regionManager.getRegion(new V10Location(entity.getLocation())); if(entity instanceof InventoryHolder && region.name != "global" && region.getBoolean(RegionSetting.UNIQUE_INVENTORY)) user.revertInventory((InventoryHolder)entity); plugin.userManager.deleteUser(user); if(entity instanceof Player) //TODO plugin.gelManager.resetPlayer((Player)entity); } }
true
true
public void despawn(EntityRemoveEvent event) { Entity entity = event.getEntity(); if(plugin.config.DisabledWorlds.contains(entity.getLocation().getWorld().getName())) return; if(plugin.gelManager.flyingGels.containsKey(entity.getUniqueId())) { V10Location from = plugin.gelManager.flyingGels.get(entity.getUniqueId()); Location loc = entity.getLocation(); V10Location vloc = new V10Location(loc); Block b = loc.getBlock(); if(!plugin.grillManager.insideBlocks.containsKey(vloc)) b.setType(Material.AIR); FallingBlock fb = (FallingBlock)entity; Block b2; int mat = fb.getBlockId(); byte data = fb.getBlockData(); ArrayList<BlockHolder> blocks; if(plugin.gelManager.gels.containsKey(from)) blocks = plugin.gelManager.gels.get(from); else { blocks = new ArrayList<BlockHolder>(); plugin.gelManager.gels.put(from, blocks); } BlockHolder bh; for(BlockFace face: new BlockFace[] {BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP}) { b2 = b.getRelative(face); if(b2.getType() != Material.AIR && !b2.isLiquid()) { vloc = new V10Location(b2); if(plugin.portalManager.borderBlocks.containsKey(vloc) || plugin.portalManager.insideBlocks.containsKey(vloc) || plugin.portalManager.behindBlocks.containsKey(vloc) || plugin.grillManager.borderBlocks.containsKey(vloc) || plugin.grillManager.insideBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeMachineBlocks.containsKey(vloc)) continue; bh = new BlockHolder(b2); if(!blocks.contains(bh)) { if(plugin.gelManager.gelMap.containsKey(bh)) bh = plugin.gelManager.gelMap.get(bh); else plugin.gelManager.gelMap.put(bh, bh); blocks.add(bh); b2.setTypeIdAndData(mat, data, true); } } } } User user = plugin.userManager.getUser(entity); // System.out.print("Despawned: "+entity.getType()); Region region = plugin.regionManager.getRegion(new V10Location(entity.getLocation())); if(entity instanceof InventoryHolder && region.name != "global" && region.getBoolean(RegionSetting.UNIQUE_INVENTORY)) user.revertInventory((InventoryHolder)entity); plugin.userManager.deleteUser(user); if(entity instanceof Player) //TODO plugin.gelManager.resetPlayer((Player)entity); }
public void despawn(EntityRemoveEvent event) { Entity entity = event.getEntity(); if(plugin.config.DisabledWorlds.contains(entity.getLocation().getWorld().getName())) return; if(plugin.gelManager.flyingGels.containsKey(entity.getUniqueId())) { V10Location from = plugin.gelManager.flyingGels.get(entity.getUniqueId()); Location loc = entity.getLocation(); V10Location vloc = new V10Location(loc); Block b = loc.getBlock(); if(!plugin.grillManager.insideBlocks.containsKey(vloc)) b.setType(Material.AIR); FallingBlock fb = (FallingBlock)entity; Block b2; int mat = fb.getBlockId(); byte data = fb.getBlockData(); ArrayList<BlockHolder> blocks; if(plugin.gelManager.gels.containsKey(from)) blocks = plugin.gelManager.gels.get(from); else { blocks = new ArrayList<BlockHolder>(); plugin.gelManager.gels.put(from, blocks); } BlockHolder bh; for(BlockFace face: new BlockFace[] {BlockFace.DOWN, BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP}) { b2 = b.getRelative(face); if(b2.getType() != Material.AIR && !b2.isLiquid()) { vloc = new V10Location(b2); if(plugin.portalManager.borderBlocks.containsKey(vloc) || plugin.portalManager.insideBlocks.containsKey(vloc) || plugin.portalManager.behindBlocks.containsKey(vloc) || plugin.grillManager.borderBlocks.containsKey(vloc) || plugin.grillManager.insideBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeBlocks.containsKey(vloc) || plugin.funnelBridgeManager.bridgeMachineBlocks.containsKey(vloc)) continue; bh = new BlockHolder(b2); if(!blocks.contains(bh)) { if(plugin.gelManager.gelMap.containsKey(bh)) bh = plugin.gelManager.gelMap.get(bh); else plugin.gelManager.gelMap.put(bh, bh); blocks.add(bh); b2.setTypeIdAndData(mat, data, true); } } } } User user = plugin.userManager.getUser(entity); if(user == null) //TODO: This shouldn't happen. Bug in BKCommonLib. return; // System.out.print("Despawned: "+entity.getType()); Region region = plugin.regionManager.getRegion(new V10Location(entity.getLocation())); if(entity instanceof InventoryHolder && region.name != "global" && region.getBoolean(RegionSetting.UNIQUE_INVENTORY)) user.revertInventory((InventoryHolder)entity); plugin.userManager.deleteUser(user); if(entity instanceof Player) //TODO plugin.gelManager.resetPlayer((Player)entity); }
diff --git a/src/main/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizer.java b/src/main/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizer.java index 38ba5dbaf..6e20b130c 100644 --- a/src/main/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizer.java +++ b/src/main/java/org/apache/commons/math/optimization/general/NonLinearConjugateGradientOptimizer.java @@ -1,310 +1,310 @@ /* * 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.commons.math.optimization.general; import org.apache.commons.math.exception.MathIllegalStateException; import org.apache.commons.math.analysis.UnivariateRealFunction; import org.apache.commons.math.analysis.solvers.BrentSolver; import org.apache.commons.math.analysis.solvers.UnivariateRealSolver; import org.apache.commons.math.exception.util.LocalizedFormats; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; import org.apache.commons.math.optimization.SimpleScalarValueChecker; import org.apache.commons.math.optimization.ConvergenceChecker; import org.apache.commons.math.util.FastMath; /** * Non-linear conjugate gradient optimizer. * <p> * This class supports both the Fletcher-Reeves and the Polak-Ribi&egrave;re * update formulas for the conjugate search directions. It also supports * optional preconditioning. * </p> * * @version $Id$ * @since 2.0 * */ public class NonLinearConjugateGradientOptimizer extends AbstractScalarDifferentiableOptimizer { /** Update formula for the beta parameter. */ private final ConjugateGradientFormula updateFormula; /** Preconditioner (may be null). */ private final Preconditioner preconditioner; /** solver to use in the line search (may be null). */ private final UnivariateRealSolver solver; /** Initial step used to bracket the optimum in line search. */ private double initialStep; /** Current point. */ private double[] point; /** * Constructor with default {@link SimpleScalarValueChecker checker}, * {@link BrentSolver line search solver} and * {@link IdentityPreconditioner preconditioner}. * * @param updateFormula formula to use for updating the &beta; parameter, * must be one of {@link ConjugateGradientFormula#FLETCHER_REEVES} or {@link * ConjugateGradientFormula#POLAK_RIBIERE}. */ public NonLinearConjugateGradientOptimizer(final ConjugateGradientFormula updateFormula) { this(updateFormula, new SimpleScalarValueChecker()); } /** * Constructor with default {@link BrentSolver line search solver} and * {@link IdentityPreconditioner preconditioner}. * * @param updateFormula formula to use for updating the &beta; parameter, * must be one of {@link ConjugateGradientFormula#FLETCHER_REEVES} or {@link * ConjugateGradientFormula#POLAK_RIBIERE}. * @param checker Convergence checker. */ public NonLinearConjugateGradientOptimizer(final ConjugateGradientFormula updateFormula, ConvergenceChecker<RealPointValuePair> checker) { this(updateFormula, checker, new BrentSolver(), new IdentityPreconditioner()); } /** * Constructor with default {@link IdentityPreconditioner preconditioner}. * * @param updateFormula formula to use for updating the &beta; parameter, * must be one of {@link ConjugateGradientFormula#FLETCHER_REEVES} or {@link * ConjugateGradientFormula#POLAK_RIBIERE}. * @param checker Convergence checker. * @param lineSearchSolver Solver to use during line search. */ public NonLinearConjugateGradientOptimizer(final ConjugateGradientFormula updateFormula, ConvergenceChecker<RealPointValuePair> checker, final UnivariateRealSolver lineSearchSolver) { this(updateFormula, checker, lineSearchSolver, new IdentityPreconditioner()); } /** * @param updateFormula formula to use for updating the &beta; parameter, * must be one of {@link ConjugateGradientFormula#FLETCHER_REEVES} or {@link * ConjugateGradientFormula#POLAK_RIBIERE}. * @param checker Convergence checker. * @param lineSearchSolver Solver to use during line search. * @param preconditioner Preconditioner. */ public NonLinearConjugateGradientOptimizer(final ConjugateGradientFormula updateFormula, ConvergenceChecker<RealPointValuePair> checker, final UnivariateRealSolver lineSearchSolver, final Preconditioner preconditioner) { super(checker); this.updateFormula = updateFormula; solver = lineSearchSolver; this.preconditioner = preconditioner; initialStep = 1.0; } /** * Set the initial step used to bracket the optimum in line search. * <p> * The initial step is a factor with respect to the search direction, * which itself is roughly related to the gradient of the function * </p> * @param initialStep initial step used to bracket the optimum in line search, * if a non-positive value is used, the initial step is reset to its * default value of 1.0 */ public void setInitialStep(final double initialStep) { if (initialStep <= 0) { this.initialStep = 1.0; } else { this.initialStep = initialStep; } } /** {@inheritDoc} */ @Override protected RealPointValuePair doOptimize() { - final ConvergenceChecker checker = getConvergenceChecker(); + final ConvergenceChecker<RealPointValuePair> checker = getConvergenceChecker(); point = getStartPoint(); final GoalType goal = getGoalType(); final int n = point.length; double[] r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Initial search direction. double[] steepestDescent = preconditioner.precondition(point, r); double[] searchDirection = steepestDescent.clone(); double delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * searchDirection[i]; } RealPointValuePair current = null; int iter = 0; int maxEval = getMaxEvaluations(); while (true) { ++iter; final double objective = computeObjectiveValue(point); RealPointValuePair previous = current; current = new RealPointValuePair(point, objective); if (previous != null) { if (checker.converged(iter, previous, current)) { // We have found an optimum. return current; } } // Find the optimal step in the search direction. final UnivariateRealFunction lsf = new LineSearchFunction(searchDirection); final double uB = findUpperBound(lsf, 0, initialStep); // XXX Last parameters is set to a value close to zero in order to // work around the divergence problem in the "testCircleFitting" // unit test (see MATH-439). final double step = solver.solve(maxEval, lsf, 0, uB, 1e-15); maxEval -= solver.getEvaluations(); // Subtract used up evaluations. // Validate new point. for (int i = 0; i < point.length; ++i) { point[i] += step * searchDirection[i]; } r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Compute beta. final double deltaOld = delta; final double[] newSteepestDescent = preconditioner.precondition(point, r); delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * newSteepestDescent[i]; } final double beta; if (updateFormula == ConjugateGradientFormula.FLETCHER_REEVES) { beta = delta / deltaOld; } else { double deltaMid = 0; for (int i = 0; i < r.length; ++i) { deltaMid += r[i] * steepestDescent[i]; } beta = (delta - deltaMid) / deltaOld; } steepestDescent = newSteepestDescent; // Compute conjugate search direction. if (iter % n == 0 || beta < 0) { // Break conjugation: reset search direction. searchDirection = steepestDescent.clone(); } else { // Compute new conjugate search direction. for (int i = 0; i < n; ++i) { searchDirection[i] = steepestDescent[i] + beta * searchDirection[i]; } } } } /** * Find the upper bound b ensuring bracketing of a root between a and b. * * @param f function whose root must be bracketed. * @param a lower bound of the interval. * @param h initial step to try. * @return b such that f(a) and f(b) have opposite signs. * @throws MathIllegalStateException if no bracket can be found. */ private double findUpperBound(final UnivariateRealFunction f, final double a, final double h) { final double yA = f.value(a); double yB = yA; for (double step = h; step < Double.MAX_VALUE; step *= FastMath.max(2, yA / yB)) { final double b = a + step; yB = f.value(b); if (yA * yB <= 0) { return b; } } throw new MathIllegalStateException(LocalizedFormats.UNABLE_TO_BRACKET_OPTIMUM_IN_LINE_SEARCH); } /** Default identity preconditioner. */ public static class IdentityPreconditioner implements Preconditioner { /** {@inheritDoc} */ public double[] precondition(double[] variables, double[] r) { return r.clone(); } } /** Internal class for line search. * <p> * The function represented by this class is the dot product of * the objective function gradient and the search direction. Its * value is zero when the gradient is orthogonal to the search * direction, i.e. when the objective function value is a local * extremum along the search direction. * </p> */ private class LineSearchFunction implements UnivariateRealFunction { /** Search direction. */ private final double[] searchDirection; /** Simple constructor. * @param searchDirection search direction */ public LineSearchFunction(final double[] searchDirection) { this.searchDirection = searchDirection; } /** {@inheritDoc} */ public double value(double x) { // current point in the search direction final double[] shiftedPoint = point.clone(); for (int i = 0; i < shiftedPoint.length; ++i) { shiftedPoint[i] += x * searchDirection[i]; } // gradient of the objective function final double[] gradient = computeObjectiveGradient(shiftedPoint); // dot product with the search direction double dotProduct = 0; for (int i = 0; i < gradient.length; ++i) { dotProduct += gradient[i] * searchDirection[i]; } return dotProduct; } } }
true
true
protected RealPointValuePair doOptimize() { final ConvergenceChecker checker = getConvergenceChecker(); point = getStartPoint(); final GoalType goal = getGoalType(); final int n = point.length; double[] r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Initial search direction. double[] steepestDescent = preconditioner.precondition(point, r); double[] searchDirection = steepestDescent.clone(); double delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * searchDirection[i]; } RealPointValuePair current = null; int iter = 0; int maxEval = getMaxEvaluations(); while (true) { ++iter; final double objective = computeObjectiveValue(point); RealPointValuePair previous = current; current = new RealPointValuePair(point, objective); if (previous != null) { if (checker.converged(iter, previous, current)) { // We have found an optimum. return current; } } // Find the optimal step in the search direction. final UnivariateRealFunction lsf = new LineSearchFunction(searchDirection); final double uB = findUpperBound(lsf, 0, initialStep); // XXX Last parameters is set to a value close to zero in order to // work around the divergence problem in the "testCircleFitting" // unit test (see MATH-439). final double step = solver.solve(maxEval, lsf, 0, uB, 1e-15); maxEval -= solver.getEvaluations(); // Subtract used up evaluations. // Validate new point. for (int i = 0; i < point.length; ++i) { point[i] += step * searchDirection[i]; } r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Compute beta. final double deltaOld = delta; final double[] newSteepestDescent = preconditioner.precondition(point, r); delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * newSteepestDescent[i]; } final double beta; if (updateFormula == ConjugateGradientFormula.FLETCHER_REEVES) { beta = delta / deltaOld; } else { double deltaMid = 0; for (int i = 0; i < r.length; ++i) { deltaMid += r[i] * steepestDescent[i]; } beta = (delta - deltaMid) / deltaOld; } steepestDescent = newSteepestDescent; // Compute conjugate search direction. if (iter % n == 0 || beta < 0) { // Break conjugation: reset search direction. searchDirection = steepestDescent.clone(); } else { // Compute new conjugate search direction. for (int i = 0; i < n; ++i) { searchDirection[i] = steepestDescent[i] + beta * searchDirection[i]; } } } }
protected RealPointValuePair doOptimize() { final ConvergenceChecker<RealPointValuePair> checker = getConvergenceChecker(); point = getStartPoint(); final GoalType goal = getGoalType(); final int n = point.length; double[] r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Initial search direction. double[] steepestDescent = preconditioner.precondition(point, r); double[] searchDirection = steepestDescent.clone(); double delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * searchDirection[i]; } RealPointValuePair current = null; int iter = 0; int maxEval = getMaxEvaluations(); while (true) { ++iter; final double objective = computeObjectiveValue(point); RealPointValuePair previous = current; current = new RealPointValuePair(point, objective); if (previous != null) { if (checker.converged(iter, previous, current)) { // We have found an optimum. return current; } } // Find the optimal step in the search direction. final UnivariateRealFunction lsf = new LineSearchFunction(searchDirection); final double uB = findUpperBound(lsf, 0, initialStep); // XXX Last parameters is set to a value close to zero in order to // work around the divergence problem in the "testCircleFitting" // unit test (see MATH-439). final double step = solver.solve(maxEval, lsf, 0, uB, 1e-15); maxEval -= solver.getEvaluations(); // Subtract used up evaluations. // Validate new point. for (int i = 0; i < point.length; ++i) { point[i] += step * searchDirection[i]; } r = computeObjectiveGradient(point); if (goal == GoalType.MINIMIZE) { for (int i = 0; i < n; ++i) { r[i] = -r[i]; } } // Compute beta. final double deltaOld = delta; final double[] newSteepestDescent = preconditioner.precondition(point, r); delta = 0; for (int i = 0; i < n; ++i) { delta += r[i] * newSteepestDescent[i]; } final double beta; if (updateFormula == ConjugateGradientFormula.FLETCHER_REEVES) { beta = delta / deltaOld; } else { double deltaMid = 0; for (int i = 0; i < r.length; ++i) { deltaMid += r[i] * steepestDescent[i]; } beta = (delta - deltaMid) / deltaOld; } steepestDescent = newSteepestDescent; // Compute conjugate search direction. if (iter % n == 0 || beta < 0) { // Break conjugation: reset search direction. searchDirection = steepestDescent.clone(); } else { // Compute new conjugate search direction. for (int i = 0; i < n; ++i) { searchDirection[i] = steepestDescent[i] + beta * searchDirection[i]; } } } }
diff --git a/src/main/java/org/otherobjects/cms/controllers/SiteController.java b/src/main/java/org/otherobjects/cms/controllers/SiteController.java index 74bf86f1..688059c5 100644 --- a/src/main/java/org/otherobjects/cms/controllers/SiteController.java +++ b/src/main/java/org/otherobjects/cms/controllers/SiteController.java @@ -1,127 +1,114 @@ package org.otherobjects.cms.controllers; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.otherobjects.cms.controllers.renderers.ResourceRenderer; import org.otherobjects.cms.dao.DaoService; import org.otherobjects.cms.jcr.UniversalJcrDao; import org.otherobjects.cms.model.BaseNode; import org.otherobjects.cms.model.SiteFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; /** * Site controller handles all site page requests. For custom application functionality * you will need to create and map your own controllers. * * @author rich */ public class SiteController extends AbstractController { private final Logger logger = LoggerFactory.getLogger(SiteController.class); private DaoService daoService; private Map<String, ResourceRenderer> renderers = new HashMap<String, ResourceRenderer>(); @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { // Make sure folders end with slash String path = request.getPathInfo(); if (StringUtils.isEmpty(path)) path = "/"; else if (path.length() > 1 && !path.contains(".") && !path.endsWith("/")) path = path + "/"; this.logger.info("Requested resource: {}", path); UniversalJcrDao universalJcrDao = (UniversalJcrDao) this.daoService.getDao(BaseNode.class); BaseNode resourceObject = null; + String newCode = StringUtils.substringAfterLast(path, "/"); if (path.contains(".")) { // Page requested resourceObject = universalJcrDao.getByPath("/site" + path); } else { // Folder requested. If this folder has it's own template then // render that. resourceObject = universalJcrDao.getByPath("/site" + path); if (resourceObject instanceof SiteFolder) { - // resourceObject = null; - // // Folder requested. Get first item that isn't a folder. - // List<BaseNode> contents = universalJcrDao.getAllByPath("/site" + path); - // - // for (BaseNode n : contents) - // { - // // FIXME Need better way of dealing with components - // if (!n.isFolder() && !(n instanceof PublishingOptions)) - // { - // resourceObject = n; - // break; - // } - // } SiteFolder folder = (SiteFolder) resourceObject; String defaultPage = StringUtils.isNotBlank(folder.getDefaultPage()) ? folder.getDefaultPage() : "index.html"; + newCode = defaultPage; resourceObject = universalJcrDao.getByPath(folder.getJcrPath() + "/" + defaultPage); - if (resourceObject == null) - { - ModelAndView mv = new ModelAndView("/site/templates/pages/404"); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - mv.addObject("requestedPath", path); - mv.addObject("folder", folder); - return mv; - } +// if (resourceObject == null) +// { +// ModelAndView mv = new ModelAndView("/site/templates/pages/404"); +// response.setStatus(HttpServletResponse.SC_NOT_FOUND); +// mv.addObject("requestedPath", path); +// mv.addObject("folder", folder); +// return mv; +// } } } // Handle page not found if (resourceObject == null) { // Determine folder - String newCode = StringUtils.substringAfterLast(path, "/"); path = StringUtils.substringBeforeLast(path, "/"); Object folder = universalJcrDao.getByPath("/site" + path); //FIXME Add Security check here - ModelAndView mv = new ModelAndView("/otherobjects/templates/hud/error-handling/oo-404-create"); -// ModelAndView mv = new ModelAndView("/site/templates/pages/404"); + ModelAndView mv = new ModelAndView("/otherobjects/templates/hud/error-handling/oo-404-create"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); mv.addObject("requestedPath", path); mv.addObject("folder", folder); mv.addObject("newCode", newCode); return mv; //throw new NotFoundException("No resource at: " + path); } // Pass control to renderer ResourceRenderer handler = renderers.get(resourceObject.getClass().getName()); if (handler == null) handler = renderers.get("*"); return handler.handleRequest(resourceObject, request, response); } public void setRenderers(Map<String, ResourceRenderer> renderers) { this.renderers = renderers; } public void setDaoService(DaoService daoService) { this.daoService = daoService; } }
false
true
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { // Make sure folders end with slash String path = request.getPathInfo(); if (StringUtils.isEmpty(path)) path = "/"; else if (path.length() > 1 && !path.contains(".") && !path.endsWith("/")) path = path + "/"; this.logger.info("Requested resource: {}", path); UniversalJcrDao universalJcrDao = (UniversalJcrDao) this.daoService.getDao(BaseNode.class); BaseNode resourceObject = null; if (path.contains(".")) { // Page requested resourceObject = universalJcrDao.getByPath("/site" + path); } else { // Folder requested. If this folder has it's own template then // render that. resourceObject = universalJcrDao.getByPath("/site" + path); if (resourceObject instanceof SiteFolder) { // resourceObject = null; // // Folder requested. Get first item that isn't a folder. // List<BaseNode> contents = universalJcrDao.getAllByPath("/site" + path); // // for (BaseNode n : contents) // { // // FIXME Need better way of dealing with components // if (!n.isFolder() && !(n instanceof PublishingOptions)) // { // resourceObject = n; // break; // } // } SiteFolder folder = (SiteFolder) resourceObject; String defaultPage = StringUtils.isNotBlank(folder.getDefaultPage()) ? folder.getDefaultPage() : "index.html"; resourceObject = universalJcrDao.getByPath(folder.getJcrPath() + "/" + defaultPage); if (resourceObject == null) { ModelAndView mv = new ModelAndView("/site/templates/pages/404"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); mv.addObject("requestedPath", path); mv.addObject("folder", folder); return mv; } } } // Handle page not found if (resourceObject == null) { // Determine folder String newCode = StringUtils.substringAfterLast(path, "/"); path = StringUtils.substringBeforeLast(path, "/"); Object folder = universalJcrDao.getByPath("/site" + path); //FIXME Add Security check here ModelAndView mv = new ModelAndView("/otherobjects/templates/hud/error-handling/oo-404-create"); // ModelAndView mv = new ModelAndView("/site/templates/pages/404"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); mv.addObject("requestedPath", path); mv.addObject("folder", folder); mv.addObject("newCode", newCode); return mv; //throw new NotFoundException("No resource at: " + path); } // Pass control to renderer ResourceRenderer handler = renderers.get(resourceObject.getClass().getName()); if (handler == null) handler = renderers.get("*"); return handler.handleRequest(resourceObject, request, response); }
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { // Make sure folders end with slash String path = request.getPathInfo(); if (StringUtils.isEmpty(path)) path = "/"; else if (path.length() > 1 && !path.contains(".") && !path.endsWith("/")) path = path + "/"; this.logger.info("Requested resource: {}", path); UniversalJcrDao universalJcrDao = (UniversalJcrDao) this.daoService.getDao(BaseNode.class); BaseNode resourceObject = null; String newCode = StringUtils.substringAfterLast(path, "/"); if (path.contains(".")) { // Page requested resourceObject = universalJcrDao.getByPath("/site" + path); } else { // Folder requested. If this folder has it's own template then // render that. resourceObject = universalJcrDao.getByPath("/site" + path); if (resourceObject instanceof SiteFolder) { SiteFolder folder = (SiteFolder) resourceObject; String defaultPage = StringUtils.isNotBlank(folder.getDefaultPage()) ? folder.getDefaultPage() : "index.html"; newCode = defaultPage; resourceObject = universalJcrDao.getByPath(folder.getJcrPath() + "/" + defaultPage); // if (resourceObject == null) // { // ModelAndView mv = new ModelAndView("/site/templates/pages/404"); // response.setStatus(HttpServletResponse.SC_NOT_FOUND); // mv.addObject("requestedPath", path); // mv.addObject("folder", folder); // return mv; // } } } // Handle page not found if (resourceObject == null) { // Determine folder path = StringUtils.substringBeforeLast(path, "/"); Object folder = universalJcrDao.getByPath("/site" + path); //FIXME Add Security check here ModelAndView mv = new ModelAndView("/otherobjects/templates/hud/error-handling/oo-404-create"); response.setStatus(HttpServletResponse.SC_NOT_FOUND); mv.addObject("requestedPath", path); mv.addObject("folder", folder); mv.addObject("newCode", newCode); return mv; //throw new NotFoundException("No resource at: " + path); } // Pass control to renderer ResourceRenderer handler = renderers.get(resourceObject.getClass().getName()); if (handler == null) handler = renderers.get("*"); return handler.handleRequest(resourceObject, request, response); }
diff --git a/query/src/test/java/org/infinispan/query/distributed/MassIndexingTest.java b/query/src/test/java/org/infinispan/query/distributed/MassIndexingTest.java index d750bb48e1..8a5f3b6ddc 100644 --- a/query/src/test/java/org/infinispan/query/distributed/MassIndexingTest.java +++ b/query/src/test/java/org/infinispan/query/distributed/MassIndexingTest.java @@ -1,40 +1,40 @@ package org.infinispan.query.distributed; import org.infinispan.context.Flag; import org.infinispan.query.api.NotIndexedType; import org.infinispan.query.queries.faceting.Car; import org.testng.annotations.Test; /** * Running mass indexer on big bunch of data. * * @author Anna Manukyan */ @Test(groups = "functional", testName = "query.distributed.MassIndexingTest") public class MassIndexingTest extends DistributedMassIndexingTest { public void testReindexing() throws Exception { - for(int i = 0; i < 2000; i++) { + for(int i = 0; i < 200; i++) { caches.get(i % 2).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F" + i + "NUM"), new Car((i % 2 == 0 ? "megane" : "bmw"), "blue", 300 + i)); } //Adding also non-indexed values caches.get(0).getAdvancedCache().put(key("FNonIndexed1NUM"), new NotIndexedType("test1")); caches.get(0).getAdvancedCache().put(key("FNonIndexed2NUM"), new NotIndexedType("test2")); verifyFindsCar(0, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); caches.get(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("FNonIndexed3NUM"), new NotIndexedType("test3")); verifyFindsCar(0, "test3"); //re-sync datacontainer with indexes: rebuildIndexes(); - verifyFindsCar(1000, "megane"); + verifyFindsCar(100, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); } }
false
true
public void testReindexing() throws Exception { for(int i = 0; i < 2000; i++) { caches.get(i % 2).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F" + i + "NUM"), new Car((i % 2 == 0 ? "megane" : "bmw"), "blue", 300 + i)); } //Adding also non-indexed values caches.get(0).getAdvancedCache().put(key("FNonIndexed1NUM"), new NotIndexedType("test1")); caches.get(0).getAdvancedCache().put(key("FNonIndexed2NUM"), new NotIndexedType("test2")); verifyFindsCar(0, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); caches.get(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("FNonIndexed3NUM"), new NotIndexedType("test3")); verifyFindsCar(0, "test3"); //re-sync datacontainer with indexes: rebuildIndexes(); verifyFindsCar(1000, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); }
public void testReindexing() throws Exception { for(int i = 0; i < 200; i++) { caches.get(i % 2).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("F" + i + "NUM"), new Car((i % 2 == 0 ? "megane" : "bmw"), "blue", 300 + i)); } //Adding also non-indexed values caches.get(0).getAdvancedCache().put(key("FNonIndexed1NUM"), new NotIndexedType("test1")); caches.get(0).getAdvancedCache().put(key("FNonIndexed2NUM"), new NotIndexedType("test2")); verifyFindsCar(0, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); caches.get(0).getAdvancedCache().withFlags(Flag.SKIP_INDEXING).put(key("FNonIndexed3NUM"), new NotIndexedType("test3")); verifyFindsCar(0, "test3"); //re-sync datacontainer with indexes: rebuildIndexes(); verifyFindsCar(100, "megane"); verifyFindsCar(0, "test1"); verifyFindsCar(0, "test2"); }
diff --git a/src/ScheduleDisplay.java b/src/ScheduleDisplay.java index ebe22e6..24792c7 100644 --- a/src/ScheduleDisplay.java +++ b/src/ScheduleDisplay.java @@ -1,132 +1,132 @@ import java.awt.Color; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.border.Border; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; public class ScheduleDisplay { private JTable table; DefaultTableModel tm; int maxStudentsPerClass; Object[][] data; JButton button = new JButton("Schedule Teachers"); // numClasses = #subjects; numRooms = #divisions private int numRooms = ClassFactory.getMaxCls(); String[] columnNames; public ScheduleDisplay() { data = new Object[(3 * 7) + 1][numRooms + 2]; for (int i = 0; i < 22; i++) { for (int j = 0; j < (numRooms + 2); j++) data[i][j] = ""; } columnNames = new String[numRooms + 2]; columnNames[0] = "Subject"; for (int i = 1; i < numRooms + 1; i++) { columnNames[i] = " "; } columnNames[numRooms + 1] = "Unable to Place"; tm = new DefaultTableModel(data, columnNames); table = new JTable(); table.setModel(tm); update(); } public void update() { populateTable(); tm.setDataVector(data, columnNames); // format table table.setShowGrid(true); table.setGridColor(Color.BLACK); table.setRowHeight(20); Border border = BorderFactory.createLineBorder(Color.BLACK, 1); table.setBorder(border); table.setColumnSelectionAllowed(true); // Make table scrollable table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Fix Sizing TableColumnModel cm = table.getColumnModel(); cm.getColumn(0).setMinWidth(100); for (int i = 1; i < cm.getColumnCount(); i++) { cm.getColumn(i).setMinWidth(150); } } public void populateTable() { // TODO: constants for subjects and max students // table.setValueAt("Reading", 1, 0); data[1][0] = "Reading"; // table.setValueAt("LA", 8, 0); data[8][0] = "Language Arts"; // table.setValueAt("Math", 15, 0); data[15][0] = "Math"; // TODO: add rows for specials and homeroom (same as math) // TODO: add formatting- times of classes // label room numbers // for (int i = 0; i < numRooms; ++i) { // table.setValueAt("Room " + (i + 1), 0, i + 1); // } // table.setValueAt("Unable to place", 0, numRooms + 1); // get student names and place classes in table: // fill in students for Reading for (int i = 0; i < ClassFactory.readClsLst.size(); ++i) { Classes cls = ClassFactory.readClsLst.get(i); data[0][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 1, i + 1); data[j][i+1] = std; //changed from stdNameStr } } // fill in students for LA for (int i = 0; i < ClassFactory.getTotalLA(); ++i) { - Classes cls = ClassFactory.mathClsLst.get(i); + Classes cls = ClassFactory.laClsLst.get(i); data[7][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 8, i + 1); data[j+7][i+1] = std; //changed from stdNameStr } } // fill in students for Math for (int i = 0; i < ClassFactory.getTotalMath(); ++i) { Classes cls = ClassFactory.mathClsLst.get(i); data[14][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 15, i + 1); data[j+14][i+1] = std; //changed from stdNameStr } } } public JTable getScheduleTable() { return table; } }
true
true
public void populateTable() { // TODO: constants for subjects and max students // table.setValueAt("Reading", 1, 0); data[1][0] = "Reading"; // table.setValueAt("LA", 8, 0); data[8][0] = "Language Arts"; // table.setValueAt("Math", 15, 0); data[15][0] = "Math"; // TODO: add rows for specials and homeroom (same as math) // TODO: add formatting- times of classes // label room numbers // for (int i = 0; i < numRooms; ++i) { // table.setValueAt("Room " + (i + 1), 0, i + 1); // } // table.setValueAt("Unable to place", 0, numRooms + 1); // get student names and place classes in table: // fill in students for Reading for (int i = 0; i < ClassFactory.readClsLst.size(); ++i) { Classes cls = ClassFactory.readClsLst.get(i); data[0][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 1, i + 1); data[j][i+1] = std; //changed from stdNameStr } } // fill in students for LA for (int i = 0; i < ClassFactory.getTotalLA(); ++i) { Classes cls = ClassFactory.mathClsLst.get(i); data[7][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 8, i + 1); data[j+7][i+1] = std; //changed from stdNameStr } } // fill in students for Math for (int i = 0; i < ClassFactory.getTotalMath(); ++i) { Classes cls = ClassFactory.mathClsLst.get(i); data[14][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 15, i + 1); data[j+14][i+1] = std; //changed from stdNameStr } } }
public void populateTable() { // TODO: constants for subjects and max students // table.setValueAt("Reading", 1, 0); data[1][0] = "Reading"; // table.setValueAt("LA", 8, 0); data[8][0] = "Language Arts"; // table.setValueAt("Math", 15, 0); data[15][0] = "Math"; // TODO: add rows for specials and homeroom (same as math) // TODO: add formatting- times of classes // label room numbers // for (int i = 0; i < numRooms; ++i) { // table.setValueAt("Room " + (i + 1), 0, i + 1); // } // table.setValueAt("Unable to place", 0, numRooms + 1); // get student names and place classes in table: // fill in students for Reading for (int i = 0; i < ClassFactory.readClsLst.size(); ++i) { Classes cls = ClassFactory.readClsLst.get(i); data[0][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 1, i + 1); data[j][i+1] = std; //changed from stdNameStr } } // fill in students for LA for (int i = 0; i < ClassFactory.getTotalLA(); ++i) { Classes cls = ClassFactory.laClsLst.get(i); data[7][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 8, i + 1); data[j+7][i+1] = std; //changed from stdNameStr } } // fill in students for Math for (int i = 0; i < ClassFactory.getTotalMath(); ++i) { Classes cls = ClassFactory.mathClsLst.get(i); data[14][i+1] = cls.getClsName() + " " + cls.getLvl(); List<Students> students = cls.getStudents(); for (int j = 1; j < students.size(); j++) { Students std = students.get(j); String stdNameStr = std.getFirstName(); stdNameStr += " " + std.getLastName(); //table.setValueAt(stdNameStr, j + 15, i + 1); data[j+14][i+1] = std; //changed from stdNameStr } } }
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java index 29944b32..0787829a 100644 --- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java +++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/operation/RemoveReferenceComponentOperation.java @@ -1,103 +1,105 @@ /******************************************************************************* * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.common.componentcore.internal.operation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jem.util.emf.workbench.ProjectUtilities; import org.eclipse.wst.common.componentcore.datamodel.properties.ICreateReferenceComponentsDataModelProperties; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.componentcore.resources.IVirtualReference; import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; public class RemoveReferenceComponentOperation extends AbstractDataModelOperation { public RemoveReferenceComponentOperation() { super(); } public RemoveReferenceComponentOperation(IDataModel model) { super(model); } public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { removeReferencedComponents(monitor); return OK_STATUS; } protected void removeReferencedComponents(IProgressMonitor monitor) { IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT); if (!sourceComp.getProject().isAccessible()) return; List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST); List targetprojectList = new ArrayList(); for (int i = 0; i < modList.size(); i++) { IVirtualComponent comp = (IVirtualComponent) modList.get(i); + if (comp==null || sourceComp==null) + continue; IVirtualReference ref = sourceComp.getReference(comp.getName()); if( ref != null && ref.getReferencedComponent() != null && ref.getReferencedComponent().isBinary()){ removeRefereneceInComponent(sourceComp, ref); }else{ if (Arrays.asList(comp.getReferencingComponents()).contains(sourceComp)) { String deployPath = model.getStringProperty( ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH ); IPath path = new Path( deployPath ); if( ref.getRuntimePath() != null && path != null && ref.getRuntimePath().equals( path )){ removeRefereneceInComponent(sourceComp,sourceComp.getReference(comp.getName())); IProject targetProject = comp.getProject(); targetprojectList.add(targetProject); } } } } try { ProjectUtilities.removeReferenceProjects(sourceComp.getProject(),targetprojectList); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void removeRefereneceInComponent(IVirtualComponent component, IVirtualReference reference) { List refList = new ArrayList(); IVirtualReference[] refArray = component.getReferences(); for (int i = 0; i < refArray.length; i++) { if (refArray[i].getReferencedComponent() != null && !refArray[i].getReferencedComponent().equals(reference.getReferencedComponent())) refList.add(refArray[i]); } component.setReferences((IVirtualReference[]) refList.toArray(new IVirtualReference[refList.size()])); } public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return null; } public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return null; } }
true
true
protected void removeReferencedComponents(IProgressMonitor monitor) { IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT); if (!sourceComp.getProject().isAccessible()) return; List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST); List targetprojectList = new ArrayList(); for (int i = 0; i < modList.size(); i++) { IVirtualComponent comp = (IVirtualComponent) modList.get(i); IVirtualReference ref = sourceComp.getReference(comp.getName()); if( ref != null && ref.getReferencedComponent() != null && ref.getReferencedComponent().isBinary()){ removeRefereneceInComponent(sourceComp, ref); }else{ if (Arrays.asList(comp.getReferencingComponents()).contains(sourceComp)) { String deployPath = model.getStringProperty( ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH ); IPath path = new Path( deployPath ); if( ref.getRuntimePath() != null && path != null && ref.getRuntimePath().equals( path )){ removeRefereneceInComponent(sourceComp,sourceComp.getReference(comp.getName())); IProject targetProject = comp.getProject(); targetprojectList.add(targetProject); } } } } try { ProjectUtilities.removeReferenceProjects(sourceComp.getProject(),targetprojectList); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
protected void removeReferencedComponents(IProgressMonitor monitor) { IVirtualComponent sourceComp = (IVirtualComponent) model.getProperty(ICreateReferenceComponentsDataModelProperties.SOURCE_COMPONENT); if (!sourceComp.getProject().isAccessible()) return; List modList = (List) model.getProperty(ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENT_LIST); List targetprojectList = new ArrayList(); for (int i = 0; i < modList.size(); i++) { IVirtualComponent comp = (IVirtualComponent) modList.get(i); if (comp==null || sourceComp==null) continue; IVirtualReference ref = sourceComp.getReference(comp.getName()); if( ref != null && ref.getReferencedComponent() != null && ref.getReferencedComponent().isBinary()){ removeRefereneceInComponent(sourceComp, ref); }else{ if (Arrays.asList(comp.getReferencingComponents()).contains(sourceComp)) { String deployPath = model.getStringProperty( ICreateReferenceComponentsDataModelProperties.TARGET_COMPONENTS_DEPLOY_PATH ); IPath path = new Path( deployPath ); if( ref.getRuntimePath() != null && path != null && ref.getRuntimePath().equals( path )){ removeRefereneceInComponent(sourceComp,sourceComp.getReference(comp.getName())); IProject targetProject = comp.getProject(); targetprojectList.add(targetProject); } } } } try { ProjectUtilities.removeReferenceProjects(sourceComp.getProject(),targetprojectList); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java b/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java index d60e6bf..38311db 100644 --- a/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java +++ b/mcu/src/org/smbarbour/mcu/AppletLauncherThread.java @@ -1,238 +1,243 @@ package org.smbarbour.mcu; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JButton; import javax.swing.JOptionPane; import org.smbarbour.mcu.util.LoginData; import org.smbarbour.mcu.util.MCUpdater; import org.smbarbour.mcu.util.ServerList; public class AppletLauncherThread implements GenericLauncherThread, Runnable { private ConsoleArea console; private MainForm parent; private LoginData session; private String jrePath; private String minMem; private String maxMem; private File output; private Thread thread; private boolean forceKilled; private ServerList server; private Process task; private JButton launchButton; private MenuItem killItem; private boolean ready; public AppletLauncherThread(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output, ServerList server) { this.parent = parent; this.session = session; this.jrePath = jrePath; this.minMem = minMem; this.maxMem = maxMem; this.output = output; this.server = server; } public static AppletLauncherThread launch(MainForm parent, LoginData session, String jrePath, String minMem, String maxMem, File output, ConsoleArea console, ServerList server) { AppletLauncherThread me = new AppletLauncherThread(parent, session, jrePath, minMem, maxMem, output, server); me.console = console; console.setText(""); return me; } @Override public void run() { String javaBin = "java"; - File binDir = (new File(jrePath)).toPath().resolve("bin").toFile(); + File binDir; + if (System.getProperty("os.name").startsWith("Mac")) { + binDir = (new File(jrePath)).toPath().resolve("Commands").toFile(); + } else { + binDir = (new File(jrePath)).toPath().resolve("bin").toFile(); + } if( binDir.exists() ) { javaBin = binDir.toPath().resolve("java").toString(); } List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); args.add("-Xms" + this.minMem); args.add("-Xmx" + this.maxMem); args.add("-classpath"); args.add(MCUpdater.getJarFile().toString()); args.add("org.smbarbour.mcu.MinecraftFrame"); args.add(session.getUserName()); args.add(session.getSessionId()); args.add(server.getName()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString()); args.add(server.getAddress()); args.add(server.getIconUrl()); if (!Version.isMasterBranch()) { parent.log("Process args:"); Iterator<String> itArgs = args.iterator(); while (itArgs.hasNext()) { String entry = itArgs.next(); parent.log(entry); } } ProcessBuilder pb = new ProcessBuilder(args); System.out.println("Running on: " + System.getProperty("os.name")); if(System.getProperty("os.name").startsWith("Linux")) { pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString()); - } else if(System.getProperty("os.name").startsWith("Mac")) { - pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("amd64").toString()); +// } else if(System.getProperty("os.name").startsWith("Mac")) { +// pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("Lib").resolve("amd64").toString()); } pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } } private void restoreFrame() { parent.restore(); toggleKillable(false); } private void minimizeFrame() { parent.minimize(true); toggleKillable(true); } private void setReady() { ready = true; if(launchButton != null) { launchButton.setEnabled(true); } } private void toggleKillable(boolean enabled) { if( killItem == null ) return; killItem.setEnabled(enabled); if( enabled ) { final AppletLauncherThread thread = this; killItem.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { thread.stop(); } }); } else { for( ActionListener listener : killItem.getActionListeners() ) { killItem.removeActionListener(listener); } killItem = null; } } @Override public void start() { thread = new Thread(this); thread.start(); } @Override public void stop() { if( task != null ) { final int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to kill Minecraft?\nThis could result in corrupted world save data.", "Kill Minecraft", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ); if( confirm == JOptionPane.YES_OPTION ) { forceKilled = true; try { task.destroy(); } catch( Exception e ) { // maximum paranoia here e.printStackTrace(); } } } } private void log(String msg) { if( console == null ) return; console.log(msg); } @Override public void register(MainForm form, JButton btnLaunchMinecraft, MenuItem killItem) { launchButton = btnLaunchMinecraft; this.killItem = killItem; if( ready ) { setReady(); } } }
false
true
public void run() { String javaBin = "java"; File binDir = (new File(jrePath)).toPath().resolve("bin").toFile(); if( binDir.exists() ) { javaBin = binDir.toPath().resolve("java").toString(); } List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); args.add("-Xms" + this.minMem); args.add("-Xmx" + this.maxMem); args.add("-classpath"); args.add(MCUpdater.getJarFile().toString()); args.add("org.smbarbour.mcu.MinecraftFrame"); args.add(session.getUserName()); args.add(session.getSessionId()); args.add(server.getName()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString()); args.add(server.getAddress()); args.add(server.getIconUrl()); if (!Version.isMasterBranch()) { parent.log("Process args:"); Iterator<String> itArgs = args.iterator(); while (itArgs.hasNext()) { String entry = itArgs.next(); parent.log(entry); } } ProcessBuilder pb = new ProcessBuilder(args); System.out.println("Running on: " + System.getProperty("os.name")); if(System.getProperty("os.name").startsWith("Linux")) { pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString()); } else if(System.getProperty("os.name").startsWith("Mac")) { pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("amd64").toString()); } pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } }
public void run() { String javaBin = "java"; File binDir; if (System.getProperty("os.name").startsWith("Mac")) { binDir = (new File(jrePath)).toPath().resolve("Commands").toFile(); } else { binDir = (new File(jrePath)).toPath().resolve("bin").toFile(); } if( binDir.exists() ) { javaBin = binDir.toPath().resolve("java").toString(); } List<String> args = new ArrayList<String>(); args.add(javaBin); args.add("-XX:+UseConcMarkSweepGC"); args.add("-XX:+CMSIncrementalMode"); args.add("-XX:+AggressiveOpts"); args.add("-Xms" + this.minMem); args.add("-Xmx" + this.maxMem); args.add("-classpath"); args.add(MCUpdater.getJarFile().toString()); args.add("org.smbarbour.mcu.MinecraftFrame"); args.add(session.getUserName()); args.add(session.getSessionId()); args.add(server.getName()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).toString()); args.add(MCUpdater.getInstance().getInstanceRoot().resolve(server.getServerId()).resolve("bin").toString()); args.add(server.getAddress()); args.add(server.getIconUrl()); if (!Version.isMasterBranch()) { parent.log("Process args:"); Iterator<String> itArgs = args.iterator(); while (itArgs.hasNext()) { String entry = itArgs.next(); parent.log(entry); } } ProcessBuilder pb = new ProcessBuilder(args); System.out.println("Running on: " + System.getProperty("os.name")); if(System.getProperty("os.name").startsWith("Linux")) { pb.environment().put("LD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("lib").resolve("i386").toString()); // } else if(System.getProperty("os.name").startsWith("Mac")) { // pb.environment().put("DYLD_LIBRARY_PATH", (new File(jrePath)).toPath().resolve("Lib").resolve("amd64").toString()); } pb.redirectErrorStream(true); BufferedWriter buffWrite = null; try { buffWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output))); } catch (FileNotFoundException e) { log(e.getMessage()+"\n"); e.printStackTrace(); } try { task = pb.start(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(task.getInputStream())); String line; buffRead.mark(1024); final String firstLine = buffRead.readLine(); setReady(); if (firstLine == null || firstLine.startsWith("Error occurred during initialization of VM") || firstLine.startsWith("Could not create the Java virtual machine.")) { log("!!! Failure to launch detected.\n"); // fetch the whole error message StringBuilder err = new StringBuilder(firstLine); while ((line = buffRead.readLine()) != null) { err.append('\n'); err.append(line); } log(err+"\n"); JOptionPane.showMessageDialog(null, err); } else { buffRead.reset(); minimizeFrame(); log("* Launching client...\n"); int counter = 0; while ((line = buffRead.readLine()) != null) { if (buffWrite != null) { buffWrite.write(line); buffWrite.newLine(); counter++; if (counter >= 20) { buffWrite.flush(); counter = 0; } } else { System.out.println(line); } if( line.length() > 0) { log(line+"\n"); } } } buffWrite.flush(); buffWrite.close(); restoreFrame(); log("* Exiting Minecraft"+(forceKilled?" (killed)":"")+"\n"); } catch (IOException ioe) { ioe.printStackTrace(); } }
diff --git a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/SpringEntityWidgetBuilder.java b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/SpringEntityWidgetBuilder.java index 0572352..be5c2d2 100644 --- a/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/SpringEntityWidgetBuilder.java +++ b/src/main/java/org/jboss/forge/scaffold/spring/metawidget/widgetbuilder/SpringEntityWidgetBuilder.java @@ -1,294 +1,294 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.forge.scaffold.spring.metawidget.widgetbuilder; import static org.jboss.forge.scaffold.spring.metawidget.inspector.ForgeInspectionResultConstants.*; import static org.metawidget.inspector.InspectionResultConstants.*; import static org.metawidget.inspector.spring.SpringInspectionResultConstants.*; import java.util.Collection; import java.util.Map; import org.jboss.forge.env.Configuration; import org.jboss.forge.parser.java.util.Strings; import org.jboss.forge.scaffold.spring.SpringScaffold; import org.jvnet.inflector.Noun; import org.metawidget.iface.MetawidgetException; import org.metawidget.statically.BaseStaticXmlWidget; import org.metawidget.statically.StaticXmlStub; import org.metawidget.statically.StaticXmlWidget; import org.metawidget.statically.html.widgetbuilder.HtmlInput; import org.metawidget.statically.html.widgetbuilder.HtmlTableCell; import org.metawidget.statically.jsp.StaticJspMetawidget; import org.metawidget.statically.jsp.StaticJspUtils; import org.metawidget.statically.jsp.widgetbuilder.CoreOut; import org.metawidget.statically.jsp.widgetprocessor.StandardBindingProcessor; import org.metawidget.statically.layout.SimpleLayout; import org.metawidget.statically.spring.StaticSpringMetawidget; import org.metawidget.statically.spring.widgetbuilder.FormOptionTag; import org.metawidget.statically.spring.widgetbuilder.FormOptionsTag; import org.metawidget.statically.spring.widgetbuilder.FormSelectTag; import org.metawidget.statically.spring.widgetbuilder.SpringWidgetBuilder; import org.metawidget.util.WidgetBuilderUtils; import org.metawidget.util.simple.StringUtils; /** * Builds widgets with Forge-specific behaviours (such as links to other Scaffolding pages) * * @author Ryan Bradley */ public class SpringEntityWidgetBuilder extends SpringWidgetBuilder { // // Private statics // /** * Current Forge configuration. Useful to retrieve <code>targetDir</code>. */ private final Configuration config; // // Constructor // public SpringEntityWidgetBuilder(EntityWidgetBuilderConfig config) { this.config = config.getConfig(); } // // Public methods // @Override public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticSpringMetawidget metawidget) { // Suppress nested INVERSE ONE_TO_ONE to avoid recursion. if (TRUE.equals(attributes.get(ONE_TO_ONE)) && TRUE.equals(attributes.get(INVERSE_RELATIONSHIP))) { return new StaticXmlStub(); } - Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, null); + Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, String.class); if (WidgetBuilderUtils.isReadOnly(attributes)) { // Render read-only Spring lookup as a link. if (attributes.containsKey(SPRING_LOOKUP)) { // (unless parent is already a link) if (widgetIsLink((BaseStaticXmlWidget) metawidget.getParent())) { return null; } FormSelectTag select = new FormSelectTag(); select.putAttribute("items", Noun.pluralOf(attributes.get(NAME))); select.putAttribute("path", attributes.get(NAME)); String itemLabel = attributes.get(SPRING_LOOKUP_ITEM_LABEL); String itemValue = attributes.get(SPRING_LOOKUP_ITEM_VALUE); if (itemLabel != null) { select.putAttribute("itemLabel", itemLabel); } if (itemValue != null) { select.putAttribute("itemValue", itemValue); } if (TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); } String controllerName = Noun.pluralOf(clazz.getSimpleName()).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + "/" + controllerName); HtmlAnchor link = new HtmlAnchor(); link.putAttribute("href", curl.toString()); link.putAttribute("value", "Create New " + StringUtils.uncamelCase(clazz.getSimpleName())); HtmlTableCell lookupCell = new HtmlTableCell(); lookupCell.getChildren().add(select); lookupCell.getChildren().add(link); return lookupCell; } if (clazz != null) { // Render read-only booleans as graphics if (boolean.class.equals(clazz)) { CoreOut cout = new CoreOut(); StandardBindingProcessor processor = new StandardBindingProcessor(); processor.processWidget(cout, elementName, attributes, metawidget); return cout; } } } // Render collection tables with links. // Render non-optional ONE_TO_ONE with a button. if (TRUE.equals(attributes.get(ONE_TO_ONE))) { // (we are about to create a nested metawidget, so we must prevent recursion) if (ENTITY.equals(elementName)) { return null; } // Create nested StaticSpringMetawidget StaticSpringMetawidget nestedMetawidget = new StaticSpringMetawidget(); String valueExpression = StaticJspUtils.unwrapExpression(((StaticJspMetawidget) metawidget).getValue()); valueExpression += StringUtils.SEPARATOR_DOT_CHAR + attributes.get(NAME); ((StaticJspMetawidget) nestedMetawidget).setValue(valueExpression); metawidget.initNestedMetawidget(nestedMetawidget, attributes); // If read-only, we're done. if (WidgetBuilderUtils.isReadOnly(attributes)) { return nestedMetawidget; } // Otherwise, use a dropdown menu with a create button. FormSelectTag select = new FormSelectTag(); select.putAttribute("path", attributes.get(NAME)); if (!TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); FormOptionsTag options = new FormOptionsTag(); options.putAttribute("items", StaticJspUtils.wrapExpression(attributes.get(NAME))); select.getChildren().add(options); } else { select.putAttribute("items", StaticJspUtils.wrapExpression(Noun.pluralOf(attributes.get(NAME)))); } HtmlTableCell cell = new HtmlTableCell(); cell.getChildren().add(select); // TODO: Find a way to direct this link to a create form for the top entity, not the member. // TODO: Find a better way to retrieve the controller name. int lastIndexOf = attributes.get(TYPE).lastIndexOf(StringUtils.SEPARATOR_DOT_CHAR); String controllerName = Noun.pluralOf(attributes.get(TYPE).substring(lastIndexOf + 1)).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + controllerName + "/create"); HtmlAnchor createLink = new HtmlAnchor(); createLink.setTextContent("Create New " + StringUtils.uncamelCase(attributes.get(TYPE).substring(lastIndexOf + 1))); createLink.putAttribute("href", curl.toString()); cell.getChildren().add(createLink); return cell; } if (clazz != null) { if (Collection.class.isAssignableFrom(clazz)) { StaticJspMetawidget nestedMetawidget = new StaticJspMetawidget(); nestedMetawidget.setInspector( metawidget.getInspector() ); nestedMetawidget.setLayout( new SimpleLayout() ); nestedMetawidget.setPath( metawidget.getPath() + StringUtils.SEPARATOR_FORWARD_SLASH_CHAR + attributes.get( NAME ) ); // If using an external config, lookup StaticJspMetawidget within it if ( metawidget.getConfig() != null ) { nestedMetawidget.setConfig( metawidget.getConfig() ); try { nestedMetawidget.getWidgetProcessors(); } catch ( MetawidgetException e ) { nestedMetawidget.setConfig( null ); } } return nestedMetawidget; } } return null; } // // Private methods // private String getTargetDir() { String target = this.config.getString(SpringScaffold.class.getName() + "_targetDir"); target = Strings.isNullOrEmpty(target) ? "" : target; if (!target.startsWith("/")) target = "/" + target; if (target.endsWith("/") && !target.startsWith("/")) target = target.substring(0, target.length()-1); return target; } private boolean widgetIsLink(BaseStaticXmlWidget widget) { if (widget instanceof HtmlAnchor) { return true; } if (widget instanceof HtmlInput && !widget.getAttribute("onclick").isEmpty()) { return true; } return false; } }
true
true
public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticSpringMetawidget metawidget) { // Suppress nested INVERSE ONE_TO_ONE to avoid recursion. if (TRUE.equals(attributes.get(ONE_TO_ONE)) && TRUE.equals(attributes.get(INVERSE_RELATIONSHIP))) { return new StaticXmlStub(); } Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, null); if (WidgetBuilderUtils.isReadOnly(attributes)) { // Render read-only Spring lookup as a link. if (attributes.containsKey(SPRING_LOOKUP)) { // (unless parent is already a link) if (widgetIsLink((BaseStaticXmlWidget) metawidget.getParent())) { return null; } FormSelectTag select = new FormSelectTag(); select.putAttribute("items", Noun.pluralOf(attributes.get(NAME))); select.putAttribute("path", attributes.get(NAME)); String itemLabel = attributes.get(SPRING_LOOKUP_ITEM_LABEL); String itemValue = attributes.get(SPRING_LOOKUP_ITEM_VALUE); if (itemLabel != null) { select.putAttribute("itemLabel", itemLabel); } if (itemValue != null) { select.putAttribute("itemValue", itemValue); } if (TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); } String controllerName = Noun.pluralOf(clazz.getSimpleName()).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + "/" + controllerName); HtmlAnchor link = new HtmlAnchor(); link.putAttribute("href", curl.toString()); link.putAttribute("value", "Create New " + StringUtils.uncamelCase(clazz.getSimpleName())); HtmlTableCell lookupCell = new HtmlTableCell(); lookupCell.getChildren().add(select); lookupCell.getChildren().add(link); return lookupCell; } if (clazz != null) { // Render read-only booleans as graphics if (boolean.class.equals(clazz)) { CoreOut cout = new CoreOut(); StandardBindingProcessor processor = new StandardBindingProcessor(); processor.processWidget(cout, elementName, attributes, metawidget); return cout; } } } // Render collection tables with links. // Render non-optional ONE_TO_ONE with a button. if (TRUE.equals(attributes.get(ONE_TO_ONE))) { // (we are about to create a nested metawidget, so we must prevent recursion) if (ENTITY.equals(elementName)) { return null; } // Create nested StaticSpringMetawidget StaticSpringMetawidget nestedMetawidget = new StaticSpringMetawidget(); String valueExpression = StaticJspUtils.unwrapExpression(((StaticJspMetawidget) metawidget).getValue()); valueExpression += StringUtils.SEPARATOR_DOT_CHAR + attributes.get(NAME); ((StaticJspMetawidget) nestedMetawidget).setValue(valueExpression); metawidget.initNestedMetawidget(nestedMetawidget, attributes); // If read-only, we're done. if (WidgetBuilderUtils.isReadOnly(attributes)) { return nestedMetawidget; } // Otherwise, use a dropdown menu with a create button. FormSelectTag select = new FormSelectTag(); select.putAttribute("path", attributes.get(NAME)); if (!TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); FormOptionsTag options = new FormOptionsTag(); options.putAttribute("items", StaticJspUtils.wrapExpression(attributes.get(NAME))); select.getChildren().add(options); } else { select.putAttribute("items", StaticJspUtils.wrapExpression(Noun.pluralOf(attributes.get(NAME)))); } HtmlTableCell cell = new HtmlTableCell(); cell.getChildren().add(select); // TODO: Find a way to direct this link to a create form for the top entity, not the member. // TODO: Find a better way to retrieve the controller name. int lastIndexOf = attributes.get(TYPE).lastIndexOf(StringUtils.SEPARATOR_DOT_CHAR); String controllerName = Noun.pluralOf(attributes.get(TYPE).substring(lastIndexOf + 1)).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + controllerName + "/create"); HtmlAnchor createLink = new HtmlAnchor(); createLink.setTextContent("Create New " + StringUtils.uncamelCase(attributes.get(TYPE).substring(lastIndexOf + 1))); createLink.putAttribute("href", curl.toString()); cell.getChildren().add(createLink); return cell; } if (clazz != null) { if (Collection.class.isAssignableFrom(clazz)) { StaticJspMetawidget nestedMetawidget = new StaticJspMetawidget(); nestedMetawidget.setInspector( metawidget.getInspector() ); nestedMetawidget.setLayout( new SimpleLayout() ); nestedMetawidget.setPath( metawidget.getPath() + StringUtils.SEPARATOR_FORWARD_SLASH_CHAR + attributes.get( NAME ) ); // If using an external config, lookup StaticJspMetawidget within it if ( metawidget.getConfig() != null ) { nestedMetawidget.setConfig( metawidget.getConfig() ); try { nestedMetawidget.getWidgetProcessors(); } catch ( MetawidgetException e ) { nestedMetawidget.setConfig( null ); } } return nestedMetawidget; } } return null; }
public StaticXmlWidget buildWidget(String elementName, Map<String, String> attributes, StaticSpringMetawidget metawidget) { // Suppress nested INVERSE ONE_TO_ONE to avoid recursion. if (TRUE.equals(attributes.get(ONE_TO_ONE)) && TRUE.equals(attributes.get(INVERSE_RELATIONSHIP))) { return new StaticXmlStub(); } Class<?> clazz = WidgetBuilderUtils.getActualClassOrType(attributes, String.class); if (WidgetBuilderUtils.isReadOnly(attributes)) { // Render read-only Spring lookup as a link. if (attributes.containsKey(SPRING_LOOKUP)) { // (unless parent is already a link) if (widgetIsLink((BaseStaticXmlWidget) metawidget.getParent())) { return null; } FormSelectTag select = new FormSelectTag(); select.putAttribute("items", Noun.pluralOf(attributes.get(NAME))); select.putAttribute("path", attributes.get(NAME)); String itemLabel = attributes.get(SPRING_LOOKUP_ITEM_LABEL); String itemValue = attributes.get(SPRING_LOOKUP_ITEM_VALUE); if (itemLabel != null) { select.putAttribute("itemLabel", itemLabel); } if (itemValue != null) { select.putAttribute("itemValue", itemValue); } if (TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); } String controllerName = Noun.pluralOf(clazz.getSimpleName()).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + "/" + controllerName); HtmlAnchor link = new HtmlAnchor(); link.putAttribute("href", curl.toString()); link.putAttribute("value", "Create New " + StringUtils.uncamelCase(clazz.getSimpleName())); HtmlTableCell lookupCell = new HtmlTableCell(); lookupCell.getChildren().add(select); lookupCell.getChildren().add(link); return lookupCell; } if (clazz != null) { // Render read-only booleans as graphics if (boolean.class.equals(clazz)) { CoreOut cout = new CoreOut(); StandardBindingProcessor processor = new StandardBindingProcessor(); processor.processWidget(cout, elementName, attributes, metawidget); return cout; } } } // Render collection tables with links. // Render non-optional ONE_TO_ONE with a button. if (TRUE.equals(attributes.get(ONE_TO_ONE))) { // (we are about to create a nested metawidget, so we must prevent recursion) if (ENTITY.equals(elementName)) { return null; } // Create nested StaticSpringMetawidget StaticSpringMetawidget nestedMetawidget = new StaticSpringMetawidget(); String valueExpression = StaticJspUtils.unwrapExpression(((StaticJspMetawidget) metawidget).getValue()); valueExpression += StringUtils.SEPARATOR_DOT_CHAR + attributes.get(NAME); ((StaticJspMetawidget) nestedMetawidget).setValue(valueExpression); metawidget.initNestedMetawidget(nestedMetawidget, attributes); // If read-only, we're done. if (WidgetBuilderUtils.isReadOnly(attributes)) { return nestedMetawidget; } // Otherwise, use a dropdown menu with a create button. FormSelectTag select = new FormSelectTag(); select.putAttribute("path", attributes.get(NAME)); if (!TRUE.equals(attributes.get(REQUIRED))) { FormOptionTag emptyOption = new FormOptionTag(); emptyOption.putAttribute("value", ""); select.getChildren().add(emptyOption); FormOptionsTag options = new FormOptionsTag(); options.putAttribute("items", StaticJspUtils.wrapExpression(attributes.get(NAME))); select.getChildren().add(options); } else { select.putAttribute("items", StaticJspUtils.wrapExpression(Noun.pluralOf(attributes.get(NAME)))); } HtmlTableCell cell = new HtmlTableCell(); cell.getChildren().add(select); // TODO: Find a way to direct this link to a create form for the top entity, not the member. // TODO: Find a better way to retrieve the controller name. int lastIndexOf = attributes.get(TYPE).lastIndexOf(StringUtils.SEPARATOR_DOT_CHAR); String controllerName = Noun.pluralOf(attributes.get(TYPE).substring(lastIndexOf + 1)).toLowerCase(); CoreUrl curl = new CoreUrl(); curl.setValue(getTargetDir() + controllerName + "/create"); HtmlAnchor createLink = new HtmlAnchor(); createLink.setTextContent("Create New " + StringUtils.uncamelCase(attributes.get(TYPE).substring(lastIndexOf + 1))); createLink.putAttribute("href", curl.toString()); cell.getChildren().add(createLink); return cell; } if (clazz != null) { if (Collection.class.isAssignableFrom(clazz)) { StaticJspMetawidget nestedMetawidget = new StaticJspMetawidget(); nestedMetawidget.setInspector( metawidget.getInspector() ); nestedMetawidget.setLayout( new SimpleLayout() ); nestedMetawidget.setPath( metawidget.getPath() + StringUtils.SEPARATOR_FORWARD_SLASH_CHAR + attributes.get( NAME ) ); // If using an external config, lookup StaticJspMetawidget within it if ( metawidget.getConfig() != null ) { nestedMetawidget.setConfig( metawidget.getConfig() ); try { nestedMetawidget.getWidgetProcessors(); } catch ( MetawidgetException e ) { nestedMetawidget.setConfig( null ); } } return nestedMetawidget; } } return null; }
diff --git a/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java b/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java index da9b1b5dc..fe2f63782 100755 --- a/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java +++ b/src/java/org/infoglue/deliver/util/SelectiveLivePublicationThread.java @@ -1,278 +1,278 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.deliver.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.exolab.castor.jdo.Database; import org.infoglue.cms.controllers.kernel.impl.simple.CastorDatabaseService; import org.infoglue.cms.controllers.kernel.impl.simple.ContentController; import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController; import org.infoglue.cms.controllers.kernel.impl.simple.PublicationController; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeController; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeVersionController; import org.infoglue.cms.entities.content.Content; import org.infoglue.cms.entities.content.ContentVersion; import org.infoglue.cms.entities.content.ContentVersionVO; import org.infoglue.cms.entities.content.impl.simple.ContentImpl; import org.infoglue.cms.entities.content.impl.simple.ContentVersionImpl; import org.infoglue.cms.entities.content.impl.simple.DigitalAssetImpl; import org.infoglue.cms.entities.content.impl.simple.MediumContentImpl; import org.infoglue.cms.entities.content.impl.simple.SmallContentImpl; import org.infoglue.cms.entities.management.impl.simple.AvailableServiceBindingImpl; import org.infoglue.cms.entities.management.impl.simple.GroupImpl; import org.infoglue.cms.entities.management.impl.simple.RoleImpl; import org.infoglue.cms.entities.management.impl.simple.SmallAvailableServiceBindingImpl; import org.infoglue.cms.entities.management.impl.simple.SystemUserImpl; import org.infoglue.cms.entities.publishing.PublicationDetailVO; import org.infoglue.cms.entities.publishing.impl.simple.PublicationDetailImpl; import org.infoglue.cms.entities.publishing.impl.simple.PublicationImpl; import org.infoglue.cms.entities.structure.SiteNodeVO; import org.infoglue.cms.entities.structure.SiteNodeVersion; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeVersionImpl; import org.infoglue.cms.entities.structure.impl.simple.SmallSiteNodeImpl; import org.infoglue.cms.util.CmsPropertyHandler; import org.infoglue.cms.util.NotificationMessage; import org.infoglue.deliver.applications.databeans.CacheEvictionBean; import org.infoglue.deliver.controllers.kernel.impl.simple.DigitalAssetDeliveryController; /** * @author mattias * * This is a selective publication thread. What that means is that it only throws * away objects and pages in the cache which are affected. Experimental for now. */ public class SelectiveLivePublicationThread extends PublicationThread { public final static Logger logger = Logger.getLogger(SelectiveLivePublicationThread.class.getName()); private List cacheEvictionBeans = new ArrayList(); public SelectiveLivePublicationThread() { } public List getCacheEvictionBeans() { return cacheEvictionBeans; } public void run() { logger.info("Run in SelectiveLivePublicationThread...."); int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); try { sleep(publicationDelay); } catch (InterruptedException e1) { e1.printStackTrace(); } logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests()); if(cacheEvictionBeans.size() > 0) { try { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); Iterator i = cacheEvictionBeans.iterator(); while(i.hasNext()) { CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next(); String className = cacheEvictionBean.getClassName(); String objectId = cacheEvictionBean.getObjectId(); String objectName = cacheEvictionBean.getObjectName(); String typeId = cacheEvictionBean.getTypeId(); logger.info("className:" + className); logger.info("objectId:" + objectId); logger.info("objectName:" + objectName); logger.info("typeId:" + typeId); boolean isDependsClass = false; if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName())) isDependsClass = true; CacheController.clearCaches(className, objectId, null); logger.info("Updating className with id:" + className + ":" + objectId); if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM)) { Class type = Class.forName(className); if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName())) { Object[] ids = {objectId}; CacheController.clearCache(type, ids); } else if(!isDependsClass) { Object[] ids = {new Integer(objectId)}; CacheController.clearCache(type, ids); } //If it's an contentVersion we should delete all images it might have generated from attributes. if(Class.forName(className).getName().equals(ContentImpl.class.getName())) { logger.info("We clear all small contents as well " + objectId); Class typesExtra = SmallContentImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + objectId); Class typesExtraMedium = MediumContentImpl.class; Object[] idsExtraMedium = {new Integer(objectId)}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName())) { Class typesExtra = SmallAvailableServiceBindingImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName())) { Class typesExtra = SmallSiteNodeImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName())) { logger.info("We should delete all images with digitalAssetId " + objectId); DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId)); } else if(Class.forName(className).getName().equals(PublicationImpl.class.getName())) { List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId)); Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator(); while(publicationDetailVOListIterator.hasNext()) { PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next(); logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass()); logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId()); if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName())) { logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId()); Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId()); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small contents as well " + contentId); Class typesExtra = SmallContentImpl.class; - Object[] idsExtra = {new Integer(contentId)}; + Object[] idsExtra = {contentId}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + contentId); Class typesExtraMedium = MediumContentImpl.class; - Object[] idsExtraMedium = {new Integer(contentId)}; + Object[] idsExtraMedium = {contentId}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName())) { Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId(); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small siteNodes as well " + siteNodeId); Class typesExtra = SmallSiteNodeImpl.class; - Object[] idsExtra = {new Integer(siteNodeId)}; + Object[] idsExtra = {siteNodeId}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We also clear the meta info content.."); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId); logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtra = ContentImpl.class; - Object[] idsMetaInfoContentExtra = {new Integer(siteNodeVO.getMetaInfoContentId())}; + Object[] idsMetaInfoContentExtra = {siteNodeVO.getMetaInfoContentId()}; CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra); logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraSmall = SmallContentImpl.class; CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra); logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraMedium = MediumContentImpl.class; CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra); CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null); Database db = CastorDatabaseService.getDatabase(); db.begin(); Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db); List contentVersionIds = new ArrayList(); Iterator contentVersionIterator = content.getContentVersions().iterator(); logger.info("Versions:" + content.getContentVersions().size()); while(contentVersionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next(); contentVersionIds.add(contentVersion.getId()); logger.info("We clear the meta info contentVersion " + contentVersion.getId()); } db.rollback(); db.close(); Iterator contentVersionIdsIterator = contentVersionIds.iterator(); logger.info("Versions:" + contentVersionIds.size()); while(contentVersionIdsIterator.hasNext()) { Integer contentVersionId = (Integer)contentVersionIdsIterator.next(); logger.info("We clear the meta info contentVersion " + contentVersionId); Class metaInfoContentVersionExtra = ContentVersionImpl.class; - Object[] idsMetaInfoContentVersionExtra = {new Integer(contentVersionId)}; + Object[] idsMetaInfoContentVersionExtra = {contentVersionId}; CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra); CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null); } logger.info("After:" + content.getContentVersions().size()); } } } } } } catch (Exception e) { logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e); } } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); } }
false
true
public void run() { logger.info("Run in SelectiveLivePublicationThread...."); int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); try { sleep(publicationDelay); } catch (InterruptedException e1) { e1.printStackTrace(); } logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests()); if(cacheEvictionBeans.size() > 0) { try { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); Iterator i = cacheEvictionBeans.iterator(); while(i.hasNext()) { CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next(); String className = cacheEvictionBean.getClassName(); String objectId = cacheEvictionBean.getObjectId(); String objectName = cacheEvictionBean.getObjectName(); String typeId = cacheEvictionBean.getTypeId(); logger.info("className:" + className); logger.info("objectId:" + objectId); logger.info("objectName:" + objectName); logger.info("typeId:" + typeId); boolean isDependsClass = false; if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName())) isDependsClass = true; CacheController.clearCaches(className, objectId, null); logger.info("Updating className with id:" + className + ":" + objectId); if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM)) { Class type = Class.forName(className); if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName())) { Object[] ids = {objectId}; CacheController.clearCache(type, ids); } else if(!isDependsClass) { Object[] ids = {new Integer(objectId)}; CacheController.clearCache(type, ids); } //If it's an contentVersion we should delete all images it might have generated from attributes. if(Class.forName(className).getName().equals(ContentImpl.class.getName())) { logger.info("We clear all small contents as well " + objectId); Class typesExtra = SmallContentImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + objectId); Class typesExtraMedium = MediumContentImpl.class; Object[] idsExtraMedium = {new Integer(objectId)}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName())) { Class typesExtra = SmallAvailableServiceBindingImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName())) { Class typesExtra = SmallSiteNodeImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName())) { logger.info("We should delete all images with digitalAssetId " + objectId); DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId)); } else if(Class.forName(className).getName().equals(PublicationImpl.class.getName())) { List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId)); Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator(); while(publicationDetailVOListIterator.hasNext()) { PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next(); logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass()); logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId()); if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName())) { logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId()); Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId()); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small contents as well " + contentId); Class typesExtra = SmallContentImpl.class; Object[] idsExtra = {new Integer(contentId)}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + contentId); Class typesExtraMedium = MediumContentImpl.class; Object[] idsExtraMedium = {new Integer(contentId)}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName())) { Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId(); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small siteNodes as well " + siteNodeId); Class typesExtra = SmallSiteNodeImpl.class; Object[] idsExtra = {new Integer(siteNodeId)}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We also clear the meta info content.."); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId); logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtra = ContentImpl.class; Object[] idsMetaInfoContentExtra = {new Integer(siteNodeVO.getMetaInfoContentId())}; CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra); logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraSmall = SmallContentImpl.class; CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra); logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraMedium = MediumContentImpl.class; CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra); CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null); Database db = CastorDatabaseService.getDatabase(); db.begin(); Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db); List contentVersionIds = new ArrayList(); Iterator contentVersionIterator = content.getContentVersions().iterator(); logger.info("Versions:" + content.getContentVersions().size()); while(contentVersionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next(); contentVersionIds.add(contentVersion.getId()); logger.info("We clear the meta info contentVersion " + contentVersion.getId()); } db.rollback(); db.close(); Iterator contentVersionIdsIterator = contentVersionIds.iterator(); logger.info("Versions:" + contentVersionIds.size()); while(contentVersionIdsIterator.hasNext()) { Integer contentVersionId = (Integer)contentVersionIdsIterator.next(); logger.info("We clear the meta info contentVersion " + contentVersionId); Class metaInfoContentVersionExtra = ContentVersionImpl.class; Object[] idsMetaInfoContentVersionExtra = {new Integer(contentVersionId)}; CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra); CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null); } logger.info("After:" + content.getContentVersions().size()); } } } } } } catch (Exception e) { logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e); } } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); }
public void run() { logger.info("Run in SelectiveLivePublicationThread...."); int publicationDelay = 5000; String publicationThreadDelay = CmsPropertyHandler.getPublicationThreadDelay(); if(publicationThreadDelay != null && !publicationThreadDelay.equalsIgnoreCase("") && publicationThreadDelay.indexOf("publicationThreadDelay") == -1) publicationDelay = Integer.parseInt(publicationThreadDelay); logger.info("\n\n\nSleeping " + publicationDelay + "ms.\n\n\n"); try { sleep(publicationDelay); } catch (InterruptedException e1) { e1.printStackTrace(); } logger.info("cacheEvictionBeans.size:" + cacheEvictionBeans.size() + ":" + RequestAnalyser.getRequestAnalyser().getBlockRequests()); if(cacheEvictionBeans.size() > 0) { try { logger.info("setting block"); RequestAnalyser.getRequestAnalyser().setBlockRequests(true); Iterator i = cacheEvictionBeans.iterator(); while(i.hasNext()) { CacheEvictionBean cacheEvictionBean = (CacheEvictionBean)i.next(); String className = cacheEvictionBean.getClassName(); String objectId = cacheEvictionBean.getObjectId(); String objectName = cacheEvictionBean.getObjectName(); String typeId = cacheEvictionBean.getTypeId(); logger.info("className:" + className); logger.info("objectId:" + objectId); logger.info("objectName:" + objectName); logger.info("typeId:" + typeId); boolean isDependsClass = false; if(className != null && className.equalsIgnoreCase(PublicationDetailImpl.class.getName())) isDependsClass = true; CacheController.clearCaches(className, objectId, null); logger.info("Updating className with id:" + className + ":" + objectId); if(className != null && !typeId.equalsIgnoreCase("" + NotificationMessage.SYSTEM)) { Class type = Class.forName(className); if(!isDependsClass && className.equalsIgnoreCase(SystemUserImpl.class.getName()) || className.equalsIgnoreCase(RoleImpl.class.getName()) || className.equalsIgnoreCase(GroupImpl.class.getName())) { Object[] ids = {objectId}; CacheController.clearCache(type, ids); } else if(!isDependsClass) { Object[] ids = {new Integer(objectId)}; CacheController.clearCache(type, ids); } //If it's an contentVersion we should delete all images it might have generated from attributes. if(Class.forName(className).getName().equals(ContentImpl.class.getName())) { logger.info("We clear all small contents as well " + objectId); Class typesExtra = SmallContentImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + objectId); Class typesExtraMedium = MediumContentImpl.class; Object[] idsExtraMedium = {new Integer(objectId)}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(className).getName().equals(AvailableServiceBindingImpl.class.getName())) { Class typesExtra = SmallAvailableServiceBindingImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(SiteNodeImpl.class.getName())) { Class typesExtra = SmallSiteNodeImpl.class; Object[] idsExtra = {new Integer(objectId)}; CacheController.clearCache(typesExtra, idsExtra); } else if(Class.forName(className).getName().equals(DigitalAssetImpl.class.getName())) { logger.info("We should delete all images with digitalAssetId " + objectId); DigitalAssetDeliveryController.getDigitalAssetDeliveryController().deleteDigitalAssets(new Integer(objectId)); } else if(Class.forName(className).getName().equals(PublicationImpl.class.getName())) { List publicationDetailVOList = PublicationController.getController().getPublicationDetailVOList(new Integer(objectId)); Iterator publicationDetailVOListIterator = publicationDetailVOList.iterator(); while(publicationDetailVOListIterator.hasNext()) { PublicationDetailVO publicationDetailVO = (PublicationDetailVO)publicationDetailVOListIterator.next(); logger.info("publicationDetailVO.getEntityClass():" + publicationDetailVO.getEntityClass()); logger.info("publicationDetailVO.getEntityId():" + publicationDetailVO.getEntityId()); if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(ContentVersion.class.getName())) { logger.info("We clear all caches having references to contentVersion: " + publicationDetailVO.getEntityId()); Integer contentId = ContentVersionController.getContentVersionController().getContentIdForContentVersion(publicationDetailVO.getEntityId()); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small contents as well " + contentId); Class typesExtra = SmallContentImpl.class; Object[] idsExtra = {contentId}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We clear all medium contents as well " + contentId); Class typesExtraMedium = MediumContentImpl.class; Object[] idsExtraMedium = {contentId}; CacheController.clearCache(typesExtraMedium, idsExtraMedium); } else if(Class.forName(publicationDetailVO.getEntityClass()).getName().equals(SiteNodeVersion.class.getName())) { Integer siteNodeId = SiteNodeVersionController.getController().getSiteNodeVersionVOWithId(publicationDetailVO.getEntityId()).getSiteNodeId(); CacheController.clearCaches(publicationDetailVO.getEntityClass(), publicationDetailVO.getEntityId().toString(), null); logger.info("We clear all small siteNodes as well " + siteNodeId); Class typesExtra = SmallSiteNodeImpl.class; Object[] idsExtra = {siteNodeId}; CacheController.clearCache(typesExtra, idsExtra); logger.info("We also clear the meta info content.."); SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(siteNodeId); logger.info("We clear all contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtra = ContentImpl.class; Object[] idsMetaInfoContentExtra = {siteNodeVO.getMetaInfoContentId()}; CacheController.clearCache(metaInfoContentExtra, idsMetaInfoContentExtra); logger.info("We clear all small contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraSmall = SmallContentImpl.class; CacheController.clearCache(metaInfoContentExtraSmall, idsMetaInfoContentExtra); logger.info("We clear all medium contents as well " + siteNodeVO.getMetaInfoContentId()); Class metaInfoContentExtraMedium = MediumContentImpl.class; CacheController.clearCache(metaInfoContentExtraMedium, idsMetaInfoContentExtra); CacheController.clearCaches(ContentImpl.class.getName(), siteNodeVO.getMetaInfoContentId().toString(), null); Database db = CastorDatabaseService.getDatabase(); db.begin(); Content content = ContentController.getContentController().getContentWithId(siteNodeVO.getMetaInfoContentId(), db); List contentVersionIds = new ArrayList(); Iterator contentVersionIterator = content.getContentVersions().iterator(); logger.info("Versions:" + content.getContentVersions().size()); while(contentVersionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)contentVersionIterator.next(); contentVersionIds.add(contentVersion.getId()); logger.info("We clear the meta info contentVersion " + contentVersion.getId()); } db.rollback(); db.close(); Iterator contentVersionIdsIterator = contentVersionIds.iterator(); logger.info("Versions:" + contentVersionIds.size()); while(contentVersionIdsIterator.hasNext()) { Integer contentVersionId = (Integer)contentVersionIdsIterator.next(); logger.info("We clear the meta info contentVersion " + contentVersionId); Class metaInfoContentVersionExtra = ContentVersionImpl.class; Object[] idsMetaInfoContentVersionExtra = {contentVersionId}; CacheController.clearCache(metaInfoContentVersionExtra, idsMetaInfoContentVersionExtra); CacheController.clearCaches(ContentVersionImpl.class.getName(), contentVersionId.toString(), null); } logger.info("After:" + content.getContentVersions().size()); } } } } } } catch (Exception e) { logger.error("An error occurred in the SelectiveLivePublicationThread:" + e.getMessage(), e); } } logger.info("released block \n\n DONE---"); RequestAnalyser.getRequestAnalyser().setBlockRequests(false); }
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/AutocompleteVisitor.java b/src/main/java/com/redhat/ceylon/compiler/js/AutocompleteVisitor.java index 4d84194d..5c999fa1 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/AutocompleteVisitor.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/AutocompleteVisitor.java @@ -1,156 +1,156 @@ package com.redhat.ceylon.compiler.js; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.redhat.ceylon.compiler.typechecker.TypeChecker; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.compiler.typechecker.model.DeclarationWithProximity; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Identifier; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; /** A visitor that can return a list of suggestions given a location on the AST. * * @author Enrique Zamudio */ public class AutocompleteVisitor extends Visitor { private final int row; private final int col; private final TypeChecker checker; private String text; private Node node; private int pass; /** Create a new instance that will look for suggestions for the node at the specified location. */ public AutocompleteVisitor(int row, int col, TypeChecker tc) { this.row = row; this.col = col; checker = tc; } public int getRow() { return row; } public int getColumn() { return col; } public Node findNode(AutocompleteUnitValidator callback) { //First pass, to find the identifier pass = 1; for (PhasedUnit pu : checker.getPhasedUnits().getPhasedUnits()) { if (callback.processUnit(pu)) { pu.getCompilationUnit().visit(this); } } //Second pass, to find its parent if (node != null) { pass = 2; for (PhasedUnit pu : checker.getPhasedUnits().getPhasedUnits()) { if (callback.processUnit(pu)) { pu.getCompilationUnit().visit(this); } } } return node; } public Node findNode() { return findNode(new DefaultAutocompleteUnitValidator()); } /** Checks if the identifier contains the location we're interested in. */ @Override public void visit(Identifier that) { if (pass == 1 && that.getToken().getLine() == row) { final int col0 = that.getToken().getCharPositionInLine(); final int col1 = Math.max(col0+that.getText().length()-1, col0); if (col >= col0 && col <= col1) { node = that; text = node.getText(); } } super.visit(that); } @Override public void visitAny(Node that) { if (pass == 2 && node != null) { for (Node n : that.getChildren()) { if (n.getChildren().contains(node)) { node = n; pass = 3; break; } } } super.visitAny(that); } /** Returns the node containing the specified location, if any. */ public Node getNodeAtLocation() { return node; } /** Returns the text belonging to the node at the specified location. */ public String getTextAtLocation() { return text; } /** Looks for matching declarations in the specified phased unit, recursively navigating through its dependent units. */ private void addCompletions(Map<String, DeclarationWithProximity> comps, Set<PhasedUnit> units, Set<com.redhat.ceylon.compiler.typechecker.model.Package> packs, PhasedUnit pu) { if (!packs.contains(pu.getPackage())) { Map<String, DeclarationWithProximity> c2 = pu.getPackage().getMatchingDeclarations(node.getUnit(), text, 100); comps.putAll(c2); packs.add(pu.getPackage()); } if (!units.contains(pu)) { Map<String, DeclarationWithProximity> c2 = node.getScope().getMatchingDeclarations(pu.getUnit(), text, 100); comps.putAll(c2); units.add(pu); } /* COMMENTING OUT until I figure out if I really need to do this and how to get the units by name/path * for (String sub : pu.getUnit().getDependentsOf()) { addCompletions(comps, units, packs, sub); }*/ } /** Looks for declarations matching the node's text and returns them as strings. */ public List<String> getCompletions() { Map<String, DeclarationWithProximity> comps = new HashMap<String, DeclarationWithProximity>(); if (node != null) { HashSet<PhasedUnit> units = new HashSet<PhasedUnit>(); HashSet<com.redhat.ceylon.compiler.typechecker.model.Package> packs = new HashSet<com.redhat.ceylon.compiler.typechecker.model.Package>(); if (node instanceof QualifiedMemberExpression) { QualifiedMemberExpression exp = (QualifiedMemberExpression)node; ProducedType type = exp.getPrimary().getTypeModel(); - Map<String, DeclarationWithProximity> c2 = type.getDeclaration().getMatchingMemberDeclarations(text, 0); + Map<String, DeclarationWithProximity> c2 = type.getDeclaration().getMatchingMemberDeclarations(null, text, 0); comps.putAll(c2); } else { for (PhasedUnits pus : checker.getPhasedUnitsOfDependencies()) { for (PhasedUnit pu : pus.getPhasedUnits()) { addCompletions(comps, units, packs, pu); } } } } return Arrays.asList(comps.keySet().toArray(new String[0])); } /** Callbacks can implement this to tell the visitor if a unit should be processed or not. */ public interface AutocompleteUnitValidator { public boolean processUnit(PhasedUnit pu); } private class DefaultAutocompleteUnitValidator implements AutocompleteUnitValidator { @Override public boolean processUnit(PhasedUnit pu) { return true; } } }
true
true
public List<String> getCompletions() { Map<String, DeclarationWithProximity> comps = new HashMap<String, DeclarationWithProximity>(); if (node != null) { HashSet<PhasedUnit> units = new HashSet<PhasedUnit>(); HashSet<com.redhat.ceylon.compiler.typechecker.model.Package> packs = new HashSet<com.redhat.ceylon.compiler.typechecker.model.Package>(); if (node instanceof QualifiedMemberExpression) { QualifiedMemberExpression exp = (QualifiedMemberExpression)node; ProducedType type = exp.getPrimary().getTypeModel(); Map<String, DeclarationWithProximity> c2 = type.getDeclaration().getMatchingMemberDeclarations(text, 0); comps.putAll(c2); } else { for (PhasedUnits pus : checker.getPhasedUnitsOfDependencies()) { for (PhasedUnit pu : pus.getPhasedUnits()) { addCompletions(comps, units, packs, pu); } } } } return Arrays.asList(comps.keySet().toArray(new String[0])); }
public List<String> getCompletions() { Map<String, DeclarationWithProximity> comps = new HashMap<String, DeclarationWithProximity>(); if (node != null) { HashSet<PhasedUnit> units = new HashSet<PhasedUnit>(); HashSet<com.redhat.ceylon.compiler.typechecker.model.Package> packs = new HashSet<com.redhat.ceylon.compiler.typechecker.model.Package>(); if (node instanceof QualifiedMemberExpression) { QualifiedMemberExpression exp = (QualifiedMemberExpression)node; ProducedType type = exp.getPrimary().getTypeModel(); Map<String, DeclarationWithProximity> c2 = type.getDeclaration().getMatchingMemberDeclarations(null, text, 0); comps.putAll(c2); } else { for (PhasedUnits pus : checker.getPhasedUnitsOfDependencies()) { for (PhasedUnit pu : pus.getPhasedUnits()) { addCompletions(comps, units, packs, pu); } } } } return Arrays.asList(comps.keySet().toArray(new String[0])); }
diff --git a/src/main/java/org/perfcake/validation/ValidatorManager.java b/src/main/java/org/perfcake/validation/ValidatorManager.java index cdacd60b..0699864b 100644 --- a/src/main/java/org/perfcake/validation/ValidatorManager.java +++ b/src/main/java/org/perfcake/validation/ValidatorManager.java @@ -1,266 +1,266 @@ /* * -----------------------------------------------------------------------\ * PerfCake *   * Copyright (C) 2010 - 2013 the original author or authors. *   * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -----------------------------------------------------------------------/ */ package org.perfcake.validation; import java.io.File; import java.io.IOException; import java.util.Queue; import java.util.TreeMap; import org.apache.log4j.Logger; import org.perfcake.PerfCakeException; import org.perfcake.message.Message; import org.perfcake.message.ReceivedMessage; /** * A manager of validator that should validate message responses. * * @author Martin Večeřa <[email protected]> * @author Lucie Fabriková <[email protected]> */ public class ValidatorManager { /** * A map of validators: validator id => validator instance */ private final TreeMap<String, MessageValidator> validators = new TreeMap<>(); /** * An internal thread that takes one response after another and validates them. */ private Thread validationThread = null; /** * Indicates whether the validation is finished. Starts with true as there is no validation running at the beginning. */ private boolean finished = true; /** * Were all messages validated properly so far? */ private boolean allMessagesValid = true; /** * Is validation enabled? */ private boolean enabled = false; /** * At the end, when there is nothing else to do, we can go through the remaining responses faster. Otherwise, the validation * thread has some sleep for it not to influence measurement. */ private boolean fastForward = false; /** * A logger. */ private final Logger log = Logger.getLogger(ValidatorManager.class); /** * A queue with the message responses. */ private Queue<ReceivedMessage> resultMessages; /** * Creates a new validator menager. The message responses are store in a file queue in a temporary file. * * @throws PerfCakeException * When it was not possible to initialize the message store. */ public ValidatorManager() throws PerfCakeException { try { final File tmpFile = File.createTempFile("perfcake", "queue"); tmpFile.deleteOnExit(); setQueueFile(tmpFile); } catch (final IOException e) { throw new PerfCakeException("Cannot create a file queue for messages to be validated: ", e); } } /** * Sets a different location of the file queue for storing message responses. * * @param queueFile * The new location of the file queue. * @throws PerfCakeException * When it was not possible to initialize the file queue or there is a running validation. */ public void setQueueFile(final File queueFile) throws PerfCakeException { if (isFinished()) { resultMessages = new FileQueue<ReceivedMessage>(queueFile); } else { throw new PerfCakeException("It is not possible to change the file queue while there is a running validation."); } } /** * Adds a new message validator. * * @param validatorId * A string id of the new validator. * @param messageValidator * A validator instance. */ public void addValidator(final String validatorId, final MessageValidator messageValidator) { validators.put(validatorId, messageValidator); } /** * Gets the validator with the given id. * * @param validatorId * A string id of the validator. * @return The validator instance or null if there is no such validator with the given id. */ public MessageValidator getValidator(final String validatorId) { return validators.get(validatorId); } /** * Starts the validation process. This mainly means starting a new validator thread. */ public void startValidation() { if (validationThread == null || !validationThread.isAlive()) { validationThread = new Thread(new ValidationThread()); validationThread.setDaemon(true); // we do not want to block JVM validationThread.start(); } } /** * Wait for the validation to be finished. The call is blocked until the validator thread finishes execution or an exception * is thrown. Internally, this joins the validator thread to the current thread. * * @throws InterruptedException * If the validator thread was interrupted. */ public void waitForValidation() throws InterruptedException { if (validationThread != null) { fastForward = true; validationThread.join(); } } /** * Interrupts the validator thread immediately. There might be remaining unfinished validations. */ public void terminateNow() { if (validationThread != null) { validationThread.interrupt(); } } /** * Internal class representing the validator thread. The thread validates one message with all registered validators and then * sleeps for 500ms. This is needed for the validation not to influence measurement. After a call to {@link #waitForValidation()} the * sleeps are skipped. */ private class ValidationThread implements Runnable { @Override public void run() { boolean isMessageValid = false; ReceivedMessage receivedMessage = null; finished = false; allMessagesValid = true; fastForward = false; if (validators.isEmpty()) { log.warn("No validators set in scenario."); return; } try { while (!validationThread.isInterrupted() && (receivedMessage = resultMessages.poll()) != null) { - while (receivedMessage != null) { + if (receivedMessage != null) { for (final MessageValidator validator : receivedMessage.getSentMessage().getValidators()) { isMessageValid = validator.isValid(new Message(receivedMessage.getPayload())); if (log.isTraceEnabled()) { log.trace(String.format("Message response %s validated with %s returns %s.", receivedMessage.getPayload().toString(), validator.toString(), String.valueOf(isMessageValid))); } allMessagesValid &= isMessageValid; } } if (!fastForward) { Thread.sleep(500); // we do not want to block senders } } } catch (final InterruptedException ex) { // never mind, we have been asked to terminate } if (log.isInfoEnabled()) { log.info("The validator thread finished with result " + (allMessagesValid ? "all messages are valid." : "there were validation errors.")); } finished = true; } } /** * Adds a new message response to be validated. * * @param receivedMessage * The message response to be validated. */ public void addToResultMessages(final ReceivedMessage receivedMessage) { resultMessages.add(receivedMessage); } /** * Gets the number of messages that needs to be validated. * * @return The current size of the file queue with messages waiting for validation. */ public int getSize() { return resultMessages.size(); } /** * Is validation facility enabled? * * @return True if validation is enabled. */ public boolean isEnabled() { return enabled; } /** * Enables/disables validation. This only takes effect before the validation is started. * * @param enabled */ public void setEnabled(final boolean enabled) { assert enabled == true || finished == true : "Validation cannot be disabled while the validation is in progress."; // we know this is about to disable the validation since it is running already this.enabled = enabled; } /** * Determines whether the validation process finished already. * * @return True if the validation finished or was not started yet. */ public boolean isFinished() { return finished; } }
true
true
public void run() { boolean isMessageValid = false; ReceivedMessage receivedMessage = null; finished = false; allMessagesValid = true; fastForward = false; if (validators.isEmpty()) { log.warn("No validators set in scenario."); return; } try { while (!validationThread.isInterrupted() && (receivedMessage = resultMessages.poll()) != null) { while (receivedMessage != null) { for (final MessageValidator validator : receivedMessage.getSentMessage().getValidators()) { isMessageValid = validator.isValid(new Message(receivedMessage.getPayload())); if (log.isTraceEnabled()) { log.trace(String.format("Message response %s validated with %s returns %s.", receivedMessage.getPayload().toString(), validator.toString(), String.valueOf(isMessageValid))); } allMessagesValid &= isMessageValid; } } if (!fastForward) { Thread.sleep(500); // we do not want to block senders } } } catch (final InterruptedException ex) { // never mind, we have been asked to terminate } if (log.isInfoEnabled()) { log.info("The validator thread finished with result " + (allMessagesValid ? "all messages are valid." : "there were validation errors.")); } finished = true; }
public void run() { boolean isMessageValid = false; ReceivedMessage receivedMessage = null; finished = false; allMessagesValid = true; fastForward = false; if (validators.isEmpty()) { log.warn("No validators set in scenario."); return; } try { while (!validationThread.isInterrupted() && (receivedMessage = resultMessages.poll()) != null) { if (receivedMessage != null) { for (final MessageValidator validator : receivedMessage.getSentMessage().getValidators()) { isMessageValid = validator.isValid(new Message(receivedMessage.getPayload())); if (log.isTraceEnabled()) { log.trace(String.format("Message response %s validated with %s returns %s.", receivedMessage.getPayload().toString(), validator.toString(), String.valueOf(isMessageValid))); } allMessagesValid &= isMessageValid; } } if (!fastForward) { Thread.sleep(500); // we do not want to block senders } } } catch (final InterruptedException ex) { // never mind, we have been asked to terminate } if (log.isInfoEnabled()) { log.info("The validator thread finished with result " + (allMessagesValid ? "all messages are valid." : "there were validation errors.")); } finished = true; }