code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on 25/08/2005 * * @author Fabio Zadrozny */ package com.python.pydev.codecompletion.participant; import java.io.File; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.jface.text.Document; import org.python.pydev.ast.codecompletion.PyCodeCompletion; import org.python.pydev.ast.codecompletion.PyCodeCompletionPreferences; import org.python.pydev.ast.codecompletion.revisited.modules.SourceToken; import org.python.pydev.core.IToken; import org.python.pydev.core.TestDependent; import org.python.pydev.core.TokensList; import org.python.pydev.core.proposals.CompletionProposalFactory; import org.python.pydev.editor.actions.PySelectionTest; import org.python.pydev.editor.codecompletion.proposals.CtxInsensitiveImportComplProposal; import org.python.pydev.editor.codecompletion.proposals.DefaultCompletionProposalFactory; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.NameTok; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.shared_core.code_completion.ICompletionProposalHandle; import org.python.pydev.shared_core.preferences.InMemoryEclipsePreferences; import com.python.pydev.analysis.AnalysisPreferences; import com.python.pydev.analysis.additionalinfo.AdditionalInfoTestsBase; import com.python.pydev.codecompletion.ctxinsensitive.CtxParticipant; public class CompletionParticipantTest extends AdditionalInfoTestsBase { public static void main(String[] args) { CompletionParticipantTest test = new CompletionParticipantTest(); try { test.setUp(); test.testImportCompletionFromZip(); test.tearDown(); junit.textui.TestRunner.run(CompletionParticipantTest.class); } catch (Throwable e) { e.printStackTrace(); } } @Override public void setUp() throws Exception { // forceAdditionalInfoRecreation = true; -- just for testing purposes super.setUp(); codeCompletion = new PyCodeCompletion(); CompletionProposalFactory.set(new DefaultCompletionProposalFactory()); } @Override public void tearDown() throws Exception { super.tearDown(); PyCodeCompletionPreferences.getPreferencesForTests = null; CompletionProposalFactory.set(null); } @Override protected String getSystemPythonpathPaths() { return TestDependent.getCompletePythonLib(true, isPython3Test()) + "|" + TestDependent.TEST_PYSRC_TESTING_LOC + "myzipmodule.zip" + "|" + TestDependent.TEST_PYSRC_TESTING_LOC + "myeggmodule.egg"; } public void testImportCompletion() throws Exception { participant = new ImportsCompletionParticipant(); //check simple ICompletionProposalHandle[] proposals = requestCompl( "unittest", -1, -1, new String[] { "unittest", "unittest - testlib" }); //the unittest module and testlib.unittest Document document = new Document("unittest"); ICompletionProposalHandle p0 = null; ICompletionProposalHandle p1 = null; for (ICompletionProposalHandle p : proposals) { String displayString = p.getDisplayString(); if (displayString.equals("unittest")) { p0 = p; } else if (displayString.equals("unittest - testlib")) { p1 = p; } } if (p0 == null) { fail("Could not find unittest import"); } if (p1 == null) { fail("Could not find unittest - testlib import"); } ((CtxInsensitiveImportComplProposal) p0).indentString = " "; ((CtxInsensitiveImportComplProposal) p0).apply(document, ' ', 0, 8); PySelectionTest.checkStrEquals("import unittest\r\nunittest", document.get()); document = new Document("unittest"); ((CtxInsensitiveImportComplProposal) p1).indentString = " "; ((CtxInsensitiveImportComplProposal) p1).apply(document, ' ', 0, 8); PySelectionTest.checkStrEquals("from testlib import unittest\r\nunittest", document.get()); document = new Document("unittest"); final IEclipsePreferences prefs = new InMemoryEclipsePreferences(); PyCodeCompletionPreferences.getPreferencesForTests = () -> prefs; document = new Document("unittest"); prefs.putBoolean(PyCodeCompletionPreferences.APPLY_COMPLETION_ON_DOT, false); ((CtxInsensitiveImportComplProposal) p1).indentString = " "; ((CtxInsensitiveImportComplProposal) p1).apply(document, '.', 0, 8); PySelectionTest.checkStrEquals("unittest.", document.get()); document = new Document("unittest"); prefs.putBoolean(PyCodeCompletionPreferences.APPLY_COMPLETION_ON_DOT, true); ((CtxInsensitiveImportComplProposal) p1).indentString = " "; ((CtxInsensitiveImportComplProposal) p1).apply(document, '.', 0, 8); PySelectionTest.checkStrEquals("from testlib import unittest\r\nunittest.", document.get()); //for imports, the behavior never changes AnalysisPreferences.TESTS_DO_IGNORE_IMPORT_STARTING_WITH_UNDER = true; try { proposals = requestCompl("_priv3", new String[] { "_priv3 - relative.rel1._priv1._priv2" }); document = new Document("_priv3"); ((CtxInsensitiveImportComplProposal) proposals[0]).indentString = " "; ((CtxInsensitiveImportComplProposal) proposals[0]).apply(document, ' ', 0, 6); PySelectionTest.checkStrEquals("from relative.rel1._priv1._priv2 import _priv3\r\n_priv3", document.get()); } finally { AnalysisPreferences.TESTS_DO_IGNORE_IMPORT_STARTING_WITH_UNDER = false; } //check on actual file requestCompl(new File(TestDependent.TEST_PYSRC_TESTING_LOC + "/testlib/unittest/guitestcase.py"), "guite", -1, 0, new String[] {}); Import importTok = new Import(new aliasType[] { new aliasType(new NameTok("unittest", NameTok.ImportModule), null) }); this.imports = new TokensList(new IToken[] { new SourceToken(importTok, "unittest", "", "", "", null) }); requestCompl("import unittest\nunittest", new String[] {}); //none because the import for unittest is already there requestCompl("import unittest\nunittes", new String[] {}); //the local import for unittest (won't actually show anything because we're only exercising the participant test) this.imports = null; } public void testImportCompletionFromZip2() throws Exception { participant = new ImportsCompletionParticipant(); ICompletionProposalHandle[] proposals = requestCompl("myzip", -1, -1, new String[] {}); assertContains("myzipfile - myzipmodule", proposals); assertContains("myzipmodule", proposals); proposals = requestCompl("myegg", -1, -1, new String[] {}); assertContains("myeggfile - myeggmodule", proposals); assertContains("myeggmodule", proposals); } public void testImportCompletionFromZip() throws Exception { participant = new CtxParticipant(); ICompletionProposalHandle[] proposals = requestCompl("myzipc", -1, -1, new String[] {}); assertContains("MyZipClass - myzipmodule.myzipfile", proposals); proposals = requestCompl("myegg", -1, -1, new String[] {}); assertContains("MyEggClass - myeggmodule.myeggfile", proposals); } public void testImportCompletion2() throws Exception { participant = new CtxParticipant(); ICompletionProposalHandle[] proposals = requestCompl("xml", -1, -1, new String[] {}); assertNotContains("xml - xmlrpclib", proposals); requestCompl(new File(TestDependent.TEST_PYSRC_TESTING_LOC + "/testlib/unittest/guitestcase.py"), "guite", -1, 0, new String[] {}); //the behavior changes for tokens on modules AnalysisPreferences.TESTS_DO_IGNORE_IMPORT_STARTING_WITH_UNDER = true; try { proposals = requestCompl("Priv3", new String[] { "Priv3 - relative.rel1._priv1._priv2._priv3" }); Document document = new Document("Priv3"); ((CtxInsensitiveImportComplProposal) proposals[0]).indentString = " "; ((CtxInsensitiveImportComplProposal) proposals[0]).apply(document, ' ', 0, 5); PySelectionTest.checkStrEquals("from relative.rel1 import Priv3\r\nPriv3", document.get()); } finally { AnalysisPreferences.TESTS_DO_IGNORE_IMPORT_STARTING_WITH_UNDER = false; } } }
fabioz/Pydev
plugins/org.python.pydev/tests_codecompletion/com/python/pydev/codecompletion/participant/CompletionParticipantTest.java
Java
epl-1.0
8,997
package treehou.se.habit.ui.util; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.mikepenz.community_material_typeface_library.CommunityMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.typeface.IIcon; import java.util.ArrayList; import java.util.List; import treehou.se.habit.R; import treehou.se.habit.util.Util; /** * Fragment for picking categories of icons. */ public class CategoryPickerFragment extends Fragment { private RecyclerView lstIcons; private CategoryAdapter adapter; private ViewGroup container; public static CategoryPickerFragment newInstance() { CategoryPickerFragment fragment = new CategoryPickerFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public CategoryPickerFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_icon_picker, null); lstIcons = (RecyclerView) rootView.findViewById(R.id.lst_categories); lstIcons.setItemAnimator(new DefaultItemAnimator()); lstIcons.setLayoutManager(new LinearLayoutManager(getActivity())); // Hookup list of categories adapter = new CategoryAdapter(getActivity()); adapter.add(new CategoryPicker(CommunityMaterial.Icon.cmd_play, getString(R.string.media), Util.IconCategory.MEDIA)); adapter.add(new CategoryPicker(CommunityMaterial.Icon.cmd_alarm, getString(R.string.sensor), Util.IconCategory.SENSORS)); adapter.add(new CategoryPicker(CommunityMaterial.Icon.cmd_power, getString(R.string.command), Util.IconCategory.COMMANDS)); adapter.add(new CategoryPicker(CommunityMaterial.Icon.cmd_arrow_up, getString(R.string.arrows), Util.IconCategory.ARROWS)); adapter.add(new CategoryPicker(CommunityMaterial.Icon.cmd_view_module, getString(R.string.all), Util.IconCategory.ALL)); lstIcons.setAdapter(adapter); this.container = container; return rootView; } private class CategoryPicker { private IIcon icon; private String category; private Util.IconCategory id; public CategoryPicker(IIcon icon, String category, Util.IconCategory id) { this.icon = icon; this.category = category; this.id = id; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public IIcon getIcon() { return icon; } public void setIcon(IIcon icon) { this.icon = icon; } public Util.IconCategory getId() { return id; } public void setId(Util.IconCategory id) { this.id = id; } } private class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private List<CategoryPicker> categories = new ArrayList<>(); class CategoryHolder extends RecyclerView.ViewHolder { public ImageView imgIcon; public TextView lblCategory; public CategoryHolder(View itemView) { super(itemView); imgIcon = (ImageView) itemView.findViewById(R.id.img_menu); lblCategory = (TextView) itemView.findViewById(R.id.lbl_label); } } public CategoryAdapter(Context context) { this.context = context; } public void add(CategoryPicker category){ categories.add(category); notifyDataSetChanged(); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View itemView = inflater.inflate(R.layout.item_category, parent, false); return new CategoryHolder(itemView); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final CategoryPicker item = categories.get(position); CategoryHolder catHolder = (CategoryHolder) holder; IconicsDrawable drawable = new IconicsDrawable(getActivity(), item.getIcon()).color(Color.BLACK).sizeDp(50); catHolder.imgIcon.setImageDrawable(drawable); catHolder.lblCategory.setText(item.getCategory()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().getSupportFragmentManager().beginTransaction() .replace(container.getId(), IconPickerFragment.newInstance(item.getId())) .addToBackStack(null) .commit(); } }); } @Override public int getItemCount() { return categories.size(); } } }
pravussum/3House
mobile/src/main/java/treehou/se/habit/ui/util/CategoryPickerFragment.java
Java
epl-1.0
5,601
/******************************************************************************* * Copyright 2009 Regents of the University of Minnesota. All rights * reserved. * Copyright 2009 Mayo Foundation for Medical Education and Research. * All rights reserved. * * This program is made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * 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 INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS * OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A * PARTICULAR PURPOSE. See the License for the specific language * governing permissions and limitations under the License. * * Contributors: * Minnesota Supercomputing Institute - initial API and implementation ******************************************************************************/ package edu.umn.msi.tropix.persistence.service; import javax.annotation.Nullable; import edu.umn.msi.tropix.models.ITraqQuantitationAnalysis; import edu.umn.msi.tropix.persistence.aop.Modifies; import edu.umn.msi.tropix.persistence.aop.PersistenceMethod; import edu.umn.msi.tropix.persistence.aop.Reads; import edu.umn.msi.tropix.persistence.aop.UserId; public interface ITraqQuantitationAnalysisService { @PersistenceMethod ITraqQuantitationAnalysis createQuantitationAnalysis(@UserId String userId, @Nullable @Modifies String destinationId, ITraqQuantitationAnalysis quantitationAnalysis, @Modifies String dataReportId, @Reads String[] inputRunIds, @Nullable @Reads String trainingId, @Modifies String outputFileId); }
jmchilton/TINT
projects/TropixPersistence/src/service-api/edu/umn/msi/tropix/persistence/service/ITraqQuantitationAnalysisService.java
Java
epl-1.0
1,827
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on May 24, 2005 * * @author Fabio Zadrozny */ package org.python.pydev.editor.codecompletion.revisited; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.python.pydev.core.DeltaSaver; import org.python.pydev.core.ICodeCompletionASTManager; import org.python.pydev.core.IInterpreterInfo; import org.python.pydev.core.IInterpreterManager; import org.python.pydev.core.IModule; import org.python.pydev.core.IModulesManager; import org.python.pydev.core.IProjectModulesManager; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.ISystemModulesManager; import org.python.pydev.core.ModulesKey; import org.python.pydev.core.log.Log; import org.python.pydev.editor.codecompletion.revisited.javaintegration.JavaProjectModulesManagerCreator; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.shared_core.io.FileUtils; import org.python.pydev.shared_core.string.StringUtils; import org.python.pydev.shared_core.structure.Tuple; /** * @author Fabio Zadrozny */ public final class ProjectModulesManager extends ModulesManagerWithBuild implements IProjectModulesManager { private static final boolean DEBUG_MODULES = false; //these attributes must be set whenever this class is restored. private volatile IProject project; private volatile IPythonNature nature; public ProjectModulesManager() { } /** * @see org.python.pydev.core.IProjectModulesManager#setProject(org.eclipse.core.resources.IProject, boolean) */ @Override public void setProject(IProject project, IPythonNature nature, boolean restoreDeltas) { this.project = project; this.nature = nature; File completionsCacheDir = this.nature.getCompletionsCacheDir(); if (completionsCacheDir == null) { return; //project was deleted. } DeltaSaver<ModulesKey> d = this.deltaSaver = new DeltaSaver<ModulesKey>(completionsCacheDir, "v1_astdelta", readFromFileMethod, toFileMethod); if (!restoreDeltas) { d.clearAll(); //remove any existing deltas } else { d.processDeltas(this); //process the current deltas (clears current deltas automatically and saves it when the processing is concluded) } } // ------------------------ delta processing /** * @see org.python.pydev.core.IProjectModulesManager#endProcessing() */ @Override public void endProcessing() { //save it with the updated info nature.saveAstManager(); } // ------------------------ end delta processing /** * @see org.python.pydev.core.IProjectModulesManager#setPythonNature(org.python.pydev.core.IPythonNature) */ @Override public void setPythonNature(IPythonNature nature) { this.nature = nature; } /** * @see org.python.pydev.core.IProjectModulesManager#getNature() */ @Override public IPythonNature getNature() { return nature; } /** * @param defaultSelectedInterpreter * @see org.python.pydev.core.IProjectModulesManager#getSystemModulesManager() */ @Override public ISystemModulesManager getSystemModulesManager() { if (nature == null) { Log.log("Nature still not set"); return null; //still not set (initialization) } try { return nature.getProjectInterpreter().getModulesManager(); } catch (Exception e1) { return null; } } /** * @see org.python.pydev.core.IProjectModulesManager#getAllModuleNames(boolean addDependencies, String partStartingWithLowerCase) */ @Override public Set<String> getAllModuleNames(boolean addDependencies, String partStartingWithLowerCase) { if (addDependencies) { Set<String> s = new HashSet<String>(); IModulesManager[] managersInvolved = this.getManagersInvolved(true); for (int i = 0; i < managersInvolved.length; i++) { s.addAll(managersInvolved[i].getAllModuleNames(false, partStartingWithLowerCase)); } return s; } else { return super.getAllModuleNames(addDependencies, partStartingWithLowerCase); } } /** * @return all the modules that start with some token (from this manager and others involved) */ @Override public SortedMap<ModulesKey, ModulesKey> getAllModulesStartingWith(String strStartingWith) { SortedMap<ModulesKey, ModulesKey> ret = new TreeMap<ModulesKey, ModulesKey>(); IModulesManager[] managersInvolved = this.getManagersInvolved(true); for (int i = 0; i < managersInvolved.length; i++) { ret.putAll(managersInvolved[i].getAllDirectModulesStartingWith(strStartingWith)); } return ret; } /** * @see org.python.pydev.core.IProjectModulesManager#getModule(java.lang.String, org.python.pydev.plugin.nature.PythonNature, boolean) */ @Override public IModule getModule(String name, IPythonNature nature, boolean dontSearchInit) { return getModule(name, nature, true, dontSearchInit); } /** * When looking for relative, we do not check dependencies */ @Override public IModule getRelativeModule(String name, IPythonNature nature) { return super.getModule(false, name, nature, true); //cannot be a compiled module } /** * @see org.python.pydev.core.IProjectModulesManager#getModule(java.lang.String, org.python.pydev.plugin.nature.PythonNature, boolean, boolean) */ @Override public IModule getModule(String name, IPythonNature nature, boolean checkSystemManager, boolean dontSearchInit) { Tuple<IModule, IModulesManager> ret = getModuleAndRelatedModulesManager(name, nature, checkSystemManager, dontSearchInit); if (ret != null) { return ret.o1; } return null; } /** * @return a tuple with the IModule requested and the IModulesManager that contained that module. */ @Override public Tuple<IModule, IModulesManager> getModuleAndRelatedModulesManager(String name, IPythonNature nature, boolean checkSystemManager, boolean dontSearchInit) { IModule module = null; IModulesManager[] managersInvolved = this.getManagersInvolved(true); //only get the system manager here (to avoid recursion) for (IModulesManager m : managersInvolved) { if (m instanceof ISystemModulesManager) { module = ((ISystemModulesManager) m).getBuiltinModule(name, dontSearchInit); if (module != null) { if (DEBUG_MODULES) { System.out.println("Trying to get:" + name + " - " + " returned builtin:" + module + " - " + m.getClass()); } return new Tuple<IModule, IModulesManager>(module, m); } } } for (IModulesManager m : managersInvolved) { if (m instanceof IProjectModulesManager) { IProjectModulesManager pM = (IProjectModulesManager) m; module = pM.getModuleInDirectManager(name, nature, dontSearchInit); } else if (m instanceof ISystemModulesManager) { ISystemModulesManager systemModulesManager = (ISystemModulesManager) m; module = systemModulesManager.getModuleWithoutBuiltins(name, nature, dontSearchInit); } else { throw new RuntimeException("Unexpected: " + m); } if (module != null) { if (DEBUG_MODULES) { System.out.println("Trying to get:" + name + " - " + " returned:" + module + " - " + m.getClass()); } return new Tuple<IModule, IModulesManager>(module, m); } } if (DEBUG_MODULES) { System.out.println("Trying to get:" + name + " - " + " returned:null - " + this.getClass()); } return null; } /** * Only searches the modules contained in the direct modules manager. */ @Override public IModule getModuleInDirectManager(String name, IPythonNature nature, boolean dontSearchInit) { return super.getModule(name, nature, dontSearchInit); } @Override protected String getResolveModuleErr(IResource member) { return "Unable to find the path " + member + " in the project were it\n" + "is added as a source folder for pydev (project: " + project.getName() + ")"; } public String resolveModuleOnlyInProjectSources(String fileAbsolutePath, boolean addExternal) throws CoreException { String onlyProjectPythonPathStr = this.nature.getPythonPathNature().getOnlyProjectPythonPathStr(addExternal); List<String> pathItems = StringUtils.splitAndRemoveEmptyTrimmed(onlyProjectPythonPathStr, '|'); List<String> filteredPathItems = filterDuplicatesPreservingOrder(pathItems); return this.pythonPathHelper.resolveModule(fileAbsolutePath, false, filteredPathItems, project); } private List<String> filterDuplicatesPreservingOrder(List<String> pathItems) { return new ArrayList<>(new LinkedHashSet<>(pathItems)); } /** * @see org.python.pydev.core.IProjectModulesManager#resolveModule(java.lang.String) */ @Override public String resolveModule(String full) { return resolveModule(full, true); } /** * @see org.python.pydev.core.IProjectModulesManager#resolveModule(java.lang.String, boolean) */ @Override public String resolveModule(String full, boolean checkSystemManager) { IModulesManager[] managersInvolved = this.getManagersInvolved(checkSystemManager); for (IModulesManager m : managersInvolved) { String mod; if (m instanceof IProjectModulesManager) { IProjectModulesManager pM = (IProjectModulesManager) m; mod = pM.resolveModuleInDirectManager(full); } else { mod = m.resolveModule(full); } if (mod != null) { return mod; } } return null; } @Override public String resolveModuleInDirectManager(String full) { if (nature != null) { return pythonPathHelper.resolveModule(full, false, nature.getProject()); } return super.resolveModule(full); } @Override public String resolveModuleInDirectManager(IFile member) { File inOs = member.getRawLocation().toFile(); return resolveModuleInDirectManager(FileUtils.getFileAbsolutePath(inOs)); } /** * @see org.python.pydev.core.IProjectModulesManager#getSize(boolean) */ @Override public int getSize(boolean addDependenciesSize) { if (addDependenciesSize) { int size = 0; IModulesManager[] managersInvolved = this.getManagersInvolved(true); for (int i = 0; i < managersInvolved.length; i++) { size += managersInvolved[i].getSize(false); } return size; } else { return super.getSize(addDependenciesSize); } } /** * @see org.python.pydev.core.IProjectModulesManager#getBuiltins() */ @Override public String[] getBuiltins() { String[] builtins = null; ISystemModulesManager systemModulesManager = getSystemModulesManager(); if (systemModulesManager != null) { builtins = systemModulesManager.getBuiltins(); } return builtins; } /** * @param checkSystemManager whether the system manager should be added * @param referenced true if we should get the referenced projects * false if we should get the referencing projects * @return the Managers that this project references or the ones that reference this project (depends on 'referenced') * * Change in 1.3.3: adds itself to the list of returned managers */ private synchronized IModulesManager[] getManagers(boolean checkSystemManager, boolean referenced) { CompletionCache localCompletionCache = this.completionCache; if (localCompletionCache != null) { IModulesManager[] ret = localCompletionCache.getManagers(referenced); if (ret != null) { return ret; } } ArrayList<IModulesManager> list = new ArrayList<IModulesManager>(); ISystemModulesManager systemModulesManager = getSystemModulesManager(); //add itself 1st list.add(this); //get the projects 1st if (project != null) { IModulesManager javaModulesManagerForProject = JavaProjectModulesManagerCreator .createJavaProjectModulesManagerIfPossible(project); if (javaModulesManagerForProject != null) { list.add(javaModulesManagerForProject); } Set<IProject> projs; if (referenced) { projs = getReferencedProjects(project); } else { projs = getReferencingProjects(project); } addModuleManagers(list, projs); } //the system is the last one we add //http://sourceforge.net/tracker/index.php?func=detail&aid=1687018&group_id=85796&atid=577329 if (checkSystemManager && systemModulesManager != null) { //may be null in initialization or if the project does not have a related interpreter manager at the present time //(i.e.: misconfigured project) list.add(systemModulesManager); } IModulesManager[] ret = list.toArray(new IModulesManager[list.size()]); if (localCompletionCache != null) { localCompletionCache.setManagers(ret, referenced); } return ret; } public static Set<IProject> getReferencingProjects(IProject project) { HashSet<IProject> memo = new HashSet<IProject>(); getProjectsRecursively(project, false, memo); memo.remove(project); //shouldn't happen unless we've a cycle... return memo; } public static Set<IProject> getReferencedProjects(IProject project) { HashSet<IProject> memo = new HashSet<IProject>(); getProjectsRecursively(project, true, memo); memo.remove(project); //shouldn't happen unless we've a cycle... return memo; } /** * @param project the project for which we want references. * @param referenced whether we want to get the referenced projects or the ones referencing this one. * @param memo (out) this is the place where all the projects will e available. * * Note: the project itself will not be added. */ private static void getProjectsRecursively(IProject project, boolean referenced, HashSet<IProject> memo) { IProject[] projects = null; try { if (project == null || !project.isOpen() || !project.exists() || memo.contains(projects)) { return; } if (referenced) { projects = project.getReferencedProjects(); } else { projects = project.getReferencingProjects(); } } catch (CoreException e) { //ignore (it's closed) } if (projects != null) { for (IProject p : projects) { if (!memo.contains(p)) { memo.add(p); getProjectsRecursively(p, referenced, memo); } } } } /** * @param list the list that will be filled with the managers * @param projects the projects that should have the managers added */ private void addModuleManagers(ArrayList<IModulesManager> list, Collection<IProject> projects) { for (IProject project : projects) { PythonNature nature = PythonNature.getPythonNature(project); if (nature != null) { ICodeCompletionASTManager otherProjectAstManager = nature.getAstManager(); if (otherProjectAstManager != null) { IModulesManager projectModulesManager = otherProjectAstManager.getModulesManager(); if (projectModulesManager != null) { list.add(projectModulesManager); } } else { //Removed the warning below: this may be common when starting up... //String msg = "No ast manager configured for :" + project.getName(); //Log.log(IStatus.WARNING, msg, new RuntimeException(msg)); } } IModulesManager javaModulesManagerForProject = JavaProjectModulesManagerCreator .createJavaProjectModulesManagerIfPossible(project); if (javaModulesManagerForProject != null) { list.add(javaModulesManagerForProject); } } } /** * @return Returns the managers that this project references, including itself. */ public IModulesManager[] getManagersInvolved(boolean checkSystemManager) { return getManagers(checkSystemManager, true); } /** * @return Returns the managers that reference this project, including itself. */ public IModulesManager[] getRefencingManagersInvolved(boolean checkSystemManager) { return getManagers(checkSystemManager, false); } /** * Helper to work as a timer to know when to check for pythonpath consistencies. */ private volatile long checkedPythonpathConsistency = 0; /** * @see org.python.pydev.core.IProjectModulesManager#getCompletePythonPath() */ @Override public List<String> getCompletePythonPath(IInterpreterInfo interpreter, IInterpreterManager manager) { List<String> l = new ArrayList<String>(); IModulesManager[] managersInvolved = getManagersInvolved(true); for (IModulesManager m : managersInvolved) { if (m instanceof ISystemModulesManager) { ISystemModulesManager systemModulesManager = (ISystemModulesManager) m; l.addAll(systemModulesManager.getCompletePythonPath(interpreter, manager)); } else { PythonPathHelper h = (PythonPathHelper) m.getPythonPathHelper(); if (h != null) { List<String> pythonpath = h.getPythonpath(); //Note: this was previously only l.addAll(pythonpath), and was changed to the code below as a place //to check for consistencies in the pythonpath stored in the pythonpath helper and the pythonpath //available in the PythonPathNature (in general, when requesting it the PythonPathHelper should be //used, as it's a cache for the resolved values of the PythonPathNature). boolean forceCheck = false; ProjectModulesManager m2 = null; String onlyProjectPythonPathStr = null; if (m instanceof ProjectModulesManager) { long currentTimeMillis = System.currentTimeMillis(); m2 = (ProjectModulesManager) m; //check at most once every 20 seconds (or every time if the pythonpath is empty... in which case //it should be fast to get it too if it's consistent). if (pythonpath.size() == 0 || currentTimeMillis - m2.checkedPythonpathConsistency > 20 * 1000) { try { IPythonNature n = m.getNature(); if (n != null) { IPythonPathNature pythonPathNature = n.getPythonPathNature(); if (pythonPathNature != null) { onlyProjectPythonPathStr = pythonPathNature.getOnlyProjectPythonPathStr(true); m2.checkedPythonpathConsistency = currentTimeMillis; forceCheck = true; } } } catch (Exception e) { Log.log(e); } } } if (forceCheck) { //Check if it's actually correct and auto-fix if it's not. List<String> parsed = PythonPathHelper.parsePythonPathFromStr(onlyProjectPythonPathStr, null); if (m2.nature != null && !new HashSet<String>(parsed).equals(new HashSet<String>(pythonpath))) { // Make it right at this moment (so any other place that calls it before the restore //takes place has the proper version). h.setPythonPath(parsed); // Force a rebuild as the PythonPathHelper paths are not up to date. m2.nature.rebuildPath(); } l.addAll(parsed); //add the proper paths } else { l.addAll(pythonpath); } } } } return l; } }
bobwalker99/Pydev
plugins/org.python.pydev/src_completions/org/python/pydev/editor/codecompletion/revisited/ProjectModulesManager.java
Java
epl-1.0
22,376
/** * */ package com.coin.arbitrage.huobi.util; /** * @author Frank * */ public enum DepthType { STEP0("step0"), STEP1("step1"), STEP2("step2"), STEP3("step3"), STEP4("step4"), STEP5("step5"); private String depth; private DepthType(String depth) { this.depth = depth; } public String getDepth() { return depth; } }
zzzzwwww12/BuyLowSellHigh
BuyLowSellHigh/src/main/java/com/coin/arbitrage/huobi/util/DepthType.java
Java
epl-1.0
375
/******************************************************************************* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2020, Deep Blue C Technology Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *******************************************************************************/ package Debrief.Tools.Tote; import MWC.GUI.PlainChart; import MWC.GUI.ToolParent; import MWC.GUI.Tools.Action; import MWC.GUI.Tools.PlainTool; public final class StartTote extends PlainTool { /** * */ private static final long serialVersionUID = 1L; ///////////////////////////////////////////////////////////// // member variables //////////////////////////////////////////////////////////// private final PlainChart _theChart; ///////////////////////////////////////////////////////////// // constructor //////////////////////////////////////////////////////////// public StartTote(final ToolParent theParent, final PlainChart theChart) { super(theParent, "Step Forward", null); _theChart = theChart; } @Override public final void execute() { _theChart.update(); } ///////////////////////////////////////////////////////////// // member functions //////////////////////////////////////////////////////////// @Override public final Action getData() { // return the product return null; } }
debrief/debrief
org.mwc.debrief.legacy/src/Debrief/Tools/Tote/StartTote.java
Java
epl-1.0
1,752
/** */ package org.liquibase.xml.ns.dbchangelog.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.BasicFeatureMap; import org.eclipse.emf.ecore.util.FeatureMap; import org.eclipse.emf.ecore.util.InternalEList; import org.liquibase.xml.ns.dbchangelog.AndType; import org.liquibase.xml.ns.dbchangelog.ChangeLogPropertyDefinedType; import org.liquibase.xml.ns.dbchangelog.ChangeSetExecutedType; import org.liquibase.xml.ns.dbchangelog.ColumnExistsType; import org.liquibase.xml.ns.dbchangelog.CustomPreconditionType; import org.liquibase.xml.ns.dbchangelog.DbchangelogPackage; import org.liquibase.xml.ns.dbchangelog.DbmsType; import org.liquibase.xml.ns.dbchangelog.ExpectedQuotingStrategyType; import org.liquibase.xml.ns.dbchangelog.ForeignKeyConstraintExistsType; import org.liquibase.xml.ns.dbchangelog.IndexExistsType; import org.liquibase.xml.ns.dbchangelog.NotType; import org.liquibase.xml.ns.dbchangelog.OrType; import org.liquibase.xml.ns.dbchangelog.PrimaryKeyExistsType; import org.liquibase.xml.ns.dbchangelog.RowCountType; import org.liquibase.xml.ns.dbchangelog.RunningAsType; import org.liquibase.xml.ns.dbchangelog.SequenceExistsType; import org.liquibase.xml.ns.dbchangelog.SqlCheckType; import org.liquibase.xml.ns.dbchangelog.TableExistsType; import org.liquibase.xml.ns.dbchangelog.TableIsEmptyType; import org.liquibase.xml.ns.dbchangelog.ViewExistsType; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>And Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getGroup <em>Group</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getAnd <em>And</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getOr <em>Or</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getNot <em>Not</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getDbms <em>Dbms</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getRunningAs <em>Running As</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getChangeSetExecuted <em>Change Set Executed</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getTableExists <em>Table Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getColumnExists <em>Column Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getSequenceExists <em>Sequence Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getForeignKeyConstraintExists <em>Foreign Key Constraint Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getIndexExists <em>Index Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getPrimaryKeyExists <em>Primary Key Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getViewExists <em>View Exists</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getTableIsEmpty <em>Table Is Empty</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getRowCount <em>Row Count</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getSqlCheck <em>Sql Check</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getChangeLogPropertyDefined <em>Change Log Property Defined</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getExpectedQuotingStrategy <em>Expected Quoting Strategy</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getCustomPrecondition <em>Custom Precondition</em>}</li> * <li>{@link org.liquibase.xml.ns.dbchangelog.impl.AndTypeImpl#getAny <em>Any</em>}</li> * </ul> * * @generated */ public class AndTypeImpl extends MinimalEObjectImpl.Container implements AndType { /** * The cached value of the '{@link #getGroup() <em>Group</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getGroup() * @generated * @ordered */ protected FeatureMap group; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AndTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DbchangelogPackage.eINSTANCE.getAndType(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FeatureMap getGroup() { if (group == null) { group = new BasicFeatureMap(this, DbchangelogPackage.AND_TYPE__GROUP); } return group; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<AndType> getAnd() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_And()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<OrType> getOr() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_Or()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<NotType> getNot() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_Not()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DbmsType> getDbms() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_Dbms()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<RunningAsType> getRunningAs() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_RunningAs()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ChangeSetExecutedType> getChangeSetExecuted() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ChangeSetExecuted()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<TableExistsType> getTableExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_TableExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ColumnExistsType> getColumnExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ColumnExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<SequenceExistsType> getSequenceExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_SequenceExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ForeignKeyConstraintExistsType> getForeignKeyConstraintExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ForeignKeyConstraintExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<IndexExistsType> getIndexExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_IndexExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<PrimaryKeyExistsType> getPrimaryKeyExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_PrimaryKeyExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ViewExistsType> getViewExists() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ViewExists()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<TableIsEmptyType> getTableIsEmpty() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_TableIsEmpty()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<RowCountType> getRowCount() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_RowCount()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<SqlCheckType> getSqlCheck() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_SqlCheck()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ChangeLogPropertyDefinedType> getChangeLogPropertyDefined() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ChangeLogPropertyDefined()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<ExpectedQuotingStrategyType> getExpectedQuotingStrategy() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_ExpectedQuotingStrategy()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<CustomPreconditionType> getCustomPrecondition() { return getGroup().list(DbchangelogPackage.eINSTANCE.getAndType_CustomPrecondition()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FeatureMap getAny() { return (FeatureMap)getGroup().<FeatureMap.Entry>list(DbchangelogPackage.eINSTANCE.getAndType_Any()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case DbchangelogPackage.AND_TYPE__GROUP: return ((InternalEList<?>)getGroup()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__AND: return ((InternalEList<?>)getAnd()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__OR: return ((InternalEList<?>)getOr()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__NOT: return ((InternalEList<?>)getNot()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__DBMS: return ((InternalEList<?>)getDbms()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__RUNNING_AS: return ((InternalEList<?>)getRunningAs()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__CHANGE_SET_EXECUTED: return ((InternalEList<?>)getChangeSetExecuted()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__TABLE_EXISTS: return ((InternalEList<?>)getTableExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__COLUMN_EXISTS: return ((InternalEList<?>)getColumnExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__SEQUENCE_EXISTS: return ((InternalEList<?>)getSequenceExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__FOREIGN_KEY_CONSTRAINT_EXISTS: return ((InternalEList<?>)getForeignKeyConstraintExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__INDEX_EXISTS: return ((InternalEList<?>)getIndexExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__PRIMARY_KEY_EXISTS: return ((InternalEList<?>)getPrimaryKeyExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__VIEW_EXISTS: return ((InternalEList<?>)getViewExists()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__TABLE_IS_EMPTY: return ((InternalEList<?>)getTableIsEmpty()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__ROW_COUNT: return ((InternalEList<?>)getRowCount()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__SQL_CHECK: return ((InternalEList<?>)getSqlCheck()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__CHANGE_LOG_PROPERTY_DEFINED: return ((InternalEList<?>)getChangeLogPropertyDefined()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__EXPECTED_QUOTING_STRATEGY: return ((InternalEList<?>)getExpectedQuotingStrategy()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__CUSTOM_PRECONDITION: return ((InternalEList<?>)getCustomPrecondition()).basicRemove(otherEnd, msgs); case DbchangelogPackage.AND_TYPE__ANY: return ((InternalEList<?>)getAny()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DbchangelogPackage.AND_TYPE__GROUP: if (coreType) return getGroup(); return ((FeatureMap.Internal)getGroup()).getWrapper(); case DbchangelogPackage.AND_TYPE__AND: return getAnd(); case DbchangelogPackage.AND_TYPE__OR: return getOr(); case DbchangelogPackage.AND_TYPE__NOT: return getNot(); case DbchangelogPackage.AND_TYPE__DBMS: return getDbms(); case DbchangelogPackage.AND_TYPE__RUNNING_AS: return getRunningAs(); case DbchangelogPackage.AND_TYPE__CHANGE_SET_EXECUTED: return getChangeSetExecuted(); case DbchangelogPackage.AND_TYPE__TABLE_EXISTS: return getTableExists(); case DbchangelogPackage.AND_TYPE__COLUMN_EXISTS: return getColumnExists(); case DbchangelogPackage.AND_TYPE__SEQUENCE_EXISTS: return getSequenceExists(); case DbchangelogPackage.AND_TYPE__FOREIGN_KEY_CONSTRAINT_EXISTS: return getForeignKeyConstraintExists(); case DbchangelogPackage.AND_TYPE__INDEX_EXISTS: return getIndexExists(); case DbchangelogPackage.AND_TYPE__PRIMARY_KEY_EXISTS: return getPrimaryKeyExists(); case DbchangelogPackage.AND_TYPE__VIEW_EXISTS: return getViewExists(); case DbchangelogPackage.AND_TYPE__TABLE_IS_EMPTY: return getTableIsEmpty(); case DbchangelogPackage.AND_TYPE__ROW_COUNT: return getRowCount(); case DbchangelogPackage.AND_TYPE__SQL_CHECK: return getSqlCheck(); case DbchangelogPackage.AND_TYPE__CHANGE_LOG_PROPERTY_DEFINED: return getChangeLogPropertyDefined(); case DbchangelogPackage.AND_TYPE__EXPECTED_QUOTING_STRATEGY: return getExpectedQuotingStrategy(); case DbchangelogPackage.AND_TYPE__CUSTOM_PRECONDITION: return getCustomPrecondition(); case DbchangelogPackage.AND_TYPE__ANY: if (coreType) return getAny(); return ((FeatureMap.Internal)getAny()).getWrapper(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DbchangelogPackage.AND_TYPE__GROUP: ((FeatureMap.Internal)getGroup()).set(newValue); return; case DbchangelogPackage.AND_TYPE__AND: getAnd().clear(); getAnd().addAll((Collection<? extends AndType>)newValue); return; case DbchangelogPackage.AND_TYPE__OR: getOr().clear(); getOr().addAll((Collection<? extends OrType>)newValue); return; case DbchangelogPackage.AND_TYPE__NOT: getNot().clear(); getNot().addAll((Collection<? extends NotType>)newValue); return; case DbchangelogPackage.AND_TYPE__DBMS: getDbms().clear(); getDbms().addAll((Collection<? extends DbmsType>)newValue); return; case DbchangelogPackage.AND_TYPE__RUNNING_AS: getRunningAs().clear(); getRunningAs().addAll((Collection<? extends RunningAsType>)newValue); return; case DbchangelogPackage.AND_TYPE__CHANGE_SET_EXECUTED: getChangeSetExecuted().clear(); getChangeSetExecuted().addAll((Collection<? extends ChangeSetExecutedType>)newValue); return; case DbchangelogPackage.AND_TYPE__TABLE_EXISTS: getTableExists().clear(); getTableExists().addAll((Collection<? extends TableExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__COLUMN_EXISTS: getColumnExists().clear(); getColumnExists().addAll((Collection<? extends ColumnExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__SEQUENCE_EXISTS: getSequenceExists().clear(); getSequenceExists().addAll((Collection<? extends SequenceExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__FOREIGN_KEY_CONSTRAINT_EXISTS: getForeignKeyConstraintExists().clear(); getForeignKeyConstraintExists().addAll((Collection<? extends ForeignKeyConstraintExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__INDEX_EXISTS: getIndexExists().clear(); getIndexExists().addAll((Collection<? extends IndexExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__PRIMARY_KEY_EXISTS: getPrimaryKeyExists().clear(); getPrimaryKeyExists().addAll((Collection<? extends PrimaryKeyExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__VIEW_EXISTS: getViewExists().clear(); getViewExists().addAll((Collection<? extends ViewExistsType>)newValue); return; case DbchangelogPackage.AND_TYPE__TABLE_IS_EMPTY: getTableIsEmpty().clear(); getTableIsEmpty().addAll((Collection<? extends TableIsEmptyType>)newValue); return; case DbchangelogPackage.AND_TYPE__ROW_COUNT: getRowCount().clear(); getRowCount().addAll((Collection<? extends RowCountType>)newValue); return; case DbchangelogPackage.AND_TYPE__SQL_CHECK: getSqlCheck().clear(); getSqlCheck().addAll((Collection<? extends SqlCheckType>)newValue); return; case DbchangelogPackage.AND_TYPE__CHANGE_LOG_PROPERTY_DEFINED: getChangeLogPropertyDefined().clear(); getChangeLogPropertyDefined().addAll((Collection<? extends ChangeLogPropertyDefinedType>)newValue); return; case DbchangelogPackage.AND_TYPE__EXPECTED_QUOTING_STRATEGY: getExpectedQuotingStrategy().clear(); getExpectedQuotingStrategy().addAll((Collection<? extends ExpectedQuotingStrategyType>)newValue); return; case DbchangelogPackage.AND_TYPE__CUSTOM_PRECONDITION: getCustomPrecondition().clear(); getCustomPrecondition().addAll((Collection<? extends CustomPreconditionType>)newValue); return; case DbchangelogPackage.AND_TYPE__ANY: ((FeatureMap.Internal)getAny()).set(newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DbchangelogPackage.AND_TYPE__GROUP: getGroup().clear(); return; case DbchangelogPackage.AND_TYPE__AND: getAnd().clear(); return; case DbchangelogPackage.AND_TYPE__OR: getOr().clear(); return; case DbchangelogPackage.AND_TYPE__NOT: getNot().clear(); return; case DbchangelogPackage.AND_TYPE__DBMS: getDbms().clear(); return; case DbchangelogPackage.AND_TYPE__RUNNING_AS: getRunningAs().clear(); return; case DbchangelogPackage.AND_TYPE__CHANGE_SET_EXECUTED: getChangeSetExecuted().clear(); return; case DbchangelogPackage.AND_TYPE__TABLE_EXISTS: getTableExists().clear(); return; case DbchangelogPackage.AND_TYPE__COLUMN_EXISTS: getColumnExists().clear(); return; case DbchangelogPackage.AND_TYPE__SEQUENCE_EXISTS: getSequenceExists().clear(); return; case DbchangelogPackage.AND_TYPE__FOREIGN_KEY_CONSTRAINT_EXISTS: getForeignKeyConstraintExists().clear(); return; case DbchangelogPackage.AND_TYPE__INDEX_EXISTS: getIndexExists().clear(); return; case DbchangelogPackage.AND_TYPE__PRIMARY_KEY_EXISTS: getPrimaryKeyExists().clear(); return; case DbchangelogPackage.AND_TYPE__VIEW_EXISTS: getViewExists().clear(); return; case DbchangelogPackage.AND_TYPE__TABLE_IS_EMPTY: getTableIsEmpty().clear(); return; case DbchangelogPackage.AND_TYPE__ROW_COUNT: getRowCount().clear(); return; case DbchangelogPackage.AND_TYPE__SQL_CHECK: getSqlCheck().clear(); return; case DbchangelogPackage.AND_TYPE__CHANGE_LOG_PROPERTY_DEFINED: getChangeLogPropertyDefined().clear(); return; case DbchangelogPackage.AND_TYPE__EXPECTED_QUOTING_STRATEGY: getExpectedQuotingStrategy().clear(); return; case DbchangelogPackage.AND_TYPE__CUSTOM_PRECONDITION: getCustomPrecondition().clear(); return; case DbchangelogPackage.AND_TYPE__ANY: getAny().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DbchangelogPackage.AND_TYPE__GROUP: return group != null && !group.isEmpty(); case DbchangelogPackage.AND_TYPE__AND: return !getAnd().isEmpty(); case DbchangelogPackage.AND_TYPE__OR: return !getOr().isEmpty(); case DbchangelogPackage.AND_TYPE__NOT: return !getNot().isEmpty(); case DbchangelogPackage.AND_TYPE__DBMS: return !getDbms().isEmpty(); case DbchangelogPackage.AND_TYPE__RUNNING_AS: return !getRunningAs().isEmpty(); case DbchangelogPackage.AND_TYPE__CHANGE_SET_EXECUTED: return !getChangeSetExecuted().isEmpty(); case DbchangelogPackage.AND_TYPE__TABLE_EXISTS: return !getTableExists().isEmpty(); case DbchangelogPackage.AND_TYPE__COLUMN_EXISTS: return !getColumnExists().isEmpty(); case DbchangelogPackage.AND_TYPE__SEQUENCE_EXISTS: return !getSequenceExists().isEmpty(); case DbchangelogPackage.AND_TYPE__FOREIGN_KEY_CONSTRAINT_EXISTS: return !getForeignKeyConstraintExists().isEmpty(); case DbchangelogPackage.AND_TYPE__INDEX_EXISTS: return !getIndexExists().isEmpty(); case DbchangelogPackage.AND_TYPE__PRIMARY_KEY_EXISTS: return !getPrimaryKeyExists().isEmpty(); case DbchangelogPackage.AND_TYPE__VIEW_EXISTS: return !getViewExists().isEmpty(); case DbchangelogPackage.AND_TYPE__TABLE_IS_EMPTY: return !getTableIsEmpty().isEmpty(); case DbchangelogPackage.AND_TYPE__ROW_COUNT: return !getRowCount().isEmpty(); case DbchangelogPackage.AND_TYPE__SQL_CHECK: return !getSqlCheck().isEmpty(); case DbchangelogPackage.AND_TYPE__CHANGE_LOG_PROPERTY_DEFINED: return !getChangeLogPropertyDefined().isEmpty(); case DbchangelogPackage.AND_TYPE__EXPECTED_QUOTING_STRATEGY: return !getExpectedQuotingStrategy().isEmpty(); case DbchangelogPackage.AND_TYPE__CUSTOM_PRECONDITION: return !getCustomPrecondition().isEmpty(); case DbchangelogPackage.AND_TYPE__ANY: return !getAny().isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (group: "); result.append(group); result.append(')'); return result.toString(); } } //AndTypeImpl
Treehopper/EclipseAugments
liquibase-editor/eu.hohenegger.xsd.liquibase/src-gen/org/liquibase/xml/ns/dbchangelog/impl/AndTypeImpl.java
Java
epl-1.0
23,515
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Denise Smith - 2.4 - February 11, 2013 ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.xmlattribute.imports; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases; import org.eclipse.persistence.testing.jaxb.xmlattribute.imports2.IdentifierType; public class XmlAttributeImportsTestCases extends JAXBWithJSONTestCases { private final static String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmlattribute/imports.xml"; private final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmlattribute/imports.json"; private final static String XSD_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmlattribute/imports.xsd"; private final static String XSD_RESOURCE2 = "org/eclipse/persistence/testing/jaxb/xmlattribute/imports2.xsd"; public XmlAttributeImportsTestCases(String name) throws Exception { super(name); setControlDocument(XML_RESOURCE); setControlJSON(JSON_RESOURCE); setClasses(new Class[]{Person.class}); } protected Object getControlObject() { Person obj = new Person(); obj.name = "theName"; obj.setId(IdentifierType.thirdThing); return obj; } public void testSchemaGen() throws Exception{ List<InputStream> controlSchemas = new ArrayList<InputStream>(); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(XSD_RESOURCE); InputStream is2 = Thread.currentThread().getContextClassLoader().getResourceAsStream(XSD_RESOURCE2); controlSchemas.add(is); controlSchemas.add(is2); super.testSchemaGen(controlSchemas); } }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmlattribute/imports/XmlAttributeImportsTestCases.java
Java
epl-1.0
2,290
/** * Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités, Univ. Paris 06 - CNRS UMR 7606 (LIP6) * * 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 * * Project leader / Initial Contributor: * Lom Messan Hillah - <lom-messan.hillah@lip6.fr> * * Contributors: * ${ocontributors} - <$oemails}> * * Mailing list: * lom-messan.hillah@lip6.fr */ /** * (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6) * 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: * Lom HILLAH (LIP6) - Initial models and implementation * Rachid Alahyane (UPMC) - Infrastructure and continuous integration * Bastien Bouzerau (UPMC) - Architecture * Guillaume Giffo (UPMC) - Code generation refactoring, High-level API * * $Id ggiffo, Wed Feb 10 15:00:49 CET 2016$ */ package fr.lip6.move.pnml.ptnet.hlapi; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; import org.apache.axiom.om.OMElement; import org.eclipse.emf.common.util.DiagnosticChain; import fr.lip6.move.pnml.framework.hlapi.HLAPIClass; import fr.lip6.move.pnml.framework.utils.IdRefLinker; import fr.lip6.move.pnml.framework.utils.ModelRepository; import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException; import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException; import fr.lip6.move.pnml.framework.utils.exception.OtherException; import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException; import fr.lip6.move.pnml.ptnet.Arc; import fr.lip6.move.pnml.ptnet.Name; import fr.lip6.move.pnml.ptnet.NodeGraphics; import fr.lip6.move.pnml.ptnet.Page; import fr.lip6.move.pnml.ptnet.PtnetFactory; import fr.lip6.move.pnml.ptnet.RefTransition; import fr.lip6.move.pnml.ptnet.ToolInfo; import fr.lip6.move.pnml.ptnet.Transition; import fr.lip6.move.pnml.ptnet.impl.PtnetFactoryImpl; public class TransitionHLAPI implements HLAPIClass,PnObjectHLAPI,NodeHLAPI,TransitionNodeHLAPI{ /** * The contained LLAPI element. */ private Transition item; /** * this constructor allows you to set all 'settable' values * excepted container. */ public TransitionHLAPI( java.lang.String id , NameHLAPI name , NodeGraphicsHLAPI nodegraphics ) throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY PtnetFactory fact = PtnetFactoryImpl.eINSTANCE; synchronized(fact){item = fact.createTransition();} if(id!=null){ item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if(name!=null) item.setName((Name)name.getContainedItem()); if(nodegraphics!=null) item.setNodegraphics((NodeGraphics)nodegraphics.getContainedItem()); } /** * this constructor allows you to set all 'settable' values, including container if any. */ public TransitionHLAPI( java.lang.String id , NameHLAPI name , NodeGraphicsHLAPI nodegraphics , PageHLAPI containerPage ) throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY PtnetFactory fact = PtnetFactoryImpl.eINSTANCE; synchronized(fact){item = fact.createTransition();} if(id!=null){ item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if(name!=null) item.setName((Name)name.getContainedItem()); if(nodegraphics!=null) item.setNodegraphics((NodeGraphics)nodegraphics.getContainedItem()); if(containerPage!=null) item.setContainerPage((Page)containerPage.getContainedItem()); } /** * This constructor give access to required stuff only (not container if any) */ public TransitionHLAPI( java.lang.String id ) throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY PtnetFactory fact = PtnetFactoryImpl.eINSTANCE; synchronized(fact){item = fact.createTransition();} if(id!=null){ item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } } /** * This constructor give access to required stuff only (and container) */ public TransitionHLAPI( java.lang.String id , PageHLAPI containerPage ) throws InvalidIDException ,VoidRepositoryException {//BEGIN CONSTRUCTOR BODY PtnetFactory fact = PtnetFactoryImpl.eINSTANCE; synchronized(fact){item = fact.createTransition();} if(id!=null){ item.setId(ModelRepository.getInstance().getCurrentIdRepository().checkId(id, this)); } if(containerPage!=null) item.setContainerPage((Page)containerPage.getContainedItem()); } /** * This constructor encapsulate a low level API object in HLAPI. */ public TransitionHLAPI(Transition lowLevelAPI){ item = lowLevelAPI; } // access to low level API /** * Return encapsulated object */ public Transition getContainedItem(){ return item; } //getters giving LLAPI object /** * Return the encapsulate Low Level API object. */ public String getId(){ return item.getId(); } /** * Return the encapsulate Low Level API object. */ public Name getName(){ return item.getName(); } /** * Return the encapsulate Low Level API object. */ public List<ToolInfo> getToolspecifics(){ return item.getToolspecifics(); } /** * Return the encapsulate Low Level API object. */ public Page getContainerPage(){ return item.getContainerPage(); } /** * Return the encapsulate Low Level API object. */ public List<Arc> getInArcs(){ return item.getInArcs(); } /** * Return the encapsulate Low Level API object. */ public List<Arc> getOutArcs(){ return item.getOutArcs(); } /** * Return the encapsulate Low Level API object. */ public NodeGraphics getNodegraphics(){ return item.getNodegraphics(); } /** * Return the encapsulate Low Level API object. */ public List<RefTransition> getReferencingTransitions(){ return item.getReferencingTransitions(); } //getters giving HLAPI object /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ public NameHLAPI getNameHLAPI(){ if(item.getName() == null) return null; return new NameHLAPI(item.getName()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ToolInfoHLAPI> getToolspecificsHLAPI(){ java.util.List<ToolInfoHLAPI> retour = new ArrayList<ToolInfoHLAPI>(); for (ToolInfo elemnt : getToolspecifics()) { retour.add(new ToolInfoHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ public PageHLAPI getContainerPageHLAPI(){ if(item.getContainerPage() == null) return null; return new PageHLAPI(item.getContainerPage()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ArcHLAPI> getInArcsHLAPI(){ java.util.List<ArcHLAPI> retour = new ArrayList<ArcHLAPI>(); for (Arc elemnt : getInArcs()) { retour.add(new ArcHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<ArcHLAPI> getOutArcsHLAPI(){ java.util.List<ArcHLAPI> retour = new ArrayList<ArcHLAPI>(); for (Arc elemnt : getOutArcs()) { retour.add(new ArcHLAPI(elemnt)); } return retour; } /** * This accessor automatically encapsulate an element of the current object. * WARNING : this creates a new object in memory. * @return : null if the element is null */ public NodeGraphicsHLAPI getNodegraphicsHLAPI(){ if(item.getNodegraphics() == null) return null; return new NodeGraphicsHLAPI(item.getNodegraphics()); } /** * This accessor automatically encapsulate all elements of the selected sublist. * WARNING : this can creates a lot of new object in memory. */ public java.util.List<RefTransitionHLAPI> getReferencingTransitionsHLAPI(){ java.util.List<RefTransitionHLAPI> retour = new ArrayList<RefTransitionHLAPI>(); for (RefTransition elemnt : getReferencingTransitions()) { retour.add(new RefTransitionHLAPI(elemnt)); } return retour; } //Special getter for list of generics object, return only one object type. //setters (including container setter if aviable) /** * set Id */ public void setIdHLAPI( java.lang.String elem) throws InvalidIDException ,VoidRepositoryException { if(elem!=null){ try{ item.setId(ModelRepository.getInstance().getCurrentIdRepository().changeId(this, elem)); }catch (OtherException e){ ModelRepository.getInstance().getCurrentIdRepository().checkId(elem, this); } } } /** * set Name */ public void setNameHLAPI( NameHLAPI elem){ if(elem!=null) item.setName((Name)elem.getContainedItem()); } /** * set Nodegraphics */ public void setNodegraphicsHLAPI( NodeGraphicsHLAPI elem){ if(elem!=null) item.setNodegraphics((NodeGraphics)elem.getContainedItem()); } /** * set ContainerPage */ public void setContainerPageHLAPI( PageHLAPI elem){ if(elem!=null) item.setContainerPage((Page)elem.getContainedItem()); } //setters/remover for lists. public void addToolspecificsHLAPI(ToolInfoHLAPI unit){ item.getToolspecifics().add((ToolInfo)unit.getContainedItem()); } public void removeToolspecificsHLAPI(ToolInfoHLAPI unit){ item.getToolspecifics().remove((ToolInfo)unit.getContainedItem()); } //equals method public boolean equals(TransitionHLAPI item){ return item.getContainedItem().equals(getContainedItem()); } //PNML /** * Returns the PNML xml tree for this object. */ public String toPNML(){ return item.toPNML(); } /** * Writes the PNML XML tree of this object into file channel. */ public void toPNML(FileChannel fc){ item.toPNML(fc); } /** * creates an object from the xml nodes.(symetric work of toPNML) */ public void fromPNML(OMElement subRoot,IdRefLinker idr) throws InnerBuildException, InvalidIDException, VoidRepositoryException{ item.fromPNML(subRoot,idr); } public boolean validateOCL(DiagnosticChain diagnostics){ return item.validateOCL(diagnostics); } }
lhillah/pnmlframework
pnmlFw-PTNet/src/fr/lip6/move/pnml/ptnet/hlapi/TransitionHLAPI.java
Java
epl-1.0
11,212
/******************************************************************************* * Copyright (c) 1998, 2013 Oracle and/or its affiliates, Frank Schwarz. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink * 08/20/2008-1.0.1 Nathan Beyer (Cerner) * - 241308: Primary key is incorrectly assigned to embeddable class * field with the same name as the primary key field's name * 01/12/2009-1.1 Daniel Lo, Tom Ware, Guy Pelletier * - 247041: Null element inserted in the ArrayList * 07/17/2009 - tware - added tests for DDL generation of maps * 01/22/2010-2.0.1 Guy Pelletier * - 294361: incorrect generated table for element collection attribute overrides * 06/14/2010-2.2 Guy Pelletier * - 264417: Table generation is incorrect for JoinTables in AssociationOverrides * 09/15/2010-2.2 Chris Delahunt * - 322233 - AttributeOverrides and AssociationOverride dont change field type info * 11/17/2010-2.2.0 Chris Delahunt * - 214519: Allow appending strings to CREATE TABLE statements * 11/23/2010-2.2 Frank Schwarz * - 328774: TABLE_PER_CLASS-mapped key of a java.util.Map does not work for querying * 01/04/2011-2.3 Guy Pelletier * - 330628: @PrimaryKeyJoinColumn(...) is not working equivalently to @JoinColumn(..., insertable = false, updatable = false) * 01/06/2011-2.3 Guy Pelletier * - 312244: can't map optional one-to-one relationship using @PrimaryKeyJoinColumn * 01/11/2011-2.3 Guy Pelletier * - 277079: EmbeddedId's fields are null when using LOB with fetchtype LAZY ******************************************************************************/ package org.eclipse.persistence.testing.tests.jpa.ddlgeneration; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.persistence.testing.framework.junit.JUnitTestCase; import javax.persistence.EntityManager; /** * JUnit test case(s) for DDL generation. */ public class DDLTablePerClassTestSuite extends DDLGenerationJUnitTestSuite { // This is the persistence unit name on server as for persistence unit name "ddlTablePerClass" in J2SE private static final String DDL_TPC_PU = "MulitPU-2"; public DDLTablePerClassTestSuite() { super(); } public DDLTablePerClassTestSuite(String name) { super(name); setPuName(DDL_TPC_PU); } public static Test suite() { TestSuite suite = new TestSuite(); suite.setName("DDLTablePerClassTestSuite"); suite.addTest(new DDLTablePerClassTestSuite("testSetup")); suite.addTest(new DDLTablePerClassTestSuite("testDDLTablePerClassModel")); suite.addTest(new DDLTablePerClassTestSuite("testDDLTablePerClassModelQuery")); if (! JUnitTestCase.isJPA10()) { suite.addTest(new DDLTablePerClassTestSuite("testTPCMappedKeyMapQuery")); } return suite; } /** * The setup is done as a test, both to record its failure, and to allow execution in the server. */ public void testSetup() { // Trigger DDL generation EntityManager emDDLTPC = createEntityManager("MulitPU-2"); closeEntityManager(emDDLTPC); clearCache(DDL_TPC_PU); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } }
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/tests/jpa/ddlgeneration/DDLTablePerClassTestSuite.java
Java
epl-1.0
3,927
/******************************************************************************* * Copyright (c) 2000, 2016 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.jface.text.rules; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.DocumentRewriteSession; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IDocumentPartitionerExtension; import org.eclipse.jface.text.IDocumentPartitionerExtension2; import org.eclipse.jface.text.IDocumentPartitionerExtension3; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.TypedRegion; /** * A standard implementation of a document partitioner. It uses an * {@link IPartitionTokenScanner} to scan the document and to determine the * document's partitioning. The tokens returned by the scanner must return the * partition type as their data. The partitioner remembers the document's * partitions in the document itself rather than maintaining its own data * structure. * <p> * To reduce array creations in {@link IDocument#getPositions(String)}, the * positions get cached. The cache is cleared after updating the positions in * {@link #documentChanged2(DocumentEvent)}. Subclasses need to call * {@link #clearPositionCache()} after modifying the partitioner's positions. * The cached positions may be accessed through {@link #getPositions()}. * </p> * * @see IPartitionTokenScanner * @since 3.1 */ public class FastPartitioner implements IDocumentPartitioner, IDocumentPartitionerExtension, IDocumentPartitionerExtension2, IDocumentPartitionerExtension3 { /** * The position category this partitioner uses to store the document's partitioning information. */ private static final String CONTENT_TYPES_CATEGORY= "__content_types_category"; //$NON-NLS-1$ /** The partitioner's scanner */ protected final IPartitionTokenScanner fScanner; /** The legal content types of this partitioner */ protected final String[] fLegalContentTypes; /** The partitioner's document */ protected IDocument fDocument; /** The document length before a document change occurred */ protected int fPreviousDocumentLength; /** The position updater used to for the default updating of partitions */ protected final DefaultPositionUpdater fPositionUpdater; /** The offset at which the first changed partition starts */ protected int fStartOffset; /** The offset at which the last changed partition ends */ protected int fEndOffset; /**The offset at which a partition has been deleted */ protected int fDeleteOffset; /** * The position category this partitioner uses to store the document's partitioning information. */ private final String fPositionCategory; /** * The active document rewrite session. */ private DocumentRewriteSession fActiveRewriteSession; /** * Flag indicating whether this partitioner has been initialized. */ private boolean fIsInitialized= false; /** * The cached positions from our document, so we don't create a new array every time * someone requests partition information. */ private Position[] fCachedPositions= null; /** Debug option for cache consistency checking. */ private static final boolean CHECK_CACHE_CONSISTENCY= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.jface.text/debug/FastPartitioner/PositionCache")); //$NON-NLS-1$//$NON-NLS-2$; /** * Creates a new partitioner that uses the given scanner and may return * partitions of the given legal content types. * * @param scanner the scanner this partitioner is supposed to use * @param legalContentTypes the legal content types of this partitioner */ public FastPartitioner(IPartitionTokenScanner scanner, String[] legalContentTypes) { fScanner= scanner; fLegalContentTypes= TextUtilities.copy(legalContentTypes); fPositionCategory= CONTENT_TYPES_CATEGORY + hashCode(); fPositionUpdater= new DefaultPositionUpdater(fPositionCategory); } @Override public String[] getManagingPositionCategories() { return new String[] { fPositionCategory }; } @Override public final void connect(IDocument document) { connect(document, false); } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public void connect(IDocument document, boolean delayInitialization) { Assert.isNotNull(document); Assert.isTrue(!document.containsPositionCategory(fPositionCategory)); fDocument= document; fDocument.addPositionCategory(fPositionCategory); fIsInitialized= false; if (!delayInitialization) checkInitialization(); } /** * Calls {@link #initialize()} if the receiver is not yet initialized. */ protected final void checkInitialization() { if (!fIsInitialized) initialize(); } /** * Performs the initial partitioning of the partitioner's document. * <p> * May be extended by subclasses. * </p> */ protected void initialize() { fIsInitialized= true; clearPositionCache(); fScanner.setRange(fDocument, 0, fDocument.getLength()); try { IToken token= fScanner.nextToken(); while (!token.isEOF()) { String contentType= getTokenContentType(token); if (isSupportedContentType(contentType)) { TypedPosition p= new TypedPosition(fScanner.getTokenOffset(), fScanner.getTokenLength(), contentType); fDocument.addPosition(fPositionCategory, p); } token= fScanner.nextToken(); } } catch (BadLocationException x) { // cannot happen as offsets come from scanner } catch (BadPositionCategoryException x) { // cannot happen if document has been connected before } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public void disconnect() { Assert.isTrue(fDocument.containsPositionCategory(fPositionCategory)); try { fDocument.removePositionCategory(fPositionCategory); } catch (BadPositionCategoryException x) { // can not happen because of Assert } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public void documentAboutToBeChanged(DocumentEvent e) { if (fIsInitialized) { Assert.isTrue(e.getDocument() == fDocument); fPreviousDocumentLength= e.getDocument().getLength(); fStartOffset= -1; fEndOffset= -1; fDeleteOffset= -1; } } @Override public final boolean documentChanged(DocumentEvent e) { if (fIsInitialized) { IRegion region= documentChanged2(e); return (region != null); } return false; } /** * Helper method for tracking the minimal region containing all partition changes. * If <code>offset</code> is smaller than the remembered offset, <code>offset</code> * will from now on be remembered. If <code>offset + length</code> is greater than * the remembered end offset, it will be remembered from now on. * * @param offset the offset * @param length the length */ private void rememberRegion(int offset, int length) { // remember start offset if (fStartOffset == -1) fStartOffset= offset; else if (offset < fStartOffset) fStartOffset= offset; // remember end offset int endOffset= offset + length; if (fEndOffset == -1) fEndOffset= endOffset; else if (endOffset > fEndOffset) fEndOffset= endOffset; } /** * Remembers the given offset as the deletion offset. * * @param offset the offset */ private void rememberDeletedOffset(int offset) { fDeleteOffset= offset; } /** * Creates the minimal region containing all partition changes using the * remembered offset, end offset, and deletion offset. * * @return the minimal region containing all the partition changes */ private IRegion createRegion() { if (fDeleteOffset == -1) { if (fStartOffset == -1 || fEndOffset == -1) return null; return new Region(fStartOffset, fEndOffset - fStartOffset); } else if (fStartOffset == -1 || fEndOffset == -1) { return new Region(fDeleteOffset, 0); } else { int offset= Math.min(fDeleteOffset, fStartOffset); int endOffset= Math.max(fDeleteOffset, fEndOffset); return new Region(offset, endOffset - offset); } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public IRegion documentChanged2(DocumentEvent e) { if (!fIsInitialized) return null; try { Assert.isTrue(e.getDocument() == fDocument); Position[] category= getPositions(); IRegion line= fDocument.getLineInformationOfOffset(e.getOffset()); int reparseStart= line.getOffset(); int partitionStart= -1; String contentType= null; int newLength= e.getText() == null ? 0 : e.getText().length(); int first= fDocument.computeIndexInCategory(fPositionCategory, reparseStart); if (first > 0) { TypedPosition partition= (TypedPosition) category[first - 1]; if (partition.includes(reparseStart)) { partitionStart= partition.getOffset(); contentType= partition.getType(); reparseStart= partitionStart; -- first; } else if (reparseStart == e.getOffset() && reparseStart == partition.getOffset() + partition.getLength()) { partitionStart= partition.getOffset(); contentType= partition.getType(); reparseStart= partitionStart; -- first; } else { partitionStart= partition.getOffset() + partition.getLength(); contentType= IDocument.DEFAULT_CONTENT_TYPE; } } else { partitionStart= 0; reparseStart= 0; } fPositionUpdater.update(e); for (int i= first; i < category.length; i++) { Position p= category[i]; if (p.isDeleted) { rememberDeletedOffset(e.getOffset()); break; } } clearPositionCache(); category= getPositions(); fScanner.setPartialRange(fDocument, reparseStart, fDocument.getLength() - reparseStart, contentType, partitionStart); int behindLastScannedPosition= reparseStart; IToken token= fScanner.nextToken(); while (!token.isEOF()) { contentType= getTokenContentType(token); if (!isSupportedContentType(contentType)) { token= fScanner.nextToken(); continue; } int start= fScanner.getTokenOffset(); int length= fScanner.getTokenLength(); behindLastScannedPosition= start + length; int lastScannedPosition= behindLastScannedPosition - 1; // remove all affected positions while (first < category.length) { TypedPosition p= (TypedPosition) category[first]; if (lastScannedPosition >= p.offset + p.length || (p.overlapsWith(start, length) && (!fDocument.containsPosition(fPositionCategory, start, length) || !contentType.equals(p.getType())))) { rememberRegion(p.offset, p.length); fDocument.removePosition(fPositionCategory, p); ++ first; } else break; } // if position already exists and we have scanned at least the // area covered by the event, we are done if (fDocument.containsPosition(fPositionCategory, start, length)) { if (lastScannedPosition >= e.getOffset() + newLength) return createRegion(); ++ first; } else { // insert the new type position try { fDocument.addPosition(fPositionCategory, new TypedPosition(start, length, contentType)); rememberRegion(start, length); } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } } token= fScanner.nextToken(); } first= fDocument.computeIndexInCategory(fPositionCategory, behindLastScannedPosition); clearPositionCache(); category= getPositions(); TypedPosition p; while (first < category.length) { p= (TypedPosition) category[first++]; fDocument.removePosition(fPositionCategory, p); rememberRegion(p.offset, p.length); } } catch (BadPositionCategoryException x) { // should never happen on connected documents } catch (BadLocationException x) { } finally { clearPositionCache(); } return createRegion(); } /** * Returns the position in the partitoner's position category which is * close to the given offset. This is, the position has either an offset which * is the same as the given offset or an offset which is smaller than the given * offset. This method profits from the knowledge that a partitioning is * a ordered set of disjoint position. * <p> * May be extended or replaced by subclasses. * </p> * @param offset the offset for which to search the closest position * @return the closest position in the partitioner's category */ protected TypedPosition findClosestPosition(int offset) { try { int index= fDocument.computeIndexInCategory(fPositionCategory, offset); Position[] category= getPositions(); if (category.length == 0) return null; if (index < category.length) { if (offset == category[index].offset) return (TypedPosition) category[index]; } if (index > 0) index--; return (TypedPosition) category[index]; } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } return null; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public String getContentType(int offset) { checkInitialization(); TypedPosition p= findClosestPosition(offset); if (p != null && p.includes(offset)) return p.getType(); return IDocument.DEFAULT_CONTENT_TYPE; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public ITypedRegion getPartition(int offset) { checkInitialization(); try { Position[] category = getPositions(); if (category == null || category.length == 0) return new TypedRegion(0, fDocument.getLength(), IDocument.DEFAULT_CONTENT_TYPE); int index= fDocument.computeIndexInCategory(fPositionCategory, offset); if (index < category.length) { TypedPosition next= (TypedPosition) category[index]; if (offset == next.offset) return new TypedRegion(next.getOffset(), next.getLength(), next.getType()); if (index == 0) return new TypedRegion(0, next.offset, IDocument.DEFAULT_CONTENT_TYPE); TypedPosition previous= (TypedPosition) category[index - 1]; if (previous.includes(offset)) return new TypedRegion(previous.getOffset(), previous.getLength(), previous.getType()); int endOffset= previous.getOffset() + previous.getLength(); return new TypedRegion(endOffset, next.getOffset() - endOffset, IDocument.DEFAULT_CONTENT_TYPE); } TypedPosition previous= (TypedPosition) category[category.length - 1]; if (previous.includes(offset)) return new TypedRegion(previous.getOffset(), previous.getLength(), previous.getType()); int endOffset= previous.getOffset() + previous.getLength(); return new TypedRegion(endOffset, fDocument.getLength() - endOffset, IDocument.DEFAULT_CONTENT_TYPE); } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } return new TypedRegion(0, fDocument.getLength(), IDocument.DEFAULT_CONTENT_TYPE); } @Override public final ITypedRegion[] computePartitioning(int offset, int length) { return computePartitioning(offset, length, false); } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public String[] getLegalContentTypes() { return TextUtilities.copy(fLegalContentTypes); } /** * Returns whether the given type is one of the legal content types. * <p> * May be extended by subclasses. * </p> * * @param contentType the content type to check * @return <code>true</code> if the content type is a legal content type */ protected boolean isSupportedContentType(String contentType) { if (contentType != null) { for (String fLegalContentType : fLegalContentTypes) { if (fLegalContentType.equals(contentType)) return true; } } return false; } /** * Returns a content type encoded in the given token. If the token's * data is not <code>null</code> and a string it is assumed that * it is the encoded content type. * <p> * May be replaced or extended by subclasses. * </p> * * @param token the token whose content type is to be determined * @return the token's content type */ protected String getTokenContentType(IToken token) { Object data= token.getData(); if (data instanceof String) return (String) data; return null; } /* zero-length partition support */ /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public String getContentType(int offset, boolean preferOpenPartitions) { return getPartition(offset, preferOpenPartitions).getType(); } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public ITypedRegion getPartition(int offset, boolean preferOpenPartitions) { ITypedRegion region= getPartition(offset); if (preferOpenPartitions) { if (region.getOffset() == offset && !region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) { if (offset > 0) { region= getPartition(offset - 1); if (region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) return region; } return new TypedRegion(offset, 0, IDocument.DEFAULT_CONTENT_TYPE); } } return region; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ @Override public ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) { checkInitialization(); List<TypedRegion> list= new ArrayList<>(); try { int endOffset= offset + length; Position[] category= getPositions(); TypedPosition previous= null, current= null; int start, end, gapOffset; Position gap= new Position(0); int startIndex= getFirstIndexEndingAfterOffset(category, offset); int endIndex= getFirstIndexStartingAfterOffset(category, endOffset); for (int i= startIndex; i < endIndex; i++) { current= (TypedPosition) category[i]; gapOffset= (previous != null) ? previous.getOffset() + previous.getLength() : 0; gap.setOffset(gapOffset); gap.setLength(current.getOffset() - gapOffset); if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) { start= Math.max(offset, gapOffset); end= Math.min(endOffset, gap.getOffset() + gap.getLength()); list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE)); } if (current.overlapsWith(offset, length)) { start= Math.max(offset, current.getOffset()); end= Math.min(endOffset, current.getOffset() + current.getLength()); list.add(new TypedRegion(start, end - start, current.getType())); } previous= current; } if (previous != null) { gapOffset= previous.getOffset() + previous.getLength(); gap.setOffset(gapOffset); gap.setLength(fDocument.getLength() - gapOffset); if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) { start= Math.max(offset, gapOffset); end= Math.min(endOffset, fDocument.getLength()); list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE)); } } if (list.isEmpty()) list.add(new TypedRegion(offset, length, IDocument.DEFAULT_CONTENT_TYPE)); } catch (BadPositionCategoryException ex) { // Make sure we clear the cache clearPositionCache(); } catch (RuntimeException ex) { // Make sure we clear the cache clearPositionCache(); throw ex; } TypedRegion[] result= new TypedRegion[list.size()]; list.toArray(result); return result; } /** * Returns <code>true</code> if the given ranges overlap with or touch each other. * * @param gap the first range * @param offset the offset of the second range * @param length the length of the second range * @return <code>true</code> if the given ranges overlap with or touch each other */ private boolean overlapsOrTouches(Position gap, int offset, int length) { return gap.getOffset() <= offset + length && offset <= gap.getOffset() + gap.getLength(); } /** * Returns the index of the first position which ends after the given offset. * * @param positions the positions in linear order * @param offset the offset * @return the index of the first position which ends after the offset */ private int getFirstIndexEndingAfterOffset(Position[] positions, int offset) { int i= -1, j= positions.length; while (j - i > 1) { int k= (i + j) >> 1; Position p= positions[k]; if (p.getOffset() + p.getLength() > offset) j= k; else i= k; } return j; } /** * Returns the index of the first position which starts at or after the given offset. * * @param positions the positions in linear order * @param offset the offset * @return the index of the first position which starts after the offset */ private int getFirstIndexStartingAfterOffset(Position[] positions, int offset) { int i= -1, j= positions.length; while (j - i > 1) { int k= (i + j) >> 1; Position p= positions[k]; if (p.getOffset() >= offset) j= k; else i= k; } return j; } @Override public void startRewriteSession(DocumentRewriteSession session) throws IllegalStateException { if (fActiveRewriteSession != null) throw new IllegalStateException(); fActiveRewriteSession= session; } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public void stopRewriteSession(DocumentRewriteSession session) { if (fActiveRewriteSession == session) flushRewriteSession(); } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ @Override public DocumentRewriteSession getActiveRewriteSession() { return fActiveRewriteSession; } /** * Flushes the active rewrite session. */ protected final void flushRewriteSession() { fActiveRewriteSession= null; // remove all position belonging to the partitioner position category try { fDocument.removePositionCategory(fPositionCategory); } catch (BadPositionCategoryException x) { } fDocument.addPositionCategory(fPositionCategory); fIsInitialized= false; } /** * Clears the position cache. Needs to be called whenever the positions have * been updated. */ protected final void clearPositionCache() { if (fCachedPositions != null) { fCachedPositions= null; } } /** * Returns the partitioners positions. * * @return the partitioners positions * @throws BadPositionCategoryException if getting the positions from the * document fails */ protected final Position[] getPositions() throws BadPositionCategoryException { if (fCachedPositions == null) { fCachedPositions= fDocument.getPositions(fPositionCategory); } else if (CHECK_CACHE_CONSISTENCY) { Position[] positions= fDocument.getPositions(fPositionCategory); int len= Math.min(positions.length, fCachedPositions.length); for (int i= 0; i < len; i++) { if (!positions[i].equals(fCachedPositions[i])) System.err.println("FastPartitioner.getPositions(): cached position is not up to date: from document: " + toString(positions[i]) + " in cache: " + toString(fCachedPositions[i])); //$NON-NLS-1$ //$NON-NLS-2$ } for (int i= len; i < positions.length; i++) System.err.println("FastPartitioner.getPositions(): new position in document: " + toString(positions[i])); //$NON-NLS-1$ for (int i= len; i < fCachedPositions.length; i++) System.err.println("FastPartitioner.getPositions(): stale position in cache: " + toString(fCachedPositions[i])); //$NON-NLS-1$ } return fCachedPositions; } /** * Pretty print a <code>Position</code>. * * @param position the position to format * @return a formatted string */ private String toString(Position position) { return "P[" + position.getOffset() + "+" + position.getLength() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
elucash/eclipse-oxygen
org.eclipse.jface.text/src/org/eclipse/jface/text/rules/FastPartitioner.java
Java
epl-1.0
24,915
package mesfavoris.bookmarktype; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Optional; import mesfavoris.model.Bookmark; public abstract class AbstractBookmarkMarkerPropertiesProvider implements IBookmarkMarkerAttributesProvider { protected Optional<String> getMessage(Bookmark bookmark) { String comment = bookmark.getPropertyValue(Bookmark.PROPERTY_COMMENT); if (comment == null) { return Optional.empty(); } try (BufferedReader br = new BufferedReader(new StringReader(comment))) { return Optional.ofNullable(br.readLine()); } catch (IOException e) { return Optional.empty(); } } }
cchabanois/mesfavoris
bundles/mesfavoris/src/mesfavoris/bookmarktype/AbstractBookmarkMarkerPropertiesProvider.java
Java
epl-1.0
675
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text.source; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension5; import org.eclipse.jface.text.JFaceTextUtil; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.source.projection.AnnotationBag; /** * Ruler presented next to a source viewer showing all annotations of the * viewer's annotation model in a compact format. The ruler has the same height * as the source viewer. * <p> * Clients usually instantiate and configure objects of this class.</p> * * @since 2.1 */ public class OverviewRuler implements IOverviewRuler { /** * Internal listener class. */ class InternalListener implements ITextListener, IAnnotationModelListener, IAnnotationModelListenerExtension { /* * @see ITextListener#textChanged */ public void textChanged(TextEvent e) { if (fTextViewer != null && e.getDocumentEvent() == null && e.getViewerRedrawState()) { // handle only changes of visible document redraw(); } } /* * @see IAnnotationModelListener#modelChanged(IAnnotationModel) */ public void modelChanged(IAnnotationModel model) { update(); } /* * @see org.eclipse.jface.text.source.IAnnotationModelListenerExtension#modelChanged(org.eclipse.jface.text.source.AnnotationModelEvent) * @since 3.3 */ public void modelChanged(AnnotationModelEvent event) { if (!event.isValid()) return; if (event.isWorldChange()) { update(); return; } Annotation[] annotations= event.getAddedAnnotations(); int length= annotations.length; for (int i= 0; i < length; i++) { if (!skip(annotations[i].getType())) { update(); return; } } annotations= event.getRemovedAnnotations(); length= annotations.length; for (int i= 0; i < length; i++) { if (!skip(annotations[i].getType())) { update(); return; } } annotations= event.getChangedAnnotations(); length= annotations.length; for (int i= 0; i < length; i++) { if (!skip(annotations[i].getType())) { update(); return; } } } } /** * Enumerates the annotations of a specified type and characteristics * of the associated annotation model. */ class FilterIterator implements Iterator { final static int TEMPORARY= 1 << 1; final static int PERSISTENT= 1 << 2; final static int IGNORE_BAGS= 1 << 3; private Iterator fIterator; private Object fType; private Annotation fNext; private int fStyle; /** * Creates a new filter iterator with the given specification. * * @param annotationType the annotation type * @param style the style */ public FilterIterator(Object annotationType, int style) { fType= annotationType; fStyle= style; if (fModel != null) { fIterator= fModel.getAnnotationIterator(); skip(); } } /** * Creates a new filter iterator with the given specification. * * @param annotationType the annotation type * @param style the style * @param iterator the iterator */ public FilterIterator(Object annotationType, int style, Iterator iterator) { fType= annotationType; fStyle= style; fIterator= iterator; skip(); } private void skip() { boolean temp= (fStyle & TEMPORARY) != 0; boolean pers= (fStyle & PERSISTENT) != 0; boolean ignr= (fStyle & IGNORE_BAGS) != 0; while (fIterator.hasNext()) { Annotation next= (Annotation) fIterator.next(); if (next.isMarkedDeleted()) continue; if (ignr && (next instanceof AnnotationBag)) continue; fNext= next; Object annotationType= next.getType(); if (fType == null || fType.equals(annotationType) || !fConfiguredAnnotationTypes.contains(annotationType) && isSubtype(annotationType)) { if (temp && pers) return; if (pers && next.isPersistent()) return; if (temp && !next.isPersistent()) return; } } fNext= null; } private boolean isSubtype(Object annotationType) { if (fAnnotationAccess instanceof IAnnotationAccessExtension) { IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; return extension.isSubtype(annotationType, fType); } return fType.equals(annotationType); } /* * @see Iterator#hasNext() */ public boolean hasNext() { return fNext != null; } /* * @see Iterator#next() */ public Object next() { try { return fNext; } finally { if (fIterator != null) skip(); } } /* * @see Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } /** * The painter of the overview ruler's header. */ class HeaderPainter implements PaintListener { private Color fIndicatorColor; private Color fSeparatorColor; /** * Creates a new header painter. */ public HeaderPainter() { fSeparatorColor= fHeader.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW); } /** * Sets the header color. * * @param color the header color */ public void setColor(Color color) { fIndicatorColor= color; } private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topLeft, Color bottomRight) { gc.setForeground(topLeft == null ? fSeparatorColor : topLeft); gc.drawLine(x, y, x + w -1, y); gc.drawLine(x, y, x, y + h -1); gc.setForeground(bottomRight == null ? fSeparatorColor : bottomRight); gc.drawLine(x + w, y, x + w, y + h); gc.drawLine(x, y + h, x + w, y + h); } public void paintControl(PaintEvent e) { if (fIndicatorColor == null) return; Point s= fHeader.getSize(); e.gc.setBackground(fIndicatorColor); Rectangle r= new Rectangle(INSET, (s.y - (2*ANNOTATION_HEIGHT)) / 2, s.x - (2*INSET), 2*ANNOTATION_HEIGHT); e.gc.fillRectangle(r); Display d= fHeader.getDisplay(); if (d != null) // drawBevelRect(e.gc, r.x, r.y, r.width -1, r.height -1, d.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), d.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); drawBevelRect(e.gc, r.x, r.y, r.width -1, r.height -1, null, null); e.gc.setForeground(fSeparatorColor); e.gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance e.gc.drawLine(0, s.y -1, s.x -1, s.y -1); } } private static final int INSET= 2; private static final int ANNOTATION_HEIGHT= 4; private static boolean ANNOTATION_HEIGHT_SCALABLE= true; /** The model of the overview ruler */ private IAnnotationModel fModel; /** The view to which this ruler is connected */ private ITextViewer fTextViewer; /** The ruler's canvas */ private Canvas fCanvas; /** The ruler's header */ private Canvas fHeader; /** The buffer for double buffering */ private Image fBuffer; /** The internal listener */ private InternalListener fInternalListener= new InternalListener(); /** The width of this vertical ruler */ private int fWidth; /** The hit detection cursor. Do not dispose. */ private Cursor fHitDetectionCursor; /** The last cursor. Do not dispose. */ private Cursor fLastCursor; /** The line of the last mouse button activity */ private int fLastMouseButtonActivityLine= -1; /** The actual annotation height */ private int fAnnotationHeight= -1; /** The annotation access */ private IAnnotationAccess fAnnotationAccess; /** The header painter */ private HeaderPainter fHeaderPainter; /** * The list of annotation types to be shown in this ruler. * @since 3.0 */ private Set fConfiguredAnnotationTypes= new HashSet(); /** * The list of annotation types to be shown in the header of this ruler. * @since 3.0 */ private Set fConfiguredHeaderAnnotationTypes= new HashSet(); /** The mapping between annotation types and colors */ private Map fAnnotationTypes2Colors= new HashMap(); /** The color manager */ private ISharedTextColors fSharedTextColors; /** * All available annotation types sorted by layer. * * @since 3.0 */ private List fAnnotationsSortedByLayer= new ArrayList(); /** * All available layers sorted by layer. * This list may contain duplicates. * @since 3.0 */ private List fLayersSortedByLayer= new ArrayList(); /** * Map of allowed annotation types. * An allowed annotation type maps to <code>true</code>, a disallowed * to <code>false</code>. * @since 3.0 */ private Map fAllowedAnnotationTypes= new HashMap(); /** * Map of allowed header annotation types. * An allowed annotation type maps to <code>true</code>, a disallowed * to <code>false</code>. * @since 3.0 */ private Map fAllowedHeaderAnnotationTypes= new HashMap(); /** * The cached annotations. * @since 3.0 */ private List fCachedAnnotations= new ArrayList(); /** * Redraw runnable lock * @since 3.3 */ private Object fRunnableLock= new Object(); /** * Redraw runnable state * @since 3.3 */ private boolean fIsRunnablePosted= false; /** * Redraw runnable * @since 3.3 */ private Runnable fRunnable= new Runnable() { public void run() { synchronized (fRunnableLock) { fIsRunnablePosted= false; } redraw(); updateHeader(); } }; /** * Tells whether temporary annotations are drawn with * a separate color. This color will be computed by * discoloring the original annotation color. * * @since 3.4 */ private boolean fIsTemporaryAnnotationDiscolored; /** * Constructs a overview ruler of the given width using the given annotation access and the given * color manager. * <p><strong>Note:</strong> As of 3.4, temporary annotations are no longer discolored. * Use {@link #OverviewRuler(IAnnotationAccess, int, ISharedTextColors, boolean)} if you * want to keep the old behavior.</p> * * @param annotationAccess the annotation access * @param width the width of the vertical ruler * @param sharedColors the color manager */ public OverviewRuler(IAnnotationAccess annotationAccess, int width, ISharedTextColors sharedColors) { this(annotationAccess, width, sharedColors, false); } /** * Constructs a overview ruler of the given width using the given annotation * access and the given color manager. * * @param annotationAccess the annotation access * @param width the width of the vertical ruler * @param sharedColors the color manager * @param discolorTemporaryAnnotation <code>true</code> if temporary annotations should be discolored * @since 3.4 */ public OverviewRuler(IAnnotationAccess annotationAccess, int width, ISharedTextColors sharedColors, boolean discolorTemporaryAnnotation) { fAnnotationAccess= annotationAccess; fWidth= width; fSharedTextColors= sharedColors; fIsTemporaryAnnotationDiscolored= discolorTemporaryAnnotation; } /* * @see org.eclipse.jface.text.source.IVerticalRulerInfo#getControl() */ public Control getControl() { return fCanvas; } /* * @see org.eclipse.jface.text.source.IVerticalRulerInfo#getWidth() */ public int getWidth() { return fWidth; } /* * @see org.eclipse.jface.text.source.IVerticalRuler#setModel(org.eclipse.jface.text.source.IAnnotationModel) */ public void setModel(IAnnotationModel model) { if (model != fModel || model != null) { if (fModel != null) fModel.removeAnnotationModelListener(fInternalListener); fModel= model; if (fModel != null) fModel.addAnnotationModelListener(fInternalListener); update(); } } /* * @see org.eclipse.jface.text.source.IVerticalRuler#createControl(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.ITextViewer) */ public Control createControl(Composite parent, ITextViewer textViewer) { fTextViewer= textViewer; fHitDetectionCursor= parent.getDisplay().getSystemCursor(SWT.CURSOR_HAND); fHeader= new Canvas(parent, SWT.NONE); if (fAnnotationAccess instanceof IAnnotationAccessExtension) { fHeader.addMouseTrackListener(new MouseTrackAdapter() { /* * @see org.eclipse.swt.events.MouseTrackAdapter#mouseHover(org.eclipse.swt.events.MouseEvent) * @since 3.3 */ public void mouseEnter(MouseEvent e) { updateHeaderToolTipText(); } }); } fCanvas= new Canvas(parent, SWT.NO_BACKGROUND); fCanvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent event) { if (fTextViewer != null) doubleBufferPaint(event.gc); } }); fCanvas.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent event) { handleDispose(); fTextViewer= null; } }); fCanvas.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent event) { handleMouseDown(event); } }); fCanvas.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent event) { handleMouseMove(event); } }); if (fTextViewer != null) fTextViewer.addTextListener(fInternalListener); return fCanvas; } /** * Disposes the ruler's resources. */ private void handleDispose() { if (fTextViewer != null) { fTextViewer.removeTextListener(fInternalListener); fTextViewer= null; } if (fModel != null) fModel.removeAnnotationModelListener(fInternalListener); if (fBuffer != null) { fBuffer.dispose(); fBuffer= null; } fConfiguredAnnotationTypes.clear(); fAllowedAnnotationTypes.clear(); fConfiguredHeaderAnnotationTypes.clear(); fAllowedHeaderAnnotationTypes.clear(); fAnnotationTypes2Colors.clear(); fAnnotationsSortedByLayer.clear(); fLayersSortedByLayer.clear(); } /** * Double buffer drawing. * * @param dest the GC to draw into */ private void doubleBufferPaint(GC dest) { Point size= fCanvas.getSize(); if (size.x <= 0 || size.y <= 0) return; if (fBuffer != null) { Rectangle r= fBuffer.getBounds(); if (r.width != size.x || r.height != size.y) { fBuffer.dispose(); fBuffer= null; } } if (fBuffer == null) fBuffer= new Image(fCanvas.getDisplay(), size.x, size.y); GC gc= new GC(fBuffer); try { gc.setBackground(fCanvas.getBackground()); gc.fillRectangle(0, 0, size.x, size.y); cacheAnnotations(); if (fTextViewer instanceof ITextViewerExtension5) doPaint1(gc); else doPaint(gc); } finally { gc.dispose(); } dest.drawImage(fBuffer, 0, 0); } /** * Draws this overview ruler. * * @param gc the GC to draw into */ private void doPaint(GC gc) { Rectangle r= new Rectangle(0, 0, 0, 0); int yy, hh= ANNOTATION_HEIGHT; IDocument document= fTextViewer.getDocument(); IRegion visible= fTextViewer.getVisibleRegion(); StyledText textWidget= fTextViewer.getTextWidget(); int maxLines= textWidget.getLineCount(); Point size= fCanvas.getSize(); int writable= JFaceTextUtil.computeLineHeight(textWidget, 0, maxLines, maxLines); if (size.y > writable) size.y= Math.max(writable - fHeader.getSize().y, 0); for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) { Object annotationType= iterator.next(); if (skip(annotationType)) continue; int[] style= new int[] { FilterIterator.PERSISTENT, FilterIterator.TEMPORARY }; for (int t=0; t < style.length; t++) { Iterator e= new FilterIterator(annotationType, style[t], fCachedAnnotations.iterator()); boolean areColorsComputed= false; Color fill= null; Color stroke= null; for (int i= 0; e.hasNext(); i++) { Annotation a= (Annotation) e.next(); Position p= fModel.getPosition(a); if (p == null || !p.overlapsWith(visible.getOffset(), visible.getLength())) continue; int annotationOffset= Math.max(p.getOffset(), visible.getOffset()); int annotationEnd= Math.min(p.getOffset() + p.getLength(), visible.getOffset() + visible.getLength()); int annotationLength= annotationEnd - annotationOffset; try { if (ANNOTATION_HEIGHT_SCALABLE) { int numbersOfLines= document.getNumberOfLines(annotationOffset, annotationLength); // don't count empty trailing lines IRegion lastLine= document.getLineInformationOfOffset(annotationOffset + annotationLength); if (lastLine.getOffset() == annotationOffset + annotationLength) { numbersOfLines -= 2; hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT; if (hh < ANNOTATION_HEIGHT) hh= ANNOTATION_HEIGHT; } else hh= ANNOTATION_HEIGHT; } fAnnotationHeight= hh; int startLine= textWidget.getLineAtOffset(annotationOffset - visible.getOffset()); yy= Math.min((startLine * size.y) / maxLines, size.y - hh); if (!areColorsComputed) { fill= getFillColor(annotationType, style[t] == FilterIterator.TEMPORARY); stroke= getStrokeColor(annotationType, style[t] == FilterIterator.TEMPORARY); areColorsComputed= true; } if (fill != null) { gc.setBackground(fill); gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh); } if (stroke != null) { gc.setForeground(stroke); r.x= INSET; r.y= yy; r.width= size.x - (2 * INSET); r.height= hh; gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance gc.drawRectangle(r); } } catch (BadLocationException x) { } } } } } private void cacheAnnotations() { fCachedAnnotations.clear(); if (fModel != null) { Iterator iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { Annotation annotation= (Annotation) iter.next(); if (annotation.isMarkedDeleted()) continue; if (skip(annotation.getType())) continue; fCachedAnnotations.add(annotation); } } } /** * Draws this overview ruler. Uses <code>ITextViewerExtension5</code> for * its implementation. Will replace <code>doPaint(GC)</code>. * * @param gc the GC to draw into */ private void doPaint1(GC gc) { Rectangle r= new Rectangle(0, 0, 0, 0); int yy, hh= ANNOTATION_HEIGHT; ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer; IDocument document= fTextViewer.getDocument(); StyledText textWidget= fTextViewer.getTextWidget(); int maxLines= textWidget.getLineCount(); Point size= fCanvas.getSize(); int writable= JFaceTextUtil.computeLineHeight(textWidget, 0, maxLines, maxLines); if (size.y > writable) size.y= Math.max(writable - fHeader.getSize().y, 0); for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) { Object annotationType= iterator.next(); if (skip(annotationType)) continue; int[] style= new int[] { FilterIterator.PERSISTENT, FilterIterator.TEMPORARY }; for (int t=0; t < style.length; t++) { Iterator e= new FilterIterator(annotationType, style[t], fCachedAnnotations.iterator()); boolean areColorsComputed= false; Color fill= null; Color stroke= null; for (int i= 0; e.hasNext(); i++) { Annotation a= (Annotation) e.next(); Position p= fModel.getPosition(a); if (p == null) continue; IRegion widgetRegion= extension.modelRange2WidgetRange(new Region(p.getOffset(), p.getLength())); if (widgetRegion == null) continue; try { if (ANNOTATION_HEIGHT_SCALABLE) { int numbersOfLines= document.getNumberOfLines(p.getOffset(), p.getLength()); // don't count empty trailing lines IRegion lastLine= document.getLineInformationOfOffset(p.getOffset() + p.getLength()); if (lastLine.getOffset() == p.getOffset() + p.getLength()) { numbersOfLines -= 2; hh= (numbersOfLines * size.y) / maxLines + ANNOTATION_HEIGHT; if (hh < ANNOTATION_HEIGHT) hh= ANNOTATION_HEIGHT; } else hh= ANNOTATION_HEIGHT; } fAnnotationHeight= hh; int startLine= textWidget.getLineAtOffset(widgetRegion.getOffset()); yy= Math.min((startLine * size.y) / maxLines, size.y - hh); if (!areColorsComputed) { fill= getFillColor(annotationType, style[t] == FilterIterator.TEMPORARY); stroke= getStrokeColor(annotationType, style[t] == FilterIterator.TEMPORARY); areColorsComputed= true; } if (fill != null) { gc.setBackground(fill); gc.fillRectangle(INSET, yy, size.x-(2*INSET), hh); } if (stroke != null) { gc.setForeground(stroke); r.x= INSET; r.y= yy; r.width= size.x - (2 * INSET); r.height= hh; gc.setLineWidth(0); // NOTE: 0 means width is 1 but with optimized performance gc.drawRectangle(r); } } catch (BadLocationException x) { } } } } } /* * @see org.eclipse.jface.text.source.IVerticalRuler#update() */ public void update() { if (fCanvas != null && !fCanvas.isDisposed()) { Display d= fCanvas.getDisplay(); if (d != null) { synchronized (fRunnableLock) { if (fIsRunnablePosted) return; fIsRunnablePosted= true; } d.asyncExec(fRunnable); } } } /** * Redraws the overview ruler. */ private void redraw() { if (fTextViewer == null || fModel == null) return; if (fCanvas != null && !fCanvas.isDisposed()) { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } /** * Translates a given y-coordinate of this ruler into the corresponding * document lines. The number of lines depends on the concrete scaling * given as the ration between the height of this ruler and the length * of the document. * * @param y_coordinate the y-coordinate * @return the corresponding document lines */ private int[] toLineNumbers(int y_coordinate) { StyledText textWidget= fTextViewer.getTextWidget(); int maxLines= textWidget.getContent().getLineCount(); int rulerLength= fCanvas.getSize().y; int writable= JFaceTextUtil.computeLineHeight(textWidget, 0, maxLines, maxLines); if (rulerLength > writable) rulerLength= Math.max(writable - fHeader.getSize().y, 0); if (y_coordinate >= writable || y_coordinate >= rulerLength) return new int[] {-1, -1}; int[] lines= new int[2]; int pixel0= Math.max(y_coordinate - 1, 0); int pixel1= Math.min(rulerLength, y_coordinate + 1); rulerLength= Math.max(rulerLength, 1); lines[0]= (pixel0 * maxLines) / rulerLength; lines[1]= (pixel1 * maxLines) / rulerLength; if (fTextViewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5) fTextViewer; lines[0]= extension.widgetLine2ModelLine(lines[0]); lines[1]= extension.widgetLine2ModelLine(lines[1]); } else { try { IRegion visible= fTextViewer.getVisibleRegion(); int lineNumber= fTextViewer.getDocument().getLineOfOffset(visible.getOffset()); lines[0] += lineNumber; lines[1] += lineNumber; } catch (BadLocationException x) { } } return lines; } /** * Returns the position of the first annotation found in the given line range. * * @param lineNumbers the line range * @return the position of the first found annotation */ private Position getAnnotationPosition(int[] lineNumbers) { if (lineNumbers[0] == -1) return null; Position found= null; try { IDocument d= fTextViewer.getDocument(); IRegion line= d.getLineInformation(lineNumbers[0]); int start= line.getOffset(); line= d.getLineInformation(lineNumbers[lineNumbers.length - 1]); int end= line.getOffset() + line.getLength(); for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) { Object annotationType= fAnnotationsSortedByLayer.get(i); Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY); while (e.hasNext() && found == null) { Annotation a= (Annotation) e.next(); if (a.isMarkedDeleted()) continue; if (skip(a.getType())) continue; Position p= fModel.getPosition(a); if (p == null) continue; int posOffset= p.getOffset(); int posEnd= posOffset + p.getLength(); IRegion region= d.getLineInformationOfOffset(posEnd); // trailing empty lines don't count if (posEnd > posOffset && region.getOffset() == posEnd) { posEnd--; region= d.getLineInformationOfOffset(posEnd); } if (posOffset <= end && posEnd >= start) found= p; } } } catch (BadLocationException x) { } return found; } /** * Returns the line which corresponds best to one of * the underlying annotations at the given y-coordinate. * * @param lineNumbers the line numbers * @return the best matching line or <code>-1</code> if no such line can be found */ private int findBestMatchingLineNumber(int[] lineNumbers) { if (lineNumbers == null || lineNumbers.length < 1) return -1; try { Position pos= getAnnotationPosition(lineNumbers); if (pos == null) return -1; return fTextViewer.getDocument().getLineOfOffset(pos.getOffset()); } catch (BadLocationException ex) { return -1; } } /** * Handles mouse clicks. * * @param event the mouse button down event */ private void handleMouseDown(MouseEvent event) { if (fTextViewer != null) { int[] lines= toLineNumbers(event.y); Position p= getAnnotationPosition(lines); if (p == null && event.button == 1) { try { p= new Position(fTextViewer.getDocument().getLineInformation(lines[0]).getOffset(), 0); } catch (BadLocationException e) { // do nothing } } if (p != null) { fTextViewer.revealRange(p.getOffset(), p.getLength()); fTextViewer.setSelectedRange(p.getOffset(), p.getLength()); } fTextViewer.getTextWidget().setFocus(); } fLastMouseButtonActivityLine= toDocumentLineNumber(event.y); } /** * Handles mouse moves. * * @param event the mouse move event */ private void handleMouseMove(MouseEvent event) { if (fTextViewer != null) { int[] lines= toLineNumbers(event.y); Position p= getAnnotationPosition(lines); Cursor cursor= (p != null ? fHitDetectionCursor : null); if (cursor != fLastCursor) { fCanvas.setCursor(cursor); fLastCursor= cursor; } } } /* * @see org.eclipse.jface.text.source.IOverviewRuler#addAnnotationType(java.lang.Object) */ public void addAnnotationType(Object annotationType) { fConfiguredAnnotationTypes.add(annotationType); fAllowedAnnotationTypes.clear(); } /* * @see org.eclipse.jface.text.source.IOverviewRuler#removeAnnotationType(java.lang.Object) */ public void removeAnnotationType(Object annotationType) { fConfiguredAnnotationTypes.remove(annotationType); fAllowedAnnotationTypes.clear(); } /* * @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeLayer(java.lang.Object, int) */ public void setAnnotationTypeLayer(Object annotationType, int layer) { int j= fAnnotationsSortedByLayer.indexOf(annotationType); if (j != -1) { fAnnotationsSortedByLayer.remove(j); fLayersSortedByLayer.remove(j); } if (layer >= 0) { int i= 0; int size= fLayersSortedByLayer.size(); while (i < size && layer >= ((Integer)fLayersSortedByLayer.get(i)).intValue()) i++; Integer layerObj= new Integer(layer); fLayersSortedByLayer.add(i, layerObj); fAnnotationsSortedByLayer.add(i, annotationType); } } /* * @see org.eclipse.jface.text.source.IOverviewRuler#setAnnotationTypeColor(java.lang.Object, org.eclipse.swt.graphics.Color) */ public void setAnnotationTypeColor(Object annotationType, Color color) { if (color != null) fAnnotationTypes2Colors.put(annotationType, color); else fAnnotationTypes2Colors.remove(annotationType); } /** * Returns whether the given annotation type should be skipped by the drawing routine. * * @param annotationType the annotation type * @return <code>true</code> if annotation of the given type should be skipped */ private boolean skip(Object annotationType) { return !contains(annotationType, fAllowedAnnotationTypes, fConfiguredAnnotationTypes); } /** * Returns whether the given annotation type should be skipped by the drawing routine of the header. * * @param annotationType the annotation type * @return <code>true</code> if annotation of the given type should be skipped * @since 3.0 */ private boolean skipInHeader(Object annotationType) { return !contains(annotationType, fAllowedHeaderAnnotationTypes, fConfiguredHeaderAnnotationTypes); } /** * Returns whether the given annotation type is mapped to <code>true</code> * in the given <code>allowed</code> map or covered by the <code>configured</code> * set. * * @param annotationType the annotation type * @param allowed the map with allowed annotation types mapped to booleans * @param configured the set with configured annotation types * @return <code>true</code> if annotation is contained, <code>false</code> * otherwise * @since 3.0 */ private boolean contains(Object annotationType, Map allowed, Set configured) { Boolean cached= (Boolean) allowed.get(annotationType); if (cached != null) return cached.booleanValue(); boolean covered= isCovered(annotationType, configured); allowed.put(annotationType, covered ? Boolean.TRUE : Boolean.FALSE); return covered; } /** * Computes whether the annotations of the given type are covered by the given <code>configured</code> * set. This is the case if either the type of the annotation or any of its * super types is contained in the <code>configured</code> set. * * @param annotationType the annotation type * @param configured the set with configured annotation types * @return <code>true</code> if annotation is covered, <code>false</code> * otherwise * @since 3.0 */ private boolean isCovered(Object annotationType, Set configured) { if (fAnnotationAccess instanceof IAnnotationAccessExtension) { IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; Iterator e= configured.iterator(); while (e.hasNext()) { if (extension.isSubtype(annotationType,e.next())) return true; } return false; } return configured.contains(annotationType); } /** * Returns a specification of a color that lies between the given * foreground and background color using the given scale factor. * * @param fg the foreground color * @param bg the background color * @param scale the scale factor * @return the interpolated color */ private static RGB interpolate(RGB fg, RGB bg, double scale) { return new RGB( (int) ((1.0-scale) * fg.red + scale * bg.red), (int) ((1.0-scale) * fg.green + scale * bg.green), (int) ((1.0-scale) * fg.blue + scale * bg.blue) ); } /** * Returns the grey value in which the given color would be drawn in grey-scale. * * @param rgb the color * @return the grey-scale value */ private static double greyLevel(RGB rgb) { if (rgb.red == rgb.green && rgb.green == rgb.blue) return rgb.red; return (0.299 * rgb.red + 0.587 * rgb.green + 0.114 * rgb.blue + 0.5); } /** * Returns whether the given color is dark or light depending on the colors grey-scale level. * * @param rgb the color * @return <code>true</code> if the color is dark, <code>false</code> if it is light */ private static boolean isDark(RGB rgb) { return greyLevel(rgb) > 128; } /** * Returns a color based on the color configured for the given annotation type and the given scale factor. * * @param annotationType the annotation type * @param scale the scale factor * @return the computed color */ private Color getColor(Object annotationType, double scale) { Color base= findColor(annotationType); if (base == null) return null; RGB baseRGB= base.getRGB(); RGB background= fCanvas.getBackground().getRGB(); boolean darkBase= isDark(baseRGB); boolean darkBackground= isDark(background); if (darkBase && darkBackground) background= new RGB(255, 255, 255); else if (!darkBase && !darkBackground) background= new RGB(0, 0, 0); return fSharedTextColors.getColor(interpolate(baseRGB, background, scale)); } /** * Returns the color for the given annotation type * * @param annotationType the annotation type * @return the color * @since 3.0 */ private Color findColor(Object annotationType) { Color color= (Color) fAnnotationTypes2Colors.get(annotationType); if (color != null) return color; if (fAnnotationAccess instanceof IAnnotationAccessExtension) { IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; Object[] superTypes= extension.getSupertypes(annotationType); if (superTypes != null) { for (int i= 0; i < superTypes.length; i++) { color= (Color) fAnnotationTypes2Colors.get(superTypes[i]); if (color != null) return color; } } } return null; } /** * Returns the stroke color for the given annotation type and characteristics. * * @param annotationType the annotation type * @param temporary <code>true</code> if for temporary annotations * @return the stroke color */ private Color getStrokeColor(Object annotationType, boolean temporary) { return getColor(annotationType, temporary && fIsTemporaryAnnotationDiscolored ? 0.5 : 0.2); } /** * Returns the fill color for the given annotation type and characteristics. * * @param annotationType the annotation type * @param temporary <code>true</code> if for temporary annotations * @return the fill color */ private Color getFillColor(Object annotationType, boolean temporary) { return getColor(annotationType, temporary && fIsTemporaryAnnotationDiscolored ? 0.9 : 0.75); } /* * @see IVerticalRulerInfo#getLineOfLastMouseButtonActivity() */ public int getLineOfLastMouseButtonActivity() { if (fLastMouseButtonActivityLine >= fTextViewer.getDocument().getNumberOfLines()) fLastMouseButtonActivityLine= -1; return fLastMouseButtonActivityLine; } /* * @see IVerticalRulerInfo#toDocumentLineNumber(int) */ public int toDocumentLineNumber(int y_coordinate) { if (fTextViewer == null || y_coordinate == -1) return -1; int[] lineNumbers= toLineNumbers(y_coordinate); int bestLine= findBestMatchingLineNumber(lineNumbers); if (bestLine == -1 && lineNumbers.length > 0) return lineNumbers[0]; return bestLine; } /* * @see org.eclipse.jface.text.source.IVerticalRuler#getModel() */ public IAnnotationModel getModel() { return fModel; } /* * @see org.eclipse.jface.text.source.IOverviewRuler#getAnnotationHeight() */ public int getAnnotationHeight() { return fAnnotationHeight; } /* * @see org.eclipse.jface.text.source.IOverviewRuler#hasAnnotation(int) */ public boolean hasAnnotation(int y) { return findBestMatchingLineNumber(toLineNumbers(y)) != -1; } /* * @see org.eclipse.jface.text.source.IOverviewRuler#getHeaderControl() */ public Control getHeaderControl() { return fHeader; } /* * @see org.eclipse.jface.text.source.IOverviewRuler#addHeaderAnnotationType(java.lang.Object) */ public void addHeaderAnnotationType(Object annotationType) { fConfiguredHeaderAnnotationTypes.add(annotationType); fAllowedHeaderAnnotationTypes.clear(); } /* * @see org.eclipse.jface.text.source.IOverviewRuler#removeHeaderAnnotationType(java.lang.Object) */ public void removeHeaderAnnotationType(Object annotationType) { fConfiguredHeaderAnnotationTypes.remove(annotationType); fAllowedHeaderAnnotationTypes.clear(); } /** * Updates the header of this ruler. */ private void updateHeader() { if (fHeader == null || fHeader.isDisposed()) return; fHeader.setToolTipText(null); Object colorType= null; outer: for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) { Object annotationType= fAnnotationsSortedByLayer.get(i); if (skipInHeader(annotationType) || skip(annotationType)) continue; Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); while (e.hasNext()) { if (e.next() != null) { colorType= annotationType; break outer; } } } Color color= null; if (colorType != null) color= findColor(colorType); if (color == null) { if (fHeaderPainter != null) fHeaderPainter.setColor(null); } else { if (fHeaderPainter == null) { fHeaderPainter= new HeaderPainter(); fHeader.addPaintListener(fHeaderPainter); } fHeaderPainter.setColor(color); } fHeader.redraw(); } /** * Updates the header tool tip text of this ruler. */ private void updateHeaderToolTipText() { if (fHeader == null || fHeader.isDisposed()) return; if (fHeader.getToolTipText() != null) return; String overview= ""; //$NON-NLS-1$ for (int i= fAnnotationsSortedByLayer.size() -1; i >= 0; i--) { Object annotationType= fAnnotationsSortedByLayer.get(i); if (skipInHeader(annotationType) || skip(annotationType)) continue; int count= 0; String annotationTypeLabel= null; Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); while (e.hasNext()) { Annotation annotation= (Annotation)e.next(); if (annotation != null) { if (annotationTypeLabel == null) annotationTypeLabel= ((IAnnotationAccessExtension)fAnnotationAccess).getTypeLabel(annotation); count++; } } if (annotationTypeLabel != null) { if (overview.length() > 0) overview += "\n"; //$NON-NLS-1$ overview += JFaceTextMessages.getFormattedString("OverviewRulerHeader.toolTipTextEntry", new Object[] {annotationTypeLabel, new Integer(count)}); //$NON-NLS-1$ } } if (overview.length() > 0) fHeader.setToolTipText(overview); } }
neelance/jface4ruby
jface4ruby/src/org/eclipse/jface/text/source/OverviewRuler.java
Java
epl-1.0
39,538
package org.cohorte.studio.eclipse.ui.node.project; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonBuilderFactory; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonWriter; import javax.json.stream.JsonGenerator; import org.cohorte.studio.eclipse.api.annotations.NonNull; import org.cohorte.studio.eclipse.api.objects.IHttpTransport; import org.cohorte.studio.eclipse.api.objects.INode; import org.cohorte.studio.eclipse.api.objects.IRuntime; import org.cohorte.studio.eclipse.api.objects.ITransport; import org.cohorte.studio.eclipse.api.objects.IXmppTransport; import org.cohorte.studio.eclipse.core.api.IProjectContentManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.e4.core.di.annotations.Creatable; /** * Node project content manager. * * @author Ahmad Shahwan * */ @Creatable public class CNodeContentManager implements IProjectContentManager<INode> { private static final String CONF = "conf"; //$NON-NLS-1$ private static final String RUN_JS = new StringBuilder().append(CONF).append("/run.js").toString(); //$NON-NLS-1$ @SuppressWarnings("nls") private interface IJsonKeys { String NODE = "node"; String SHELL_PORT = "shell-port"; String HTTP_PORT = "http-port"; String NAME = "name"; String TOP_COMPOSER = "top-composer"; String CONSOLE = "console"; String COHORTE_VERSION = "cohorte-version"; String TRANSPORT = "transport"; String TRANSPORT_HTTP = "transport-http"; String HTTP_IPV = "http-ipv"; String TRANSPORT_XMPP = "transport-xmpp"; String XMPP_SERVER = "xmpp-server"; String XMPP_USER_ID = "xmpp-user-jid"; String XMPP_USER_PASSWORD = "xmpp-user-password"; String XMPP_PORT = "xmpp-port"; } /** * Constructor. */ @Inject public CNodeContentManager() { } @Override public void populate(@NonNull IProject aProject, INode aModel) throws CoreException { if (!aProject.isOpen()) { aProject.open(null); } aProject.getFolder(CONF).create(true, true, null); IFile wRun = aProject.getFile(RUN_JS); StringWriter wBuffer = new StringWriter(); Map<String, Object> wProperties = new HashMap<>(1); wProperties.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriter wJWriter = Json.createWriterFactory(wProperties).createWriter(wBuffer); JsonBuilderFactory wJ = Json.createBuilderFactory(null); JsonObjectBuilder wJson = wJ.createObjectBuilder() .add(IJsonKeys.NODE, wJ.createObjectBuilder() .add(IJsonKeys.SHELL_PORT, 0) .add(IJsonKeys.HTTP_PORT, 0) .add(IJsonKeys.NAME, aModel.getName()) .add(IJsonKeys.TOP_COMPOSER, aModel.isComposer()) .add(IJsonKeys.CONSOLE, true)); JsonArrayBuilder wTransports = wJ.createArrayBuilder(); for (ITransport wTransport : aModel.getTransports()) { wTransports.add(wTransport.getName()); if (wTransport instanceof IHttpTransport) { IHttpTransport wHttp = (IHttpTransport) wTransport; String wVer = wHttp.getVersion() == IHttpTransport.EVersion.IPV4 ? "4" : "6"; //$NON-NLS-1$//$NON-NLS-2$ wJson.add(IJsonKeys.TRANSPORT_HTTP, wJ.createObjectBuilder().add(IJsonKeys.HTTP_IPV, wVer)); } if (wTransport instanceof IXmppTransport) { IXmppTransport wXmpp = (IXmppTransport) wTransport; JsonObjectBuilder wJsonXmpp = wJ.createObjectBuilder() .add(IJsonKeys.XMPP_SERVER, wXmpp.getHostname()) .add(IJsonKeys.XMPP_PORT, wXmpp.getPort()); if (wXmpp.getUsername() != null) { wJsonXmpp .add(IJsonKeys.XMPP_USER_ID, wXmpp.getUsername()) .add(IJsonKeys.XMPP_USER_PASSWORD, wXmpp.getPassword()); } wJson .add(IJsonKeys.TRANSPORT_XMPP, wJsonXmpp); } } wJson.add(IJsonKeys.TRANSPORT, wTransports); IRuntime wRuntime = aModel.getRuntime(); if (wRuntime != null) { wJson.add(IJsonKeys.COHORTE_VERSION, wRuntime.getVersion()); } JsonObject wRunJs = wJson.build(); wJWriter.write(wRunJs); InputStream wInStream = new ByteArrayInputStream(wBuffer.toString().getBytes()); wRun.create(wInStream, true, null); } }
cohorte/cohorte-studio
org.cohorte.studio.eclipse.ui.node/src/org/cohorte/studio/eclipse/ui/node/project/CNodeContentManager.java
Java
epl-1.0
4,320
/** * Copyright (c) 2014 - 2022 Frank Appel * 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: * Frank Appel - initial API and implementation */ package com.codeaffine.eclipse.swt.util; import org.eclipse.swt.widgets.Display; public class ActionScheduler { private final Display display; private final Runnable action; public ActionScheduler( Display display, Runnable action ) { this.display = display; this.action = action; } public void schedule( int delay ) { display.timerExec( delay, action ); } }
fappel/xiliary
com.codeaffine.eclipse.swt/src/com/codeaffine/eclipse/swt/util/ActionScheduler.java
Java
epl-1.0
753
/** * Copyright (c) 2010-2013, openHAB.org 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.openhab.io.habmin.services.events; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.atmosphere.annotation.Broadcast; import org.atmosphere.annotation.Suspend; import org.atmosphere.annotation.Suspend.SCOPE; import org.atmosphere.cpr.AtmosphereConfig; import org.atmosphere.cpr.AtmosphereResource; import org.atmosphere.cpr.BroadcasterFactory; import org.atmosphere.cpr.BroadcasterLifeCyclePolicyListener; import org.atmosphere.cpr.HeaderConfig; import org.atmosphere.jersey.JerseyBroadcaster; import org.atmosphere.jersey.SuspendResponse; import org.openhab.core.items.GenericItem; import org.openhab.core.items.Item; import org.openhab.core.items.ItemNotFoundException; import org.openhab.core.items.StateChangeListener; import org.openhab.core.types.State; import org.openhab.io.habmin.HABminApplication; import org.openhab.io.habmin.internal.resources.MediaTypeHelper; import org.openhab.io.habmin.internal.resources.ResponseTypeHelper; import org.openhab.ui.items.ItemUIRegistry; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jersey.api.json.JSONWithPadding; /** * <p> * This class acts as a REST resource for history data and provides different * methods to interact with the, persistence store * * <p> * The typical content types are plain text for status values and XML or JSON(P) * for more complex data structures * </p> * * <p> * This resource is registered with the Jersey servlet. * </p> * * @author Chris Jackson * @since 1.3.0 */ @Path(EventResource.PATH_EVENTS) public class EventResource { private static final Logger logger = LoggerFactory.getLogger(EventResource.class); /** The URI path to this resource */ public static final String PATH_EVENTS = "events"; /* @Context UriInfo uriInfo; @Suspend(contentType = "application/json") @GET public String suspend() { return ""; } @Broadcast(writeEntity = false) @GET @Produces({ MediaType.WILDCARD }) public SuspendResponse<Response> getItems(@Context HttpHeaders headers, @HeaderParam(HeaderConfig.X_ATMOSPHERE_TRANSPORT) String atmosphereTransport, @HeaderParam(HeaderConfig.X_CACHE_DATE) long cacheDate, @QueryParam("type") String type, @QueryParam("jsoncallback") @DefaultValue("callback") String callback, @Context AtmosphereResource resource) { logger.debug("Received HTTP GET request at '{}' for media type '{}'.", uriInfo.getPath(), type); String responseType = MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type); if (atmosphereTransport == null || atmosphereTransport.isEmpty()) { // first request => return all values // if (responseType != null) { // throw new WebApplicationException(Response.ok( // getItemStateListBean(itemNames, System.currentTimeMillis()), // responseType).build()); // } else { throw new WebApplicationException(Response.notAcceptable(null).build()); // } } String p = resource.getRequest().getPathInfo(); EventBroadcaster broadcaster = (EventBroadcaster) BroadcasterFactory.getDefault().lookup( EventBroadcaster.class, p, true); broadcaster.register(); // itemBroadcaster.addStateChangeListener(new // ItemStateChangeListener(itemNames)); return new SuspendResponse.SuspendResponseBuilder<Response>().scope(SCOPE.REQUEST) .resumeOnBroadcast(!ResponseTypeHelper.isStreamingTransport(resource.getRequest())) .broadcaster(broadcaster).outputComments(true).build(); } */ /* * @GET * * @Path("/{bundlename: [a-zA-Z_0-9]*}") * * @Produces({ MediaType.WILDCARD }) public SuspendResponse<Response> * getItemData(@Context HttpHeaders headers, @PathParam("bundlename") String * bundlename, * * @QueryParam("type") String type, @QueryParam("jsoncallback") * * @DefaultValue("callback") String callback, * * @HeaderParam(HeaderConfig.X_ATMOSPHERE_TRANSPORT) String * atmosphereTransport, * * @Context AtmosphereResource resource) { * logger.debug("Received HTTP GET request at '{}' for media type '{}'.", * uriInfo.getPath(), type ); * * if (atmosphereTransport == null || atmosphereTransport.isEmpty()) { final * String responseType = * MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), * type); if (responseType != null) { final Object responseObject = * responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT) ? new * JSONWithPadding( getBundleBean(bundlename, true), callback) : * getBundleBean(bundlename, true); throw new * WebApplicationException(Response.ok(responseObject, * responseType).build()); } else { throw new * WebApplicationException(Response.notAcceptable(null).build()); } } * GeneralBroadcaster itemBroadcaster = (GeneralBroadcaster) * BroadcasterFactory.getDefault().lookup( GeneralBroadcaster.class, * resource.getRequest().getPathInfo(), true); return new * SuspendResponse.SuspendResponseBuilder<Response>().scope(SCOPE.REQUEST) * .resumeOnBroadcast * (!ResponseTypeHelper.isStreamingTransport(resource.getRequest())) * .broadcaster(itemBroadcaster).outputComments(true).build(); } * * public static BundleBean createBundleBean(Bundle bundle, String uriPath, * boolean detail) { BundleBean bean = new BundleBean(); * * bean.name = bundle.getSymbolicName(); bean.version = * bundle.getVersion().toString(); bean.modified = bundle.getLastModified(); * bean.id = bundle.getBundleId(); bean.state = bundle.getState(); bean.link * = uriPath; * * return bean; } * * static public Item getBundle(String itemname, String uriPath) { * ItemUIRegistry registry = HABminApplication.getItemUIRegistry(); if * (registry != null) { try { Item item = registry.getItem(itemname); return * item; } catch (ItemNotFoundException e) { logger.debug(e.getMessage()); } * } return null; } * * private ItemBean getBundleBean(String bundlename, String uriPath) { * * Item item = getItem(itemname); if (item != null) { return * createBundleBean(item, uriInfo.getBaseUri().toASCIIString(), true); } * else { * logger.info("Received HTTP GET request at '{}' for the unknown item '{}'." * , uriInfo.getPath(), itemname); throw new WebApplicationException(404); } * } * * private List<BundleBean> getBundles(String uriPath) { List<BundleBean> * beans = new LinkedList<BundleBean>(); * * BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) * .getBundleContext(); * * for (Bundle bundle : bundleContext.getBundles()) { * logger.info(bundle.toString()); BundleBean bean = * (BundleBean)createBundleBean(bundle, uriPath, false); * * if(bean != null) beans.add(bean); } return beans; } */ }
jenskastensson/openhab
bundles/io/org.openhab.io.habmin/src/main/java/org/openhab/io/habmin/services/events/EventResource.java
Java
epl-1.0
7,435
/******************************************************************************* * Copyright (c) 2014 Pivotal Software, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Pivotal Software, Inc. - initial API and implementation *******************************************************************************/ package org.springsource.ide.eclipse.gradle.core.modelmanager; import org.eclipse.core.runtime.IProgressMonitor; import org.springsource.ide.eclipse.gradle.core.GradleProject; /** * Interface that hides the mechanics of how models are being built via Gradle's tooling API (or whatever way * models are being built). To implement a ModelBuilder create a subclass of AbstractModelBuilder */ public interface ModelBuilder { public <T> BuildResult<T> buildModel(GradleProject project, Class<T> type, final IProgressMonitor mon); }
oxmcvusd/eclipse-integration-gradle
org.springsource.ide.eclipse.gradle.core/src/org/springsource/ide/eclipse/gradle/core/modelmanager/ModelBuilder.java
Java
epl-1.0
1,069
/******************************************************************************* "FreePastry" Peer-to-Peer Application Development Substrate Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute for Software Systems. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Rice University (RICE), Max Planck Institute for Software Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is" basis, without any representations or warranties of any kind, express or implied including, but not limited to, representations or warranties of non-infringement, merchantability or fitness for a particular purpose. In no event shall RICE, MPI-SWS 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.mpisws.p2p.transport.peerreview.commitment; import java.io.IOException; import java.nio.ByteBuffer; import java.security.SignatureException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.mpisws.p2p.transport.MessageCallback; import org.mpisws.p2p.transport.MessageRequestHandle; import org.mpisws.p2p.transport.peerreview.PeerReview; import org.mpisws.p2p.transport.peerreview.PeerReviewConstants; import org.mpisws.p2p.transport.peerreview.history.HashSeq; import org.mpisws.p2p.transport.peerreview.history.IndexEntry; import org.mpisws.p2p.transport.peerreview.history.SecureHistory; import org.mpisws.p2p.transport.peerreview.history.logentry.EvtAck; import org.mpisws.p2p.transport.peerreview.history.logentry.EvtRecv; import org.mpisws.p2p.transport.peerreview.history.logentry.EvtSend; import org.mpisws.p2p.transport.peerreview.history.logentry.EvtSign; import org.mpisws.p2p.transport.peerreview.identity.IdentityTransport; import org.mpisws.p2p.transport.peerreview.infostore.PeerInfoStore; import org.mpisws.p2p.transport.peerreview.message.AckMessage; import org.mpisws.p2p.transport.peerreview.message.OutgoingUserDataMessage; import org.mpisws.p2p.transport.peerreview.message.UserDataMessage; import org.mpisws.p2p.transport.util.MessageRequestHandleImpl; import rice.environment.logging.Logger; import rice.p2p.commonapi.rawserialization.RawSerializable; import rice.p2p.util.MathUtils; import rice.p2p.util.rawserialization.SimpleInputBuffer; import rice.p2p.util.tuples.Tuple; import rice.selector.TimerTask; public class CommitmentProtocolImpl<Handle extends RawSerializable, Identifier extends RawSerializable> implements CommitmentProtocol<Handle, Identifier>, PeerReviewConstants { public int MAX_PEERS = 250; public int INITIAL_TIMEOUT_MILLIS = 1000; public int RETRANSMIT_TIMEOUT_MILLIS = 1000; public int RECEIVE_CACHE_SIZE = 100; public int MAX_RETRANSMISSIONS = 2; public int TI_PROGRESS = 1; public int PROGRESS_INTERVAL_MILLIS = 1000; public int MAX_ENTRIES_PER_MS = 1000000; /* Max number of entries per millisecond */ /** * We need to keep some state for each peer, including separate transmit and * receive queues */ Map<Identifier, PeerInfo<Handle>> peer = new HashMap<Identifier, PeerInfo<Handle>>(); /** * We cache a few recently received messages, so we can recognize duplicates. * We also remember the location of the corresponding RECV entry in the log, * so we can reproduce the matching acknowledgment */ Map<Tuple<Identifier, Long>, ReceiveInfo<Identifier>> receiveCache; AuthenticatorStore<Identifier> authStore; SecureHistory history; PeerReview<Handle, Identifier> peerreview; PeerInfoStore<Handle, Identifier> infoStore; IdentityTransport<Handle, Identifier> transport; /** * If the time is more different than this from a peer, we discard the message */ long timeToleranceMillis; int nextReceiveCacheEntry; int signatureSizeBytes; int hashSizeBytes; TimerTask makeProgressTask; Logger logger; public CommitmentProtocolImpl(PeerReview<Handle,Identifier> peerreview, IdentityTransport<Handle, Identifier> transport, PeerInfoStore<Handle, Identifier> infoStore, AuthenticatorStore<Identifier> authStore, SecureHistory history, long timeToleranceMillis) throws IOException { this.peerreview = peerreview; this.transport = transport; this.infoStore = infoStore; this.authStore = authStore; this.history = history; this.nextReceiveCacheEntry = 0; // this.numPeers = 0; this.timeToleranceMillis = timeToleranceMillis; this.logger = peerreview.getEnvironment().getLogManager().getLogger(CommitmentProtocolImpl.class, null); initReceiveCache(); makeProgressTask = new TimerTask(){ @Override public void run() { makeProgressAllPeers(); } }; peerreview.getEnvironment().getSelectorManager().schedule(makeProgressTask, PROGRESS_INTERVAL_MILLIS, PROGRESS_INTERVAL_MILLIS); } /** * Load the last events from the history into the cache */ protected void initReceiveCache() throws IOException { receiveCache = new LinkedHashMap<Tuple<Identifier, Long>, ReceiveInfo<Identifier>>(RECEIVE_CACHE_SIZE, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > RECEIVE_CACHE_SIZE; } }; for (long i=history.getNumEntries()-1; (i>=1) && (receiveCache.size() < RECEIVE_CACHE_SIZE); i--) { IndexEntry hIndex = history.statEntry(i); if (hIndex.getType() == PeerReviewConstants.EVT_RECV) { // NOTE: this could be more efficient, because we don't need the whole thing SimpleInputBuffer sib = new SimpleInputBuffer(history.getEntry(hIndex, hIndex.getSizeInFile())); Identifier thisSender = peerreview.getIdSerializer().deserialize(sib); // NOTE: the message better start with the sender seq, but this is done within this protocol addToReceiveCache(thisSender, sib.readLong(), i); } } } protected void addToReceiveCache(Identifier id, long senderSeq, long indexInLocalHistory) { receiveCache.put(new Tuple<Identifier, Long>(id,senderSeq), new ReceiveInfo<Identifier>(id, senderSeq, indexInLocalHistory)); } protected PeerInfo<Handle> lookupPeer(Handle handle) { PeerInfo<Handle> ret = peer.get(peerreview.getIdentifierExtractor().extractIdentifier(handle)); if (ret != null) return ret; ret = new PeerInfo<Handle>(handle); peer.put(peerreview.getIdentifierExtractor().extractIdentifier(handle), ret); return ret; } @Override public void notifyCertificateAvailable(Identifier id) { makeProgress(id); } /** * Checks whether an incoming message is already in the log (which can happen with duplicates). * If not, it adds the message to the log. * @return The ack message and whether it was already logged. * @throws SignatureException */ @Override public Tuple<AckMessage<Identifier>,Boolean> logMessageIfNew(UserDataMessage<Handle> udm) { try { boolean loggedPreviously; // part of the return statement long seqOfRecvEntry; byte[] myHashTop; byte[] myHashTopMinusOne; // SimpleInputBuffer sib = new SimpleInputBuffer(message); // UserDataMessage<Handle> udm = UserDataMessage.build(sib, peerreview.getHandleSerializer(), peerreview.getHashSizeInBytes(), peerreview.getSignatureSizeInBytes()); /* Check whether the log contains a matching RECV entry, i.e. one with a message from the same node and with the same send sequence number */ long indexOfRecvEntry = findRecvEntry(peerreview.getIdentifierExtractor().extractIdentifier(udm.getSenderHandle()), udm.getTopSeq()); /* If there is no such RECV entry, we append one */ if (indexOfRecvEntry < 0L) { /* Construct the RECV entry and append it to the log */ myHashTopMinusOne = history.getTopLevelEntry().getHash(); EvtRecv<Handle> recv = udm.getReceiveEvent(transport); history.appendEntry(EVT_RECV, true, recv.serialize()); HashSeq foo = history.getTopLevelEntry(); myHashTop = foo.getHash(); seqOfRecvEntry = foo.getSeq(); addToReceiveCache(peerreview.getIdentifierExtractor().extractIdentifier(udm.getSenderHandle()), udm.getTopSeq(), history.getNumEntries() - 1); if (logger.level < Logger.FINE) logger.log("New message logged as seq#"+seqOfRecvEntry); /* Construct the SIGN entry and append it to the log */ history.appendEntry(EVT_SIGN, true, new EvtSign(udm.getHTopMinusOne(),udm.getSignature()).serialize()); loggedPreviously = false; } else { loggedPreviously = true; /* If the RECV entry already exists, retrieve it */ // unsigned char type; // bool ok = true; IndexEntry i2 = history.statEntry(indexOfRecvEntry); //, &seqOfRecvEntry, &type, NULL, NULL, myHashTop); IndexEntry i1 = history.statEntry(indexOfRecvEntry-1); //, NULL, NULL, NULL, NULL, myHashTopMinusOne); assert(i1 != null && i2 != null && i2.getType() == EVT_RECV) : "i1:"+i1+" i2:"+i2; seqOfRecvEntry = i2.getSeq(); myHashTop = i2.getNodeHash(); myHashTopMinusOne = i1.getNodeHash(); if (logger.level < Logger.FINE) logger.log("This message has already been logged as seq#"+seqOfRecvEntry); } /* Generate ACK = (MSG_ACK, myID, remoteSeq, localSeq, myTopMinusOne, signature) */ byte[] hToSign = transport.hash(ByteBuffer.wrap(MathUtils.longToByteArray(seqOfRecvEntry)), ByteBuffer.wrap(myHashTop)); AckMessage<Identifier> ack = new AckMessage<Identifier>( peerreview.getLocalId(), udm.getTopSeq(), seqOfRecvEntry, myHashTopMinusOne, transport.sign(hToSign)); return new Tuple<AckMessage<Identifier>,Boolean>(ack, loggedPreviously); } catch (IOException ioe) { RuntimeException throwMe = new RuntimeException("Unexpect error logging message :"+udm); throwMe.initCause(ioe); throw throwMe; } } @Override public void notifyStatusChange(Identifier id, int newStatus) { makeProgressAllPeers(); } protected void makeProgressAllPeers() { for (Identifier i : peer.keySet()) { makeProgress(i); } } /** * Tries to make progress on the message queue of the specified peer, e.g. after that peer * has become TRUSTED, or after it has sent us an acknowledgment */ protected void makeProgress(Identifier idx) { // logger.log("makeProgress("+idx+")"); PeerInfo<Handle> info = peer.get(idx); if (info == null || (info.xmitQueue.isEmpty() && info.recvQueue.isEmpty())) { return; } /* Get the public key. If we don't have it (yet), ask the peer to send it */ if (!transport.hasCertificate(idx)) { peerreview.requestCertificate(info.handle, idx); return; } /* Transmit queue: If the peer is suspected, challenge it; otherwise, send the next message or retransmit the one currently in flight */ if (!info.xmitQueue.isEmpty()) { int status = infoStore.getStatus(idx); switch (status) { case STATUS_EXPOSED: /* Node is already exposed; no point in sending it any further messages */ if (logger.level <= Logger.WARNING) logger.log("Releasing messages sent to exposed node "+idx); info.clearXmitQueue(); return; case STATUS_SUSPECTED: /* Node is suspected; send the first unanswered challenge */ if (info.lastChallenge < (peerreview.getTime() - info.currentChallengeInterval)) { if (logger.level <= Logger.WARNING) logger.log( "Pending message for SUSPECTED node "+info.getHandle()+"; challenging node (interval="+info.currentChallengeInterval+")"); info.lastChallenge = peerreview.getTime(); info.currentChallengeInterval *= 2; peerreview.challengeSuspectedNode(info.handle); } return; case STATUS_TRUSTED: /* Node is trusted; continue below */ info.lastChallenge = -1; info.currentChallengeInterval = PeerInfo.INITIAL_CHALLENGE_INTERVAL_MICROS; break; } /* If there are no unacknowledged packets to that node, transmit the next packet */ if (info.numOutstandingPackets == 0) { info.numOutstandingPackets++; info.lastTransmit = peerreview.getTime(); info.currentTimeout = INITIAL_TIMEOUT_MILLIS; info.retransmitsSoFar = 0; OutgoingUserDataMessage<Handle> oudm = info.xmitQueue.getFirst(); // try { peerreview.transmit(info.getHandle(), oudm, null, oudm.getOptions()); // } catch (IOException ioe) { // info.xmitQueue.removeFirst(); // oudm.sendFailed(ioe); // return; // } } else if (peerreview.getTime() > (info.lastTransmit + info.currentTimeout)) { /* Otherwise, retransmit the current packet a few times, up to the specified limit */ if (info.retransmitsSoFar < MAX_RETRANSMISSIONS) { if (logger.level <= Logger.WARNING) logger.log( "Retransmitting a "+info.xmitQueue.getFirst().getPayload().remaining()+"-byte message to "+info.getHandle()+ " (lastxmit="+info.lastTransmit+", timeout="+info.currentTimeout+", type="+ info.xmitQueue.getFirst().getType()+")"); info.retransmitsSoFar++; info.currentTimeout = RETRANSMIT_TIMEOUT_MILLIS; info.lastTransmit = peerreview.getTime(); OutgoingUserDataMessage<Handle> oudm = info.xmitQueue.getFirst(); // try { peerreview.transmit(info.handle, oudm, null, oudm.getOptions()); // } catch (IOException ioe) { // info.xmitQueue.removeFirst(); // oudm.sendFailed(ioe); // return; // } } else { /* If the peer still won't acknowledge the message, file a SEND challenge with its witnesses */ if (logger.level <= Logger.WARNING) logger.log(info.handle+ " has not acknowledged our message after "+info.retransmitsSoFar+ " retransmissions; filing as evidence"); OutgoingUserDataMessage<Handle> challenge = info.xmitQueue.removeFirst(); challenge.sendFailed(new IOException("Peer Review Giving Up sending message to "+idx)); long evidenceSeq = peerreview.getEvidenceSeq(); try { infoStore.addEvidence(peerreview.getLocalId(), peerreview.getIdentifierExtractor().extractIdentifier(info.handle), evidenceSeq, challenge, null); } catch (IOException ioe) { throw new RuntimeException(ioe); } peerreview.sendEvidenceToWitnesses(peerreview.getIdentifierExtractor().extractIdentifier(info.handle), evidenceSeq, challenge); info.numOutstandingPackets --; } } } /* Receive queue */ if (!info.recvQueue.isEmpty() && !info.isReceiving) { info.isReceiving = true; /* Dequeue the packet. After this point, we must either deliver it or discard it */ Tuple<UserDataMessage<Handle>, Map<String, Object>> t = info.recvQueue.removeFirst(); UserDataMessage<Handle> udm = t.a(); /* Extract the authenticator */ Authenticator authenticator; byte[] innerHash = udm.getInnerHash(peerreview.getLocalId(), transport); authenticator = peerreview.extractAuthenticator( peerreview.getIdentifierExtractor().extractIdentifier(udm.getSenderHandle()), udm.getTopSeq(), EVT_SEND, innerHash, udm.getHTopMinusOne(), udm.getSignature()); // logger.log("received message, extract auth from "+udm.getSenderHandle()+" seq:"+udm.getTopSeq()+" "+ // MathUtils.toBase64(innerHash)+" htop-1:"+MathUtils.toBase64(udm.getHTopMinusOne())+" sig:"+MathUtils.toBase64(udm.getSignature())); if (authenticator != null) { /* At this point, we are convinced that: - The remote node is TRUSTED [TODO!!] - The message has an acceptable sequence number - The message is properly signed Now we must check our log for an existing RECV entry: - If we already have such an entry, we generate the ACK from there - If we do not yet have the entry, we log the message and deliver it */ Tuple<AckMessage<Identifier>, Boolean> ret = logMessageIfNew(udm); /* Since the message is not yet in the log, deliver it to the application */ if (!ret.b()) { if (logger.level <= Logger.FINE) logger.log( "Delivering message from "+udm.getSenderHandle()+" via "+info.handle+" ("+ udm.getPayloadLen()+" bytes; "+udm.getRelevantLen()+"/"+udm.getPayloadLen()+" relevant)"); try { peerreview.getApp().messageReceived(udm.getSenderHandle(), udm.getPayload(), t.b()); } catch (IOException ioe) { logger.logException("Error handling "+udm, ioe); } } else { if (logger.level <= Logger.FINE) logger.log( "Message from "+udm.getSenderHandle()+" via "+info.getHandle()+" was previously logged; not delivered"); } /* Send the ACK */ if (logger.level <= Logger.FINE) logger.log("Returning ACK to"+info.getHandle()); // try { peerreview.transmit(info.handle, ret.a(), null, t.b()); // } catch (IOException ioe) { // throw new RuntimeException("Major problem, ack couldn't be serialized." +ret.a(),ioe); // } } else { if (logger.level <= Logger.WARNING) logger.log("Cannot verify signature on message "+udm.getTopSeq()+" from "+info.getHandle()+"; discarding"); } /* Release the message */ info.isReceiving = false; makeProgress(idx); } } protected long findRecvEntry(Identifier id, long seq) { ReceiveInfo<Identifier> ret = receiveCache.get(new Tuple<Identifier, Long>(id,seq)); if (ret == null) return -1; return ret.indexInLocalHistory; } protected long findAckEntry(Identifier id, long seq) { return -1; } /** * Handle an incoming USERDATA message */ @Override public void handleIncomingMessage(Handle source, UserDataMessage<Handle> msg, Map<String, Object> options) throws IOException { // char buf1[256]; /* Check whether the timestamp (in the sequence number) is close enough to our local time. If not, the node may be trying to roll forward its clock, so we discard the message. */ long txmit = (msg.getTopSeq() / MAX_ENTRIES_PER_MS); if ((txmit < (peerreview.getTime()-timeToleranceMillis)) || (txmit > (peerreview.getTime()+timeToleranceMillis))) { if (logger.level <= Logger.WARNING) logger.log("Invalid sequence no #"+msg.getTopSeq()+" on incoming message (dt="+(txmit-peerreview.getTime())+"); discarding"); return; } /** * Append a copy of the message to our receive queue. If the node is * trusted, the message is going to be delivered directly by makeProgress(); * otherwise a challenge is sent. */ lookupPeer(source).recvQueue.addLast(new Tuple<UserDataMessage<Handle>, Map<String,Object>>(msg,options)); makeProgress(peerreview.getIdentifierExtractor().extractIdentifier(source)); } @Override public MessageRequestHandle<Handle, ByteBuffer> handleOutgoingMessage( final Handle target, final ByteBuffer message, MessageCallback<Handle, ByteBuffer> deliverAckToMe, final Map<String, Object> options) { int relevantlen = message.remaining(); if (options != null && options.containsKey(PeerReview.RELEVANT_LENGTH)) { Number n = (Number)options.get(PeerReview.RELEVANT_LENGTH); relevantlen = n.intValue(); } assert(relevantlen >= 0); /* Append a SEND entry to our local log */ byte[] hTopMinusOne, hTop, hToSign; // long topSeq; hTopMinusOne = history.getTopLevelEntry().getHash(); EvtSend<Identifier> evtSend; if (relevantlen < message.remaining()) { evtSend = new EvtSend<Identifier>(peerreview.getIdentifierExtractor().extractIdentifier(target),message,relevantlen,transport); } else { evtSend = new EvtSend<Identifier>(peerreview.getIdentifierExtractor().extractIdentifier(target),message); } try { // logger.log("XXXa "+Arrays.toString(evtSend.serialize().array())); history.appendEntry(evtSend.getType(), true, evtSend.serialize()); } catch (IOException ioe) { MessageRequestHandle<Handle, ByteBuffer> ret = new MessageRequestHandleImpl<Handle, ByteBuffer>(target,message,options); if (deliverAckToMe != null) deliverAckToMe.sendFailed(ret, ioe); return ret; } // hTop, &topSeq HashSeq top = history.getTopLevelEntry(); /* Sign the authenticator */ // logger.log("about to sign: "+top.getSeq()+" "+MathUtils.toBase64(top.getHash())); hToSign = transport.hash(ByteBuffer.wrap(MathUtils.longToByteArray(top.getSeq())), ByteBuffer.wrap(top.getHash())); byte[] signature = transport.sign(hToSign); /* Append a SENDSIGN entry */ ByteBuffer relevantMsg = message; if (relevantlen < message.remaining()) { relevantMsg = ByteBuffer.wrap(message.array(), message.position(), relevantlen); } else { relevantMsg = ByteBuffer.wrap(message.array(), message.position(), message.remaining()); } try { history.appendEntry(EVT_SENDSIGN, true, relevantMsg, ByteBuffer.wrap(signature)); } catch (IOException ioe) { MessageRequestHandle<Handle, ByteBuffer> ret = new MessageRequestHandleImpl<Handle, ByteBuffer>(target,message,options); if (deliverAckToMe != null) deliverAckToMe.sendFailed(ret, ioe); return ret; } /* Construct a USERDATA message... */ assert((relevantlen == message.remaining()) || (relevantlen < 255)); PeerInfo<Handle> pi = lookupPeer(target); OutgoingUserDataMessage<Handle> udm = new OutgoingUserDataMessage<Handle>(top.getSeq(), peerreview.getLocalHandle(), hTopMinusOne, signature, message, relevantlen, options, pi, deliverAckToMe); /* ... and put it into the send queue. If the node is trusted and does not have any unacknowledged messages, makeProgress() will simply send it out. */ pi.xmitQueue.addLast(udm); makeProgress(peerreview.getIdentifierExtractor().extractIdentifier(target)); return udm; } /* This is called if we receive an acknowledgment from another node */ @Override public void handleIncomingAck(Handle source, AckMessage<Identifier> ackMessage, Map<String, Object> options) throws IOException { // AckMessage<Identifier> ackMessage = AckMessage.build(sib, peerreview.getIdSerializer(), hasher.getHashSizeBytes(), transport.signatureSizeInBytes()); /* Acknowledgment: Log it (if we don't have it already) and send the next message, if any */ if (logger.level <= Logger.FINE) logger.log("Received an ACK from "+source); // TODO: check that ackMessage came from the source if (transport.hasCertificate(ackMessage.getNodeId())) { PeerInfo<Handle> p = lookupPeer(source); boolean checkAck = true; OutgoingUserDataMessage<Handle> udm = null; if (p.xmitQueue.isEmpty()) { checkAck = false; // don't know why this happens, but maybe the ACK gets duplicated somehow } else { udm = p.xmitQueue.getFirst(); } /* The ACK must acknowledge the sequence number of the packet that is currently at the head of the send queue */ if (checkAck && ackMessage.getSendEntrySeq() == udm.getTopSeq()) { /* Now we're ready to check the signature */ /* The peer will have logged a RECV entry, and the signature is calculated over that entry. To verify the signature, we must reconstruct that RECV entry locally */ byte[] innerHash = udm.getInnerHash(transport); Authenticator authenticator = peerreview.extractAuthenticator( ackMessage.getNodeId(), ackMessage.getRecvEntrySeq(), EVT_RECV, innerHash, ackMessage.getHashTopMinusOne(), ackMessage.getSignature()); if (authenticator != null) { /* Signature is okay... append an ACK entry to the log */ if (logger.level <= Logger.FINE) logger.log("ACK is okay; logging "+ackMessage); EvtAck<Identifier> evtAck = new EvtAck<Identifier>(ackMessage.getNodeId(), ackMessage.getSendEntrySeq(), ackMessage.getRecvEntrySeq(), ackMessage.getHashTopMinusOne(), ackMessage.getSignature()); history.appendEntry(EVT_ACK, true, evtAck.serialize()); udm.sendComplete(); //ackMessage.getSendEntrySeq()); /* Remove the message from the xmit queue */ p.xmitQueue.removeFirst(); p.numOutstandingPackets--; /* Make progress (e.g. by sending the next message) */ makeProgress(peerreview.getIdentifierExtractor().extractIdentifier(p.getHandle())); } else { if (logger.level <= Logger.WARNING) logger.log("Invalid ACK from <"+ackMessage.getNodeId()+">; discarding"); } } else { if (findAckEntry(ackMessage.getNodeId(), ackMessage.getSendEntrySeq()) < 0) { if (logger.level <= Logger.WARNING) logger.log("<"+ackMessage.getNodeId()+"> has ACKed something we haven't sent ("+ackMessage.getSendEntrySeq()+"); discarding"); } else { if (logger.level <= Logger.WARNING) logger.log("Duplicate ACK from <"+ackMessage.getNodeId()+">; discarding"); } } } else { if (logger.level <= Logger.WARNING) logger.log("We got an ACK from <"+ackMessage.getNodeId()+">, but we don't have the certificate; discarding"); } } @Override public void setTimeToleranceMillis(long timeToleranceMillis) { this.timeToleranceMillis = timeToleranceMillis; } }
michele-loreti/jResp
core/org.cmg.jresp.pastry/pastry-2.1/src/org/mpisws/p2p/transport/peerreview/commitment/CommitmentProtocolImpl.java
Java
epl-1.0
27,337
/******************************************************************************* * Copyright (c) 2017 TypeFox GmbH (http://www.typefox.io) 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.xtext.formatting2.regionaccess.internal; import static org.eclipse.xtext.formatting2.regionaccess.HiddenRegionPartAssociation.*; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.formatting2.debug.TextRegionAccessToString; import org.eclipse.xtext.formatting2.regionaccess.IEObjectRegion; import org.eclipse.xtext.formatting2.regionaccess.IHiddenRegion; import org.eclipse.xtext.formatting2.regionaccess.ISemanticRegion; import org.eclipse.xtext.formatting2.regionaccess.ITextRegionAccess; import org.eclipse.xtext.formatting2.regionaccess.ITextRegionDiffBuilder; import org.eclipse.xtext.formatting2.regionaccess.ITextSegment; import org.eclipse.xtext.serializer.ISerializationContext; import org.eclipse.xtext.serializer.acceptor.ISequenceAcceptor; import org.eclipse.xtext.util.ITextRegion; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * @author Moritz Eysholdt - Initial contribution and API */ public class StringBasedTextRegionAccessDiffBuilder implements ITextRegionDiffBuilder { private final static Logger LOG = Logger.getLogger(StringBasedTextRegionAccessDiffBuilder.class); protected interface Insert { public IHiddenRegion getInsertFirst(); public IHiddenRegion getInsertLast(); } protected static class MoveSource extends Rewrite { private MoveTarget target = null; public MoveSource(IHiddenRegion first, IHiddenRegion last) { super(first, last); } public MoveTarget getTarget() { return target; } } protected static class MoveTarget extends Rewrite implements Insert { private final MoveSource source; public MoveTarget(IHiddenRegion insertAt, MoveSource source) { super(insertAt, insertAt); this.source = source; this.source.target = this; } @Override public IHiddenRegion getInsertFirst() { return this.source.originalFirst; } @Override public IHiddenRegion getInsertLast() { return this.source.originalLast; } } protected static class Remove extends Rewrite { public Remove(IHiddenRegion originalFirst, IHiddenRegion originalLast) { super(originalFirst, originalLast); } } protected static class Replace1 extends Rewrite implements Insert { private final IHiddenRegion modifiedFirst; private final IHiddenRegion modifiedLast; public Replace1(IHiddenRegion originalFirst, IHiddenRegion originalLast, IHiddenRegion modifiedFirst, IHiddenRegion modifiedLast) { super(originalFirst, originalLast); this.modifiedFirst = modifiedFirst; this.modifiedLast = modifiedLast; } @Override public IHiddenRegion getInsertFirst() { return this.modifiedFirst; } @Override public IHiddenRegion getInsertLast() { return this.modifiedLast; } } protected static class Preserve extends Rewrite implements Insert { public Preserve(IHiddenRegion first, IHiddenRegion last) { super(first, last); } @Override public IHiddenRegion getInsertFirst() { return this.originalFirst; } @Override public IHiddenRegion getInsertLast() { return this.originalLast; } @Override public boolean isDiff() { return false; } } public abstract static class Rewrite implements Comparable<Rewrite> { protected IHiddenRegion originalFirst; protected IHiddenRegion originalLast; public Rewrite(IHiddenRegion originalFirst, IHiddenRegion originalLast) { super(); this.originalFirst = originalFirst; this.originalLast = originalLast; } public boolean isDiff() { return true; } @Override public int compareTo(Rewrite o) { return Integer.compare(originalFirst.getOffset(), o.originalFirst.getOffset()); } } protected static class Replace2 extends Rewrite implements Insert { private final TextRegionAccessBuildingSequencer sequencer; public Replace2(IHiddenRegion originalFirst, IHiddenRegion originalLast, TextRegionAccessBuildingSequencer sequencer) { super(originalFirst, originalLast); this.sequencer = sequencer; } @Override public IHiddenRegion getInsertFirst() { return sequencer.getRegionAccess().regionForRootEObject().getPreviousHiddenRegion(); } @Override public IHiddenRegion getInsertLast() { return sequencer.getRegionAccess().regionForRootEObject().getNextHiddenRegion(); } } private final ITextRegionAccess original; private List<Rewrite> rewrites = Lists.newArrayList(); private Map<ITextSegment, String> changes = Maps.newHashMap(); public StringBasedTextRegionAccessDiffBuilder(ITextRegionAccess base) { super(); this.original = base; } protected void checkOriginal(ITextSegment segment) { Preconditions.checkNotNull(segment); Preconditions.checkArgument(original == segment.getTextRegionAccess()); } protected List<Rewrite> createList() { List<Rewrite> sorted = Lists.newArrayList(rewrites); Collections.sort(sorted); List<Rewrite> result = Lists.newArrayListWithExpectedSize(sorted.size() * 2); IHiddenRegion last = original.regionForRootEObject().getPreviousHiddenRegion(); for (Rewrite rw : sorted) { int lastOffset = last.getOffset(); int rwOffset = rw.originalFirst.getOffset(); if (rwOffset == lastOffset) { result.add(rw); last = rw.originalLast; } else if (rwOffset > lastOffset) { result.add(new Preserve(last, rw.originalFirst)); result.add(rw); last = rw.originalLast; } else { LOG.error("Error, conflicting document modifications."); } } IHiddenRegion end = original.regionForRootEObject().getNextHiddenRegion(); if (last.getOffset() < end.getOffset()) { result.add(new Preserve(last, end)); } return result; } @Override public StringBasedTextRegionAccessDiff create() { StringBasedTextRegionAccessDiffAppender appender = createAppender(); IEObjectRegion root = original.regionForRootEObject(); appender.copyAndAppend(root.getPreviousHiddenRegion(), PREVIOUS); appender.copyAndAppend(root.getPreviousHiddenRegion(), CONTAINER); List<Rewrite> rws = createList(); IHiddenRegion last = null; for (Rewrite rw : rws) { boolean diff = rw.isDiff(); if (diff) { appender.beginDiff(); } if (rw instanceof Insert) { Insert ins = (Insert) rw; IHiddenRegion f = ins.getInsertFirst(); IHiddenRegion l = ins.getInsertLast(); appender.copyAndAppend(f, NEXT); if (f != l) { appender.copyAndAppend(f.getNextSemanticRegion(), l.getPreviousSemanticRegion()); } appender.copyAndAppend(l, PREVIOUS); } if (diff) { appender.endDiff(); } if (rw.originalLast != last) { appender.copyAndAppend(rw.originalLast, CONTAINER); } last = rw.originalLast; } appender.copyAndAppend(root.getNextHiddenRegion(), NEXT); StringBasedTextRegionAccessDiff result = appender.finish(); AbstractEObjectRegion newRoot = result.regionForEObject(root.getSemanticElement()); result.setRootEObject(newRoot); return result; } protected StringBasedTextRegionAccessDiffAppender createAppender() { return new StringBasedTextRegionAccessDiffAppender(original, changes); } @Override public ITextRegionAccess getOriginalTextRegionAccess() { return original; } @Override public boolean isModified(ITextRegion region) { int offset = region.getOffset(); int endOffset = offset + region.getLength(); for (Rewrite action : rewrites) { int rwOffset = action.originalFirst.getOffset(); int rwEndOffset = action.originalLast.getEndOffset(); if (rwOffset <= offset && offset < rwEndOffset) { return true; } if (rwOffset < endOffset && endOffset <= rwEndOffset) { return true; } } return false; } @Override public void move(IHiddenRegion insertAt, IHiddenRegion substituteFirst, IHiddenRegion substituteLast) { checkOriginal(insertAt); checkOriginal(substituteFirst); checkOriginal(substituteLast); MoveSource source = new MoveSource(substituteFirst, substituteLast); MoveTarget target = new MoveTarget(insertAt, source); rewrites.add(source); rewrites.add(target); } @Override public void remove(IHiddenRegion first, IHiddenRegion last) { checkOriginal(first); checkOriginal(last); rewrites.add(new Remove(first, last)); } @Override public void remove(ISemanticRegion region) { remove(region.getPreviousHiddenRegion(), region.getNextHiddenRegion()); } @Override public void replace(IHiddenRegion originalFirst, IHiddenRegion originalLast, IHiddenRegion modifiedFirst, IHiddenRegion modifiedLast) { checkOriginal(originalFirst); checkOriginal(originalLast); rewrites.add(new Replace1(originalFirst, originalLast, modifiedFirst, modifiedLast)); } @Override public void replace(IHiddenRegion originalFirst, IHiddenRegion originalLast, ITextRegionAccess acc) { checkOriginal(originalFirst); checkOriginal(originalLast); IEObjectRegion substituteRoot = acc.regionForRootEObject(); IHiddenRegion substituteFirst = substituteRoot.getPreviousHiddenRegion(); IHiddenRegion substituteLast = substituteRoot.getNextHiddenRegion(); replace(originalFirst, originalLast, substituteFirst, substituteLast); } @Override public void replace(ISemanticRegion region, String newText) { Preconditions.checkNotNull(newText); checkOriginal(region); changes.put(region, newText); } @Override public ISequenceAcceptor replaceSequence(IHiddenRegion originalFirst, IHiddenRegion originalLast, ISerializationContext ctx, EObject root) { checkOriginal(originalFirst); checkOriginal(originalLast); TextRegionAccessBuildingSequencer sequenceAcceptor = new TextRegionAccessBuildingSequencer(); rewrites.add(new Replace2(originalFirst, originalLast, sequenceAcceptor)); return sequenceAcceptor.withRoot(ctx, root); } @Override public String toString() { try { StringBasedTextRegionAccessDiff regions = create(); return new TextRegionAccessToString().withRegionAccess(regions).toString(); } catch (Throwable t) { return t.getMessage() + "\n" + Throwables.getStackTraceAsString(t); } } }
miklossy/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/formatting2/regionaccess/internal/StringBasedTextRegionAccessDiffBuilder.java
Java
epl-1.0
10,636
/** */ package org.eclipse.papyrus.RobotML.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.papyrus.RobotML.RobotMLPackage; import org.eclipse.papyrus.RobotML.RoboticMiddleware; import org.eclipse.papyrus.RobotML.RoboticMiddlewareKind; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Robotic Middleware</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.papyrus.RobotML.impl.RoboticMiddlewareImpl#getKind <em>Kind</em>}</li> * </ul> * </p> * * @generated */ public class RoboticMiddlewareImpl extends PlatformImpl implements RoboticMiddleware { /** * The default value of the '{@link #getKind() <em>Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKind() * @generated * @ordered */ protected static final RoboticMiddlewareKind KIND_EDEFAULT = RoboticMiddlewareKind.RT_MAPS; /** * The cached value of the '{@link #getKind() <em>Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getKind() * @generated * @ordered */ protected RoboticMiddlewareKind kind = KIND_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected RoboticMiddlewareImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RobotMLPackage.Literals.ROBOTIC_MIDDLEWARE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public RoboticMiddlewareKind getKind() { return kind; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setKind(RoboticMiddlewareKind newKind) { RoboticMiddlewareKind oldKind = kind; kind = newKind == null ? KIND_EDEFAULT : newKind; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RobotMLPackage.ROBOTIC_MIDDLEWARE__KIND, oldKind, kind)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case RobotMLPackage.ROBOTIC_MIDDLEWARE__KIND: return getKind(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case RobotMLPackage.ROBOTIC_MIDDLEWARE__KIND: setKind((RoboticMiddlewareKind)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case RobotMLPackage.ROBOTIC_MIDDLEWARE__KIND: setKind(KIND_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case RobotMLPackage.ROBOTIC_MIDDLEWARE__KIND: return kind != KIND_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (kind: "); result.append(kind); result.append(')'); return result.toString(); } } //RoboticMiddlewareImpl
RobotML/RobotML-SDK-Juno
plugins/robotml/org.eclipse.papyrus.robotml/src/org/eclipse/papyrus/RobotML/impl/RoboticMiddlewareImpl.java
Java
epl-1.0
3,660
/******************************************************************************* * Copyright (c) 2000, 2016 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 * * Based on org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy * * Contributors: * IBM Corporation - initial API and implementation * Red Hat, Inc - decoupling from jdt.ui *******************************************************************************/ package org.eclipse.jdt.ls.core.internal.contentassist; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.manipulation.CodeGeneration; import org.eclipse.jdt.internal.core.manipulation.StubUtility; import org.eclipse.jdt.internal.corext.util.MethodOverrideTester; import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache; import org.eclipse.jdt.ls.core.internal.JDTUtils; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.handlers.CompletionResolveHandler; import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.lsp4j.CompletionItem; import org.eclipse.lsp4j.CompletionItemKind; import org.eclipse.lsp4j.InsertTextFormat; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.TextEdit; public class JavadocCompletionProposal { private static final String ASTERISK = "*"; private static final String WHITESPACES = " \t"; public static final String JAVA_DOC_COMMENT = "Javadoc comment"; public List<CompletionItem> getProposals(ICompilationUnit cu, int offset, CompletionProposalRequestor collector, IProgressMonitor monitor) throws JavaModelException { if (cu == null) { throw new IllegalArgumentException("Compilation unit must not be null"); //$NON-NLS-1$ } List<CompletionItem> result = new ArrayList<>(); IDocument d = JsonRpcHelpers.toDocument(cu.getBuffer()); if (offset < 0 || d.getLength() == 0) { return result; } try { int p = (offset == d.getLength() ? offset - 1 : offset); IRegion line = d.getLineInformationOfOffset(p); String lineStr = d.get(line.getOffset(), line.getLength()).trim(); if (!lineStr.startsWith("/**")) { return result; } if (!hasEndJavadoc(d, offset)) { return result; } String text = collector.getContext().getToken() == null ? "" : new String(collector.getContext().getToken()); StringBuilder buf = new StringBuilder(text); IRegion prefix = findPrefixRange(d, line); String indentation = d.get(prefix.getOffset(), prefix.getLength()); int lengthToAdd = Math.min(offset - prefix.getOffset(), prefix.getLength()); buf.append(indentation.substring(0, lengthToAdd)); String lineDelimiter = TextUtilities.getDefaultLineDelimiter(d); ICompilationUnit unit = cu; try { unit.reconcile(ICompilationUnit.NO_AST, false, null, null); String string = createJavaDocTags(d, offset, indentation, lineDelimiter, unit); if (string != null && !string.trim().equals(ASTERISK)) { buf.append(string); } else { return result; } int nextNonWS = findEndOfWhiteSpace(d, offset, d.getLength()); if (!Character.isWhitespace(d.getChar(nextNonWS))) { buf.append(lineDelimiter); } } catch (CoreException e) { // ignore } final CompletionItem ci = new CompletionItem(); Range range = JDTUtils.toRange(unit, offset, 0); boolean isSnippetSupported = JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isCompletionSnippetsSupported(); String replacement = prepareTemplate(buf.toString(), lineDelimiter, isSnippetSupported); ci.setTextEdit(new TextEdit(range, replacement)); ci.setFilterText(JAVA_DOC_COMMENT); ci.setLabel(JAVA_DOC_COMMENT); ci.setSortText(SortTextHelper.convertRelevance(0)); ci.setKind(CompletionItemKind.Snippet); ci.setInsertTextFormat(isSnippetSupported ? InsertTextFormat.Snippet : InsertTextFormat.PlainText); String documentation = prepareTemplate(buf.toString(), lineDelimiter, false); if (documentation.indexOf(lineDelimiter) == 0) { documentation = documentation.replaceFirst(lineDelimiter, ""); } ci.setDocumentation(documentation); Map<String, String> data = new HashMap<>(3); data.put(CompletionResolveHandler.DATA_FIELD_URI, JDTUtils.toURI(cu)); data.put(CompletionResolveHandler.DATA_FIELD_REQUEST_ID, "0"); data.put(CompletionResolveHandler.DATA_FIELD_PROPOSAL_ID, "0"); ci.setData(data); result.add(ci); } catch (BadLocationException excp) { // stop work } return result; } private String prepareTemplate(String text, String lineDelimiter, boolean addGap) { boolean endWithLineDelimiter = text.endsWith(lineDelimiter); String[] lines = text.split(lineDelimiter); StringBuilder buf = new StringBuilder(); for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (addGap) { String stripped = StringUtils.stripStart(line, WHITESPACES); if (stripped.startsWith(ASTERISK)) { if (!stripped.equals(ASTERISK)) { int index = line.indexOf(ASTERISK); buf.append(line.substring(0, index + 1)); buf.append(" ${0}"); buf.append(lineDelimiter); } addGap = false; } } buf.append(StringUtils.stripEnd(line, WHITESPACES)); if (i < lines.length - 1 || endWithLineDelimiter) { buf.append(lineDelimiter); } } return buf.toString(); } private IRegion findPrefixRange(IDocument document, IRegion line) throws BadLocationException { int lineOffset = line.getOffset(); int lineEnd = lineOffset + line.getLength(); int indentEnd = findEndOfWhiteSpace(document, lineOffset, lineEnd); if (indentEnd < lineEnd && document.getChar(indentEnd) == '*') { indentEnd++; while (indentEnd < lineEnd && document.getChar(indentEnd) == ' ') { indentEnd++; } } return new Region(lineOffset, indentEnd - lineOffset); } private int findEndOfWhiteSpace(IDocument document, int offset, int end) throws BadLocationException { while (offset < end) { char c = document.getChar(offset); if (c != ' ' && c != '\t') { return offset; } offset++; } return end; } private boolean hasEndJavadoc(IDocument document, int offset) throws BadLocationException { int pos = -1; while (offset < document.getLength()) { char c = document.getChar(offset); if (!Character.isWhitespace(c) && !(c == '*')) { pos = offset; break; } offset++; } if (document.getLength() >= pos + 2 && document.get(pos - 1, 2).equals("*/")) { return true; } return false; } private String createJavaDocTags(IDocument document, int offset, String indentation, String lineDelimiter, ICompilationUnit unit) throws CoreException, BadLocationException { IJavaElement element = unit.getElementAt(offset); if (element == null) { return null; } switch (element.getElementType()) { case IJavaElement.TYPE: return createTypeTags(document, offset, indentation, lineDelimiter, (IType) element); case IJavaElement.METHOD: return createMethodTags(document, offset, indentation, lineDelimiter, (IMethod) element); default: return null; } } private String createTypeTags(IDocument document, int offset, String indentation, String lineDelimiter, IType type) throws CoreException, BadLocationException { if (!accept(offset, type)) { return null; } String[] typeParamNames = StubUtility.getTypeParameterNames(type.getTypeParameters()); String comment = CodeGeneration.getTypeComment(type.getCompilationUnit(), type.getTypeQualifiedName('.'), typeParamNames, lineDelimiter); if (comment != null) { return prepareTemplateComment(comment.trim(), indentation, type.getJavaProject(), lineDelimiter); } return null; } private boolean accept(int offset, IMember member) throws JavaModelException { ISourceRange nameRange = member.getNameRange(); if (nameRange == null) { return false; } int srcOffset = nameRange.getOffset(); return srcOffset > offset; } private String createMethodTags(IDocument document, int offset, String indentation, String lineDelimiter, IMethod method) throws CoreException, BadLocationException { if (!accept(offset, method)) { return null; } IMethod inheritedMethod = getInheritedMethod(method); String comment = CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter); if (comment != null) { comment = comment.trim(); boolean javadocComment = comment.startsWith("/**"); //$NON-NLS-1$ if (javadocComment) { return prepareTemplateComment(comment, indentation, method.getJavaProject(), lineDelimiter); } } return null; } private String prepareTemplateComment(String comment, String indentation, IJavaProject project, String lineDelimiter) { // trim comment start and end if any if (comment.endsWith("*/")) { comment = comment.substring(0, comment.length() - 2); } comment = comment.trim(); if (comment.startsWith("/*")) { //$NON-NLS-1$ if (comment.length() > 2 && comment.charAt(2) == '*') { comment = comment.substring(3); // remove '/**' } else { comment = comment.substring(2); // remove '/*' } } // trim leading spaces, but not new lines int nonSpace = 0; int len = comment.length(); while (nonSpace < len && Character.getType(comment.charAt(nonSpace)) == Character.SPACE_SEPARATOR) { nonSpace++; } comment = comment.substring(nonSpace); return comment; } private IMethod getInheritedMethod(IMethod method) throws JavaModelException { IType declaringType = method.getDeclaringType(); MethodOverrideTester tester = SuperTypeHierarchyCache.getMethodOverrideTester(declaringType); return tester.findOverriddenMethod(method, true); } }
gorkem/java-language-server
org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/contentassist/JavadocCompletionProposal.java
Java
epl-1.0
10,626
package mx.com.cinepolis.digital.booking.commons.exception; /** * Clase con los códigos de errores para las excepciones * @author rgarcia * */ public enum DigitalBookingExceptionCode { /** Error desconocido */ GENERIC_UNKNOWN_ERROR(0), /*** * CATALOG NULO */ CATALOG_ISNULL(1), /** * Paging Request Nulo */ PAGING_REQUEST_ISNULL(2), /** * Errores de persistencia */ PERSISTENCE_ERROR_GENERIC(3), PERSISTENCE_ERROR_NEW_OBJECT_FOUND_DURING_COMMIT(4), PERSISTENCE_ERROR_CATALOG_ALREADY_REGISTERED(5), PERSISTENCE_ERROR_CATALOG_NOT_FOUND(6), PERSISTENCE_ERROR_CATALOG_ALREADY_REGISTERED_WITH_ID_VISTA(7), PERSISTENCE_ERROR_WEEK_ALREADY_REGISTERED(8), /** * Errores de Administración de Catalogos */ THEATER_NUM_THEATER_ALREADY_EXISTS(9), CANNOT_DELETE_REGION(10), INEXISTENT_REGION(11), INVALID_TERRITORY(12), THEATER_IS_NULL(13), THEATER_IS_NOT_IN_ANY_REGION(14), THEATER_NOT_HAVE_SCREENS(15), INEXISTENT_THEATER(16), THEATER_IS_NOT_IN_ANY_CITY(17), THEATER_IS_NOT_IN_ANY_STATE(18), INVALID_SCREEN(19), INVALID_MOVIE_FORMATS(20), INVALID_SOUND_FORMATS(21), FILE_NULL(22), EVENT_MOVIE_NULL(23), /** * Errores de Administración de cines */ SCREEN_NUMBER_ALREADY_EXISTS(24), SCREEN_NEEDS_AT_LEAST_ONE_SOUND_FORMAT(25), SCREEN_NEEDS_AT_LEAST_ONE_MOVIE_FORMAT(26), DISTRIBUTOR_IS_ASSOCIATED_WITH_AN_EXISTING_MOVIE(27), CATEGORY_SOUND_FORMAT_IS_ASSOCIATED_WITH_AN_EXISTING_MOVIE(28), CATEGORY_SOUND_FORMAT_IS_ASSOCIATED_WITH_AN_EXISTING_SCREEN(29), CATEGORY_MOVIE_FORMAT_IS_ASSOCIATED_WITH_AN_EXISTING_MOVIE(30), CATEGORY_MOVIE_FORMAT_IS_ASSOCIATED_WITH_AN_EXISTING_SCREEN(31), CATEGORY_SCREEN_FORMAT_IS_ASSOCIATED_WITH_AN_EXISTING_SCREEN(39), SCREEN_NEEDS_SCREEN_FORMAT(32), MOVIE_NAME_BLANK(33), MOVIE_DISTRIBUTOR_NULL(35), MOVIE_COUNTRIES_EMPTY(36), MOVIE_DETAIL_EMPTY(37), MOVIE_IMAGE_NULL(38), /** * Booking errors */ BOOKING_PERSISTENCE_ERROR_STATUS_NOT_FOUND(40), BOOKING_PERSISTENCE_ERROR_EVENT_NOT_FOUND(41), BOOKING_PERSISTENCE_ERROR_THEATER_NOT_FOUND(42), BOOKING_PERSISTENCE_ERROR_WEEK_NOT_FOUND(43), BOOKING_PERSISTENCE_ERROR_BOOKING_NOT_FOUND(44), BOOKING_PERSISTENCE_ERROR_USER_NOT_FOUND(45), BOOKING_PERSISTENCE_ERROR_EVENT_TYPE_NOT_FOUND(46), BOOKING_PERSISTENCE_ERROR_AT_CONSULT_BOOKINGS(221), /** * Week errors */ WEEK_PERSISTENCE_ERROR_NOT_FOUND(50), /** * Observation errors */ NEWS_FEED_OBSERVATION_NOT_FOUND(51), BOOKING_OBSERVATION_NOT_FOUND2(52), OBSERVATION_NOT_FOUND(53), NEWS_FEED_OBSERVATION_ASSOCIATED_TO_ANOTHER_USER(103), /** * Email Errors */ EMAIL_DOES_NOT_COMPLIES_REGEX(54), EMAIL_IS_REPEATED(55), /** * Configuration Errors */ CONFIGURATION_ID_IS_NULL(60), CONFIGURATION_NAME_IS_NULL(61), CONFIGURATION_PARAMETER_NOT_FOUND(62), /** * Email Errors */ ERROR_SENDING_EMAIL_NO_DATA(70), ERROR_SENDING_EMAIL_NO_RECIPIENTS(71), ERROR_SENDING_EMAIL_SUBJECT(72), ERROR_SENDING_EMAIL_MESSAGE(73), /** * Booking errors */ BOOKING_IS_NULL(74), BOOKING_COPIES_IS_NULL(75), BOOKING_WEEK_NULL(76), BOOKING_EVENT_NULL(77), BOOKING_WRONG_STATUS_FOR_CANCELLATION(78), BOOKING_WRONG_STATUS_FOR_TERMINATION(79), BOOKING_THEATER_NEEDS_WEEK_ID(80), BOOKING_THEATER_NEEDS_THEATER_ID(81), BOOKING_NUMBER_COPIES_ZERO(82), BOOKING_NUM_SCREENS_GREATER_NUM_COPIES(83), BOOKING_CAN_NOT_BE_CANCELED(84), BOOKING_CAN_NOT_BE_TERMINATED(85), BOOKING_WRONG_STATUS_FOR_EDITION(86), ERROR_THEATER_HAS_NO_EMAIL(87), BOOKING_NUMBER_OF_COPIES_EXCEEDS_NUMBER_OF_SCREENS(88), BOOKING_NON_EDITABLE_WEEK(89), BOOKING_THEATER_REPEATED(90), BOOKING_IS_WEEK_ONE(91), BOOKING_THEATER_HAS_SCREEN_ZERO(92), BOOKING_MAXIMUM_COPY(93), BOOKING_NOT_SAVED_FOR_CANCELLATION(94), BOOKING_NOT_SAVED_FOR_TERMINATION(194), BOOKING_NOT_THEATERS_IN_REGION(196), BOOKING_NUMBER_OF_COPIES_EXCEEDS_NUMBER_OF_SCREENS_WHIT_THIS_FORMAT(195), BOOKING_NUM_SCREENS_GREATER_NUM_COPIES_NO_THEATER(95), BOOKING_SENT_CAN_NOT_BE_CANCELED(96), BOOKING_SENT_CAN_NOT_BE_TERMINATED(97), BOOKING_WITH_FOLLOWING_WEEK_CAN_NOT_BE_CANCELED(98), BOOKING_WITH_FOLLOWING_WEEK_CAN_NOT_BE_TERMINATED(99), /** * Report errors */ CREATE_XLSX_ERROR(100), BOOKING_THEATER_IS_NOT_ASSIGNED_TO_ANY_SCREEN(101), SEND_EMAIL_REGION_ERROR_CAN_ONLY_UPLOAD_UP_TO_TWO_FILES(102), /** * Security errors */ SECURITY_ERROR_USER_DOES_NOT_EXISTS(200), SECURITY_ERROR_PASSWORD_INVALID(201), SECURITY_ERROR_INVALID_USER(202), MENU_EXCEPTION(203), /** * UserErrors */ USER_IS_NULL(204), USER_USERNAME_IS_BLANK(205), USER_NAME_IS_BLANK(206), USER_LAST_NAME_IS_BLANK(207), USER_ROLE_IS_NULL(208), USER_EMAIL_IS_NULL(209), USER_THE_USERNAME_IS_DUPLICATE(210), USER_TRY_DELETE_OWN_USER(211), /** * Week errors */ WEEK_IS_NULL(212), WEEK_INVALID_NUMBER(213), WEEK_INVALID_YEAR(214), WEEK_INVALID_FINAL_DAY(215), /** * EventMovie errors */ EVENT_CODE_DBS_NULL(216), CATALOG_ALREADY_REGISTERED_WITH_DS_CODE_DBS(217), CATALOG_ALREADY_REGISTERED_WITH_SHORT_NAME(218), CANNOT_DELETE_WEEK(219), CANNOT_REMOVE_EVENT_MOVIE(220), /** * Income errors */ INCOMES_COULD_NOT_OBTAIN_DATABASE_PROPERTIES(300), INCOMES_DRIVER_ERROR(301), INCOMES_CONNECTION_ERROR(302), /** * SynchronizeErrors */ CANNOT_CONNECT_TO_SERVICE(500), /** * Transaction timeout */ TRANSACTION_TIMEOUT(501), /** * INVALID PARAMETERS FOR BOOKING PRE RELEASE */ INVALID_COPIES_PARAMETER(600), INVALID_DATES_PARAMETERS(601), INVALID_SCREEN_PARAMETER_CASE_ONE(602), INVALID_SCREEN_PARAMETER_CASE_TWO(603), INVALID_DATES_BEFORE_TODAY_PARAMETERS(604), INVALID_PRESALE_DATES_PARAMETERS(605), /** * VALIDATIONS FOR PRESALE IN BOOKING MOVIE */ ERROR_BOOKING_PRESALE_FOR_NO_PREMIERE(606), ERROR_BOOKING_PRESALE_FOR_ZERO_SCREEN(607), ERROR_BOOKING_PRESALE_NOT_ASSOCIATED_AT_BOOKING(608), /** * INVALID SELECTION OF PARAMETERS * TO APPLY IN SPECIAL EVENT */ INVALID_STARTING_DATES(617), INVALID_FINAL_DATES(618), INVALID_STARTING_AND_RELREASE_DATES(619), INVALID_THEATER_SELECTION(620), INVALID_SCREEN_SELECTION(621), BOOKING_THEATER_NULL(622), BOOKING_TYPE_INVALID(623), BOOKING_SPECIAL_EVENT_LIST_EMPTY(624), /** * Invalid datetime range for system log. */ LOG_FINAL_DATE_BEFORE_START_DATE(625), LOG_INVALID_DATE_RANGE(626), LOG_INVALID_TIME_RANGE(627), /** * Invavlid cityTO */ CITY_IS_NULL(628), CITY_HAS_NO_NAME(629), CITY_HAS_NO_COUNTRY(630), CITY_INVALID_LIQUIDATION_ID(631), PERSISTENCE_ERROR_CATALOG_ALREADY_REGISTERED_WITH_LIQUIDATION_ID(632) ; /** * Constructor interno * * @param id */ private DigitalBookingExceptionCode( int id ) { this.id = id; } private int id; /** * @return the id */ public int getId() { return id; } }
sidlors/digital-booking
digital-booking-commons/src/main/java/mx/com/cinepolis/digital/booking/commons/exception/DigitalBookingExceptionCode.java
Java
epl-1.0
7,193
package com.temenos.soa.plugin.uml2dsconverter.utils; // General String utilities public class StringUtils { /** * Turns the first character of a string in to an uppercase character * @param source The source string * @return String Resultant string */ public static String upperInitialCharacter(String source) { final StringBuilder result = new StringBuilder(source.length()); result.append(Character.toUpperCase(source.charAt(0))).append(source.substring(1)); return result.toString(); } /** * Turns the first character of a string in to a lowercase character * @param source The source string * @return String Resultant string */ public static String lowerInitialCharacter(String source) { final StringBuilder result = new StringBuilder(source.length()); result.append(Character.toLowerCase(source.charAt(0))).append(source.substring(1)); return result.toString(); } }
junejosheeraz/UML2DS
com.temenos.soa.plugin.uml2dsconverter/src/com/temenos/soa/plugin/uml2dsconverter/utils/StringUtils.java
Java
epl-1.0
938
/****************************************************************************** * Copyright (c) 2000-2015 Ericsson Telecom AB * 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.titan.designer.AST.TTCN3.values.expressions; import java.util.List; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.INamedNode; import org.eclipse.titan.designer.AST.IReferenceChain; import org.eclipse.titan.designer.AST.IValue; import org.eclipse.titan.designer.AST.ReferenceFinder; import org.eclipse.titan.designer.AST.Scope; import org.eclipse.titan.designer.AST.Value; import org.eclipse.titan.designer.AST.IType.Type_type; import org.eclipse.titan.designer.AST.ReferenceFinder.Hit; import org.eclipse.titan.designer.AST.TTCN3.Expected_Value_type; import org.eclipse.titan.designer.AST.TTCN3.values.Expression_Value; import org.eclipse.titan.designer.AST.TTCN3.values.Hexstring_Value; import org.eclipse.titan.designer.AST.TTCN3.values.Octetstring_Value; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.ttcn3parser.ReParseException; import org.eclipse.titan.designer.parsers.ttcn3parser.TTCN3ReparseUpdater; /** * @author Kristof Szabados * */ public final class Hex2OctExpression extends Expression_Value { private static final String OPERANDERROR = "The operand of the `hex2oct' operation should be a hexstring value"; private final Value value; public Hex2OctExpression(final Value value) { this.value = value; if (value != null) { value.setFullNameParent(this); } } @Override public Operation_type getOperationType() { return Operation_type.HEX2OCT_OPERATION; } @Override public String createStringRepresentation() { final StringBuilder builder = new StringBuilder(); builder.append("hex2oct(").append(value.createStringRepresentation()).append(')'); return builder.toString(); } @Override public void setMyScope(final Scope scope) { super.setMyScope(scope); if (value != null) { value.setMyScope(scope); } } @Override public StringBuilder getFullName(final INamedNode child) { final StringBuilder builder = super.getFullName(child); if (value == child) { return builder.append(OPERAND); } return builder; } @Override public Type_type getExpressionReturntype(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue) { return Type_type.TYPE_OCTETSTRING; } @Override public boolean isUnfoldable(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (value == null) { return true; } return value.isUnfoldable(timestamp, expectedValue, referenceChain); } /** * Checks the parameters of the expression and if they are valid in * their position in the expression or not. * * @param timestamp * the timestamp of the actual semantic check cycle. * @param expectedValue * the kind of value expected. * @param referenceChain * a reference chain to detect cyclic references. * */ private void checkExpressionOperands(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (value == null) { return; } value.setLoweridToReference(timestamp); Type_type tempType = value.getExpressionReturntype(timestamp, expectedValue); switch (tempType) { case TYPE_HEXSTRING: value.getValueRefdLast(timestamp, expectedValue, referenceChain); return; case TYPE_UNDEFINED: setIsErroneous(true); return; default: if (!isErroneous) { location.reportSemanticError(OPERANDERROR); setIsErroneous(true); } return; } } @Override public IValue evaluateValue(final CompilationTimeStamp timestamp, final Expected_Value_type expectedValue, final IReferenceChain referenceChain) { if (lastTimeChecked != null && !lastTimeChecked.isLess(timestamp)) { return lastValue; } isErroneous = false; lastTimeChecked = timestamp; lastValue = this; if (value == null) { return lastValue; } checkExpressionOperands(timestamp, expectedValue, referenceChain); if (getIsErroneous(timestamp)) { return lastValue; } if (isUnfoldable(timestamp, referenceChain)) { return lastValue; } IValue last = value.getValueRefdLast(timestamp, referenceChain); if (last.getIsErroneous(timestamp)) { setIsErroneous(true); return lastValue; } switch (last.getValuetype()) { case HEXSTRING_VALUE: String temp = ((Hexstring_Value) last).getValue(); lastValue = new Octetstring_Value(hex2oct(temp)); lastValue.copyGeneralProperties(this); break; default: setIsErroneous(true); break; } return lastValue; } public static String hex2oct(final String hexString) { if (hexString.length() % 2 == 0) { return hexString; } return new StringBuilder(hexString.length() + 1).append('0').append(hexString).toString(); } @Override public void checkRecursions(final CompilationTimeStamp timestamp, final IReferenceChain referenceChain) { if (referenceChain.add(this) && value != null) { referenceChain.markState(); value.checkRecursions(timestamp, referenceChain); referenceChain.previousState(); } } @Override public void updateSyntax(final TTCN3ReparseUpdater reparser, final boolean isDamaged) throws ReParseException { if (isDamaged) { throw new ReParseException(); } if (value != null) { value.updateSyntax(reparser, false); reparser.updateLocation(value.getLocation()); } } @Override public void findReferences(final ReferenceFinder referenceFinder, final List<Hit> foundIdentifiers) { if (value == null) { return; } value.findReferences(referenceFinder, foundIdentifiers); } @Override protected boolean memberAccept(final ASTVisitor v) { if (value != null && !value.accept(v)) { return false; } return true; } }
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/AST/TTCN3/values/expressions/Hex2OctExpression.java
Java
epl-1.0
6,252
/* * Copyright (c) 2013 Red Hat, Inc. and/or its affiliates. * * 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: * Brad Davis - bradsdavis@gmail.com - Initial API and implementation */ package org.jboss.windup.interrogator.impl; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.windup.metadata.decoration.Summary; import org.jboss.windup.metadata.decoration.AbstractDecoration.NotificationLevel; import org.jboss.windup.metadata.type.FileMetadata; import org.jboss.windup.metadata.type.XmlMetadata; import org.jboss.windup.metadata.type.ZipEntryMetadata; import org.w3c.dom.Document; /** * Interrogates XML files. Extracts the XML, and creates an XmlMetadata object, which is passed down * the decorator pipeline. * * @author bdavis * */ public class XmlInterrogator extends ExtensionInterrogator<XmlMetadata> { private static final Log LOG = LogFactory.getLog(XmlInterrogator.class); @Override public void processMeta(XmlMetadata fileMeta) { Document document = fileMeta.getParsedDocument(); if (document == null) { if (LOG.isDebugEnabled()) { LOG.debug("Document was null. Problem parsing: " + fileMeta.getFilePointer().getAbsolutePath()); } // attach the bad file so we see it in the reports... fileMeta.getArchiveMeta().getEntries().add(fileMeta); return; } super.processMeta(fileMeta); } @Override public boolean isOfInterest(XmlMetadata fileMeta) { return true; } @Override public XmlMetadata archiveEntryToMeta(ZipEntryMetadata archiveEntry) { File file = archiveEntry.getFilePointer(); LOG.debug("Processing XML: " + file.getAbsolutePath()); FileMetadata meta = null; if (file.length() > 1048576L * 1) { LOG.warn("XML larger than 1 MB: " + file.getAbsolutePath() + "; Skipping processing."); meta = new FileMetadata(); meta.setArchiveMeta(archiveEntry.getArchiveMeta()); meta.setFilePointer(file); Summary sr = new Summary(); sr.setDescription("File is too large; skipped."); sr.setLevel(NotificationLevel.WARNING); meta.getDecorations().add(sr); } else { XmlMetadata xmlMeta = new XmlMetadata(); xmlMeta.setArchiveMeta(archiveEntry.getArchiveMeta()); xmlMeta.setFilePointer(file); meta = xmlMeta; return xmlMeta; } return null; } @Override public XmlMetadata fileEntryToMeta(FileMetadata entry) { File file = entry.getFilePointer(); LOG.debug("Processing XML: " + file.getAbsolutePath()); FileMetadata meta = null; if (file.length() > 1048576L * 1) { LOG.warn("XML larger than 1 MB: " + file.getAbsolutePath() + "; Skipping processing."); meta = new FileMetadata(); //meta.setArchiveMeta(archiveEntry.getArchiveMeta()); meta.setFilePointer(file); meta.setArchiveMeta(entry.getArchiveMeta()); Summary sr = new Summary(); sr.setDescription("File is too large; skipped."); sr.setLevel(NotificationLevel.WARNING); meta.getDecorations().add(sr); } else { XmlMetadata xmlMeta = new XmlMetadata(); xmlMeta.setArchiveMeta(entry.getArchiveMeta()); xmlMeta.setFilePointer(file); meta = xmlMeta; return xmlMeta; } return null; } }
Maarc/windup-as-a-service
windup_0_7/windup-engine/src/main/java/org/jboss/windup/interrogator/impl/XmlInterrogator.java
Java
epl-1.0
3,422
package de.uks.beast.editor.util; public enum Fonts { //@formatter:off HADOOP_MASTER_TITEL ("Arial", 10, true, true), HADOOP_SLAVE_TITEL ("Arial", 10, true, true), NETWORK_TITEL ("Arial", 10, true, true), CONTROL_CENTER_TITEL ("Arial", 10, true, true), HADOOP_MASTER_PROPERTY ("Arial", 8, false, true), HADOOP_SLAVE_PROPERTY ("Arial", 8, false, true), NETWORK_PROPERTY ("Arial", 8, false, true), CONTROL_CENTER_PROPERTY ("Arial", 8, false, true), ;//@formatter:on private final String name; private final int size; private final boolean italic; private final boolean bold; private Fonts(final String name, final int size, final boolean italic, final boolean bold) { this.name = name; this.size = size; this.italic = italic; this.bold = bold; } /** * @return the name */ public String getName() { return name; } /** * @return the size */ public int getSize() { return size; } /** * @return the italic */ public boolean isItalic() { return italic; } /** * @return the bold */ public boolean isBold() { return bold; } }
fujaba/BeAST
de.uks.beast.editor/src/de/uks/beast/editor/util/Fonts.java
Java
epl-1.0
1,163
/* * 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.solr.client.solrj.request; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.response.SolrPingResponse; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; /** * Verify that there is a working Solr core at the URL of a {@link org.apache.solr.client.solrj.SolrClient}. * To use this class, the solrconfig.xml for the relevant core must include the * request handler for <code>/admin/ping</code>. * * @since solr 1.3 */ public class SolrPing extends SolrRequest<SolrPingResponse> { /** serialVersionUID. */ private static final long serialVersionUID = 5828246236669090017L; /** Request parameters. */ private ModifiableSolrParams params; /** * Create a new SolrPing object. */ public SolrPing() { super(METHOD.GET, CommonParams.PING_HANDLER); params = new ModifiableSolrParams(); } @Override protected SolrPingResponse createResponse(SolrClient client) { return new SolrPingResponse(); } @Override public ModifiableSolrParams getParams() { return params; } /** * Remove the action parameter from this request. This will result in the same * behavior as {@code SolrPing#setActionPing()}. For Solr server version 4.0 * and later. * * @return this */ public SolrPing removeAction() { params.remove(CommonParams.ACTION); return this; } /** * Set the action parameter on this request to enable. This will delete the * health-check file for the Solr core. For Solr server version 4.0 and later. * * @return this */ public SolrPing setActionDisable() { params.set(CommonParams.ACTION, CommonParams.DISABLE); return this; } /** * Set the action parameter on this request to enable. This will create the * health-check file for the Solr core. For Solr server version 4.0 and later. * * @return this */ public SolrPing setActionEnable() { params.set(CommonParams.ACTION, CommonParams.ENABLE); return this; } /** * Set the action parameter on this request to ping. This is the same as not * including the action at all. For Solr server version 4.0 and later. * * @return this */ public SolrPing setActionPing() { params.set(CommonParams.ACTION, CommonParams.PING); return this; } }
DavidGutknecht/elexis-3-base
bundles/org.apache.solr/src/org/apache/solr/client/solrj/request/SolrPing.java
Java
epl-1.0
3,236
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2020.05.20 um 02:10:33 PM CEST // package ch.fd.invoice450.request; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java-Klasse für xtraDrugType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="xtraDrugType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="indicated" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="iocm_category"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="A"/> * &lt;enumeration value="B"/> * &lt;enumeration value="C"/> * &lt;enumeration value="D"/> * &lt;enumeration value="E"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="delivery" default="first"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="first"/> * &lt;enumeration value="repeated"/> * &lt;enumeration value="permanent"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="regulation_attributes" type="{http://www.w3.org/2001/XMLSchema}unsignedInt" default="0" /> * &lt;attribute name="limitation" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "xtraDrugType") public class XtraDrugType { @XmlAttribute(name = "indicated") protected Boolean indicated; @XmlAttribute(name = "iocm_category") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String iocmCategory; @XmlAttribute(name = "delivery") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String delivery; @XmlAttribute(name = "regulation_attributes") @XmlSchemaType(name = "unsignedInt") protected Long regulationAttributes; @XmlAttribute(name = "limitation") protected Boolean limitation; /** * Ruft den Wert der indicated-Eigenschaft ab. * * @return * possible object is * {@link Boolean } * */ public Boolean isIndicated() { return indicated; } /** * Legt den Wert der indicated-Eigenschaft fest. * * @param value * allowed object is * {@link Boolean } * */ public void setIndicated(Boolean value) { this.indicated = value; } /** * Ruft den Wert der iocmCategory-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getIocmCategory() { return iocmCategory; } /** * Legt den Wert der iocmCategory-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setIocmCategory(String value) { this.iocmCategory = value; } /** * Ruft den Wert der delivery-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getDelivery() { if (delivery == null) { return "first"; } else { return delivery; } } /** * Legt den Wert der delivery-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setDelivery(String value) { this.delivery = value; } /** * Ruft den Wert der regulationAttributes-Eigenschaft ab. * * @return * possible object is * {@link Long } * */ public long getRegulationAttributes() { if (regulationAttributes == null) { return 0L; } else { return regulationAttributes; } } /** * Legt den Wert der regulationAttributes-Eigenschaft fest. * * @param value * allowed object is * {@link Long } * */ public void setRegulationAttributes(Long value) { this.regulationAttributes = value; } /** * Ruft den Wert der limitation-Eigenschaft ab. * * @return * possible object is * {@link Boolean } * */ public Boolean isLimitation() { return limitation; } /** * Legt den Wert der limitation-Eigenschaft fest. * * @param value * allowed object is * {@link Boolean } * */ public void setLimitation(Boolean value) { this.limitation = value; } }
DavidGutknecht/elexis-3-base
bundles/at.medevit.elexis.tarmed.model/src-gen/ch/fd/invoice450/request/XtraDrugType.java
Java
epl-1.0
5,592
/******************************************************************************* * Copyright (c) 2001, 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 * Jens Lukowski/Innoopract - initial renaming/restructuring * *******************************************************************************/ package org.eclipse.wst.xml.core.internal.contenttype; import org.eclipse.wst.sse.core.internal.encoding.EncodingMemento; import org.eclipse.wst.sse.core.internal.encoding.NonContentBasedEncodingRules; /** * This class can be used in place of an EncodingMemento (its super class), * when there is not in fact ANY encoding information. For example, when a * structuredDocument is created directly from a String */ public class NullMemento extends EncodingMemento { /** * */ public NullMemento() { super(); String defaultCharset = NonContentBasedEncodingRules.useDefaultNameRules(null); setJavaCharsetName(defaultCharset); setAppropriateDefault(defaultCharset); setDetectedCharsetName(null); } }
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xml.core/src/org/eclipse/wst/xml/core/internal/contenttype/NullMemento.java
Java
epl-1.0
1,336
/******************************************************************************* * Copyright (c) 2013-2015 UAH Space Research Group. * 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: * MICOBS SRG Team - Initial API and implementation ******************************************************************************/ package es.uah.aut.srg.micobs.mclev.library.mclevlibrary; /** * A representation of an MCLEV Library versioned item corresponding to the * model of a regular component. * * <p> * The following features are supported: * <ul> * <li>{@link es.uah.aut.srg.micobs.mclev.library.mclevlibrary.MMCLEVVersionedItemComponent#getSwPackageURI <em>Sw Package URI</em>}</li> * <li>{@link es.uah.aut.srg.micobs.mclev.library.mclevlibrary.MMCLEVVersionedItemComponent#getSwPackageVersion <em>Sw Package Version</em>}</li> * </ul> * </p> * * @see es.uah.aut.srg.micobs.mclev.library.mclevlibrary.mclevlibraryPackage#getMMCLEVVersionedItemComponent() * @model * @generated */ public interface MMCLEVVersionedItemComponent extends MMCLEVPackageVersionedItem { /** * Returns the URI of the MESP software package that stores the * implementation of the component or <code>null</code> if no software * package is defined for the component. * @return the URI of the attached MESP software package or * <code>null</code> if no software package is defined for the component. * @see #setSwPackageURI(String) * @see es.uah.aut.srg.micobs.mclev.library.mclevlibrary.mclevlibraryPackage#getMMCLEVVersionedItemComponent_SwPackageURI() * @model * @generated */ String getSwPackageURI(); /** * Sets the URI of the MESP software package that stores the * implementation of the component. * @param value the new URI of the attached MESP software package. * @see #getSwPackageURI() * @generated */ void setSwPackageURI(String value); /** * Returns the version of the MESP software package that stores the * implementation of the component or <code>null</code> if no software * package is defined for the component. * @return the version of the attached MESP software package or * <code>null</code> if no software package is defined for the component. * @see #setSwPackageVersion(String) * @see es.uah.aut.srg.micobs.mclev.library.mclevlibrary.mclevlibraryPackage#getMMCLEVVersionedItemComponent_SwPackageVersion() * @model * @generated */ String getSwPackageVersion(); /** * Sets the version of the MESP software package that stores the * implementation of the component. * @param value the new version of the attached MESP software package. * @see #getSwPackageVersion() * @generated */ void setSwPackageVersion(String value); /** * Returns the value of the '<em><b>Sw Interface URI</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sw Interface URI</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sw Interface URI</em>' attribute. * @see #setSwInterfaceURI(String) * @see es.uah.aut.srg.micobs.mclev.library.mclevlibrary.mclevlibraryPackage#getMMCLEVVersionedItemComponent_SwInterfaceURI() * @model * @generated */ String getSwInterfaceURI(); /** * Sets the value of the '{@link es.uah.aut.srg.micobs.mclev.library.mclevlibrary.MMCLEVVersionedItemComponent#getSwInterfaceURI <em>Sw Interface URI</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sw Interface URI</em>' attribute. * @see #getSwInterfaceURI() * @generated */ void setSwInterfaceURI(String value); /** * Returns the value of the '<em><b>Sw Interface Version</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sw Interface Version</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sw Interface Version</em>' attribute. * @see #setSwInterfaceVersion(String) * @see es.uah.aut.srg.micobs.mclev.library.mclevlibrary.mclevlibraryPackage#getMMCLEVVersionedItemComponent_SwInterfaceVersion() * @model * @generated */ String getSwInterfaceVersion(); /** * Sets the value of the '{@link es.uah.aut.srg.micobs.mclev.library.mclevlibrary.MMCLEVVersionedItemComponent#getSwInterfaceVersion <em>Sw Interface Version</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sw Interface Version</em>' attribute. * @see #getSwInterfaceVersion() * @generated */ void setSwInterfaceVersion(String value); }
parraman/micobs
mclev/es.uah.aut.srg.micobs.mclev/src/es/uah/aut/srg/micobs/mclev/library/mclevlibrary/MMCLEVVersionedItemComponent.java
Java
epl-1.0
4,916
package org.eclipse.scout.widgets.heatmap.client.ui.form.fields.heatmapfield; import java.util.Collection; import org.eclipse.scout.rt.client.ui.form.fields.IFormField; public interface IHeatmapField extends IFormField { String PROP_VIEW_PARAMETER = "viewParameter"; String PROP_HEAT_POINT_LIST = "heatPointList"; HeatmapViewParameter getViewParameter(); Collection<HeatPoint> getHeatPoints(); void handleClick(MapPoint point); void addHeatPoint(HeatPoint heatPoint); void addHeatPoints(Collection<HeatPoint> heatPoints); void setHeatPoints(Collection<HeatPoint> heatPoints); void setViewParameter(HeatmapViewParameter parameter); IHeatmapFieldUIFacade getUIFacade(); void addHeatmapListener(IHeatmapListener listener); void removeHeatmapListener(IHeatmapListener listener); }
BSI-Business-Systems-Integration-AG/org.thethingsnetwork.zrh.monitor
ttn_monitor/org.eclipse.scout.widgets.heatmap.client/src/main/java/org/eclipse/scout/widgets/heatmap/client/ui/form/fields/heatmapfield/IHeatmapField.java
Java
epl-1.0
817
/* * Copyright (c) 2015 Cisco Systems, Inc. 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.opendaylight.protocol.bgp.linkstate.nlri; import static org.opendaylight.protocol.util.ByteBufWriteUtil.writeIpv4Address; import static org.opendaylight.protocol.util.ByteBufWriteUtil.writeIpv6Address; import static org.opendaylight.protocol.util.ByteBufWriteUtil.writeShort; import static org.opendaylight.protocol.util.ByteBufWriteUtil.writeUnsignedShort; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import io.netty.buffer.ByteBuf; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.NlriType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.destination.CLinkstateDestination; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.TeLspCase; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.TeLspCaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.te.lsp._case.AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.te.lsp._case.address.family.Ipv4Case; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.te.lsp._case.address.family.Ipv4CaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.te.lsp._case.address.family.Ipv6Case; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.linkstate.object.type.te.lsp._case.address.family.Ipv6CaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.TunnelId; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode; import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode; @VisibleForTesting public final class TeLspNlriParser { @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier LSP_ID = new YangInstanceIdentifier.NodeIdentifier( QName.create(CLinkstateDestination.QNAME, "lsp-id").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier TUNNEL_ID = new YangInstanceIdentifier.NodeIdentifier( QName.create(CLinkstateDestination.QNAME, "tunnel-id").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV4_TUNNEL_SENDER_ADDRESS = new YangInstanceIdentifier.NodeIdentifier( QName.create(CLinkstateDestination.QNAME, "ipv4-tunnel-sender-address").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV4_TUNNEL_ENDPOINT_ADDRESS = new YangInstanceIdentifier .NodeIdentifier(QName.create(CLinkstateDestination.QNAME, "ipv4-tunnel-endpoint-address").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV6_TUNNEL_SENDER_ADDRESS = new YangInstanceIdentifier .NodeIdentifier( QName.create(CLinkstateDestination.QNAME, "ipv6-tunnel-sender-address").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV6_TUNNEL_ENDPOINT_ADDRESS = new YangInstanceIdentifier .NodeIdentifier(QName.create(CLinkstateDestination.QNAME, "ipv6-tunnel-endpoint-address").intern()); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV4_CASE = new YangInstanceIdentifier.NodeIdentifier(Ipv4Case.QNAME); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier IPV6_CASE = new YangInstanceIdentifier.NodeIdentifier(Ipv6Case.QNAME); @VisibleForTesting public static final YangInstanceIdentifier.NodeIdentifier ADDRESS_FAMILY = new YangInstanceIdentifier.NodeIdentifier(AddressFamily.QNAME); private TeLspNlriParser() { throw new UnsupportedOperationException(); } public static NlriType serializeIpvTSA(final AddressFamily addressFamily, final ByteBuf body) { if (addressFamily.equals(Ipv6Case.class)) { final Ipv6Address ipv6 = ((Ipv6Case) addressFamily).getIpv6TunnelSenderAddress(); Preconditions.checkArgument(ipv6 != null, "Ipv6TunnelSenderAddress is mandatory."); writeIpv6Address(ipv6, body); return NlriType.Ipv6TeLsp; } final Ipv4Address ipv4 = ((Ipv4Case) addressFamily).getIpv4TunnelSenderAddress(); Preconditions.checkArgument(ipv4 != null, "Ipv4TunnelSenderAddress is mandatory."); writeIpv4Address(ipv4, body); return NlriType.Ipv4TeLsp; } public static void serializeTunnelID(final TunnelId tunnelID, final ByteBuf body) { Preconditions.checkArgument(tunnelID != null, "TunnelId is mandatory."); writeUnsignedShort(tunnelID.getValue(), body); } public static void serializeLspID(final LspId lspId, final ByteBuf body) { Preconditions.checkArgument(lspId != null, "LspId is mandatory."); writeShort(lspId.getValue().shortValue(), body); } public static void serializeTEA(final AddressFamily addressFamily, final ByteBuf body) { if (addressFamily.equals(Ipv6Case.class)) { final Ipv6Address ipv6 = ((Ipv6Case) addressFamily).getIpv6TunnelEndpointAddress(); Preconditions.checkArgument(ipv6 != null, "Ipv6TunnelEndpointAddress is mandatory."); writeIpv6Address(ipv6, body); return; } final Ipv4Address ipv4 = ((Ipv4Case) addressFamily).getIpv4TunnelEndpointAddress(); Preconditions.checkArgument(ipv4 != null, "Ipv4TunnelEndpointAddress is mandatory."); Preconditions.checkArgument(ipv4 != null, "Ipv4TunnelEndpointAddress is mandatory."); writeIpv4Address(ipv4, body); } public static TeLspCase serializeTeLsp(final ContainerNode containerNode) { final TeLspCaseBuilder teLspCase = new TeLspCaseBuilder(); teLspCase.setLspId(new LspId((Long) containerNode.getChild(LSP_ID).get().getValue())); teLspCase.setTunnelId(new TunnelId((Integer) containerNode.getChild(TUNNEL_ID).get().getValue())); if(containerNode.getChild(ADDRESS_FAMILY).isPresent()) { final ChoiceNode addressFamily = (ChoiceNode) containerNode.getChild(ADDRESS_FAMILY).get(); if(addressFamily.getChild(IPV4_CASE).isPresent()) { teLspCase.setAddressFamily(serializeAddressFamily((ContainerNode) addressFamily.getChild(IPV4_CASE) .get(), true)); }else{ teLspCase.setAddressFamily(serializeAddressFamily((ContainerNode) addressFamily.getChild(IPV6_CASE) .get(), false)); } } return teLspCase.build(); } private static AddressFamily serializeAddressFamily(final ContainerNode containerNode, final boolean ipv4Case) { if(ipv4Case) { return new Ipv4CaseBuilder() .setIpv4TunnelSenderAddress(new Ipv4Address((String) containerNode.getChild(IPV4_TUNNEL_SENDER_ADDRESS).get().getValue())) .setIpv4TunnelEndpointAddress(new Ipv4Address((String) containerNode.getChild(IPV4_TUNNEL_ENDPOINT_ADDRESS).get().getValue())) .build(); } return new Ipv6CaseBuilder() .setIpv6TunnelSenderAddress(new Ipv6Address((String) containerNode.getChild(IPV6_TUNNEL_SENDER_ADDRESS).get().getValue())) .setIpv6TunnelEndpointAddress(new Ipv6Address((String) containerNode.getChild(IPV6_TUNNEL_ENDPOINT_ADDRESS).get().getValue())) .build(); } }
inocybe/odl-bgpcep
bgp/linkstate/src/main/java/org/opendaylight/protocol/bgp/linkstate/nlri/TeLspNlriParser.java
Java
epl-1.0
8,515
/** */ package WTSpec4M.presentation; import org.eclipse.emf.common.ui.URIEditorInput; import org.eclipse.emf.common.ui.action.WorkbenchWindowActionDelegate; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.edit.ui.action.LoadResourceAction; import org.eclipse.emf.edit.ui.util.EditUIUtil; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IFolderLayout; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.application.ActionBarAdvisor; import org.eclipse.ui.application.IActionBarConfigurer; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; import org.mondo.collaboration.online.rap.widgets.CurrentUserView; import org.mondo.collaboration.online.rap.widgets.DefaultPerspectiveAdvisor; import org.mondo.collaboration.online.rap.widgets.ModelExplorer; import org.mondo.collaboration.online.rap.widgets.ModelLogView; import org.mondo.collaboration.online.rap.widgets.WhiteboardChatView; /** * Customized {@link WorkbenchAdvisor} for the RCP application. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public final class WTSpec4MEditorAdvisor extends WorkbenchAdvisor { /** * This looks up a string in the plugin's plugin.properties file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static String getString(String key) { return WTSpec4MEditorPlugin.INSTANCE.getString(key); } /** * This looks up a string in plugin.properties, making a substitution. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static String getString(String key, Object s1) { return WTSpec4M.presentation.WTSpec4MEditorPlugin.INSTANCE.getString(key, new Object [] { s1 }); } /** * RCP's application * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class Application implements IApplication { /** * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Object start(IApplicationContext context) throws Exception { WorkbenchAdvisor workbenchAdvisor = new WTSpec4MEditorAdvisor(); Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, workbenchAdvisor); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } else { return IApplication.EXIT_OK; } } finally { display.dispose(); } } /** * @see org.eclipse.equinox.app.IApplication#stop() * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void stop() { // Do nothing. } } /** * RCP's perspective * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class Perspective implements IPerspectiveFactory { /** * Perspective ID * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final String ID_PERSPECTIVE = "WTSpec4M.presentation.WTSpec4MEditorAdvisorPerspective"; /** * @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(true); layout.addPerspectiveShortcut(ID_PERSPECTIVE); IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT, (float)0.33, layout.getEditorArea()); left.addView(ModelExplorer.ID); IFolderLayout bottomLeft = layout.createFolder("bottomLeft", IPageLayout.BOTTOM, (float)0.90, "left"); bottomLeft.addView(CurrentUserView.ID); IFolderLayout topRight = layout.createFolder("topRight", IPageLayout.RIGHT, (float)0.55, layout.getEditorArea()); topRight.addView(WhiteboardChatView.ID); IFolderLayout right = layout.createFolder("right", IPageLayout.BOTTOM, (float)0.33, "topRight"); right.addView(ModelLogView.ID); IFolderLayout bottomRight = layout.createFolder("bottomRight", IPageLayout.BOTTOM, (float)0.60, "right"); bottomRight.addView(IPageLayout.ID_PROP_SHEET); } } /** * RCP's window advisor * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class WindowAdvisor extends WorkbenchWindowAdvisor { private Shell shell; /** * @see WorkbenchWindowAdvisor#WorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public WindowAdvisor(IWorkbenchWindowConfigurer configurer) { super(configurer); } @Override public void createWindowContents(Shell shell) { super.createWindowContents(shell); this.shell = shell; } @Override public void postWindowOpen() { super.postWindowOpen(); shell.setMaximized(true); DefaultPerspectiveAdvisor.hideDefaultViews(); } /** * @see org.eclipse.ui.application.WorkbenchWindowAdvisor#preWindowOpen() * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void preWindowOpen() { IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); // configurer.setInitialSize(new Point(600, 450)); configurer.setShowCoolBar(false); configurer.setShowStatusLine(true); configurer.setTitle(getString("_UI_Application_title")); } /** * @see org.eclipse.ui.application.WorkbenchWindowAdvisor#createActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) { return new WindowActionBarAdvisor(configurer); } } /** * RCP's action bar advisor * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class WindowActionBarAdvisor extends ActionBarAdvisor { /** * @see ActionBarAdvisor#ActionBarAdvisor(org.eclipse.ui.application.IActionBarConfigurer) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public WindowActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } /** * @see org.eclipse.ui.application.ActionBarAdvisor#fillMenuBar(org.eclipse.jface.action.IMenuManager) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void fillMenuBar(IMenuManager menuBar) { IWorkbenchWindow window = getActionBarConfigurer().getWindowConfigurer().getWindow(); menuBar.add(createFileMenu(window)); menuBar.add(createEditMenu(window)); menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); menuBar.add(createWindowMenu(window)); menuBar.add(createHelpMenu(window)); } /** * Creates the 'File' menu. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createFileMenu(IWorkbenchWindow window) { IMenuManager menu = new MenuManager(getString("_UI_Menu_File_label"), IWorkbenchActionConstants.M_FILE); menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START)); IMenuManager newMenu = new MenuManager(getString("_UI_Menu_New_label"), "new"); newMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(newMenu); menu.add(new Separator()); menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator()); addToMenuAndRegister(menu, ActionFactory.CLOSE.create(window)); addToMenuAndRegister(menu, ActionFactory.CLOSE_ALL.create(window)); menu.add(new Separator()); addToMenuAndRegister(menu, ActionFactory.SAVE.create(window)); addToMenuAndRegister(menu, ActionFactory.SAVE_AS.create(window)); addToMenuAndRegister(menu, ActionFactory.SAVE_ALL.create(window)); menu.add(new Separator()); addToMenuAndRegister(menu, ActionFactory.QUIT.create(window)); menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_END)); return menu; } /** * Creates the 'Edit' menu. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createEditMenu(IWorkbenchWindow window) { IMenuManager menu = new MenuManager(getString("_UI_Menu_Edit_label"), IWorkbenchActionConstants.M_EDIT); menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_START)); addToMenuAndRegister(menu, ActionFactory.UNDO.create(window)); addToMenuAndRegister(menu, ActionFactory.REDO.create(window)); menu.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT)); menu.add(new Separator()); addToMenuAndRegister(menu, ActionFactory.CUT.create(window)); addToMenuAndRegister(menu, ActionFactory.COPY.create(window)); addToMenuAndRegister(menu, ActionFactory.PASTE.create(window)); menu.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT)); menu.add(new Separator()); addToMenuAndRegister(menu, ActionFactory.DELETE.create(window)); addToMenuAndRegister(menu, ActionFactory.SELECT_ALL.create(window)); menu.add(new Separator()); menu.add(new GroupMarker(IWorkbenchActionConstants.ADD_EXT)); menu.add(new GroupMarker(IWorkbenchActionConstants.EDIT_END)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); return menu; } /** * Creates the 'Window' menu. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createWindowMenu(IWorkbenchWindow window) { IMenuManager menu = new MenuManager(getString("_UI_Menu_Window_label"), IWorkbenchActionConstants.M_WINDOW); addToMenuAndRegister(menu, ActionFactory.OPEN_NEW_WINDOW.create(window)); menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); return menu; } /** * Creates the 'Help' menu. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createHelpMenu(IWorkbenchWindow window) { IMenuManager menu = new MenuManager(getString("_UI_Menu_Help_label"), IWorkbenchActionConstants.M_HELP); // Welcome or intro page would go here // Help contents would go here // Tips and tricks page would go here menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_START)); menu.add(new GroupMarker(IWorkbenchActionConstants.HELP_END)); menu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); return menu; } /** * Adds the specified action to the given menu and also registers the action with the * action bar configurer, in order to activate its key binding. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addToMenuAndRegister(IMenuManager menuManager, IAction action) { menuManager.add(action); getActionBarConfigurer().registerGlobalAction(action); } } /** * About action for the RCP application. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class AboutAction extends WorkbenchWindowActionDelegate { /** * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void run(IAction action) { MessageDialog.openInformation(getWindow().getShell(), getString("_UI_About_title"), getString("_UI_About_text")); } } /** * Open URI action for the objects from the WTSpec4M model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static class OpenURIAction extends WorkbenchWindowActionDelegate { /** * Opens the editors for the files selected using the LoadResourceDialog. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void run(IAction action) { LoadResourceAction.LoadResourceDialog loadResourceDialog = new LoadResourceAction.LoadResourceDialog(getWindow().getShell()); if (Window.OK == loadResourceDialog.open()) { for (URI uri : loadResourceDialog.getURIs()) { openEditor(getWindow().getWorkbench(), uri); } } } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static boolean openEditor(IWorkbench workbench, URI uri) { IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); IWorkbenchPage page = workbenchWindow.getActivePage(); IEditorDescriptor editorDescriptor = EditUIUtil.getDefaultEditor(uri, null); if (editorDescriptor == null) { MessageDialog.openError( workbenchWindow.getShell(), getString("_UI_Error_title"), getString("_WARN_No_Editor", uri.lastSegment())); return false; } else { try { page.openEditor(new URIEditorInput(uri), editorDescriptor.getId()); } catch (PartInitException exception) { MessageDialog.openError( workbenchWindow.getShell(), getString("_UI_OpenEditorError_label"), exception.getMessage()); return false; } } return true; } /** * @see org.eclipse.ui.application.WorkbenchAdvisor#getInitialWindowPerspectiveId() * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getInitialWindowPerspectiveId() { return Perspective.ID_PERSPECTIVE; } /** * @see org.eclipse.ui.application.WorkbenchAdvisor#initialize(org.eclipse.ui.application.IWorkbenchConfigurer) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void initialize(IWorkbenchConfigurer configurer) { super.initialize(configurer); configurer.setSaveAndRestore(true); } /** * @see org.eclipse.ui.application.WorkbenchAdvisor#createWorkbenchWindowAdvisor(org.eclipse.ui.application.IWorkbenchWindowConfigurer) * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new WindowAdvisor(configurer); } }
mondo-project/mondo-demo-wt
MONDO-Collab/org.mondo.wt.cstudy.metamodel.online.editor/src/WTSpec4M/presentation/WTSpec4MEditorAdvisor.java
Java
epl-1.0
14,965
import java.sql.*; public class ConnessioneDB { static { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "calcio"; String userName = "root"; String password = ""; /* String url = "jdbc:mysql://127.11.139.2:3306/"; String dbName = "sirio"; String userName = "adminlL8hBfI"; String password = "HPZjQCQsnVG4"; */ public Connection openConnection(){ try { conn = DriverManager.getConnection(url+dbName,userName,password); System.out.println("Connessione al DataBase stabilita!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public void closeConnection(Connection conn){ try { conn.close(); System.out.println(" Chiusa connessione al DB!"); } catch (SQLException e) { e.printStackTrace(); } } }
nicolediana/progetto
ServletExample/src/ConnessioneDB.java
Java
epl-1.0
1,248
package com.huihuang.utils; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class BeanToMap<K, V> { private BeanToMap() { } @SuppressWarnings("unchecked") public static <K, V> Map<K, V> bean2Map(Object javaBean) { Map<K, V> ret = new HashMap<K, V>(); try { Method[] methods = javaBean.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getName().startsWith("get")) { String field = method.getName(); field = field.substring(field.indexOf("get") + 3); field = field.toLowerCase().charAt(0) + field.substring(1); Object value = method.invoke(javaBean, (Object[]) null); ret.put((K) field, (V) (null == value ? "" : value)); } } } catch (Exception e) { } return ret; } }
yc654084303/QuickConnQuickConnect
QuickConnectPay/src/com/huihuang/utils/BeanToMap.java
Java
epl-1.0
1,034
/** * Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved. * This software is the confidential and proprietary information of SK holdings. * You shall not disclose such confidential information and shall use it only in * accordance with the terms of the license agreement you entered into with SK holdings. * (http://www.eclipse.org/legal/epl-v10.html) */ package nexcore.alm.common.excel; import nexcore.alm.common.exception.BaseException; /** * Excel import/export 과정에서 발생할 수 있는 예외상황 * * @author indeday * */ public class ExcelException extends BaseException { /** * serialVersionUID */ private static final long serialVersionUID = 5191191573910676820L; /** * @see BaseException#BaseException(String, String) */ public ExcelException(String message, String logType) { super(message, logType); } /** * @see BaseException#BaseException(String, Throwable, String) */ public ExcelException(Throwable cause, String message, String logType) { super(message, cause, logType); } /** * @see BaseException#BaseException(Throwable, String) */ public ExcelException(Throwable cause, String message) { super(cause, message); } /** * @see BaseException#BaseException(Throwable, boolean) */ public ExcelException(Throwable cause, boolean useLog) { super(cause, useLog); } }
SK-HOLDINGS-CC/NEXCORE-UML-Modeler
nexcore.alm.common/src/nexcore/alm/common/excel/ExcelException.java
Java
epl-1.0
1,457
/******************************************************************************* * Copyright (c) 2009 Andrey Loskutov. * 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 * Contributor: Andrey Loskutov - initial API and implementation *******************************************************************************/ package de.loskutov.anyedit.actions.replace; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.Writer; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.handlers.HandlerUtil; import de.loskutov.anyedit.AnyEditToolsPlugin; import de.loskutov.anyedit.IAnyEditConstants; import de.loskutov.anyedit.compare.ContentWrapper; import de.loskutov.anyedit.ui.editor.AbstractEditor; import de.loskutov.anyedit.util.EclipseUtils; /** * @author Andrey */ public abstract class ReplaceWithAction extends AbstractHandler implements IObjectActionDelegate { protected ContentWrapper selectedContent; protected AbstractEditor editor; public ReplaceWithAction() { super(); editor = new AbstractEditor(null); } @Override public Object execute(final ExecutionEvent event) throws ExecutionException { IWorkbenchPart activePart = HandlerUtil.getActivePart(event); Action dummyAction = new Action(){ @Override public String getId() { return event.getCommand().getId(); } }; setActivePart(dummyAction, activePart); ISelection currentSelection = HandlerUtil.getCurrentSelection(event); selectionChanged(dummyAction, currentSelection); if(dummyAction.isEnabled()) { run(dummyAction); } return null; } @Override public void setActivePart(IAction action, IWorkbenchPart targetPart) { if (targetPart instanceof IEditorPart) { editor = new AbstractEditor((IEditorPart) targetPart); } else { editor = new AbstractEditor(null); } } @Override public void run(IAction action) { InputStream stream = createInputStream(); if (stream == null) { return; } replace(stream); } private void replace(InputStream stream) { if(selectedContent == null || !selectedContent.isModifiable()){ return; } IDocument document = editor.getDocument(); if (!editor.isDisposed() && document != null) { // replace selection only String text = getChangedCompareText(stream); ITextSelection selection = editor.getSelection(); if (selection == null || selection.getLength() == 0) { document.set(text); } else { try { document.replace(selection.getOffset(), selection.getLength(), text); } catch (BadLocationException e) { AnyEditToolsPlugin.logError("Can't update text in editor", e); } } return; } replace(selectedContent, stream); } private String getChangedCompareText(InputStream stream) { StringWriter sw = new StringWriter(); copyStreamToWriter(stream, sw); return sw.toString(); } private void replace(ContentWrapper content, InputStream stream) { IFile file = content.getIFile(); if (file == null || file.getLocation() == null) { saveExternalFile(content, stream); return; } try { if (!file.exists()) { file.create(stream, true, new NullProgressMonitor()); } else { ITextFileBuffer buffer = EclipseUtils.getBuffer(file); try { if (AnyEditToolsPlugin.getDefault().getPreferenceStore().getBoolean( IAnyEditConstants.SAVE_DIRTY_BUFFER)) { if (buffer != null && buffer.isDirty()) { buffer.commit(new NullProgressMonitor(), false); } } if (buffer != null) { buffer.validateState(new NullProgressMonitor(), AnyEditToolsPlugin.getShell()); } } finally { EclipseUtils.disconnectBuffer(buffer); } file.setContents(stream, true, true, new NullProgressMonitor()); } } catch (CoreException e) { AnyEditToolsPlugin.errorDialog("Can't replace file content: " + file, e); } finally { try { stream.close(); } catch (IOException e) { AnyEditToolsPlugin.logError("Failed to close stream", e); } } } private void copyStreamToWriter(InputStream stream, Writer writer){ InputStreamReader in = null; try { in = new InputStreamReader(stream, editor.computeEncoding()); BufferedReader br = new BufferedReader(in); int i; while ((i = br.read()) != -1) { writer.write(i); } writer.flush(); } catch (IOException e) { AnyEditToolsPlugin.logError("Error during reading/writing streams", e); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { AnyEditToolsPlugin.logError("Failed to close stream", e); } try { if (in != null) { in.close(); } } catch (IOException e) { AnyEditToolsPlugin.logError("Failed to close stream", e); } } } private void saveExternalFile(ContentWrapper content, InputStream stream) { File file2 = null; IFile iFile = content.getIFile(); if (iFile != null) { file2 = new File(iFile.getFullPath().toOSString()); } else { file2 = content.getFile(); } if (!file2.exists()) { try { file2.createNewFile(); } catch (IOException e) { AnyEditToolsPlugin.errorDialog("Can't create file: " + file2, e); return; } } boolean canWrite = file2.canWrite(); if (!canWrite) { AnyEditToolsPlugin.errorDialog("File is read-only: " + file2); return; } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(file2)); copyStreamToWriter(stream, bw); } catch (IOException e) { AnyEditToolsPlugin.logError("Error on saving to file: " + file2, e); return; } finally { try { if(bw != null) { bw.close(); } } catch (IOException e) { AnyEditToolsPlugin.logError("Error on saving to file: " + file2, e); } } if (iFile != null) { try { iFile.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); } catch (CoreException e) { AnyEditToolsPlugin.logError("Failed to refresh file: " + iFile, e); } } } abstract protected InputStream createInputStream(); @Override public void selectionChanged(IAction action, ISelection selection) { if (!(selection instanceof IStructuredSelection) || selection.isEmpty()) { if(!editor.isDisposed()){ selectedContent = ContentWrapper.create(editor); } action.setEnabled(selectedContent != null); return; } IStructuredSelection sSelection = (IStructuredSelection) selection; Object firstElement = sSelection.getFirstElement(); if(!editor.isDisposed()) { selectedContent = ContentWrapper.create(editor); } else { selectedContent = ContentWrapper.create(firstElement); } action.setEnabled(selectedContent != null && sSelection.size() == 1); } }
iloveeclipse/anyedittools
AnyEditTools/src/de/loskutov/anyedit/actions/replace/ReplaceWithAction.java
Java
epl-1.0
9,434
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.aesh.complete; import org.jboss.aesh.console.AeshContext; import org.jboss.aesh.parser.Parser; import org.jboss.aesh.terminal.TerminalString; import java.util.ArrayList; import java.util.List; /** * A payload object to store completion data * * @author Ståle W. Pedersen <stale.pedersen@jboss.org> */ public class CompleteOperation { private String buffer; private int cursor; private int offset; private List<TerminalString> completionCandidates; private boolean trimmed = false; private boolean ignoreStartsWith = false; private String nonTrimmedBuffer; private AeshContext aeshContext; private char separator = ' '; private boolean appendSeparator = true; private boolean ignoreOffset = false; public CompleteOperation(AeshContext aeshContext, String buffer, int cursor) { this.aeshContext = aeshContext; setCursor(cursor); setSeparator(' '); doAppendSeparator(true); completionCandidates = new ArrayList<>(); setBuffer(buffer); } public String getBuffer() { return buffer; } private void setBuffer(String buffer) { if(buffer != null && buffer.startsWith(" ")) { trimmed = true; this.buffer = Parser.trimInFront(buffer); nonTrimmedBuffer = buffer; setCursor(cursor - getTrimmedSize()); } else this.buffer = buffer; } public boolean isTrimmed() { return trimmed; } public int getTrimmedSize() { return nonTrimmedBuffer.length() - buffer.length(); } public String getNonTrimmedBuffer() { return nonTrimmedBuffer; } public int getCursor() { return cursor; } private void setCursor(int cursor) { if(cursor < 0) this.cursor = 0; else this.cursor = cursor; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public void setIgnoreOffset(boolean ignoreOffset) { this.ignoreOffset = ignoreOffset; } public boolean doIgnoreOffset() { return ignoreOffset; } public AeshContext getAeshContext() { return aeshContext; } /** * Get the separator character, by default its space * * @return separator */ public char getSeparator() { return separator; } /** * By default the separator is one space char, but * it can be overridden here. * * @param separator separator */ public void setSeparator(char separator) { this.separator = separator; } /** * Do this completion allow for appending a separator * after completion? By default this is true. * * @return appendSeparator */ public boolean hasAppendSeparator() { return appendSeparator; } /** * Set if this CompletionOperation would allow an separator to * be appended. By default this is true. * * @param appendSeparator appendSeparator */ public void doAppendSeparator(boolean appendSeparator) { this.appendSeparator = appendSeparator; } public List<TerminalString> getCompletionCandidates() { return completionCandidates; } public void setCompletionCandidates(List<String> completionCandidates) { addCompletionCandidates(completionCandidates); } public void setCompletionCandidatesTerminalString(List<TerminalString> completionCandidates) { this.completionCandidates = completionCandidates; } public void addCompletionCandidate(TerminalString completionCandidate) { this.completionCandidates.add(completionCandidate); } public void addCompletionCandidate(String completionCandidate) { addStringCandidate(completionCandidate); } public void addCompletionCandidates(List<String> completionCandidates) { addStringCandidates(completionCandidates); } public void addCompletionCandidatesTerminalString(List<TerminalString> completionCandidates) { this.completionCandidates.addAll(completionCandidates); } public void removeEscapedSpacesFromCompletionCandidates() { Parser.switchEscapedSpacesToSpacesInTerminalStringList(getCompletionCandidates()); } private void addStringCandidate(String completionCandidate) { this.completionCandidates.add(new TerminalString(completionCandidate, true)); } private void addStringCandidates(List<String> completionCandidates) { for(String s : completionCandidates) addStringCandidate(s); } public List<String> getFormattedCompletionCandidates() { List<String> fixedCandidates = new ArrayList<String>(completionCandidates.size()); for(TerminalString c : completionCandidates) { if(!ignoreOffset && offset < cursor) { int pos = cursor - offset; if(c.getCharacters().length() >= pos) fixedCandidates.add(c.getCharacters().substring(pos)); else fixedCandidates.add(""); } else { fixedCandidates.add(c.getCharacters()); } } return fixedCandidates; } public List<TerminalString> getFormattedCompletionCandidatesTerminalString() { List<TerminalString> fixedCandidates = new ArrayList<TerminalString>(completionCandidates.size()); for(TerminalString c : completionCandidates) { if(!ignoreOffset && offset < cursor) { int pos = cursor - offset; if(c.getCharacters().length() >= pos) { TerminalString ts = c; ts.setCharacters(c.getCharacters().substring(pos)); fixedCandidates.add(ts); } else fixedCandidates.add(new TerminalString("", true)); } else { fixedCandidates.add(c); } } return fixedCandidates; } public String getFormattedCompletion(String completion) { if(offset < cursor) { int pos = cursor - offset; if(completion.length() > pos) return completion.substring(pos); else return ""; } else return completion; } public boolean isIgnoreStartsWith() { return ignoreStartsWith; } public void setIgnoreStartsWith(boolean ignoreStartsWith) { this.ignoreStartsWith = ignoreStartsWith; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Buffer: ").append(buffer) .append(", Cursor:").append(cursor) .append(", Offset:").append(offset) .append(", IgnoreOffset:").append(ignoreOffset) .append(", Append separator: ").append(appendSeparator) .append(", Candidates:").append(completionCandidates); return sb.toString(); } }
aslakknutsen/aesh
src/main/java/org/jboss/aesh/complete/CompleteOperation.java
Java
epl-1.0
7,366
package dao.inf; // Generated 27/11/2014 02:39:51 AM by Hibernate Tools 3.4.0.CR1 import java.util.List; import javax.naming.InitialContext; import model.Query; import model.QueryId; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.LockMode; import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; /** * Home object for domain model class Query. * @see .Query * @author Hibernate Tools */ public interface QueryDAO { public boolean save(Query query); public Integer lastId(); }
mhersc1/SIGAE
src/main/java/dao/inf/QueryDAO.java
Java
epl-1.0
590
/** * <copyright> * </copyright> * * $Id$ */ package klaper.expr.util; import java.util.List; import klaper.expr.Atom; import klaper.expr.Binary; import klaper.expr.Div; import klaper.expr.Exp; import klaper.expr.ExprPackage; import klaper.expr.Expression; import klaper.expr.Minus; import klaper.expr.Mult; import klaper.expr.Operator; import klaper.expr.Plus; import klaper.expr.Unary; import klaper.expr.Variable; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see klaper.expr.ExprPackage * @generated */ public class ExprSwitch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ExprPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ExprSwitch() { if (modelPackage == null) { modelPackage = ExprPackage.eINSTANCE; } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ public T doSwitch(EObject theEObject) { return doSwitch(theEObject.eClass(), theEObject); } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(EClass theEClass, EObject theEObject) { if (theEClass.eContainer() == modelPackage) { return doSwitch(theEClass.getClassifierID(), theEObject); } else { List<EClass> eSuperTypes = theEClass.getESuperTypes(); return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch(eSuperTypes.get(0), theEObject); } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case ExprPackage.EXPRESSION: { Expression expression = (Expression)theEObject; T result = caseExpression(expression); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.ATOM: { Atom atom = (Atom)theEObject; T result = caseAtom(atom); if (result == null) result = caseExpression(atom); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.NUMBER: { klaper.expr.Number number = (klaper.expr.Number)theEObject; T result = caseNumber(number); if (result == null) result = caseAtom(number); if (result == null) result = caseExpression(number); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.VARIABLE: { Variable variable = (Variable)theEObject; T result = caseVariable(variable); if (result == null) result = caseAtom(variable); if (result == null) result = caseExpression(variable); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.INTEGER: { klaper.expr.Integer integer = (klaper.expr.Integer)theEObject; T result = caseInteger(integer); if (result == null) result = caseNumber(integer); if (result == null) result = caseAtom(integer); if (result == null) result = caseExpression(integer); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.DOUBLE: { klaper.expr.Double double_ = (klaper.expr.Double)theEObject; T result = caseDouble(double_); if (result == null) result = caseNumber(double_); if (result == null) result = caseAtom(double_); if (result == null) result = caseExpression(double_); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.UNARY: { Unary unary = (Unary)theEObject; T result = caseUnary(unary); if (result == null) result = caseExpression(unary); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.BINARY: { Binary binary = (Binary)theEObject; T result = caseBinary(binary); if (result == null) result = caseExpression(binary); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.OPERATOR: { Operator operator = (Operator)theEObject; T result = caseOperator(operator); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.PLUS: { Plus plus = (Plus)theEObject; T result = casePlus(plus); if (result == null) result = caseOperator(plus); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.MINUS: { Minus minus = (Minus)theEObject; T result = caseMinus(minus); if (result == null) result = caseOperator(minus); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.MULT: { Mult mult = (Mult)theEObject; T result = caseMult(mult); if (result == null) result = caseOperator(mult); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.DIV: { Div div = (Div)theEObject; T result = caseDiv(div); if (result == null) result = caseOperator(div); if (result == null) result = defaultCase(theEObject); return result; } case ExprPackage.EXP: { Exp exp = (Exp)theEObject; T result = caseExp(exp); if (result == null) result = caseOperator(exp); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Expression</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Expression</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExpression(Expression object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Atom</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Atom</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseAtom(Atom object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Number</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Number</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNumber(klaper.expr.Number object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Variable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Variable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseVariable(Variable object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Integer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Integer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInteger(klaper.expr.Integer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Double</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Double</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDouble(klaper.expr.Double object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Unary</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Unary</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseUnary(Unary object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Binary</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Binary</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseBinary(Binary object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Operator</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Operator</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseOperator(Operator object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Plus</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Plus</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePlus(Plus object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Minus</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Minus</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMinus(Minus object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Mult</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Mult</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseMult(Mult object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Div</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Div</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDiv(Div object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Exp</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Exp</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExp(Exp object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ public T defaultCase(EObject object) { return null; } } //ExprSwitch
aciancone/klapersuite
klapersuite.metamodel.klaper/src/klaper/expr/util/ExprSwitch.java
Java
epl-1.0
14,296
package critterbot.actions; public class XYThetaAction extends CritterbotAction { private static final long serialVersionUID = -1434106060178637255L; private static final int ActionValue = 30; public static final CritterbotAction NoMove = new XYThetaAction(0, 0, 0); public static final CritterbotAction TurnLeft = new XYThetaAction(ActionValue, ActionValue, ActionValue); public static final CritterbotAction TurnRight = new XYThetaAction(ActionValue, ActionValue, -ActionValue); public static final CritterbotAction Forward = new XYThetaAction(ActionValue, 0, 0); public static final CritterbotAction Backward = new XYThetaAction(-ActionValue, 0, 0); public static final CritterbotAction Left = new XYThetaAction(0, -ActionValue, 0); public static final CritterbotAction Right = new XYThetaAction(0, ActionValue, 0); public XYThetaAction(double x, double y, double theta) { super(MotorMode.XYTHETA_SPACE, x, y, theta); } public XYThetaAction(double[] actions) { super(MotorMode.XYTHETA_SPACE, actions); } static public CritterbotAction[] sevenActions() { return new CritterbotAction[] { NoMove, TurnLeft, TurnRight, Forward, Backward, Left, Right }; } }
amw8/rlpark
rlpark.plugin.critterbot/jvsrc/critterbot/actions/XYThetaAction.java
Java
epl-1.0
1,202
package mx.com.cinepolis.digital.booking.persistence.dao.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.interceptor.Interceptors; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.Order; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import mx.com.cinepolis.digital.booking.commons.query.ModelQuery; import mx.com.cinepolis.digital.booking.commons.query.ScreenQuery; import mx.com.cinepolis.digital.booking.commons.query.SortOrder; import mx.com.cinepolis.digital.booking.commons.to.CatalogTO; import mx.com.cinepolis.digital.booking.commons.to.PagingRequestTO; import mx.com.cinepolis.digital.booking.commons.to.PagingResponseTO; import mx.com.cinepolis.digital.booking.commons.to.ScreenTO; import mx.com.cinepolis.digital.booking.dao.util.CriteriaQueryBuilder; import mx.com.cinepolis.digital.booking.dao.util.ExceptionHandlerDAOInterceptor; import mx.com.cinepolis.digital.booking.dao.util.ScreenDOToScreenTOTransformer; import mx.com.cinepolis.digital.booking.model.CategoryDO; import mx.com.cinepolis.digital.booking.model.ScreenDO; import mx.com.cinepolis.digital.booking.model.TheaterDO; import mx.com.cinepolis.digital.booking.model.utils.AbstractEntityUtils; import mx.com.cinepolis.digital.booking.persistence.base.dao.AbstractBaseDAO; import mx.com.cinepolis.digital.booking.persistence.dao.CategoryDAO; import mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO; import org.apache.commons.collections.CollectionUtils; /** * Implementation of the interface {@link mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO} * * @author agustin.ramirez * @since 0.0.1 */ @Stateless @Interceptors({ ExceptionHandlerDAOInterceptor.class }) public class ScreenDAOImpl extends AbstractBaseDAO<ScreenDO> implements ScreenDAO { /** * Entity Manager */ @PersistenceContext(unitName = "DigitalBookingPU") private EntityManager em; @EJB private CategoryDAO categoryDAO; /** * {@inheritDoc} */ @Override protected EntityManager getEntityManager() { return em; } /** * Constructor Default */ public ScreenDAOImpl() { super( ScreenDO.class ); } /* * (non-Javadoc) * @see mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO#save(mx.com * .cinepolis.digital.booking.model.to.ScreenTO) */ @Override public void save( ScreenTO screenTO ) { ScreenDO entity = new ScreenDO(); AbstractEntityUtils.applyElectronicSign( entity, screenTO ); entity.setIdTheater( new TheaterDO( screenTO.getIdTheater() ) ); entity.setIdVista( screenTO.getIdVista() ); entity.setNuCapacity( screenTO.getNuCapacity() ); entity.setNuScreen( screenTO.getNuScreen() ); entity.setCategoryDOList( new ArrayList<CategoryDO>() ); for( CatalogTO catalogTO : screenTO.getSoundFormats() ) { CategoryDO categorySound = categoryDAO.find( catalogTO.getId().intValue() ); categorySound.getScreenDOList().add( entity ); entity.getCategoryDOList().add( categorySound ); } for( CatalogTO catalogTO : screenTO.getMovieFormats() ) { CategoryDO categoryMovieFormat = categoryDAO.find( catalogTO.getId().intValue() ); categoryMovieFormat.getScreenDOList().add( entity ); entity.getCategoryDOList().add( categoryMovieFormat ); } if( screenTO.getScreenFormat() != null ) { CategoryDO categoryMovieFormat = categoryDAO.find( screenTO.getScreenFormat().getId().intValue() ); categoryMovieFormat.getScreenDOList().add( entity ); entity.getCategoryDOList().add( categoryMovieFormat ); } this.create( entity ); this.flush(); screenTO.setId( entity.getIdScreen().longValue() ); } /* * (non-Javadoc) * @see mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO#update(mx. * com.cinepolis.digital.booking.model.to.ScreenTO) */ @Override public void update( ScreenTO screenTO ) { ScreenDO entity = this.find( screenTO.getId().intValue() ); if( entity != null ) { AbstractEntityUtils.applyElectronicSign( entity, screenTO ); entity.setNuCapacity( screenTO.getNuCapacity() ); entity.setNuScreen( screenTO.getNuScreen() ); entity.setIdVista( screenTO.getIdVista() ); updateCategories( screenTO, entity ); this.edit( entity ); } } private void updateCategories( ScreenTO screenTO, ScreenDO entity ) { List<CatalogTO> categories = new ArrayList<CatalogTO>(); // Limpieza de categorías for( CategoryDO categoryDO : entity.getCategoryDOList() ) { categoryDO.getScreenDOList().remove( entity ); this.categoryDAO.edit( categoryDO ); } entity.setCategoryDOList( new ArrayList<CategoryDO>() ); for( CatalogTO to : screenTO.getMovieFormats() ) { categories.add( to ); } for( CatalogTO to : screenTO.getSoundFormats() ) { categories.add( to ); } if( screenTO.getScreenFormat() != null ) { categories.add( screenTO.getScreenFormat() ); } for( CatalogTO catalogTO : categories ) { CategoryDO category = this.categoryDAO.find( catalogTO.getId().intValue() ); category.getScreenDOList().add( entity ); entity.getCategoryDOList().add( category ); } } /* * (non-Javadoc) * @see mx.com.cinepolis.digital.booking.persistence.base.dao.AbstractBaseDAO #remove(java.lang.Object) */ @Override public void remove( ScreenDO screenDO ) { ScreenDO remove = super.find( screenDO.getIdScreen() ); if( remove != null ) { AbstractEntityUtils.copyElectronicSign( remove, screenDO ); remove.setFgActive( false ); super.edit( remove ); } } /* * (non-Javadoc) * @see mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO#delete(mx. * com.cinepolis.digital.booking.model.to.ScreenTO) */ @Override public void delete( ScreenTO screenTO ) { ScreenDO screenDO = new ScreenDO( screenTO.getId().intValue() ); AbstractEntityUtils.applyElectronicSign( screenDO, screenTO ); this.remove( screenDO ); } /* * (non-Javadoc) * @see mx.com.cinepolis.digital.booking.persistence.dao.ScreenDAO#findAllByPaging * (mx.com.cinepolis.digital.booking.model.to.PagingRequestTO) */ @SuppressWarnings("unchecked") @Override public PagingResponseTO<ScreenTO> findAllByPaging( PagingRequestTO pagingRequestTO ) { List<ModelQuery> sortFields = pagingRequestTO.getSort(); SortOrder sortOrder = pagingRequestTO.getSortOrder(); Map<ModelQuery, Object> filters = getFilters( pagingRequestTO ); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ScreenDO> q = cb.createQuery( ScreenDO.class ); Root<ScreenDO> screenDO = q.from( ScreenDO.class ); Join<ScreenDO, TheaterDO> theatherDO = screenDO.join( "idTheater" ); q.select( screenDO ); applySorting( sortFields, sortOrder, cb, q, screenDO, theatherDO ); Predicate filterCondition = applyFilters( filters, cb, screenDO, theatherDO ); CriteriaQuery<Long> queryCountRecords = cb.createQuery( Long.class ); queryCountRecords.select( cb.count( screenDO ) ); if( filterCondition != null ) { q.where( filterCondition ); queryCountRecords.where( filterCondition ); } // pagination TypedQuery<ScreenDO> tq = em.createQuery( q ); int count = em.createQuery( queryCountRecords ).getSingleResult().intValue(); if( pagingRequestTO.getNeedsPaging() ) { int page = pagingRequestTO.getPage(); int pageSize = pagingRequestTO.getPageSize(); if( pageSize > 0 ) { tq.setMaxResults( pageSize ); } if( page >= 0 ) { tq.setFirstResult( page * pageSize ); } } PagingResponseTO<ScreenTO> response = new PagingResponseTO<ScreenTO>(); response.setElements( (List<ScreenTO>) CollectionUtils.collect( tq.getResultList(), new ScreenDOToScreenTOTransformer( pagingRequestTO.getLanguage() ) ) ); response.setTotalCount( count ); return response; } /** * Aplicamos los filtros * * @param filters * @param cb * @param screenDO * @param theaterDO * @param categoryLanguage * @return */ private Predicate applyFilters( Map<ModelQuery, Object> filters, CriteriaBuilder cb, Root<ScreenDO> screenDO, Join<ScreenDO, TheaterDO> theaterDO ) { Predicate filterCondition = null; if( filters != null && !filters.isEmpty() ) { filterCondition = cb.conjunction(); filterCondition = CriteriaQueryBuilder.<Integer> applyFilterRootEqual( filters, ScreenQuery.SCREEN_ID, screenDO, cb, filterCondition ); filterCondition = CriteriaQueryBuilder.<Integer> applyFilterRootEqual( filters, ScreenQuery.SCREEN_NUMBER, screenDO, cb, filterCondition ); filterCondition = CriteriaQueryBuilder.<Integer> applyFilterRootEqual( filters, ScreenQuery.SCREEN_CAPACITY, screenDO, cb, filterCondition ); filterCondition = CriteriaQueryBuilder.<Integer> applyFilterJoinEqual( filters, ScreenQuery.SCREEN_THEATER_ID, theaterDO, cb, filterCondition ); } return filterCondition; } /** * Metodo que aplica el campo por le cual se ordenaran * * @param sortField * @param sortOrder * @param cb * @param q * @param screenDO * @param theather */ private void applySorting( List<ModelQuery> sortFields, SortOrder sortOrder, CriteriaBuilder cb, CriteriaQuery<ScreenDO> q, Root<ScreenDO> screenDO, Join<ScreenDO, TheaterDO> theather ) { if( sortOrder != null && CollectionUtils.isNotEmpty( sortFields ) ) { List<Order> order = new ArrayList<Order>(); for( ModelQuery sortField : sortFields ) { if( sortField instanceof ScreenQuery ) { Path<?> path = null; switch( (ScreenQuery) sortField ) { case SCREEN_ID: path = screenDO.get( sortField.getQuery() ); break; case SCREEN_NUMBER: path = screenDO.get( sortField.getQuery() ); break; case SCREEN_CAPACITY: path = screenDO.get( sortField.getQuery() ); break; case SCREEN_THEATER_ID: path = theather.get( sortField.getQuery() ); break; default: path = screenDO.get( ScreenQuery.SCREEN_ID.getQuery() ); } if( sortOrder.equals( SortOrder.ASCENDING ) ) { order.add( cb.asc( path ) ); } else { order.add( cb.desc( path ) ); } } } q.orderBy( order ); } } /** * Obtiene los filtros y añade el lenguaje * * @param pagingRequestTO * @return */ private Map<ModelQuery, Object> getFilters( PagingRequestTO pagingRequestTO ) { Map<ModelQuery, Object> filters = pagingRequestTO.getFilters(); if( filters == null ) { filters = new HashMap<ModelQuery, Object>(); } return filters; } @SuppressWarnings("unchecked") @Override public List<ScreenDO> findAllActiveByIdCinema( Integer idTheater ) { Query q = this.em.createNamedQuery( "ScreenDO.findAllActiveByIdCinema" ); q.setParameter( "idTheater", idTheater ); return q.getResultList(); } @SuppressWarnings("unchecked") @Override public List<ScreenDO> findByIdVistaAndActive( String idVista ) { Query q = this.em.createNamedQuery( "ScreenDO.findByIdVistaAndActive" ); q.setParameter( "idVista", idVista ); return q.getResultList(); } }
sidlors/digital-booking
digital-booking-persistence/src/main/java/mx/com/cinepolis/digital/booking/persistence/dao/impl/ScreenDAOImpl.java
Java
epl-1.0
12,056
/** */ package TaxationWithRoot; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Tax Card</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link TaxationWithRoot.Tax_Card#getCard_identifier <em>Card identifier</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getTax_office <em>Tax office</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getPercentage_of_witholding <em>Percentage of witholding</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_name_surname <em>Tax payers name surname</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_partner_name_surname <em>Tax payers partner name surname</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getTax_payers_address <em>Tax payers address</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getJobs_Employer_SSNo <em>Jobs Employer SS No</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getJobs_employers_name <em>Jobs employers name</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getJobs_activity_type <em>Jobs activity type</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getJobs_place_of_work <em>Jobs place of work</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FD_daily <em>Deduction FD daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FD_monthly <em>Deduction FD monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_daily <em>Deduction AC daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_monthly <em>Deduction AC monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_AC_yearly <em>Deduction AC yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_daily <em>Deduction CE daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_monthly <em>Deduction CE monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_CE_yearly <em>Deduction CE yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_daily <em>Deduction DS daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_monthly <em>Deduction DS monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_daily <em>Deduction FO daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_monthly <em>Deduction FO monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_FO_yearly <em>Deduction FO yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIS_daily <em>Credit CIS daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIS_monthly <em>Credit CIS monthly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIM_daily <em>Credit CIM daily</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#isValidity <em>Validity</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getIncome_Tax_Credit <em>Income Tax Credit</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getCredit_CIM_yearly <em>Credit CIM yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Alimony_yearly <em>Deduction DS Alimony yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Debt_yearly <em>Deduction DS Debt yearly</em>}</li> * <li>{@link TaxationWithRoot.Tax_Card#getIncome <em>Income</em>}</li> * </ul> * * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card() * @model * @generated */ public interface Tax_Card extends EObject { /** * Returns the value of the '<em><b>Card identifier</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Card identifier</em>' attribute. * @see #setCard_identifier(String) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Card_identifier() * @model id="true" * @generated */ String getCard_identifier(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCard_identifier <em>Card identifier</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Card identifier</em>' attribute. * @see #getCard_identifier() * @generated */ void setCard_identifier(String value); /** * Returns the value of the '<em><b>Tax office</b></em>' attribute. * The literals are from the enumeration {@link TaxationWithRoot.Tax_Office}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Tax office</em>' attribute. * @see TaxationWithRoot.Tax_Office * @see #setTax_office(Tax_Office) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_office() * @model required="true" * @generated */ Tax_Office getTax_office(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getTax_office <em>Tax office</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Tax office</em>' attribute. * @see TaxationWithRoot.Tax_Office * @see #getTax_office() * @generated */ void setTax_office(Tax_Office value); /** * Returns the value of the '<em><b>Percentage of witholding</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Percentage of witholding</em>' attribute. * @see #setPercentage_of_witholding(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Percentage_of_witholding() * @model required="true" * @generated */ double getPercentage_of_witholding(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getPercentage_of_witholding <em>Percentage of witholding</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Percentage of witholding</em>' attribute. * @see #getPercentage_of_witholding() * @generated */ void setPercentage_of_witholding(double value); /** * Returns the value of the '<em><b>Tax payers name surname</b></em>' attribute list. * The list contents are of type {@link java.lang.String}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Tax payers name surname</em>' attribute list. * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_name_surname() * @model ordered="false" * @generated */ EList<String> getTax_payers_name_surname(); /** * Returns the value of the '<em><b>Tax payers partner name surname</b></em>' attribute list. * The list contents are of type {@link java.lang.String}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Tax payers partner name surname</em>' attribute list. * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_partner_name_surname() * @model ordered="false" * @generated */ EList<String> getTax_payers_partner_name_surname(); /** * Returns the value of the '<em><b>Tax payers address</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Tax payers address</em>' reference. * @see #setTax_payers_address(Address) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Tax_payers_address() * @model * @generated */ Address getTax_payers_address(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getTax_payers_address <em>Tax payers address</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Tax payers address</em>' reference. * @see #getTax_payers_address() * @generated */ void setTax_payers_address(Address value); /** * Returns the value of the '<em><b>Jobs Employer SS No</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Jobs Employer SS No</em>' attribute. * @see #setJobs_Employer_SSNo(String) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_Employer_SSNo() * @model unique="false" ordered="false" * @generated */ String getJobs_Employer_SSNo(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_Employer_SSNo <em>Jobs Employer SS No</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Jobs Employer SS No</em>' attribute. * @see #getJobs_Employer_SSNo() * @generated */ void setJobs_Employer_SSNo(String value); /** * Returns the value of the '<em><b>Jobs employers name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Jobs employers name</em>' attribute. * @see #setJobs_employers_name(String) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_employers_name() * @model unique="false" ordered="false" * @generated */ String getJobs_employers_name(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_employers_name <em>Jobs employers name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Jobs employers name</em>' attribute. * @see #getJobs_employers_name() * @generated */ void setJobs_employers_name(String value); /** * Returns the value of the '<em><b>Jobs activity type</b></em>' attribute. * The literals are from the enumeration {@link TaxationWithRoot.Job_Activity}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Jobs activity type</em>' attribute. * @see TaxationWithRoot.Job_Activity * @see #setJobs_activity_type(Job_Activity) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_activity_type() * @model required="true" * @generated */ Job_Activity getJobs_activity_type(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_activity_type <em>Jobs activity type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Jobs activity type</em>' attribute. * @see TaxationWithRoot.Job_Activity * @see #getJobs_activity_type() * @generated */ void setJobs_activity_type(Job_Activity value); /** * Returns the value of the '<em><b>Jobs place of work</b></em>' attribute. * The literals are from the enumeration {@link TaxationWithRoot.Town}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Jobs place of work</em>' attribute. * @see TaxationWithRoot.Town * @see #setJobs_place_of_work(Town) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Jobs_place_of_work() * @model required="true" * @generated */ Town getJobs_place_of_work(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getJobs_place_of_work <em>Jobs place of work</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Jobs place of work</em>' attribute. * @see TaxationWithRoot.Town * @see #getJobs_place_of_work() * @generated */ void setJobs_place_of_work(Town value); /** * Returns the value of the '<em><b>Deduction FD daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction FD daily</em>' attribute. * @see #setDeduction_FD_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FD_daily() * @model default="0.0" unique="false" required="true" ordered="false" * @generated */ double getDeduction_FD_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FD_daily <em>Deduction FD daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction FD daily</em>' attribute. * @see #getDeduction_FD_daily() * @generated */ void setDeduction_FD_daily(double value); /** * Returns the value of the '<em><b>Deduction FD monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction FD monthly</em>' attribute. * @see #setDeduction_FD_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FD_monthly() * @model default="0.0" unique="false" required="true" ordered="false" * @generated */ double getDeduction_FD_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FD_monthly <em>Deduction FD monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction FD monthly</em>' attribute. * @see #getDeduction_FD_monthly() * @generated */ void setDeduction_FD_monthly(double value); /** * Returns the value of the '<em><b>Deduction AC daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction AC daily</em>' attribute. * @see #setDeduction_AC_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_AC_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_daily <em>Deduction AC daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction AC daily</em>' attribute. * @see #getDeduction_AC_daily() * @generated */ void setDeduction_AC_daily(double value); /** * Returns the value of the '<em><b>Deduction AC monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction AC monthly</em>' attribute. * @see #setDeduction_AC_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_monthly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_AC_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_monthly <em>Deduction AC monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction AC monthly</em>' attribute. * @see #getDeduction_AC_monthly() * @generated */ void setDeduction_AC_monthly(double value); /** * Returns the value of the '<em><b>Deduction AC yearly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction AC yearly</em>' attribute. * @see #setDeduction_AC_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_AC_yearly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_AC_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_AC_yearly <em>Deduction AC yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction AC yearly</em>' attribute. * @see #getDeduction_AC_yearly() * @generated */ void setDeduction_AC_yearly(double value); /** * Returns the value of the '<em><b>Deduction CE daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction CE daily</em>' attribute. * @see #setDeduction_CE_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_CE_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_daily <em>Deduction CE daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction CE daily</em>' attribute. * @see #getDeduction_CE_daily() * @generated */ void setDeduction_CE_daily(double value); /** * Returns the value of the '<em><b>Deduction CE monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction CE monthly</em>' attribute. * @see #setDeduction_CE_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_monthly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_CE_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_monthly <em>Deduction CE monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction CE monthly</em>' attribute. * @see #getDeduction_CE_monthly() * @generated */ void setDeduction_CE_monthly(double value); /** * Returns the value of the '<em><b>Deduction CE yearly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction CE yearly</em>' attribute. * @see #setDeduction_CE_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_CE_yearly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_CE_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_CE_yearly <em>Deduction CE yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction CE yearly</em>' attribute. * @see #getDeduction_CE_yearly() * @generated */ void setDeduction_CE_yearly(double value); /** * Returns the value of the '<em><b>Deduction DS daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction DS daily</em>' attribute. * @see #setDeduction_DS_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_DS_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_daily <em>Deduction DS daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction DS daily</em>' attribute. * @see #getDeduction_DS_daily() * @generated */ void setDeduction_DS_daily(double value); /** * Returns the value of the '<em><b>Deduction DS monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction DS monthly</em>' attribute. * @see #setDeduction_DS_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_monthly() * @model default="0.0" required="true" * @generated */ double getDeduction_DS_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_monthly <em>Deduction DS monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction DS monthly</em>' attribute. * @see #getDeduction_DS_monthly() * @generated */ void setDeduction_DS_monthly(double value); /** * Returns the value of the '<em><b>Deduction FO daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction FO daily</em>' attribute. * @see #setDeduction_FO_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_FO_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_daily <em>Deduction FO daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction FO daily</em>' attribute. * @see #getDeduction_FO_daily() * @generated */ void setDeduction_FO_daily(double value); /** * Returns the value of the '<em><b>Deduction FO monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction FO monthly</em>' attribute. * @see #setDeduction_FO_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_monthly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_FO_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_monthly <em>Deduction FO monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction FO monthly</em>' attribute. * @see #getDeduction_FO_monthly() * @generated */ void setDeduction_FO_monthly(double value); /** * Returns the value of the '<em><b>Deduction FO yearly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction FO yearly</em>' attribute. * @see #setDeduction_FO_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_FO_yearly() * @model default="0.0" unique="false" required="true" * @generated */ double getDeduction_FO_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_FO_yearly <em>Deduction FO yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction FO yearly</em>' attribute. * @see #getDeduction_FO_yearly() * @generated */ void setDeduction_FO_yearly(double value); /** * Returns the value of the '<em><b>Credit CIS daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Credit CIS daily</em>' attribute. * @see #setCredit_CIS_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIS_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getCredit_CIS_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIS_daily <em>Credit CIS daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Credit CIS daily</em>' attribute. * @see #getCredit_CIS_daily() * @generated */ void setCredit_CIS_daily(double value); /** * Returns the value of the '<em><b>Credit CIS monthly</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Credit CIS monthly</em>' attribute. * @see #setCredit_CIS_monthly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIS_monthly() * @model default="0.0" unique="false" required="true" * @generated */ double getCredit_CIS_monthly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIS_monthly <em>Credit CIS monthly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Credit CIS monthly</em>' attribute. * @see #getCredit_CIS_monthly() * @generated */ void setCredit_CIS_monthly(double value); /** * Returns the value of the '<em><b>Credit CIM daily</b></em>' attribute. * The default value is <code>"0.0"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Credit CIM daily</em>' attribute. * @see #setCredit_CIM_daily(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIM_daily() * @model default="0.0" unique="false" required="true" * @generated */ double getCredit_CIM_daily(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIM_daily <em>Credit CIM daily</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Credit CIM daily</em>' attribute. * @see #getCredit_CIM_daily() * @generated */ void setCredit_CIM_daily(double value); /** * Returns the value of the '<em><b>Validity</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Validity</em>' attribute. * @see #setValidity(boolean) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Validity() * @model required="true" * @generated */ boolean isValidity(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#isValidity <em>Validity</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Validity</em>' attribute. * @see #isValidity() * @generated */ void setValidity(boolean value); /** * Returns the value of the '<em><b>Income Tax Credit</b></em>' reference list. * The list contents are of type {@link TaxationWithRoot.Income_Tax_Credit}. * It is bidirectional and its opposite is '{@link TaxationWithRoot.Income_Tax_Credit#getTaxation_Frame <em>Taxation Frame</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Income Tax Credit</em>' reference list. * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Income_Tax_Credit() * @see TaxationWithRoot.Income_Tax_Credit#getTaxation_Frame * @model opposite="taxation_Frame" ordered="false" * @generated */ EList<Income_Tax_Credit> getIncome_Tax_Credit(); /** * Returns the value of the '<em><b>Previous</b></em>' reference. * It is bidirectional and its opposite is '{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Previous</em>' reference. * @see #setPrevious(Tax_Card) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Previous() * @see TaxationWithRoot.Tax_Card#getCurrent_tax_card * @model opposite="current_tax_card" * @generated */ Tax_Card getPrevious(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Previous</em>' reference. * @see #getPrevious() * @generated */ void setPrevious(Tax_Card value); /** * Returns the value of the '<em><b>Current tax card</b></em>' reference. * It is bidirectional and its opposite is '{@link TaxationWithRoot.Tax_Card#getPrevious <em>Previous</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Current tax card</em>' reference. * @see #setCurrent_tax_card(Tax_Card) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Current_tax_card() * @see TaxationWithRoot.Tax_Card#getPrevious * @model opposite="previous" * @generated */ Tax_Card getCurrent_tax_card(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCurrent_tax_card <em>Current tax card</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Current tax card</em>' reference. * @see #getCurrent_tax_card() * @generated */ void setCurrent_tax_card(Tax_Card value); /** * Returns the value of the '<em><b>Credit CIM yearly</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Credit CIM yearly</em>' attribute. * @see #setCredit_CIM_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Credit_CIM_yearly() * @model required="true" ordered="false" * @generated */ double getCredit_CIM_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getCredit_CIM_yearly <em>Credit CIM yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Credit CIM yearly</em>' attribute. * @see #getCredit_CIM_yearly() * @generated */ void setCredit_CIM_yearly(double value); /** * Returns the value of the '<em><b>Deduction DS Alimony yearly</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction DS Alimony yearly</em>' attribute. * @see #setDeduction_DS_Alimony_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_Alimony_yearly() * @model required="true" ordered="false" * @generated */ double getDeduction_DS_Alimony_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Alimony_yearly <em>Deduction DS Alimony yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction DS Alimony yearly</em>' attribute. * @see #getDeduction_DS_Alimony_yearly() * @generated */ void setDeduction_DS_Alimony_yearly(double value); /** * Returns the value of the '<em><b>Deduction DS Debt yearly</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Deduction DS Debt yearly</em>' attribute. * @see #setDeduction_DS_Debt_yearly(double) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Deduction_DS_Debt_yearly() * @model required="true" ordered="false" * @generated */ double getDeduction_DS_Debt_yearly(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getDeduction_DS_Debt_yearly <em>Deduction DS Debt yearly</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deduction DS Debt yearly</em>' attribute. * @see #getDeduction_DS_Debt_yearly() * @generated */ void setDeduction_DS_Debt_yearly(double value); /** * Returns the value of the '<em><b>Income</b></em>' container reference. * It is bidirectional and its opposite is '{@link TaxationWithRoot.Income#getTax_card <em>Tax card</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the value of the '<em>Income</em>' container reference. * @see #setIncome(Income) * @see TaxationWithRoot.TaxationWithRootPackage#getTax_Card_Income() * @see TaxationWithRoot.Income#getTax_card * @model opposite="tax_card" required="true" transient="false" * @generated */ Income getIncome(); /** * Sets the value of the '{@link TaxationWithRoot.Tax_Card#getIncome <em>Income</em>}' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Income</em>' container reference. * @see #getIncome() * @generated */ void setIncome(Income value); } // Tax_Card
viatra/VIATRA-Generator
Tests/MODELS2020-CaseStudies/models20.diversity-calculator/src/TaxationWithRoot/Tax_Card.java
Java
epl-1.0
32,297
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ @FeatureFlag(name = ORIENT_ENABLED) package org.sonatype.nexus.repository.maven.internal.orient; import org.sonatype.nexus.common.app.FeatureFlag; import static org.sonatype.nexus.common.app.FeatureFlags.ORIENT_ENABLED;
sonatype/nexus-public
plugins/nexus-repository-maven/src/main/java/org/sonatype/nexus/repository/maven/internal/orient/package-info.java
Java
epl-1.0
1,002
/******************************************************************************* * Copyright (c) 2010, 2012 Tasktop Technologies * Copyright (c) 2010, 2011 SpringSource, a division of VMware * * 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: * Tasktop Technologies - initial API and implementation ******************************************************************************/ package com.tasktop.c2c.server.profile.web.ui.client.place; import java.util.Arrays; import java.util.List; import com.tasktop.c2c.server.common.profile.web.client.navigation.AbstractPlaceTokenizer; import com.tasktop.c2c.server.common.profile.web.client.navigation.PageMapping; import com.tasktop.c2c.server.common.profile.web.client.place.Breadcrumb; import com.tasktop.c2c.server.common.profile.web.client.place.BreadcrumbPlace; import com.tasktop.c2c.server.common.profile.web.client.place.HeadingPlace; import com.tasktop.c2c.server.common.profile.web.client.place.LoggedInPlace; import com.tasktop.c2c.server.common.profile.web.client.place.WindowTitlePlace; import com.tasktop.c2c.server.common.profile.web.client.util.WindowTitleBuilder; import com.tasktop.c2c.server.common.profile.web.shared.actions.GetSshPublicKeysAction; import com.tasktop.c2c.server.common.profile.web.shared.actions.GetSshPublicKeysResult; import com.tasktop.c2c.server.profile.domain.project.Profile; import com.tasktop.c2c.server.profile.domain.project.SshPublicKey; import com.tasktop.c2c.server.profile.web.ui.client.gin.AppGinjector; public class UserAccountPlace extends LoggedInPlace implements HeadingPlace, WindowTitlePlace, BreadcrumbPlace { public static PageMapping Account = new PageMapping(new UserAccountPlace.Tokenizer(), "account"); @Override public String getHeading() { return "Account Settings"; } private static class Tokenizer extends AbstractPlaceTokenizer<UserAccountPlace> { @Override public UserAccountPlace getPlace(String token) { return UserAccountPlace.createPlace(); } } private Profile profile; private List<SshPublicKey> sshPublicKeys; public static UserAccountPlace createPlace() { return new UserAccountPlace(); } private UserAccountPlace() { } public Profile getProfile() { return profile; } public List<SshPublicKey> getSshPublicKeys() { return sshPublicKeys; } @Override public String getPrefix() { return Account.getUrl(); } @Override protected void addActions() { super.addActions(); addAction(new GetSshPublicKeysAction()); } @Override protected void handleBatchResults() { super.handleBatchResults(); profile = AppGinjector.get.instance().getAppState().getCredentials().getProfile(); sshPublicKeys = getResult(GetSshPublicKeysResult.class).get(); onPlaceDataFetched(); } @Override public String getWindowTitle() { return WindowTitleBuilder.createWindowTitle("Account Settings"); } @Override public List<Breadcrumb> getBreadcrumbs() { return Arrays.asList(new Breadcrumb("", "Projects"), new Breadcrumb(getHref(), "Account")); } }
Tasktop/code2cloud.server
com.tasktop.c2c.server/com.tasktop.c2c.server.profile.web.ui/src/main/java/com/tasktop/c2c/server/profile/web/ui/client/place/UserAccountPlace.java
Java
epl-1.0
3,244
package com.openMap1.mapper.converters; import java.util.Iterator; import org.eclipse.emf.common.util.EList; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.openMap1.mapper.ElementDef; import com.openMap1.mapper.MappedStructure; import com.openMap1.mapper.core.MapperException; import com.openMap1.mapper.structures.MapperWrapper; import com.openMap1.mapper.util.XMLUtil; import com.openMap1.mapper.util.XSLOutputFile; import com.openMap1.mapper.writer.TemplateFilter; public class FACEWrapper extends AbstractMapperWrapper implements MapperWrapper{ public static String FACE_PREFIX = "face"; public static String FACE_URI = "http://schemas.facecode.com/webservices/2010/01/"; //---------------------------------------------------------------------------------------- // Constructor and initialisation from the Ecore model //---------------------------------------------------------------------------------------- public FACEWrapper(MappedStructure ms, Object spare) throws MapperException { super(ms,spare); } /** * @return the file extension of the outer document, with initial '*.' */ public String fileExtension() {return ("*.xml");} /** * @return the type of document transformed to and from; * see static constants in class AbstractMapperWrapper. */ public int transformType() {return AbstractMapperWrapper.XML_TYPE;} //---------------------------------------------------------------------------------------- // In-wrapper transform //---------------------------------------------------------------------------------------- @Override public Document transformIn(Object incoming) throws MapperException { if (!(incoming instanceof Element)) throw new MapperException("Document root is not an Element"); Element mappingRoot = (Element)incoming; String mappingRootPath = "/GetIndicativeBudget"; inResultDoc = XMLUtil.makeOutDoc(); Element inRoot = scanDocument(mappingRoot, mappingRootPath, AbstractMapperWrapper.IN_TRANSFORM); inResultDoc.appendChild(inRoot); return inResultDoc; } /** * default behaviour is a shallow copy - copying the element name, attributes, * and text content only if the element has no child elements. * to be overridden for specific paths in implementing classes */ protected Element inTransformNode(Element el, String path) throws MapperException { // copy the element with namespaces, prefixed tag name, attributes but no text or child Elements Element copy = (Element)inResultDoc.importNode(el, false); // convert <FaceCompletedItem> elements to specific types of item if (XMLUtil.getLocalName(el).equals("FaceCompletedItem")) { String questionCode = getPathValue(el,"QuestionId"); String newName = "FaceCompletedItem_" + questionCode; copy = renameElement(el, newName, true); } // if the source element has no child elements but has text, copy the text String text = textOnly(el); if (!text.equals("")) copy.appendChild(inResultDoc.createTextNode(text)); return copy; } //---------------------------------------------------------------------------------------- // Out-wrapper transform //---------------------------------------------------------------------------------------- @Override public Object transformOut(Element outgoing) throws MapperException { String mappingRootPath = "/Envelope"; outResultDoc = XMLUtil.makeOutDoc(); Element outRoot = scanDocument(outgoing, mappingRootPath, AbstractMapperWrapper.OUT_TRANSFORM); outResultDoc.appendChild(outRoot); return outResultDoc; } /** * default behaviour is a shallow copy - copying the element name, attributes, * and text content only if the element has no child elements. * to be overridden for specific paths in implementing classes */ protected Element outTransformNode(Element el, String path) throws MapperException { // copy the element with namespaces, prefixed tag name, attributes but no text or child Elements Element copy = (Element)outResultDoc.importNode(el, false); // convert specific types of <FaceCompletedItem_XX> back to plain <FACECompletedItem> if (XMLUtil.getLocalName(el).startsWith("FaceCompletedItem")) { copy = renameElement(el,"FaceCompletedItem",false); } // if the source element has no child elements but has text, copy the text String text = textOnly(el); if (!text.equals("")) copy.appendChild(outResultDoc.createTextNode(text)); return copy; } /** * copy an element and all its attributes to the new document, renaming it * and putting it in no namespace. * @param el * @param newName * @param isIn true for the in-transform, false for the out-transform * @return * @throws MapperException */ protected Element renameElement(Element el, String newName, boolean isIn) throws MapperException { Element newEl = null; if (isIn) newEl = inResultDoc.createElementNS(FACE_URI, newName); else if (!isIn) newEl = outResultDoc.createElementNS(FACE_URI, newName); // set all attributes of the constrained element, including namespace attributes for (int a = 0; a < el.getAttributes().getLength();a++) { Attr at = (Attr)el.getAttributes().item(a); newEl.setAttribute(at.getName(), at.getValue()); } return newEl; } //-------------------------------------------------------------------------------------------------------------- // XSLT Wrapper Transforms //-------------------------------------------------------------------------------------------------------------- /** * @param xout XSLT output being made * @param templateFilter a filter on the templates, implemented by XSLGeneratorImpl * append the templates and variables to be included in the XSL * to do the full transformation, to apply the wrapper transform in the 'in' direction. * Templates must have mode = "inWrapper" */ public void addWrapperInTemplates(XSLOutputFile xout, TemplateFilter templateFilter) throws MapperException { // see class AbstractMapperWrapper - adds a plain identity template super.addWrapperInTemplates(xout, templateFilter); // add the FACE namespace xout.topOut().setAttribute("xmlns:" + FACE_PREFIX, FACE_URI); for (Iterator<ElementDef> it = findFACEItemsElementDefs(ms()).iterator();it.hasNext();) { ElementDef FACEItem = it.next(); String tagName = FACEItem.getName(); if (tagName.startsWith("FaceCompletedItem_")) { String questionId = tagName.substring("FaceCompletedItem_".length()); addInTemplate(xout,tagName,questionId); } } } /** * @param xout XSLT output being made * @param templateFilter a filter on the templates to be included, implemented by XSLGeneratorImpl * append the templates and variables to be included in the XSL * to do the full transformation, to apply the wrapper transform in the 'out' direction. * Templates must have mode = "outWrapper" * @throws MapperException */ public void addWrapperOutTemplates(XSLOutputFile xout, TemplateFilter templateFilter) throws MapperException { // see class AbstractMapperWrapper - adds a plain identity template super.addWrapperOutTemplates(xout, templateFilter); // add the FACE namespace xout.topOut().setAttribute("xmlns:" + FACE_PREFIX, FACE_URI); for (Iterator<ElementDef> it = findFACEItemsElementDefs(ms()).iterator();it.hasNext();) { ElementDef FACEItem = it.next(); String tagName = FACEItem.getName(); if (tagName.startsWith("FaceCompletedItem_")) { String questionId = tagName.substring("FaceCompletedItem_".length()); addOutTemplate(xout,tagName,questionId); } } } /** * add an in-wrapper template of the form <xsl:template match="face:FaceCompletedItem[face:QuestionId='F14_14_46_11_15_33T61_38']" mode="inWrapper"> <face:FaceCompletedItem_F14_14_46_11_15_33T61_38> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="inWrapper"/> </face:FaceCompletedItem_F14_14_46_11_15_33T61_38> </xsl:template> * @param xout * @param tagName * @param questionId */ private void addInTemplate(XSLOutputFile xout,String tagName,String questionId) throws MapperException { Element tempEl = xout.XSLElement("template"); tempEl.setAttribute("match", FACE_PREFIX + ":FaceCompletedItem[" + FACE_PREFIX + ":QuestionId='" + questionId + "']"); tempEl.setAttribute("mode", "inWrapper"); Element FACEEl = xout.NSElement(FACE_PREFIX, tagName, FACE_URI); tempEl.appendChild(FACEEl); addApplyChildren(xout,FACEEl,"inWrapper"); xout.topOut().appendChild(tempEl); } /** * add an out-wrapper template of the form <xsl:template match="face:FaceCompletedItem_F14_14_46_11_15_33T61_38" mode="outWrapper"> <face:FaceCompletedItem> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="outWrapper"/> </face:FaceCompletedItem> </xsl:template> * @param xout * @param tagName * @param questionId */ private void addOutTemplate(XSLOutputFile xout,String tagName,String questionId) throws MapperException { Element tempEl = xout.XSLElement("template"); tempEl.setAttribute("match", FACE_PREFIX + ":" + tagName); tempEl.setAttribute("mode", "outWrapper"); Element FACEEl = xout.NSElement(FACE_PREFIX, "FaceCompletedItem", FACE_URI); tempEl.appendChild(FACEEl); addApplyChildren(xout,FACEEl,"outWrapper"); xout.topOut().appendChild(tempEl); } /** * add two child nodes to a template to carry on copying down the tree * @param xout * @param FACEEl * @param mode * @throws MapperException */ private void addApplyChildren(XSLOutputFile xout,Element FACEEl, String mode) throws MapperException { Element copyOfEl = xout.XSLElement("copy-of"); copyOfEl.setAttribute("select", "@*"); FACEEl.appendChild(copyOfEl); Element applyEl = xout.XSLElement("apply-templates"); applyEl.setAttribute("mode", mode); FACEEl.appendChild(applyEl); } /** * * @param mappedStructure * @return a lit of nodes in the mapping set which are children of the 'Items' node * @throws MapperException */ public static EList<ElementDef> findFACEItemsElementDefs(MappedStructure mappedStructure) throws MapperException { ElementDef msRoot = mappedStructure.getRootElement(); if (msRoot == null) throw new MapperException("No root element in mapping set"); if (!msRoot.getName().equals("GetIndicativeBudget")) throw new MapperException("Root Element of mapping set must be called 'GetIndicativeBudget'"); // there must be a chain of child ElementDefs with the names below; throw an exception if not ElementDef payload = findChildElementDef(msRoot,"payload"); ElementDef items = findChildElementDef(payload,"Items"); return items.getChildElements(); } /** * * @param parent * @param childName * @return the child ElementDef with given name * @throws MapperException if it does not exist */ private static ElementDef findChildElementDef(ElementDef parent, String childName) throws MapperException { ElementDef child = parent.getNamedChildElement(childName); if (child == null) throw new MapperException("Mapping set node '" + parent.getName() + "' has no child '" + childName + "'"); return child; } }
openmapsoftware/mappingtools
openmap-mapper-lib/src/main/java/com/openMap1/mapper/converters/FACEWrapper.java
Java
epl-1.0
11,744
package org.matmaul.freeboxos.ftp; import org.matmaul.freeboxos.internal.Response; public class FtpResponse { public static class FtpConfigResponse extends Response<FtpConfig> {} }
MatMaul/freeboxos-java
src/org/matmaul/freeboxos/ftp/FtpResponse.java
Java
epl-1.0
184
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ /* ----------------- * Specifics.java * ----------------- * (C) Copyright 2015-2015, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): * * $Id$ * * Changes * ------- */ package org.jgrapht.graph.specifics; import java.io.Serializable; import java.util.Set; /** * . * * @author Barak Naveh */ public abstract class Specifics<V, E> implements Serializable { private static final long serialVersionUID = 785196247314761183L; public abstract void addVertex(V vertex); public abstract Set<V> getVertexSet(); /** * . * * @param sourceVertex * @param targetVertex * * @return */ public abstract Set<E> getAllEdges(V sourceVertex, V targetVertex); /** * . * * @param sourceVertex * @param targetVertex * * @return */ public abstract E getEdge(V sourceVertex, V targetVertex); /** * Adds the specified edge to the edge containers of its source and * target vertices. * * @param e */ public abstract void addEdgeToTouchingVertices(E e); /** * . * * @param vertex * * @return */ public abstract int degreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set<E> edgesOf(V vertex); /** * . * * @param vertex * * @return */ public abstract int inDegreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set<E> incomingEdgesOf(V vertex); /** * . * * @param vertex * * @return */ public abstract int outDegreeOf(V vertex); /** * . * * @param vertex * * @return */ public abstract Set<E> outgoingEdgesOf(V vertex); /** * Removes the specified edge from the edge containers of its source and * target vertices. * * @param e */ public abstract void removeEdgeFromTouchingVertices(E e); }
arcanefoam/jgrapht
jgrapht-core/src/main/java/org/jgrapht/graph/specifics/Specifics.java
Java
epl-1.0
2,800
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileLogger extends MyLoggerImpl { private String fileName; public FileLogger(String fileName) { super(); this.fileName = fileName; } @Override public void log(int level, String message) throws ErrorIntegerLevelException { super.log(level, message); try { File file = new File(fileName); FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); if(file.length() > 0) { bw.write("\n"+ getLogMessage()); } else { bw.write(getLogMessage()); } bw.close(); } catch (IOException e) { System.err.println("This file doesn`t exist!"); } } public static void main(String[] argv) { MyLogger consoleLogger = new FileLogger("test.txt"); try { consoleLogger.log(1, "Hello world!"); consoleLogger.log(2, "The application`s digital signature has error!"); consoleLogger.log(3, "Checking file system on C!"); consoleLogger.log(4, "Error level!"); } catch (ErrorIntegerLevelException e) { System.err.println("Error level! It must be 1, 2 or 3"); } } }
irin4eto/HackBulgaria_JavaScript
Candidacy/SimpleLogger/src/FileLogger.java
Java
gpl-2.0
1,200
/** * 项目名: java-code-tutorials-tools * 包名: net.fantesy84.common.util * 文件名: IPUtils.java * Copy Right © 2015 Andronicus Ge * 时间: 2015年11月9日 */ package net.fantesy84.common.util; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Andronicus * @since 2015年11月9日 */ public abstract class IPUtils { private static final Logger logger = LoggerFactory.getLogger(IPUtils.class); private static String LOCALHOST_NAME; static { try { LOCALHOST_NAME = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { logger.error(e.getMessage(), new IllegalStateException(e)); } } /** * 获取本地网络适配器IP地址 * <P>有多个网卡时会有多个IP,一一对应 * @return 网卡地址列表 */ public static String getLocalIPv4Address(){ String ip = null; try { InetAddress[] addresses = InetAddress.getAllByName(LOCALHOST_NAME); if (!ArrayUtils.isEmpty(addresses)) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < addresses.length; i++) { if (addresses[i].getHostAddress().matches(RegularExpressions.IP_V4_REGEX)){ builder.append(",").append(addresses[i].getHostAddress()); } } ip = builder.toString().replaceFirst(",", ""); } } catch (UnknownHostException e) { logger.error(e.getMessage(), new IllegalStateException(e)); } return ip; } /** * 获取远程访问者IP地址 * <P> 关于代理请求,通过代理过滤进行查询.有多层代理时,第一个IP地址即为真实地址. * @param request 网络请求 * @return 远程访问者IP地址 */ public static String getRemoteIP(HttpServletRequest request, String regex){ String ip = null; ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) { ip = getLocalIPv4Address(); } if (ip != null && ip.length() > 15) { if (!StringUtils.isBlank(regex)) { StringBuilder builder = new StringBuilder(); String[] addrs = ip.split(","); for (String addr : addrs) { if (addr.matches(regex)) { builder.append(",").append(addr); } } ip = builder.toString().replaceFirst(",", ""); } if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } if (ip == null) { logger.error("未获取到任何IP地址!请检查网络配置!", new IllegalStateException()); } return ip; } }
fantesy84/java-code-tutorials
java-code-tutorials-tools/src/main/java/net/fantesy84/common/util/IPUtils.java
Java
gpl-2.0
2,924
/* UnknownTypeException.java -- Thrown by an unknown type. Copyright (C) 2012 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.lang.model.type; /** * Thrown when an unknown type is encountered, * usually by a {@link TypeVisitor}. * * @author Andrew John Hughes (gnu_andrew@member.fsf.org) * @since 1.6 * @see TypeVisitor#visitUnknown(TypeMirror,P) */ public class UnknownTypeException extends RuntimeException { private static final long serialVersionUID = 269L; /** * The unknown type. */ private TypeMirror type; /** * The additional parameter. */ private Object param; /** * Constructs a new {@code UnknownTypeException} * for the specified type. An additional * object may also be passed to give further context as * to where the exception occurred, such as the additional parameter * used by visitor classes. * * @param type the unknown type or {@code null}. * @param param the additional parameter or {@code null}. */ public UnknownTypeException(TypeMirror type, Object param) { this.type = type; this.param = param; } /** * Returns the additional parameter or {@code null} if * unavailable. * * @return the additional parameter. */ public Object getArgument() { return param; } /** * Returns the unknown type or {@code null} * if unavailable. The type may be {@code null} if * the value is not {@link java.io.Serializable} but the * exception has been serialized and read back in. * * @return the unknown type. */ public TypeMirror getUnknownType() { return type; } }
penberg/classpath
javax/lang/model/type/UnknownTypeException.java
Java
gpl-2.0
3,277
package com.citypark.api.task; import com.citypark.api.parser.CityParkStartPaymentParser; import android.content.Context; import android.os.AsyncTask; import android.text.format.Time; public class StopPaymentTask extends AsyncTask<Void, Void, Boolean> { private Context context; private String sessionId; private String paymentProviderName; private double latitude; private double longitude; private String operationStatus; public StopPaymentTask(Context context, String sessionId, String paymentProviderName, double latitude, double longitude, String operationStatus) { super(); this.context = context; this.sessionId = sessionId; this.paymentProviderName = paymentProviderName; this.latitude = latitude; this.longitude = longitude; this.operationStatus = operationStatus; } @Override protected Boolean doInBackground(Void... params) { //update citypark through API on success or failure CityParkStartPaymentParser parser = new CityParkStartPaymentParser(context, sessionId, paymentProviderName, latitude, longitude, operationStatus); parser.parse(); return true; } }
kruzel/citypark-android
src/com/citypark/api/task/StopPaymentTask.java
Java
gpl-2.0
1,144
package newpackage; public class DaneWejsciowe { float wartosc; String argument; public DaneWejsciowe( String argument,float wartosc) { this.wartosc = wartosc; this.argument = argument; } }
Zajcew/SystemEkspertowy
System Ekspertowy/src/newpackage/DaneWejsciowe.java
Java
gpl-2.0
213
/** * AshtavargaChartData.java * Created On 2006, Mar 31, 2006 5:12:23 PM * @author E. Rajasekar */ package app.astrosoft.beans; import java.util.EnumMap; import app.astrosoft.consts.AshtavargaName; import app.astrosoft.consts.AstrosoftTableColumn; import app.astrosoft.consts.Rasi; import app.astrosoft.core.Ashtavarga; import app.astrosoft.export.Exportable; import app.astrosoft.export.Exporter; import app.astrosoft.ui.table.ColumnMetaData; import app.astrosoft.ui.table.DefaultColumnMetaData; import app.astrosoft.ui.table.Table; import app.astrosoft.ui.table.TableData; import app.astrosoft.ui.table.TableRowData; public class AshtaVargaChartData extends AbstractChartData implements Exportable{ private EnumMap<Rasi, Integer> varga; public AshtaVargaChartData(AshtavargaName name, EnumMap<Rasi, Integer> varga) { super(); this.varga = varga; chartName = name.toString(); int count = Ashtavarga.getCount(name); if ( count != -1){ chartName = chartName + " ( " +String.valueOf(count) + " ) "; } } public Table getChartHouseTable(final Rasi rasi) { Table ashtavargaTable = new Table(){ public TableData<TableRowData> getTableData() { return new TableData<TableRowData>(){ public TableRowData getRow(final int index){ return new TableRowData(){ public Object getColumnData(AstrosoftTableColumn col) { return (index == 1) ? varga.get(rasi) : null; } }; } public int getRowCount() { return 2; } }; } public ColumnMetaData getColumnMetaData() { return colMetaData; } }; return ashtavargaTable; } @Override public DefaultColumnMetaData getHouseTableColMetaData() { return new DefaultColumnMetaData(AstrosoftTableColumn.C1){ @Override public Class getColumnClass(AstrosoftTableColumn col) { return Integer.class; } }; } public EnumMap<Rasi, Integer> getVarga() { return varga; } public void doExport(Exporter e) { e.export(this); } }
erajasekar/Astrosoft
src/app/astrosoft/beans/AshtaVargaChartData.java
Java
gpl-2.0
2,069
package mcmod.nxs.animalwarriors.lib; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemArmor; public class ArmorHelper extends ItemArmor { public ArmorHelper(ArmorMaterial material, int type, int layer) { super(material, type, layer); } public ItemArmor setNameAndTab(String name, CreativeTabs tab) { this.setTextureName(ResourcePathHelper.getResourcesPath() + name); this.setUnlocalizedName(name); this.setCreativeTab(tab); return this; } }
AlphaSwittle-Team/AnimalWarriors
src/main/java/mcmod/nxs/animalwarriors/lib/ArmorHelper.java
Java
gpl-2.0
489
package org.scada_lts.dao.model.multichangehistory; import java.util.Objects; /** * @author grzegorz.bylica@abilit.eu on 16.10.2019 */ public class MultiChangeHistoryValues { private int id; private int userId; private String userName; private String viewAndCmpIdentyfication; private String interpretedState; private long timeStamp; private int valueId; private String value; private int dataPointId; private String xidPoint; public MultiChangeHistoryValues() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getViewAndCmpIdentyfication() { return viewAndCmpIdentyfication; } public void setViewAndCmpIdentyfication(String viewAndCmpIdentyfication) { this.viewAndCmpIdentyfication = viewAndCmpIdentyfication; } public String getInterpretedState() { return interpretedState; } public void setInterpretedState(String interpretedState) { this.interpretedState = interpretedState; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public int getValueId() { return valueId; } public void setValueId(int valueId) { this.valueId = valueId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getDataPointId() { return dataPointId; } public void setDataPointId(int dataPointId) { this.dataPointId = dataPointId; } public String getXidPoint() { return xidPoint; } public void setXidPoint(String xidPoint) { this.xidPoint = xidPoint; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultiChangeHistoryValues that = (MultiChangeHistoryValues) o; return id == that.id && userId == that.userId && valueId == that.valueId && dataPointId == that.dataPointId && Objects.equals(userName, that.userName) && Objects.equals(viewAndCmpIdentyfication, that.viewAndCmpIdentyfication) && Objects.equals(interpretedState, that.interpretedState) && Objects.equals(timeStamp, that.timeStamp) && Objects.equals(value, that.value) && Objects.equals(xidPoint, that.xidPoint); } @Override public int hashCode() { return Objects.hash(id, userId, userName, viewAndCmpIdentyfication, interpretedState, timeStamp, valueId, value, dataPointId, xidPoint); } @Override public String toString() { return "MultiChangeHistoryValues{" + "id=" + id + ", userId=" + userId + ", userName='" + userName + '\'' + ", viewAndCmpIdentyfication='" + viewAndCmpIdentyfication + '\'' + ", interpretedState='" + interpretedState + '\'' + ", ts=" + timeStamp + ", valueId=" + valueId + ", value='" + value + '\'' + ", dataPointId=" + dataPointId + ", xidPoint='" + xidPoint + '\'' + '}'; } }
SCADA-LTS/Scada-LTS
src/org/scada_lts/dao/model/multichangehistory/MultiChangeHistoryValues.java
Java
gpl-2.0
3,725
/* * 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.fontbox.cff.charset; /** * This is specialized CFFCharset. It's used if the CharsetId of a font is set to 1. * * @author Villu Ruusmann * @version $Revision$ */ public class CFFExpertCharset extends CFFCharset { private CFFExpertCharset() { } /** * Returns an instance of the CFFExpertCharset class. * * @return an instance of CFFExpertCharset */ public static CFFExpertCharset getInstance() { return CFFExpertCharset.INSTANCE; } private static final CFFExpertCharset INSTANCE = new CFFExpertCharset(); static { INSTANCE.register(1, "space"); INSTANCE.register(13, "comma"); INSTANCE.register(14, "hyphen"); INSTANCE.register(15, "period"); INSTANCE.register(27, "colon"); INSTANCE.register(28, "semicolon"); INSTANCE.register(99, "fraction"); INSTANCE.register(109, "fi"); INSTANCE.register(110, "fl"); INSTANCE.register(150, "onesuperior"); INSTANCE.register(155, "onehalf"); INSTANCE.register(158, "onequarter"); INSTANCE.register(163, "threequarters"); INSTANCE.register(164, "twosuperior"); INSTANCE.register(169, "threesuperior"); INSTANCE.register(229, "exclamsmall"); INSTANCE.register(230, "Hungarumlautsmall"); INSTANCE.register(231, "dollaroldstyle"); INSTANCE.register(232, "dollarsuperior"); INSTANCE.register(233, "ampersandsmall"); INSTANCE.register(234, "Acutesmall"); INSTANCE.register(235, "parenleftsuperior"); INSTANCE.register(236, "parenrightsuperior"); INSTANCE.register(237, "twodotenleader"); INSTANCE.register(238, "onedotenleader"); INSTANCE.register(239, "zerooldstyle"); INSTANCE.register(240, "oneoldstyle"); INSTANCE.register(241, "twooldstyle"); INSTANCE.register(242, "threeoldstyle"); INSTANCE.register(243, "fouroldstyle"); INSTANCE.register(244, "fiveoldstyle"); INSTANCE.register(245, "sixoldstyle"); INSTANCE.register(246, "sevenoldstyle"); INSTANCE.register(247, "eightoldstyle"); INSTANCE.register(248, "nineoldstyle"); INSTANCE.register(249, "commasuperior"); INSTANCE.register(250, "threequartersemdash"); INSTANCE.register(251, "periodsuperior"); INSTANCE.register(252, "questionsmall"); INSTANCE.register(253, "asuperior"); INSTANCE.register(254, "bsuperior"); INSTANCE.register(255, "centsuperior"); INSTANCE.register(256, "dsuperior"); INSTANCE.register(257, "esuperior"); INSTANCE.register(258, "isuperior"); INSTANCE.register(259, "lsuperior"); INSTANCE.register(260, "msuperior"); INSTANCE.register(261, "nsuperior"); INSTANCE.register(262, "osuperior"); INSTANCE.register(263, "rsuperior"); INSTANCE.register(264, "ssuperior"); INSTANCE.register(265, "tsuperior"); INSTANCE.register(266, "ff"); INSTANCE.register(267, "ffi"); INSTANCE.register(268, "ffl"); INSTANCE.register(269, "parenleftinferior"); INSTANCE.register(270, "parenrightinferior"); INSTANCE.register(271, "Circumflexsmall"); INSTANCE.register(272, "hyphensuperior"); INSTANCE.register(273, "Gravesmall"); INSTANCE.register(274, "Asmall"); INSTANCE.register(275, "Bsmall"); INSTANCE.register(276, "Csmall"); INSTANCE.register(277, "Dsmall"); INSTANCE.register(278, "Esmall"); INSTANCE.register(279, "Fsmall"); INSTANCE.register(280, "Gsmall"); INSTANCE.register(281, "Hsmall"); INSTANCE.register(282, "Ismall"); INSTANCE.register(283, "Jsmall"); INSTANCE.register(284, "Ksmall"); INSTANCE.register(285, "Lsmall"); INSTANCE.register(286, "Msmall"); INSTANCE.register(287, "Nsmall"); INSTANCE.register(288, "Osmall"); INSTANCE.register(289, "Psmall"); INSTANCE.register(290, "Qsmall"); INSTANCE.register(291, "Rsmall"); INSTANCE.register(292, "Ssmall"); INSTANCE.register(293, "Tsmall"); INSTANCE.register(294, "Usmall"); INSTANCE.register(295, "Vsmall"); INSTANCE.register(296, "Wsmall"); INSTANCE.register(297, "Xsmall"); INSTANCE.register(298, "Ysmall"); INSTANCE.register(299, "Zsmall"); INSTANCE.register(300, "colonmonetary"); INSTANCE.register(301, "onefitted"); INSTANCE.register(302, "rupiah"); INSTANCE.register(303, "Tildesmall"); INSTANCE.register(304, "exclamdownsmall"); INSTANCE.register(305, "centoldstyle"); INSTANCE.register(306, "Lslashsmall"); INSTANCE.register(307, "Scaronsmall"); INSTANCE.register(308, "Zcaronsmall"); INSTANCE.register(309, "Dieresissmall"); INSTANCE.register(310, "Brevesmall"); INSTANCE.register(311, "Caronsmall"); INSTANCE.register(312, "Dotaccentsmall"); INSTANCE.register(313, "Macronsmall"); INSTANCE.register(314, "figuredash"); INSTANCE.register(315, "hypheninferior"); INSTANCE.register(316, "Ogoneksmall"); INSTANCE.register(317, "Ringsmall"); INSTANCE.register(318, "Cedillasmall"); INSTANCE.register(319, "questiondownsmall"); INSTANCE.register(320, "oneeighth"); INSTANCE.register(321, "threeeighths"); INSTANCE.register(322, "fiveeighths"); INSTANCE.register(323, "seveneighths"); INSTANCE.register(324, "onethird"); INSTANCE.register(325, "twothirds"); INSTANCE.register(326, "zerosuperior"); INSTANCE.register(327, "foursuperior"); INSTANCE.register(328, "fivesuperior"); INSTANCE.register(329, "sixsuperior"); INSTANCE.register(330, "sevensuperior"); INSTANCE.register(331, "eightsuperior"); INSTANCE.register(332, "ninesuperior"); INSTANCE.register(333, "zeroinferior"); INSTANCE.register(334, "oneinferior"); INSTANCE.register(335, "twoinferior"); INSTANCE.register(336, "threeinferior"); INSTANCE.register(337, "fourinferior"); INSTANCE.register(338, "fiveinferior"); INSTANCE.register(339, "sixinferior"); INSTANCE.register(340, "seveninferior"); INSTANCE.register(341, "eightinferior"); INSTANCE.register(342, "nineinferior"); INSTANCE.register(343, "centinferior"); INSTANCE.register(344, "dollarinferior"); INSTANCE.register(345, "periodinferior"); INSTANCE.register(346, "commainferior"); INSTANCE.register(347, "Agravesmall"); INSTANCE.register(348, "Aacutesmall"); INSTANCE.register(349, "Acircumflexsmall"); INSTANCE.register(350, "Atildesmall"); INSTANCE.register(351, "Adieresissmall"); INSTANCE.register(352, "Aringsmall"); INSTANCE.register(353, "AEsmall"); INSTANCE.register(354, "Ccedillasmall"); INSTANCE.register(355, "Egravesmall"); INSTANCE.register(356, "Eacutesmall"); INSTANCE.register(357, "Ecircumflexsmall"); INSTANCE.register(358, "Edieresissmall"); INSTANCE.register(359, "Igravesmall"); INSTANCE.register(360, "Iacutesmall"); INSTANCE.register(361, "Icircumflexsmall"); INSTANCE.register(362, "Idieresissmall"); INSTANCE.register(363, "Ethsmall"); INSTANCE.register(364, "Ntildesmall"); INSTANCE.register(365, "Ogravesmall"); INSTANCE.register(366, "Oacutesmall"); INSTANCE.register(367, "Ocircumflexsmall"); INSTANCE.register(368, "Otildesmall"); INSTANCE.register(369, "Odieresissmall"); INSTANCE.register(370, "OEsmall"); INSTANCE.register(371, "Oslashsmall"); INSTANCE.register(372, "Ugravesmall"); INSTANCE.register(373, "Uacutesmall"); INSTANCE.register(374, "Ucircumflexsmall"); INSTANCE.register(375, "Udieresissmall"); INSTANCE.register(376, "Yacutesmall"); INSTANCE.register(377, "Thornsmall"); INSTANCE.register(378, "Ydieresissmall"); } }
sencko/NALB
nalb2013/src/org/apache/fontbox/cff/charset/CFFExpertCharset.java
Java
gpl-2.0
8,359
package com.starfarers.dao; import java.util.List; public interface BaseDao<T> { public void create(T entity); public T save(T entity); public void save(List<T> entities); public void remove(T entity); public T find(Integer id); public List<T> findAll(); public <P> T findBy(String attribute, P parameter); }
Zweanslord/starfarers
src/main/java/com/starfarers/dao/BaseDao.java
Java
gpl-2.0
325
package agaroyun.view; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import agaroyun.Model.GameObject; import agaroyun.Model.Player; /** * draws GameObjects to panel * @author varyok * @version 1.0 */ public class GamePanel extends JPanel { private ArrayList<GameObject> gameObjects; /** * Keeps gameObjects ArrayList * @param gameObjects */ public GamePanel(ArrayList<GameObject> gameObjects) { this.gameObjects=gameObjects; } /** * draws GameObjects to panel */ @Override protected synchronized void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d=(Graphics2D)g; //Graphics 2d daha fazla özellik sağlayabilir. daha kolaydır for (GameObject gameObject : gameObjects) { gameObject.draw(g2d); } } }
by-waryoq/LYKJava2017Basics
src/agaroyun/view/GamePanel.java
Java
gpl-2.0
916
package net.sf.memoranda.util; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import net.sf.memoranda.ui.AppFrame; /** * <p> * Title: * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2002 * </p> * <p> * Company: * </p> * * @author unascribed * @version 1.0 */ /* $Id: Context.java,v 1.3 2004/01/30 12:17:42 alexeya Exp $ */ public class Context { public static LoadableProperties context = new LoadableProperties(); static { CurrentStorage.get().restoreContext(); AppFrame.addExitListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CurrentStorage.get().storeContext(); } }); } public static Object get(Object key) { return context.get(key); } public static void put(Object key, Object value) { context.put(key, value); } }
cst316/spring16project-Fortran
src/net/sf/memoranda/util/Context.java
Java
gpl-2.0
845
package org.emulinker.kaillera.controller.v086.action; import java.util.*; import org.apache.commons.logging.*; import org.emulinker.kaillera.access.AccessManager; import org.emulinker.kaillera.controller.messaging.MessageFormatException; import org.emulinker.kaillera.controller.v086.V086Controller; import org.emulinker.kaillera.controller.v086.protocol.*; import org.emulinker.kaillera.model.exception.ActionException; import org.emulinker.kaillera.model.impl.*; import org.emulinker.kaillera.model.*; import org.emulinker.util.EmuLang; import org.emulinker.util.WildcardStringPattern; public class GameOwnerCommandAction implements V086Action { public static final String COMMAND_HELP = "/help"; //$NON-NLS-1$ public static final String COMMAND_DETECTAUTOFIRE = "/detectautofire"; //$NON-NLS-1$ private static Log log = LogFactory.getLog(GameOwnerCommandAction.class); private static final String desc = "GameOwnerCommandAction"; //$NON-NLS-1$ private static GameOwnerCommandAction singleton = new GameOwnerCommandAction(); public static GameOwnerCommandAction getInstance() { return singleton; } private int actionCount = 0; private GameOwnerCommandAction() { } public int getActionPerformedCount() { return actionCount; } public String toString() { return desc; } public void performAction(V086Message message, V086Controller.V086ClientHandler clientHandler) throws FatalActionException { GameChat chatMessage = (GameChat) message; String chat = chatMessage.getMessage(); KailleraUserImpl user = (KailleraUserImpl) clientHandler.getUser(); KailleraGameImpl game = user.getGame(); if(game == null) { throw new FatalActionException("GameOwner Command Failed: Not in a game: " + chat); //$NON-NLS-1$ } if(!user.equals(game.getOwner())) { log.warn("GameOwner Command Denied: Not game owner: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return; } try { if (chat.startsWith(COMMAND_HELP)) { processHelp(chat, game, user, clientHandler); } else if (chat.startsWith(COMMAND_DETECTAUTOFIRE)) { processDetectAutoFire(chat, game, user, clientHandler); } else { log.info("Unknown GameOwner Command: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } catch (ActionException e) { log.info("GameOwner Command Failed: " + game + ": " + user + ": " + chat); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ game.announce(EmuLang.getString("GameOwnerCommandAction.CommandFailed", e.getMessage())); //$NON-NLS-1$ } catch (MessageFormatException e) { log.error("Failed to contruct message: " + e.getMessage(), e); //$NON-NLS-1$ } } private void processHelp(String message, KailleraGameImpl game, KailleraUserImpl admin, V086Controller.V086ClientHandler clientHandler) throws ActionException, MessageFormatException { game.announce(EmuLang.getString("GameOwnerCommandAction.AvailableCommands")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.SetAutofireDetection")); //$NON-NLS-1$ } private void autoFireHelp(KailleraGameImpl game) { int cur = game.getAutoFireDetector().getSensitivity(); game.announce(EmuLang.getString("GameOwnerCommandAction.HelpSensitivity")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.HelpDisable")); //$NON-NLS-1$ game.announce(EmuLang.getString("GameOwnerCommandAction.HelpCurrentSensitivity", cur) + (cur == 0 ? (EmuLang.getString("GameOwnerCommandAction.HelpDisabled")) : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } private void processDetectAutoFire(String message, KailleraGameImpl game, KailleraUserImpl admin, V086Controller.V086ClientHandler clientHandler) throws ActionException, MessageFormatException { if(game.getStatus() != KailleraGame.STATUS_WAITING) { game.announce(EmuLang.getString("GameOwnerCommandAction.AutoFireChangeDeniedInGame")); //$NON-NLS-1$ return; } StringTokenizer st = new StringTokenizer(message, " "); //$NON-NLS-1$ if(st.countTokens() != 2) { autoFireHelp(game); return; } String command = st.nextToken(); String sensitivityStr = st.nextToken(); int sensitivity = -1; try { sensitivity = Integer.parseInt(sensitivityStr); } catch(NumberFormatException e) {} if(sensitivity > 5 || sensitivity < 0) { autoFireHelp(game); return; } game.getAutoFireDetector().setSensitivity(sensitivity); game.announce(EmuLang.getString("GameOwnerCommandAction.HelpCurrentSensitivity", sensitivity) + (sensitivity == 0 ? (EmuLang.getString("GameOwnerCommandAction.HelpDisabled")) : "")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
monospacesoftware/emulinker
src/org/emulinker/kaillera/controller/v086/action/GameOwnerCommandAction.java
Java
gpl-2.0
4,749
package net.senmori.customtextures.events; import net.senmori.customtextures.util.MovementType; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerEvent; import com.sk89q.worldguard.protection.regions.ProtectedRegion; /** * event that is triggered after a player entered a WorldGuard region * @author mewin<mewin001@hotmail.de> */ public class RegionEnteredEvent extends RegionEvent { /** * creates a new RegionEnteredEvent * @param region the region the player entered * @param player the player who triggered the event * @param movement the type of movement how the player entered the region */ public RegionEnteredEvent(ProtectedRegion region, Player player, MovementType movement, PlayerEvent parent) { super(player, region, parent, movement); } }
Senmori/CustomTextures
src/main/java/net/senmori/customtextures/events/RegionEnteredEvent.java
Java
gpl-2.0
851
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sv.edu.uesocc.ingenieria.disenio2_2015.pymesell.presentacion.pymesellv1desktopclient; /** * * @author David */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Hola a todos!!!"); } }
girondave/Proyecto_Disenio2_2015-PymeSell_v1
PymeSellV1DesktopClient/src/java/sv/edu/uesocc/ingenieria/disenio2_2015/pymesell/presentacion/pymesellv1desktopclient/Main.java
Java
gpl-2.0
496
package org.booleanfloat.traveler.links; import org.booleanfloat.traveler.Location; import org.booleanfloat.traveler.interfaces.Traversable; import java.util.ArrayList; import java.util.concurrent.Callable; public class OneWayLink { public OneWayLink(Location start, Location end) { this(start, end, new ArrayList<Traversable>(), null); } public OneWayLink(Location start, Location end, ArrayList<Traversable> steps) { this(start, end, steps, null); } public OneWayLink(Location start, Location end, ArrayList<Traversable> steps, Callable<Boolean> requirement) { new Link(start, end, steps, requirement); } }
BooleanFloat/Traveler
src/org/booleanfloat/traveler/links/OneWayLink.java
Java
gpl-2.0
662
public class trace { public void mnonnullelements(int[] a) { int i = 0; //@ assert i == 0 && \nonnullelements(a); return ; } public void mnotmodified(int i) { //@ assert \not_modified(i); i = 4; //@ assert i == 4 && \not_modified(i); return ; } }
shunghsiyu/OpenJML_XOR
OpenJML/testfiles/escTraceBS/trace.java
Java
gpl-2.0
342
/** * */ package org.sylvani.io.voice.http; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.emf.common.util.EList; import org.eclipse.smarthome.model.sitemap.Sitemap; import org.eclipse.smarthome.model.sitemap.SitemapProvider; import org.eclipse.smarthome.model.sitemap.Widget; import org.eclipse.smarthome.ui.items.ItemUIRegistry; /** * Varianten * - Simple and Stupid HAL9000 * - Volltext * - Tagged Analyse * * @author hkuhn * */ public class RecognitionRelayServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ItemUIRegistry itemUIRegistry; private List<SitemapProvider> sitemaps; public RecognitionRelayServlet(ItemUIRegistry itemUIRegistry, List<SitemapProvider> sitemaps) { this.itemUIRegistry = itemUIRegistry; this.sitemaps = sitemaps; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { for (SitemapProvider sitemapProvider : sitemaps) { for (String sitemapName : sitemapProvider.getSitemapNames()) { System.out.println("sitemap " + sitemapName); Sitemap sitemap = sitemapProvider.getSitemap(sitemapName); EList<Widget> list = sitemap.getChildren(); for (Widget widget : list) { System.out.println("#Widget " + widget.getLabel() + " " + widget.getItem()); } } } } }
hkuhn42/sylvani
org.sylvani.io/src/main/java/org/sylvani/io/voice/http/RecognitionRelayServlet.java
Java
gpl-2.0
1,853
class Class3_Sub28 extends Class3 { static Class94[] aClass94Array2566 = new Class94[200]; static int anInt2567 = -1; private static Class94 aClass94_2568 = Class3_Sub4.buildString("Started 3d Library"); long aLong2569; Class3_Sub28 aClass3_Sub28_2570; static int anInt2571; static int anInt2572; static Class153 aClass153_2573; static int[] anIntArray2574 = new int[14]; static int anInt2575; static Class94 aClass94_2576 = aClass94_2568; static int anInt2577 = 0; Class3_Sub28 aClass3_Sub28_2578; static final void method518(Class140_Sub4_Sub1 var0, int var1) { try { Class3_Sub9 var2 = (Class3_Sub9)Class3_Sub28_Sub7_Sub1.aClass130_4046.method1780(var0.aClass94_3967.method1578(-121), 0); if(var1 >= -85) { method523(40, -17, -52, -32, 9, -51, -85, -84, -19); } if(var2 != null) { var2.method134(1); } else { Class70.method1286(var0.anIntArray2755[0], false, (Class111)null, 0, (Class140_Sub4_Sub2)null, var0.anIntArray2767[0], Class26.anInt501, var0); } } catch (RuntimeException var3) { throw Class44.method1067(var3, "rg.UA(" + (var0 != null?"{...}":"null") + ',' + var1 + ')'); } } static final int method519(int var0, boolean var1, int var2, int var3) { try { var0 &= 3; if(!var1) { method520((byte)-89); } return 0 != var0?(~var0 != -2?(~var0 == -3?-var3 + 7:-var2 + 7):var2):var3; } catch (RuntimeException var5) { throw Class44.method1067(var5, "rg.RA(" + var0 + ',' + var1 + ',' + var2 + ',' + var3 + ')'); } } static final Class3_Sub28_Sub3 method520(byte var0) { try { int var1 = -122 % ((var0 - -48) / 33); return Class3_Sub30.aClass3_Sub28_Sub3_2600; } catch (RuntimeException var2) { throw Class44.method1067(var2, "rg.OA(" + var0 + ')'); } } public static void method521(int var0) { try { aClass153_2573 = null; if(var0 == -3) { aClass94Array2566 = null; aClass94_2568 = null; anIntArray2574 = null; aClass94_2576 = null; } } catch (RuntimeException var2) { throw Class44.method1067(var2, "rg.QA(" + var0 + ')'); } } static final Class90 method522(int var0, int var1) { try { Class90 var2 = (Class90)Class3_Sub28_Sub7_Sub1.aClass93_4043.method1526((long)var0, (byte)121); if(null == var2) { byte[] var3 = Class29.aClass153_557.method2133(Class38_Sub1.method1031(var0, 2), (byte)-122, Canvas_Sub1.method54(var0, false)); var2 = new Class90(); if(var1 != 27112) { anInt2572 = -67; } var2.anInt1284 = var0; if(null != var3) { var2.method1478(new Class3_Sub30(var3), 74); } var2.method1481(98); Class3_Sub28_Sub7_Sub1.aClass93_4043.method1515((byte)-95, var2, (long)var0); return var2; } else { return var2; } } catch (RuntimeException var4) { throw Class44.method1067(var4, "rg.PA(" + var0 + ',' + var1 + ')'); } } static final void method523(int var0, int var1, int var2, int var3, int var4, int var5, int var6, int var7, int var8) { try { int var9 = var3 - var8; int var11 = (-var5 + var0 << 16) / var9; int var10 = -var4 + var6; int var12 = (var7 + -var1 << 16) / var10; Class83.method1410(var1, 0, var6, var4, var3, var5, var8, var12, var11, var2, -12541); } catch (RuntimeException var13) { throw Class44.method1067(var13, "rg.SA(" + var0 + ',' + var1 + ',' + var2 + ',' + var3 + ',' + var4 + ',' + var5 + ',' + var6 + ',' + var7 + ',' + var8 + ')'); } } final void method524(byte var1) { try { if(this.aClass3_Sub28_2570 != null) { this.aClass3_Sub28_2570.aClass3_Sub28_2578 = this.aClass3_Sub28_2578; this.aClass3_Sub28_2578.aClass3_Sub28_2570 = this.aClass3_Sub28_2570; this.aClass3_Sub28_2578 = null; this.aClass3_Sub28_2570 = null; if(var1 != -107) { this.aClass3_Sub28_2578 = (Class3_Sub28)null; } } } catch (RuntimeException var3) { throw Class44.method1067(var3, "rg.TA(" + var1 + ')'); } } }
Lmctruck30/RiotScape-Client
src/Class3_Sub28.java
Java
gpl-2.0
4,615
package lionse.client.stage; import java.util.ArrayList; import java.util.List; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import lionse.client.Display; import lionse.client.asset.Asset; import lionse.client.net.Header; import lionse.client.net.Server; public class Character implements Renderable { // character format constant values public static final float RESOLUTION = 1.5f; public static final float C_HEAD = 0 * RESOLUTION; public static final float C_FACE = 10 * RESOLUTION; public static final float C_BODY = 24 * RESOLUTION; public static final float C_HAND = 29 * RESOLUTION; public static final float C_LEG = 30 * RESOLUTION; public static LabelStyle NAME_TAG_STYLE; public static float[] SINE_WAVE = { 0, 0.27f, 0.52f, 0.74f, 0.89f, 0.98f, 0.99f, 0.93f, 0.79f, 0.59f, 0.35f, 0.08f, -0.19f, -0.45f, -0.67f, -0.85f, -0.96f, -0.99f, -0.95f, -0.84f, -0.66f, -0.43f, -0.17f }; static { NAME_TAG_STYLE = new LabelStyle(); NAME_TAG_STYLE.font = Asset.Font.get(Asset.NanumGothic); NAME_TAG_STYLE.fontColor = Color.BLACK; } public boolean me = false; // character property public String name; public int head; public int face; public int body; public int clothes; public int weapon; public float speed = 200f; // positioning property public Point position; public Point target; public Point bottom; // character graphics public Label nameTag; // ��dz�� ��� public TalkBalloon talkBalloon; // ��ũ ���߱� ��� public List<Path> path; public int pathIndex = 0; public int direction = 0; public boolean moving = false; private int step = 0; // graphics variables private float stepTime = 0; private int next = -1; // graphics cache private TextureRegion[] texture_head; private TextureRegion[] texture_face; private TextureRegion[] texture_body; private TextureRegion[] texture_hand; private TextureRegion[] texture_leg_stop; private TextureRegion[] texture_leg_step1; private TextureRegion[] texture_leg_step2; private TextureRegion[] texture_leg_step3; private TextureRegion[] texture_leg_step4; // animated character format (sine-wave) private float p_head; private float p_face; private float p_body; private float p_hand; // name, head, face, body, clothes, weapon public Character(String name, int head, int face, int body, int weapon) { this.name = name; this.head = head; this.face = face; this.body = body; this.weapon = weapon; this.position = new Point(); this.bottom = new Point(); this.talkBalloon = new TalkBalloon(this); this.nameTag = new Label(name, NAME_TAG_STYLE); this.path = new ArrayList<Path>(); cache(); } // cache values. if this method is not called when texture value is // changed.noting happens to the graphic public void cache() { texture_head = Asset.Character.get("HEAD"); texture_face = Asset.Character.get("FACE"); texture_body = Asset.Character.get("BODY"); texture_hand = Asset.Character.get("HAND"); texture_leg_stop = Asset.Character.get("LEG_STAND"); texture_leg_step1 = Asset.Character.get("LEG_STEP1"); texture_leg_step2 = Asset.Character.get("LEG_STEP2"); texture_leg_step3 = Asset.Character.get("LEG_STEP3"); texture_leg_step4 = Asset.Character.get("LEG_STEP4"); } public void talk(String message) { talkBalloon.show(message); } @Override public void draw(SpriteBatch spriteBatch, float delta) { // Debugger.log(texture_head.length); // draw leg if (moving) { switch (step) { case 0: spriteBatch.draw(texture_leg_step1[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 1: spriteBatch.draw(texture_leg_step2[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 2: spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 3: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 4: spriteBatch.draw(texture_leg_step4[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; case 5: spriteBatch.draw(texture_leg_step3[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); break; } } else { spriteBatch.draw(texture_leg_stop[direction], position.x, Display.HEIGHT - (position.y + C_LEG)); } // draw body spriteBatch.draw(texture_body[direction], position.x, Display.HEIGHT - (position.y + p_body)); // draw hands spriteBatch.draw(texture_hand[direction], position.x, Display.HEIGHT - (position.y + p_hand)); // draw face spriteBatch.draw(texture_face[direction], position.x, Display.HEIGHT - (position.y + p_face)); // draw head spriteBatch.draw(texture_head[direction], position.x, Display.HEIGHT - (position.y + p_head)); // draw name tag nameTag.draw(spriteBatch, 1); // draw talk balloon if (talkBalloon.talking) talkBalloon.draw(spriteBatch, delta); } @Override public void update(float delta) { // update time values. stepTime += delta; next += 1; if (next >= SINE_WAVE.length) next = 0; // increase step if moving. if (stepTime > 0.05f && moving) { step += 1; stepTime = 0; if (step > 5) step = 0; } // �̵����̶�� ��ǥ�� ������Ʈ�Ѵ�. // if (moving) { // updatePosition(delta); // �̵� ���� �� ��ũ ������ �߻��Ѵ�. if (me && moving) { updatePosition(delta); } else if (this.path.size() > 0 && !me && this.path.size() > pathIndex) { Path path = this.path.get(pathIndex); if (path.disabled) { pathIndex++; } else { this.direction = path.direction; if (path.target == null) { updatePosition(delta); } else { // moveTo(path, delta); updatePosition(delta); } // ���� ��ǥ�� Ÿ�� ��ǥ�� �˻��ؼ� ���� �ȿ� ������ �Ϸ� if (path.check(position)) { // �Ϸ� ��, ���ÿ��� �����Ͱ� 0�̸� ������ �ʱ�ȭ�Ѵ� (�޸� ���) if (this.path.size() - 1 <= pathIndex) { this.path.clear(); pathIndex = 0; } else { pathIndex++; } // ���̰� �ʹ� ũ�� �� ��� �ϵ弼���Ѵ�. } else if (path.previousDistance > 2000 && path.target != null) { // ������ ���� ���� position.x = path.target.x; position.y = path.target.y; } } } nameTag.setPosition(position.x - (nameTag.getWidth() / 2) + 27, Display.HEIGHT - position.y + 27); if (talkBalloon.talking) talkBalloon.update(delta); // ���� ������ ���� ������ ���� �Ųٱ� ���� ��δ� �������� �̺�Ʈ�� ���� �� �̸� ����� ���´�. // ���� �Ųٴ� ���� move �̺�Ʈ�� ���Դٸ� ���ÿ� �״´�. // ��� ������ �����̹Ƿ�, ��ǥ üũ�� �����ϴ�! ^^ // animation effect. (sine wave) p_head = C_HEAD + SINE_WAVE[next] * 2f; p_face = C_FACE + SINE_WAVE[next] * 2f; p_body = C_BODY + SINE_WAVE[next] * 2; p_hand = C_HAND + SINE_WAVE[next] * 2; } private void updatePosition(float delta) { switch (direction) { case 0: position.x -= speed * delta; position.y += speed * delta / 2; break; case 1: position.x -= speed * delta; break; case 2: position.x -= speed * delta; position.y -= speed * delta / 2; break; case 3: position.y -= speed * delta / 2; break; case 4: position.x += speed * delta; position.y -= speed * delta / 2; break; case 5: position.x += speed * delta; break; case 6: position.x += speed * delta; position.y += speed * delta / 2; break; case 7: position.y += speed * delta / 2; break; } } @Override public Point getPosition() { bottom.x = position.x; bottom.y = position.y + 150; bottom.z = position.z; return bottom; } public void move(int targetDirection) { this.direction = targetDirection; Server.send(Header.MOVE + Server.H_L + direction + Server.H_L + Math.round(speed) + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public void stop() { Server.send(Header.STOP + Server.H_L + Math.round(position.x) + Server.H_L + Math.round(position.y) + Server.H_L + Math.round(position.z)); } public int getDirection(Point point) { int xdet = 0; // -1-����, 0-���� ����, 1-������ int ydet = 0; // -1-�Ʒ���, 0-���� ����, 1-���� if (point.x - position.x > 0) { // �����ʿ� �ִ�. xdet = 1; } else if (point.x == position.x) { // ����. } else {// ���ʿ� �ִ�. xdet = -1; } if (point.y - position.y > 0) { // ���ʿ� �ִ�. ydet = -1; } else if (point.y == position.y) { // ����. } else {// �Ʒ��ʿ� �ִ�. ydet = 1; } if (xdet > 0) { // ������ if (ydet > 0) { // ������ �� return 4; } else if (ydet == 0) { // �׳� ������ return 5; } else { // ������ �Ʒ� return 6; } } else if (xdet == 0) { // y�� ������ if (ydet > 0) { // �� return 3; } else if (ydet == 0) { // �� ������ (����Ʈ ��ũ!) return -1; } else { // �Ʒ� return 7; } } else { // ���� if (ydet > 0) { // ���� �� return 2; } else if (ydet == 0) { // �׳� ���� return 1; } else { // ���� �Ʒ� return 0; } } } }
agemor/lionse
src/lionse/client/stage/Character.java
Java
gpl-2.0
10,099
package com.lami.tuomatuo.mq.zookeeper.server; import com.lami.tuomatuo.mq.zookeeper.jmx.ZKMBeanInfo; /** * This class implements the data tree MBean * * Created by xujiankang on 2017/3/19. */ public class DataTreeBean implements DataTreeMXBean, ZKMBeanInfo{ public DataTree dataTree; public DataTreeBean(DataTree dataTree) { this.dataTree = dataTree; } @Override public int getNodeCount() { return dataTree.getNodeCount(); } @Override public long approximateDataSize() { return dataTree.approximateDataSize(); } @Override public int countEphemerals() { return dataTree.getEphemeralsCount(); } public int getWatchCount(){ return dataTree.getWatchCount(); } @Override public String getName() { return "InMemoryDataTree"; } @Override public boolean isHidden() { return false; } @Override public String getLastZxid() { return "0x" + Long.toHexString(dataTree.lastProcessedZxid); } }
jackkiexu/tuomatuo
tuomatuo-mq/src/main/java/com/lami/tuomatuo/mq/zookeeper/server/DataTreeBean.java
Java
gpl-2.0
1,052
import tests.util.*; import java.util.Map; // Test case for Issue 134: // http://code.google.com/p/checker-framework/issues/detail?id=134 // Handling of generics from different enclosing classes. // TODO: revisit with nested types in 1.3. // @skip-test class GenericTest4 { public interface Foo {} class Outer<O> { O getOuter() { return null; } class Inner<I> { O getInner() { return null; } I setter1(O p) { return null; } O setter2(I p) { return null; } Map<O, I> wow(Map<O, I> p) { return null; } } } class OuterImpl extends Outer<Foo> { void test() { Foo foo = getOuter(); } class InnerImpl extends Inner<@Odd String> { void test() { Foo foo = getInner(); String s = setter1(foo); foo = setter2(s); } void testWow(Map<Foo, String> p) { p = wow(p); } } } // Add uses from outside of both classes. }
biddyweb/checker-framework
framework/tests/framework/GenericTest4.java
Java
gpl-2.0
939
package com.carpoolsophia; import java.util.concurrent.ExecutionException; import org.json.JSONException; import org.json.JSONObject; import android.app.Fragment; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import butterknife.InjectView; import butterknife.Views; import com.carpoolsophia.gcloudApi.model.CarpoolSophiaUser; import com.carpoolsophia.service.CarpoolSophiaUserService; import com.carpoolsophia.service.ProfileService; import com.facebook.AccessToken; import com.facebook.AccessTokenUtils; import com.facebook.GraphRequest; import com.facebook.GraphResponse; public class ProfileFragment extends Fragment { private final static String CLASSNAME = ProfileFragment.class.getSimpleName(); @InjectView(R.id.TestLoadFromFB) Button testLoadFromFbBtn; @InjectView(R.id.profile_firstName) EditText profileFirstName; @InjectView(R.id.profile_lastName) EditText profileLastName; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.profile_fragment, container, false); Views.inject(this, view); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ProfileFragment finalThis = this; testLoadFromFbBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.w(ProfileFragment.class.getSimpleName(), "loadFromFB"); CarpoolSophiaUser user; try { user = (new LoadUserFromFbTask(finalThis).execute()).get(); if (user != null) { // Log.w(getClass().getSimpleName(), // "user loaded: "+ModelToJSONParseAdapter.toJSONParse(user)); profileFirstName.setText(user.getFirstName()); profileLastName.setText(user.getLastName()); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } public void updateProfileInfo(View btn) { Log.w(getClass().getSimpleName(), "updateProfileInfo"); } private class LoadUserFromFbTask extends AsyncTask<CarpoolSophiaUser, Void, CarpoolSophiaUser> { private ProfileFragment profileFragment; public LoadUserFromFbTask(ProfileFragment fragment) { super(); this.profileFragment = fragment; } @SuppressWarnings("serial") protected CarpoolSophiaUser doInBackground(final CarpoolSophiaUser... users) { CarpoolSophiaUser user = CarpoolSophiaUserService.get() .getCurrentCSuser(); AccessToken accessToken = AccessTokenUtils.deserializeToken(user .getAccessToken()); GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { // Log.d(CLASSNAME, "JSONobject: " + object); // Log.d(CLASSNAME, "GraphResponse #1: " + // response.getRawResponse()); } }); GraphResponse response = request.executeAndWait(); Log.d(CLASSNAME, "GraphResponse #2: " + response.getRawResponse()); CarpoolSophiaUser userFromFB = new CarpoolSophiaUser(); try { userFromFB.setFirstName(response.getJSONObject() .getString("first_name")); userFromFB.setLastName(response.getJSONObject().getString("last_name")); } catch (JSONException e) { e.printStackTrace(); } ProfileService.get().refreshCSUser(user, userFromFB); return user; } @Override protected void onPostExecute(CarpoolSophiaUser result) { super.onPostExecute(result); } } }
cernier/carpoolsophia
carpoolsophia/src/main/java/com/carpoolsophia/ProfileFragment.java
Java
gpl-2.0
4,190
package com.yh.admin.bo; import java.util.Date; import com.yh.platform.core.bo.BaseBo; public class UserAgent extends BaseBo { private static final long serialVersionUID = 2715416587055228708L; private Long userAgentOid; private Long systemPositionOid; private String userId; // 被代理人 private String agentUserId; // 指定的代理人 private Date effectiveDate; // 有效开始期 private Date expiredDt; private String isActive; public Long getSystemPositionOid() { return systemPositionOid; } public void setSystemPositionOid(Long systemPositionOid) { this.systemPositionOid = systemPositionOid; } public Long getUserAgentOid() { return userAgentOid; } public void setUserAgentOid(Long userAgentOid) { this.userAgentOid = userAgentOid; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getAgentUserId() { return agentUserId; } public void setAgentUserId(String agentUserId) { this.agentUserId = agentUserId; } public Date getExpiredDt() { return expiredDt; } public void setExpiredDt(Date expiredDt) { this.expiredDt = expiredDt; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public Date getEffectiveDate() { return effectiveDate; } public void setEffectiveDate(Date effectiveDate) { this.effectiveDate = effectiveDate; } }
meijmOrg/Repo-test
freelance-admin/src/java/com/yh/admin/bo/UserAgent.java
Java
gpl-2.0
1,512
package org.rebecalang.modeltransformer.ros.timedrebeca; import java.util.HashMap; import java.util.Map; import org.rebecalang.compiler.modelcompiler.corerebeca.CoreRebecaTypeSystem; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.BinaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.CastExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.DotPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Expression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.FieldDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Literal; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.MsgsrvDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.NonDetExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PlusSubExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PrimaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.ReactiveClassDeclaration; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecInstantiationPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecaModel; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TermPrimary; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TernaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.UnaryExpression; import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.VariableDeclarator; import org.rebecalang.compiler.modelcompiler.timedrebeca.TimedRebecaTypeSystem; import org.rebecalang.compiler.utils.CodeCompilationException; import org.rebecalang.compiler.utils.ExceptionContainer; import org.rebecalang.compiler.utils.Pair; import org.rebecalang.modeltransformer.StatementTransformingException; import org.rebecalang.modeltransformer.ros.Utilities; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class TimedRebeca2ROSExpressionTransformer { public final static String NEW_LINE = "\r\n"; public final static String TAB = "\t"; static Integer i = 0; private String modelName; private ReactiveClassDeclaration rc; private RebecaModel rebecaModel; private Map <Pair<String, String>, String> methodCalls = new HashMap<Pair<String, String>, String>(); @Autowired TimedRebecaTypeSystem timedRebecaTypeSystem; @Autowired ExceptionContainer exceptionContainer; public void prepare(String modelName, ReactiveClassDeclaration rc, RebecaModel rebecaModel) { this.modelName = modelName; this.rebecaModel = rebecaModel; this.rc = rc; } public String translate(Expression expression) { String retValue = ""; if (expression instanceof TernaryExpression) { TernaryExpression tExpression = (TernaryExpression)expression; Expression condition = tExpression.getCondition(); retValue = "(" + (translate(condition)) + ")"; retValue += " ? " + "(" + translate(tExpression.getLeft()) + ")"; retValue += " : " + "(" + translate(tExpression.getRight()) + ")"; } else if (expression instanceof BinaryExpression) { BinaryExpression bExpression = (BinaryExpression) expression; String op = bExpression.getOperator(); retValue = translate(bExpression.getLeft()) + " " + op + " " + translate(bExpression.getRight()); } else if (expression instanceof UnaryExpression) { UnaryExpression uExpression = (UnaryExpression) expression; retValue = uExpression.getOperator() + " " + translate(uExpression.getExpression()); } else if (expression instanceof CastExpression) { exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " + "\"cast\" expression.", expression.getLineNumber(), expression.getCharacter())); } else if (expression instanceof NonDetExpression) { NonDetExpression nonDetExpression = (NonDetExpression)expression; int numberOfChoices = nonDetExpression.getChoices().size(); retValue += nonDetExpression.getType().getTypeName(); retValue += "int numberOfChoices = " + Integer.toString(numberOfChoices) + ";" + NEW_LINE; retValue += "int choice = " + "rand() % " + Integer.toString(numberOfChoices) + ";" + NEW_LINE; int index = numberOfChoices; for (Expression nonDetChoice : ((NonDetExpression)expression).getChoices()) { retValue += "if (" + "choice ==" + Integer.toString(numberOfChoices - index) + ")" + NEW_LINE; retValue += ((NonDetExpression)nonDetChoice); index ++; } } else if (expression instanceof Literal) { Literal lExpression = (Literal) expression; retValue = lExpression.getLiteralValue(); if (retValue.equals("null")) retValue = "\"dummy\""; } else if (expression instanceof PlusSubExpression) { retValue = translate(((PlusSubExpression)expression).getValue()) + ((PlusSubExpression)expression).getOperator(); } else if (expression instanceof PrimaryExpression) { PrimaryExpression pExpression = (PrimaryExpression) expression; retValue = translatePrimaryExpression(pExpression); } else { exceptionContainer.addException( new StatementTransformingException("Unknown translation rule for expression type " + expression.getClass(), expression.getLineNumber(), expression.getCharacter())); } return retValue; } protected String translatePrimaryExpression(PrimaryExpression pExpression) { String retValue = ""; if (pExpression instanceof DotPrimary) { DotPrimary dotPrimary = (DotPrimary) pExpression; retValue = translateDotPrimary(dotPrimary); } else if (pExpression instanceof TermPrimary) { retValue = translatePrimaryTermExpression((TermPrimary) pExpression); } else if (pExpression instanceof RebecInstantiationPrimary) { RebecInstantiationPrimary rip = (RebecInstantiationPrimary) pExpression; boolean hasMoreVariable = false; String args = ""; try { ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) timedRebecaTypeSystem.getMetaData(rip.getType()); if (!rcd.getStatevars().isEmpty()) { args += " , "; for (FieldDeclaration fd : rcd.getStatevars()) { for (VariableDeclarator vd : fd.getVariableDeclarators()) { hasMoreVariable = true; String typeInit = fd.getType() == CoreRebecaTypeSystem.BOOLEAN_TYPE ? "false" : fd.getType().canTypeCastTo(CoreRebecaTypeSystem.INT_TYPE) ? "0" : "\"dummy\""; args += "(" + rcd.getName() + "-" + vd.getVariableName() + " |-> " + typeInit + ") " ; } } } if (!hasMoreVariable) args += "emptyValuation"; } catch (CodeCompilationException e) { e.printStackTrace(); } args += ","; hasMoreVariable = false; String typeName = rip.getType().getTypeName(); for (Expression expression : rip.getBindings()) { args += " arg(" + translate(expression) + ")"; hasMoreVariable = true; } for (Expression expression : rip.getArguments()) { args += " arg(" + translate(expression) + ")"; hasMoreVariable = true; } if (!hasMoreVariable) args += "noArg"; retValue = " new (" + typeName + args + ")"; } else { exceptionContainer.addException(new StatementTransformingException("Unknown translation rule for initializer type " + pExpression.getClass(), pExpression.getLineNumber(), pExpression.getCharacter())); } return retValue; } private String translateDotPrimary(DotPrimary dotPrimary) { String retValue = ""; if (!(dotPrimary.getLeft() instanceof TermPrimary) || !(dotPrimary.getRight() instanceof TermPrimary)) { exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " + "nested record access expression.", dotPrimary.getLineNumber(), dotPrimary.getCharacter())); } else { // TODO: Modified by Ehsan as the return vlaue type of message servers is always set to MSGSRV_TYPE // if(TypesUtilities.getInstance().getSuperType(dotPrimary.getRight().getType()) == TypesUtilities.MSGSRV_TYPE) { if(dotPrimary.getRight().getType() == CoreRebecaTypeSystem.MSGSRV_TYPE) { retValue = mapToROSPublishing(dotPrimary); } } return retValue; } private String mapToROSPublishing(DotPrimary dotPrimary) { String retValue = ""; /* map to ROS Publishing */ retValue = modelName + "::" + ((TermPrimary)dotPrimary.getRight()).getName() + " " + "pubMsg" + i.toString() + ";" + NEW_LINE; /* fill the ROS message fields with the arguments to be published */ int argumentIndex = 0; for (Expression expression : ((TermPrimary)dotPrimary.getRight()).getParentSuffixPrimary().getArguments()) { ReactiveClassDeclaration toClass = null; TermPrimary toRebec = (TermPrimary)dotPrimary.getLeft(); toClass = Utilities.findKnownReactiveClass(rc, toRebec.getName(), rebecaModel); String toMsgsrvName = ((TermPrimary)dotPrimary.getRight()).getName(); MsgsrvDeclaration toMsgsrv = Utilities.findTheMsgsrv(toClass, toMsgsrvName); String argumentName = toMsgsrv.getFormalParameters().get(argumentIndex).getName(); retValue += "pubMsg" + i.toString() + "." + argumentName + " = " + translate(expression) + ";" + NEW_LINE; argumentIndex ++; } retValue += "pubMsg" + i.toString() + "." + "sender" + "=" + "sender" + ";" + NEW_LINE; retValue += ((TermPrimary) dotPrimary.getLeft()).getName() + "_" + ((TermPrimary)dotPrimary.getRight()).getName() + "_pub" + "." + "publish(" + "pubMsg" + i.toString() + ")" + ";" + NEW_LINE; i ++; /* to prevent from repeated names */ /* end of publishing */ /* storing the name of callee rebec and the name of called msgsrv in order to declare publishers */ Pair<String, String> methodCall = new Pair<String, String>( ((TermPrimary)dotPrimary.getLeft()).getName(), ((TermPrimary)dotPrimary.getRight()).getName() ); methodCalls.put(methodCall, ""); //ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) TransformingContext.getInstance().lookupInContext("current-reactive-class"); //retValue = ((TermPrimary) dotPrimary.getLeft()).getName(); //String typeName = TypesUtilities.getTypeName(((TermPrimary) dotPrimary.getLeft()).getType()); //System.out.println(typeName); return retValue; } private String translatePrimaryTermExpression(TermPrimary pExpression) { String retValue = ""; if(pExpression.getName().equals("assertion") || pExpression.getName().equals("after") || pExpression.getName().equals("deadline")){ return retValue; } if(pExpression.getName().equals("delay")) retValue += "sleep"; else if(pExpression.getName().equals("sender")) return "thisMsg.sender"; else retValue += pExpression.getName(); if( pExpression.getParentSuffixPrimary() != null) { retValue += "("; for(Expression argument: pExpression.getParentSuffixPrimary().getArguments()) { retValue += translate(argument) + ","; } if(! pExpression.getParentSuffixPrimary().getArguments().isEmpty()) { retValue = retValue.substring(0, retValue.length() - 1); } retValue += ")"; } //To support movement in ROS if (retValue.compareTo("Move(1,0)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(0,1)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(-1,0)")==0) { //ROSCode to publish on CM_Vel topic } else if (retValue.compareTo("Move(0,-1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(1,1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(1,-1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(-1,1)")==0) { //ROSCode to publish on CM_Vel topic } else if(retValue.compareTo("Move(-1,-1)")==0) { //ROSCode to publish on CM_Vel topic } /* to support arrays */ for(Expression ex: pExpression.getIndices()) { retValue += "[" + translate(ex) + "]"; } return retValue; } public Map <Pair<String, String>, String> getMethodCalls() { return methodCalls; } }
rebeca-lang/org.rebecalang.modeltransformer
src/main/java/org/rebecalang/modeltransformer/ros/timedrebeca/TimedRebeca2ROSExpressionTransformer.java
Java
gpl-2.0
12,240
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pt.jkaiui.core.messages; import java.util.regex.Matcher; import java.util.regex.Pattern; import pt.jkaiui.core.KaiString; import pt.jkaiui.manager.I_InMessage; /** * * @author yuu@akron */ public class ConnectedArena extends Message implements I_InMessage { public ConnectedArena() { } public Message parse(String s) { Pattern p = Pattern.compile("KAI_CLIENT_CONNECTED_ARENA;"); Matcher m = p.matcher(s); if (m.matches()){ ConnectedArena msg = new ConnectedArena(); return msg; } return null; } }
yuuakron/jKaiUI_Custom
src/pt/jkaiui/core/messages/ConnectedArena.java
Java
gpl-2.0
731
// Test for method java.util.IllegalFormatPrecisionException.getClass().getFields() // Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com> // This file is part of Mauve. // Mauve 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. // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301 USA. // Tags: JDK1.5 package gnu.testlet.java.util.IllegalFormatPrecisionException.classInfo; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.util.IllegalFormatPrecisionException; import java.util.Map; import java.util.HashMap; /** * Test for method java.util.IllegalFormatPrecisionException.getClass().getFields() */ public class getFields implements Testlet { /** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { // map of fields which should exists Map<String, String> testedFields = null; // map of fields for (Open)JDK6 Map<String, String> testedFields_jdk6 = new HashMap<String, String>(); // map of fields for (Open)JDK7 Map<String, String> testedFields_jdk7 = new HashMap<String, String>(); // map for fields declared in (Open)JDK6 // --- empty --- // map for fields declared in (Open)JDK7 // --- empty --- // create instance of a class IllegalFormatPrecisionException final Object o = new IllegalFormatPrecisionException(42); // get a runtime class of an object "o" final Class c = o.getClass(); // get the right map containing field signatures testedFields = getJavaVersion() < 7 ? testedFields_jdk6 : testedFields_jdk7; // get all fields for this class java.lang.reflect.Field[] fields = c.getFields(); // expected number of fields final int expectedNumberOfFields = testedFields.size(); // basic check for a number of fields harness.check(fields.length, expectedNumberOfFields); } /** * Returns version of Java. The input could have the following form: "1.7.0_06" * and we are interested only in "7" in this case. * * @return Java version */ protected int getJavaVersion() { String javaVersionStr = System.getProperty("java.version"); String[] parts = javaVersionStr.split("\\."); return Integer.parseInt(parts[1]); } }
niloc132/mauve-gwt
src/main/java/gnu/testlet/java/util/IllegalFormatPrecisionException/classInfo/getFields.java
Java
gpl-2.0
3,040
package com.mmm.product.domain; import java.io.Serializable; public class ShippingDetails implements Serializable{ private static final long serialVersionUID = 5941389959992371612L; }
Lnjena/mmm.com
mmm-spring-boot/src/main/java/com/mmm/product/domain/ShippingDetails.java
Java
gpl-2.0
189
package org.jiserte.bioformats.readers.phylip; import org.jiserte.bioformats.readers.faults.AlignmentReadingFault; public class FirstBlockLinePhylipFault extends AlignmentReadingFault { public FirstBlockLinePhylipFault() { super(); this.setMessage("Sequences in the first block of data must have a description of 10 characters and then the sequence."); } }
javieriserte/XI-bio-formats
XI-Bio-Formats/src/org/jiserte/bioformats/readers/phylip/FirstBlockLinePhylipFault.java
Java
gpl-2.0
378
/* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is modified by Felix Natter in 2013. * * 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 org.freeplane.core.resources.components; import javax.swing.JButton; import com.jgoodies.forms.builder.DefaultFormBuilder; public class ButtonProperty extends PropertyBean implements IPropertyControl { final JButton mButton; /** */ public ButtonProperty(final String name, JButton button) { super(name); mButton = button; } @Override public String getValue() { return ""; } public void appendToForm(final DefaultFormBuilder builder) { appendToForm(builder, mButton); } public void setEnabled(final boolean pEnabled) { mButton.setEnabled(pEnabled); super.setEnabled(pEnabled); } @Override public void setValue(final String value) { } public void setToolTipText(String text) { mButton.setToolTipText(text); } }
freeplane/freeplane
freeplane/src/main/java/org/freeplane/core/resources/components/ButtonProperty.java
Java
gpl-2.0
1,600
package com.mikesantiago.mariofighter; import static com.mikesantiago.mariofighter.GlobalVariables.PPM; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; import com.mikesantiago.mariofighter.assets.Animation; public class PlayerOne { public enum Direction { LEFT, RIGHT, STOP } private BodyDef playerBodyDef; private Body playerBody; private PolygonShape playerShape; private FixtureDef playerFixtureDef; private Fixture playerFixture; private boolean isMoving = false; private Direction currentDirection = Direction.RIGHT; private Animation animationRight; private Animation animationLeft; public boolean getMoving(){return isMoving;} public Direction getCurrentDirection(){return currentDirection;} public PlayerOne(World worldToCreateIn) { playerBodyDef = new BodyDef(); playerBodyDef.type = BodyType.DynamicBody; playerBodyDef.position.set(new Vector2(32f / PPM, 256f / PPM)); playerBody = worldToCreateIn.createBody(playerBodyDef); playerShape = new PolygonShape(); playerShape.setAsBox((32f / 2) / PPM, (36f / 2) / PPM); playerFixtureDef = new FixtureDef(); playerFixtureDef.shape = playerShape; playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT; playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT; playerFixture = playerBody.createFixture(playerFixtureDef); playerFixture.setUserData("body"); //create foot sensor { playerShape.setAsBox(2 / PPM, 2 / PPM, new Vector2(0, -32 / PPM), 0); playerFixtureDef.shape = playerShape; playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT; playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT; playerFixtureDef.isSensor = true; playerBody.createFixture(playerFixtureDef).setUserData("FOOT"); } CreateAnimation(); System.out.println("Player 1 created!"); } private void CreateAnimation() { float updateInterval = 1 / 20f; Texture tex = GlobalVariables.manager.GetTexture("mario"); TextureRegion[] sprites = TextureRegion.split(tex, 16, 28)[0]; if(animationRight == null) animationRight = new Animation(); animationRight.setFrames(sprites, updateInterval); if(animationLeft == null) animationLeft = new Animation(); TextureRegion[] leftSprites = TextureRegion.split(tex, 16, 28)[0]; for(TextureRegion tr : leftSprites) tr.flip(true, false); animationLeft.setFrames(leftSprites, updateInterval); sprWidth = sprites[0].getRegionWidth(); sprHeight = sprites[0].getRegionHeight(); } private int sprWidth, sprHeight; public void update(float dt) { if(this.isMoving) { animationRight.update(dt); animationLeft.update(dt); } } public void render(SpriteBatch sb) { if(!sb.isDrawing()) sb.begin(); sb.setProjectionMatrix(GlobalVariables.maincamera.combined); if(this.isMoving) { if(this.currentDirection == Direction.RIGHT) { sb.draw(animationRight.getFrame(), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } else if(this.currentDirection == Direction.LEFT) { sb.draw(animationLeft.getFrame(), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } } else { if(this.currentDirection == Direction.RIGHT) { sb.draw(animationRight.getFrame(0), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } else if(this.currentDirection == Direction.LEFT) { sb.draw(animationLeft.getFrame(0), (playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34, sprWidth * 2, sprHeight * 2); } } if(sb.isDrawing()) sb.end(); } public void setMoving(boolean a){this.isMoving = a;} public void setCurrentDirection(Direction a){currentDirection = a;} public BodyDef getPlayerBodyDef() { return playerBodyDef; } public void setPlayerBodyDef(BodyDef playerBodyDef) { this.playerBodyDef = playerBodyDef; } public Body getPlayerBody() { return playerBody; } public void setPlayerBody(Body playerBody) { this.playerBody = playerBody; } public PolygonShape getPlayerShape() { return playerShape; } public void setPlayerShape(PolygonShape playerShape) { this.playerShape = playerShape; } public FixtureDef getPlayerFixtureDef() { return playerFixtureDef; } public void setPlayerFixtureDef(FixtureDef playerFixtureDef) { this.playerFixtureDef = playerFixtureDef; } public Fixture getPlayerFixture() { return playerFixture; } public void setPlayerFixture(Fixture playerFixture) { this.playerFixture = playerFixture; } }
Luigifan/MarioFighter
core/src/com/mikesantiago/mariofighter/PlayerOne.java
Java
gpl-2.0
5,195
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.quercus.lib.spl; import com.caucho.quercus.env.Value; public interface OuterIterator extends Iterator { public Value getInnerIterator(); }
dlitz/resin
modules/quercus/src/com/caucho/quercus/lib/spl/OuterIterator.java
Java
gpl-2.0
1,187
package cz.vutbr.fit.xfekia00; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedList; /** * jedno vykonanie skriptu sa uklada ako polozka historie * @author Filip Fekiac */ public class HistoryItem { private final String usedDatabase; // pouzity databazovy system private final LinkedList<String[][]> resultList; // vysledky dopytov private final LinkedList<String[]> resultHeader; // hlavicky dopytov private final LinkedList<String> resultCaption; // jednotlive dopyty private final Calendar date; public HistoryItem(String _usedDB) { usedDatabase = _usedDB; resultList = new LinkedList<>(); resultHeader = new LinkedList<>(); resultCaption = new LinkedList<>(); date = Calendar.getInstance(); } public void addResultItem(int pos, String[][] _item) { resultList.add(pos, _item); } public void addHeaderItem(int pos, String[] _item) { resultHeader.add(pos, _item); } public void addCaptionItem(int pos, String _item) { resultCaption.add(pos, _item); } public String getUsedDatabase() { return usedDatabase; } public LinkedList<String[][]> getResultList() { return resultList; } public LinkedList<String[]> getResultHeader() { return resultHeader; } public LinkedList<String> getResultCaption() { return resultCaption; } @Override public String toString() { SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy"); return format.format(date.getTime()) + " " + usedDatabase; } }
waresko18/TempJDBC
src-gui/src/cz/vutbr/fit/xfekia00/HistoryItem.java
Java
gpl-2.0
1,674
package org.lastbamboo.common.util.mina.decode.binary; import org.littleshoot.mina.common.ByteBuffer; import org.littleshoot.mina.filter.codec.ProtocolDecoderOutput; import org.littleshoot.util.mina.DecodingState; /** * Decoding state for reading a single unsigned int. */ public abstract class UnsignedIntDecodingState implements DecodingState { public DecodingState decode(final ByteBuffer in, final ProtocolDecoderOutput out) throws Exception { if (in.remaining() > 3) { final long decoded = in.getUnsignedInt(); return finishDecode(decoded, out); } else { return this; } } /** * Called on the subclass when the unsigned int has been successfully * decoded. * * @param decodedShort The decoded unsigned int. * @param out The decoder output. * @return The next state. * @throws Exception If any unexpected error occurs. */ protected abstract DecodingState finishDecode(final long decodedShort, final ProtocolDecoderOutput out) throws Exception; }
adamfisk/littleshoot-client
common/util/mina/src/main/java/org/lastbamboo/common/util/mina/decode/binary/UnsignedIntDecodingState.java
Java
gpl-2.0
1,151
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config.datacollection; import java.io.Reader; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.exolab.castor.xml.Validator; import org.opennms.core.xml.ValidateUsing; /** * a MIB object * * @version $Revision$ $Date$ */ @XmlRootElement(name="mibObj", namespace="http://xmlns.opennms.org/xsd/config/datacollection") @XmlAccessorType(XmlAccessType.NONE) @XmlType(propOrder={"oid", "instance", "alias", "type", "maxval", "minval"}) @ValidateUsing("datacollection-config.xsd") public class MibObj implements java.io.Serializable { private static final long serialVersionUID = -7831201614734695268L; /** * object identifier */ private String m_oid; /** * instance identifier. Only valid instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. */ private String m_instance; /** * a human readable name for the object (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. */ private String m_alias; /** * SNMP data type SNMP supported types: counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file */ private String m_type; /** * Maximum Value. In order to correctly manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. */ private String m_maxval; /** * Minimum Value. For completeness, adding the ability * to use a minimum value. */ private String m_minval; public MibObj() { super(); } public MibObj(final String oid, final String instance, final String alias, final String type) { super(); m_oid = oid; m_instance = instance; m_alias = alias; m_type = type; } /** * Overrides the java.lang.Object.equals method. * * @param obj * @return true if the objects are equal. */ @Override() public boolean equals(final java.lang.Object obj) { if ( this == obj ) return true; if (obj instanceof MibObj) { final MibObj temp = (MibObj)obj; if (m_oid != null) { if (temp.m_oid == null) return false; else if (!(m_oid.equals(temp.m_oid))) return false; } else if (temp.m_oid != null) return false; if (m_instance != null) { if (temp.m_instance == null) return false; else if (!(m_instance.equals(temp.m_instance))) return false; } else if (temp.m_instance != null) return false; if (m_alias != null) { if (temp.m_alias == null) return false; else if (!(m_alias.equals(temp.m_alias))) return false; } else if (temp.m_alias != null) return false; if (m_type != null) { if (temp.m_type == null) return false; else if (!(m_type.equals(temp.m_type))) return false; } else if (temp.m_type != null) return false; if (m_maxval != null) { if (temp.m_maxval == null) return false; else if (!(m_maxval.equals(temp.m_maxval))) return false; } else if (temp.m_maxval != null) return false; if (m_minval != null) { if (temp.m_minval == null) return false; else if (!(m_minval.equals(temp.m_minval))) return false; } else if (temp.m_minval != null) return false; return true; } return false; } /** * Returns the value of field 'alias'. The field 'alias' has * the following description: a human readable name for the * object (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. * * @return the value of field 'Alias'. */ @XmlAttribute(name="alias", required=true) public String getAlias() { return m_alias; } /** * Returns the value of field 'instance'. The field 'instance' * has the following description: instance identifier. Only * valid instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. * * @return the value of field 'Instance'. */ @XmlAttribute(name="instance", required=true) public String getInstance() { return m_instance; } /** * Returns the value of field 'maxval'. The field 'maxval' has * the following description: Maximum Value. In order to * correctly manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. * * @return the value of field 'Maxval'. */ @XmlAttribute(name="maxval", required=false) public String getMaxval() { return m_maxval; } /** * Returns the value of field 'minval'. The field 'minval' has * the following description: Minimum Value. For completeness, * adding the ability * to use a minimum value. * * @return the value of field 'Minval'. */ @XmlAttribute(name="minval", required=false) public String getMinval() { return m_minval; } /** * Returns the value of field 'oid'. The field 'oid' has the * following description: object identifier * * @return the value of field 'Oid'. */ @XmlAttribute(name="oid", required=true) public String getOid() { return m_oid; } /** * Returns the value of field 'type'. The field 'type' has the * following description: SNMP data type SNMP supported types: * counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file * * @return the value of field 'Type'. */ @XmlAttribute(name="type", required=true) public String getType() { return m_type; } /** * Overrides the java.lang.Object.hashCode method. * <p> * The following steps came from <b>Effective Java Programming * Language Guide</b> by Joshua Bloch, Chapter 3 * * @return a hash code value for the object. */ public int hashCode() { int result = 17; if (m_oid != null) { result = 37 * result + m_oid.hashCode(); } if (m_instance != null) { result = 37 * result + m_instance.hashCode(); } if (m_alias != null) { result = 37 * result + m_alias.hashCode(); } if (m_type != null) { result = 37 * result + m_type.hashCode(); } if (m_maxval != null) { result = 37 * result + m_maxval.hashCode(); } if (m_minval != null) { result = 37 * result + m_minval.hashCode(); } return result; } /** * Method isValid. * * @return true if this object is valid according to the schema */ @Deprecated public boolean isValid() { try { validate(); } catch (ValidationException vex) { return false; } return true; } /** * * * @param out * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws ValidationException if this * object is an invalid instance according to the schema */ @Deprecated public void marshal(final java.io.Writer out) throws MarshalException, ValidationException { Marshaller.marshal(this, out); } /** * * * @param handler * @throws java.io.IOException if an IOException occurs during * marshaling * @throws ValidationException if this * object is an invalid instance according to the schema * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling */ @Deprecated public void marshal(final org.xml.sax.ContentHandler handler) throws java.io.IOException, MarshalException, ValidationException { Marshaller.marshal(this, handler); } /** * Sets the value of field 'alias'. The field 'alias' has the * following description: a human readable name for the object * (such as * "ifOctetsIn"). NOTE: This value is used as the RRD file * name and * data source name. RRD only supports data source names up to * 19 chars * in length. If the SNMP data collector encounters an alias * which * exceeds 19 characters it will be truncated. * * @param alias the value of field 'alias'. */ public void setAlias(final String alias) { m_alias = alias.intern(); } /** * Sets the value of field 'instance'. The field 'instance' has * the following description: instance identifier. Only valid * instance identifier * values are a positive integer value or the keyword * "ifIndex" which * indicates that the ifIndex of the interface is to be * substituted for * the instance value for each interface the oid is retrieved * for. * * @param instance the value of field 'instance'. */ public void setInstance(final String instance) { m_instance = instance.intern(); } /** * Sets the value of field 'maxval'. The field 'maxval' has the * following description: Maximum Value. In order to correctly * manage counter * wraps, it is possible to add a maximum value for a * collection. For * example, a 32-bit counter would have a max value of * 4294967295. * * @param maxval the value of field 'maxval'. */ public void setMaxval(final String maxval) { m_maxval = maxval.intern(); } /** * Sets the value of field 'minval'. The field 'minval' has the * following description: Minimum Value. For completeness, * adding the ability * to use a minimum value. * * @param minval the value of field 'minval'. */ public void setMinval(final String minval) { m_minval = minval.intern(); } /** * Sets the value of field 'oid'. The field 'oid' has the * following description: object identifier * * @param oid the value of field 'oid'. */ public void setOid(final String oid) { m_oid = oid.intern(); } /** * Sets the value of field 'type'. The field 'type' has the * following description: SNMP data type SNMP supported types: * counter, gauge, * timeticks, integer, octetstring, string. The SNMP type is * mapped to * one of two RRD supported data types COUNTER or GAUGE, or * the * string.properties file. The mapping is as follows: SNMP * counter * -> RRD COUNTER; SNMP gauge, timeticks, integer, octetstring * -> * RRD GAUGE; SNMP string -> String properties file * * @param type the value of field 'type'. */ public void setType(final String type) { m_type = type.intern(); } /** * Method unmarshal. * * @param reader * @throws MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws ValidationException if this * object is an invalid instance according to the schema * @return the unmarshaled * MibObj */ @Deprecated public static MibObj unmarshal(final Reader reader) throws MarshalException, ValidationException { return (MibObj)Unmarshaller.unmarshal(MibObj.class, reader); } /** * * * @throws ValidationException if this * object is an invalid instance according to the schema */ public void validate() throws ValidationException { Validator validator = new Validator(); validator.validate(this); } }
vishwaAbhinav/OpenNMS
opennms-config/src/main/java/org/opennms/netmgt/config/datacollection/MibObj.java
Java
gpl-2.0
15,302
package org.mo.com.io; public class FLinkInput { }
favedit/MoPlatform
mo-1-common/src/lang-java/org/mo/com/io/FLinkInput.java
Java
gpl-2.0
52
package com.app.labeli; import com.app.labeli.member.Member; import net.tools.*; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * > @FragmentConnection * * Fragment to create a connection between app * and API. * * @author Florian "Aamu Lumi" Kauder * for the project @Label[i] */ public class FragmentConnection extends Fragment { private EditText editTextLogin, editTextPassword; private Button button; private ProgressDialog pDialog; public FragmentConnection() { } public void connectToAPI(View v){ if (editTextLogin.length() == 0) Toast.makeText(getActivity(), "Veuillez rentrer un identifiant", Toast.LENGTH_SHORT).show(); else if (editTextPassword.length() == 0) Toast.makeText(getActivity(), "Veuillez rentrer un mot de passe", Toast.LENGTH_SHORT).show(); else { new InitConnection(editTextLogin.getText().toString(), editTextPassword.getText().toString()) .execute(); } } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); getActivity().getActionBar().setTitle("Connexion"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_connection, container, false); editTextLogin = (EditText) v.findViewById(R.id.fragment_connection_edit_text_login); editTextPassword = (EditText) v.findViewById(R.id.fragment_connection_edit_text_password); button = (Button) v.findViewById(R.id.fragment_connection_button_connection); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { connectToAPI(arg0); } }); return v; } private class InitConnection extends AsyncTask<Void, Void, String> { String username, password; boolean success; public InitConnection(String username, String password){ this.username = username; this.password = password; this.success = false; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(FragmentConnection.this.getActivity()); pDialog.setMessage("Connexion"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } @Override protected String doInBackground(Void... params) { success = APIConnection.login(username, password); return null; } @Override protected void onPostExecute(String file_url) { pDialog.dismiss(); if (!success) Toast.makeText(getActivity(), "Mauvais identifiant / mot de passe", Toast.LENGTH_SHORT).show(); else { Member loggedUser = APIConnection.getLoggedUser(); Toast.makeText(getActivity(), "Bonjour " + loggedUser.getFirstName() + " " + loggedUser.getLastName(), Toast.LENGTH_SHORT).show(); ((MainActivity)getActivity()).loadLeftMenu(); Fragment fragment = new FragmentAccount(); Bundle args = new Bundle(); fragment.setArguments(args); FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); transaction.replace(R.id.activity_main_content_frame, fragment, fragment.getClass().getName()); transaction.addToBackStack(fragment.getClass().getName()); transaction.commit(); } } } }
asso-labeli/labeli-android-app
src/com/app/labeli/FragmentConnection.java
Java
gpl-2.0
3,863
package teammates.test.cases.action; import org.testng.annotations.Test; import teammates.common.datatransfer.DataBundle; import teammates.common.datatransfer.attributes.FeedbackQuestionAttributes; import teammates.common.datatransfer.attributes.FeedbackResponseAttributes; import teammates.common.datatransfer.attributes.FeedbackSessionAttributes; import teammates.common.datatransfer.attributes.InstructorAttributes; import teammates.common.datatransfer.questions.FeedbackNumericalScaleQuestionDetails; import teammates.common.exception.NullPostParameterException; import teammates.common.util.Const; import teammates.common.util.EmailType; import teammates.common.util.EmailWrapper; import teammates.common.util.StringHelper; import teammates.common.util.TimeHelper; import teammates.logic.core.CoursesLogic; import teammates.storage.api.FeedbackQuestionsDb; import teammates.storage.api.FeedbackResponsesDb; import teammates.storage.api.FeedbackSessionsDb; import teammates.ui.controller.InstructorFeedbackSubmissionEditSaveAction; import teammates.ui.controller.RedirectResult; /** * SUT: {@link InstructorFeedbackSubmissionEditSaveAction}. */ public class InstructorFeedbackSubmissionEditSaveActionTest extends BaseActionTest { private static final CoursesLogic coursesLogic = CoursesLogic.inst(); private final FeedbackSessionsDb fsDb = new FeedbackSessionsDb(); @Override protected String getActionUri() { return Const.ActionURIs.INSTRUCTOR_FEEDBACK_SUBMISSION_EDIT_SAVE; } @Override protected void prepareTestData() { super.prepareTestData(); dataBundle = loadDataBundle("/InstructorFeedbackSubmissionEditSaveActionTest.json"); removeAndRestoreDataBundle(dataBundle); } @Override @Test public void testExecuteAndPostProcess() { prepareTestData(); InstructorAttributes instructor1InCourse1 = dataBundle.getInstructors().get("instructor1InCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); ______TS("Unsuccessful case: test empty feedback session name parameter"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, dataBundle.getFeedbackResponses().get("response1ForQ1S1C1").courseId }; InstructorFeedbackSubmissionEditSaveAction a; RedirectResult r; try { a = getAction(submissionParams); r = getRedirectResult(a); signalFailureToDetectException("Did not detect that parameters are null."); } catch (NullPostParameterException e) { assertEquals(String.format(Const.StatusCodes.NULL_POST_PARAMETER, Const.ParamsNames.FEEDBACK_SESSION_NAME), e.getMessage()); } ______TS("Unsuccessful case: test empty course id parameter"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_SESSION_NAME, dataBundle.getFeedbackResponses().get("response1ForQ1S1C1").feedbackSessionName }; try { a = getAction(submissionParams); r = getRedirectResult(a); signalFailureToDetectException("Did not detect that parameters are null."); } catch (NullPostParameterException e) { assertEquals(String.format(Const.StatusCodes.NULL_POST_PARAMETER, Const.ParamsNames.COURSE_ID), e.getMessage()); } ______TS("Successful case: edit existing answer"); FeedbackQuestionsDb fqDb = new FeedbackQuestionsDb(); FeedbackQuestionAttributes fq = fqDb.getFeedbackQuestion("First Session", "idOfCourse1", 1); assertNotNull("Feedback question not found in database", fq); FeedbackResponsesDb frDb = new FeedbackResponsesDb(); FeedbackResponseAttributes fr = dataBundle.getFeedbackResponses().get("response1ForQ1S1C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); instructor1InCourse1 = dataBundle.getInstructors().get("instructor1InCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "Edited" + fr.getResponseDetails().getAnswerString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination(Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); // submission confirmation email not sent if parameter does not exist verifyNoEmailsSent(a); ______TS("Successful case: deleted response"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "", Const.ParamsNames.SEND_SUBMISSION_EMAIL, "on" }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); // submission confirmation email sent verifyNumberOfEmailsSent(a, 1); EmailWrapper email = getEmailsSent(a).get(0); String courseName = coursesLogic.getCourse(fr.courseId).getName(); assertEquals(String.format(EmailType.FEEDBACK_SUBMISSION_CONFIRMATION.getSubject(), courseName, fr.feedbackSessionName), email.getSubject()); assertEquals(instructor1InCourse1.email, email.getRecipient()); ______TS("Successful case: skipped question"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "", Const.ParamsNames.SEND_SUBMISSION_EMAIL, "off" }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); // submission confirmation email not sent if parameter is not "on" verifyNoEmailsSent(a); ______TS("Successful case: new response"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "New " + fr.getResponseDetails().getAnswerString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: edit response, did not specify recipient"); fq = fqDb.getFeedbackQuestion("First Session", "idOfCourse1", 2); assertNotNull("Feedback question not found in database", fq); fr = dataBundle.getFeedbackResponses().get("response1ForQ2S1C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-2", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-2-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-2", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-2-0", "student1InCourse1@gmail.tmt", Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-2", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-2-0", "Edited" + fr.getResponseDetails().getAnswerString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: new response, did not specify recipient"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-2", "1", Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-2", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-2-0", "student1InCourse1@gmail.tmt", Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-2", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-2-0", fr.getResponseDetails().getAnswerString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: private session"); fq = fqDb.getFeedbackQuestion("Private Session", "idOfCourse1", 1); assertNotNull("Feedback question not found in database", fq); fr = dataBundle.getFeedbackResponses().get("response1ForPrivateSession"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "Edited" + fr.getResponseDetails().getAnswerString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Unsuccessful case: modified recipient to invalid recipient"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", "invalid_recipient_email", Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", fr.getResponseDetails().getAnswerString(), Const.ParamsNames.SEND_SUBMISSION_EMAIL, "on" }; a = getAction(submissionParams); r = getRedirectResult(a); assertTrue(r.isError); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "instructor1InCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, "invalid_recipient_email")); // submission confirmation email not sent if the action is an error, even with submission parameter "on" verifyNoEmailsSent(a); ______TS("Successful case: mcq: typical case"); DataBundle dataBundle = loadDataBundle("/FeedbackSessionQuestionTypeTest.json"); removeAndRestoreDataBundle(dataBundle); fq = fqDb.getFeedbackQuestion("MCQ Session", "FSQTT.idOfTypicalCourse1", 2); assertNotNull("Feedback question not found in database", fq); fr = dataBundle.getFeedbackResponses().get("response1ForQ2S1C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); instructor1InCourse1 = dataBundle.getInstructors().get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "It's perfect" }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: mcq: question skipped"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: msq: typical case"); fq = fqDb.getFeedbackQuestion("MSQ Session", "FSQTT.idOfTypicalCourse1", 2); assertNotNull("Feedback question not found in database", fq); fr = dataBundle.getFeedbackResponses().get("response1ForQ2S2C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); instructor1InCourse1 = dataBundle.getInstructors().get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "It's perfect" }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful csae: msq: question skipped"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString() }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: numerical scale: typical case"); fq = fqDb.getFeedbackQuestion("NUMSCALE Session", "FSQTT.idOfTypicalCourse1", 2); assertNotNull("Feedback question not found in database", fq); FeedbackNumericalScaleQuestionDetails fqd = (FeedbackNumericalScaleQuestionDetails) fq.getQuestionDetails(); fr = dataBundle.getFeedbackResponses().get("response1ForQ2S3C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); instructor1InCourse1 = dataBundle.getInstructors().get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "3.5", Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_MIN + "-1-0", Integer.toString(fqd.getMinScale()), Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_MAX + "-1-0", Integer.toString(fqd.getMaxScale()), Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_STEP + "-1-0", StringHelper.toDecimalFormatString(fqd.getStep()) }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: numerical scale: question skipped"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "", Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_MIN + "-1-0", Integer.toString(fqd.getMinScale()), Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_MAX + "-1-0", Integer.toString(fqd.getMaxScale()), Const.ParamsNames.FEEDBACK_QUESTION_NUMSCALE_STEP + "-1-0", StringHelper.toDecimalFormatString(fqd.getStep()) }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: const sum: typical case"); fq = fqDb.getFeedbackQuestion("CONSTSUM Session", "FSQTT.idOfTypicalCourse1", 2); assertNotNull("Feedback question not found in database", fq); fr = dataBundle.getFeedbackResponses().get("response1ForQ2S4C1"); // necessary to get the correct responseId fr = frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient); assertNotNull("Feedback response not found in database", fr); FeedbackResponseAttributes fr2 = dataBundle.getFeedbackResponses().get("response2ForQ2S4C1"); // necessary to get the correct responseId fr2 = frDb.getFeedbackResponse(fq.getId(), fr2.giver, fr2.recipient); assertNotNull("Feedback response not found in database", fr2); instructor1InCourse1 = dataBundle.getInstructors().get("instructor1OfCourse1"); gaeSimulation.loginAsInstructor(instructor1InCourse1.googleId); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "2", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "150", //Const sum question needs response to each recipient to sum up properly. Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-1", fr2.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr2.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr2.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr2.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-1", fr2.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr2.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-1", "50", }; a = getAction(submissionParams); r = getRedirectResult(a); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertFalse(r.isError); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); assertNotNull(frDb.getFeedbackResponse(fq.getId(), fr2.giver, fr2.recipient)); ______TS("Successful case: const sum: question skipped"); submissionParams = new String[]{ Const.ParamsNames.FEEDBACK_QUESTION_RESPONSETOTAL + "-1", "1", Const.ParamsNames.FEEDBACK_RESPONSE_ID + "-1-0", fr.getId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fr.feedbackSessionName, Const.ParamsNames.COURSE_ID, fr.courseId, Const.ParamsNames.FEEDBACK_QUESTION_ID + "-1", fr.feedbackQuestionId, Const.ParamsNames.FEEDBACK_RESPONSE_RECIPIENT + "-1-0", fr.recipient, Const.ParamsNames.FEEDBACK_QUESTION_TYPE + "-1", fr.feedbackQuestionType.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_TEXT + "-1-0", "" }; a = getAction(submissionParams); r = getRedirectResult(a); assertFalse(r.isError); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, r.isError, "FSQTT.idOfInstructor1OfCourse1"), r.getDestinationWithParams()); assertNull(frDb.getFeedbackResponse(fq.getId(), fr.giver, fr.recipient)); ______TS("Successful case: contrib qn: typical case"); // No tests since contrib qn can only be answered by students to own team members including self. } @Test public void testGracePeriodExecuteAndPostProcess() throws Exception { dataBundle = loadDataBundle("/InstructorFeedbackSubmissionEditSaveActionTest.json"); FeedbackSessionsDb feedbackSessionDb = new FeedbackSessionsDb(); FeedbackSessionAttributes fs = dataBundle.getFeedbackSessions().get("Grace Period Session"); InstructorAttributes instructor = dataBundle.getInstructors().get("instructor1InCourse1"); gaeSimulation.loginAsInstructor(instructor.googleId); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName() }; ______TS("opened"); fs.setEndTime(TimeHelper.getDateOffsetToCurrentTime(1)); feedbackSessionDb.updateFeedbackSession(fs); assertTrue(fs.isOpened()); assertFalse(fs.isInGracePeriod()); InstructorFeedbackSubmissionEditSaveAction a = getAction(submissionParams); RedirectResult r = getRedirectResult(a); assertEquals( getPageResultDestination( Const.ActionURIs.INSTRUCTOR_HOME_PAGE, false, "instructor1InCourse1"), r.getDestinationWithParams()); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertFalse(r.isError); ______TS("during grace period"); fs.setEndTime(TimeHelper.getDateOffsetToCurrentTime(0)); feedbackSessionDb.updateFeedbackSession(fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); a = getAction(submissionParams); r = getRedirectResult(a); assertEquals( getPageResultDestination(Const.ActionURIs.INSTRUCTOR_HOME_PAGE, false, "instructor1InCourse1"), r.getDestinationWithParams()); assertEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, r.getStatusMessage()); assertFalse(r.isError); ______TS("after grace period"); fs.setEndTime(TimeHelper.getDateOffsetToCurrentTime(-10)); feedbackSessionDb.updateFeedbackSession(fs); assertFalse(fs.isOpened()); assertFalse(fs.isInGracePeriod()); a = getAction(submissionParams); r = getRedirectResult(a); assertEquals(Const.StatusMessages.FEEDBACK_SUBMISSIONS_NOT_OPEN, r.getStatusMessage()); } @Override protected InstructorFeedbackSubmissionEditSaveAction getAction(String... params) { return (InstructorFeedbackSubmissionEditSaveAction) gaeSimulation.getActionObject(getActionUri(), params); } @Override @Test protected void testAccessControl() throws Exception { dataBundle = getTypicalDataBundle(); FeedbackSessionAttributes fs = dataBundle.getFeedbackSessions().get("session1InCourse1"); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName() }; verifyUnaccessibleWithoutSubmitSessionInSectionsPrivilege(submissionParams); verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); testGracePeriodAccessControlForInstructors(); } private void testGracePeriodAccessControlForInstructors() throws Exception { dataBundle = getTypicalDataBundle(); FeedbackSessionAttributes fs = dataBundle.getFeedbackSessions().get("gracePeriodSession"); closeSession(fs); assertFalse(fs.isOpened()); assertTrue(fs.isInGracePeriod()); assertFalse(fs.isClosed()); String[] submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, fs.getCourseId(), Const.ParamsNames.FEEDBACK_SESSION_NAME, fs.getFeedbackSessionName() }; verifyOnlyInstructorsOfTheSameCourseCanAccess(submissionParams); } private void closeSession(FeedbackSessionAttributes fs) throws Exception { fs.setEndTime(TimeHelper.getDateOffsetToCurrentTime(0)); fsDb.updateFeedbackSession(fs); } }
Gorgony/teammates
src/test/java/teammates/test/cases/action/InstructorFeedbackSubmissionEditSaveActionTest.java
Java
gpl-2.0
34,801
/* * 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.io.monitor; import java.io.File; import java.io.Serializable; /** * {@link FileEntry} represents the state of a file or directory, capturing * the following {@link File} attributes at a point in time. * <ul> * <li>File Name (see {@link File#getName()})</li> * <li>Exists - whether the file exists or not (see {@link File#exists()})</li> * <li>Directory - whether the file is a directory or not (see {@link File#isDirectory()})</li> * <li>Last Modified Date/Time (see {@link File#lastModified()})</li> * <li>Length (see {@link File#length()}) - directories treated as zero</li> * <li>Children - contents of a directory (see {@link File#listFiles(java.io.FileFilter)})</li> * </ul> * <p> * <h3>Custom Implementations</h3> * If the state of additional {@link File} attributes is required then create a custom * {@link FileEntry} with properties for those attributes. Override the * {@link #newChildInstance(File)} to return a new instance of the appropriate type. * You may also want to override the {@link #refresh(File)} method. * @see FileAlterationObserver * @since 2.0 */ public class FileEntry implements Serializable { static final FileEntry[] EMPTY_ENTRIES = new FileEntry[0]; private final FileEntry parent; private FileEntry[] children; private final File file; private String name; private boolean exists; private boolean directory; private long lastModified; private long length; /** * Construct a new monitor for a specified {@link File}. * * @param file The file being monitored */ public FileEntry(File file) { this((FileEntry)null, file); } /** * Construct a new monitor for a specified {@link File}. * * @param parent The parent * @param file The file being monitored */ public FileEntry(FileEntry parent, File file) { if (file == null) { throw new IllegalArgumentException("File is missing"); } this.file = file; this.parent = parent; this.name = file.getName(); } /** * Refresh the attributes from the {@link File}, indicating * whether the file has changed. * <p> * This implementation refreshes the <code>name</code>, <code>exists</code>, * <code>directory</code>, <code>lastModified</code> and <code>length</code> * properties. * <p> * The <code>exists</code>, <code>directory</code>, <code>lastModified</code> * and <code>length</code> properties are compared for changes * * @param file the file instance to compare to * @return <code>true</code> if the file has changed, otherwise <code>false</code> */ public boolean refresh(File file) { // cache original values boolean origExists = exists; long origLastModified = lastModified; boolean origDirectory = directory; long origLength = length; // refresh the values name = file.getName(); exists = file.exists(); directory = exists ? file.isDirectory() : false; lastModified = exists ? file.lastModified() : 0; length = exists && !directory ? file.length() : 0; // Return if there are changes return exists != origExists || lastModified != origLastModified || directory != origDirectory || length != origLength; } /** * Create a new child instance. * <p> * Custom implementations should override this method to return * a new instance of the appropriate type. * * @param file The child file * @return a new child instance */ public FileEntry newChildInstance(File file) { return new FileEntry(this, file); } /** * Return the parent entry. * * @return the parent entry */ public FileEntry getParent() { return parent; } /** * Return the level * * @return the level */ public int getLevel() { return parent == null ? 0 : parent.getLevel() + 1; } /** * Return the directory's files. * * @return This directory's files or an empty * array if the file is not a directory or the * directory is empty */ public FileEntry[] getChildren() { return children != null ? children : EMPTY_ENTRIES; } /** * Set the directory's files. * * @param children This directory's files, may be null */ public void setChildren(FileEntry[] children) { this.children = children; } /** * Return the file being monitored. * * @return the file being monitored */ public File getFile() { return file; } /** * Return the file name. * * @return the file name */ public String getName() { return name; } /** * Set the file name. * * @param name the file name */ public void setName(String name) { this.name = name; } /** * Return the last modified time from the last time it * was checked. * * @return the last modified time */ public long getLastModified() { return lastModified; } /** * Return the last modified time from the last time it * was checked. * * @param lastModified The last modified time */ public void setLastModified(long lastModified) { this.lastModified = lastModified; } /** * Return the length. * * @return the length */ public long getLength() { return length; } /** * Set the length. * * @param length the length */ public void setLength(long length) { this.length = length; } /** * Indicate whether the file existed the last time it * was checked. * * @return whether the file existed */ public boolean isExists() { return exists; } /** * Set whether the file existed the last time it * was checked. * * @param exists whether the file exists or not */ public void setExists(boolean exists) { this.exists = exists; } /** * Indicate whether the file is a directory or not. * * @return whether the file is a directory or not */ public boolean isDirectory() { return directory; } /** * Set whether the file is a directory or not. * * @param directory whether the file is a directory or not */ public void setDirectory(boolean directory) { this.directory = directory; } }
BIORIMP/biorimp
BIO-RIMP/test_data/code/cio/src/main/java/org/apache/commons/io/monitor/FileEntry.java
Java
gpl-2.0
7,542
package com.lj.learning.dao; // THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS // KEEP INCLUDES - put your custom includes here // KEEP INCLUDES END /** * Entity mapped to table "SHEET". */ public class Sheet implements java.io.Serializable { private Long id; /** Not-null value. */ /** * 表格页签名称 */ private String sheetname; /** Not-null value. */ /** * 数据库表名称 */ private String databasename; // KEEP FIELDS - put your custom fields here // KEEP FIELDS END public Sheet() { } public Sheet(Long id) { this.id = id; } public Sheet(Long id, String sheetname, String databasename) { this.id = id; this.sheetname = sheetname; this.databasename = databasename; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** Not-null value. */ public String getSheetname() { return sheetname; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setSheetname(String sheetname) { this.sheetname = sheetname; } /** Not-null value. */ public String getDatabasename() { return databasename; } /** Not-null value; ensure this value is available before it is saved to the database. */ public void setDatabasename(String databasename) { this.databasename = databasename; } // KEEP METHODS - put your custom methods here // KEEP METHODS END }
wbhqf3/test
Learning/app/src/main/java/com/lj/learning/dao/Sheet.java
Java
gpl-2.0
1,601
public class ValueGenerator { }
DB-SE/isp2014.marcus.kamieth
Algorithms_DataStructures_AspectJ/src/base/ValueGenerator.java
Java
gpl-2.0
35
package remasterkit; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.border.TitledBorder; import javax.swing.border.LineBorder; import java.awt.Color; import java.awt.Toolkit; import javax.swing.JButton; import java.awt.Font; import javax.swing.JCheckBox; import com.jtattoo.plaf.graphite.GraphiteLookAndFeel; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JTextField; public class Menu_Utama extends JFrame { private JPanel contentPane; private JTextField txtName; private JTextField txtURL; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(new GraphiteLookAndFeel()); Menu_Utama frame = new Menu_Utama(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Menu_Utama() { setIconImage(Toolkit.getDefaultToolkit().getImage("/home/newbieilmu/workspace/app.remasterkit/src/icon/logo.png")); setTitle("RemasterKit(Custom Linuxmu Sesuka Hati)"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 589, 357); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panelRKit = new JPanel(); panelRKit.setBorder(new TitledBorder(null, "RemasterKit", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelRKit.setBounds(146, 12, 421, 163); contentPane.add(panelRKit); panelRKit.setLayout(null); JLabel lblPilihDe = new JLabel("1. Pilih DE "); lblPilihDe.setBounds(12, 27, 105, 18); panelRKit.add(lblPilihDe); JComboBox cmbDE = new JComboBox(); cmbDE.setModel(new DefaultComboBoxModel(new String[] {"LXDE", "MATE", "GNOME", "KDE", "Manokwari"})); cmbDE.setBounds(110, 24, 89, 24); panelRKit.add(cmbDE); JLabel lblUbahSourcelist = new JLabel("2. Source.List"); lblUbahSourcelist.setBounds(12, 57, 105, 18); panelRKit.add(lblUbahSourcelist); JLabel lblPilihConsole = new JLabel("3. Console "); lblPilihConsole.setBounds(12, 87, 105, 18); panelRKit.add(lblPilihConsole); JLabel lblInstallDeb = new JLabel("4. Install DEB"); lblInstallDeb.setBounds(12, 117, 105, 18); panelRKit.add(lblInstallDeb); JLabel lblPaketList = new JLabel("5. Paket List "); lblPaketList.setBounds(217, 27, 105, 18); panelRKit.add(lblPaketList); JLabel lblSynaptic = new JLabel("6. Synaptic "); lblSynaptic.setBounds(217, 58, 105, 18); panelRKit.add(lblSynaptic); JLabel lblDesktop = new JLabel("7. Desktop"); lblDesktop.setBounds(217, 88, 105, 18); panelRKit.add(lblDesktop); JLabel lblUbiquity = new JLabel("8. Ubiquity"); lblUbiquity.setBounds(217, 120, 105, 18); panelRKit.add(lblUbiquity); JButton btnSource = new JButton("Source.list"); btnSource.setEnabled(false); btnSource.setBounds(110, 54, 86, 24); panelRKit.add(btnSource); JButton btnConsole = new JButton("Console"); btnConsole.setEnabled(false); btnConsole.setBounds(110, 84, 86, 24); panelRKit.add(btnConsole); JButton btnDeb = new JButton("DEB"); btnDeb.setEnabled(false); btnDeb.setBounds(110, 114, 86, 24); panelRKit.add(btnDeb); JButton btnPaketList = new JButton("Paket list"); btnPaketList.setEnabled(false); btnPaketList.setBounds(309, 24, 86, 24); panelRKit.add(btnPaketList); JButton btnSynaptic = new JButton("Synaptic"); btnSynaptic.setEnabled(false); btnSynaptic.setBounds(309, 55, 86, 24); panelRKit.add(btnSynaptic); JButton btnDekstop = new JButton("Dekstop"); btnDekstop.setEnabled(false); btnDekstop.setBounds(309, 87, 86, 24); panelRKit.add(btnDekstop); JButton btnUbiquity = new JButton("Ubiquity"); btnUbiquity.setEnabled(false); btnUbiquity.setBounds(309, 117, 86, 24); panelRKit.add(btnUbiquity); JButton btnAbout = new JButton("Tentang"); btnAbout.setBounds(299, 280, 86, 31); contentPane.add(btnAbout); JButton btnCredits = new JButton("Kredits"); btnCredits.setBounds(389, 280, 86, 31); contentPane.add(btnCredits); JButton btnLisensi = new JButton("Lisensi"); btnLisensi.setBounds(481, 280, 86, 31); contentPane.add(btnLisensi); JLabel lblIcon1 = new JLabel(""); lblIcon1.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533657__settings.png")); lblIcon1.setBounds(12, 12, 55, 67); contentPane.add(lblIcon1); JLabel lblicon2 = new JLabel(""); lblicon2.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533644_Import.png")); lblicon2.setBounds(12, 72, 55, 67); contentPane.add(lblicon2); JLabel lblicon3 = new JLabel(""); lblicon3.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374533631_Export.png")); lblicon3.setBounds(12, 137, 55, 67); contentPane.add(lblicon3); JLabel lblicon4 = new JLabel(""); lblicon4.setIcon(new ImageIcon("/home/newbieilmu/workspace/app.remasterkit/src/icon/1374534090_118.png")); lblicon4.setBounds(12, 202, 55, 67); contentPane.add(lblicon4); JLabel lblKonfigurasi = new JLabel("Konfigurasi"); lblKonfigurasi.setFont(new Font("Dialog", Font.BOLD, 13)); lblKonfigurasi.setBounds(67, 35, 86, 18); contentPane.add(lblKonfigurasi); JLabel lblImport = new JLabel("Import"); lblImport.setFont(new Font("Dialog", Font.BOLD, 13)); lblImport.setBounds(67, 91, 86, 18); contentPane.add(lblImport); JLabel lblEksport = new JLabel("Eksport"); lblEksport.setFont(new Font("Dialog", Font.BOLD, 13)); lblEksport.setBounds(67, 151, 86, 18); contentPane.add(lblEksport); JLabel lblBuild = new JLabel("Build"); lblBuild.setFont(new Font("Dialog", Font.BOLD, 13)); lblBuild.setBounds(67, 216, 86, 18); contentPane.add(lblBuild); JPanel panelSetting = new JPanel(); panelSetting.setBorder(new TitledBorder(null, "Setting ", TitledBorder.LEADING, TitledBorder.TOP, null, null)); panelSetting.setBounds(146, 181, 421, 88); contentPane.add(panelSetting); panelSetting.setLayout(null); JLabel lblNamaLinuxmu = new JLabel("Nama Linuxmu :"); lblNamaLinuxmu.setBounds(12, 24, 92, 18); panelSetting.add(lblNamaLinuxmu); txtName = new JTextField(); txtName.setColumns(10); txtName.setBounds(122, 22, 179, 22); panelSetting.add(txtName); JLabel lblUrl = new JLabel("URL :"); lblUrl.setBounds(12, 54, 92, 18); panelSetting.add(lblUrl); txtURL = new JTextField(); txtURL.setColumns(10); txtURL.setBounds(122, 52, 179, 22); panelSetting.add(txtURL); JButton btnDonasi = new JButton("Donasi"); btnDonasi.setBounds(207, 280, 86, 31); contentPane.add(btnDonasi); } }
anugrahbsoe/RemasterKit
app.remasterkit/src/remasterkit/Menu_Utama.java
Java
gpl-2.0
6,973
package com.algebraweb.editor.client; import com.google.gwt.user.client.ui.Button; /** * A button for the control panel. Will be styled accordingly. * * @author Patrick Brosi * */ public class ControlPanelButton extends Button { public ControlPanelButton(String desc) { super(); this.addStyleName("controllpanel-button"); super.getElement().setAttribute("title", desc); this.setWidth("39px"); this.setHeight("39px"); } public ControlPanelButton(String desc, String styleClass) { this(desc); this.addStyleName("controllbutton-" + styleClass); } }
patrickbr/ferryleaks
src/com/algebraweb/editor/client/ControlPanelButton.java
Java
gpl-2.0
573
package com.omnicrola.panoptes.ui.autocomplete; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; import org.junit.Test; import com.omnicrola.panoptes.control.DataController; import com.omnicrola.panoptes.control.IControlObserver; import com.omnicrola.panoptes.control.TimeblockSet; import com.omnicrola.panoptes.data.IReadTimeblock; import com.omnicrola.panoptes.data.TimeData; import com.omnicrola.testing.util.EnhancedTestCase; public class CardNumberProviderTest extends EnhancedTestCase { private DataController mockController; private String expectedNumber1; private String expectedNumber2; private String expectedNumber3; @Test public void testImplementsInterfaces() throws Exception { assertImplementsInterface(IOptionProvider.class, CardNumberProvider.class); assertImplementsInterface(IControlObserver.class, CardNumberProvider.class); } @Test public void testConstructorParams() throws Exception { DataController mockController = useMock(DataController.class); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(mockController); assertConstructionParamSame("dataController", mockController, cardNumberProvider); } @Test public void testDataChanged_UpdatesOptionList() throws Exception { setupMockTimeblockSet(); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(this.mockController); assertEquals(0, cardNumberProvider.getOptionsList().size()); cardNumberProvider.dataChanged(); List<Object> optionsList = cardNumberProvider.getOptionsList(); assertEquals(3, optionsList.size()); assertTrue(optionsList.contains(this.expectedNumber1)); assertTrue(optionsList.contains(this.expectedNumber2)); assertTrue(optionsList.contains(this.expectedNumber3)); } @Test public void testTimeblockSetChanged_UpdatesOptionList() throws Exception { TimeblockSet mockTimeblockSet = useMock(TimeblockSet.class); setupMockTimeblockSet(); startReplay(); CardNumberProvider cardNumberProvider = new CardNumberProvider(this.mockController); assertEquals(0, cardNumberProvider.getOptionsList().size()); cardNumberProvider.timeblockSetChanged(mockTimeblockSet); List<Object> optionsList = cardNumberProvider.getOptionsList(); assertEquals(3, optionsList.size()); assertTrue(optionsList.contains(this.expectedNumber1)); assertTrue(optionsList.contains(this.expectedNumber2)); assertTrue(optionsList.contains(this.expectedNumber3)); } public void setupMockTimeblockSet() { TimeblockSet mockTimeblockSet = useMock(TimeblockSet.class); this.expectedNumber1 = "cardnumber"; this.expectedNumber2 = "a different number"; this.expectedNumber3 = "duplicate"; IReadTimeblock mockTimeblock1 = createMockBlockWithCardNumber(this.expectedNumber1); IReadTimeblock mockTimeblock2 = createMockBlockWithCardNumber(this.expectedNumber2); IReadTimeblock mockTimeblock3 = createMockBlockWithCardNumber(this.expectedNumber3); IReadTimeblock mockTimeblock4 = createMockBlockWithCardNumber(this.expectedNumber3); List<IReadTimeblock> timblocks = Arrays.asList(mockTimeblock1, mockTimeblock2, mockTimeblock3, mockTimeblock4); expect(mockTimeblockSet.getBlockSet()).andReturn(timblocks); this.mockController = useMock(DataController.class); expect(this.mockController.getAllTimeblocks()).andReturn(mockTimeblockSet); } private IReadTimeblock createMockBlockWithCardNumber(String expectedNumber) { IReadTimeblock mockTimeblock = useMock(IReadTimeblock.class); TimeData mockData = useMock(TimeData.class); expect(mockTimeblock.getTimeData()).andReturn(mockData); expect(mockData.getCard()).andReturn(expectedNumber); return mockTimeblock; } }
Omnicrola/Panoptes
Panoptes.Test/src/com/omnicrola/panoptes/ui/autocomplete/CardNumberProviderTest.java
Java
gpl-2.0
3,813
package com.rideon.web.security; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.springframework.web.client.RestTemplate; public class ClientAuthenticator { public ClientAuthenticator() { super(); } // API public static void setAuthentication(final RestTemplate restTemplate, final String username, final String password) { basicAuth(restTemplate, username, password); } private static void basicAuth(final RestTemplate restTemplate, final String username, final String password) { final HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = ((HttpComponentsClientHttpRequestFactoryBasicAuth) restTemplate.getRequestFactory()); DefaultHttpClient httpClient = (DefaultHttpClient) requestFactory.getHttpClient(); CredentialsProvider prov = httpClient.getCredentialsProvider(); prov.setCredentials(requestFactory.getAuthScope(), new UsernamePasswordCredentials(username, password)); } }
vilasmaciel/rideon
rideon-client/src/main/java/com/rideon/web/security/ClientAuthenticator.java
Java
gpl-2.0
1,128
/* * Copyright 2006-2020 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package io.github.mzmine.parameters.parametertypes.ranges; import java.text.NumberFormat; import java.util.Collection; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.google.common.collect.Range; import io.github.mzmine.parameters.UserParameter; public class DoubleRangeParameter implements UserParameter<Range<Double>, DoubleRangeComponent> { private final String name, description; protected final boolean valueRequired; private final boolean nonEmptyRequired; private NumberFormat format; private Range<Double> value; private Range<Double> maxAllowedRange; public DoubleRangeParameter(String name, String description, NumberFormat format) { this(name, description, format, true, false, null); } public DoubleRangeParameter(String name, String description, NumberFormat format, Range<Double> defaultValue) { this(name, description, format, true, false, defaultValue); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, Range<Double> defaultValue) { this(name, description, format, valueRequired, false, defaultValue); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, boolean nonEmptyRequired, Range<Double> defaultValue) { this(name, description, format, valueRequired, nonEmptyRequired, defaultValue, null); } public DoubleRangeParameter(String name, String description, NumberFormat format, boolean valueRequired, boolean nonEmptyRequired, Range<Double> defaultValue, Range<Double> maxAllowedRange) { this.name = name; this.description = description; this.format = format; this.valueRequired = valueRequired; this.nonEmptyRequired = nonEmptyRequired; this.value = defaultValue; this.maxAllowedRange = maxAllowedRange; } /** * @see io.github.mzmine.data.Parameter#getName() */ @Override public String getName() { return name; } /** * @see io.github.mzmine.data.Parameter#getDescription() */ @Override public String getDescription() { return description; } public boolean isValueRequired() { return valueRequired; } @Override public DoubleRangeComponent createEditingComponent() { return new DoubleRangeComponent(format); } public Range<Double> getValue() { return value; } @Override public void setValue(Range<Double> value) { this.value = value; } @Override public DoubleRangeParameter cloneParameter() { DoubleRangeParameter copy = new DoubleRangeParameter(name, description, format); copy.setValue(this.getValue()); return copy; } @Override public void setValueFromComponent(DoubleRangeComponent component) { value = component.getValue(); } @Override public void setValueToComponent(DoubleRangeComponent component, Range<Double> newValue) { component.setValue(newValue); } @Override public void loadValueFromXML(Element xmlElement) { NodeList minNodes = xmlElement.getElementsByTagName("min"); if (minNodes.getLength() != 1) return; NodeList maxNodes = xmlElement.getElementsByTagName("max"); if (maxNodes.getLength() != 1) return; String minText = minNodes.item(0).getTextContent(); String maxText = maxNodes.item(0).getTextContent(); double min = Double.valueOf(minText); double max = Double.valueOf(maxText); value = Range.closed(min, max); } @Override public void saveValueToXML(Element xmlElement) { if (value == null) return; Document parentDocument = xmlElement.getOwnerDocument(); Element newElement = parentDocument.createElement("min"); newElement.setTextContent(String.valueOf(value.lowerEndpoint())); xmlElement.appendChild(newElement); newElement = parentDocument.createElement("max"); newElement.setTextContent(String.valueOf(value.upperEndpoint())); xmlElement.appendChild(newElement); } @Override public boolean checkValue(Collection<String> errorMessages) { if (valueRequired && (value == null)) { errorMessages.add(name + " is not set properly"); return false; } if (value != null) { if (!nonEmptyRequired && value.lowerEndpoint() > value.upperEndpoint()) { errorMessages.add(name + " range maximum must be higher than minimum, or equal"); return false; } if (nonEmptyRequired && value.lowerEndpoint() >= value.upperEndpoint()) { errorMessages.add(name + " range maximum must be higher than minimum"); return false; } } if (value != null && maxAllowedRange != null) { if (maxAllowedRange.intersection(value) != value) { errorMessages.add(name + " must be within " + maxAllowedRange.toString()); return false; } } return true; } }
tomas-pluskal/mzmine3
src/main/java/io/github/mzmine/parameters/parametertypes/ranges/DoubleRangeParameter.java
Java
gpl-2.0
5,669
/* * RapidMiner * * Copyright (C) 2001-2008 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.tools; import java.awt.Component; import java.awt.Dialog; import java.awt.Frame; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * Some utils for the creation of a modal progress monitor dialog. * * @author Santhosh Kumar, Ingo Mierswa * @version $Id: ProgressUtils.java,v 1.3 2008/05/09 19:22:59 ingomierswa Exp $ */ public class ProgressUtils { static class MonitorListener implements ChangeListener, ActionListener { private ProgressMonitor monitor; private Window owner; private Timer timer; private boolean modal; public MonitorListener(Window owner, ProgressMonitor monitor, boolean modal) { this.owner = owner; this.monitor = monitor; this.modal = modal; } public void stateChanged(ChangeEvent ce) { ProgressMonitor monitor = (ProgressMonitor) ce.getSource(); if (monitor.getCurrent() != monitor.getTotal()) { if (timer == null) { timer = new Timer(monitor.getWaitingTime(), this); timer.setRepeats(false); timer.start(); } } else { if (timer != null && timer.isRunning()) timer.stop(); monitor.removeChangeListener(this); } } public void actionPerformed(ActionEvent e) { monitor.removeChangeListener(this); ProgressDialog dlg = owner instanceof Frame ? new ProgressDialog((Frame) owner, monitor, modal) : new ProgressDialog((Dialog) owner, monitor, modal); dlg.pack(); dlg.setLocationRelativeTo(null); dlg.setVisible(true); } } /** Create a new (modal) progress monitor dialog. Please note the the value for total (the maximum * number of possible steps) is greater then 0 even for indeterminate progresses. The value * of waitingTime is used before the dialog is actually created and shown. */ public static ProgressMonitor createModalProgressMonitor(Component owner, int total, boolean indeterminate, int waitingTimeBeforeDialogAppears, boolean modal) { ProgressMonitor monitor = new ProgressMonitor(total, indeterminate, waitingTimeBeforeDialogAppears); Window window = owner instanceof Window ? (Window) owner : SwingUtilities.getWindowAncestor(owner); monitor.addChangeListener(new MonitorListener(window, monitor, modal)); return monitor; } }
ntj/ComplexRapidMiner
src/com/rapidminer/gui/tools/ProgressUtils.java
Java
gpl-2.0
3,354
package org.mo.jfa.face.database.connector; import org.mo.web.core.container.AContainer; import org.mo.web.core.webform.IFormPage; import org.mo.web.protocol.context.IWebContext; public interface IConnectorAction { String catalog(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String list(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String sort(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String insert(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String update(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); String delete(IWebContext context, @AContainer(name = IFormPage.Page) FConnectorPage page); }
favedit/MoPlatform
mo-4-web/src/web-face/org/mo/jfa/face/database/connector/IConnectorAction.java
Java
gpl-2.0
890
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.epl.join.rep; import com.espertech.esper.client.EventBean; import com.espertech.esper.support.epl.join.SupportJoinResultNodeFactory; import com.espertech.esper.support.event.SupportEventBeanFactory; import java.util.*; import junit.framework.TestCase; public class TestRepositoryImpl extends TestCase { private EventBean s0Event; private RepositoryImpl repository; public void setUp() { s0Event = SupportEventBeanFactory.createObject(new Object()); repository = new RepositoryImpl(0, s0Event, 6); } public void testGetCursors() { // get cursor for root stream lookup Iterator<Cursor> it = repository.getCursors(0); assertTrue(it.hasNext()); Cursor cursor = it.next(); assertSame(s0Event, cursor.getTheEvent()); assertSame(0, cursor.getStream()); assertFalse(it.hasNext()); tryIteratorEmpty(it); // try invalid get cursor for no results try { repository.getCursors(2); fail(); } catch (NullPointerException ex) { // expected } } public void testAddResult() { Set<EventBean> results = SupportJoinResultNodeFactory.makeEventSet(2); repository.addResult(repository.getCursors(0).next(), results, 1); assertEquals(1, repository.getNodesPerStream()[1].size()); try { repository.addResult(repository.getCursors(0).next(), new HashSet<EventBean>(), 1); fail(); } catch (IllegalArgumentException ex) { // expected } try { repository.addResult(repository.getCursors(0).next(), null, 1); fail(); } catch (NullPointerException ex) { // expected } } public void testFlow() { // Lookup from s0 Cursor cursors[] = read(repository.getCursors(0)); assertEquals(1, cursors.length); Set<EventBean> resultsS1 = SupportJoinResultNodeFactory.makeEventSet(2); repository.addResult(cursors[0], resultsS1, 1); // Lookup from s1 cursors = read(repository.getCursors(1)); assertEquals(2, cursors.length); Set<EventBean> resultsS2[] = SupportJoinResultNodeFactory.makeEventSets(new int[] {2, 3}); repository.addResult(cursors[0], resultsS2[0], 2); repository.addResult(cursors[1], resultsS2[1], 2); // Lookup from s2 cursors = read(repository.getCursors(2)); assertEquals(5, cursors.length); // 2 + 3 for s2 Set<EventBean> resultsS3[] = SupportJoinResultNodeFactory.makeEventSets(new int[] {2, 1, 3, 5, 1}); repository.addResult(cursors[0], resultsS3[0], 3); repository.addResult(cursors[1], resultsS3[1], 3); repository.addResult(cursors[2], resultsS3[2], 3); repository.addResult(cursors[3], resultsS3[3], 3); repository.addResult(cursors[4], resultsS3[4], 3); // Lookup from s3 cursors = read(repository.getCursors(3)); assertEquals(12, cursors.length); } private void tryIteratorEmpty(Iterator it) { try { it.next(); fail(); } catch (NoSuchElementException ex) { // expected } } private Cursor[] read(Iterator<Cursor> iterator) { List<Cursor> cursors = new ArrayList<Cursor>(); while (iterator.hasNext()) { Cursor cursor = iterator.next(); cursors.add(cursor); } return cursors.toArray(new Cursor[0]); } }
sungsoo/esper
esper/src/test/java/com/espertech/esper/epl/join/rep/TestRepositoryImpl.java
Java
gpl-2.0
4,571
package doodle; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Comparator; import java.util.Date; /** * A poll is made up of two or more time slots, which are voted on by poll * invitees. A time slot is defined by a start datetime and optionally an end * datetime. * * @author Jonas Michel * */ public class TimeSlot implements Serializable { private static final long serialVersionUID = -8690469227753138784L; /** The time slot's start time. */ private Date start = null; /** The time slot's end time (optional). */ private Date end = null; public TimeSlot(Date start, Date end) { this.start = start; this.end = end; } public TimeSlot(Date start) { this.start = start; } public TimeSlot(Date day, String timeStr) throws NumberFormatException { if (timeStr.contains("-")) initDoubleTime(day, timeStr); else initSingleTime(day, timeStr); } public Date getStart() { return start; } public Date getEnd() { return end; } private void initSingleTime(Date day, String timeStr) throws NumberFormatException { start = parseTimeString(day, timeStr); } private void initDoubleTime(Date day, String timeStr) throws NumberFormatException { String[] timeStrArr = timeStr.split("-"); start = parseTimeString(day, timeStrArr[0]); end = parseTimeString(day, timeStrArr[1]); } private Date parseTimeString(Date day, String timeStr) throws NumberFormatException { int hour = 0, minute = 0; if (timeStr.contains(":")) { hour = Integer.parseInt(timeStr.split(":")[0]); minute = Integer.parseInt(timeStr.split(":")[1]); } else { hour = Integer.parseInt(timeStr); } Calendar cal = Calendar.getInstance(); cal.setTime(day); cal.add(Calendar.HOUR_OF_DAY, hour); cal.add(Calendar.MINUTE, minute); return cal.getTime(); } public String toDayString() { SimpleDateFormat day = new SimpleDateFormat("MM/dd/yyyy"); return day.format(start); } public String toTimeString() { SimpleDateFormat time = new SimpleDateFormat("HH:mm"); StringBuilder sb = new StringBuilder(); sb.append(time.format(start)); if (end == null) return sb.toString(); sb.append("-" + time.format(end)); return sb.toString(); } @Override public String toString() { return toDayString() + " " + toTimeString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((end == null) ? 0 : end.hashCode()); result = prime * result + ((start == null) ? 0 : start.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TimeSlot)) return false; TimeSlot other = (TimeSlot) obj; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; return true; } public static class TimeSlotComparator implements Comparator<TimeSlot> { @Override public int compare(TimeSlot ts1, TimeSlot ts2) { if (ts1.getStart().before(ts2.getStart())) return -1; else if (ts1.getStart().after(ts2.getStart())) return 1; else return 0; } } }
jonasrmichel/jms-doodle-poll
joram-jms/samples/src/joram/doodle/TimeSlot.java
Java
gpl-2.0
3,355
package tim.prune.threedee; import java.awt.event.InputEvent; /* * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * * Copyright (c) 2021 ActivityWorkshop simplifications and renamings, * and restriction to upright orientations. */ import java.awt.event.MouseEvent; import java.awt.AWTEvent; import javax.media.j3d.Transform3D; import javax.media.j3d.Canvas3D; import javax.vecmath.Vector3d; import javax.vecmath.Point3d; import javax.vecmath.Matrix3d; import com.sun.j3d.utils.behaviors.vp.ViewPlatformAWTBehavior; import com.sun.j3d.utils.universe.ViewingPlatform; /** * Moves the View around a point of interest when the mouse is dragged with * a mouse button pressed. Includes rotation, zoom, and translation * actions. Zooming can also be obtained by using mouse wheel. * <p> * The rotate action rotates the ViewPlatform around the point of interest * when the mouse is moved with the main mouse button pressed. The * rotation is in the direction of the mouse movement, with a default * rotation of 0.01 radians for each pixel of mouse movement. * <p> * The zoom action moves the ViewPlatform closer to or further from the * point of interest when the mouse is moved with the middle mouse button * pressed (or Alt-main mouse button on systems without a middle mouse button). * The default zoom action is to translate the ViewPlatform 0.01 units for each * pixel of mouse movement. Moving the mouse up moves the ViewPlatform closer, * moving the mouse down moves the ViewPlatform further away. * <p> * The translate action translates the ViewPlatform when the mouse is moved * with the right mouse button pressed. The translation is in the direction * of the mouse movement, with a default translation of 0.01 units for each * pixel of mouse movement. * <p> * The actions can be reversed using the <code>REVERSE_</code><i>ACTION</i> * constructor flags. The default action moves the ViewPlatform around the * objects in the scene. The <code>REVERSE_</code><i>ACTION</i> flags can * make the objects in the scene appear to be moving in the direction * of the mouse movement. */ public class UprightOrbiter extends ViewPlatformAWTBehavior { private Transform3D _longitudeTransform = new Transform3D(); private Transform3D _latitudeTransform = new Transform3D(); private Transform3D _rotateTransform = new Transform3D(); // needed for integrateTransforms but don't want to new every time private Transform3D _temp1 = new Transform3D(); private Transform3D _temp2 = new Transform3D(); private Transform3D _translation = new Transform3D(); private Vector3d _transVector = new Vector3d(); private Vector3d _distanceVector = new Vector3d(); private Vector3d _centerVector = new Vector3d(); private Vector3d _invertCenterVector = new Vector3d(); private double _deltaYaw = 0.0, _deltaPitch = 0.0; private double _startDistanceFromCenter = 20.0; private double _distanceFromCenter = 20.0; private Point3d _rotationCenter = new Point3d(); private Matrix3d _rotMatrix = new Matrix3d(); private int _mouseX = 0, _mouseY = 0; private double _xtrans = 0.0, _ytrans = 0.0, _ztrans = 0.0; private static final double MIN_RADIUS = 0.0; // the factor to be applied to wheel zooming so that it does not // look much different with mouse movement zooming. private static final float wheelZoomFactor = 50.0f; private static final double NOMINAL_ZOOM_FACTOR = .01; private static final double NOMINAL_ROT_FACTOR = .008; private static final double NOMINAL_TRANS_FACTOR = .003; private double _pitchAngle = 0.0; /** * Creates a new OrbitBehaviour * @param inCanvas The Canvas3D to add the behaviour to * @param inInitialPitch pitch angle in degrees */ public UprightOrbiter(Canvas3D inCanvas, double inInitialPitch) { super(inCanvas, MOUSE_LISTENER | MOUSE_MOTION_LISTENER | MOUSE_WHEEL_LISTENER ); _pitchAngle = Math.toRadians(inInitialPitch); } protected synchronized void processAWTEvents( final AWTEvent[] events ) { motion = false; for (AWTEvent event : events) { if (event instanceof MouseEvent) { processMouseEvent((MouseEvent) event); } } } protected void processMouseEvent( final MouseEvent evt ) { if (evt.getID() == MouseEvent.MOUSE_PRESSED) { _mouseX = evt.getX(); _mouseY = evt.getY(); motion = true; } else if (evt.getID() == MouseEvent.MOUSE_DRAGGED) { int xchange = evt.getX() - _mouseX; int ychange = evt.getY() - _mouseY; // rotate if (isRotateEvent(evt)) { _deltaYaw -= xchange * NOMINAL_ROT_FACTOR; _deltaPitch -= ychange * NOMINAL_ROT_FACTOR; } // translate else if (isTranslateEvent(evt)) { _xtrans -= xchange * NOMINAL_TRANS_FACTOR; _ytrans += ychange * NOMINAL_TRANS_FACTOR; } // zoom else if (isZoomEvent(evt)) { doZoomOperations( ychange ); } _mouseX = evt.getX(); _mouseY = evt.getY(); motion = true; } else if (evt.getID() == MouseEvent.MOUSE_WHEEL ) { if (isZoomEvent(evt)) { // if zooming is done through mouse wheel, the number of wheel increments // is multiplied by the wheelZoomFactor, to make zoom speed look natural if ( evt instanceof java.awt.event.MouseWheelEvent) { int zoom = ((int)(((java.awt.event.MouseWheelEvent)evt).getWheelRotation() * wheelZoomFactor)); doZoomOperations( zoom ); motion = true; } } } } /* * zoom but stop at MIN_RADIUS */ private void doZoomOperations( int ychange ) { if ((_distanceFromCenter - ychange * NOMINAL_ZOOM_FACTOR) > MIN_RADIUS) { _distanceFromCenter -= ychange * NOMINAL_ZOOM_FACTOR; } else { _distanceFromCenter = MIN_RADIUS; } } /** * Sets the ViewingPlatform for this behaviour. This method is * called by the ViewingPlatform. * If a sub-calls overrides this method, it must call * super.setViewingPlatform(vp). * NOTE: Applications should <i>not</i> call this method. */ @Override public void setViewingPlatform(ViewingPlatform vp) { super.setViewingPlatform( vp ); if (vp != null) { resetView(); integrateTransforms(); } } /** * Reset the orientation and distance of this behaviour to the current * values in the ViewPlatform Transform Group */ private void resetView() { Vector3d centerToView = new Vector3d(); targetTG.getTransform( targetTransform ); targetTransform.get( _rotMatrix, _transVector ); centerToView.sub( _transVector, _rotationCenter ); _distanceFromCenter = centerToView.length(); _startDistanceFromCenter = _distanceFromCenter; targetTransform.get( _rotMatrix ); _rotateTransform.set( _rotMatrix ); // compute the initial x/y/z offset _temp1.set(centerToView); _rotateTransform.invert(); _rotateTransform.mul(_temp1); _rotateTransform.get(centerToView); _xtrans = centerToView.x; _ytrans = centerToView.y; _ztrans = centerToView.z; // reset rotMatrix _rotateTransform.set( _rotMatrix ); } protected synchronized void integrateTransforms() { // Check if the transform has been changed by another behaviour Transform3D currentXfm = new Transform3D(); targetTG.getTransform(currentXfm); if (! targetTransform.equals(currentXfm)) resetView(); // Three-step rotation process, firstly undo the pitch and apply the delta yaw _latitudeTransform.rotX(_pitchAngle); _rotateTransform.mul(_rotateTransform, _latitudeTransform); _longitudeTransform.rotY( _deltaYaw ); _rotateTransform.mul(_rotateTransform, _longitudeTransform); // Now update pitch angle according to delta and apply _pitchAngle = Math.min(Math.max(0.0, _pitchAngle - _deltaPitch), Math.PI/2.0); _latitudeTransform.rotX(-_pitchAngle); _rotateTransform.mul(_rotateTransform, _latitudeTransform); _distanceVector.z = _distanceFromCenter - _startDistanceFromCenter; _temp1.set(_distanceVector); _temp1.mul(_rotateTransform, _temp1); // want to look at rotationCenter _transVector.x = _rotationCenter.x + _xtrans; _transVector.y = _rotationCenter.y + _ytrans; _transVector.z = _rotationCenter.z + _ztrans; _translation.set(_transVector); targetTransform.mul(_temp1, _translation); // handle rotationCenter _temp1.set(_centerVector); _temp1.mul(targetTransform); _invertCenterVector.x = -_centerVector.x; _invertCenterVector.y = -_centerVector.y; _invertCenterVector.z = -_centerVector.z; _temp2.set(_invertCenterVector); targetTransform.mul(_temp1, _temp2); Vector3d finalTranslation = new Vector3d(); targetTransform.get(finalTranslation); targetTG.setTransform(targetTransform); // reset yaw and pitch deltas _deltaYaw = 0.0; _deltaPitch = 0.0; } private boolean isRotateEvent(MouseEvent evt) { final boolean isRightDrag = (evt.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0; return !evt.isAltDown() && !isRightDrag; } private boolean isZoomEvent(MouseEvent evt) { if (evt instanceof java.awt.event.MouseWheelEvent) { return true; } return evt.isAltDown() && !evt.isMetaDown(); } private boolean isTranslateEvent(MouseEvent evt) { final boolean isRightDrag = (evt.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0; return !evt.isAltDown() && isRightDrag; } }
activityworkshop/GpsPrune
src/tim/prune/threedee/UprightOrbiter.java
Java
gpl-2.0
10,939
/** * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ // ------------------------------------------------------------------------ package com.weixin.sdk.encrypt; import java.security.MessageDigest; import java.util.Arrays; /** * SHA1 class * * 计算公众平台的消息签名接口. */ class SHA1 { /** * 用SHA1算法生成安全签名 * @param token 票据 * @param timestamp 时间戳 * @param nonce 随机字符串 * @param encrypt 密文 * @return 安全签名 * @throws AesException */ public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException { try { String[] array = new String[] { token, timestamp, nonce, encrypt }; StringBuffer sb = new StringBuffer(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < 4; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuffer hexstr = new StringBuffer(); String shaHex = ""; for (int i = 0; i < digest.length; i++) { shaHex = Integer.toHexString(digest[i] & 0xFF); if (shaHex.length() < 2) { hexstr.append(0); } hexstr.append(shaHex); } return hexstr.toString(); } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.ComputeSignatureError); } } }
teabo/wholly-framework
wholly-demo/wholly_weixin/src/main/java/com/weixin/sdk/encrypt/SHA1.java
Java
gpl-2.0
1,592