repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
eea/eionet.webq
src/main/java/eionet/webq/dao/orm/util/UserFileInfo.java
2942
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Web Questionnaires 2 * * The Initial Owner of the Original Code is European Environment * Agency. Portions created by TripleDev are Copyright * (C) European Environment Agency. All Rights Reserved. * * Contributor(s): * Anton Dmitrijev */ package eionet.webq.dao.orm.util; import java.util.Date; import eionet.webq.dao.orm.UserFile; /** * Provides utility methods for {@link eionet.webq.dao.orm.UserFile}. */ public final class UserFileInfo { /** * Default dummy XML schema for files extracted from zip file. * It should not match any conversion or web form xml schema. */ public static final String DUMMY_XML_SCHEMA = "IGNORE_THIS_FILE"; /** * Do not instantiate. */ private UserFileInfo() { } /** * Checks whether this file was downloaded or updated after change using form. * * @param userFile file * @return is downloaded after update using form. */ public static boolean isNotUpdatedOrDownloadedAfterUpdateUsingForm(UserFile userFile) { return notUpdated(userFile) || (isUpdatedAfterUpload(userFile) && isDownloadedAfterUpdate(userFile)); } /** * Checks whether this file was downloaded after change using form. * * @param userFile file * @return is downloaded after update using form. */ public static boolean isNotDownloadedAfterUpdateUsingForm(UserFile userFile) { return isUpdatedAfterUpload(userFile) && !isDownloadedAfterUpdate(userFile); } /** * Checks whether file was downloaded after last update. * * @param userFile file * @return was file downloaded after update */ public static boolean isDownloadedAfterUpdate(UserFile userFile) { Date downloaded = userFile.getDownloaded(); return !(downloaded == null) && userFile.getUpdated().before(downloaded); } /** * Checks whether this file was updated after upload. * * @param userFile file * @return is updated after upload. */ public static boolean isUpdatedAfterUpload(UserFile userFile) { return userFile.getUpdated().after(userFile.getCreated()); } /** * Checks whether file was not updated. * @param userFile file * @return is file updated. */ public static boolean notUpdated(UserFile userFile) { return userFile.getCreated().equals(userFile.getUpdated()); } }
mpl-2.0
icchange/openmrs-module-openhmis.inventory
omod/src/main/java/org/openmrs/module/webservices/rest/search/StockOperationSearchHandler.java
4743
/* * The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.webservices.rest.search; import java.util.Arrays; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.module.openhmis.commons.api.PagingInfo; import org.openmrs.module.openhmis.inventory.api.IStockOperationDataService; import org.openmrs.module.openhmis.inventory.api.IStockroomDataService; import org.openmrs.module.openhmis.inventory.api.model.StockOperation; import org.openmrs.module.openhmis.inventory.api.model.StockOperationStatus; import org.openmrs.module.openhmis.inventory.api.model.Stockroom; import org.openmrs.module.openhmis.inventory.api.search.StockOperationSearch; import org.openmrs.module.openhmis.inventory.web.ModuleRestConstants; import org.openmrs.module.webservices.rest.resource.AlreadyPagedWithLength; import org.openmrs.module.webservices.rest.resource.PagingUtil; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.resource.api.PageableResult; import org.openmrs.module.webservices.rest.web.resource.api.SearchConfig; import org.openmrs.module.webservices.rest.web.resource.api.SearchHandler; import org.openmrs.module.webservices.rest.web.resource.api.SearchQuery; import org.openmrs.module.webservices.rest.web.resource.impl.EmptySearchResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class StockOperationSearchHandler implements SearchHandler { private static final Log LOG = LogFactory.getLog(StockOperationSearchHandler.class); private final SearchConfig searchConfig = new SearchConfig("default", ModuleRestConstants.OPERATION_RESOURCE, Arrays.asList("*"), Arrays.asList( new SearchQuery.Builder("Finds stock operations with an optional status and/or stockroom.") .withOptionalParameters("status", "stockroom_uuid") .build() ) ); private IStockroomDataService stockroomDataService; private IStockOperationDataService operationDataService; @Autowired public StockOperationSearchHandler(IStockroomDataService stockroomDataService, IStockOperationDataService operationDataService) { this.stockroomDataService = stockroomDataService; this.operationDataService = operationDataService; } @Override public SearchConfig getSearchConfig() { return searchConfig; } @Override public PageableResult search(RequestContext context) { String statusText = context.getParameter("status"); String stockroomText = context.getParameter("stockroom_uuid"); StockOperationStatus status = null; if (!StringUtils.isEmpty(statusText)) { status = StockOperationStatus.valueOf(statusText); if (status == null) { LOG.warn("Could not parse Stock Operation Status '" + statusText + "'"); return new EmptySearchResult(); } } Stockroom stockroom = null; if (!StringUtils.isEmpty(stockroomText)) { stockroom = stockroomDataService.getByUuid(stockroomText); if (stockroom == null) { LOG.warn("Could not find stockroom '" + stockroomText + "'"); return new EmptySearchResult(); } } StockOperationSearch search = null; if (status != null) { search = new StockOperationSearch(); search.getTemplate().setStatus(status); } PagingInfo pagingInfo = PagingUtil.getPagingInfoFromContext(context); List<StockOperation> operations; if (stockroom == null) { if (search == null) { // No search was defined so just return everything (excluding retired) operations = operationDataService.getAll(false, pagingInfo); } else { // Return the operations with the specified status operations = operationDataService.getOperations(search, pagingInfo); } } else { // Return the operations for the specified stockroom and status operations = stockroomDataService.getOperations(stockroom, search, pagingInfo); } if (operations == null || operations.size() == 0) { return new EmptySearchResult(); } else { return new AlreadyPagedWithLength<StockOperation>(context, operations, pagingInfo.hasMoreResults(), pagingInfo.getTotalRecordCount()); } } }
mpl-2.0
sthaiya/muzima-api
src/main/java/com/muzima/api/model/algorithm/PatientIdentifierAlgorithm.java
3893
/* * Copyright (c) 2014. The Trustees of Indiana University. * * This version of the code is licensed under the MPL 2.0 Open Source license with additional * healthcare disclaimer. If the user is an entity intending to commercialize any application * that uses this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.api.model.algorithm; import com.jayway.jsonpath.JsonPath; import com.muzima.api.model.Location; import com.muzima.api.model.PatientIdentifier; import com.muzima.api.model.PatientIdentifierType; import com.muzima.search.api.model.object.Searchable; import com.muzima.util.JsonUtils; import net.minidev.json.JSONObject; import java.io.IOException; public class PatientIdentifierAlgorithm extends BaseOpenmrsAlgorithm { public static final String PATIENT_IDENTIFIER_REPRESENTATION = "(uuid,identifier,preferred," + "identifierType:" + PatientIdentifierTypeAlgorithm.PATIENT_IDENTIFIER_TYPE_REPRESENTATION + ","+ "location:" + LocationAlgorithm.LOCATION_STANDARD_REPRESENTATION + ")"; private PatientIdentifierTypeAlgorithm patientIdentifierTypeAlgorithm; private LocationAlgorithm locationAlgorithm; public PatientIdentifierAlgorithm() { this.patientIdentifierTypeAlgorithm = new PatientIdentifierTypeAlgorithm(); locationAlgorithm = new LocationAlgorithm(); } /** * Implementation of this method will define how the observation will be serialized from the JSON representation. * * @param serialized the json representation * @return the concrete observation object */ @Override public Searchable deserialize(final String serialized, final boolean isFullSerialization) throws IOException { PatientIdentifier patientIdentifier = new PatientIdentifier(); patientIdentifier.setUuid(JsonUtils.readAsString(serialized, "$['uuid']")); patientIdentifier.setIdentifier(JsonUtils.readAsString(serialized, "$['identifier']")); patientIdentifier.setPreferred(JsonUtils.readAsBoolean(serialized, "$['preferred']")); Object identifierTypeObject = JsonUtils.readAsObject(serialized, "$['identifierType']"); PatientIdentifierType identifierType = (PatientIdentifierType) patientIdentifierTypeAlgorithm.deserialize(String.valueOf(identifierTypeObject), true); patientIdentifier.setIdentifierType(identifierType); Object locationObject = JsonUtils.readAsObject(serialized, "$['location']"); Location location = (Location)locationAlgorithm.deserialize(String.valueOf(locationObject),isFullSerialization); patientIdentifier.setLocation(location); return patientIdentifier; } /** * Implementation of this method will define how the object will be de-serialized into the String representation. * * @param object the object * @return the string representation */ @Override public String serialize(final Searchable object, final boolean isFullSerialization) throws IOException { PatientIdentifier patientIdentifier = (PatientIdentifier) object; JSONObject jsonObject = new JSONObject(); JsonUtils.writeAsString(jsonObject, "uuid", patientIdentifier.getUuid()); JsonUtils.writeAsString(jsonObject, "identifier", patientIdentifier.getIdentifier()); JsonUtils.writeAsBoolean(jsonObject, "preferred", patientIdentifier.isPreferred()); String identifierType = patientIdentifierTypeAlgorithm.serialize(patientIdentifier.getIdentifierType(), true); jsonObject.put("identifierType", JsonPath.read(identifierType, "$")); String location = locationAlgorithm.serialize(patientIdentifier.getLocation(), true); jsonObject.put("location", JsonPath.read(location, "$")); return jsonObject.toJSONString(); } }
mpl-2.0
zyxakarene/LearningOpenGl
GameServer/src/zyx/server/world/humanoids/npc/behavior/cleaner/CleanerGoingToTableBehavior.java
459
package zyx.server.world.humanoids.npc.behavior.cleaner; import zyx.server.world.humanoids.npc.Cleaner; import zyx.server.world.interactable.common.CommonTable; public class CleanerGoingToTableBehavior extends CleanerWalkingBehavior<CommonTable<Cleaner>> { public CleanerGoingToTableBehavior(Cleaner npc) { super(npc, CleanerBehaviorType.GETTING_DIRTY_PLATE_TABLE); } @Override protected void onArrivedAtDestination() { params.clean(npc); } }
mpl-2.0
itesla/ipst
modelica-events-adder/src/main/java/eu/itesla_project/modelica_events_adder/events/EventsParser.java
3215
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.modelica_events_adder.events; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.itesla_project.modelica_events_adder.events.records.Event; /** * @author Silvia Machado <machados@aia.es> */ public class EventsParser { public EventsParser(File eventsFile) { this.eventsFile = eventsFile; } public void parse() { BufferedReader reader; try { reader = new BufferedReader(new FileReader(this.eventsFile)); String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { //Commented events continue; } Event event; List<String> data = new ArrayList<String>(Arrays.asList(line.split(";"))); int fileId = Integer.parseInt(data.get(0)); data.remove(0); int id = Integer.parseInt(data.get(0)); data.remove(0); String eventType = data.get(0); data.remove(0); String device = data.get(0); data.remove(0); event = new Event(fileId, id, eventType, device, data); // if (eventsMap.containsKey(fileId)) { eventsMap.get(fileId).add(event); } else { List<Event> evList = new ArrayList<Event>(); evList.add(event); eventsMap.put(fileId, evList); } // eventsList.add(event); eventsDevices.add(device); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } public List<Event> getEventsList() { return eventsList; } public void setEventsList(List<Event> eventsList) { this.eventsList = eventsList; } public List<String> getEventsDevices() { return eventsDevices; } public void setEventsDevices(List<String> eventsDevices) { this.eventsDevices = eventsDevices; } public Map<Integer, List<Event>> getEventsMap() { return eventsMap; } public void setEventsMap(Map<Integer, List<Event>> eventsMap) { this.eventsMap = eventsMap; } private Map<Integer, List<Event>> eventsMap = new HashMap<Integer, List<Event>>(); private List<Event> eventsList = new ArrayList<Event>(); private List<String> eventsDevices = new ArrayList<String>(); private File eventsFile; private static final Logger LOGGER = LoggerFactory.getLogger(EventsParser.class); }
mpl-2.0
santiago-hollmann/sample-enteprise
app/src/main/java/com/shollmann/enterprise/app/ui/adapter/CrewAdapter.java
1248
package com.shollmann.enterprise.app.ui.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.shollmann.enterprise.R; import com.shollmann.enterprise.app.ui.viewholder.CrewMemberViewHolder; import java.util.List; import com.shollmann.enterprise.app.model.CrewMember; public class CrewAdapter extends RecyclerView.Adapter<CrewMemberViewHolder> { private List<CrewMember> listCrewCrewMembers; public CrewAdapter(List<CrewMember> listCrewCrewMembers) { this.listCrewCrewMembers = listCrewCrewMembers; } @Override public CrewMemberViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.content_crew_list, parent, false); CrewMemberViewHolder crewMemberViewHolder = new CrewMemberViewHolder(view); return crewMemberViewHolder; } @Override public void onBindViewHolder(CrewMemberViewHolder holder, int position) { holder.setMember(listCrewCrewMembers.get(position)); } @Override public int getItemCount() { return listCrewCrewMembers.size(); } }
mpl-2.0
brianhlin/syncthing-android
src/main/java/com/nutomic/syncthingandroid/fragments/FolderFragment.java
14591
package com.nutomic.syncthingandroid.fragments; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.SwitchCompat; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.nutomic.syncthingandroid.R; import com.nutomic.syncthingandroid.activities.FolderPickerActivity; import com.nutomic.syncthingandroid.activities.SettingsActivity; import com.nutomic.syncthingandroid.activities.SyncthingActivity; import com.nutomic.syncthingandroid.fragments.dialog.KeepVersionsDialogFragment; import com.nutomic.syncthingandroid.syncthing.RestApi; import com.nutomic.syncthingandroid.syncthing.RestApi.SimpleVersioning; import com.nutomic.syncthingandroid.syncthing.RestApi.Versioning; import com.nutomic.syncthingandroid.syncthing.SyncthingService; import com.nutomic.syncthingandroid.util.TextWatcherAdapter; import java.util.ArrayList; import java.util.List; import static android.support.v4.view.MarginLayoutParamsCompat.setMarginEnd; import static android.support.v4.view.MarginLayoutParamsCompat.setMarginStart; import static android.view.Gravity.CENTER_VERTICAL; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static com.nutomic.syncthingandroid.syncthing.SyncthingService.State.ACTIVE; import static com.nutomic.syncthingandroid.util.DpConverter.dp; import static java.lang.String.valueOf; /** * Shows folder details and allows changing them. */ public class FolderFragment extends Fragment implements SyncthingActivity.OnServiceConnectedListener, SyncthingService.OnApiChangeListener { /** * The ID of the folder to be edited. To be used with {@link com.nutomic.syncthingandroid.activities.SettingsActivity#EXTRA_IS_CREATE} * set to false. */ public static final String EXTRA_REPO_ID = "folder_id"; private static final int DIRECTORY_REQUEST_CODE = 234; private static final String TAG = "EditFolderFragment"; public static final String KEEP_VERSIONS_DIALOG_TAG = "KeepVersionsDialogFragment"; private SyncthingService mSyncthingService; private RestApi.Folder mFolder; private EditText mIdView; private TextView mPathView; private SwitchCompat mFolderMasterView; private ViewGroup mDevicesContainer; private TextView mVersioningKeepView; private boolean mIsCreateMode; private KeepVersionsDialogFragment mKeepVersionsDialogFragment = new KeepVersionsDialogFragment(); private TextWatcher mIdTextWatcher = new TextWatcherAdapter() { @Override public void afterTextChanged(Editable s) { mFolder.id = s.toString(); updateRepo(); } }; private TextWatcher mPathTextWatcher = new TextWatcherAdapter() { @Override public void afterTextChanged(Editable s) { mFolder.path = s.toString(); } }; private CompoundButton.OnCheckedChangeListener mMasterCheckedListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton view, boolean isChecked) { mFolder.readOnly = isChecked; updateRepo(); } }; private CompoundButton.OnCheckedChangeListener mOnShareChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton view, boolean isChecked) { RestApi.Device device = (RestApi.Device) view.getTag(); if (isChecked) { mFolder.deviceIds.add(device.deviceID); } else { mFolder.deviceIds.remove(device.deviceID); } updateRepo(); } }; private KeepVersionsDialogFragment.OnValueChangeListener mOnValueChangeListener = new KeepVersionsDialogFragment.OnValueChangeListener() { @Override public void onValueChange(int intValue) { if (intValue == 0) { mFolder.versioning = new Versioning(); mVersioningKeepView.setText(R.string.off); } else { mFolder.versioning = new SimpleVersioning(); ((SimpleVersioning) mFolder.versioning).setParams(intValue); mVersioningKeepView.setText(valueOf(intValue)); } updateRepo(); } }; private View.OnClickListener mPathViewClickListener = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), FolderPickerActivity.class); if (mFolder.path.length() > 0) { intent.putExtra(FolderPickerActivity.EXTRA_INITIAL_DIRECTORY, mFolder.path); } startActivityForResult(intent, DIRECTORY_REQUEST_CODE); } }; private View.OnClickListener mVersioningContainerClickListener = new View.OnClickListener() { @Override public void onClick(View v) { mKeepVersionsDialogFragment.show(getFragmentManager(), KEEP_VERSIONS_DIALOG_TAG); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SettingsActivity activity = (SettingsActivity) getActivity(); mIsCreateMode = activity.getIsCreate(); activity.setTitle(mIsCreateMode ? R.string.create_folder : R.string.edit_folder); activity.registerOnServiceConnectedListener(this); setHasOptionsMenu(true); if (mIsCreateMode) { if (savedInstanceState != null) { mFolder = (RestApi.Folder) savedInstanceState.getSerializable("folder"); } if (mFolder == null) { initFolder(); } } } @Override public void onDestroy() { super.onDestroy(); if (mSyncthingService != null) { mSyncthingService.unregisterOnApiChangeListener(this); } } /** * Save current settings in case we are in create mode and they aren't yet stored in the config. */ @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("folder", mFolder); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_folder, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mIdView = (EditText) view.findViewById(R.id.id); mPathView = (TextView) view.findViewById(R.id.directory); mFolderMasterView = (SwitchCompat) view.findViewById(R.id.master); mVersioningKeepView = (TextView) view.findViewById(R.id.versioningKeep); mDevicesContainer = (ViewGroup) view.findViewById(R.id.devicesContainer); mPathView.setOnClickListener(mPathViewClickListener); view.findViewById(R.id.versioningContainer).setOnClickListener(mVersioningContainerClickListener); if (!mIsCreateMode) { prepareEditMode(); } } @Override public void onDestroyView() { super.onDestroyView(); mIdView.removeTextChangedListener(mIdTextWatcher); mPathView.removeTextChangedListener(mPathTextWatcher); } @Override public void onServiceConnected() { mSyncthingService = ((SyncthingActivity) getActivity()).getService(); mSyncthingService.registerOnApiChangeListener(this); } @Override public void onApiChange(SyncthingService.State currentState) { if (currentState != ACTIVE) { getActivity().finish(); return; } if (!mIsCreateMode) { List<RestApi.Folder> folders = mSyncthingService.getApi().getFolders(); String passedId = getActivity().getIntent().getStringExtra(EXTRA_REPO_ID); for (RestApi.Folder currentFolder : folders) { if (currentFolder.id.equals(passedId)) { mFolder = currentFolder; break; } } if (mFolder == null) { Log.w(TAG, "Folder not found in API update"); getActivity().finish(); return; } } updateViewsAndSetListeners(); } private void updateViewsAndSetListeners() { // Update views mIdView.setText(mFolder.id); mPathView.setText(mFolder.path); mFolderMasterView.setChecked(mFolder.readOnly); List<RestApi.Device> devicesList = mSyncthingService.getApi().getDevices(false); if (devicesList.isEmpty()) { addEmptyDeviceListView(); } else { for (RestApi.Device n : devicesList) { addDeviceViewAndSetListener(n, LayoutInflater.from(getActivity())); } } boolean versioningEnabled = mFolder.versioning instanceof SimpleVersioning; int versions = 0; if (versioningEnabled) { versions = Integer.valueOf(mFolder.versioning.getParams().get("keep")); mVersioningKeepView.setText(valueOf(versions)); } else { mVersioningKeepView.setText(R.string.off); } mKeepVersionsDialogFragment.setValue(versions); // Keep state updated mIdView.addTextChangedListener(mIdTextWatcher); mPathView.addTextChangedListener(mPathTextWatcher); mFolderMasterView.setOnCheckedChangeListener(mMasterCheckedListener); mKeepVersionsDialogFragment.setOnValueChangeListener(mOnValueChangeListener); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.folder_settings, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.create).setVisible(mIsCreateMode); menu.findItem(R.id.delete).setVisible(!mIsCreateMode); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.create: if (mFolder.id.length() > 64 || !mFolder.id.matches("[a-zA-Z0-9-_\\.]+")) { Toast.makeText(getActivity(), R.string.folder_id_invalid, Toast.LENGTH_LONG) .show(); return true; } if (mFolder.path.equals("")) { Toast.makeText(getActivity(), R.string.folder_path_required, Toast.LENGTH_LONG) .show(); return true; } mSyncthingService.getApi().editFolder(mFolder, true, getActivity()); getActivity().finish(); return true; case R.id.delete: new AlertDialog.Builder(getActivity()) .setMessage(R.string.delete_folder_confirm) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { mSyncthingService.getApi().deleteFolder(mFolder, getActivity()); } }) .setNegativeButton(android.R.string.no, null) .show(); return true; case android.R.id.home: getActivity().finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == DIRECTORY_REQUEST_CODE) { mFolder.path = data.getStringExtra(FolderPickerActivity.EXTRA_RESULT_DIRECTORY); mPathView.setText(mFolder.path); updateRepo(); } } private void initFolder() { mFolder = new RestApi.Folder(); mFolder.id = ""; mFolder.path = ""; mFolder.rescanIntervalS = 259200; // Scan every 3 days (in case inotify dropped some changes) mFolder.deviceIds = new ArrayList<>(); mFolder.versioning = new Versioning(); } private void prepareEditMode() { mIdView.clearFocus(); mIdView.setFocusable(false); mIdView.setEnabled(false); mPathView.setEnabled(false); } private void addEmptyDeviceListView() { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WRAP_CONTENT, dp(48, getActivity())); int dividerInset = getResources().getDimensionPixelOffset(R.dimen.material_divider_inset); int contentInset = getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material); setMarginStart(params, dividerInset); setMarginEnd(params, contentInset); TextView emptyView = new TextView(mDevicesContainer.getContext()); emptyView.setGravity(CENTER_VERTICAL); emptyView.setText(R.string.devices_list_empty); mDevicesContainer.addView(emptyView, params); } private void addDeviceViewAndSetListener(RestApi.Device device, LayoutInflater inflater) { inflater.inflate(R.layout.item_device_form, mDevicesContainer); SwitchCompat deviceView = (SwitchCompat) mDevicesContainer.getChildAt(mDevicesContainer.getChildCount()-1); deviceView.setChecked(mFolder.deviceIds.contains(device.deviceID)); deviceView.setText(device.name); deviceView.setTag(device); deviceView.setOnCheckedChangeListener(mOnShareChangeListener); } private void updateRepo() { if (!mIsCreateMode) { mSyncthingService.getApi().editFolder(mFolder, false, getActivity()); } } }
mpl-2.0
mil-oss/fgsms
fgsms-server/fgsms.Services/src/main/java/org/miloss/fgsms/auxsrv/AuxConstants.java
3099
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * If it is not possible or desirable to put the notice in a particular * file, then You may include the notice in a location (such as a LICENSE * file in a relevant directory) where a recipient would be likely to look * for such a notice. * */ /* --------------------------------------------------------------------------- * U.S. Government, Department of the Army * Army Materiel Command * Research Development Engineering Command * Communications Electronics Research Development and Engineering Center * --------------------------------------------------------------------------- */ package org.miloss.fgsms.auxsrv; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; /** * * @author AO */ public class AuxConstants { public static final String VERSION = "7.0 BUILD"; public static final String QUARTZ_SCHEDULER_NAME = "fgsmsAuxServicesQuartzScheduler"; public static final String QUARTZ_GROUP_NAME = "fgsms Aux Services"; public static final String QUARTZ_TRIGGER_GROUP_NAME = "fgsmsAuxServicesTriggers"; public static boolean QuartzJobExists(String JobName, Scheduler sc) throws SchedulerException { if (sc == null) { //added in the case of the scheduler being null, which is probably only when the jdbc datasource is not configured. in this case we have bigger issues return false; } String[] jobNames = sc.getJobNames(QUARTZ_GROUP_NAME); for (int i = 0; i < jobNames.length; i++) { if (jobNames[i].equals(JobName)) { return true; } } return false; } public static JobDetail GetQuartzJobReference(String JobName, Scheduler sc) throws SchedulerException { if (sc == null) { //added in the case of the scheduler being null, which is probably only when the jdbc datasource is not configured. in this case we have bigger issues return null; } String[] jobNames = sc.getJobNames(QUARTZ_GROUP_NAME); for (int i = 0; i < jobNames.length; i++) { if (jobNames[i].equals(JobName)) { return sc.getJobDetail(JobName, QUARTZ_GROUP_NAME); } } return null; } public static Trigger GetQuartzTriggerReference(String JobName, Scheduler sc) throws SchedulerException { if (sc == null) { //added in the case of the scheduler being null, which is probably only when the jdbc datasource is not configured. in this case we have bigger issues return null; } String[] jobNames = sc.getJobNames(QUARTZ_GROUP_NAME); for (int i = 0; i < jobNames.length; i++) { if (jobNames[i].equals(JobName)) { return sc.getTrigger(JobName, QUARTZ_GROUP_NAME); } } return null; } }
mpl-2.0
barbocz/zeromq
src/test/java/org/zeromq/TestReqRouterThreadedTcp.java
5676
package org.zeromq; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Test; import org.zeromq.ZMQ.Socket; /** * Tests a REQ-ROUTER dialog with several methods, * each component being on a separate thread. * */ public class TestReqRouterThreadedTcp { private static final long REQUEST_TIMEOUT = 1000; // msecs /** * A very simple server for one reply only. * */ private class Server implements Runnable { private final int port; /** * Creates a new server. * @param port the port to which to connect. */ public Server(int port) { this.port = port; } @Override public void run() { ZContext ctx = new ZContext(); ZMQ.Socket server = ctx.createSocket(ZMQ.ROUTER); server.bind("tcp://localhost:" + port); System.out.println("Server started"); ZMsg msg = ZMsg.recvMsg(server); // only one echo message for this server msg.send(server); System.out.println("Server sent reply"); zmq.ZMQ.sleep(1); msg.destroy(); // Clean up. ctx.destroySocket(server); ctx.close(); } } private class Client implements Runnable { private final int port; final AtomicBoolean finished = new AtomicBoolean(); /** * Creates a new client. * @param port the port to which to connect. */ public Client(int port) { this.port = port; } @Override public void run() { ZContext ctx = new ZContext(); ZMQ.Socket client = ctx.createSocket(ZMQ.REQ); client.connect("tcp://localhost:" + port); System.out.println("Client started"); client.send("DATA"); System.out.println("Client sent message"); inBetween(ctx, client); String reply = client.recvStr(); System.out.println("Client received message"); assertThat(reply, notNullValue()); assertThat(reply, is("DATA")); finished.set(true); // Clean up. ctx.destroySocket(client); ctx.close(); } /** * Called between the request-reply cycle. * @param client the socket participating to the cycle of request-reply */ protected void inBetween(ZContext ctx, Socket client) { // to be overriden } } private class ClientPoll extends Client { public ClientPoll(int port) { super(port); } // same results // @Override // protected void inBetween(ZContext ctx, Socket client) // { // // Poll socket for a reply, with timeout // PollItem items[] = { new PollItem(client, ZMQ.Poller.POLLIN) }; // int rc = ZMQ.poll(items, 1, REQUEST_TIMEOUT); // assertThat(rc, is(1)); // boolean readable = items[0].isReadable(); // assertThat(readable, is(true)); // } // /** * Here we use a poller to check for readability of the message. * This should activate the prefetching mechanism. */ @Override protected void inBetween(ZContext ctx, Socket client) { // Poll socket for a reply, with timeout ZMQ.Poller poller = ctx.createPoller(1); poller.register(client, ZMQ.Poller.POLLIN); int rc = poller.poll(REQUEST_TIMEOUT); assertThat(rc, is(1)); boolean readable = poller.pollin(0); assertThat(readable, is(true)); // now a message should have been prefetched } } /** * Test dialog directly. * @throws Exception if something bad occurs. */ @Test public void testReqRouterTcp() throws Exception { System.out.println("test Req + Router"); int port = Utils.findOpenPort(); ExecutorService executor = Executors.newFixedThreadPool(2); Server server = new Server(port); Client client = new Client(port); executor.submit(server); executor.submit(client); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); boolean finished = client.finished.get(); assertThat(finished, is(true)); } /** * Test dialog with a polling access in between request-reply. * This should activate the prefetching mechanism. * @throws Exception if something bad occurs. */ @Test public void testReqRouterTcpPoll() throws Exception { System.out.println("test Req + Router with polling"); int port = Utils.findOpenPort(); ExecutorService executor = Executors.newFixedThreadPool(2); Server server = new Server(port); ClientPoll client = new ClientPoll(port); executor.submit(server); executor.submit(client); executor.shutdown(); executor.awaitTermination(30, TimeUnit.SECONDS); boolean finished = client.finished.get(); assertThat(finished, is(true)); } }
mpl-2.0
itesla/ipst-core
action/action-util/src/main/java/eu/itesla_project/action/util/CloseSwitchTask.java
1104
/** * Copyright (c) 2017, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.action.util; import eu.itesla_project.computation.ComputationManager; import eu.itesla_project.contingency.tasks.ModificationTask; import eu.itesla_project.iidm.network.Network; import eu.itesla_project.iidm.network.Switch; import java.util.Objects; /** * @author Mathieu Bague <mathieu.bague at rte-france.com> */ public class CloseSwitchTask implements ModificationTask { private final String switchId; CloseSwitchTask(String switchId) { this.switchId = Objects.requireNonNull(switchId); } @Override public void modify(Network network, ComputationManager computationManager) { Switch sw = network.getSwitch(switchId); if (sw == null) { throw new RuntimeException("Switch '" + switchId + "' not found"); } sw.setOpen(false); } }
mpl-2.0
Contargo/iris
src/test/java/net/contargo/iris/route/RouteProductUnitTest.java
564
package net.contargo.iris.route; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * @author Marc Kannegiesser - kannegiesser@synyx.de */ public class RouteProductUnitTest { @Test public void createsRoundtripFromIsRoundTripTrue() { assertThat(RouteProduct.fromIsRoundtrip(true), is(RouteProduct.ROUNDTRIP)); } @Test public void createsExportFromIsImportFalse() { assertThat(RouteProduct.fromIsRoundtrip(false), is(RouteProduct.ONEWAY)); } }
agpl-3.0
semantic-web-software/dynagent
Nucleo/src/dynagent/gui/adapter/old/DataCase.java
793
package dynagent.gui.adapter.old; public class DataCase { private Integer idoClass; private Integer idoRel; private Integer idoPeer; public DataCase(Integer idoClass,Integer idoRel,Integer idoPeer){ this.idoClass=idoClass; this.idoRel=idoRel; this.idoPeer=idoPeer; } public Integer getIdoClass() { return idoClass; } public void setIdoClass(Integer idoClass) { this.idoClass = idoClass; } public Integer getIdoPeer() { return idoPeer; } public void setIdoPeer(Integer idoPeer) { this.idoPeer = idoPeer; } public Integer getIdoRel() { return idoRel; } public void setIdoRel(Integer idoRel) { this.idoRel = idoRel; } public String toString(){ String result; result="IDOCLASS= "+idoClass+" IDOREL= "+idoRel+" IDOPEER= "+idoPeer; return result; } }
agpl-3.0
automenta/narchy
util/src/main/java/com/metamx/collections/spatial/split/QuadraticGutmanSplitStrategy.java
2542
/* * Copyright 2011 - 2015 Metamarkets Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.metamx.collections.spatial.split; import com.metamx.collections.bitmap.BitmapFactory; import com.metamx.collections.spatial.Node; import com.metamx.collections.spatial.RTreeUtils; import java.util.List; /** */ public class QuadraticGutmanSplitStrategy extends GutmanSplitStrategy { public QuadraticGutmanSplitStrategy(int minNumChildren, int maxNumChildren, BitmapFactory bf) { super(minNumChildren, maxNumChildren, bf); } @Override public Node[] pickSeeds(List<Node> nodes) { double highestCost = Double.MIN_VALUE; int[] highestCostIndices = new int[2]; for (int i = 0; i < nodes.size() - 1; i++) { for (int j = i + 1; j < nodes.size(); j++) { double cost = RTreeUtils.getEnclosingArea(nodes.get(i), nodes.get(j)) - nodes.get(i).area() - nodes.get(j).area(); if (cost > highestCost) { highestCost = cost; highestCostIndices[0] = i; highestCostIndices[1] = j; } } } return new Node[]{nodes.remove(highestCostIndices[0]), nodes.remove(highestCostIndices[1] - 1)}; } @Override public Node pickNext(List<Node> nodes, Node[] groups) { double highestCost = Double.MIN_VALUE; Node costlyNode = null; int counter = 0; int index = -1; for (Node node : nodes) { double group0Cost = RTreeUtils.getEnclosingArea(node, groups[0]); double group1Cost = RTreeUtils.getEnclosingArea(node, groups[1]); double cost = Math.abs(group0Cost - group1Cost); if (cost > highestCost) { highestCost = cost; costlyNode = node; index = counter; } counter++; } if (costlyNode != null) { nodes.remove(index); } return costlyNode; } }
agpl-3.0
SilverDav/Silverpeas-Core
core-library/src/integration-test/java/org/silverpeas/core/util/logging/AnObjectWithAnnotatedMethods.java
1506
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 org.silverpeas.core.util.logging; import org.silverpeas.core.annotation.Bean; @Bean public class AnObjectWithAnnotatedMethods { @Log public void doSomething() throws InterruptedException { Thread.sleep(100); } @Log(message = "I love to do anything for you") public void doAnotherThing() throws InterruptedException { Thread.sleep(100); } }
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/MappingExecuteQueue.java
4105
package com.x.processplatform.assemble.designer; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import com.google.gson.JsonElement; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.annotation.CheckPersistType; import com.x.base.core.entity.dataitem.DataItemConverter; import com.x.base.core.entity.dataitem.ItemCategory; import com.x.base.core.entity.dynamic.DynamicEntity; import com.x.base.core.project.exception.ExceptionEntityNotExist; import com.x.base.core.project.gson.XGsonBuilder; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import com.x.base.core.project.queue.AbstractQueue; import com.x.processplatform.core.entity.content.Data; import com.x.processplatform.core.entity.content.WorkCompleted; import com.x.processplatform.core.entity.element.Mapping; import com.x.processplatform.core.entity.element.util.MappingFactory; import com.x.query.core.entity.Item; public class MappingExecuteQueue extends AbstractQueue<String> { private static Logger logger = LoggerFactory.getLogger(MappingExecuteQueue.class); private DataItemConverter<Item> converter = new DataItemConverter<Item>(Item.class); @Override protected void execute(String id) throws Exception { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); Mapping mapping = emc.find(id, Mapping.class); if (null == mapping) { throw new ExceptionEntityNotExist(id, Mapping.class); } if (BooleanUtils.isTrue(mapping.getEnable())) { this.workCompleted(business, mapping); } } catch (Exception e) { logger.error(e); } } private void workCompleted(Business business, Mapping mapping) throws Exception { String sequence = ""; List<WorkCompleted> os = new ArrayList<>(); Data data = null; do { if (StringUtils.isNotEmpty(mapping.getProcess())) { os = business.entityManagerContainer().listEqualAndSequenceAfter(WorkCompleted.class, WorkCompleted.process_FIELDNAME, mapping.getProcess(), 100, sequence); } else if (StringUtils.isNotEmpty(mapping.getApplication())) { os = business.entityManagerContainer().listEqualAndSequenceAfter(WorkCompleted.class, WorkCompleted.application_FIELDNAME, mapping.getApplication(), 100, sequence); } else { os = new ArrayList<>(); } if (!os.isEmpty()) { Class<? extends JpaObject> cls = (Class<? extends JpaObject>) Class .forName(DynamicEntity.CLASS_PACKAGE + "." + mapping.getTableName()); business.entityManagerContainer().beginTransaction(cls); for (WorkCompleted o : os) { sequence = o.getSequence(); data = this.data(business, o); JpaObject jpaObject = business.entityManagerContainer().find(o.getJob(), cls); if (null == jpaObject) { jpaObject = (JpaObject) cls.newInstance(); jpaObject.setId(o.getJob()); business.entityManagerContainer().persist(jpaObject, CheckPersistType.all); } MappingFactory.mapping(mapping, o, data, jpaObject); } business.entityManagerContainer().commit(); } } while (!os.isEmpty()); } private Data data(Business business, WorkCompleted workCompleted) throws Exception { if (BooleanUtils.isTrue(workCompleted.getMerged()) && (null != workCompleted.getProperties().getData())) { return workCompleted.getProperties().getData(); } List<Item> items = business.entityManagerContainer().listEqualAndEqual(Item.class, Item.bundle_FIELDNAME, workCompleted.getJob(), Item.itemCategory_FIELDNAME, ItemCategory.pp); if (items.isEmpty()) { return new Data(); } else { JsonElement jsonElement = converter.assemble(items); if (jsonElement.isJsonObject()) { return XGsonBuilder.convert(jsonElement, Data.class); } else { /* 如果不是Object强制返回一个Map对象 */ return new Data(); } } } }
agpl-3.0
subshare/subshare
org.subshare/org.subshare.local/src/main/java/org/subshare/local/persistence/SsRemoteRepository.java
1292
package org.subshare.local.persistence; import static co.codewizards.cloudstore.core.util.Util.*; import java.util.UUID; import javax.jdo.annotations.Discriminator; import javax.jdo.annotations.DiscriminatorStrategy; import javax.jdo.annotations.Inheritance; import javax.jdo.annotations.InheritanceStrategy; import javax.jdo.annotations.PersistenceCapable; import co.codewizards.cloudstore.local.persistence.RemoteRepository; @PersistenceCapable @Inheritance(strategy=InheritanceStrategy.SUPERCLASS_TABLE) @Discriminator(strategy=DiscriminatorStrategy.VALUE_MAP, value="SsRemoteRepository") public class SsRemoteRepository extends RemoteRepository { public SsRemoteRepository() { } public SsRemoteRepository(UUID repositoryId) { super(repositoryId); } private String remotePathPrefix; public String getRemotePathPrefix() { return remotePathPrefix; } public void setRemotePathPrefix(String remotePathPrefix) { if (this.remotePathPrefix == null) this.remotePathPrefix = remotePathPrefix; else if (! equal(this.remotePathPrefix, remotePathPrefix)) throw new IllegalStateException(String.format("Cannot change remotePathPrefix! Assigned is '%s'; tried to assign '%s'.", this.remotePathPrefix, remotePathPrefix)); // this.remotePathPrefix = remotePathPrefix; } }
agpl-3.0
medsob/Tanaguru
rules/rgaa3.0/src/main/java/org/tanaguru/rules/rgaa30/Rgaa30Rule050301.java
5377
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * 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/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.rgaa30; import org.apache.commons.lang3.tuple.ImmutablePair; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.ruleimplementation.AbstractMarkerPageRuleImplementation; import org.tanaguru.rules.elementchecker.CompositeChecker; import org.tanaguru.rules.elementchecker.attribute.AttributeWithValuePresenceChecker; import org.tanaguru.rules.elementchecker.element.ElementPresenceChecker; import org.tanaguru.rules.elementselector.SimpleElementSelector; import org.tanaguru.rules.keystore.AttributeStore; import static org.tanaguru.rules.keystore.AttributeStore.PRESENTATION_VALUE; import static org.tanaguru.rules.keystore.AttributeStore.ROLE_ATTR; import static org.tanaguru.rules.keystore.HtmlElementStore.TABLE_ELEMENT; import static org.tanaguru.rules.keystore.MarkerStore.COMPLEX_TABLE_MARKER; import static org.tanaguru.rules.keystore.MarkerStore.DATA_TABLE_MARKER; import static org.tanaguru.rules.keystore.MarkerStore.PRESENTATION_TABLE_MARKER; import static org.tanaguru.rules.keystore.RemarkMessageStore.CHECK_LINEARISED_CONTENT_MSG; import static org.tanaguru.rules.keystore.RemarkMessageStore.CHECK_NATURE_OF_TABLE_AND_LINEARISED_CONTENT_MSG; import static org.tanaguru.rules.keystore.RemarkMessageStore.CHECK_TABLE_IS_NOT_PRESENTATION_WITHOUT_ROLE_ARIA_MSG; import static org.tanaguru.rules.keystore.RemarkMessageStore.CHECK_TABLE_IS_PRESENTATION_WITH_ROLE_ARIA_MSG; import static org.tanaguru.rules.keystore.RemarkMessageStore.PRESENTATION_TABLE_WITHOUT_ARIA_MARKUP_MSG; /** * Implementation of the rule 5.3.1 of the referential Rgaa 3.0. * <br/> * For more details about the implementation, refer to <a * href="http://tanaguru-rules-rgaa3.readthedocs.org/en/latest/Rule-5-3-1">the rule 5.3.1 * design page.</a> * * @see <a * href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-5-3-1"> * 5.3.1 rule specification</a> * */ public class Rgaa30Rule050301 extends AbstractMarkerPageRuleImplementation { /** * Default constructor */ public Rgaa30Rule050301() { super( new SimpleElementSelector(TABLE_ELEMENT), // the presentation tables are not part of the scope new String[]{PRESENTATION_TABLE_MARKER}, // the data and complex tables are part of the scope new String[]{DATA_TABLE_MARKER,COMPLEX_TABLE_MARKER}, new CompositeChecker( new ElementPresenceChecker( // nmi when element is found new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_LINEARISED_CONTENT_MSG), // na when element is not found new ImmutablePair(TestSolution.NOT_APPLICABLE,"") ), new AttributeWithValuePresenceChecker( ROLE_ATTR, PRESENTATION_VALUE, // empty msg because the CHECK_LINEARISED_CONTENT_MSG // is already use above in this case. new ImmutablePair(TestSolution.NEED_MORE_INFO,""), new ImmutablePair(TestSolution.FAILED,PRESENTATION_TABLE_WITHOUT_ARIA_MARKUP_MSG), AttributeStore.ROLE_ATTR ) ), // checker for elements not identified by marker new CompositeChecker( new ElementPresenceChecker( // nmi when element is found new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_NATURE_OF_TABLE_AND_LINEARISED_CONTENT_MSG), // na when element is not found new ImmutablePair(TestSolution.NOT_APPLICABLE,"") ), new AttributeWithValuePresenceChecker( ROLE_ATTR, PRESENTATION_VALUE, new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_TABLE_IS_PRESENTATION_WITH_ROLE_ARIA_MSG), new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_TABLE_IS_NOT_PRESENTATION_WITHOUT_ROLE_ARIA_MSG), AttributeStore.ROLE_ATTR ) ) ); } }
agpl-3.0
kuzukami/subartifact-maven-plugin
src/main/java/jp/co/iidev/subartifact1/divider1/mojo/PredefinedPropagateOption.java
3109
package jp.co.iidev.subartifact1.divider1.mojo; public enum PredefinedPropagateOption { TOPLEVEL_CLASSS_MARKS_INNER_CLASSES_IN_SIGNATURE { @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.byInnerClassSignature = true; return m; } }, PACKAGE_INFO_MARKS_ALL_IN_PACKAGE{ @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "package-info"; return m; } }, PACKAGE_INFO_MARKS_PUBLICACCESSSTOPLEVELCLASSES_AND_RESOURCES_IN_PACKAGE{ @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "package-info"; m.getTargetResourceTypeOR().clear(); m.getTargetResourceTypeOR().add(ResourceType.Resource); m.getTargetResourceTypeOR().add(ResourceType.PublicAccessTopLevelClass); return m; } }, PACKAGE_INFO_MARKS_PUBLICTOPLEVELCLASSES_IN_PACKAGE { @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "package-info"; m.targetResourceTypeOR.clear(); m.targetResourceTypeOR.add( ResourceType.PublicAccessTopLevelClass ); // m.targetResourceTypeOR.add( ResourceType.PackageTopLevelClass ); return m; } }, PACKAGE_INFO_MARKS_DEFAULTACCESSTOPLEVELCLASSES_IN_PACKAGE { @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "package-info"; m.targetResourceTypeOR.clear(); m.targetResourceTypeOR.add( ResourceType.DefaultAccessTopLevelClass ); // m.targetResourceTypeOR.add( ResourceType.PackageTopLevelClass ); return m; } }, PACKAGE_INFO_MARKS_RESOURCES_IN_PACKAGE{ @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "package-info"; m.getTargetResourceTypeOR().clear(); m.getTargetResourceTypeOR().add(ResourceType.Resource); // m.getTargetResourceTypeOR().add(ResourceType.PublicTopLevelClass); return m; } }, IID_RES_MARKS_RESOURCES_IN_PACKAGE { @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.bySimpleClassNameInPacakge = "Res"; m.targetResourceTypeOR.clear(); m.targetResourceTypeOR.add( ResourceType.Resource ); return m; } }, META_INF_SERVICES_FILE_MARKS_SERVICE_CLASSES { @Override public OptionalPropagation getAsOption() { OptionalPropagation m = new OptionalPropagation(); m.byServicesFileContents = true; m.targetResourceTypeOR.clear(); m.targetResourceTypeOR.add( ResourceType.PublicAccessTopLevelClass ); m.targetResourceTypeOR.add( ResourceType.DefaultAccessTopLevelClass ); m.targetResourceTypeOR.add( ResourceType.InnerClass ); return m; } }, ; public abstract OptionalPropagation getAsOption(); }
agpl-3.0
ozwillo/ozwillo-kernel
oasis-webapp/src/main/java/oasis/tools/CommandLineTool.java
2711
/** * Ozwillo Kernel * Copyright (C) 2015 The Ozwillo Kernel Authors * * 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 oasis.tools; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import com.typesafe.config.Config; import de.thetaphi.forbiddenapis.SuppressForbidden; public abstract class CommandLineTool { @Option(name = "-c", usage = "Configuration file", metaVar = "file") private Path configurationPath; @Option(name = "-l", usage = "Log4j configuration file", metaVar = "file") private Path log4jConfig; protected abstract Logger logger(); protected Config init(String[] args) throws IOException { System.setProperty("org.jboss.logging.provider", "slf4j"); parseArgs(args); if (log4jConfig != null && Files.isRegularFile(log4jConfig) && Files.isReadable(log4jConfig)) { System.setProperty("log4j.configurationFile", log4jConfig.toRealPath().toString()); } else { // use default log4j configuration: all INFO and more to stdout System.setProperty("org.apache.logging.log4j.level", "INFO"); if (log4jConfig != null) { if (!Files.isRegularFile(log4jConfig) || !Files.isReadable(log4jConfig)) { logger().warn("log4j2 configuration file not found or not readable. Using default configuration."); } } else { logger().debug("No log4j2 configuration file specified. Using default configuration."); } } return SettingsLoader.load(configurationPath); } private void parseArgs(String[] args) { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { printUsage(e); System.exit(1); } } @SuppressForbidden protected void printUsage(CmdLineException e) { // TODO: detailed usage description System.err.println(e.getMessage()); e.getParser().printUsage(System.err); } }
agpl-3.0
kaltura/KalturaGeneratedAPIClientsAndroid
KalturaClient/src/main/java/com/kaltura/client/types/LiveAsset.java
3894
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(LiveAsset.Tokenizer.class) public class LiveAsset extends FlavorAsset { public interface Tokenizer extends FlavorAsset.Tokenizer { String multicastIP(); String multicastPort(); } private String multicastIP; private Integer multicastPort; // multicastIP: public String getMulticastIP(){ return this.multicastIP; } public void setMulticastIP(String multicastIP){ this.multicastIP = multicastIP; } public void multicastIP(String multirequestToken){ setToken("multicastIP", multirequestToken); } // multicastPort: public Integer getMulticastPort(){ return this.multicastPort; } public void setMulticastPort(Integer multicastPort){ this.multicastPort = multicastPort; } public void multicastPort(String multirequestToken){ setToken("multicastPort", multirequestToken); } public LiveAsset() { super(); } public LiveAsset(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: multicastIP = GsonParser.parseString(jsonObject.get("multicastIP")); multicastPort = GsonParser.parseInt(jsonObject.get("multicastPort")); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaLiveAsset"); kparams.add("multicastIP", this.multicastIP); kparams.add("multicastPort", this.multicastPort); return kparams; } public static final Creator<LiveAsset> CREATOR = new Creator<LiveAsset>() { @Override public LiveAsset createFromParcel(Parcel source) { return new LiveAsset(source); } @Override public LiveAsset[] newArray(int size) { return new LiveAsset[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(this.multicastIP); dest.writeValue(this.multicastPort); } public LiveAsset(Parcel in) { super(in); this.multicastIP = in.readString(); this.multicastPort = (Integer)in.readValue(Integer.class.getClassLoader()); } }
agpl-3.0
gnosygnu/xowa_android
_100_core/src/main/java/gplx/langs/dsvs/DsvSymbols.java
1930
package gplx.langs.dsvs; import gplx.*; import gplx.langs.*; class DsvSymbols {//_20110417 public String FldSep() {return fldSep;} public DsvSymbols FldSep_(String v) {fldSep = v; CmdSequence_set(); return this;} private String fldSep; public String RowSep() {return rowSep;} public DsvSymbols RowSep_(String v) { rowSep = v; rowSepIsNewLine = String_.Has(v, "\n") || String_.Has(v, "\r"); return this; } String rowSep; public String QteDlm() {return qteDlm;} public void QteDlm_set(String v) {qteDlm = v; CmdSequence_set();} private String qteDlm; public String CmdDlm() {return cmdDlm;} public void CmdDlm_set(String v) {cmdDlm = v; CmdSequence_set();} private String cmdDlm; public String CmdSequence() {return cmdSequence;} private String cmdSequence; public String CommentSym() {return commentSym;} public void CommentSym_set(String v) {commentSym = v;} private String commentSym; public String TblNameSym() {return tblNameSym;} public void TblNamesSym_set(String v) {tblNameSym = v;} private String tblNameSym; public String FldNamesSym() {return fldNamesSym;} public void FldNamesSym_set(String v) {fldNamesSym = v;} private String fldNamesSym; public String FldTypesSym() {return fldTypesSym;} public void FldTypesSym_set(String v) {fldTypesSym = v;} private String fldTypesSym; public boolean RowSepIsNewLine() {return rowSepIsNewLine;} private boolean rowSepIsNewLine; public void Reset() { fldSep = ","; RowSep_ ("\r\n"); qteDlm = "\""; cmdDlm = " "; CmdSequence_set(); commentSym = "//"; tblNameSym = "#"; fldNamesSym = "@"; fldTypesSym = "$"; } void CmdSequence_set() { // commandDelimiters are repeated; once without quotes and once with quotes; ex: , ," ", cmdSequence = String_.Concat(cmdDlm, fldSep, qteDlm, cmdDlm, qteDlm); } public static DsvSymbols default_() {return new DsvSymbols();} DsvSymbols() {this.Reset();} }
agpl-3.0
tyatsumi/hareka
server/src/main/java/org/kareha/hareka/server/game/stat/AbstractCharacterStat.java
2946
package org.kareha.hareka.server.game.stat; import java.util.Collection; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.kareha.hareka.annotation.GuardedBy; import org.kareha.hareka.annotation.ThreadSafe; import org.kareha.hareka.game.AbilityType; import org.kareha.hareka.game.Power; @ThreadSafe @XmlJavaTypeAdapter(AbstractCharacterStat.Adapter.class) public abstract class AbstractCharacterStat implements CharacterStat { public static abstract class Builder { protected Species species; protected String shape; public Builder species(final Species v) { species = v; return this; } public Builder shape(final String v) { shape = v; return this; } public abstract AbstractCharacterStat build(); } protected final Species species; @GuardedBy("this") protected String shape; protected AbstractCharacterStat(final Builder builder) { species = builder.species; shape = builder.shape; } @XmlType(name = "abstractCharacterStat") @XmlSeeAlso({ NormalCharacterStat.Adapted.class }) @XmlAccessorType(XmlAccessType.NONE) protected static abstract class Adapted { @XmlElement protected String speciesId; @XmlElement protected String shape; protected Adapted() { // used by JAXB } protected Adapted(final AbstractCharacterStat v) { speciesId = v.species.getId(); synchronized (v) { shape = v.shape; } } protected abstract AbstractCharacterStat unmarshal(); } protected abstract Adapted marshal(); static class Adapter extends XmlAdapter<Adapted, AbstractCharacterStat> { @Override public Adapted marshal(final AbstractCharacterStat v) throws Exception { if (v == null) { return null; } return v.marshal(); } @Override public AbstractCharacterStat unmarshal(final Adapted v) throws Exception { if (v == null) { return null; } return v.unmarshal(); } } @Override public synchronized String getShape() { return shape; } @Override public long getCount() { return 1; } @Override public Species getSpecies() { return species; } @Override public Collection<AbilityType> getAbilities() { return species.getAbilities(); } @Override public boolean hasAbility(final AbilityType v) { return species.hasAbility(v); } @Override public Collection<Power> getPowers() { return species.getPowers(); } @Override public boolean hasPower(final Power v) { return species.hasPower(v); } @Override public VisualType getVisualType() { return species.getVisualType(); } @Override public boolean isVisible(final VisualType visualType) { return species.isVisible(visualType); } }
agpl-3.0
o2oa/o2oa
o2server/x_query_assemble_designer/src/main/java/com/x/query/assemble/designer/jaxrs/statement/ActionCreate.java
3572
package com.x.query.assemble.designer.jaxrs.statement; import java.util.Date; import org.apache.commons.lang3.StringUtils; import com.google.gson.JsonElement; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.entity.annotation.CheckPersistType; import com.x.base.core.project.bean.WrapCopier; import com.x.base.core.project.bean.WrapCopierFactory; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.exception.ExceptionAccessDenied; import com.x.base.core.project.exception.ExceptionDuplicateFlag; import com.x.base.core.project.exception.ExceptionEntityFieldEmpty; import com.x.base.core.project.exception.ExceptionEntityNotExist; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WoId; import com.x.base.core.project.tools.ListTools; import com.x.query.assemble.designer.Business; import com.x.query.core.entity.Query; import com.x.query.core.entity.schema.Statement; import com.x.query.core.entity.schema.Table; class ActionCreate extends BaseAction { ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { ActionResult<Wo> result = new ActionResult<>(); Business business = new Business(emc); Wi wi = this.convertToWrapIn(jsonElement, Wi.class); Statement statement = Wi.copier.copy(wi); Query query = emc.flag(wi.getQuery(), Query.class); if (null == query) { throw new ExceptionEntityNotExist(wi.getQuery(), Query.class); } statement.setQuery(query.getId()); if (StringUtils.equals(statement.getEntityCategory(), Statement.ENTITYCATEGORY_DYNAMIC)) { Table table = emc.flag(wi.getTable(), Table.class); if (null == table) { throw new ExceptionEntityNotExist(wi.getTable(), Table.class); } statement.setTable(table.getId()); } else { try { Class.forName(statement.getEntityClassName()); } catch (Exception e) { throw new ExceptionEntityClass(statement.getEntityClassName()); } } if (!business.editable(effectivePerson, query)) { throw new ExceptionAccessDenied(effectivePerson, query); } if (StringUtils.isEmpty(statement.getName())) { throw new ExceptionEntityFieldEmpty(Statement.class, Table.name_FIELDNAME); } if (StringUtils.isNotEmpty(emc.conflict(Statement.class, statement))) { throw new ExceptionDuplicateFlag(Statement.class, emc.conflict(Statement.class, statement)); } emc.beginTransaction(Statement.class); statement.setCreatorPerson(effectivePerson.getDistinguishedName()); statement.setLastUpdatePerson(effectivePerson.getDistinguishedName()); statement.setLastUpdateTime(new Date()); emc.persist(statement, CheckPersistType.all); emc.commit(); CacheManager.notify(Statement.class); Wo wo = new Wo(); wo.setId(statement.getId()); result.setData(wo); return result; } } public static class Wo extends WoId { } public static class Wi extends Statement { private static final long serialVersionUID = -5237741099036357033L; static WrapCopier<Wi, Statement> copier = WrapCopierFactory.wi(Wi.class, Statement.class, null, ListTools.toList(JpaObject.FieldsUnmodify, Statement.creatorPerson_FIELDNAME, Statement.lastUpdatePerson_FIELDNAME, Statement.lastUpdateTime_FIELDNAME)); } }
agpl-3.0
paulmartel/voltdb
src/frontend/org/voltdb/GlobalServiceElector.java
3356
/* This file is part of VoltDB. * Copyright (C) 2008-2016 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.voltcore.logging.VoltLogger; import org.voltcore.zk.LeaderElector; import org.voltcore.zk.LeaderNoticeHandler; /** * GlobalServiceElector performs leader election to determine which VoltDB cluster node * will be responsible for leading various cluster-wide services, particularly those which must * run on the same node. */ class GlobalServiceElector implements LeaderNoticeHandler { private static final VoltLogger hostLog = new VoltLogger("HOST"); private final LeaderElector m_leaderElector; private final List<Promotable> m_services = new ArrayList<Promotable>(); private final int m_hostId; private boolean m_isLeader = false; GlobalServiceElector(ZooKeeper zk, int hostId) { m_leaderElector = new LeaderElector(zk, VoltZK.leaders_globalservice, "globalservice", null, this); m_hostId = hostId; } /** Add a service to be notified if this node becomes the global leader */ synchronized void registerService(Promotable service) { m_services.add(service); if (m_isLeader) { try { service.acceptPromotion(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to promote global service.", true, e); } } } /** Kick off the leader election. * Will block until all of the acceptPromotion() calls to all of the services return at the initial leader. */ void start() throws KeeperException, InterruptedException, ExecutionException { m_leaderElector.start(true); } @Override synchronized public void becomeLeader() { hostLog.info("Host " + m_hostId + " promoted to be the global service provider"); m_isLeader = true; for (Promotable service : m_services) { try { service.acceptPromotion(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to promote global service.", true, e); } } } void shutdown() { try { m_leaderElector.shutdown(); } catch (Exception e) { VoltDB.crashLocalVoltDB("Error shutting down GlobalServiceElector's LeaderElector", true, e); } } @Override public void noticedTopologyChange(boolean added, boolean removed) { } }
agpl-3.0
deerwalk/voltdb
src/frontend/org/voltdb/VoltNonTransactionalProcedure.java
3071
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.util.concurrent.CompletableFuture; import org.voltdb.client.ClientResponse; /** * Base class for any user provided non-transactional procedures. * To be a valid procedure, there muse exist a run(..) method that * accepts compatible parameters and returns one of: * long, VoltTable, VoltTable[], CompletableFuture<ClientResponse> * */ public class VoltNonTransactionalProcedure { ProcedureRunnerNT m_runner = null; /** * Calls a procedure (either transactional or not) and returns a CompletableFuture that can * be returned from the procedure. * * To add a callback to the future, try: * return callProcedure(procname, params).thenApply(javafunction); * * Where "javafunction" takes a ClientResponse and returns an acceptable procedure return type. * * @return */ public CompletableFuture<ClientResponse> callProcedure(String procName, Object... params) { return m_runner.callProcedure(procName, params); } /** * Get the ID of cluster that the client connects to. * @return An ID that identifies the VoltDB cluster */ public int getClusterId() { return m_runner.getClusterId(); } /** * Set the status code that will be returned to the client. This is not the same as the status * code returned by the server. If a procedure sets the status code and then rolls back or causes an error * the status code will still be propagated back to the client so it is always necessary to check * the server status code first. * * @param statusCode Byte-long application-specific status code. */ public void setAppStatusCode(byte statusCode) { m_runner.setAppStatusCode(statusCode); } /** * Set the string that will be turned to the client. This is not the same as the status string * returned by the server. If a procedure sets the status string and then rolls back or causes an error * the status string will still be propagated back to the client so it is always necessary to check * the server status code first. * * @param statusString Application specific status string. */ public void setAppStatusString(String statusString) { m_runner.setAppStatusString(statusString); } }
agpl-3.0
dzc34/Asqatasun
rules/rules-rgaa3.0/src/test/java/org/asqatasun/rules/rgaa30/Rgaa30Rule111004Test.java
2854
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa30; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.entity.audit.ProcessResult; import org.asqatasun.rules.keystore.HtmlElementStore; import org.asqatasun.rules.keystore.RemarkMessageStore; import org.asqatasun.rules.rgaa30.test.Rgaa30RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 11.10.4 of the referential Rgaa 3.0. * * @author */ public class Rgaa30Rule111004Test extends Rgaa30RuleImplementationTestCase { /** * Default constructor * @param testName */ public Rgaa30Rule111004Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.rgaa30.Rgaa30Rule111004"); } @Override protected void setUpWebResourceMap() { addWebResource("Rgaa30.Test.11.10.4-3NMI-01"); addWebResource("Rgaa30.Test.11.10.4-4NA-01"); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------3NMI-01--------------------------------- //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa30.Test.11.10.4-3NMI-01"); checkResultIsPreQualified(processResult, 1, 1); checkRemarkIsPresent( processResult, TestSolution.NEED_MORE_INFO, RemarkMessageStore.MANUAL_CHECK_ON_ELEMENTS_MSG, HtmlElementStore.FORM_ELEMENT, 1); //---------------------------------------------------------------------- //------------------------------4NA-01---------------------------------- //---------------------------------------------------------------------- checkResultIsNotApplicable(processPageTest("Rgaa30.Test.11.10.4-4NA-01")); } }
agpl-3.0
egelke/eIDSuite
app/src/main/java/net/egelke/android/eid/view/GoDialog.java
3722
/* This file is part of eID Suite. Copyright (C) 2015 Egelke BVBA eID Suite 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. eID Suite 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 eID Suite. If not, see <http://www.gnu.org/licenses/>. */ package net.egelke.android.eid.view; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.StandardExceptionParser; import com.google.android.gms.analytics.Tracker; import net.egelke.android.eid.EidSuiteApp; import net.egelke.android.eid.R; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; public class GoDialog extends DialogFragment { public interface Listener { void onGo(String url); } private TextView url; private Listener listener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View v = inflater.inflate(R.layout.dialog_go, null); url = (TextView) v.findViewById(R.id.url); url.setText(getArguments().getString("url")); builder.setView(v).setTitle(R.string.action_go) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.cont, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { navigate(); } }); url.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { navigate(); dismiss(); return true; } }); // Create the AlertDialog object and return it return builder.create(); } private void navigate() { try { String urlValue = url.getText().toString(); URL parsed = new URL(urlValue.contains("://") ? urlValue : "http://" + urlValue); listener.onGo(parsed.toString()); } catch (MalformedURLException e) { Toast.makeText(GoDialog.this.getActivity(), R.string.toastInvalidUrl, Toast.LENGTH_LONG).show(); Tracker tracker = ((EidSuiteApp) GoDialog.this.getActivity().getApplication()).getTracker(); tracker.send(new HitBuilders.ExceptionBuilder() .setDescription(new StandardExceptionParser(GoDialog.this.getActivity(), null).getDescription(Thread.currentThread().getName(), e)) .setFatal(false).build()); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); listener = (Listener) activity; } }
agpl-3.0
kaltura/KalturaGeneratedAPIClientsAndroid
KalturaClient/src/main/java/com/kaltura/client/types/ZoomIntegrationSetting.java
9841
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.enums.ZoomUsersMatching; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(ZoomIntegrationSetting.Tokenizer.class) public class ZoomIntegrationSetting extends IntegrationSetting { public interface Tokenizer extends IntegrationSetting.Tokenizer { String zoomCategory(); String enableRecordingUpload(); String zoomUserMatchingMode(); String zoomUserPostfix(); String zoomWebinarCategory(); String enableWebinarUploads(); String jwtToken(); String enableZoomTranscription(); String zoomAccountDescription(); String enableMeetingUpload(); } private String zoomCategory; private Boolean enableRecordingUpload; private ZoomUsersMatching zoomUserMatchingMode; private String zoomUserPostfix; private String zoomWebinarCategory; private Boolean enableWebinarUploads; private String jwtToken; private Boolean enableZoomTranscription; private String zoomAccountDescription; private Boolean enableMeetingUpload; // zoomCategory: public String getZoomCategory(){ return this.zoomCategory; } public void setZoomCategory(String zoomCategory){ this.zoomCategory = zoomCategory; } public void zoomCategory(String multirequestToken){ setToken("zoomCategory", multirequestToken); } // enableRecordingUpload: public Boolean getEnableRecordingUpload(){ return this.enableRecordingUpload; } public void setEnableRecordingUpload(Boolean enableRecordingUpload){ this.enableRecordingUpload = enableRecordingUpload; } public void enableRecordingUpload(String multirequestToken){ setToken("enableRecordingUpload", multirequestToken); } // zoomUserMatchingMode: public ZoomUsersMatching getZoomUserMatchingMode(){ return this.zoomUserMatchingMode; } public void setZoomUserMatchingMode(ZoomUsersMatching zoomUserMatchingMode){ this.zoomUserMatchingMode = zoomUserMatchingMode; } public void zoomUserMatchingMode(String multirequestToken){ setToken("zoomUserMatchingMode", multirequestToken); } // zoomUserPostfix: public String getZoomUserPostfix(){ return this.zoomUserPostfix; } public void setZoomUserPostfix(String zoomUserPostfix){ this.zoomUserPostfix = zoomUserPostfix; } public void zoomUserPostfix(String multirequestToken){ setToken("zoomUserPostfix", multirequestToken); } // zoomWebinarCategory: public String getZoomWebinarCategory(){ return this.zoomWebinarCategory; } public void setZoomWebinarCategory(String zoomWebinarCategory){ this.zoomWebinarCategory = zoomWebinarCategory; } public void zoomWebinarCategory(String multirequestToken){ setToken("zoomWebinarCategory", multirequestToken); } // enableWebinarUploads: public Boolean getEnableWebinarUploads(){ return this.enableWebinarUploads; } public void setEnableWebinarUploads(Boolean enableWebinarUploads){ this.enableWebinarUploads = enableWebinarUploads; } public void enableWebinarUploads(String multirequestToken){ setToken("enableWebinarUploads", multirequestToken); } // jwtToken: public String getJwtToken(){ return this.jwtToken; } public void setJwtToken(String jwtToken){ this.jwtToken = jwtToken; } public void jwtToken(String multirequestToken){ setToken("jwtToken", multirequestToken); } // enableZoomTranscription: public Boolean getEnableZoomTranscription(){ return this.enableZoomTranscription; } public void setEnableZoomTranscription(Boolean enableZoomTranscription){ this.enableZoomTranscription = enableZoomTranscription; } public void enableZoomTranscription(String multirequestToken){ setToken("enableZoomTranscription", multirequestToken); } // zoomAccountDescription: public String getZoomAccountDescription(){ return this.zoomAccountDescription; } public void setZoomAccountDescription(String zoomAccountDescription){ this.zoomAccountDescription = zoomAccountDescription; } public void zoomAccountDescription(String multirequestToken){ setToken("zoomAccountDescription", multirequestToken); } // enableMeetingUpload: public Boolean getEnableMeetingUpload(){ return this.enableMeetingUpload; } public void setEnableMeetingUpload(Boolean enableMeetingUpload){ this.enableMeetingUpload = enableMeetingUpload; } public void enableMeetingUpload(String multirequestToken){ setToken("enableMeetingUpload", multirequestToken); } public ZoomIntegrationSetting() { super(); } public ZoomIntegrationSetting(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: zoomCategory = GsonParser.parseString(jsonObject.get("zoomCategory")); enableRecordingUpload = GsonParser.parseBoolean(jsonObject.get("enableRecordingUpload")); zoomUserMatchingMode = ZoomUsersMatching.get(GsonParser.parseInt(jsonObject.get("zoomUserMatchingMode"))); zoomUserPostfix = GsonParser.parseString(jsonObject.get("zoomUserPostfix")); zoomWebinarCategory = GsonParser.parseString(jsonObject.get("zoomWebinarCategory")); enableWebinarUploads = GsonParser.parseBoolean(jsonObject.get("enableWebinarUploads")); jwtToken = GsonParser.parseString(jsonObject.get("jwtToken")); enableZoomTranscription = GsonParser.parseBoolean(jsonObject.get("enableZoomTranscription")); zoomAccountDescription = GsonParser.parseString(jsonObject.get("zoomAccountDescription")); enableMeetingUpload = GsonParser.parseBoolean(jsonObject.get("enableMeetingUpload")); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaZoomIntegrationSetting"); kparams.add("zoomCategory", this.zoomCategory); kparams.add("enableRecordingUpload", this.enableRecordingUpload); kparams.add("zoomUserMatchingMode", this.zoomUserMatchingMode); kparams.add("zoomUserPostfix", this.zoomUserPostfix); kparams.add("zoomWebinarCategory", this.zoomWebinarCategory); kparams.add("enableWebinarUploads", this.enableWebinarUploads); kparams.add("jwtToken", this.jwtToken); kparams.add("enableZoomTranscription", this.enableZoomTranscription); kparams.add("zoomAccountDescription", this.zoomAccountDescription); kparams.add("enableMeetingUpload", this.enableMeetingUpload); return kparams; } public static final Creator<ZoomIntegrationSetting> CREATOR = new Creator<ZoomIntegrationSetting>() { @Override public ZoomIntegrationSetting createFromParcel(Parcel source) { return new ZoomIntegrationSetting(source); } @Override public ZoomIntegrationSetting[] newArray(int size) { return new ZoomIntegrationSetting[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(this.zoomCategory); dest.writeValue(this.enableRecordingUpload); dest.writeInt(this.zoomUserMatchingMode == null ? -1 : this.zoomUserMatchingMode.ordinal()); dest.writeString(this.zoomUserPostfix); dest.writeString(this.zoomWebinarCategory); dest.writeValue(this.enableWebinarUploads); dest.writeString(this.jwtToken); dest.writeValue(this.enableZoomTranscription); dest.writeString(this.zoomAccountDescription); dest.writeValue(this.enableMeetingUpload); } public ZoomIntegrationSetting(Parcel in) { super(in); this.zoomCategory = in.readString(); this.enableRecordingUpload = (Boolean)in.readValue(Boolean.class.getClassLoader()); int tmpZoomUserMatchingMode = in.readInt(); this.zoomUserMatchingMode = tmpZoomUserMatchingMode == -1 ? null : ZoomUsersMatching.values()[tmpZoomUserMatchingMode]; this.zoomUserPostfix = in.readString(); this.zoomWebinarCategory = in.readString(); this.enableWebinarUploads = (Boolean)in.readValue(Boolean.class.getClassLoader()); this.jwtToken = in.readString(); this.enableZoomTranscription = (Boolean)in.readValue(Boolean.class.getClassLoader()); this.zoomAccountDescription = in.readString(); this.enableMeetingUpload = (Boolean)in.readValue(Boolean.class.getClassLoader()); } }
agpl-3.0
DHBW-Karlsruhe/businesshorizon2
businesshorizon2-cf/src/main/java/dhbw/ka/mwi/businesshorizon2/cf/CFIntermediateResult.java
1012
package dhbw.ka.mwi.businesshorizon2.cf; /** * Speichert die übergebenen Unternehmenswerte und Eigenkapitalkosten. * Wird verwendet, um Zwischenergebnisse aller Perioden zu speichern. */ class CFIntermediateResult { private final double[] uWert; private final double[] ekKost; /** * All args Konstruktor * @param uWert definiert die Unternehmenswerte als double Wert in einem Array. * @param ekKost definiert die Eigenkapitalkosten als double Wert in einem Array. */ CFIntermediateResult(final double[] uWert, final double[] ekKost) { this.uWert = uWert; this.ekKost = ekKost; } /** * Getter Methode für den Unternehmenswert. * @return Gibt die Unternehmenswerte als Array zurück. */ double[] getuWert() { return uWert; } /** * Getter Methode für die Eigenkapitalkosten. * @return Gibt die Eigenkapitalkosten als Array zurück. */ double[] getEkKost() { return ekKost; } }
agpl-3.0
fharias/purplecore
jpos/src/main/java/org/jpos/iso/channel/PostChannel.java
2850
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2013 Alejandro P. Revilla * * 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 org.jpos.iso.channel; import org.jpos.iso.*; import java.io.IOException; import java.net.ServerSocket; /** * ISOChannel implementation - Postilion Channel * Send packet len (2 bytes network byte order MSB/LSB) followed by * raw data. * * @author salaman@teknos.com * @version Id: PostChannel.java,v 1.0 1999/05/14 19:00:00 may Exp * @see ISOMsg * @see ISOException * @see ISOChannel */ public class PostChannel extends BaseChannel { /** * Public constructor (used by Class.forName("...").newInstance()) */ public PostChannel () { super(); } /** * Construct client ISOChannel * @param host server TCP Address * @param port server port number * @param p an ISOPackager * @see ISOPackager */ public PostChannel (String host, int port, ISOPackager p) { super(host, port, p); } /** * Construct server ISOChannel * @param p an ISOPackager * @exception IOException * @see ISOPackager */ public PostChannel (ISOPackager p) throws IOException { super(p); } /** * constructs a server ISOChannel associated with a Server Socket * @param p an ISOPackager * @param serverSocket where to accept a connection * @exception IOException * @see ISOPackager */ public PostChannel (ISOPackager p, ServerSocket serverSocket) throws IOException { super(p, serverSocket); } protected void sendMessageLength(int len) throws IOException { serverOut.write (len >> 8); serverOut.write (len); } protected int getMessageLength() throws IOException, ISOException { byte[] b = new byte[2]; serverIn.readFully(b,0,2); return (int) ( ((((int)b[0])&0xFF) << 8) | (((int)b[1])&0xFF)); } /** * * @param header Hex representation of header */ public void setHeader (String header) { super.setHeader ( ISOUtil.hex2byte (header.getBytes(), 0, header.length() / 2) ); } }
agpl-3.0
StratusLab/claudia
tcloud-server/src/main/java/com/telefonica/claudia/smi/monitoring/bean/error/BasicError.java
1631
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the Affero GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.smi.monitoring.bean.error; import java.io.Serializable; public abstract class BasicError implements Serializable{ /** * */ private static final long serialVersionUID = 6833491115808890546L; protected String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
agpl-3.0
diederikd/DeBrug
languages/ObjectiefRecht/source_gen/ObjectiefRecht/behavior/OvergangZonderRechtsgevolg__BehaviorDescriptor.java
4301
package ObjectiefRecht.behavior; /*Generated by MPS */ import jetbrains.mps.core.aspects.behaviour.BaseBHDescriptor; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.core.aspects.behaviour.api.BehaviorRegistry; import jetbrains.mps.smodel.language.ConceptRegistry; import jetbrains.mps.core.aspects.behaviour.api.SMethod; import java.util.List; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.core.aspects.behaviour.SMethodBuilder; import jetbrains.mps.core.aspects.behaviour.SJavaCompoundTypeImpl; import jetbrains.mps.core.aspects.behaviour.SModifiersImpl; import jetbrains.mps.core.aspects.behaviour.AccessPrivileges; import java.util.Arrays; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.core.aspects.behaviour.api.SConstructor; import org.jetbrains.annotations.Nullable; import jetbrains.mps.core.aspects.behaviour.api.BHMethodNotFoundException; public final class OvergangZonderRechtsgevolg__BehaviorDescriptor extends BaseBHDescriptor { private static final SAbstractConcept CONCEPT = MetaAdapterFactory.getConcept(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x3b19ba47355a8fe6L, "ObjectiefRecht.structure.OvergangZonderRechtsgevolg"); private static final BehaviorRegistry REGISTRY = ConceptRegistry.getInstance().getBehaviorRegistry(); public static final SMethod<List<SNode>> GeefLijstMetInvoerKenmerken_id6$f4rrvMdoa = new SMethodBuilder<List<SNode>>(new SJavaCompoundTypeImpl((Class<List<SNode>>) ((Class) Object.class))).name("GeefLijstMetInvoerKenmerken").modifiers(SModifiersImpl.create(8, AccessPrivileges.PUBLIC)).concept(CONCEPT).id("6$f4rrvMdoa").registry(REGISTRY).build(); private static final List<SMethod<?>> BH_METHODS = Arrays.<SMethod<?>>asList(GeefLijstMetInvoerKenmerken_id6$f4rrvMdoa); private static void ___init___(@NotNull SNode __thisNode__) { } /*package*/ static List<SNode> GeefLijstMetInvoerKenmerken_id6$f4rrvMdoa(@NotNull SNode __thisNode__) { List<SNode> lijstMetKenmerken = new ArrayList<SNode>(); for (SNode methode : ListSequence.fromList(SLinkOperations.getChildren(__thisNode__, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x3b19ba47355a8fe6L, 0x75a9691d14b327a0L, "nieuweFeiten")))) { for (SNode kenmerk : ListSequence.fromList(SLinkOperations.getChildren(methode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x1d41347b06d6c3eL, 0x1d41347b06d6c86L, "kenmerken")))) { ListSequence.fromList(lijstMetKenmerken).addElement(SLinkOperations.getTarget(kenmerk, MetaAdapterFactory.getReferenceLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x6e43a734f86e13f2L, 0x6e43a734f86e13f3L, "kenmerk"))); } } return lijstMetKenmerken; } /*package*/ OvergangZonderRechtsgevolg__BehaviorDescriptor() { super(REGISTRY); } @Override protected void initNode(@NotNull SNode node, @NotNull SConstructor constructor, @Nullable Object[] parameters) { ___init___(node); } @Override protected <T> T invokeSpecial0(@NotNull SNode node, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { case 0: return (T) ((List<SNode>) GeefLijstMetInvoerKenmerken_id6$f4rrvMdoa(node)); default: throw new BHMethodNotFoundException(this, method); } } @Override protected <T> T invokeSpecial0(@NotNull SAbstractConcept concept, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { default: throw new BHMethodNotFoundException(this, method); } } @NotNull @Override public List<SMethod<?>> getDeclaredMethods() { return BH_METHODS; } @NotNull @Override public SAbstractConcept getConcept() { return CONCEPT; } }
agpl-3.0
geomajas/geomajas-project-deskmanager
widget-editors/src/main/java/org/geomajas/widget/advancedviews/editor/client/LayerConfigPanel.java
3970
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.widget.advancedviews.editor.client; import org.geomajas.widget.advancedviews.client.AdvancedViewsMessages; import org.geomajas.widget.advancedviews.editor.client.ThemeConfigurationPanel.State; import com.google.gwt.core.client.GWT; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.RadioGroupItem; import com.smartgwt.client.widgets.form.fields.SliderItem; import com.smartgwt.client.widgets.form.fields.StaticTextItem; import com.smartgwt.client.widgets.form.fields.events.ChangedEvent; import com.smartgwt.client.widgets.form.fields.events.ChangedHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.Layout; /** * @author Oliver May * */ public class LayerConfigPanel extends Layout { private static final int FORMITEM_WIDTH = 300; private DynamicForm form; private StaticTextItem layerTitle; private RadioGroupItem visibility; private SliderItem opacity; private ThemeConfigurationPanel themeConfigurationPanel; private static final AdvancedViewsMessages MESSAGES = GWT.create(AdvancedViewsMessages.class); /** * @param themeConfigurationPanel */ public LayerConfigPanel(ThemeConfigurationPanel themeConfigurationPanel) { super(); this.themeConfigurationPanel = themeConfigurationPanel; layout(); } private void layout() { // Left layout HLayout layout = new HLayout(); form = new DynamicForm(); // form.setWidth(ThemeConfigurationPanel.LEFT_WIDTH); form.setAutoFocus(true); form.setWidth(FORMITEM_WIDTH + 100); // form.setWrapItemTitles(false); layerTitle = new StaticTextItem(); layerTitle.setTitle(MESSAGES.themeConfigLayerTitle()); layerTitle.setRequired(true); layerTitle.setWidth(FORMITEM_WIDTH); visibility = new RadioGroupItem(); visibility.setTitle(MESSAGES.themeConfigLayerVisibility()); visibility.setValueMap(MESSAGES.themeConfigLayerVisibilityOn(), MESSAGES.themeConfigLayerVisibilityOff()); visibility.setRequired(true); visibility.setWidth(FORMITEM_WIDTH); visibility.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { themeConfigurationPanel.getState().getLayerConfig() .setVisible(MESSAGES.themeConfigLayerVisibilityOn().equals(visibility.getValueAsString())); } }); opacity = new SliderItem(); opacity.setTitle(MESSAGES.themeConfigLayerOpacity()); opacity.setMinValue(0); opacity.setMaxValue(100); opacity.setWidth(FORMITEM_WIDTH); opacity.setRequired(true); opacity.addChangedHandler(new ChangedHandler() { public void onChanged(ChangedEvent event) { themeConfigurationPanel.getState().getLayerConfig().setOpacity(opacity.getValueAsFloat() / 100); } }); form.setFields(layerTitle, visibility, opacity); layout.addMember(form); HLayout group = new HLayout(); group.setPadding(10); group.setIsGroup(true); group.setGroupTitle(MESSAGES.themeConfigThemeConfigGroup()); group.addMember(form); group.setOverflow(Overflow.AUTO); addMember(group); } /** * @param state */ public void update(State state) { if (state.getLayerConfig() != null) { layerTitle.setValue(state.getLayerConfig().getLayer().getLabel()); if (state.getLayerConfig().isVisible()) { visibility.setValue(MESSAGES.themeConfigLayerVisibilityOn()); } else { visibility.setValue(MESSAGES.themeConfigLayerVisibilityOff()); } opacity.setValue(state.getLayerConfig().getOpacity() * 100); } } }
agpl-3.0
crosslink/xowa
dev/400_xowa/src/gplx/xowa/apps/Xoa_shell_tst.java
1541
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012 gnosygnu@gmail.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 gplx.xowa.apps; import gplx.*; import gplx.xowa.*; import org.junit.*; public class Xoa_shell_tst { @Test public void Fetch_page() { // PURPOSE.fix: fetch_page failed with nullRef; DATE:2013-04-12 Xop_fxt parser_fxt = new Xop_fxt(); Xoa_app app = parser_fxt.App(); Xow_wiki wiki = parser_fxt.Wiki(); parser_fxt.Init_page_create("A", "test"); // need to create page in order for html output to gen wiki.Html_mgr().Page_wtr_mgr().Html_capable_(true); // need to set html_capable in order for div_home to load Xoa_gfs_mgr.Msg_parser_init(); wiki.Html_mgr().Portal_mgr().Div_home_fmtr().Fmt_("~{<>app.user.msgs.get('mainpage-description');<>}"); app.Gfs_mgr().Run_str("app.shell.fetch_page('en.wikipedia.org/wiki/A' 'html');"); // this causes a nullRef error b/c app.user.lang is null } }
agpl-3.0
RestComm/jss7
tools/trace-parser/bootstrap/src/main/java/org/restcomm/protocols/ss7/tools/traceparser/bootstrap/Main.java
11445
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.tools.traceparser.bootstrap; import java.awt.EventQueue; import java.beans.XMLDecoder; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; import org.restcomm.protocols.ss7.tools.traceparser.MainGui; import org.restcomm.protocols.ss7.tools.traceparser.Ss7ParseParameters; /** * @author <a href="mailto:amit.bhayani@jboss.com">amit bhayani</a> */ public class Main { // private static final String APP_NAME = "SS7 Trace Parser"; private static final String HOME_DIR = "TRACE_PARSER_HOME"; private static final String LOG4J_URL = "/conf/log4j.properties"; private static final String LOG4J_URL_XML = "/conf/log4j.xml"; public static final String TRACE_PARSER_HOME = "traceparser.home.dir"; public static final String TRACE_PARSER_DATA = "traceparser.data.dir"; private static int index = 0; private static Logger logger = Logger.getLogger(Main.class); // private String command = null; // private String appName = "main"; // private int rmiPort = -1; // private int httpPort = -1; public static void main(String[] args) throws Throwable { String homeDir = getHomeDir(args); System.setProperty(TRACE_PARSER_HOME, homeDir); String dataDir = homeDir + File.separator + "data" + File.separator; System.setProperty(TRACE_PARSER_DATA, dataDir); if (!initLOG4JProperties(homeDir) && !initLOG4JXml(homeDir)) { logger.error("Failed to initialize loggin, no configuration. Defaults are used."); } logger.info("log4j configured"); Ss7ParseParameters par = null; String persistDir = homeDir + File.separator + "data"; try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(persistDir + File.separator + "Ss7ParseParameters.xml")); XMLDecoder d = new XMLDecoder(bis); par = (Ss7ParseParameters) d.readObject(); d.close(); } catch (Exception e) { // we ignore exceptions } Main main = new Main(); // main.processCommandLine(args); main.boot(persistDir, par); } // private void processCommandLine(String[] args) { // // String programName = System.getProperty("program.name", APP_NAME); // // int c; // String arg; // LongOpt[] longopts = new LongOpt[5]; // longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'); // longopts[1] = new LongOpt("name", LongOpt.REQUIRED_ARGUMENT, null, 'n'); // longopts[2] = new LongOpt("http", LongOpt.REQUIRED_ARGUMENT, null, 't'); // longopts[3] = new LongOpt("rmi", LongOpt.REQUIRED_ARGUMENT, null, 'r'); // longopts[4] = new LongOpt("core", LongOpt.NO_ARGUMENT, null, 0); // // Getopt g = new Getopt(APP_NAME, args, "-:n:t:r:h", longopts); // g.setOpterr(false); // We'll do our own error handling // // // while ((c = g.getopt()) != -1) { // switch (c) { // // case 't': // // http port // arg = g.getOptarg(); // this.httpPort = Integer.parseInt(arg); // if (this.httpPort < 0 || this.httpPort > 65000) { // System.err.println("Http port should be in range 0 to 65000"); // System.exit(0); // } // break; // case 'r': // // rmi port // arg = g.getOptarg(); // this.rmiPort = Integer.parseInt(arg); // if (this.rmiPort < 0 || this.rmiPort > 65000) { // System.err.println("RMI port should be in range 0 to 65000"); // System.exit(0); // } // break; // case 'n': // // name // arg = g.getOptarg(); // this.appName = arg; // break; // // case 'h': // this.genericHelp(); // break; // // case ':': // System.out.println("You need an argument for option " + (char) g.getOptopt()); // System.exit(0); // break; // case '?': // System.out.println("The option '" + (char) g.getOptopt() + "' is not valid"); // System.exit(0); // break; // case 1: // String optArg = g.getOptarg(); // if (optArg.equals("core")) { // this.command = "core"; // } else if (optArg.equals("gui")) { // this.command = "gui"; // } else if (optArg.equals("help")) { // if (this.command == null) { // this.genericHelp(); // } else if (this.command.equals("core")) { // this.coreHelp(); // } else if (this.command.equals("gui")) { // this.guiHelp(); // } else { // System.out.println("Invalid command " + optArg); // this.genericHelp(); // } // } else { // System.out.println("Invalid command " + optArg); // this.genericHelp(); // } // break; // // default: // this.genericHelp(); // break; // } // } // // } // // private void genericHelp() { // System.out.println("usage: " + APP_NAME + "<command> [options]"); // System.out.println(); // System.out.println("command:"); // System.out.println(" core Start the SS7 Trace Parser core"); // System.out.println(" gui Start the SS7 Trace Parser gui"); // System.out.println(); // System.out.println("see 'run <command> help' for more information on a specific command:"); // System.out.println(); // System.exit(0); // } // // private void coreHelp() { // System.out.println("core: Starts the Trace Parser core"); // System.out.println(); // System.out.println("usage: " + APP_NAME + " core [options]"); // System.out.println(); // System.out.println("options:"); // System.out.println(" -n, --name=<Trace Parser name> Trace Parser name. If not passed default is main"); // System.out.println(" -t, --http=<http port> Http port for core"); // System.out.println(" -r, --rmi=<rmi port> RMI port for core"); // System.out.println(); // System.exit(0); // } // // private void guiHelp() { // System.out.println("gui: Starts the Trace Parser gui"); // System.out.println(); // System.out.println("usage: " + APP_NAME + " gui [options]"); // System.out.println(); // System.out.println("options:"); // System.out.println(" -n, --name=<Trace Parser name> Trace Parser name. If not passed default is main"); // System.out.println(); // System.exit(0); // } private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { // e.printStackTrace(); logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; } private static boolean initLOG4JXml(String homeDir) { String Log4jURL = homeDir + LOG4J_URL_XML; try { URL log4jurl = getURL(Log4jURL); DOMConfigurator.configure(log4jurl); } catch (Exception e) { // e.printStackTrace(); logger.info("Failed to initialize LOG4J with xml file."); return false; } return true; } /** * Gets the Media Server Home directory. * * @param args the command line arguments * @return the path to the home directory. */ private static String getHomeDir(String[] args) { if (System.getenv(HOME_DIR) == null) { if (args.length > index) { return args[index++]; } else { return "."; } } else { return System.getenv(HOME_DIR); } } protected void boot(String persistDir, Ss7ParseParameters par) throws Throwable { // if (this.command == null) { // System.out.println("No command passed"); // this.genericHelp(); // } else if (this.command.equals("gui")) { // EventQueue.invokeLater(new MainGui(appName)); // } else if (this.command.equals("core")) { // MainCore mainCore = new MainCore(); // mainCore.start(appName, httpPort, rmiPort); // } MainGui mainGui = new MainGui(persistDir, par); EventQueue.invokeLater(mainGui); } public static URL getURL(String url) throws Exception { File file = new File(url); if (file.exists() == false) { throw new IllegalArgumentException("No such file: " + url); } return file.toURI().toURL(); } // protected void registerShutdownThread() { // Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownThread())); // } // // private class ShutdownThread implements Runnable { // // public void run() { // System.out.println("Shutting down"); // // } // } }
agpl-3.0
sturesy/client
src/src-main/sturesy/core/ui/filetree/FileTreeCellRenderer.java
1490
/* * StuReSy - Student Response System * Copyright (C) 2012-2014 StuReSy-Team * * 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 sturesy.core.ui.filetree; import java.awt.Component; import java.io.File; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellRenderer; /** * TreeCellRenderer only for Files * * @author w.posdorfer * */ public class FileTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel s = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); s.setText(((File) value).getName()); return s; } }
agpl-3.0
MackieLoeffel/wahlzeit
src/main/java/org/wahlzeit/handlers/SendEmailFormHandler.java
4569
/* * Copyright (c) 2006-2009 by Dirk Riehle, http://dirkriehle.com * * This file is part of the Wahlzeit photo rating application. * * 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 org.wahlzeit.handlers; import org.wahlzeit.model.AccessRights; import org.wahlzeit.model.ArchitecturePhotoManager; import org.wahlzeit.model.ModelConfig; import org.wahlzeit.model.Photo; import org.wahlzeit.model.User; import org.wahlzeit.model.UserManager; import org.wahlzeit.model.UserSession; import org.wahlzeit.services.LogBuilder; import org.wahlzeit.services.mailing.EmailService; import org.wahlzeit.services.mailing.EmailServiceManager; import org.wahlzeit.webparts.WebPart; import java.util.Map; import java.util.logging.Logger; /** * A handler class for a specific web form. */ public class SendEmailFormHandler extends AbstractWebFormHandler { /** * */ public static final String USER = "user"; public static final String USER_LANGUAGE = "userLanguage"; public static final String EMAIL_SUBJECT = "emailSubject"; public static final String EMAIL_BODY = "emailBody"; private static final Logger log = Logger.getLogger(SendEmailFormHandler.class.getName()); /** * */ public SendEmailFormHandler() { initialize(PartUtil.SEND_EMAIL_FORM_FILE, AccessRights.GUEST); } /** * */ public boolean isWellFormedGet(UserSession us, String link, Map args) { return hasSavedPhotoId(us); } /** * */ protected String doHandleGet(UserSession us, String link, Map args) { if (!(us.getClient() instanceof User)) { us.setHeading(us.getClient().getLanguageConfiguration().getInformation()); us.setMessage(us.getClient().getLanguageConfiguration().getNeedToSignupFirst()); return PartUtil.SHOW_NOTE_PAGE_NAME; } return super.doHandleGet(us, link, args); } /** * */ protected void doMakeWebPart(UserSession us, WebPart part) { Map args = us.getSavedArgs(); part.addStringFromArgs(args, UserSession.MESSAGE); String id = us.getAndSaveAsString(args, Photo.ID); part.addString(Photo.ID, id); Photo photo = ArchitecturePhotoManager.getInstance().getPhoto(id); part.addString(Photo.THUMB, getPhotoThumb(us, photo)); part.maskAndAddString(USER, photo.getOwnerId()); User user = (User) us.getClient(); part.addString(USER_LANGUAGE, user.getLanguageConfiguration().asValueString(user.getLanguage())); part.maskAndAddStringFromArgs(args, EMAIL_SUBJECT); part.maskAndAddStringFromArgs(args, EMAIL_BODY); } /** * */ protected boolean isWellFormedPost(UserSession us, Map args) { return ArchitecturePhotoManager.getInstance().getPhoto(us.getAsString(args, Photo.ID)) != null; } /** * */ protected String doHandlePost(UserSession us, Map args) { String id = us.getAndSaveAsString(args, Photo.ID); Photo photo = ArchitecturePhotoManager.getInstance().getPhoto(id); String emailSubject = us.getAndSaveAsString(args, EMAIL_SUBJECT); String emailBody = us.getAndSaveAsString(args, EMAIL_BODY); ModelConfig config = us.getClient().getLanguageConfiguration(); if ((emailSubject.length() > 128) || (emailBody.length() > 1024)) { us.setMessage(config.getInputIsTooLong()); return PartUtil.SEND_EMAIL_PAGE_NAME; } UserManager userManager = UserManager.getInstance(); User toUser = userManager.getUserById(photo.getOwnerId()); emailSubject = config.getSendEmailSubjectPrefix() + emailSubject; emailBody = config.getSendEmailBodyPrefix() + emailBody + config.getSendEmailBodyPostfix(); EmailService emailService = EmailServiceManager.getDefaultService(); emailService.sendEmailIgnoreException(toUser.getEmailAddress(), config.getAuditEmailAddress(), emailSubject, emailBody); log.info(LogBuilder.createUserMessage(). addAction("Send E-Mail"). addParameter("Recipient", toUser.getNickName()).toString()); us.setMessage(config.getEmailWasSent() + toUser.getNickName() + "!"); return PartUtil.SHOW_NOTE_PAGE_NAME; } }
agpl-3.0
qcri-social/Crisis-Computing
aidr-manager/src/main/java/qa/qcri/aidr/manager/service/CollectionLogService.java
1363
package qa.qcri.aidr.manager.service; import java.util.List; import java.util.Map; import qa.qcri.aidr.manager.dto.CollectionLogDataResponse; import qa.qcri.aidr.manager.exception.AidrException; import qa.qcri.aidr.manager.persistence.entities.CollectionLog; public interface CollectionLogService { public void update(CollectionLog collection) throws Exception; public void delete(CollectionLog collection) throws Exception; public void create(CollectionLog collection) throws Exception; public CollectionLog findById(Long id) throws Exception; public CollectionLogDataResponse findAll(Integer start, Integer limit) throws Exception; public CollectionLogDataResponse findAllForCollection(Integer start, Integer limit, Long collectionId) throws Exception; public Integer countTotalDownloadedItemsForCollection(Long collectionId) throws Exception; public Map<Integer, Integer> countTotalDownloadedItemsForCollectionIds(List<Long> ids) throws Exception; public Map<String, Object> generateCSVLink(String code) throws Exception; public Map<String, Object> generateTweetIdsLink(String code) throws Exception; public Map<String, Object> generateJSONLink(String code, String jsonType) throws AidrException; public Map<String, Object> generateJsonTweetIdsLink(String code, String jsonType) throws AidrException; }
agpl-3.0
ColostateResearchServices/kc
coeus-impl/src/main/java/edu/iu/uits/kra/negotiations/lookup/IUNegotiationDaoOjb.java
35368
/* * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.iu.uits.kra.negotiations.lookup; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.ojb.broker.PersistenceBroker; import org.apache.ojb.broker.accesslayer.LookupException; import org.apache.ojb.broker.query.Criteria; import org.apache.ojb.broker.query.QueryFactory; import org.apache.ojb.broker.query.ReportQueryByCriteria; import org.kuali.kra.award.home.Award; import org.kuali.coeus.common.framework.version.VersionStatus; import org.kuali.kra.institutionalproposal.home.InstitutionalProposal; import org.kuali.kra.institutionalproposal.proposallog.ProposalLog; import org.kuali.kra.negotiations.bo.Negotiation; import org.kuali.kra.negotiations.bo.NegotiationAssociationType; import org.kuali.kra.negotiations.bo.NegotiationUnassociatedDetail; import org.kuali.kra.negotiations.lookup.NegotiationDao; import org.kuali.kra.negotiations.service.NegotiationService; import org.kuali.kra.subaward.bo.SubAward; import org.kuali.rice.core.api.util.RiceKeyConstants; import org.kuali.rice.kew.api.WorkflowRuntimeException; import org.kuali.rice.kns.datadictionary.BusinessObjectEntry; import org.kuali.rice.kns.service.KNSServiceLocator; import org.kuali.rice.krad.bo.BusinessObject; import org.kuali.rice.krad.dao.impl.LookupDaoOjb; import org.kuali.rice.krad.lookup.CollectionIncomplete; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.springframework.dao.DataIntegrityViolationException; import org.springmodules.orm.ojb.OjbFactoryUtils; import org.springmodules.orm.ojb.OjbOperationException; import edu.iu.uits.kra.negotiations.bo.IUNegotiationAssociationTypeUtil; /** * Negotiation Dao to assist with lookups. This implements looking up associated document information * as well as just negotiation info. */ public class IUNegotiationDaoOjb extends LookupDaoOjb implements NegotiationDao { private static final String ASSOC_PREFIX = "associatedNegotiable"; private static final String NEGOTIATION_TYPE_ATTR = "negotiationAssociationTypeId"; private static final String ASSOCIATED_DOC_ID_ATTR = "associatedDocumentId"; private static final String INVALID_COLUMN_NAME = "NaN"; private static Map<String, String> awardTransform; private static Map<String, String> proposalTransform; private static Map<String, String> proposalLogTransform; private static Map<String, String> unassociatedTransform; private static Map<String, String> subAwardTransform; private static Integer maxSearchResults; private NegotiationService negotiationService; private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(IUNegotiationDaoOjb.class); static { awardTransform = new HashMap<String, String>(); awardTransform.put("sponsorName", "sponsor.sponsorName"); awardTransform.put("piName", "projectPersons.fullName"); //proposal type code doesn't exist on the award so make sure we don't find awards when //search for proposal type awardTransform.put("negotiableProposalTypeCode", INVALID_COLUMN_NAME); awardTransform.put("leadUnitNumber", "unitNumber"); awardTransform.put("leadUnitName", "leadUnit.unitName"); awardTransform.put("subAwardRequisitionerId", INVALID_COLUMN_NAME); proposalTransform = new HashMap<String, String>(); proposalTransform.put("sponsorName", "sponsor.sponsorName"); proposalTransform.put("piName", "projectPersons.fullName"); proposalTransform.put("leadUnitNumber", "unitNumber"); proposalTransform.put("leadUnitName", "leadUnit.unitName"); proposalTransform.put("negotiableProposalTypeCode", "proposalTypeCode"); proposalTransform.put("subAwardRequisitionerId", INVALID_COLUMN_NAME); proposalLogTransform = new HashMap<String, String>(); proposalLogTransform.put("sponsorName", "sponsor.sponsorName"); proposalLogTransform.put("leadUnitNumber", "leadUnit"); proposalLogTransform.put("leadUnitName", "unit.unitName"); proposalLogTransform.put("negotiableProposalTypeCode", "proposalTypeCode"); proposalLogTransform.put("subAwardRequisitionerId", INVALID_COLUMN_NAME); unassociatedTransform = new HashMap<String, String>(); unassociatedTransform.put("sponsorName", "sponsor.sponsorName"); unassociatedTransform.put("piName", "piName"); //proposal type code doesn't exist here either so make sure we don't find then when //searching for proposal type unassociatedTransform.put("negotiableProposalTypeCode", INVALID_COLUMN_NAME); unassociatedTransform.put("leadUnitName", "leadUnit.unitName"); unassociatedTransform.put("subAwardRequisitionerId", INVALID_COLUMN_NAME); subAwardTransform = new HashMap<String, String>(); subAwardTransform.put("sponsorName", INVALID_COLUMN_NAME); subAwardTransform.put("sponsorCode", INVALID_COLUMN_NAME); subAwardTransform.put("piName", INVALID_COLUMN_NAME); subAwardTransform.put("negotiableProposalTypeCode", INVALID_COLUMN_NAME); subAwardTransform.put("leadUnitName", "leadUnit.unitName"); subAwardTransform.put("subAwardRequisitionerId", "requisitionerId"); /* Begin IU Customization */ // UITSRA-3711 subAwardTransform.put("leadUnitNumber", "requisitionerUnit"); /* End IU Customization */ /* Begin IU Customization */ // UITSRA-2893, UITSRA-2894 //Per Core meeting on 11/12/2013, we are not going to display subAwardOrganizationName for awards or IPs (for now) awardTransform.put("subAwardOrganizationName", INVALID_COLUMN_NAME); proposalTransform.put("subAwardOrganizationName", INVALID_COLUMN_NAME); proposalLogTransform.put("subAwardOrganizationName", INVALID_COLUMN_NAME); unassociatedTransform.put("subAwardOrganizationName", "subAwardOrganization.organizationName"); subAwardTransform.put("subAwardOrganizationName", "organization.organizationName"); /* End IU Customization */ } @SuppressWarnings("unchecked") @Override public Collection<Negotiation> getNegotiationResults(Map<String, String> fieldValues) { Map<String, String> associationDetails = new HashMap<String, String>(); Iterator<Map.Entry<String, String>> iter = fieldValues.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); if (StringUtils.startsWith(entry.getKey(), ASSOC_PREFIX)) { iter.remove(); if (!StringUtils.isEmpty(entry.getValue())) { associationDetails.put(entry.getKey().replaceFirst(ASSOC_PREFIX + ".", ""), entry.getValue()); } } } Collection<Negotiation> result = new ArrayList<Negotiation>(); if (!associationDetails.isEmpty()) { /* Begin IU Customization UITSRA-4033 */ long totalMatchingResultsCount = 0L; if (StringUtils.isEmpty(fieldValues.get("negotiationAssociationTypeId")) || StringUtils.equals(getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.AWARD_ASSOCIATION).getId().toString(), fieldValues.get("negotiationAssociationTypeId").trim())) { Collection<Negotiation> resultLinkedToAward = getNegotiationsLinkedToAward(fieldValues, associationDetails); totalMatchingResultsCount += ((CollectionIncomplete<Negotiation>) resultLinkedToAward).getActualSizeIfTruncated().longValue(); addListToList(result, resultLinkedToAward); } if (StringUtils.isEmpty(fieldValues.get("negotiationAssociationTypeId")) || StringUtils.equals(getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.INSTITUATIONAL_PROPOSAL_ASSOCIATION).getId().toString(), fieldValues.get("negotiationAssociationTypeId").trim())) { Collection<Negotiation> resultLinkedToProposal = getNegotiationsLinkedToProposal(fieldValues, associationDetails); totalMatchingResultsCount += ((CollectionIncomplete<Negotiation>) resultLinkedToProposal).getActualSizeIfTruncated().longValue(); addListToList(result, resultLinkedToProposal); } if (StringUtils.isEmpty(fieldValues.get("negotiationAssociationTypeId")) || StringUtils.equals(getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.PROPOSAL_LOG_ASSOCIATION).getId().toString(), fieldValues.get("negotiationAssociationTypeId").trim())) { Collection<Negotiation> resultLinkedToProposalLog = getNegotiationsLinkedToProposalLog(fieldValues, associationDetails); totalMatchingResultsCount += ((CollectionIncomplete<Negotiation>) resultLinkedToProposalLog).getActualSizeIfTruncated().longValue(); addListToList(result, resultLinkedToProposalLog); } if (StringUtils.isEmpty(fieldValues.get("negotiationAssociationTypeId")) || StringUtils.equals(getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.NONE_ASSOCIATION).getId().toString(), fieldValues.get("negotiationAssociationTypeId").trim())) { Collection<Negotiation> resultLinkedToUnassociated = getNegotiationsUnassociated(fieldValues, associationDetails); totalMatchingResultsCount += ((CollectionIncomplete<Negotiation>) resultLinkedToUnassociated).getActualSizeIfTruncated().longValue(); addListToList(result, resultLinkedToUnassociated); } if (StringUtils.isEmpty(fieldValues.get("negotiationAssociationTypeId")) || StringUtils.equals(getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.SUB_AWARD_ASSOCIATION).getId().toString(), fieldValues.get("negotiationAssociationTypeId").trim())) { Collection<Negotiation> resultLinkedToSubAward = getNegotiationsLinkedToSubAward(fieldValues, associationDetails); CollectionIncomplete<Negotiation> subAwardCollectionIncomplete = new CollectionIncomplete<Negotiation>(resultLinkedToSubAward, (long)resultLinkedToSubAward.size()); totalMatchingResultsCount += subAwardCollectionIncomplete.getActualSizeIfTruncated().longValue(); addListToList(result, resultLinkedToSubAward); } result = new CollectionIncomplete<Negotiation>(result, totalMatchingResultsCount); /* End IU Customization */ } else { result = findCollectionBySearchHelper(Negotiation.class, fieldValues, false, false, null); } if (result != null && !result.isEmpty() && StringUtils.isNotBlank(fieldValues.get("negotiationAge"))) { try { result = filterByNegotiationAge(fieldValues.get("negotiationAge"), result); } catch (NumberFormatException e) { GlobalVariables.getMessageMap().putError(KRADConstants.DOCUMENT_ERRORS, RiceKeyConstants.ERROR_CUSTOM, new String[] { "Invalid Numeric Input: " + fieldValues.get("negotiationAge")}); result = new ArrayList<Negotiation>(); } } return result; } private void addListToList(Collection<Negotiation> fullResultList, Collection<Negotiation> listToAdd) { if (fullResultList != null && listToAdd != null) { Integer max = getNegotiatonSearchResultsLimit(); if (max == null) { max = 500; } if (fullResultList.size() < max) { int fullResultListPlusListToAddSize = fullResultList.size() + listToAdd.size(); if (fullResultListPlusListToAddSize <= max) { fullResultList.addAll(listToAdd); } else { int numberOfNewEntriesToAdd = max - fullResultList.size(); int counter = 0; for (Negotiation neg : listToAdd) { if (counter < numberOfNewEntriesToAdd) { fullResultList.add(neg); } counter++; } } } } } public Collection findCollectionBySearchHelper(Class businessObjectClass, Map formProps, boolean unbounded, boolean usePrimaryKeyValuesOnly, Object additionalCriteria ) { BusinessObject businessObject = checkBusinessObjectClass(businessObjectClass); if (usePrimaryKeyValuesOnly) { return executeSearch(businessObjectClass, getCollectionCriteriaFromMapUsingPrimaryKeysOnly(businessObjectClass, formProps), unbounded); } Criteria crit = getCollectionCriteriaFromMap(businessObject, formProps); if (additionalCriteria != null && additionalCriteria instanceof Criteria) { crit.addAndCriteria((Criteria) additionalCriteria); } return executeSearch(businessObjectClass, crit, unbounded); } private BusinessObject checkBusinessObjectClass(Class businessObjectClass) { if (businessObjectClass == null) { throw new IllegalArgumentException("BusinessObject class passed to LookupDaoOjb findCollectionBySearchHelper... method was null"); } BusinessObject businessObject = null; try { businessObject = (BusinessObject) businessObjectClass.newInstance(); } catch (IllegalAccessException e) { throw new RuntimeException("LookupDaoOjb could not get instance of " + businessObjectClass.getName(), e); } catch (InstantiationException e) { throw new RuntimeException("LookupDaoOjb could not get instance of " + businessObjectClass.getName(), e); } return businessObject; } private Collection executeSearch(Class businessObjectClass, Criteria criteria, boolean unbounded) { Collection searchResults = new ArrayList(); Long matchingResultsCount = null; try { Integer searchResultsLimit = getNegotiatonSearchResultsLimit(); if (!unbounded && (searchResultsLimit != null)) { matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(businessObjectClass, criteria))); getDbPlatform().applyLimitSql(searchResultsLimit); } if ((matchingResultsCount == null) || (matchingResultsCount.intValue() <= searchResultsLimit.intValue())) { matchingResultsCount = new Long(0); } searchResults = getPersistenceBrokerTemplate().getCollectionByQuery(QueryFactory.newQuery(businessObjectClass, criteria)); // populate Person objects in business objects List bos = new ArrayList(); bos.addAll(searchResults); searchResults = bos; } catch (OjbOperationException e) { throw new RuntimeException("NegotiationDaoOjb encountered exception during executeSearch", e); } catch (DataIntegrityViolationException e) { throw new RuntimeException("NegotiationDaoOjb encountered exception during executeSearch", e); } return new CollectionIncomplete(searchResults, matchingResultsCount); } private Integer getNegotiatonSearchResultsLimit(){ if (maxSearchResults == null) { BusinessObjectEntry businessObjectEntry = (BusinessObjectEntry) KNSServiceLocator.getDataDictionaryService().getDataDictionary().getBusinessObjectEntry("Negotiation"); maxSearchResults = businessObjectEntry.getLookupDefinition().getResultSetLimit(); } return maxSearchResults; } /** * Search for awards linked to negotiation using both award and negotiation values. * @param negotiationValues * @param associatedValues * @return */ @SuppressWarnings("unchecked") protected CollectionIncomplete<Negotiation> getNegotiationsLinkedToAward(Map<String, String> negotiationValues, Map<String, String> associatedValues) { Map<String, String> values = transformMap(associatedValues, awardTransform); if (values == null) { return new CollectionIncomplete<Negotiation>(new ArrayList<Negotiation>(), 0L); } values.put("awardSequenceStatus", VersionStatus.ACTIVE.name()); Criteria criteria = getCollectionCriteriaFromMap(new Award(), values); Criteria negotiationCrit = new Criteria(); ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(Award.class, criteria); subQuery.setAttributes(new String[] {"awardNumber"}); negotiationCrit.addIn(ASSOCIATED_DOC_ID_ATTR, subQuery); negotiationCrit.addEqualTo(NEGOTIATION_TYPE_ATTR, getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.AWARD_ASSOCIATION).getId()); Collection<Negotiation> result = this.findCollectionBySearchHelper(Negotiation.class, negotiationValues, false, false, negotiationCrit); Long matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(Negotiation.class, negotiationCrit))); return new CollectionIncomplete<Negotiation>(result, matchingResultsCount); } /** * Search for institutional proposals linked to negotiations using both criteria. * @param negotiationValues * @param associatedValues * @return */ @SuppressWarnings("unchecked") protected CollectionIncomplete<Negotiation> getNegotiationsLinkedToProposal(Map<String, String> negotiationValues, Map<String, String> associatedValues) { Map<String, String> values = transformMap(associatedValues, proposalTransform); if (values == null) { return new CollectionIncomplete<Negotiation>(new ArrayList<Negotiation>(), 0L); } values.put("proposalSequenceStatus", VersionStatus.ACTIVE.name()); Criteria criteria = getCollectionCriteriaFromMap(new InstitutionalProposal(), values); Criteria negotiationCrit = new Criteria(); ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(InstitutionalProposal.class, criteria); subQuery.setAttributes(new String[] {"proposalNumber"}); negotiationCrit.addIn(ASSOCIATED_DOC_ID_ATTR, subQuery); negotiationCrit.addEqualTo(NEGOTIATION_TYPE_ATTR, getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.INSTITUATIONAL_PROPOSAL_ASSOCIATION).getId()); Collection<Negotiation> result = this.findCollectionBySearchHelper(Negotiation.class, negotiationValues, false, false, negotiationCrit); // UITSRA-4033 Long matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(Negotiation.class, negotiationCrit))); return new CollectionIncomplete<Negotiation>(result, matchingResultsCount); } /** * Search for proposal logs linked to negotiations using both criteria. * @param negotiationValues * @param associatedValues * @return */ @SuppressWarnings("unchecked") protected CollectionIncomplete<Negotiation> getNegotiationsLinkedToProposalLog(Map<String, String> negotiationValues, Map<String, String> associatedValues) { Map<String, String> values = transformMap(associatedValues, proposalLogTransform); if (values == null) { return new CollectionIncomplete<Negotiation>(new ArrayList<Negotiation>(), 0L); } Criteria criteria = getCollectionCriteriaFromMap(new ProposalLog(), values); Criteria negotiationCrit = new Criteria(); ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(ProposalLog.class, criteria); subQuery.setAttributes(new String[] {"proposalNumber"}); negotiationCrit.addIn(ASSOCIATED_DOC_ID_ATTR, subQuery); negotiationCrit.addEqualTo(NEGOTIATION_TYPE_ATTR, getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.PROPOSAL_LOG_ASSOCIATION).getId()); Collection<Negotiation> result = this.findCollectionBySearchHelper(Negotiation.class, negotiationValues, false, false, negotiationCrit); Long matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(Negotiation.class, negotiationCrit))); return new CollectionIncomplete<Negotiation>(result, matchingResultsCount); } /** * * This method returns Negotiations linked to subawards based on search. * @param negotiationValues * @param associatedValues * @return */ @SuppressWarnings("unchecked") protected CollectionIncomplete<Negotiation> getNegotiationsLinkedToSubAward(Map<String, String> negotiationValues, Map<String, String> associatedValues) { Map<String, String> values = transformMap(associatedValues, subAwardTransform); if (values == null) { return new CollectionIncomplete<Negotiation>(new ArrayList<Negotiation>(), 0L); } values.put("statusCode", "1|6"); Criteria criteria = getCollectionCriteriaFromMap(new SubAward(), values); Criteria negotiationCrit = new Criteria(); ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(SubAward.class, criteria); /* IU Customization Starts */ // UITSRA-4197 Negotiation Title Search is returning inaccurate results subQuery.setAttributes(new String[] {"subAwardCode"}); /* IU Customization Ends */ negotiationCrit.addIn(ASSOCIATED_DOC_ID_ATTR, subQuery); negotiationCrit.addEqualTo(NEGOTIATION_TYPE_ATTR, getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.SUB_AWARD_ASSOCIATION).getId()); Collection<Negotiation> result = this.findCollectionBySearchHelper(Negotiation.class, negotiationValues, false, false, negotiationCrit); Long matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(Negotiation.class, negotiationCrit))); return new CollectionIncomplete<Negotiation>(result, matchingResultsCount); } /** * Search for unassociated negotiations using criteria from the unassociated detail. * @param negotiationValues * @param associatedValues * @return */ @SuppressWarnings("unchecked") protected CollectionIncomplete<Negotiation> getNegotiationsUnassociated(Map<String, String> negotiationValues, Map<String, String> associatedValues) { Map<String, String> values = transformMap(associatedValues, unassociatedTransform); if (values == null) { return new CollectionIncomplete<Negotiation>(new ArrayList<Negotiation>(), 0L); } Criteria criteria = getCollectionCriteriaFromMap(new NegotiationUnassociatedDetail(), values); Criteria negotiationCrit = new Criteria(); ReportQueryByCriteria subQuery = QueryFactory.newReportQuery(NegotiationUnassociatedDetail.class, criteria); subQuery.setAttributes(new String[] {"negotiationUnassociatedDetailId"}); negotiationCrit.addIn(ASSOCIATED_DOC_ID_ATTR, subQuery); /* Begin UITSRA-3231 */ //negotiationCrit.addEqualTo(NEGOTIATION_TYPE_ATTR, // getNegotiationService().getNegotiationAssociationType(NegotiationAssociationType.NONE_ASSOCIATION).getId()); for(String associationType : IUNegotiationAssociationTypeUtil.LINKED_NEGOTIATION_ASSOCIATIONS) { negotiationCrit.addNotEqualTo(NEGOTIATION_TYPE_ATTR, getNegotiationService().getNegotiationAssociationType(associationType).getId()); } /* End UITSRA-3231 */ Collection<Negotiation> result = this.findCollectionBySearchHelper(Negotiation.class, negotiationValues, false, false, negotiationCrit); Long matchingResultsCount = new Long(getPersistenceBrokerTemplate().getCount(QueryFactory.newQuery(Negotiation.class, negotiationCrit))); return new CollectionIncomplete<Negotiation>(result, matchingResultsCount); } /** * Take the associated field values and convert them to document specific values using the provided * transform key. * @param values * @param transformKey * @return */ protected Map<String, String> transformMap(Map<String, String> values, Map<String, String> transformKey) { Map<String, String> result = new HashMap<String, String>(); for (Map.Entry<String, String> entry : values.entrySet()) { if (transformKey.get(entry.getKey()) != null) { result.put(transformKey.get(entry.getKey()), entry.getValue()); } else { result.put(entry.getKey(), entry.getValue()); } } if (result.containsKey(INVALID_COLUMN_NAME)) { return null; } else { return result; } } /** * Since the negotiation age is not persisted filter negotiations based on age. * @param value * @param negotiations * @return */ protected Collection<Negotiation> filterByNegotiationAge(String value, Collection<Negotiation> negotiations) { int lowValue = 0; int highValue = 0; boolean greaterThan = false; boolean lessThan = false; boolean between = false; if (value.contains(">")) { greaterThan = true; lowValue = Integer.parseInt(value.replace(">", "")); } else if (value.contains("<")) { lessThan = true; highValue = Integer.parseInt(value.replace("<", "")); } else if (value.contains("..")) { between = true; String[] values = value.split("\\.\\."); lowValue = Integer.parseInt(values[0]); highValue = Integer.parseInt(values[1]); } else { lowValue = Integer.parseInt(value); } Iterator<Negotiation> iter = negotiations.iterator(); while (iter.hasNext()) { Negotiation negotiation = iter.next(); if (greaterThan) { if (negotiation.getNegotiationAge() <= lowValue) { iter.remove(); } } else if (lessThan) { if (negotiation.getNegotiationAge() >= highValue) { iter.remove(); } } else if (between) { if (negotiation.getNegotiationAge() < lowValue || negotiation.getNegotiationAge() > highValue) { iter.remove(); } } else { if (negotiation.getNegotiationAge() != lowValue) { iter.remove(); } } } return negotiations; } public NegotiationService getNegotiationService() { return negotiationService; } public void setNegotiationService(NegotiationService negotiationService) { this.negotiationService = negotiationService; } /* IU Customization Starts UITSRA-3138 */ /** * @param searchString NegotiationId wild card search string * @return A list of NegotiationIds */ public Collection<Long> getNegotiationIdsWithWildcard(String searchString) { Collection<Long> negotiationIds = new ArrayList<Long>(); PersistenceBroker broker = null; Connection conn = null; ResultSet rs = null; PreparedStatement stmt = null; try { broker = getPersistenceBroker(false); conn = broker.serviceConnectionManager().getConnection(); String query = "SELECT negotiation_id FROM negotiation WHERE negotiation_id LIKE ?"; stmt = conn.prepareStatement(query); stmt.setString(1, StringUtils.replace(searchString, "*", "%")); rs = stmt.executeQuery(); try { while (rs.next()) { negotiationIds.add(rs.getLong(1)); } } finally { try { rs.close(); } catch (Exception ignore) { } } } catch (SQLException sqle) { LOG.error("SQLException: " + sqle.getMessage(), sqle); throw new WorkflowRuntimeException(sqle); } catch (LookupException le) { LOG.error("LookupException: " + le.getMessage(), le); throw new WorkflowRuntimeException(le); } finally { try { if(stmt != null) { stmt.close(); } if (broker != null) { OjbFactoryUtils.releasePersistenceBroker(broker, this.getPersistenceBrokerTemplate().getPbKey()); } } catch (Exception e) { LOG.error("Failed closing connection: " + e.getMessage(), e); } } return negotiationIds; } /** * @param piPersonId PI Person Id * @return A list of NegotiationIds searched by PI */ public Collection<Long> getNegotiationIdsByPI(String piPersonId) { Collection<Long> negotiationIds = new ArrayList<Long>(); PersistenceBroker broker = null; Connection conn = null; ResultSet rs = null; PreparedStatement stmt = null; try { broker = getPersistenceBroker(false); conn = broker.serviceConnectionManager().getConnection(); // UITSRA-3389 String query = "select NEGOTIATION_ID from NEGOTIATION where NEGOTIATION_ID in \n" + "(select NEGOTIATION_ID from NEGOTIATION_UNASSOC_DETAIL where PI_PERSON_ID=?) \n" + " UNION \n" + "select NEGOTIATION_ID from NEGOTIATION where \n" + "ASSOCIATED_DOCUMENT_ID in (select DISTINCT PROPOSAL_NUMBER from PROPOSAL_PERSONS where CONTACT_ROLE_CODE='PI' and PERSON_ID=? \n" + "and PROPOSAL_NUMBER = NEGOTIATION.ASSOCIATED_DOCUMENT_ID) and " + "NEGOTIATION_ASSC_TYPE_ID = (select NEGOTIATION_ASSC_TYPE_ID from NEGOTIATION_ASSOCIATION_TYPE where NEGOTIATION_ASSC_TYPE_CODE='IP') \n" + " UNION \n" + "select NEGOTIATION_ID from NEGOTIATION where \n" + "ASSOCIATED_DOCUMENT_ID in (select DISTINCT AWARD_NUMBER from AWARD_PERSONS where CONTACT_ROLE_CODE='PI' and PERSON_ID=? \n" + "and AWARD_NUMBER = NEGOTIATION.ASSOCIATED_DOCUMENT_ID) and \n" + "NEGOTIATION_ASSC_TYPE_ID = (select NEGOTIATION_ASSC_TYPE_ID from NEGOTIATION_ASSOCIATION_TYPE where NEGOTIATION_ASSC_TYPE_CODE='AWD')"; // End of UITSRA-3389 stmt = conn.prepareStatement(query); stmt.setString(1, piPersonId); stmt.setString(2, piPersonId); stmt.setString(3, piPersonId); rs = stmt.executeQuery(); try { while (rs.next()) { negotiationIds.add(rs.getLong(1)); } } finally { try { rs.close(); } catch (Exception ignore) { } } } catch (SQLException sqle) { LOG.error("SQLException: " + sqle.getMessage(), sqle); throw new WorkflowRuntimeException(sqle); } catch (LookupException le) { LOG.error("LookupException: " + le.getMessage(), le); throw new WorkflowRuntimeException(le); } finally { try { if(stmt != null) { stmt.close(); } if (broker != null) { OjbFactoryUtils.releasePersistenceBroker(broker, this.getPersistenceBrokerTemplate().getPbKey()); } } catch (Exception e) { LOG.error("Failed closing connection: " + e.getMessage(), e); } } return negotiationIds; } /* IU Customization Ends */ /** * @param subAwardRequisitionerId subAward Requisitioner ID * @return A list of NegotiationIds searched by subAwardRequisitionerId */ public Collection<Long> getNegotiationIdsByRequisitioner(String subAwardRequisitionerId) { Collection<Long> negotiationIds = new ArrayList<Long>(); PersistenceBroker broker = null; Connection conn = null; ResultSet rs = null; PreparedStatement stmt = null; try { broker = getPersistenceBroker(false); conn = broker.serviceConnectionManager().getConnection(); // UITSRA-3761 String query = "select NEGOTIATION_ID from NEGOTIATION where \n" + "ASSOCIATED_DOCUMENT_ID in (select SUBAWARD_CODE from SUBAWARD where REQUISITIONER_ID=?) \n" + "and NEGOTIATION_ASSC_TYPE_ID = \n" + "(select NEGOTIATION_ASSC_TYPE_ID from NEGOTIATION_ASSOCIATION_TYPE where NEGOTIATION_ASSC_TYPE_CODE = 'SWD')"; // End of UITSRA-3761 stmt = conn.prepareStatement(query); stmt.setString(1, subAwardRequisitionerId); rs = stmt.executeQuery(); try { while (rs.next()) { negotiationIds.add(rs.getLong(1)); } } finally { try { rs.close(); } catch (Exception ignore) { } } } catch (SQLException sqle) { LOG.error("SQLException: " + sqle.getMessage(), sqle); throw new WorkflowRuntimeException(sqle); } catch (LookupException le) { LOG.error("LookupException: " + le.getMessage(), le); throw new WorkflowRuntimeException(le); } finally { try { if(stmt != null) { stmt.close(); } if (broker != null) { OjbFactoryUtils.releasePersistenceBroker(broker, this.getPersistenceBrokerTemplate().getPbKey()); } } catch (Exception e) { LOG.error("Failed closing connection: " + e.getMessage(), e); } } return negotiationIds; } /* IU Customization Ends */ }
agpl-3.0
paulmartel/voltdb
tests/frontend/org/voltdb/regressionsuites/TestIndexReverseScanSuite.java
16298
/* This file is part of VoltDB. * Copyright (C) 2008-2016 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.regressionsuites; import java.io.IOException; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; /* * Functional tests of the statements compiled in the test suite * org.voltdb.planner.TestComplexGroupBySuite. */ public class TestIndexReverseScanSuite extends RegressionSuite { private final String[] procs = {"R1.insert", "P1.insert", "P2.insert", "P3.insert"}; private final String [] tbs = {"R1","P1","P2","P3"}; private void loadData() throws IOException, ProcCallException { Client client = this.getClient(); ClientResponse cr = null; // Empty data from table. for (String tb: tbs) { cr = client.callProcedure("@AdHoc", "delete from " + tb); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); } // Insert records into the table. // id, wage, dept, rate for (String tb: procs) { cr = client.callProcedure(tb, 1, 1, 1, 1, 1); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); cr = client.callProcedure(tb, 2, 2, 2, 2, 2); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); cr = client.callProcedure(tb, 3, 3, 3, 3, 3); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); cr = client.callProcedure(tb, 4, 4, 4, 4, 4); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); cr = client.callProcedure(tb, 5, 5, 5, 5, 5); assertEquals(ClientResponse.SUCCESS, cr.getStatus()); } } public void testReverseScanOneColumnIndex() throws IOException, ProcCallException { loadData(); Client c = this.getClient(); VoltTable vt; for (String tb: tbs) { // (1) < case: // Underflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < -60000000000 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < -3 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 1 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 4 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 8 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // Overflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a < 6000000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // (2) <= case: // Underflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= -60000000000 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= -3 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 1 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 4 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 8 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // Overflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a <= 6000000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // (3) > case: // Underflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 1 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 4 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 5 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 8 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); // Overflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 6000000000000 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); // (3) >= case: // Underflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= -60000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= -3 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 1 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 4 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 8 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); // Overflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a >= 6000000000000 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); // (4) between cases: // (4.1) > , < // > underflow vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < -50000000000 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < -1 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < 1 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -60000000000 AND a < 6000000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // > -3 vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < -2 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < 1 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < 2 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < 8 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > -3 AND a < 6000000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3, 2, 1}); // > 2 vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < -2 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < 1 order by a DESC").getResults()[0]; assertEquals(0, vt.getRowCount()); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < 4 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {3}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < 5 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {4, 3}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < 8 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3}); vt = c.callProcedure("@AdHoc", "SELECT a from " + tb + " where a > 2 AND a < 6000000000000 order by a DESC").getResults()[0]; validateTableOfScalarLongs(vt, new long[] {5, 4, 3}); // > 8 // (4.2) > , <= // (4.3) >= , < // (4.4) >= , <= // There are too many permutations. // Refer SQL coverage test: index-scan. } } public void notestReverseScanWithNulls() throws IOException, ProcCallException { loadData(); // // Client c = this.getClient(); // VoltTable vt; // TODO: add test cases for null here or SQL coverage. } // // Suite builder boilerplate // public TestIndexReverseScanSuite(String name) { super(name); } static public junit.framework.Test suite() { VoltServerConfig config = null; MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder( TestIndexReverseScanSuite.class); VoltProjectBuilder project = new VoltProjectBuilder(); final String literalSchema = "CREATE TABLE R1 ( " + "ID INTEGER DEFAULT '0' NOT NULL, " + "a INTEGER, " + "b INTEGER, " + "c INTEGER, " + "d INTEGER, " + "PRIMARY KEY (ID) );" + "create index R1_TREE_1 on R1 (a);" + "create index R1_TREE_2 on R1 (b, c);" + "CREATE TABLE P1 ( " + "ID INTEGER DEFAULT '0' NOT NULL, " + "a INTEGER, " + "b INTEGER, " + "c INTEGER, " + "d INTEGER, " + "PRIMARY KEY (ID) );" + "PARTITION TABLE P1 ON COLUMN ID;" + "create index P1_TREE_1 on P1 (a);" + "create index P1_TREE_2 on P1 (b, c);" + "CREATE TABLE P2 ( " + "ID INTEGER DEFAULT '0' NOT NULL ASSUMEUNIQUE, " + "a INTEGER not null, " + "b INTEGER, " + "c INTEGER, " + "d INTEGER, " + "PRIMARY KEY (ID, a) );" + "PARTITION TABLE P2 ON COLUMN a;" + "create index P2_TREE_1 on P2 (a);" + "create index P2_TREE_2 on P2 (b, c);" + "CREATE TABLE P3 ( " + "ID INTEGER DEFAULT '0' NOT NULL, " + "a INTEGER, " + "b INTEGER not null unique, " + "c INTEGER, " + "d INTEGER, " + "PRIMARY KEY (ID, b) );" + "PARTITION TABLE P3 ON COLUMN b;" + "create index P3_TREE_1 on P3 (a);" + "create index P3_TREE_2 on P3 (b, c);" + "" ; try { project.addLiteralSchema(literalSchema); } catch (IOException e) { assertFalse(true); } boolean success; config = new LocalCluster("plansgroupby-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); builder.addServerConfig(config); config = new LocalCluster("plansgroupby-hsql.jar", 1, 1, 0, BackendTarget.HSQLDB_BACKEND); success = config.compile(project); assertTrue(success); builder.addServerConfig(config); // Cluster config = new LocalCluster("plansgroupby-cluster.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); builder.addServerConfig(config); return builder; } }
agpl-3.0
WASP-System/central
plugins/gatk/src/main/java/edu/yu/einstein/wasp/gatk/fileformat/GatkBamFileTypeAttribute.java
511
package edu.yu.einstein.wasp.gatk.fileformat; import edu.yu.einstein.wasp.plugin.fileformat.plugin.BamFileTypeAttribute; public class GatkBamFileTypeAttribute extends BamFileTypeAttribute { public static final GatkBamFileTypeAttribute REALN_AROUND_INDELS = new GatkBamFileTypeAttribute("realignAroundIndels"); public static final GatkBamFileTypeAttribute RECAL_QC_SCORES = new GatkBamFileTypeAttribute("recalibratedQcScores"); public GatkBamFileTypeAttribute(String attrName) { super(attrName); } }
agpl-3.0
CBSoft2016/Aplicativo_CBSoft2016
app/src/main/java/com/applications/fronchetti/cbsoft2016/Adapters/MinicursosAdapter.java
1654
package com.applications.fronchetti.cbsoft2016.Adapters; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.applications.fronchetti.cbsoft2016.R; import java.util.ArrayList; import java.util.List; public class MinicursosAdapter extends ArrayAdapter<Minicursos>{ Context context; int resource; List<Minicursos> minicursos = new ArrayList<>(); public MinicursosAdapter(Context context, int resource, List<Minicursos> minicursos) { super(context, resource, minicursos); this.resource = resource; this.context = context; this.minicursos = minicursos; } public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null){ LayoutInflater inflater = ((Activity) context).getLayoutInflater(); convertView = inflater.inflate(resource, parent, false); } Minicursos item = minicursos.get(position); if(item != null){ TextView Nome = (TextView) convertView.findViewById(R.id.textMinicursoNome); TextView Local = (TextView) convertView.findViewById(R.id.textMinicursoLocal); TextView Instrutor = (TextView) convertView.findViewById(R.id.textMinicursoInstrutor); Nome.setText(item.getTitulo()); Local.setText(item.getLocal()); Instrutor.setText(item.getInstrutor()); } return convertView; } }
agpl-3.0
dzhw/metadatamanagement
src/test/java/eu/dzhw/fdz/metadatamanagement/datasetmanagement/rest/DataSetResourceControllerTest.java
16097
package eu.dzhw.fdz.metadatamanagement.datasetmanagement.rest; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.not; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.google.gson.JsonSyntaxException; import eu.dzhw.fdz.metadatamanagement.AbstractTest; import eu.dzhw.fdz.metadatamanagement.common.domain.I18nString; import eu.dzhw.fdz.metadatamanagement.common.rest.TestUtil; import eu.dzhw.fdz.metadatamanagement.common.service.JaversService; import eu.dzhw.fdz.metadatamanagement.common.unittesthelper.util.UnitTestCreateDomainObjectUtils; import eu.dzhw.fdz.metadatamanagement.datasetmanagement.domain.DataSet; import eu.dzhw.fdz.metadatamanagement.datasetmanagement.repository.DataSetRepository; import eu.dzhw.fdz.metadatamanagement.projectmanagement.domain.DataAcquisitionProject; import eu.dzhw.fdz.metadatamanagement.projectmanagement.repository.DataAcquisitionProjectRepository; import eu.dzhw.fdz.metadatamanagement.searchmanagement.service.ElasticsearchAdminService; import eu.dzhw.fdz.metadatamanagement.searchmanagement.service.ElasticsearchUpdateQueueService; import eu.dzhw.fdz.metadatamanagement.surveymanagement.domain.Survey; import eu.dzhw.fdz.metadatamanagement.surveymanagement.repository.SurveyRepository; import eu.dzhw.fdz.metadatamanagement.usermanagement.security.AuthoritiesConstants; /** * @author Daniel Katzberg * */ @WithMockUser(authorities=AuthoritiesConstants.PUBLISHER) public class DataSetResourceControllerTest extends AbstractTest { private static final String API_DATASETS_URI = "/api/data-sets"; @Autowired private WebApplicationContext wac; @Autowired private DataAcquisitionProjectRepository dataAcquisitionProjectRepository; @Autowired private SurveyRepository surveyRepository; @Autowired private DataSetRepository dataSetRepository; @Autowired private ElasticsearchUpdateQueueService elasticsearchUpdateQueueService; @Autowired private ElasticsearchAdminService elasticsearchAdminService; @Autowired private JaversService javersService; private MockMvc mockMvc; @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(wac) .build(); } @AfterEach public void cleanUp() { this.dataAcquisitionProjectRepository.deleteAll(); this.surveyRepository.deleteAll(); this.dataSetRepository.deleteAll(); this.elasticsearchUpdateQueueService.clearQueue(); this.elasticsearchAdminService.recreateAllIndices(); this.javersService.deleteAll(); } @Test public void testCreateDataSet() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(), 1); // Act and Assert // create the variable with the given id mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); // check that auditing attributes have been set mockMvc.perform(get(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().isOk()) .andExpect(jsonPath("$.createdDate", not(isEmptyOrNullString()))) .andExpect(jsonPath("$.lastModifiedDate", not(isEmptyOrNullString()))) .andExpect(jsonPath("$.createdBy", is("user"))) .andExpect(jsonPath("$.lastModifiedBy", is("user"))); // call toString for test coverage :-) dataSet.toString(); elasticsearchUpdateQueueService.processAllQueueItems(); // check that there is one data set documents assertThat(elasticsearchAdminService.countAllDocuments(), equalTo(1L)); } @Test public void testCreateDataSetWithPost() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(), 1); // Act and Assert // create the variable with the given id mockMvc.perform(post(API_DATASETS_URI).content(TestUtil.convertObjectToJsonBytes(dataSet)) .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); // check that auditing attributes have been set mockMvc.perform(get(API_DATASETS_URI + "/" + dataSet.getId())).andExpect(status().isOk()) .andExpect(jsonPath("$.createdDate", not(isEmptyOrNullString()))) .andExpect(jsonPath("$.lastModifiedDate", not(isEmptyOrNullString()))) .andExpect(jsonPath("$.createdBy", is("user"))) .andExpect(jsonPath("$.lastModifiedBy", is("user"))); elasticsearchUpdateQueueService.processAllQueueItems(); // check that there is one data set documents assertThat(elasticsearchAdminService.countAllDocuments(), equalTo(1L)); } @Test public void testCreateDataSetWithSurveyButWithoutProject() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); this.surveyRepository.save(survey); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(null, survey.getId(), 1); // Act and Assert // create the DataSet with a survey but without a project mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test public void testCreateDataSetWithWrongFormat() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(null, survey.getId(), 1); dataSet.setFormat(new I18nString("wrong", "wrong")); // Act and Assert // create the DataSet with a survey but without a project mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test public void testCreateDataSetWithEmptyCitationHint() throws Exception { DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(null, survey.getId(), 1); // Act and Assert // create the DataSet with a survey but without a project mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @Test public void testCreateDataSetWithUnknownSurvey() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), "notExist", null); // Act and Assert // create the DataSet with the given id but with an unknown survey mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()); } @Test public void testCreateDataSetWithSurveyFromDifferentProject() throws Exception { // Arrange DataAcquisitionProject project1 = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); DataAcquisitionProject project2 = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); project2.setId("testproject2"); project2.setMasterId("testproject2"); this.dataAcquisitionProjectRepository.save(project1); this.dataAcquisitionProjectRepository.save(project2); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project2.getId()); this.surveyRepository.save(survey); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project1.getId(), survey.getId(), 1); // Act and Assert // create the DataSet with the given id but with a survey from a different project mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); } @Test public void testDeleteDataSet() throws JsonSyntaxException, IOException, Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(), 1); // create the DataSet with the given id mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); // delete the DataSet mockMvc.perform(delete(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().is2xxSuccessful()); // check that the DataSet has been deleted mockMvc.perform(get(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().isNotFound()); elasticsearchUpdateQueueService.processAllQueueItems(); // check that there are no more data set documents assertThat(elasticsearchAdminService.countAllDocuments(), equalTo(0L)); } @Test public void testUpdateDataSet() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(), 1); // Act and Assert // create the DataSet with the given id mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); dataSet.getDescription() .setDe("Angepasst."); dataSet.setVersion(0L); // update the DataSet with the given id mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()); // read the updated DataSet and check the version mockMvc.perform(get(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", is(dataSet.getId()))) .andExpect(jsonPath("$.version", is(1))) .andExpect(jsonPath("$.description.de", is("Angepasst."))); elasticsearchUpdateQueueService.processAllQueueItems(); // check that there is one data set documents assertThat(elasticsearchAdminService.countAllDocuments(), equalTo(1L)); } @Test @WithMockUser(authorities=AuthoritiesConstants.PUBLISHER) public void testCreateShadowCopyDataSet() throws Exception { DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet("issue1991", "test", 1); dataSet.setId(dataSet.getId() + "-1.0.0"); mockMvc.perform(post(API_DATASETS_URI) .content(TestUtil.convertObjectToJsonBytes(dataSet)) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors[0].message", containsString("global.error.shadow-create-not-allowed"))); } @Test @WithMockUser(authorities=AuthoritiesConstants.PUBLISHER) public void testUpdateShadowCopyDataSet() throws Exception { DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet("issue1991", "test", 1); dataSet.setId(dataSet.getId() + "-1.0.0"); dataSet = dataSetRepository.save(dataSet); mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors[0].message", containsString("global.error.shadow-save-not-allowed"))); } @Test @WithMockUser(authorities=AuthoritiesConstants.PUBLISHER) public void testDeleteShadowCopyDataSet() throws Exception { DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet("issue1991", "test", 1); dataSet.setId(dataSet.getId() + "-1.0.0"); dataSetRepository.save(dataSet); mockMvc.perform(delete(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors[0].message", containsString("global.error.shadow-delete-not-allowed"))); } @Test @WithMockUser(authorities=AuthoritiesConstants.PUBLISHER) public void testDeletingProjectDeletesDataSet() throws Exception { // Arrange DataAcquisitionProject project = UnitTestCreateDomainObjectUtils.buildDataAcquisitionProject(); this.dataAcquisitionProjectRepository.save(project); Survey survey = UnitTestCreateDomainObjectUtils.buildSurvey(project.getId()); this.surveyRepository.save(survey); DataSet dataSet = UnitTestCreateDomainObjectUtils.buildDataSet(project.getId(), survey.getId(), 1); // Act and Assert // create the DataSet with the given id mockMvc.perform(put(API_DATASETS_URI + "/" + dataSet.getId()) .content(TestUtil.convertObjectToJsonBytes(dataSet)).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); mockMvc.perform(delete("/api/data-acquisition-projects/" + project.getId())) .andExpect(status().is2xxSuccessful()); // check that the DataSet has been deleted mockMvc.perform(get(API_DATASETS_URI + "/" + dataSet.getId())) .andExpect(status().isNotFound()); } }
agpl-3.0
gsun83/cbioportal
core/src/main/java/org/mskcc/cbio/portal/scripts/ImportFusionData.java
7448
/* * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no * obligations to provide maintenance, support, updates, enhancements or * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be * liable to any party for direct, indirect, special, incidental or * consequential damages, including lost profits, arising out of the use of this * software and its documentation, even if Memorial Sloan-Kettering Cancer * Center has been advised of the possibility of such damage. */ /* * This file is part of cBioPortal. * * cBioPortal 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. * * 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 org.mskcc.cbio.portal.scripts; import org.mskcc.cbio.portal.dao.*; import org.mskcc.cbio.portal.model.*; import org.mskcc.cbio.portal.util.*; import org.mskcc.cbio.maf.*; import java.io.*; import java.util.*; /** * Imports a fusion file. * Columns may be in any order. * Creates an ExtendedMutation instances for each row. * * @author Selcuk Onur Sumer */ public class ImportFusionData { public static final String FUSION = "Fusion"; private File fusionFile; private int geneticProfileId; private String genePanel; public ImportFusionData(File fusionFile, int geneticProfileId, String genePanel) { this.fusionFile = fusionFile; this.geneticProfileId = geneticProfileId; this.genePanel = genePanel; } public void importData() throws IOException, DaoException { Map<ExtendedMutation.MutationEvent, ExtendedMutation.MutationEvent> existingEvents = new HashMap<ExtendedMutation.MutationEvent, ExtendedMutation.MutationEvent>(); for (ExtendedMutation.MutationEvent event : DaoMutation.getAllMutationEvents()) { existingEvents.put(event, event); } long mutationEventId = DaoMutation.getLargestMutationEventId(); FileReader reader = new FileReader(this.fusionFile); BufferedReader buf = new BufferedReader(reader); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); // The MAF File Changes fairly frequently, and we cannot use column index constants. String line = buf.readLine(); line = line.trim(); FusionFileUtil fusionUtil = new FusionFileUtil(line); boolean addEvent; GeneticProfile geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); while ((line = buf.readLine()) != null) { ProgressMonitor.incrementCurValue(); ConsoleUtil.showProgress(); if( !line.startsWith("#") && line.trim().length() > 0) { FusionRecord record = fusionUtil.parseRecord(line); // process case id String barCode = record.getTumorSampleID(); // backwards compatible part (i.e. in the new process, the sample should already be there. TODO - replace this workaround later with an exception: Sample sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(barCode)); if (sample == null ) { ImportDataUtil.addPatients(new String[] { barCode }, geneticProfileId); // add the sample (except if it is a 'normal' sample): ImportDataUtil.addSamples(new String[] { barCode }, geneticProfileId); } // check again (repeated because of workaround above): sample = DaoSample.getSampleByCancerStudyAndSampleId(geneticProfile.getCancerStudyId(), StableIdUtil.getSampleId(barCode)); // can be null in case of 'normal' sample: if (sample == null) { assert StableIdUtil.isNormal(barCode); line = buf.readLine(); continue; } if (!DaoSampleProfile.sampleExistsInGeneticProfile(sample.getInternalId(), geneticProfileId)) { if (genePanel != null) { DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId, GeneticProfileUtil.getGenePanelId(genePanel)); } else { DaoSampleProfile.addSampleProfile(sample.getInternalId(), geneticProfileId, null); } } // Assume we are dealing with Entrez Gene Ids (this is the best / most stable option) String geneSymbol = record.getHugoGeneSymbol(); long entrezGeneId = record.getEntrezGeneId(); CanonicalGene gene = null; if (entrezGeneId != TabDelimitedFileUtil.NA_LONG) { gene = daoGene.getGene(entrezGeneId); } if (gene == null) { // If Entrez Gene ID Fails, try Symbol. gene = daoGene.getNonAmbiguousGene(geneSymbol, null); } if(gene == null) { ProgressMonitor.logWarning("Gene not found: " + geneSymbol + " [" + entrezGeneId + "]. Ignoring it " + "and all fusion data associated with it!"); } else { // create a mutation instance with default values ExtendedMutation mutation = ExtendedMutationUtil.newMutation(); mutation.setGeneticProfileId(geneticProfileId); mutation.setSampleId(sample.getInternalId()); mutation.setGene(gene); mutation.setSequencingCenter(record.getCenter()); mutation.setProteinChange(record.getFusion()); // TODO we may need get mutation type from the file // instead of defining a constant mutation.setMutationType(FUSION); ExtendedMutation.MutationEvent event = existingEvents.get(mutation.getEvent()); if (event != null) { mutation.setEvent(event); addEvent = false; } else { mutation.setMutationEventId(++mutationEventId); existingEvents.put(mutation.getEvent(), mutation.getEvent()); addEvent = true; } // add fusion (as a mutation) DaoMutation.addMutation(mutation, addEvent); } } } buf.close(); if( MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } } }
agpl-3.0
dCache/xrootd4j-backport
src/main/java/org/dcache/pool/repository/RepositoryChannel.java
10125
/** * Copyright (C) 2012 dCache.org <support@dcache.org> * * This file is part of xrootd4j-backport. * * xrootd4j-backport 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. * * xrootd4j-backport 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 xrootd4j-backport. If not, see * <http://www.gnu.org/licenses/>. */ package org.dcache.pool.repository; import java.io.IOException; import java.io.SyncFailedException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.channels.WritableByteChannel; public interface RepositoryChannel extends GatheringByteChannel, ScatteringByteChannel, ByteChannel { /** * Get current position in the file. * @return position */ long position() throws IOException; /** * Sets this channel's file position. * @param position * @throws IOException */ RepositoryChannel position(long position) throws IOException; /** * Get current size of the file. * @return size */ long size() throws IOException; /** * Writes a sequence of bytes to this channel from the given buffer, starting at the given file position. * * This method works in the same manner as the write(ByteBuffer) method, except that bytes are * written starting at the given file position rather than at the channel's current position. * This method does not modify this channel's position. If the given position is greater than * the file's current size then the file will be grown to accommodate the new bytes; the values * of any bytes between the previous end-of-file and the newly-written bytes are unspecified. * * @param buffer * @param position * @return The number of bytes written, possibly zero. */ int write(ByteBuffer buffer, long position) throws IOException; /** * Reads a sequence of bytes from this channel into the given buffer, starting at the given file * position. * * This method works in the same manner as the read(ByteBuffer) method, except that bytes are * read starting at the given file position rather than at the channel's current position. * This method does not modify this channel's position. If the given position is greater than * the file's current size then no bytes are read. * * @param buffer * @param position * @return The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream */ int read(ByteBuffer buffer, long position) throws IOException; /** * Truncates this channel's file to the given size. * * If the given size is less than the file's current size then the file is truncated, * discarding any bytes beyond the new end of the file. If the given size is greater * than or equal to the file's current size then the file is not modified. In either * case, if this channel's file position is greater than the given size then it is set * to that size. * * @param size * @return the file channel. */ RepositoryChannel truncate(long size) throws IOException; /** * Force all system buffers to synchronize with the underlying * device. * * This method returns after all modified data and * attributes of this FileIoChannel have been written to the * relevant device(s). * * @throws SyncFailedException * Thrown when the buffers cannot be flushed, * or because the system cannot guarantee that all the * buffers have been synchronized with physical media. */ void sync() throws SyncFailedException, IOException; /** * Transfers bytes from this channel's file to the given writable byte * channel. * * <p> An attempt is made to read up to <tt>count</tt> bytes starting at * the given <tt>position</tt> in this channel's file and write them to the * target channel. An invocation of this method may or may not transfer * all of the requested bytes; whether or not it does so depends upon the * natures and states of the channels. Fewer than the requested number of * bytes are transferred if this channel's file contains fewer than * <tt>count</tt> bytes starting at the given <tt>position</tt>, or if the * target channel is non-blocking and it has fewer than <tt>count</tt> * bytes free in its output buffer. * * <p> This method does not modify this channel's position. If the given * position is greater than the file's current size then no bytes are * transferred. If the target channel has a position then bytes are * written starting at that position and then the position is incremented * by the number of bytes written. * * <p> This method is potentially much more efficient than a simple loop * that reads from this channel and writes to the target channel. Many * operating systems can transfer bytes directly from the filesystem cache * to the target channel without actually copying them. </p> * * @param position * The position within the file at which the transfer is to begin; * must be non-negative * * @param count * The maximum number of bytes to be transferred; must be * non-negative * * @param target * The target channel * * @return The number of bytes, possibly zero, * that were actually transferred * * @throws IllegalArgumentException * If the preconditions on the parameters do not hold * * @throws NonReadableChannelException * If this channel was not opened for reading * * @throws NonWritableChannelException * If the target channel was not opened for writing * * @throws ClosedChannelException * If either this channel or the target channel is closed * * @throws AsynchronousCloseException * If another thread closes either channel * while the transfer is in progress * * @throws ClosedByInterruptException * If another thread interrupts the current thread while the * transfer is in progress, thereby closing both channels and * setting the current thread's interrupt status * * @throws IOException * If some other I/O error occurs */ long transferTo(long position, long count, WritableByteChannel target) throws IOException; /** * Transfers bytes into this channel's file from the given readable byte * channel. * * <p> An attempt is made to read up to <tt>count</tt> bytes from the * source channel and write them to this channel's file starting at the * given <tt>position</tt>. An invocation of this method may or may not * transfer all of the requested bytes; whether or not it does so depends * upon the natures and states of the channels. Fewer than the requested * number of bytes will be transferred if the source channel has fewer than * <tt>count</tt> bytes remaining, or if the source channel is non-blocking * and has fewer than <tt>count</tt> bytes immediately available in its * input buffer. * * <p> This method does not modify this channel's position. If the given * position is greater than the file's current size then no bytes are * transferred. If the source channel has a position then bytes are read * starting at that position and then the position is incremented by the * number of bytes read. * * <p> This method is potentially much more efficient than a simple loop * that reads from the source channel and writes to this channel. Many * operating systems can transfer bytes directly from the source channel * into the filesystem cache without actually copying them. </p> * * @param src * The source channel * * @param position * The position within the file at which the transfer is to begin; * must be non-negative * * @param count * The maximum number of bytes to be transferred; must be * non-negative * * @return The number of bytes, possibly zero, * that were actually transferred * * @throws IllegalArgumentException * If the preconditions on the parameters do not hold * * @throws NonReadableChannelException * If the source channel was not opened for reading * * @throws NonWritableChannelException * If this channel was not opened for writing * * @throws ClosedChannelException * If either this channel or the source channel is closed * * @throws AsynchronousCloseException * If another thread closes either channel * while the transfer is in progress * * @throws ClosedByInterruptException * If another thread interrupts the current thread while the * transfer is in progress, thereby closing both channels and * setting the current thread's interrupt status * * @throws IOException * If some other I/O error occurs */ long transferFrom(ReadableByteChannel src, long position, long count) throws IOException; }
agpl-3.0
databazoo/dev-modeler
devmodeler/src/main/java/plugins/IDataWindowPlugin.java
680
package plugins; import java.awt.*; import javax.swing.*; import plugins.api.IDataWindow; /** * Data window plugins must implement this interface * @author bobus */ public interface IDataWindowPlugin { public void init(IDataWindow instance); public IDataWindowPlugin clone(); public String getPluginName(); public String getPluginDescription(); public ImageIcon getPluginIcon(); public Component getWindowComponent(); public Component getTabComponent(); public void onQueryChange(); public void onQueryRun(); public void onQueryExplain(); public void onQueryResult(); public void onQueryFail(); public void onWindowClose(); public boolean hasError(); }
agpl-3.0
Asqatasun/Asqatasun
rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule030401.java
1924
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2020 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa30; import org.asqatasun.ruleimplementation.AbstractPageRuleWithCheckerImplementation; import org.asqatasun.rules.elementchecker.contrast.ContrastChecker; /** * Implementation of the rule 3.4.1 of the referential Rgaa 3.0. * <br/> * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/03.Colours/Rule-3-4-1.html">the rule 3.4.1 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-3-4-1"> 3.4.1 rule specification</a> * * @author jkowalczyk */ public class Rgaa30Rule030401 extends AbstractPageRuleWithCheckerImplementation { /** The contrast checker with a value of ratio set to 7*/ private final ContrastChecker contrastChecker = new ContrastChecker(7f, true, false, true); /** * Default constructor */ public Rgaa30Rule030401 () { super(); setElementChecker(contrastChecker); } @Override public int getSelectionSize() { return contrastChecker.getElementCounter(); } }
agpl-3.0
ubicity-devs/ubicity-jspf
src/main/java/net/xeoh/plugins/base/annotations/configuration/package-info.java
127
/** * Annotations related to plugin loading. * * @since 1.0 */ package net.xeoh.plugins.base.annotations.configuration;
agpl-3.0
akvo/akvo-flow
GAE/src/com/gallatinsystems/framework/servlet/RestAuthFilter.java
6499
/* * Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package com.gallatinsystems.framework.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Map; import java.util.SortedMap; import java.util.TimeZone; import java.util.TreeMap; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import com.gallatinsystems.common.util.MD5Util; import com.gallatinsystems.common.util.PropertyUtil; import com.gallatinsystems.framework.rest.RestRequest; /** * Handles verifying that the incoming request is authorized by checking the hash. * * @author Christopher Fagiani */ public class RestAuthFilter implements Filter { private static final long MAX_TIME = 60 * 10 * 1000; // 10 minutes private static final Logger log = Logger.getLogger(RestAuthFilter.class .getName()); private static final String ENABLED_PROP = "enableRestSecurity"; public static final String REST_PRIVATE_KEY_PROP = "restPrivateKey"; private String privateKey; private boolean isEnabled = false; /** * checks to see if auth is */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (isEnabled) { try { if (isAuthorized(req)) { chain.doFilter(req, res); } else { HttpServletResponse response = (HttpServletResponse) res; response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization failed"); } } catch (Exception e) { log.severe("Auth failure " + e.getMessage()); HttpServletResponse response = (HttpServletResponse) res; response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization failed"); } } else { chain.doFilter(req, res); } } @SuppressWarnings({ "unchecked", "rawtypes" }) private boolean isAuthorized(ServletRequest req) throws Exception { return validateHashParam(req) && validateTimeStamp(req); } public boolean validateHashParam(ServletRequest req) throws UnsupportedEncodingException { if (req.getParameterMap() == null || req.getParameter(RestRequest.HASH_PARAM) == null) { return false; } SortedMap<Object, String[]> sortedParamMap = new TreeMap<>(); sortedParamMap.putAll(req.getParameterMap()); StringBuilder builder = new StringBuilder(); for (Object key : sortedParamMap.keySet()) { String paramKey = (String) key; if (RestRequest.HASH_PARAM.equals(paramKey)) { continue; } if (builder.length() > 0) { builder.append("&"); } String[] vals = ((String[]) sortedParamMap.get(paramKey)); int count = 0; for (String v : vals) { if (count > 0) { builder.append("&"); } builder.append(paramKey).append("=").append(URLEncoder.encode(v, "UTF-8")); count++; } } String incomingHash = ((String[]) sortedParamMap.get(RestRequest.HASH_PARAM))[0]; incomingHash = incomingHash.replaceAll(" ", "+"); String ourHash = MD5Util.generateHMAC(builder.toString(), privateKey); if (ourHash == null) { // Do something but for now return false; return false; } return ourHash.equals(incomingHash); } public boolean validateTimeStamp(ServletRequest req) { Map<Object, String[]> paramMap = req.getParameterMap(); if(paramMap.isEmpty() || !paramMap.containsKey(RestRequest.TIMESTAMP_PARAM)) { return false; } String timestamp = ((String[]) paramMap.get(RestRequest.TIMESTAMP_PARAM))[0]; try { DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); long incomingTimeStamp = df.parse(timestamp).getTime(); return (Math.abs(System.currentTimeMillis() - incomingTimeStamp) < MAX_TIME); } catch (ParseException e) { log.warning("Recived rest api request with invalid timestamp"); return false; } } @Override public void init(FilterConfig filterConfig) throws ServletException { String enabledFlag = null; if (filterConfig.getInitParameter(ENABLED_PROP) != null) { enabledFlag = filterConfig.getInitParameter(ENABLED_PROP); } else { enabledFlag = PropertyUtil.getProperty(ENABLED_PROP); } if (enabledFlag != null) { try { isEnabled = Boolean.parseBoolean(enabledFlag.trim()); } catch (Exception e) { log.severe("Could not parse " + ENABLED_PROP + " value of " + enabledFlag); isEnabled = false; } } if (filterConfig.getInitParameter(REST_PRIVATE_KEY_PROP) != null) { privateKey = filterConfig.getInitParameter(REST_PRIVATE_KEY_PROP); } else { privateKey = PropertyUtil.getProperty(REST_PRIVATE_KEY_PROP); } } @Override public void destroy() { } }
agpl-3.0
ghjansen/cas
cas-core/src/test/java/com/ghjansen/cas/core/physics/UniverseTest.java
4823
/* * CAS - Cellular Automata Simulator * Copyright (C) 2016 Guilherme Humberto Jansen * * 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.ghjansen.cas.core.physics; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; import com.ghjansen.cas.core.ca.Combination; import com.ghjansen.cas.core.ca.DimensionalCombination; import com.ghjansen.cas.core.ca.DimensionalState; import com.ghjansen.cas.core.ca.DimensionalTransition; import com.ghjansen.cas.core.ca.State; import com.ghjansen.cas.core.ca.Transition; import com.ghjansen.cas.core.exception.InvalidAbsoluteTimeLimitException; import com.ghjansen.cas.core.exception.InvalidCombinationException; import com.ghjansen.cas.core.exception.InvalidDimensionalAmountException; import com.ghjansen.cas.core.exception.InvalidDimensionalSpaceException; import com.ghjansen.cas.core.exception.InvalidInitialConditionException; import com.ghjansen.cas.core.exception.InvalidRelativeTimeLimitException; import com.ghjansen.cas.core.exception.InvalidSpaceException; import com.ghjansen.cas.core.exception.InvalidStateException; import com.ghjansen.cas.core.exception.InvalidTimeException; import com.ghjansen.cas.core.exception.InvalidTransitionException; /** * @author Guilherme Humberto Jansen (contact.ghjansen@gmail.com) */ public class UniverseTest { @Test public void dimensionalUniverseConstructor() throws CloneNotSupportedException, InvalidAbsoluteTimeLimitException, InvalidRelativeTimeLimitException, InvalidStateException, InvalidTransitionException, InvalidCombinationException, InvalidDimensionalAmountException, InvalidInitialConditionException, InvalidDimensionalSpaceException, InvalidSpaceException, InvalidTimeException { final DimensionalTime dimensionalTime = new DimensionalTime(1000, 1000); final Cell dimensionalCell = getNewValidDimensionalCell(); final ArrayList<Cell> firstDimension = new ArrayList<Cell>(); firstDimension.add(dimensionalCell); final DimensionalSpace dimensionalSpace = new DimensionalSpace(dimensionalTime, firstDimension, true); Universe dimensionalUniverse = new DimensionalUniverse(dimensionalSpace, dimensionalTime); Assert.assertTrue(dimensionalUniverse.getSpace().equals(dimensionalSpace)); Assert.assertTrue(dimensionalUniverse.getTime().equals(dimensionalTime)); } @Test(expected = InvalidSpaceException.class) public void dimensionalUniverseConstructorInvalidSpace() throws CloneNotSupportedException, InvalidAbsoluteTimeLimitException, InvalidRelativeTimeLimitException, InvalidSpaceException, InvalidTimeException{ final DimensionalTime dimensionalTime = new DimensionalTime(1000, 1000); new DimensionalUniverse(null, dimensionalTime); } @Test(expected = InvalidTimeException.class) public void dimensionalUniverseConstructorInvalidTime() throws CloneNotSupportedException, InvalidAbsoluteTimeLimitException, InvalidRelativeTimeLimitException, InvalidStateException, InvalidTransitionException, InvalidCombinationException, InvalidDimensionalAmountException, InvalidInitialConditionException, InvalidDimensionalSpaceException, InvalidSpaceException, InvalidTimeException{ final DimensionalTime dimensionalTime = new DimensionalTime(1000, 1000); final Cell dimensionalCell = getNewValidDimensionalCell(); final ArrayList<Cell> firstDimension = new ArrayList<Cell>(); firstDimension.add(dimensionalCell); final DimensionalSpace dimensionalSpace = new DimensionalSpace(dimensionalTime, firstDimension, true); new DimensionalUniverse(dimensionalSpace, null); } private Cell getNewValidDimensionalCell() throws InvalidStateException, InvalidTransitionException, InvalidCombinationException { final DimensionalState dimensionalBlackState = new DimensionalState("black", 0); final DimensionalState dimensionalWhiteState = new DimensionalState("white", 1); final DimensionalCombination dimensionalCombination = new DimensionalCombination(dimensionalWhiteState, dimensionalBlackState, dimensionalBlackState); final DimensionalTransition dimensionalTransition = new DimensionalTransition(dimensionalCombination, dimensionalBlackState); return new DimensionalCell(dimensionalTransition); } }
agpl-3.0
scionaltera/emergentmud
src/test/java/com/emergentmud/core/service/ZoneServiceTest.java
3724
/* * EmergentMUD - A modern MUD with a procedurally generated world. * Copyright (C) 2016-2018 Peter Keeler * * This file is part of EmergentMUD. * * EmergentMUD 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. * * EmergentMUD 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.emergentmud.core.service; import com.emergentmud.core.model.Biome; import com.emergentmud.core.model.Coordinate; import com.emergentmud.core.model.WhittakerGridLocation; import com.emergentmud.core.model.Zone; import com.emergentmud.core.repository.WhittakerGridLocationRepository; import com.emergentmud.core.repository.ZoneRepository; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ZoneServiceTest { @Mock private ZoneRepository zoneRepository; @Mock private WhittakerGridLocationRepository whittakerGridLocationRepository; @Mock private Random random; @Mock private Zone zone; private List<WhittakerGridLocation> allWhittakerGridLocations = new ArrayList<>(); private ZoneService zoneService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(zoneRepository.save(any(Zone.class))).thenAnswer(i -> { Zone zone = i.getArgumentAt(0, Zone.class); zone.setId(UUID.randomUUID()); return zone; }); for (int i = 0; i < 5; i++) { WhittakerGridLocation grid = mock(WhittakerGridLocation.class); Biome biome = mock(Biome.class); when(biome.getName()).thenReturn("Biome " + i); when(grid.getBiome()).thenReturn(biome); allWhittakerGridLocations.add(grid); } when(whittakerGridLocationRepository.findAll()).thenReturn(allWhittakerGridLocations); zoneService = new ZoneService( zoneRepository, whittakerGridLocationRepository, random ); } @Test public void testFetchZone() { zoneService.fetchZone(new Coordinate(0L, 1L, 0L)); verify(zoneRepository).findZoneAtPoint(eq(0L), eq(1L)); } @Test public void testCreateZoneAlreadyExists() { when(zoneRepository.findZoneAtPoint(eq(0L), eq(0L))).thenReturn(zone); Zone zoneResult = zoneService.createZone(new Coordinate(0L, 0L, 0L)); assertEquals(zone, zoneResult); } @Test public void testCreateZone() { when(random.nextInt(eq(3))).thenReturn(0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2); when(random.nextInt(eq(4))).thenReturn(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3); Zone zoneResult = zoneService.createZone(new Coordinate(0L, 0L, 0L)); assertNotNull(zoneResult); } }
agpl-3.0
fraunhoferfokus/GovData
dataset-portlet/src/main/java/de/fhg/fokus/odp/portal/datasets/OwnMetadataPages.java
2443
package de.fhg.fokus.odp.portal.datasets; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.fhg.fokus.odp.registry.model.Metadata; /** * Implements paging for own Metadata. */ public class OwnMetadataPages { private static final Logger log = LoggerFactory .getLogger(OwnMetadataPages.class); public static final int PAGESIZECONST = 15; private List<String> m_currentOwnMetadata; private CurrentUser m_currentUser; private int page_size = PAGESIZECONST; private int currentpage; private int start; private int end; private int max_pages; private int offset; public OwnMetadataPages(CurrentUser currentUser) { m_currentUser = currentUser; List<String> datasets = currentUser.getUserDatasets(); this.m_currentOwnMetadata = datasets; this.currentpage = 1; this.max_pages = 1; refreshPages(); } public void setOffset(int i) { offset = i; } public int getOffset() { return offset; } private void refreshPages() { if (page_size > 0) { // calculate how many pages there are if (m_currentOwnMetadata.size() % page_size == 0) { max_pages = m_currentOwnMetadata.size() / page_size; } else { max_pages = (m_currentOwnMetadata.size() / page_size) + 1; } } } public List<String> getCurrentOwnMetadata() { return this.m_currentOwnMetadata; } public List<String> getOwnMetadataForPage() { return m_currentOwnMetadata.subList(start, end); } public int getPageSize() { return this.page_size; } public void setPageSize(int pageSize) { this.page_size = pageSize; refreshPages(); } public int getPage() { return this.currentpage; } public List<Integer> getPages() { List<Integer> pages = new ArrayList<Integer>(); int num = getMaxPages(); for (int i = 1; i <= num; ++i) { pages.add(Integer.valueOf(i)); } return pages; } public void setPage(int p) { if (p >= max_pages) { this.currentpage = max_pages; } else if (p <= 1) { this.currentpage = 1; } else { this.currentpage = p; } start = page_size * (currentpage - 1); if (start < 0) { start = 0; } setOffset(start); end = start + page_size; if (end > m_currentOwnMetadata.size()) { end = m_currentOwnMetadata.size(); } } public int getMaxPages() { return this.max_pages; } public List<Metadata> getMetadatas() { return m_currentUser.getUserMetadatas(getOwnMetadataForPage()); } }
agpl-3.0
aborg0/rapidminer-studio
src/main/java/com/rapidminer/gui/flow/processrendering/annotations/model/AnnotationsModel.java
21916
/** * Copyright (C) 2001-2019 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.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.flow.processrendering.annotations.model; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.swing.SwingUtilities; import com.rapidminer.gui.flow.processrendering.annotations.AnnotationDrawUtils; import com.rapidminer.gui.flow.processrendering.annotations.AnnotationsDecorator; import com.rapidminer.gui.flow.processrendering.annotations.model.AnnotationResizeHelper.ResizeDirection; import com.rapidminer.gui.flow.processrendering.annotations.style.AnnotationAlignment; import com.rapidminer.gui.flow.processrendering.annotations.style.AnnotationColor; import com.rapidminer.gui.flow.processrendering.model.ProcessRendererModel; import com.rapidminer.operator.ExecutionUnit; import com.rapidminer.operator.Operator; import com.rapidminer.tools.container.Pair; /** * The model backing the {@link AnnotationsDecorator}. * * @author Marco Boeck * @since 6.4.0 * */ public class AnnotationsModel { /** currently hovered annotation or {@code null} */ private WorkflowAnnotation hovered; /** the resize direction currently being hovered or {@code null} */ private ResizeDirection hoveredResizeDirection; /** currently selected annotation or {@code null} */ private WorkflowAnnotation selected; /** the annotation currently being dragged or {@code null} */ private AnnotationDragHelper dragged; /** the annotation currently being resized or {@code null} */ private AnnotationResizeHelper resized; /** the process renderer model */ private ProcessRendererModel model; /** a map between annotations (identified via ID) and their displayed hyperlink urls and bounds */ private Map<UUID, List<Pair<String, Rectangle>>> hyperlinkBounds = new HashMap<>(); /** the currently hovered hyperlink with url and bounds */ private Pair<String, Rectangle> hoveredHyperLink; /** * Creates a new model backing the workflow annotations. * * @param model * the process renderer model */ public AnnotationsModel(ProcessRendererModel model) { this.model = model; } /** * Returns the hovered {@link WorkflowAnnotation}. * * @return the hovered annotation or {@code null} */ public WorkflowAnnotation getHovered() { return hovered; } /** * Sets the hovered annotation. If it changes, fires a process renderer model misc event to * trigger a repaint. * * @param hovered * the new hovered annotation, can be {@code null} * @param hoveredResizeDirection * the hovered resize corner, can be {@code null} */ public void setHovered(final WorkflowAnnotation hovered, final ResizeDirection hoveredResizeDirection) { if (hovered == null) { if (this.hovered != null) { this.hovered = null; setHoveredResizeDirection(null); setHoveredHyperLink(null); model.fireAnnotationMiscChanged(null); } } else { if (!hovered.equals(this.hovered)) { this.hovered = hovered; setHoveredHyperLink(null); if (hovered.equals(selected)) { setHoveredResizeDirection(hoveredResizeDirection); } else { setHoveredResizeDirection(null); } model.fireAnnotationMiscChanged(hovered); } else { if (hovered.equals(selected)) { setHoveredResizeDirection(hoveredResizeDirection); } } } } /** * Sets the list of hyperlink bounds for the given annotation. * * @param id * the id of the annotation (see {@link WorkflowAnnotation#getId()} for which the bounds should be stored. * @param bounds * the bounds with the URL as a string. Can be empty for no bounds. Note that they are stored as if a zoom level of 100% was set, * regardless of actual zoom level. Only bounds are stored that are actually visible (i.e. are not cut off by the * "..." dots) * @since 9.0.0 */ public void setHyperlinkBoundsForAnnotation(UUID id, List<Pair<String, Rectangle>> bounds) { if (id == null) { throw new IllegalArgumentException("id must not be null!"); } if (bounds == null) { throw new IllegalArgumentException("bounds must not be null!"); } hyperlinkBounds.put(id, bounds); } /** * Gets the list of hyperlink bounds for the given annotation. * * @param id * the id of the annotation (see {@link WorkflowAnnotation#getId()} for which the bounds should be retrieved. * @return the bounds with the URL as a string, never {@code null}. Can be empty for no bounds. Note that they are stored as if a zoom level of 100% was * set, regardless of actual zoom level. Only bounds are stored that are actually visible (i.e. are not cut off by * the "..." dots) * @since 9.0.0 */ public List<Pair<String, Rectangle>> getHyperlinkBoundsForAnnotation(UUID id) { if (id == null) { throw new IllegalArgumentException("id must not be null!"); } return hyperlinkBounds.computeIfAbsent(id, notUsed -> Collections.emptyList()); } /** * Gets the hovered hyperlink. * * @return the hovered hyperlink url and its bounds, or {@code null} if no hyperlink is hovered * @since 9.0.0 */ public Pair<String, Rectangle> getHoveredHyperLink() { return hoveredHyperLink; } /** * Sets the hovered hyperlink. * * @param hoveredHyperLink * the hovered hyperlink url and its bounds, or {@code null} if no hyperlink is hovered * @since 9.0.0 */ public void setHoveredHyperLink(Pair<String, Rectangle> hoveredHyperLink) { if (hoveredHyperLink != null && hoveredHyperLink.getFirst() == null) { throw new IllegalArgumentException("url in hoveredHyperLink must not be null!"); } if (hoveredHyperLink != null && hoveredHyperLink.getSecond() == null) { throw new IllegalArgumentException("bounds in hoveredHyperLink must not be null!"); } if (this.hoveredHyperLink == hoveredHyperLink) { return; } this.hoveredHyperLink = hoveredHyperLink; model.fireAnnotationMiscChanged(null); } /** * Returns the resize direction of the hovered annotation. * * @return the resize direction or {@code null} */ public ResizeDirection getHoveredResizeDirection() { return hoveredResizeDirection; } /** * Sets the hovered resize direction. If it changes, fires a process renderer model misc event * to trigger a repaint. * * @param hoveredResizeDirection * the hovered resize direction */ public void setHoveredResizeDirection(final ResizeDirection hoveredResizeDirection) { if (hoveredResizeDirection != null) { if (!hoveredResizeDirection.equals(this.hoveredResizeDirection)) { this.hoveredResizeDirection = hoveredResizeDirection; model.fireAnnotationMiscChanged(null); } } else { if (this.hoveredResizeDirection != null) { this.hoveredResizeDirection = null; model.fireAnnotationMiscChanged(null); } } } /** * Returns the selected {@link WorkflowAnnotation}. * * @return the selected annotation or {@code null} */ public WorkflowAnnotation getSelected() { return selected; } /** * Sets the selected {@link WorkflowAnnotation}. If it changes, fires a process renderer model * annotation selection event to trigger a repaint. * * @param selected * the selected annotation or {@code null} */ public void setSelected(WorkflowAnnotation selected) { if (selected == null) { if (getSelected() != null) { this.selected = null; model.fireAnnotationSelected(null); } } else { if (!selected.equals(this.selected)) { this.selected = selected; model.fireAnnotationSelected(selected); } } } /** * Returns the drag helper if an annotation is currently being dragged. * * @return the drag helper or {@code null} */ public AnnotationDragHelper getDragged() { return dragged; } /** * Sets the drag helper if an annotation is currently being dragged. * * @param dragged * the drag helper or {@code null} */ public void setDragged(AnnotationDragHelper dragged) { this.dragged = dragged; } /** * Returns the resize helper if an annotation is currently being resized. * * @return the resize helper or {@code null} */ public AnnotationResizeHelper getResized() { return resized; } /** * Sets the resize helper if an annotation is currently being resized. * * @param resized * the resize helper or {@code null} */ public void setResized(AnnotationResizeHelper resized) { this.resized = resized; } /** * Starts a drag or resizing of the selected annotation, depending on whether the drag starts on * the annotation or one of the resize "knobs". If no annotation is selected, does nothing. If * the triggering action was not a left-click, does nothing. * * @param e * the mouse event triggering the drag/resize * @param origin * the origin of the drag/resize event * @param allowResize * if {@code true}, resize is allowed. Otherwise only a drag can be started */ public void startDragOrResize(final MouseEvent e, final Point origin, boolean allowResize) { if (getSelected() == null) { return; } if (!SwingUtilities.isLeftMouseButton(e)) { return; } // manual resizing is NEVER permitted for operator annotations if (getSelected() instanceof OperatorAnnotation) { allowResize = false; } ResizeDirection direction = null; if (allowResize) { direction = AnnotationResizeHelper.getResizeDirectionOrNull(getSelected(), origin); } if (direction != null) { resized = new AnnotationResizeHelper(selected, direction, origin); } else { dragged = new AnnotationDragHelper(selected, origin, model); } } /** * Updates the dragged position or the resizing of the selected annotation and fires a misc * model change for the process renderer. If no drag and resizing is in progress, does nothing. * * @param point * the current location */ public void updateDragOrResize(final Point point) { if (dragged == null && resized == null) { return; } if (dragged != null) { dragged.handleDragEvent(point); // fire moved event model.fireAnnotationMoved(dragged.getDraggedAnnotation()); } else if (resized != null) { resized.handleResizeEvent(point); // fire moved event model.fireAnnotationMoved(resized.getResized()); } } /** * Stops the drag or resizing of the selected annotation. If neither was in progress, does * nothing. * * @param destination * the final destination of the drag/resize event. If {@code null}, dragging is * assumed to be cancelled and no conversion from operator to process annotation or * vice versa is performed. */ public void stopDragOrResize(final Point destination) { if (dragged == null && resized == null) { return; } if (destination != null) { updateDragOrResize(destination); } // trigger process event so it becomes dirty if (dragged != null) { WorkflowAnnotation draggedAnno = dragged.getDraggedAnnotation(); // if we stop over an operator if (dragged.getHoveredOperator() != null) { if (draggedAnno instanceof ProcessAnnotation) { if (destination != null) { // delete process annotation if drag was not cancelled deleteAnnotation(draggedAnno); addOperatorAnnotation(draggedAnno.createOperatorAnnotation(dragged.getHoveredOperator())); } else { moveProcessAnnoToPoint((ProcessAnnotation) draggedAnno, dragged.getOrigin(), dragged.getStartingPoint()); } } else if (draggedAnno instanceof OperatorAnnotation) { OperatorAnnotation opAnno = (OperatorAnnotation) draggedAnno; if (destination != null) { // remove from original operator model.removeOperatorAnnotation(opAnno); moveOperatorAnnoToOperator(opAnno, dragged.getHoveredOperator()); // attach to new operator opAnno.setAttachedTo(dragged.getHoveredOperator()); model.addOperatorAnnotation(opAnno); } else { // destination is null = cancelled dragging moveOperatorAnnoToOperator(opAnno, opAnno.getAttachedTo()); } opAnno.fireUpdate(); } } else { // we did not stop over an operator and dragged an annotation if (destination == null) { // we cancelled dragging via ESC -> reset to original position if (draggedAnno instanceof OperatorAnnotation) { moveOperatorAnnoToOperator((OperatorAnnotation) draggedAnno, ((OperatorAnnotation) draggedAnno).getAttachedTo()); } else if (draggedAnno instanceof ProcessAnnotation) { moveProcessAnnoToPoint((ProcessAnnotation) draggedAnno, dragged.getOrigin(), dragged.getStartingPoint()); } } else { if (draggedAnno instanceof OperatorAnnotation && dragged.isUnsnapped()) { // an operator annotation was dragged away from an operator // convert to process annotation deleteAnnotation(draggedAnno); addProcessAnnotation(draggedAnno.createProcessAnnotation(draggedAnno.getProcess())); } else if (draggedAnno instanceof ProcessAnnotation) { // notify process of change draggedAnno.fireUpdate(); } } } // otherwise we might end up with a selection rectangle here model.setSelectionRectangle(null); } else if (resized != null) { resized.getResized().fireUpdate(); } if (resized != null) { WorkflowAnnotation anno = resized.getResized(); int prefHeight = AnnotationDrawUtils.getContentHeight(AnnotationDrawUtils.createStyledCommentString( anno.getComment(), anno.getStyle()), (int) anno.getLocation().getWidth(), AnnotationDrawUtils.ANNOTATION_FONT); boolean overflowing = false; if (prefHeight > anno.getLocation().getHeight()) { overflowing = true; } anno.setOverflowing(overflowing); } // reset dragged = null; resized = null; } /** * Deletes the given annotation and fires updates. * * @param toDelete * the annotation to delete * */ public void deleteAnnotation(final WorkflowAnnotation toDelete) { if (toDelete == null) { throw new IllegalArgumentException("toDelete must not be null!"); } if (toDelete instanceof OperatorAnnotation) { OperatorAnnotation anno = (OperatorAnnotation) toDelete; model.removeOperatorAnnotation(anno); } else if (toDelete instanceof ProcessAnnotation) { ProcessAnnotation anno = (ProcessAnnotation) toDelete; model.removeProcessAnnotation(anno); } setSelected(null); fireProcessUpdate(toDelete); model.fireAnnotationMiscChanged(null); } /** * Adds the given operator annotation and fires updates. * * @param anno * the annotation to add */ public void addOperatorAnnotation(final OperatorAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.addOperatorAnnotation(anno); setSelected(anno); fireProcessUpdate(anno); model.fireAnnotationMoved(anno); } /** * Adds the given process annotation and fires updates. * * @param anno * the annotation to add */ public void addProcessAnnotation(final ProcessAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.addProcessAnnotation(anno); setSelected(anno); fireProcessUpdate(anno); model.fireAnnotationMoved(anno); } /** * Sets the color of the annotation and fires an event afterwards. * * @param anno * the annotation which will have its color changed * @param color * the new color */ public void setAnnotationColor(final WorkflowAnnotation anno, final AnnotationColor color) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } if (color == null) { throw new IllegalArgumentException("color must not be null!"); } anno.getStyle().setAnnotationColor(color); anno.setColored(); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Sets the alignment of the annotation and fires an event afterwards. * * @param anno * the annotation which will have its alignment changed * @param alignment * the new alignment */ public void setAnnotationAlignment(final WorkflowAnnotation anno, final AnnotationAlignment alignment) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } if (alignment == null) { throw new IllegalArgumentException("alignment must not be null!"); } anno.getStyle().setAnnotationAlignment(alignment); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Sets the comment of the annotation and fires an event afterwards. * * @param anno * the annotation which will have its comment changed * @param comment * the new comment */ public void setAnnotationComment(final WorkflowAnnotation anno, final String comment) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } if (comment == null) { throw new IllegalArgumentException("comment must not be null!"); } anno.setComment(comment); fireProcessUpdate(anno); model.fireAnnotationMoved(anno); } /** * Bring the given annotation to the front. That annotation will be drawn over all other * annotations as well as receive events first. * * @param anno * the annotation to bring to the front */ public void toFront(final WorkflowAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.getProcessAnnotations(anno.getProcess()).toFront(anno); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Brings the given annotation one layer forward. * * @param anno * the annotation to bring forward */ public void sendForward(final WorkflowAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.getProcessAnnotations(anno.getProcess()).sendForward(anno); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Bring the given annotation to the back. That annotation will be drawn behind all other * annotations as well as receive events last. * * @param anno * the annotation to bring to the front */ public void toBack(final WorkflowAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.getProcessAnnotations(anno.getProcess()).toBack(anno); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Sends the given annotation one layer backward. * * @param anno * the annotation to send backward */ public void sendBack(final WorkflowAnnotation anno) { if (anno == null) { throw new IllegalArgumentException("anno must not be null!"); } model.getProcessAnnotations(anno.getProcess()).sendBack(anno); fireProcessUpdate(anno); model.fireAnnotationMiscChanged(anno); } /** * Resets model status as if the model was newly created */ public void reset() { this.hovered = null; this.hoveredResizeDirection = null; this.selected = null; this.dragged = null; this.resized = null; } /** * Moves the {@link OperatorAnnotation} to the target {@link Operator}. Only updates the * location! * * @param opAnno * the annotation to move * @param target * the operator to which the annotation should be moved */ private void moveOperatorAnnoToOperator(final OperatorAnnotation opAnno, final Operator target) { int x = (int) (model.getOperatorRect(target).getCenterX() - opAnno.getLocation().getWidth() / 2); int y = (int) model.getOperatorRect(target).getMaxY() + OperatorAnnotation.Y_OFFSET; opAnno.setLocation(new Rectangle2D.Double(x, y, opAnno.getLocation().getWidth(), opAnno.getLocation().getHeight())); } /** * Moves the {@link ProcessAnnotation} to the target {@link Point}. Only updates the location! * * @param processAnno * the annotation to move * @param current * the current absolute point of the annotation * @param target * the new absolute point of the annotation */ private void moveProcessAnnoToPoint(final ProcessAnnotation processAnno, final Point current, final Point target) { processAnno.setLocation(new Rectangle2D.Double(target.getX(), target.getY(), processAnno.getLocation().getWidth(), processAnno.getLocation().getHeight())); } /** * Fires an update for a process. If the annotation is not attached to any process, does * nothing. * * @param anno * the annotation which triggered the update */ private void fireProcessUpdate(final WorkflowAnnotation anno) { ExecutionUnit process = anno.getProcess(); if (process != null) { // dirty hack to trigger a process update process.getEnclosingOperator().rename(process.getEnclosingOperator().getName()); } } }
agpl-3.0
PureSolTechnologies/Purifinity
analysis/api/analysis.api/src/test/java/com/puresoltechnologies/purifinity/analysis/api/AnalysisProjectTest.java
1420
package com.puresoltechnologies.purifinity.analysis.api; import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import org.junit.Test; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.puresoltechnologies.commons.domain.JSONSerializer; import com.puresoltechnologies.commons.misc.io.FileSearchConfiguration; public class AnalysisProjectTest { @Test public void test() throws JsonGenerationException, JsonMappingException, IOException { Date time = new Date(); String projectId = "test_project"; AnalysisProjectInformation analysisProjectInformation = new AnalysisProjectInformation(projectId, time); AnalysisProjectSettings analysisProjectSettings = new AnalysisProjectSettings("name", "description", new File("/root/preAnalysis.sh"), new FileSearchConfiguration(new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), true), new Properties()); AnalysisProject project = new AnalysisProject(analysisProjectInformation, analysisProjectSettings); String json = JSONSerializer.toJSONString(project); assertNotNull(json); AnalysisProject unmarshalled = JSONSerializer.fromJSONString(json, AnalysisProject.class); assertNotNull(unmarshalled); } }
agpl-3.0
moparisthebest/MoparScape
clients/client508/src/main/java/Class68_Sub13_Sub15.java
19795
/* Class68_Sub13_Sub15 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ import java.io.BufferedWriter; import java.io.FileWriter; public class Class68_Sub13_Sub15 extends Class68_Sub13 { public int anInt3677 = 3216; public static int anInt3678; public static int[] anIntArray3679; public static int anInt3680; public static int anInt3681; public int anInt3682; public static int anInt3683; public int[] anIntArray3684; public static int anInt3685; public static int anInt3686; public static int anInt3687; public int anInt3688 = 4096; public static int anInt3689; public static int anInt3690; public static int anInt3691; public static int anInt3692; public static int anInt3693; public void method690(byte i) { if (i < -22) { method765((byte) -23); anInt3683++; } } public static void method764(int i, int i_0_, boolean bool) { if (i != Class68_Sub13_Sub19.anInt3746) { Class68_Sub13_Sub3.anIntArray3479 = new int[i]; for (int i_1_ = 0; (i_1_ ^ 0xffffffff) > (i ^ 0xffffffff); i_1_++) Class68_Sub13_Sub3.anIntArray3479[i_1_] = (i_1_ << 898224364) / i; Class68_Sub20_Sub13_Sub2.anInt4620 = i == 64 ? 2048 : 4096; Class30.anInt543 = -1 + i; Class68_Sub13_Sub19.anInt3746 = i; } anInt3693++; if ((i_0_ ^ 0xffffffff) != (Class68_Sub1.anInt2775 ^ 0xffffffff)) { if ((i_0_ ^ 0xffffffff) != (Class68_Sub13_Sub19.anInt3746 ^ 0xffffffff)) { Class13_Sub3.anIntArray2672 = new int[i_0_]; for (int i_2_ = 0; (i_2_ ^ 0xffffffff) > (i_0_ ^ 0xffffffff); i_2_++) Class13_Sub3.anIntArray2672[i_2_] = (i_2_ << -1932024276) / i_0_; } else Class13_Sub3.anIntArray2672 = Class68_Sub13_Sub3.anIntArray3479; Class1_Sub6_Sub2.anInt3432 = i_0_ - 1; Class68_Sub1.anInt2775 = i_0_; } if (bool != true) method767(81, 122, -111); } public Class68_Sub13_Sub15() { super(1, true); anIntArray3684 = new int[3]; anInt3682 = 3216; } public void method765(byte i) { double d = Math.cos((double) ((float) anInt3677 / 4096.0F)); anInt3690++; anIntArray3684[0] = (int) (Math.sin((double) ((float) anInt3682 / 4096.0F)) * d * 4096.0); anIntArray3684[1] = (int) (d * Math.cos((double) ((float) anInt3682 / 4096.0F)) * 4096.0); anIntArray3684[2] = (int) (4096.0 * Math.sin((double) ((float) anInt3677 / 4096.0F))); int i_3_ = anIntArray3684[1] * anIntArray3684[1] >> -1148302068; int i_4_ = anIntArray3684[2] * anIntArray3684[2] >> 1285443756; int i_5_ = anIntArray3684[0] * anIntArray3684[0] >> 1915040716; int i_6_ = (int) (4096.0 * Math.sqrt((double) (i_4_ + i_3_ + i_5_ >> 732006508))); if (i != -23) method766(3, -86L); if (i_6_ != 0) { anIntArray3684[2] = (anIntArray3684[2] << 1771585100) / i_6_; anIntArray3684[0] = (anIntArray3684[0] << -1837682996) / i_6_; anIntArray3684[1] = (anIntArray3684[1] << -805177300) / i_6_; } } public static void method766(int i, long l) { try { anInt3680++; if ((l ^ 0xffffffffffffffffL) != -1L) { int i_7_ = 0; if (i != 23136) method770((byte) -1); for (/**/; i_7_ < Class32.anInt573; i_7_++) { if (Class68_Sub13_Sub21.aLongArray3802[i_7_] == l) { Class66.anInt1201++; Class32.anInt573--; for (int i_8_ = i_7_; Class32.anInt573 > i_8_; i_8_++) { Class68_Sub13_Sub38.aRSStringArray4084[i_8_] = (Class68_Sub13_Sub38.aRSStringArray4084 [i_8_ + 1]); Class98.anIntArray1724[i_8_] = Class98.anIntArray1724[i_8_ - -1]; Class68_Sub1.aRSStringArray2754[i_8_] = Class68_Sub1.aRSStringArray2754[i_8_ - -1]; Class68_Sub13_Sub21.aLongArray3802[i_8_] = (Class68_Sub13_Sub21.aLongArray3802 [i_8_ - -1]); Class68_Sub4.anIntArray2828[i_8_] = Class68_Sub4.anIntArray2828[1 + i_8_]; Class68_Sub13_Sub29.aBooleanArray3941[i_8_] = (Class68_Sub13_Sub29.aBooleanArray3941 [1 + i_8_]); } Class123.anInt2130 = Class68_Sub22.anInt3148; Class21renamed.stream.createFrame(132); Class21renamed.stream.writeQWord(true, l); break; } } } } catch (RuntimeException runtimeexception) { throw Class107.method1652(runtimeexception, "ii.D(" + i + ',' + l + ')'); } } public static void method767(int i, int i_9_, int i_10_) { Class103.anIntArray1767[i] = i_9_; anInt3685++; Class68_Sub15 class68_sub15 = (Class68_Sub15) Class37.aClass113_646.method1678((long) i, -123); if (class68_sub15 != null) class68_sub15.aLong3014 = 500L + Class36.method438(17161); else { class68_sub15 = new Class68_Sub15(500L + Class36.method438(17161)); Class37.aClass113_646.method1677((byte) 126, class68_sub15, (long) i); } int i_11_ = 97 % ((34 - i_10_) / 52); } public void method700(Stream class68_sub14, int i, int i_12_) { int i_13_ = i; while_68_: do { do { if (i_13_ != 0) { if (i_13_ != 1) { if ((i_13_ ^ 0xffffffff) == -3) break; break while_68_; } } else { anInt3688 = class68_sub14.readUnsignedWord(1355769544); break while_68_; } anInt3682 = class68_sub14.readUnsignedWord(1355769544); break while_68_; } while (false); anInt3677 = class68_sub14.readUnsignedWord(1355769544); } while (false); if (i_12_ != -1) anInt3677 = 123; anInt3678++; } public int[] method698(byte i, int i_14_) { anInt3686++; if (i != -61) anInt3688 = 7; int[] is = aClass115_2936.method1697(false, i_14_); if (aClass115_2936.aBoolean1957) { int i_15_ = Class68_Sub20_Sub13_Sub2.anInt4620 * anInt3688 >> -803028372; int[] is_16_ = this.method696(0, Class1_Sub6_Sub2.anInt3432 & -1 + i_14_, 29149); int[] is_17_ = this.method696(0, i_14_, 29149); int[] is_18_ = this.method696(0, 1 + i_14_ & Class1_Sub6_Sub2.anInt3432, 29149); for (int i_19_ = 0; ((Class68_Sub13_Sub19.anInt3746 ^ 0xffffffff) < (i_19_ ^ 0xffffffff)); i_19_++) { int i_20_ = ((-is_17_[i_19_ - -1 & Class30.anInt543] + is_17_[i_19_ - 1 & Class30.anInt543]) * i_15_ >> 250522988); int i_21_ = (-is_16_[i_19_] + is_18_[i_19_]) * i_15_ >> 1504576684; int i_22_ = i_20_ >> 1299021796; int i_23_ = i_21_ >> 1318447268; if ((i_22_ ^ 0xffffffff) > -1) i_22_ = -i_22_; if ((i_23_ ^ 0xffffffff) > -1) i_23_ = -i_23_; if ((i_22_ ^ 0xffffffff) < -256) i_22_ = 255; if (i_23_ > 255) i_23_ = 255; int i_24_ = ((Class68_Sub20_Sub18.aByteArray4444 [i_22_ + ((i_23_ + 1) * i_23_ >> -1206695839)]) & 0xff); int i_25_ = i_20_ * i_24_ >> 1247637544; int i_26_ = 4096 * i_24_ >> -1998727416; i_25_ = i_25_ * anIntArray3684[0] >> -753290548; i_26_ = anIntArray3684[2] * i_26_ >> -555307668; int i_27_ = i_24_ * i_21_ >> 2011762088; i_27_ = i_27_ * anIntArray3684[1] >> 1453414380; is[i_19_] = i_27_ + (i_25_ + i_26_); } } return is; } public static void method768(byte i, boolean bool) { Class36.aBoolean640 = bool; if (!Class36.aBoolean640) { int i_28_ = Class68_Sub13_Sub8.inStream.readUnsignedWordA(); int i_29_ = Class68_Sub13_Sub8.inStream.readUnsignedWordBigEndianA(); int i_30_ = Class68_Sub13_Sub8.inStream.readUnsignedWordA(); int i_31_ = (-Class68_Sub13_Sub8.inStream.currentOffset + Class106.anInt1804) / 16; Class68_Sub20_Sub6.anIntArrayArray4246 = new int[i_31_][4]; for (int i_32_ = 0; (i_31_ ^ 0xffffffff) < (i_32_ ^ 0xffffffff); i_32_++) { for (int i_33_ = 0; (i_33_ ^ 0xffffffff) > -5; i_33_++) { Class68_Sub20_Sub6.anIntArrayArray4246[i_32_][i_33_] = Class68_Sub13_Sub8.inStream.readDWord(); //System.out.println("data: " + Class68_Sub20_Sub6.anIntArrayArray4246[i_32_][i_33_]); } } boolean bool_34_ = false; int i_35_ = Class68_Sub13_Sub8.inStream.readUnsignedByteC(); int i_36_ = Class68_Sub13_Sub8.inStream.readUnsignedWord(i + 1355769449); //System.out.println("x & y: " + (i_28_ << 3) + ", " + (i_36_ << 3)); //map regions //System.out.println("height: " + i_35_); Class119.anIntArray2089 = new int[i_31_]; Class23.aByteArrayArray490 = new byte[i_31_][]; Class80.anIntArray1406 = null; Class7.aByteArrayArray133 = null; if (((i_28_ / 8 ^ 0xffffffff) == -49 || i_28_ / 8 == 49) && i_36_ / 8 == 48) bool_34_ = true; Class68_Sub13_Sub29.anIntArray3942 = new int[i_31_]; Class68_Sub20_Sub11.aByteArrayArray4332 = new byte[i_31_][]; if (i_28_ / 8 == 48 && i_36_ / 8 == 148) bool_34_ = true; Class96.anIntArray1699 = new int[i_31_]; i_31_ = 0; for (int i_37_ = (i_28_ + -6) / 8; ((6 + i_28_) / 8 ^ 0xffffffff) <= (i_37_ ^ 0xffffffff); i_37_++) { for (int i_38_ = (i_36_ + -6) / 8; (i_36_ - -6) / 8 >= i_38_; i_38_++) { int i_39_ = (i_37_ << 1786653352) + i_38_; if (!bool_34_ || (i_38_ != 49 && (i_38_ ^ 0xffffffff) != -150 && i_38_ != 147 && i_37_ != 50 && ((i_37_ ^ 0xffffffff) != -50 || i_38_ != 47))) { Class119.anIntArray2089[i_31_] = i_39_; Class96.anIntArray1699[i_31_] = (Class92.aClass21_Sub1_1644.method335((Class68_Sub20_Sub13_Sub2.method1166(2, (new RSString[]{Class83.aRSString_1525, Class68_Sub13_Sub24.method816(i_37_, 0), Class68_Sub20_Sub5.aRSString_4223, Class68_Sub13_Sub24.method816(i_38_, 0)}))), (byte) -82)); Class68_Sub13_Sub29.anIntArray3942[i_31_] = (Class92.aClass21_Sub1_1644.method335((Class68_Sub20_Sub13_Sub2.method1166(2, (new RSString[]{Class68_Sub20_Sub16.aRSString_4424, Class68_Sub13_Sub24.method816(i_37_, 0), Class68_Sub20_Sub5.aRSString_4223, Class68_Sub13_Sub24.method816(i_38_, i + -95)}))), (byte) -88)); } else { Class119.anIntArray2089[i_31_] = i_39_; Class96.anIntArray1699[i_31_] = -1; Class68_Sub13_Sub29.anIntArray3942[i_31_] = -1; } //Class128.method1890(i_39_, Class68_Sub20_Sub6.anIntArrayArray4246[i_31_]); //dumpData(i_39_, Class68_Sub20_Sub6.anIntArrayArray4246[i_31_]); i_31_++; } } ISAACRandomGen.method1455((byte) -12, i_29_, i_35_, false, i_30_, i_28_, i_36_); } else { int i_40_ = Class68_Sub13_Sub8.inStream.readUnsignedByteA(); int i_41_ = Class68_Sub13_Sub8.inStream.readUnsignedWord(i + 1355769449); int i_42_ = Class68_Sub13_Sub8.inStream.readUnsignedWordA(); Class68_Sub13_Sub8.inStream.method965(i + 17); for (int i_43_ = 0; (i_43_ ^ 0xffffffff) > -5; i_43_++) { for (int i_44_ = 0; (i_44_ ^ 0xffffffff) > -14; i_44_++) { for (int i_45_ = 0; (i_45_ ^ 0xffffffff) > -14; i_45_++) { int i_46_ = Class68_Sub13_Sub8.inStream.method967((byte) 0, 1); if (i_46_ == 1) Class68_Sub2.anIntArrayArrayArray2796[i_43_][i_44_][i_45_] = Class68_Sub13_Sub8.inStream.method967((byte) 0, 26); else Class68_Sub2.anIntArrayArrayArray2796[i_43_][i_44_][i_45_] = -1; } } } Class68_Sub13_Sub8.inStream.method966((byte) -59); int i_47_ = (-Class68_Sub13_Sub8.inStream.currentOffset + Class106.anInt1804) / 16; Class68_Sub20_Sub6.anIntArrayArray4246 = new int[i_47_][4]; for (int i_48_ = 0; i_48_ < i_47_; i_48_++) { for (int i_49_ = 0; (i_49_ ^ 0xffffffff) > -5; i_49_++) Class68_Sub20_Sub6.anIntArrayArray4246[i_48_][i_49_] = Class68_Sub13_Sub8.inStream.method940((byte) 115); } int i_50_ = Class68_Sub13_Sub8.inStream.readUnsignedWordA(); int i_51_ = Class68_Sub13_Sub8.inStream.readUnsignedWordA(); Class68_Sub20_Sub11.aByteArrayArray4332 = new byte[i_47_][]; Class7.aByteArrayArray133 = null; Class96.anIntArray1699 = new int[i_47_]; Class80.anIntArray1406 = null; Class119.anIntArray2089 = new int[i_47_]; Class23.aByteArrayArray490 = new byte[i_47_][]; Class68_Sub13_Sub29.anIntArray3942 = new int[i_47_]; i_47_ = 0; for (int i_52_ = 0; i_52_ < 4; i_52_++) { for (int i_53_ = 0; (i_53_ ^ 0xffffffff) > -14; i_53_++) { for (int i_54_ = 0; i_54_ < 13; i_54_++) { int i_55_ = (Class68_Sub2.anIntArrayArrayArray2796[i_52_][i_53_][i_54_]); if (i_55_ != -1) { int i_56_ = 0x3ff & i_55_ >> -1474462546; int i_57_ = (i_55_ & 0x3fff) >> 160515; int i_58_ = i_57_ / 8 + (i_56_ / 8 << 2129198792); for (int i_59_ = 0; i_59_ < i_47_; i_59_++) { if (Class119.anIntArray2089[i_59_] == i_58_) { i_58_ = -1; break; } } if (i_58_ != -1) { int i_60_ = (i_58_ & 0xff02) >> 1393055048; int i_61_ = i_58_ & 0xff; Class119.anIntArray2089[i_47_] = i_58_; Class96.anIntArray1699[i_47_] = (Class92.aClass21_Sub1_1644.method335((Class68_Sub20_Sub13_Sub2.method1166(2, (new RSString[]{Class83.aRSString_1525, Class68_Sub13_Sub24.method816(i_60_, i + -95), Class68_Sub20_Sub5.aRSString_4223, (Class68_Sub13_Sub24.method816(i_61_, Class15.method278(i, 95)))}))), (byte) -99)); Class68_Sub13_Sub29.anIntArray3942[i_47_] = (Class92.aClass21_Sub1_1644.method335((Class68_Sub20_Sub13_Sub2.method1166(2, (new RSString[]{(Class68_Sub20_Sub16.aRSString_4424), Class68_Sub13_Sub24.method816(i_60_, 0), Class68_Sub20_Sub5.aRSString_4223, Class68_Sub13_Sub24.method816(i_61_, 0)}))), (byte) -88)); //Class128.method1890(i_58_, Class68_Sub20_Sub6.anIntArrayArray4246[i_47_]); //dumpData(i_58_, Class68_Sub20_Sub6.anIntArrayArray4246[i_47_]); i_47_++; } } } } } ISAACRandomGen.method1455((byte) -45, i_50_, i_40_, false, i_42_, i_51_, i_41_); } if (i != 95) anInt3681 = 18; anInt3692++; } public static void dumpData(int region, int[] data) { try { FileWriter fileWriter = new FileWriter("./mapdata/" + region + ".txt"); BufferedWriter out = new BufferedWriter(fileWriter); for (int i = 0; i < data.length; i++) { out.write("" + data[i]); out.newLine(); } out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } public static void method769(byte i) { if (i < 6) anIntArray3679 = null; anIntArray3679 = null; } public static void method770(byte i) { if (Class68_Sub13_Sub27.aFloat3913 > Class68_Sub9.aFloat2892) { Class68_Sub9.aFloat2892 += (double) Class68_Sub9.aFloat2892 / 30.0; if (Class68_Sub13_Sub27.aFloat3913 < Class68_Sub9.aFloat2892) Class68_Sub9.aFloat2892 = Class68_Sub13_Sub27.aFloat3913; Class128.method1782(-1); } else if (Class68_Sub13_Sub27.aFloat3913 < Class68_Sub9.aFloat2892) { Class68_Sub9.aFloat2892 -= (double) Class68_Sub9.aFloat2892 / 30.0; if (Class68_Sub13_Sub27.aFloat3913 > Class68_Sub9.aFloat2892) Class68_Sub9.aFloat2892 = Class68_Sub13_Sub27.aFloat3913; Class128.method1782(-1); } anInt3691++; if ((Class3.anInt85 ^ 0xffffffff) != 0 && (Class68_Sub22.anInt3145 ^ 0xffffffff) != 0) { int i_62_ = -Class68_Sub13_Sub24.anInt3844 + Class3.anInt85; int i_63_ = Class68_Sub22.anInt3145 - Class85.anInt1551; if (i_62_ < 2 || i_62_ > 2) i_62_ >>= 4; Class68_Sub13_Sub24.anInt3844 = i_62_ + Class68_Sub13_Sub24.anInt3844; if (i_63_ < 2 || i_63_ > 2) i_63_ >>= 4; Class85.anInt1551 = i_63_ + Class85.anInt1551; if ((i_62_ ^ 0xffffffff) == -1 && (i_63_ ^ 0xffffffff) == -1) { Class3.anInt85 = -1; Class68_Sub22.anInt3145 = -1; } Class128.method1782(-1); } if (i >= -45) method764(72, -116, false); } }
agpl-3.0
neo4j-attic/graphdb
lucene-index/src/test/java/org/neo4j/index/impl/lucene/TestLuceneIndex.java
47616
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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 org.neo4j.index.impl.lucene; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.QueryParser.Operator; import org.apache.lucene.search.DefaultSimilarity; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TermQuery; import org.junit.Test; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.index.RelationshipIndex; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.helpers.collection.MapUtil; import org.neo4j.index.Neo4jTestCase; import org.neo4j.index.lucene.QueryContext; import org.neo4j.index.lucene.ValueContext; import org.neo4j.kernel.EmbeddedGraphDatabase; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; import static org.neo4j.index.Neo4jTestCase.assertContains; import static org.neo4j.index.Neo4jTestCase.assertContainsInOrder; import static org.neo4j.index.impl.lucene.Contains.contains; import static org.neo4j.index.impl.lucene.IsEmpty.isEmpty; import static org.neo4j.index.lucene.ValueContext.numeric; public class TestLuceneIndex extends AbstractLuceneIndexTest { @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void makeSureAdditionsCanBeRead( Index<T> index, EntityCreator<T> entityCreator ) { String key = "name"; String value = "Mattias"; assertThat( index.get( key, value ).getSingle(), is( nullValue() ) ); assertThat( index.get( key, value ), isEmpty() ); assertThat( index.query( key, "*" ), isEmpty() ); T entity1 = entityCreator.create(); T entity2 = entityCreator.create(); index.add( entity1, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value ), contains( entity1 ) ); assertThat( index.query( key, "*" ), contains( entity1 ) ); assertThat( index.get( key, value ), contains( entity1 ) ); restartTx(); } index.add( entity2, key, value ); assertThat( index.get( key, value ), contains( entity1, entity2 ) ); restartTx(); assertThat( index.get( key, value ), contains( entity1, entity2 ) ); index.delete(); } @Test public void makeSureYouGetLatestTxModificationsInQueryByDefault() { Index<Node> index = nodeIndex( "failing-index", LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); assertThat( index.query( "key:value" ), contains( node ) ); } @Test public void testStartupInExistingDirectory() { File dir = new File("target" + File.separator + "temp" + File.separator); Neo4jTestCase.deleteFileOrDirectory( dir ); dir.mkdir(); EmbeddedGraphDatabase graphDatabase = new EmbeddedGraphDatabase( dir.getAbsolutePath() ); Index<Node> index = graphDatabase.index().forNodes("nodes"); assertNotNull(index); } @Test public void makeSureAdditionsCanBeReadNodeExact() { makeSureAdditionsCanBeRead( nodeIndex( "exact", LuceneIndexImplementation.EXACT_CONFIG ), NODE_CREATOR ); } @Test public void makeSureAdditionsCanBeReadNodeFulltext() { makeSureAdditionsCanBeRead( nodeIndex( "fulltext", LuceneIndexImplementation.FULLTEXT_CONFIG ), NODE_CREATOR ); } @Test public void makeSureAdditionsCanBeReadRelationshipExact() { makeSureAdditionsCanBeRead( relationshipIndex( "exact", LuceneIndexImplementation.EXACT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void makeSureAdditionsCanBeReadRelationshipFulltext() { makeSureAdditionsCanBeRead( relationshipIndex( "fulltext", LuceneIndexImplementation.FULLTEXT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void makeSureAdditionsCanBeRemovedInSameTx() { makeSureAdditionsCanBeRemoved( false ); } @Test public void makeSureYouCanAskIfAnIndexExistsOrNot() { String name = "index-that-may-exist"; assertFalse( graphDb.index().existsForNodes( name ) ); graphDb.index().forNodes( name ); assertTrue( graphDb.index().existsForNodes( name ) ); assertFalse( graphDb.index().existsForRelationships( name ) ); graphDb.index().forRelationships( name ); assertTrue( graphDb.index().existsForRelationships( name ) ); } private void makeSureAdditionsCanBeRemoved( boolean restartTx ) { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value = "Mattias"; assertNull( index.get( key, value ).getSingle() ); Node node = graphDb.createNode(); index.add( node, key, value ); if ( restartTx ) { restartTx(); } assertEquals( node, index.get( key, value ).getSingle() ); index.remove( node, key, value ); assertNull( index.get( key, value ).getSingle() ); restartTx(); assertNull( index.get( key, value ).getSingle() ); node.delete(); index.delete(); } @Test public void makeSureAdditionsCanBeRemoved() { makeSureAdditionsCanBeRemoved( true ); } private void makeSureSomeAdditionsCanBeRemoved( boolean restartTx ) { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); String key1 = "name"; String key2 = "title"; String value1 = "Mattias"; assertNull( index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); Node node = graphDb.createNode(); Node node2 = graphDb.createNode(); index.add( node, key1, value1 ); index.add( node, key2, value1 ); index.add( node2, key1, value1 ); if ( restartTx ) { restartTx(); } index.remove( node, key1, value1 ); index.remove( node, key2, value1 ); assertEquals( node2, index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); assertEquals( node2, index.get( key1, value1 ).getSingle() ); assertNull( index.get( key2, value1 ).getSingle() ); node.delete(); index.delete(); } @Test public void makeSureSomeAdditionsCanBeRemovedInSameTx() { makeSureSomeAdditionsCanBeRemoved( false ); } @Test public void makeSureSomeAdditionsCanBeRemoved() { makeSureSomeAdditionsCanBeRemoved( true ); } @Test public void makeSureThereCanBeMoreThanOneValueForAKeyAndEntity() { makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( false ); } @Test public void makeSureThereCanBeMoreThanOneValueForAKeyAndEntitySameTx() { makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( true ); } private void makeSureThereCanBeMoreThanOneValueForAKeyAndEntity( boolean restartTx ) { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "Lucene"; String value2 = "Index"; String value3 = "Rules"; assertThat( index.query( key, "*" ), isEmpty() ); Node node = graphDb.createNode(); index.add( node, key, value1 ); index.add( node, key, value2 ); if ( restartTx ) { restartTx(); } index.add( node, key, value3 ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), contains( node ) ); assertThat( index.get( key, value3 ), contains( node ) ); assertThat( index.get( key, "whatever" ), isEmpty() ); restartTx(); } index.delete(); } @Test public void shouldNotGetLatestTxModificationsWhenChoosingSpeedQueries() { Index<Node> index = nodeIndex( "indexFooBar", LuceneIndexImplementation.EXACT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); QueryContext queryContext = new QueryContext( "value" ).tradeCorrectnessForSpeed(); assertThat( index.query( "key", queryContext ), isEmpty() ); assertThat( index.query( "key", "value" ), contains( node ) ); } @Test public void makeSureArrayValuesAreSupported() { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "Lucene"; String value2 = "Index"; String value3 = "Rules"; assertThat( index.query( key, "*" ), isEmpty() ); Node node = graphDb.createNode(); index.add( node, key, new String[]{value1, value2, value3} ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), contains( node ) ); assertThat( index.get( key, value3 ), contains( node ) ); assertThat( index.get( key, "whatever" ), isEmpty() ); restartTx(); } index.remove( node, key, new String[]{value2, value3} ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, value1 ), contains( node ) ); assertThat( index.get( key, value2 ), isEmpty() ); assertThat( index.get( key, value3 ), isEmpty() ); restartTx(); } index.delete(); } @Test public void makeSureWildcardQueriesCanBeAsked() { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); String key = "name"; String value1 = "neo4j"; String value2 = "nescafe"; Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); index.add( node1, key, value1 ); index.add( node2, key, value2 ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( key, "neo*" ), contains( node1 ) ); assertThat( index.query( key, "n?o4j" ), contains( node1 ) ); assertThat( index.query( key, "ne*" ), contains( node1, node2 ) ); assertThat( index.query( key + ":neo4j" ), contains( node1 ) ); assertThat( index.query( key + ":neo*" ), contains( node1 ) ); assertThat( index.query( key + ":n?o4j" ), contains( node1 ) ); assertThat( index.query( key + ":ne*" ), contains( node1, node2 ) ); restartTx(); } index.delete(); } @Test public void makeSureCompositeQueriesCanBeAsked() { Index<Node> index = nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ); Node neo = graphDb.createNode(); Node trinity = graphDb.createNode(); index.add( neo, "username", "neo@matrix" ); index.add( neo, "sex", "male" ); index.add( trinity, "username", "trinity@matrix" ); index.add( trinity, "sex", "female" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "username:*@matrix AND sex:male" ), contains( neo ) ); assertThat( index.query( new QueryContext( "username:*@matrix sex:male" ).defaultOperator( Operator.AND ) ), contains( neo ) ); assertThat( index.query( "username:*@matrix OR sex:male" ), contains( neo, trinity ) ); assertThat( index.query( new QueryContext( "username:*@matrix sex:male" ).defaultOperator( Operator.OR ) ), contains( neo, trinity ) ); restartTx(); } index.delete(); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void doSomeRandomUseCaseTestingWithExactIndex( Index<T> index, EntityCreator<T> creator ) { String name = "name"; String mattias = "Mattias Persson"; String title = "title"; String hacker = "Hacker"; assertThat( index.get( name, mattias ), isEmpty() ); T entity1 = creator.create(); T entity2 = creator.create(); assertNull( index.get( name, mattias ).getSingle() ); index.add( entity1, name, mattias ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertContains( index.query( name, "\"" + mattias + "\"" ), entity1 ); assertContains( index.query( "name:\"" + mattias + "\"" ), entity1 ); assertEquals( entity1, index.get( name, mattias ).getSingle() ); assertContains( index.query( "name", "Mattias*" ), entity1 ); commitTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.query( name, "\"" + mattias + "\"" ), contains( entity1 ) ); assertThat( index.query( "name:\"" + mattias + "\"" ), contains( entity1 ) ); assertEquals( entity1, index.get( name, mattias ).getSingle() ); assertThat( index.query( "name", "Mattias*" ), contains( entity1 ) ); beginTx(); index.add( entity2, title, hacker ); index.add( entity1, title, hacker ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1, entity2 ) ); assertContains( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), entity1, entity2 ); commitTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1, entity2 ) ); assertThat( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), contains( entity1, entity2 ) ); assertThat( index.query( "name:\"" + mattias + "\" AND title:\"" + hacker + "\"" ), contains( entity1 ) ); beginTx(); index.remove( entity2, title, hacker ); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1 ) ); assertContains( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), entity1 ); commitTx(); assertThat( index.get( name, mattias ), contains( entity1 ) ); assertThat( index.get( title, hacker ), contains( entity1 ) ); assertThat( index.query( "name:\"" + mattias + "\" OR title:\"" + hacker + "\"" ), contains( entity1 ) ); beginTx(); index.remove( entity1, title, hacker ); index.remove( entity1, name, mattias ); index.delete(); commitTx(); } @Test public void doSomeRandomUseCaseTestingWithExactNodeIndex() { doSomeRandomUseCaseTestingWithExactIndex( nodeIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ), NODE_CREATOR ); } @Test public void doSomeRandomUseCaseTestingWithExactRelationshipIndex() { doSomeRandomUseCaseTestingWithExactIndex( relationshipIndex( "index", LuceneIndexImplementation.EXACT_CONFIG ), RELATIONSHIP_CREATOR ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void doSomeRandomTestingWithFulltextIndex( Index<T> index, EntityCreator<T> creator ) { T entity1 = creator.create(); T entity2 = creator.create(); String key = "name"; index.add( entity1, key, "The quick brown fox" ); index.add( entity2, key, "brown fox jumped over" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, "The quick brown fox" ), contains( entity1 ) ); assertThat( index.get( key, "brown fox jumped over" ), contains( entity2 ) ); assertThat( index.query( key, "quick" ), contains( entity1 ) ); assertThat( index.query( key, "brown" ), contains( entity1, entity2 ) ); assertThat( index.query( key, "quick OR jumped" ), contains( entity1, entity2 ) ); assertThat( index.query( key, "brown AND fox" ), contains( entity1, entity2 ) ); restartTx(); } index.delete(); } @Test public void doSomeRandomTestingWithNodeFulltextInde() { doSomeRandomTestingWithFulltextIndex( nodeIndex( "fulltext", LuceneIndexImplementation.FULLTEXT_CONFIG ), NODE_CREATOR ); } @Test public void doSomeRandomTestingWithRelationshipFulltextInde() { doSomeRandomTestingWithFulltextIndex( relationshipIndex( "fulltext", LuceneIndexImplementation.FULLTEXT_CONFIG ), RELATIONSHIP_CREATOR ); } @Test public void testNodeLocalRelationshipIndex() { RelationshipIndex index = relationshipIndex( "locality", LuceneIndexImplementation.EXACT_CONFIG ); RelationshipType type = DynamicRelationshipType.withName( "YO" ); Node startNode = graphDb.createNode(); Node endNode1 = graphDb.createNode(); Node endNode2 = graphDb.createNode(); Relationship rel1 = startNode.createRelationshipTo( endNode1, type ); Relationship rel2 = startNode.createRelationshipTo( endNode2, type ); index.add( rel1, "name", "something" ); index.add( rel2, "name", "something" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name:something" ), contains( rel1, rel2 ) ); assertThat( index.query( "name:something", null, endNode1 ), contains( rel1 ) ); assertThat( index.query( "name:something", startNode, endNode2 ), contains( rel2 ) ); assertThat( index.query( null, startNode, endNode1 ), contains( rel1 ) ); assertThat( index.get( "name", "something", null, endNode1 ), contains( rel1 ) ); assertThat( index.get( "name", "something", startNode, endNode2 ), contains( rel2 ) ); assertThat( index.get( null, null, startNode, endNode1 ), contains( rel1 ) ); restartTx(); } rel2.delete(); rel1.delete(); startNode.delete(); endNode1.delete(); endNode2.delete(); index.delete(); } @Test public void testSortByRelevance() { Index<Node> index = nodeIndex( "relevance", LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); index.add( node1, "name", "something" ); index.add( node2, "name", "something" ); index.add( node2, "foo", "yes" ); index.add( node3, "name", "something" ); index.add( node3, "foo", "yes" ); index.add( node3, "bar", "yes" ); restartTx(); IndexHits<Node> hits = index.query( new QueryContext( "+name:something foo:yes bar:yes" ).sort( Sort.RELEVANCE ) ); assertEquals( node3, hits.next() ); assertEquals( node2, hits.next() ); assertEquals( node1, hits.next() ); assertFalse( hits.hasNext() ); index.delete(); node1.delete(); node2.delete(); node3.delete(); } @Test public void testSorting() { Index<Node> index = nodeIndex( "sort", LuceneIndexImplementation.EXACT_CONFIG ); String name = "name"; String title = "title"; String other = "other"; String sex = "sex"; Node adam = graphDb.createNode(); Node adam2 = graphDb.createNode(); Node jack = graphDb.createNode(); Node eva = graphDb.createNode(); index.add( adam, name, "Adam" ); index.add( adam, title, "Software developer" ); index.add( adam, sex, "male" ); index.add( adam, other, "aaa" ); index.add( adam2, name, "Adam" ); index.add( adam2, title, "Blabla" ); index.add( adam2, sex, "male" ); index.add( adam2, other, "bbb" ); index.add( jack, name, "Jack" ); index.add( jack, title, "Apple sales guy" ); index.add( jack, sex, "male" ); index.add( jack, other, "ccc" ); index.add( eva, name, "Eva" ); index.add( eva, title, "Secretary" ); index.add( eva, sex, "female" ); index.add( eva, other, "ddd" ); for ( int i = 0; i < 2; i++ ) { assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, title ) ), adam2, adam, eva, jack ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, other ) ), adam, adam2, eva, jack ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( sex, title ) ), eva, jack, adam2, adam ); assertContainsInOrder( index.query( name, new QueryContext( "*" ).sort( sex, title ) ), eva, jack, adam2, adam ); assertContainsInOrder( index.query( new QueryContext( "name:*" ).sort( name, title ).top( 2 ) ), adam2, adam ); restartTx(); } } @Test public void testNumericValues() { Index<Node> index = nodeIndex( "numeric", LuceneIndexImplementation.EXACT_CONFIG ); Node node10 = graphDb.createNode(); Node node6 = graphDb.createNode(); Node node31 = graphDb.createNode(); String key = "key"; index.add( node10, key, numeric( 10 ) ); index.add( node6, key, numeric( 6 ) ); index.add( node31, key, numeric( 31 ) ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( NumericRangeQuery.newIntRange( key, 4, 40, true, true ) ), contains( node10, node6, node31 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, true, true ) ), contains( node10, node6 ) ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 6, 15, false, true ) ), contains( node10 ) ); restartTx(); } } @Test public void testRemoveNumericValues() { Index<Node> index = nodeIndex( "numeric2", LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); String key = "key"; index.add( node1, key, new ValueContext( 15 ).indexNumeric() ); index.add( node2, key, new ValueContext( 5 ).indexNumeric() ); index.remove( node1, key, new ValueContext( 15 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); index.remove( node2, key, new ValueContext( 5 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), isEmpty() ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), isEmpty() ); index.add( node1, key, new ValueContext( 15 ).indexNumeric() ); index.add( node2, key, new ValueContext( 5 ).indexNumeric() ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node1, node2 ) ); index.remove( node1, key, new ValueContext( 15 ).indexNumeric() ); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); restartTx(); assertThat( index.query( NumericRangeQuery.newIntRange( key, 0, 20, false, false ) ), contains( node2 ) ); } @Test public void testIndexNumberAsString() { Index<Node> index = nodeIndex( "nums", LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); index.add( node1, "key", 10 ); for ( int i = 0; i < 2; i++ ) { assertEquals( node1, index.get( "key", 10 ).getSingle() ); assertEquals( node1, index.get( "key", "10" ).getSingle() ); assertEquals( node1, index.query( "key", 10 ).getSingle() ); assertEquals( node1, index.query( "key", "10" ).getSingle() ); restartTx(); } } @Test( expected = IllegalArgumentException.class ) public void makeSureIndexGetsCreatedImmediately() { // Since index creation is done outside of the normal transactions, // a rollback will not roll back index creation. nodeIndex( "immediate-index", LuceneIndexImplementation.FULLTEXT_CONFIG ); assertTrue( graphDb.index().existsForNodes( "immediate-index" ) ); rollbackTx(); assertTrue( graphDb.index().existsForNodes( "immediate-index" ) ); nodeIndex( "immediate-index", LuceneIndexImplementation.EXACT_CONFIG ); } @Test public void makeSureFulltextConfigIsCaseInsensitiveByDefault() { Index<Node> index = nodeIndex( "ft-case-sensitive", LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); String key = "name"; String value = "Mattias Persson"; index.add( node, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name", "[A TO Z]" ), contains( node ) ); assertThat( index.query( "name", "[a TO z]" ), contains( node ) ); assertThat( index.query( "name", "Mattias" ), contains( node ) ); assertThat( index.query( "name", "mattias" ), contains( node ) ); assertThat( index.query( "name", "Matt*" ), contains( node ) ); assertThat( index.query( "name", "matt*" ), contains( node ) ); restartTx(); } } @Test public void makeSureFulltextIndexCanBeCaseSensitive() { Index<Node> index = nodeIndex( "ft-case-insensitive", MapUtil.stringMap( new HashMap<String, String>( LuceneIndexImplementation.FULLTEXT_CONFIG ), "to_lower_case", "false" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "Mattias Persson"; index.add( node, key, value ); for ( int i = 0; i < 2; i++ ) { assertThat( index.query( "name", "[A TO Z]" ), contains( node ) ); assertThat( index.query( "name", "[a TO z]" ), isEmpty() ); assertThat( index.query( "name", "Matt*" ), contains( node ) ); assertThat( index.query( "name", "matt*" ), isEmpty() ); assertThat( index.query( "name", "Persson" ), contains( node ) ); assertThat( index.query( "name", "persson" ), isEmpty() ); restartTx(); } } @Test public void makeSureCustomAnalyzerCanBeUsed() { CustomAnalyzer.called = false; Index<Node> index = nodeIndex( "w-custom-analyzer", MapUtil.stringMap( "provider", "lucene", "analyzer", org.neo4j.index.impl.lucene.CustomAnalyzer.class.getName(), "to_lower_case", "true" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "The value"; index.add( node, key, value ); restartTx(); assertTrue( CustomAnalyzer.called ); assertThat( index.query( key, "[A TO Z]" ), contains( node ) ); } @Test public void makeSureCustomAnalyzerCanBeUsed2() { CustomAnalyzer.called = false; Index<Node> index = nodeIndex( "w-custom-analyzer-2", MapUtil.stringMap( "provider", "lucene", "analyzer", org.neo4j.index.impl.lucene.CustomAnalyzer.class.getName(), "to_lower_case", "true", "type", "fulltext" ) ); Node node = graphDb.createNode(); String key = "name"; String value = "The value"; index.add( node, key, value ); restartTx(); assertTrue( CustomAnalyzer.called ); assertThat( index.query( key, "[A TO Z]" ), contains( node ) ); } @Test public void makeSureIndexNameAndConfigCanBeReachedFromIndex() { String indexName = "my-index-1"; Index<Node> nodeIndex = nodeIndex( indexName, LuceneIndexImplementation.EXACT_CONFIG ); assertEquals( indexName, nodeIndex.getName() ); assertEquals( LuceneIndexImplementation.EXACT_CONFIG, graphDb.index().getConfiguration( nodeIndex ) ); String indexName2 = "my-index-2"; Index<Relationship> relIndex = relationshipIndex( indexName2, LuceneIndexImplementation.FULLTEXT_CONFIG ); assertEquals( indexName2, relIndex.getName() ); assertEquals( LuceneIndexImplementation.FULLTEXT_CONFIG, graphDb.index().getConfiguration( relIndex ) ); } @Test public void testStringQueryVsQueryObject() throws IOException { Index<Node> index = nodeIndex( "query-diff", LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node = graphDb.createNode(); index.add( node, "name", "Mattias Persson" ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( "name:Mattias AND name:Per*" ), node ); assertContains( index.query( "name:mattias" ), node ); assertContains( index.query( new TermQuery( new Term( "name", "mattias" ) ) ), node ); restartTx(); } assertNull( index.query( new TermQuery( new Term( "name", "Mattias" ) ) ).getSingle() ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testAbandonedIds( EntityCreator<T> creator, Index<T> index ) { // TODO This doesn't actually test that they are deleted, it just triggers it // so that you manually can inspect what's going on T a = creator.create(); T b = creator.create(); T c = creator.create(); String key = "name"; String value = "value"; index.add( a, key, value ); index.add( b, key, value ); index.add( c, key, value ); restartTx(); creator.delete( b ); restartTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); rollbackTx(); beginTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); index.add( c, "something", "whatever" ); restartTx(); IteratorUtil.count( (Iterator<Node>) index.get( key, value ) ); } @Test public void testAbandonedNodeIds() { testAbandonedIds( NODE_CREATOR, nodeIndex( "abandoned", LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testAbandonedNodeIdsFulltext() { testAbandonedIds( NODE_CREATOR, nodeIndex( "abandonedf", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testAbandonedRelIds() { testAbandonedIds( RELATIONSHIP_CREATOR, relationshipIndex( "abandoned", LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testAbandonedRelIdsFulltext() { testAbandonedIds( RELATIONSHIP_CREATOR, relationshipIndex( "abandonedf", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void makeSureYouCanRemoveFromRelationshipIndex() { Node n1 = graphDb.createNode(); Node n2 = graphDb.createNode(); Relationship r = n1.createRelationshipTo( n2, DynamicRelationshipType.withName( "foo" ) ); RelationshipIndex index = graphDb.index().forRelationships( "rel-index" ); String key = "bar"; index.remove( r, key, "value" ); index.add( r, key, "otherValue" ); for ( int i = 0; i < 2; i++ ) { assertThat( index.get( key, "value" ), isEmpty() ); assertThat( index.get( key, "otherValue" ), contains( r ) ); restartTx(); } } @Test public void makeSureYouCanGetEntityTypeFromIndex() { Index<Node> nodeIndex = nodeIndex( "type-test", MapUtil.stringMap( "provider", "lucene", "type", "exact" ) ); Index<Relationship> relIndex = relationshipIndex( "type-test", MapUtil.stringMap( "provider", "lucene", "type", "exact" ) ); assertEquals( Node.class, nodeIndex.getEntityType() ); assertEquals( Relationship.class, relIndex.getEntityType() ); } @Test public void makeSureConfigurationCanBeModified() { Index<Node> index = nodeIndex( "conf-index", LuceneIndexImplementation.EXACT_CONFIG ); try { graphDb.index().setConfiguration( index, "provider", "something" ); fail( "Shouldn't be able to modify provider" ); } catch ( IllegalArgumentException e ) { /* Good*/ } try { graphDb.index().removeConfiguration( index, "provider" ); fail( "Shouldn't be able to modify provider" ); } catch ( IllegalArgumentException e ) { /* Good*/ } String key = "my-key"; String value = "my-value"; String newValue = "my-new-value"; assertNull( graphDb.index().setConfiguration( index, key, value ) ); assertEquals( value, graphDb.index().getConfiguration( index ).get( key ) ); assertEquals( value, graphDb.index().setConfiguration( index, key, newValue ) ); assertEquals( newValue, graphDb.index().getConfiguration( index ).get( key ) ); assertEquals( newValue, graphDb.index().removeConfiguration( index, key ) ); assertNull( graphDb.index().getConfiguration( index ).get( key ) ); } @Test public void makeSureSlightDifferencesInIndexConfigCanBeSupplied() { Map<String, String> config = MapUtil.stringMap( "provider", "lucene", "type", "fulltext" ); String name = "the-name"; nodeIndex( name, config ); nodeIndex( name, MapUtil.stringMap( new HashMap<String, String>( config ), "to_lower_case", "true" ) ); try { nodeIndex( name, MapUtil.stringMap( new HashMap<String, String>( config ), "to_lower_case", "false" ) ); fail( "Shouldn't be able to get index with these kinds of differences in config" ); } catch ( IllegalArgumentException e ) { /* */ } nodeIndex( name, MapUtil.stringMap( new HashMap<String, String>( config ), "whatever", "something" ) ); } @Test public void testScoring() { Index<Node> index = nodeIndex( "score-index", LuceneIndexImplementation.FULLTEXT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); String key = "text"; // Where the heck did I get this sentence from? index.add( node1, key, "a time where no one was really awake" ); index.add( node2, key, "once upon a time there was" ); restartTx(); IndexHits<Node> hits = index.query( key, new QueryContext( "once upon a time was" ).sort( Sort.RELEVANCE ) ); Node hit1 = hits.next(); float score1 = hits.currentScore(); Node hit2 = hits.next(); float score2 = hits.currentScore(); assertEquals( node2, hit1 ); assertEquals( node1, hit2 ); assertTrue( score1 > score2 ); } @Test public void testTopHits() { Index<Relationship> index = relationshipIndex( "topdocs", LuceneIndexImplementation.FULLTEXT_CONFIG ); EntityCreator<Relationship> creator = RELATIONSHIP_CREATOR; String key = "text"; Relationship rel1 = creator.create( key, "one two three four five six seven eight nine ten" ); Relationship rel2 = creator.create( key, "one two three four five six seven eight other things" ); Relationship rel3 = creator.create( key, "one two three four five six some thing else" ); Relationship rel4 = creator.create( key, "one two three four five what ever" ); Relationship rel5 = creator.create( key, "one two three four all that is good and bad" ); Relationship rel6 = creator.create( key, "one two three hill or something" ); Relationship rel7 = creator.create( key, "one two other time than this" ); index.add( rel2, key, rel2.getProperty( key ) ); index.add( rel1, key, rel1.getProperty( key ) ); index.add( rel3, key, rel3.getProperty( key ) ); index.add( rel7, key, rel7.getProperty( key ) ); index.add( rel5, key, rel5.getProperty( key ) ); index.add( rel4, key, rel4.getProperty( key ) ); index.add( rel6, key, rel6.getProperty( key ) ); String query = "one two three four five six seven"; for ( int i = 0; i < 2; i++ ) { assertContainsInOrder( index.query( key, new QueryContext( query ).top( 3 ).sort( Sort.RELEVANCE ) ), rel1, rel2, rel3 ); restartTx(); } } @Test public void testSimilarity() { Index<Node> index = nodeIndex( "similarity", MapUtil.stringMap( "provider", "lucene", "type", "fulltext", "similarity", DefaultSimilarity.class.getName() ) ); Node node = graphDb.createNode(); index.add( node, "key", "value" ); restartTx(); assertContains( index.get( "key", "value" ), node ); } @Test public void testCombinedHitsSizeProblem() { Index<Node> index = nodeIndex( "size-npe", LuceneIndexImplementation.EXACT_CONFIG ); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); String key = "key"; String value = "value"; index.add( node1, key, value ); index.add( node2, key, value ); restartTx(); index.add( node3, key, value ); IndexHits<Node> hits = index.get( key, value ); assertEquals( 3, hits.size() ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKey( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String key2 = "key2"; String value = "value"; T entity1 = creator.create(); index.add( entity1, key1, value ); index.add( entity1, key2, value ); T entity2 = creator.create(); index.add( entity2, key1, value ); index.add( entity2, key2, value ); restartTx(); assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity1, entity2 ); index.remove( entity1, key2 ); assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity2 ); index.add( entity1, key2, value ); for ( int i = 0; i < 2; i++ ) { assertContains( index.get( key1, value ), entity1, entity2 ); assertContains( index.get( key2, value ), entity1, entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyNodes() throws Exception { testRemoveWithoutKey( NODE_CREATOR, nodeIndex( "remove-wo-k", LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testRemoveWithoutKeyRelationships() throws Exception { testRemoveWithoutKey( RELATIONSHIP_CREATOR, relationshipIndex( "remove-wo-k", LuceneIndexImplementation.EXACT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyValue( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String value1 = "value1"; String key2 = "key2"; String value2 = "value2"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.get( key1, value1 ), entity1, entity2 ); assertContains( index.get( key2, value2 ), entity1, entity2 ); index.remove( entity1 ); assertContains( index.get( key1, value1 ), entity2 ); assertContains( index.get( key2, value2 ), entity2 ); index.add( entity1, key1, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.get( key1, value1 ), entity1, entity2 ); assertContains( index.get( key2, value2 ), entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyValueNodes() throws Exception { testRemoveWithoutKeyValue( NODE_CREATOR, nodeIndex( "remove-wo-kv", LuceneIndexImplementation.EXACT_CONFIG ) ); } @Test public void testRemoveWithoutKeyValueRelationships() throws Exception { testRemoveWithoutKeyValue( RELATIONSHIP_CREATOR, relationshipIndex( "remove-wo-kv", LuceneIndexImplementation.EXACT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyFulltext( EntityCreator<T> creator, Index<T> index ) throws Exception { String key1 = "key1"; String key2 = "key2"; String value1 = "value one"; String value2 = "other value"; String value = "value"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); index.remove( entity1, key2 ); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity2 ); index.add( entity1, key2, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyFulltextNode() throws Exception { testRemoveWithoutKeyFulltext( NODE_CREATOR, nodeIndex( "remove-wo-k-f", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testRemoveWithoutKeyFulltextRelationship() throws Exception { testRemoveWithoutKeyFulltext( RELATIONSHIP_CREATOR, relationshipIndex( "remove-wo-k-f", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @SuppressWarnings( "unchecked" ) private <T extends PropertyContainer> void testRemoveWithoutKeyValueFulltext( EntityCreator<T> creator, Index<T> index ) throws Exception { String value = "value"; String key1 = "key1"; String value1 = value + " one"; String key2 = "key2"; String value2 = value + " two"; T entity1 = creator.create(); index.add( entity1, key1, value1 ); index.add( entity1, key2, value2 ); T entity2 = creator.create(); index.add( entity2, key1, value1 ); index.add( entity2, key2, value2 ); restartTx(); assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity1, entity2 ); index.remove( entity1 ); assertContains( index.query( key1, value ), entity2 ); assertContains( index.query( key2, value ), entity2 ); index.add( entity1, key1, value1 ); for ( int i = 0; i < 2; i++ ) { assertContains( index.query( key1, value ), entity1, entity2 ); assertContains( index.query( key2, value ), entity2 ); restartTx(); } } @Test public void testRemoveWithoutKeyValueFulltextNode() throws Exception { testRemoveWithoutKeyValueFulltext( NODE_CREATOR, nodeIndex( "remove-wo-kv-f", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testRemoveWithoutKeyValueFulltextRelationship() throws Exception { testRemoveWithoutKeyValueFulltext( RELATIONSHIP_CREATOR, relationshipIndex( "remove-wo-kv-f", LuceneIndexImplementation.FULLTEXT_CONFIG ) ); } @Test public void testSortingWithTopHitsInPartCommittedPartLocal() { Index<Node> index = nodeIndex( "mix", LuceneIndexImplementation.FULLTEXT_CONFIG ); Node first = graphDb.createNode(); Node second = graphDb.createNode(); Node third = graphDb.createNode(); Node fourth = graphDb.createNode(); String key = "key"; index.add( third, key, "ccc" ); index.add( second, key, "bbb" ); restartTx(); index.add( fourth, key, "ddd" ); index.add( first, key, "aaa" ); assertContainsInOrder( index.query( key, new QueryContext( "*" ).sort( key ) ), first, second, third, fourth ); assertContainsInOrder( index.query( key, new QueryContext( "*" ).sort( key ).top( 2 ) ), first, second ); } @Test public void shouldNotFindValueDeletedInSameTx() { Index<Node> nodeIndex = graphDb.index().forNodes( "size-after-removal" ); Node node = graphDb.createNode(); nodeIndex.add( node, "key", "value" ); restartTx(); nodeIndex.remove( node ); for ( int i = 0; i < 2; i++ ) { IndexHits<Node> hits = nodeIndex.get( "key", "value" ); assertEquals( 0, hits.size() ); assertNull( hits.getSingle() ); hits.close(); restartTx(); } } }
agpl-3.0
foocorp/gnu-fm
clients/libredroid/gen/fm/libre/droid/R.java
4874
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package fm.libre.droid; public final class R { public static final class attr { } public static final class drawable { public static final int album=0x7f020000; public static final int back=0x7f020001; public static final int ban=0x7f020002; public static final int icon=0x7f020003; public static final int logo=0x7f020004; public static final int love=0x7f020005; public static final int next=0x7f020006; public static final int pause=0x7f020007; public static final int play=0x7f020008; public static final int prev=0x7f020009; public static final int quit=0x7f02000a; public static final int save=0x7f02000b; public static final int tower=0x7f02000c; } public static final class id { public static final int ImageView01=0x7f050004; public static final int ImageView05=0x7f050015; public static final int LinearLayout01=0x7f050000; public static final int LinearLayout02=0x7f050013; public static final int ScrollView01=0x7f050002; public static final int ScrollView02=0x7f05000e; public static final int ScrollView03=0x7f05001a; public static final int StationLayout=0x7f05000f; public static final int TableLayout01=0x7f050014; public static final int TableLayout02=0x7f05001b; public static final int TableLayout03=0x7f050003; public static final int TableRow02=0x7f050020; public static final int TextView02=0x7f050007; public static final int TextView03=0x7f050009; public static final int TextView04=0x7f05000d; public static final int TextView05=0x7f05000c; public static final int TextView06=0x7f050005; public static final int TextView07=0x7f050006; public static final int TextView08=0x7f050016; public static final int TextView09=0x7f050018; public static final int addStationButton=0x7f050019; public static final int albumImage=0x7f05001d; public static final int artistText=0x7f05001f; public static final int banButton=0x7f050021; public static final int communityStationButton=0x7f050012; public static final int loginButton=0x7f05000b; public static final int loveButton=0x7f050026; public static final int loveStationButton=0x7f050011; public static final int nextButton=0x7f050024; public static final int passwordEntry=0x7f05000a; public static final int playPauseButton=0x7f050023; public static final int prevButton=0x7f050022; public static final int saveButton=0x7f050025; public static final int stationEntry=0x7f050017; public static final int stationNameText=0x7f05001c; public static final int tagStationButton=0x7f050010; public static final int titleText=0x7f05001e; public static final int usernameEntry=0x7f050008; public static final int viewAnimator=0x7f050001; } public static final class layout { public static final int list_item=0x7f030000; public static final int main=0x7f030001; } public static final class string { public static final int account_details=0x7f040007; public static final int add_station=0x7f04000d; public static final int app_name=0x7f040000; public static final int banned=0x7f040015; public static final int cant_connect=0x7f040018; public static final int community_loved=0x7f04000c; public static final int download_failed=0x7f040010; public static final int downloading=0x7f040011; public static final int finished_download=0x7f04000f; public static final int login=0x7f040003; public static final int login_failed=0x7f040019; public static final int loved=0x7f040016; public static final int loved_tracks=0x7f04000b; public static final int no_account=0x7f040008; public static final int no_content=0x7f040017; public static final int not_google_account=0x7f040006; public static final int password=0x7f040004; public static final int playlist_failed=0x7f040014; public static final int quit=0x7f040012; public static final int register=0x7f040009; public static final int sd_card_needed=0x7f04000e; public static final int tag_examples=0x7f040001; public static final int tag_stations=0x7f04000a; public static final int tagged_station=0x7f040002; public static final int tuning_in=0x7f040013; public static final int username=0x7f040005; } }
agpl-3.0
GJKrupa/wwa
src/main/java/uk/me/krupa/wwa/entity/EntityConfig.java
374
package uk.me.krupa.wwa.entity; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * Created by krupagj on 24/03/2014. */ @Configuration @ComponentScan(basePackages = {"uk.me.krupa.wwa.entity"}) public class EntityConfig { }
agpl-3.0
logistimo/asset-monitoring-service
app/com/logistimo/db/DevicePowerTransition.java
3621
/* * Copyright © 2017 Logistimo. * * This file is part of Logistimo. * * Logistimo software is a mobile & web platform for supply chain management and remote temperature monitoring in * low-resource settings, made available under the terms of the GNU Affero General Public License (AGPL). * * 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/>. * * You can be released from the requirements of the license by purchasing a commercial license. To know more about * the commercial license, please contact us at opensource@logistimo.com */ package com.logistimo.db; import java.util.ArrayList; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import play.db.jpa.JPA; /** * Created by kaniyarasu on 23/09/15. */ @Entity @Table(name = "device_power_transition") public class DevicePowerTransition { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") public Long id; @Column(name = "state") public Integer state; @Column(name = "transition_time") public Integer time; @ManyToOne public Device device; public static List<DevicePowerTransition> getDevicePowerTransition(Device device, Integer from, Integer to) { List<DevicePowerTransition> devicePowerTransitionList = new ArrayList<>(1); //Getting transition within requested range devicePowerTransitionList.addAll(JPA.em() .createQuery( "from DevicePowerTransition where device = ?1 and time > ?2 and time <= ?3 order by time desc", DevicePowerTransition.class) .setParameter(1, device) .setParameter(2, from) .setParameter(3, to) .getResultList()); //Getting older state for continuity DevicePowerTransition devicePowerTransition = JPA.em().createQuery( "from DevicePowerTransition where device = ?1 and time <= ?2 order by time desc", DevicePowerTransition.class) .setParameter(1, device) .setParameter(2, from) .setMaxResults(1) .getSingleResult(); devicePowerTransition.time = from; devicePowerTransitionList.add(devicePowerTransition); return devicePowerTransitionList; } public static DevicePowerTransition getRecentDevicePowerTransition(Device device, Integer to) { return JPA.em().createQuery( "from DevicePowerTransition where device = ?1 and time <= ?2 order by time desc", DevicePowerTransition.class) .setParameter(1, device) .setParameter(2, to) .setMaxResults(1) .getSingleResult(); } public void save() { JPA.em().persist(this); } public void update() { JPA.em().merge(this); } public void delete() { JPA.em().remove(this); } }
agpl-3.0
CodeSphere/termitaria
TermitariaTS/src/ro/cs/ts/entity/SearchCostSheetBean.java
4846
/******************************************************************************* * This file is part of Termitaria, a project management tool * Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro * * Termitaria 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 Termitaria. If not, see <http://www.gnu.org/licenses/> . ******************************************************************************/ package ro.cs.ts.entity; import java.util.Date; public class SearchCostSheetBean extends PaginationBean { private Integer[] costSheetId; private Integer id; private int teamMemberId; private int projectId; private String firstName; private String lastName; private Integer organizationId; private String activityName; private Date startDate; private Date endDate; private Character billable = new Character(' '); private Float costPriceMin; private Float costPriceMax; private Integer costPriceCurrencyId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getActivityName() { return activityName; } public void setActivityName(String activityName) { this.activityName = activityName; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Character getBillable() { return billable; } public void setBillable(Character billable) { this.billable = billable; } public Float getCostPriceMin() { return costPriceMin; } public void setCostPriceMin(Float costPriceMin) { this.costPriceMin = costPriceMin; } public Float getCostPriceMax() { return costPriceMax; } public void setCostPriceMax(Float costPriceMax) { this.costPriceMax = costPriceMax; } public Integer[] getCostSheetId() { return costSheetId; } public void setCostSheetId(Integer[] costSheetId) { this.costSheetId = costSheetId; } public int getTeamMemberId() { return teamMemberId; } public void setTeamMemberId(int teamMemberId) { this.teamMemberId = teamMemberId; } public int getProjectId() { return projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getOrganizationId() { return organizationId; } public void setOrganizationId(Integer organizationId) { this.organizationId = organizationId; } public Integer getCostPriceCurrencyId() { return costPriceCurrencyId; } public void setCostPriceCurrencyId(Integer costPriceCurrencyId) { this.costPriceCurrencyId = costPriceCurrencyId; } public String toString() { StringBuffer sb = new StringBuffer("["); sb.append(this.getClass().getSimpleName()); sb.append(": "); sb.append("costSheetId = ") .append(costSheetId) .append(", "); sb.append("id = ") .append(id) .append(", "); sb.append("teamMemberId = ") .append(teamMemberId) .append(", "); sb.append("projectId = ") .append(projectId) .append(", "); sb.append("firstName = ") .append(firstName) .append(", "); sb.append("lastName = ") .append(lastName) .append(", "); sb.append("organizationId = ") .append(organizationId) .append(", "); sb.append("activityName = ") .append(activityName) .append(", "); sb.append("startDate = ") .append(startDate) .append(", "); sb.append("endDate = ") .append(endDate) .append(", "); sb.append("billable = ") .append(billable) .append(", "); sb.append("costPriceMin = ") .append(costPriceMin) .append(", "); sb.append("costPriceMax = ") .append(costPriceMax) .append(", "); sb.append("costPriceCurrencyId = ").append(costPriceCurrencyId).append("]"); return sb.toString(); } }
agpl-3.0
JavierPeris/kunagi
src/main/java/scrum/server/project/ProjectDao.java
3433
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * 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 General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.server.project; import ilarkesto.core.logging.Log; import ilarkesto.core.time.Date; import ilarkesto.core.time.DateAndTime; import scrum.server.admin.User; import scrum.server.admin.UserDao; public class ProjectDao extends GProjectDao { private static final Log LOG = Log.get(ProjectDao.class); // --- dependencies --- private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } // --- --- @Override public Project newEntityInstance() { Project project = super.newEntityInstance(); project.setLastOpenedDateAndTime(DateAndTime.now()); return project; } public Project postProject(User admin) { Project project = newEntityInstance(); project.setLabel(createProjectLabel("Project")); project.addAdmin(admin); saveEntity(project); return project; } private String createProjectLabel(String labelPrefix) { int count = 1; String label = labelPrefix + " " + count; Project project = getProjectByLabel(label); while (project != null) { count++; label = labelPrefix + " " + count; project = getProjectByLabel(label); } return label; } public void scanFiles() { LOG.info("Scanning file repositories of all projects"); for (Project project : getEntities()) { project.scanFiles(); } } // --- test data --- public Project postExampleProject(User owner, User po, User sm) { Project project = postProject(owner); project.setBegin(Date.today().addMonths(-2)); project.setEnd(Date.today().addMonths(5)); project.setSupportEmail("support@kunagi.org"); project.setIssueReplyTemplate("Hello ${issuer.name},\n" + "\n" + "Thank you for your feedback. You can check the status of your issue here: " + "${homepage.url}/${issue.reference}.html" + "\n" + "\nKind regards,\n" + "${user.name}"); project.addAdmin(owner); project.addProductOwner(po); project.addProductOwner(owner); project.addScrumMaster(sm); project.addScrumMaster(owner); project.addTeamMember(owner); project.addParticipants(project.getAdmins()); project.addParticipants(project.getTeamMembers()); project.addParticipants(project.getProductOwners()); project.addParticipants(project.getScrumMasters()); project.addTestSprints(); project.addTestRequirements(); project.addTestImpediments(); project.addTestRisks(); project.addTestQualitys(); project.addTestIssues(); project.addTestEvents(); project.addTestSimpleEvents(); project.addTestReleases(); project.getCurrentSprint().burndownTasksRandomly(Date.beforeDays(15), Date.today().addDays(-1)); po.setCurrentProject(project); return project; } @Override protected int getOrderIndex() { return -10; } }
agpl-3.0
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/LocationService.java
2366
package org.chorem.ecd.service; import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.model.settings.Location; import org.chorem.ecd.model.weather.WeatherForecast; import org.chorem.ecd.task.WeatherForecastBuilderPeriodicTask; import org.chorem.ecd.EcdConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.IOException; import java.net.URL; import java.util.Optional; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class LocationService { private static final Logger logger = LoggerFactory.getLogger(LocationService.class); @Inject protected SettingsDao settingsDao; @Inject protected EcdConfig config; @Inject protected JsonService jsonService; @Inject protected PeriodicTasksExecutorService periodicTasksExecutorService; @PostConstruct public void init() { periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); } public WeatherForecast getWeatherForecast() { try { WeatherForecast weatherForecast = jsonService.loadFromJson(WeatherForecast.class, config.getWeatherForecastPath()); return Optional.ofNullable(weatherForecast).orElse(new WeatherForecast()); } catch (IOException e) { logger.error(e.getMessage(), e); return null; } } public Location getLocation() { return settingsDao.getLocation(); } @TransactionRequired public void setLocation(Location location) { String weatherForecastUrl = location.getWeatherForecastUrl().replace("/meteo/localite/", "/services/json/"); location.setWeatherForecastUrl(weatherForecastUrl); settingsDao.setLocation(location); periodicTasksExecutorService.schedule(getWeatherForecastBuilderTask()); } private WeatherForecastBuilderPeriodicTask getWeatherForecastBuilderTask() { String forecastUrl = settingsDao.getLocation().getWeatherForecastUrl(); WeatherForecastBuilderPeriodicTask task = new WeatherForecastBuilderPeriodicTask(forecastUrl); task.setConfig(config); task.setJsonService(jsonService); return task; } }
agpl-3.0
duniter-gchange/gchange-pod
gchange-pod-es-plugin/src/main/java/org/duniter/elasticsearch/gchange/service/NetworkService.java
3765
package org.duniter.elasticsearch.gchange.service; import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.duniter.core.client.model.bma.EndpointApi; import org.duniter.core.client.model.local.Peer; import org.duniter.core.service.CryptoService; import org.duniter.elasticsearch.client.Duniter4jClient; import org.duniter.elasticsearch.gchange.PluginSettings; import org.duniter.elasticsearch.gchange.model.bma.GchangeEndpoindApi; import org.duniter.elasticsearch.service.CurrencyService; import org.duniter.elasticsearch.threadpool.ScheduledActionFuture; import org.duniter.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.common.inject.Inject; import java.io.Closeable; import java.util.Collection; import java.util.Optional; import java.util.concurrent.TimeUnit; public class NetworkService extends AbstractService { private final org.duniter.elasticsearch.service.NetworkService delegate; private final CurrencyService currencyService; private final PeerService peerService; private final ThreadPool threadPool; @Inject public NetworkService(Duniter4jClient client, PluginSettings settings, ThreadPool threadPool, CryptoService cryptoService, CurrencyService currencyService, PeerService peerService, org.duniter.elasticsearch.service.NetworkService networkService) { super("gchange.network", client, settings, cryptoService); this.threadPool = threadPool; this.currencyService = currencyService; this.peerService = peerService; this.delegate = networkService; // Register GCHANGE_API as published API, inside the peering document delegate.registerPeeringPublishApi(GchangeEndpoindApi.GCHANGE_API.label()); // Register GCHANGE_API as target API, for peering document delegate.registerPeeringTargetApi(GchangeEndpoindApi.GCHANGE_API.label()); } public Collection<Peer> getPeersWithGchangeApi() { Collection<Peer> peers = Lists.newArrayList(); for (String currency: currencyService.getAllIds()) { peers.addAll(delegate.getPeersFromApi(currency, GchangeEndpoindApi.GCHANGE_API.label())); } return peers; } public Collection<Peer> getConfigPeersWithGchangeApi() { Collection<Peer> peers = Lists.newArrayList(); for (String currency: currencyService.getAllIds()) { peers.addAll(delegate.getConfigIncludesPeers(currency, GchangeEndpoindApi.GCHANGE_API.label())); } return peers; } /** * Watch network peers, from endpoints found in config * @return a tear down logic, to call to stop the listener */ public Optional<Closeable> startListeningPeers() { final Collection<Peer> configPeers = getConfigPeersWithGchangeApi(); if (CollectionUtils.isEmpty(configPeers)) { if (logger.isWarnEnabled()) { logger.warn(String.format("No compatible endpoints found in config option '%s'. Cannot listening peers from network", "duniter.p2p.includes.endpoints")); } return Optional.empty(); } // Update peers, using endpoints found in config ScheduledActionFuture<?> future = threadPool.scheduleAtFixedRate(() -> { // Index config peers configPeers.forEach(peerService::indexPeers); }, pluginSettings.getScanPeerInterval(), pluginSettings.getScanPeerInterval(), TimeUnit.SECONDS); // Tear down logic return Optional.of(() -> future.cancel(true)); } }
agpl-3.0
splicemachine/spliceengine
hbase_sql/src/main/java/com/splicemachine/stream/QueryJob.java
9529
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine 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, or (at your option) any later version. * Splice Machine 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 Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.stream; import com.splicemachine.EngineDriver; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.services.context.ContextService; import com.splicemachine.db.iapi.sql.Activation; import com.splicemachine.db.iapi.sql.conn.LanguageConnectionContext; import com.splicemachine.db.iapi.sql.execute.ExecRow; import com.splicemachine.db.iapi.store.access.TransactionController; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.olap.OlapStatus; import com.splicemachine.derby.impl.SpliceSpark; import com.splicemachine.derby.stream.ActivationHolder; import com.splicemachine.derby.stream.function.CloneFunction; import com.splicemachine.derby.stream.function.IdentityFunction; import com.splicemachine.derby.stream.iapi.DataSet; import com.splicemachine.derby.stream.iapi.DistributedDataSetProcessor; import com.splicemachine.derby.stream.iapi.OperationContext; import com.splicemachine.derby.stream.spark.SparkDataSet; import com.splicemachine.si.api.txn.TxnView; import com.splicemachine.sparksql.SparkSQLUtilsImpl; import org.apache.log4j.Logger; import org.apache.spark.SparkContext; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.internal.SQLConf; import java.util.UUID; import java.util.concurrent.*; import static com.splicemachine.derby.impl.sql.execute.TriggerRowHolderImpl.dropTable; import static java.lang.String.format; /** * @author Scott Fines * Date: 4/1/16 */ public class QueryJob implements Callable<Void>{ private static final Logger LOG = Logger.getLogger(QueryJob.class); private final OlapStatus status; private final RemoteQueryJob queryRequest; public QueryJob(RemoteQueryJob queryRequest, OlapStatus jobStatus) { this.status = jobStatus; this.queryRequest = queryRequest; } public static void setSparkContextInLCC(SparkContext sparkContext, LanguageConnectionContext lcc, int applicationJarsHash) { if (lcc == null) return; lcc.setSparkContext(sparkContext); lcc.setApplicationJarsHashCode(applicationJarsHash); } public static LanguageConnectionContext getLCC() { return (LanguageConnectionContext) ContextService.getContextOrNull(LanguageConnectionContext.CONTEXT_ID); } @Override public Void call() throws Exception { if(!status.markRunning()){ //the client has already cancelled us or has died before we could get started, so stop now return null; } ActivationHolder ah = queryRequest.ah; SpliceOperation root = ah.getOperationsMap().get(queryRequest.rootResultSetNumber); DistributedDataSetProcessor dsp = EngineDriver.driver().processorFactory().distributedProcessor(); DataSet<ExecRow> dataset; OperationContext<SpliceOperation> context; String jobName = null; Activation activation = null; boolean resetSession = false; LanguageConnectionContext lcc = null; int initialApplicationJarsHash = 0; try { if (queryRequest.shufflePartitions != null) { SpliceSpark.getSession().conf().set(SQLConf.SHUFFLE_PARTITIONS().key(), queryRequest.shufflePartitions); resetSession = true; } ah.reinitialize(null); activation = ah.getActivation(); lcc = activation.getLanguageConnectionContext(); JavaSparkContext jsc = SpliceSpark.getContext(); if (jsc != null) { initialApplicationJarsHash = SpliceSpark.getApplicationJarsHash(); setSparkContextInLCC(jsc.sc(), lcc, initialApplicationJarsHash); lcc.setupSparkSQLUtils(SparkSQLUtilsImpl.getInstance()); } root.setActivation(activation); if (!(activation.isMaterialized())) activation.materialize(); TxnView parent = root.getCurrentTransaction(); long txnId = parent.getTxnId(); String sql = queryRequest.sql; String session = queryRequest.session; String userId = queryRequest.userId; jobName = userId + " <" + session + "," + txnId + ">"; LOG.info("Running query for user/session: " + userId + "," + session); if (LOG.isTraceEnabled()) { LOG.trace("Query: " + sql); } dsp.setJobGroup(jobName, sql); addUserJarsToSparkContext(activation, SpliceSpark.getContext()); if (lcc != null) { int applicationJarsHash; LanguageConnectionContext lccFromContext = getLCC(); if (lccFromContext != null) { applicationJarsHash = lccFromContext.getApplicationJarsHashCode(); if (applicationJarsHash != 0 && applicationJarsHash != initialApplicationJarsHash) SpliceSpark.setApplicationJarsHash(applicationJarsHash); } else { applicationJarsHash = lcc.getApplicationJarsHashCode(); if (applicationJarsHash != 0 && applicationJarsHash != initialApplicationJarsHash) SpliceSpark.setApplicationJarsHash(applicationJarsHash); } } try(SparkProgressListener counter = new SparkProgressListener(queryRequest.uuid.toString(), status) ) { dataset = root.getDataSet(dsp); context = dsp.createOperationContext(root); SparkDataSet<ExecRow> sparkDataSet = (SparkDataSet<ExecRow>) dataset .map(new CloneFunction<>(context)) .map(new IdentityFunction<>(context)); // force materialization into Derby's format String clientHost = queryRequest.host; int clientPort = queryRequest.port; UUID uuid = queryRequest.uuid; int numPartitions = sparkDataSet.rdd.rdd().getNumPartitions(); JavaRDD rdd = sparkDataSet.rdd; StreamableRDD streamableRDD = new StreamableRDD<>(rdd, context, uuid, clientHost, clientPort, queryRequest.streamingBatches, queryRequest.streamingBatchSize, queryRequest.parallelPartitions, queryRequest.partitionExecutorThreads); streamableRDD.setJobStatus(status); streamableRDD.submit(); status.markCompleted(new QueryResult(numPartitions)); LOG.info("Completed query for session: " + session); } } catch (CancellationException e) { if (jobName != null) SpliceSpark.getContext().sc().cancelJobGroup(jobName); throw e; } finally { long tempTriggerConglomerate = dsp.getTempTriggerConglomerate(); if (tempTriggerConglomerate != 0 && activation != null) dropConglomerate(tempTriggerConglomerate, activation); if(resetSession) SpliceSpark.resetSession(); ah.close(); } return null; } // Tell Spark where to find user jars that were // added via CALL SQLJ.INSTALL_JAR. private void addUserJarsToSparkContext(Activation activation, JavaSparkContext jsc) { if (jsc == null) return; SparkContext sparkContext = jsc.sc(); if (sparkContext == null) return; LanguageConnectionContext lcc = activation.getLanguageConnectionContext(); if (lcc == null) return; lcc.setSparkContext(sparkContext); lcc.setupSparkSQLUtils(SparkSQLUtilsImpl.getInstance()); lcc.addUserJarsToSparkContext(); } private void dropConglomerate(long CID, Activation activation) { TransactionController tc = activation.getTransactionController(); LOG.trace(format("Dropping temporary conglomerate splice:%d", CID)); try { tc.dropConglomerate(CID); } catch (StandardException e) { LOG.warn(format("Unable to drop temporary trigger conglomerate %d. Cleanup may have been called twice.", CID), e); } try { dropTable(CID); } catch (StandardException e) { LOG.warn(format("Unable to drop HBase table for temporary trigger conglomerate %d. Cleanup may have been called twice.", CID), e); } } }
agpl-3.0
kagucho/tsubonesystem2
src/main/java/tsuboneSystem/entity/TClub.java
2434
/* * Copyright (C) 2014-2016 Kagucho <kagucho.net@gmail.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 tsuboneSystem.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * Clubのエンティティクラス * * @author oowada */ @Entity @Table(name = "T_CLUB") public class TClub implements Serializable { private static final long serialVersionUID = 1L; /** idプロパティ */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(nullable = true, unique = true) public Integer id; /** 部名 */ @Column(nullable = true, unique = false) public String ClubName; /** 部長のID */ @Column(nullable = true, unique = false) public Integer LeadersId; /** 部の説明 */ @Column(nullable = false, unique = false) public String ClubMemo; /** 部 個別のホームページ */ @Column() public String clubUrl; /** 削除フラグ */ @Column(columnDefinition ="boolean default '0'") public Boolean deleteFlag; /** 部長のIDをTClubに関連付ける */ @OneToOne @JoinColumn(name = "LEADERS_ID", referencedColumnName = "ID") public TLeaders tLeaders; /** IdをTPartyClubに結びつける */ @OneToMany(mappedBy = "tClub") public List<TPartyClub> tPartyClubList; /** IdをTMemberClubに結びつける */ @OneToMany(mappedBy = "tClub") public List<TMemberClub> tMemberClubList; }
agpl-3.0
0x7678/openss7
src/java/javax/jain/ss7/inap/datatype/CounterAndValue.java
3730
/* @(#) $RCSfile: CounterAndValue.java,v $ $Name: $($Revision: 1.1.2.1 $) $Date: 2009-06-21 11:34:53 $ <p> Copyright &copy; 2008-2009 Monavacon Limited <a href="http://www.monavacon.com/">&lt;http://www.monavacon.com/&gt;</a>. <br> Copyright &copy; 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/">&lt;http://www.openss7.com/&gt;</a>. <br> Copyright &copy; 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org">&lt;bidulock@openss7.org&gt;</a>. <p> All Rights Reserved. <p> 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, version 3 of the license. <p> This program is distributed in the hope that it will be useful, but <b>WITHOUT ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b> or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public License for more details. <p> You should have received a copy of the GNU Affero General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses/">&lt;http://www.gnu.org/licenses/&gt</a>, or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. <p> <em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this Software on behalf of the U.S. Government ("Government"), the following provisions apply to you. If the Software is supplied by the Department of Defense ("DoD"), it is classified as "Commercial Computer Software" under paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any successor regulations) and the Government is acquiring only the license rights granted herein (the license rights customarily provided to non-Government users). If the Software is supplied to any unit or agency of the Government other than DoD, it is classified as "Restricted Computer Software" and the Government's rights in the Software are defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p> Commercial licensing and support of this software is available from OpenSS7 Corporation at a fee. See <a href="http://www.openss7.com/">http://www.openss7.com/</a> <p> Last Modified $Date: 2009-06-21 11:34:53 $ by $Author: brian $ */ package javax.jain.ss7.inap.datatype; import javax.jain.ss7.inap.constants.*; import javax.jain.ss7.inap.*; import javax.jain.ss7.*; import javax.jain.*; /** This class defines the CounterAndValue Datatype. * @version 1.2.2 * @author Monavacon Limited */ public class CounterAndValue implements java.io.Serializable { /** Constructor For CounterAndValue. */ public CounterAndValue(int counterID, int counterValue) { setCounterID(counterID); setCounterValue(counterValue); } /** Gets Counter ID. */ public int getCounterID() { return counterID; } /** Sets Counter ID. */ public void setCounterID(int counterID) { this.counterID = counterID; } /** Gets Counter Value. */ public int getCounterValue() { return counterValue; } /** Sets Counter Value. */ public void setCounterValue(int counterValue) { this.counterValue = counterValue; } private int counterID; private int counterValue; } // vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
agpl-3.0
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/map/feature/Feature.java
16672
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.gwt.client.map.feature; import org.geomajas.annotation.Api; import org.geomajas.configuration.AbstractAttributeInfo; import org.geomajas.geometry.Coordinate; import org.geomajas.gwt.client.gfx.Paintable; import org.geomajas.gwt.client.gfx.PainterVisitor; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.spatial.Bbox; import org.geomajas.gwt.client.spatial.geometry.Geometry; import org.geomajas.gwt.client.util.AttributeUtil; import org.geomajas.gwt.client.util.GeometryConverter; import org.geomajas.layer.feature.Attribute; import org.geomajas.layer.feature.attribute.AssociationValue; import org.geomajas.layer.feature.attribute.BooleanAttribute; import org.geomajas.layer.feature.attribute.CurrencyAttribute; import org.geomajas.layer.feature.attribute.DateAttribute; import org.geomajas.layer.feature.attribute.DoubleAttribute; import org.geomajas.layer.feature.attribute.FloatAttribute; import org.geomajas.layer.feature.attribute.ImageUrlAttribute; import org.geomajas.layer.feature.attribute.IntegerAttribute; import org.geomajas.layer.feature.attribute.LongAttribute; import org.geomajas.layer.feature.attribute.ManyToOneAttribute; import org.geomajas.layer.feature.attribute.OneToManyAttribute; import org.geomajas.layer.feature.attribute.ShortAttribute; import org.geomajas.layer.feature.attribute.StringAttribute; import org.geomajas.layer.feature.attribute.UrlAttribute; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * <p> * Definition of an object belonging to a {@link VectorLayer}. A feature is an object with a unique ID * within it's layer, a list of alpha-numerical attributes and a geometry. * </p> * * @author Pieter De Graef * @since 1.6.0 */ @Api public class Feature implements Paintable, Cloneable { /** Unique identifier */ private String id; /** Reference to the layer. */ private VectorLayer layer; /** Map of this feature's attributes. */ private Map<String, Attribute> attributes = new HashMap<String, Attribute>(); /** Are the attributes lazy Loaded yet? */ private boolean attributesLoaded; /** This feature's geometry. */ private Geometry geometry; /** The identifier of this feature's style. */ private String styleId; /** Label text. */ private String label = ""; // new features have no label yet, empty string to avoid npe ! /** Coordinate for the label. */ private Coordinate labelPosition; /** is the feature clipped ? */ private boolean clipped; /** * Is it allowed for the user in question to edit this feature? */ private boolean updatable; /** * Is it allowed for the user in question to delete this feature? */ private boolean deletable; private String crs; // Constructors: /** No-arguments constructor. */ public Feature() { this((org.geomajas.layer.feature.Feature) null, null); } /** * Construct feature with given id for given layer. * * @param id feature id * @param layer layer */ public Feature(String id, VectorLayer layer) { this(layer); this.id = id; } /** * Construct a feature for given layer. * * @param layer layer */ public Feature(VectorLayer layer) { this((org.geomajas.layer.feature.Feature) null, layer); } /** * Construct a feature based from a feature DTO for given layer. * * @param dto feature dto * @param layer layer */ public Feature(org.geomajas.layer.feature.Feature dto, VectorLayer layer) { this.layer = layer; this.geometry = null; this.styleId = null; this.labelPosition = null; this.clipped = false; if (null != dto) { label = dto.getLabel(); attributes = dto.getAttributes(); attributesLoaded = true; id = dto.getId(); geometry = GeometryConverter.toGwt(dto.getGeometry()); styleId = dto.getStyleId(); crs = dto.getCrs(); setUpdatable(dto.isUpdatable()); setDeletable(dto.isDeletable()); } else { if (layer != null) { // Create empty attributes: for (AbstractAttributeInfo attrInfo : layer.getLayerInfo().getFeatureInfo().getAttributes()) { attributes.put(attrInfo.getName(), AttributeUtil.createEmptyAttribute(attrInfo)); } } setUpdatable(true); setDeletable(true); } } // Paintable implementation: public void accept(PainterVisitor visitor, Object group, Bbox bounds, boolean recursive) { visitor.visit(this, group); } public String getId() { return id; } // Class specific functions: /** Clone the object. */ public Feature clone() { // NOSONAR overwriting clone but not using super.clone() Feature feature = new Feature(this.layer); if (null != attributes) { feature.attributes = new HashMap<String, Attribute>(); for (Entry<String, Attribute> entry : attributes.entrySet()) { feature.attributes.put(entry.getKey(), (Attribute<?>) entry.getValue().clone()); } } feature.clipped = clipped; feature.labelPosition = labelPosition; feature.label = label; feature.layer = layer; if (null != geometry) { feature.geometry = (Geometry) geometry.clone(); } feature.id = id; feature.styleId = styleId; feature.crs = crs; feature.deletable = deletable; feature.updatable = updatable; feature.attributesLoaded = attributesLoaded; return feature; } /** * Get attribute value for given attribute name. * * @param attributeName attribute name * @return attribute value */ public Object getAttributeValue(String attributeName) { Attribute attribute = getAttributes().get(attributeName); if (attribute != null) { return attribute.getValue(); } return null; } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setBooleanAttribute(String name, Boolean value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof BooleanAttribute)) { throw new IllegalStateException("Cannot set boolean value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((BooleanAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setCurrencyAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof CurrencyAttribute)) { throw new IllegalStateException("Cannot set currency value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((CurrencyAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setDateAttribute(String name, Date value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof DateAttribute)) { throw new IllegalStateException("Cannot set date value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((DateAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setDoubleAttribute(String name, Double value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof DoubleAttribute)) { throw new IllegalStateException("Cannot set double value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((DoubleAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setFloatAttribute(String name, Float value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof FloatAttribute)) { throw new IllegalStateException("Cannot set float value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((FloatAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setImageUrlAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof ImageUrlAttribute)) { throw new IllegalStateException("Cannot set imageUrl value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((ImageUrlAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setIntegerAttribute(String name, Integer value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof IntegerAttribute)) { throw new IllegalStateException("Cannot set integer value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((IntegerAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setLongAttribute(String name, Long value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof LongAttribute)) { throw new IllegalStateException("Cannot set boolean value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((LongAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setShortAttribute(String name, Short value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof ShortAttribute)) { throw new IllegalStateException("Cannot set short value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((ShortAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setStringAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof StringAttribute)) { throw new IllegalStateException("Cannot set boolean value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((StringAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setUrlAttribute(String name, String value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof UrlAttribute)) { throw new IllegalStateException("Cannot set url value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((UrlAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void setManyToOneAttribute(String name, AssociationValue value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof ManyToOneAttribute)) { throw new IllegalStateException("Cannot set manyToOne value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } ((ManyToOneAttribute) attribute).setValue(value); } /** * Set attribute value of given type. * * @param name attribute name * @param value attribute value */ public void addOneToManyValue(String name, AssociationValue value) { Attribute attribute = getAttributes().get(name); if (!(attribute instanceof OneToManyAttribute)) { throw new IllegalStateException("Cannot set oneToMany value on attribute with different type, " + attribute.getClass().getName() + " setting value " + value); } OneToManyAttribute oneToMany = (OneToManyAttribute) attribute; if (oneToMany.getValue() == null) { oneToMany.setValue(new ArrayList<AssociationValue>()); } oneToMany.getValue().add(value); } /** * Transform this object into a DTO feature. * * @return dto for this feature */ public org.geomajas.layer.feature.Feature toDto() { org.geomajas.layer.feature.Feature dto = new org.geomajas.layer.feature.Feature(); dto.setAttributes(attributes); dto.setClipped(clipped); dto.setId(id); dto.setGeometry(GeometryConverter.toDto(geometry)); dto.setCrs(crs); dto.setLabel(getLabel()); return dto; } /** * Get feature label. * * @return label */ public String getLabel() { return label; } /** * Set feature label. * * @param label * @since 1.15.0 */ public void setLabel(String label) { this.label = label; } // Getters and setters: /** * Crs as (optionally) set by the backend. * * @return crs for this feature */ public String getCrs() { return crs; } /** * Get the attributes map, throws exception when it needs to be lazy loaded. * * @return attributes map * @throws IllegalStateException * attributes not present because of lazy loading */ public Map<String, Attribute> getAttributes() throws IllegalStateException { return attributes; } /** * Set the attributes map. * * @param attributes * attributes map */ public void setAttributes(Map<String, Attribute> attributes) { if (null == attributes) { throw new IllegalArgumentException("Attributes should be not-null."); } this.attributes = attributes; this.attributesLoaded = true; } /** * Check whether the attributes are already available or should be lazy loaded. * * @return true when attributes are available */ public boolean isAttributesLoaded() { return attributesLoaded; } /** * Get the feature's geometry, throws exception when it needs to be lazy loaded. * * @return geometry * @throws IllegalStateException * attributes not present because of lazy loading */ public Geometry getGeometry() throws IllegalStateException { if (null == geometry) { throw new IllegalStateException("Geometry not available, use LazyLoader."); } return geometry; } /** * Set the geometry. * * @param geometry * geometry */ public void setGeometry(Geometry geometry) { this.geometry = geometry; } /** * Check whether the geometry is already available or should be lazy loaded. * * @return true when geometry are available */ public boolean isGeometryLoaded() { return geometry != null; } /** * Is this feature selected? * * @return true when feature is selected */ public boolean isSelected() { return layer.isFeatureSelected(getId()); } /** * Get the layer which contains this feature. * * @return layer which contains this feature */ public VectorLayer getLayer() { return layer; } /** * Is the logged in user allowed to edit this feature? * * @return true when edit/update is allowed for this feature */ public boolean isUpdatable() { return updatable; } /** * Set whether the logged in user is allowed to edit/update this feature. * * @param editable * true when edit/update is allowed for this feature */ public void setUpdatable(boolean editable) { this.updatable = editable; } /** * Is the logged in user allowed to delete this feature? * * @return true when delete is allowed for this feature */ public boolean isDeletable() { return deletable; } /** * Set whether the logged in user is allowed to delete this feature. * * @param deletable * true when deleting this feature is allowed */ public void setDeletable(boolean deletable) { this.deletable = deletable; } /** * Get the style id for this feature. * * @return style if */ public String getStyleId() { return styleId; } /** * Set the style id for this feature. * * @param styleId style id */ public void setStyleId(String styleId) { this.styleId = styleId; } }
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/example/table/GrowingExampleTable.java
1351
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.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.example.table; /** * {@link ExampleTable} to which rows can be added. * * @author Gisa Schaefer * @since 7.3 */ public interface GrowingExampleTable extends ExampleTable { /** * Adds the given row at the end of the table * * @param row * the row to be added * @throws RuntimeException * May be thrown if the data row does not fit the attributes of the underlying * table, depending on the data row implementation. */ void addDataRow(DataRow row); }
agpl-3.0
sakazz/exchange
core/src/main/java/io/bisq/core/dao/blockchain/parse/RpcService.java
10911
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package io.bisq.core.dao.blockchain.parse; import com.google.common.collect.ImmutableList; import com.google.inject.Inject; import com.neemre.btcdcli4j.core.BitcoindException; import com.neemre.btcdcli4j.core.CommunicationException; import com.neemre.btcdcli4j.core.client.BtcdClient; import com.neemre.btcdcli4j.core.client.BtcdClientImpl; import com.neemre.btcdcli4j.core.domain.Block; import com.neemre.btcdcli4j.core.domain.RawTransaction; import com.neemre.btcdcli4j.core.domain.Transaction; import com.neemre.btcdcli4j.core.domain.enums.ScriptTypes; import com.neemre.btcdcli4j.daemon.BtcdDaemon; import com.neemre.btcdcli4j.daemon.BtcdDaemonImpl; import com.neemre.btcdcli4j.daemon.event.BlockListener; import io.bisq.core.dao.DaoOptionKeys; import io.bisq.core.dao.blockchain.btcd.PubKeyScript; import io.bisq.core.dao.blockchain.exceptions.BsqBlockchainException; import io.bisq.core.dao.blockchain.vo.*; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Named; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Collectors; // Blocking access to Bitcoin Core via RPC requests // See the rpc.md file in the doc directory for more info about the setup. public class RpcService { private static final Logger log = LoggerFactory.getLogger(RpcService.class); private final String rpcUser; private final String rpcPassword; private final String rpcPort; private final String rpcBlockPort; private final boolean dumpBlockchainData; private BtcdClient client; private BtcdDaemon daemon; /////////////////////////////////////////////////////////////////////////////////////////// // Constructor /////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("WeakerAccess") @Inject public RpcService(@Named(DaoOptionKeys.RPC_USER) String rpcUser, @Named(DaoOptionKeys.RPC_PASSWORD) String rpcPassword, @Named(DaoOptionKeys.RPC_PORT) String rpcPort, @Named(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT) String rpcBlockPort, @Named(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA) boolean dumpBlockchainData) { this.rpcUser = rpcUser; this.rpcPassword = rpcPassword; this.rpcPort = rpcPort; this.rpcBlockPort = rpcBlockPort; this.dumpBlockchainData = dumpBlockchainData; } void setup() throws BsqBlockchainException { try { long startTs = System.currentTimeMillis(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); CloseableHttpClient httpProvider = HttpClients.custom().setConnectionManager(cm).build(); Properties nodeConfig = new Properties(); nodeConfig.setProperty("node.bitcoind.rpc.protocol", "http"); nodeConfig.setProperty("node.bitcoind.rpc.host", "127.0.0.1"); nodeConfig.setProperty("node.bitcoind.rpc.auth_scheme", "Basic"); nodeConfig.setProperty("node.bitcoind.rpc.user", rpcUser); nodeConfig.setProperty("node.bitcoind.rpc.password", rpcPassword); nodeConfig.setProperty("node.bitcoind.rpc.port", rpcPort); nodeConfig.setProperty("node.bitcoind.notification.block.port", rpcBlockPort); BtcdClientImpl client = new BtcdClientImpl(httpProvider, nodeConfig); daemon = new BtcdDaemonImpl(client); log.info("Setup took {} ms", System.currentTimeMillis() - startTs); this.client = client; } catch (BitcoindException | CommunicationException e) { if (e instanceof CommunicationException) log.error("Probably Bitcoin core is not running or the rpc port is not set correctly. rpcPort=" + rpcPort); log.error(e.toString()); e.printStackTrace(); log.error(e.getCause() != null ? e.getCause().toString() : "e.getCause()=null"); throw new BsqBlockchainException(e.getMessage(), e); } catch (Throwable e) { log.error(e.toString()); e.printStackTrace(); throw new BsqBlockchainException(e.toString(), e); } } void registerBlockHandler(Consumer<Block> blockHandler) { daemon.addBlockListener(new BlockListener() { @Override public void blockDetected(Block block) { if (block != null) { log.info("New block received: height={}, id={}", block.getHeight(), block.getHash()); blockHandler.accept(block); } else { log.error("We received a block with value null. That should not happen."); } } }); } int requestChainHeadHeight() throws BitcoindException, CommunicationException { return client.getBlockCount(); } Block requestBlock(int blockHeight) throws BitcoindException, CommunicationException { final String blockHash = client.getBlockHash(blockHeight); return client.getBlock(blockHash); } void requestFees(String txId, int blockHeight, Map<Integer, Long> feesByBlock) throws BsqBlockchainException { try { Transaction transaction = requestTx(txId); final BigDecimal fee = transaction.getFee(); if (fee != null) feesByBlock.put(blockHeight, Math.abs(fee.multiply(BigDecimal.valueOf(Coin.COIN.value)).longValue())); } catch (BitcoindException | CommunicationException e) { log.error("error at requestFees with txId={}, blockHeight={}", txId, blockHeight); throw new BsqBlockchainException(e.getMessage(), e); } } Tx requestTx(String txId, int blockHeight) throws BsqBlockchainException { try { RawTransaction rawTransaction = requestRawTransaction(txId); // rawTransaction.getTime() is in seconds but we keep it in ms internally final long time = rawTransaction.getTime() * 1000; final List<TxInput> txInputs = rawTransaction.getVIn() .stream() .filter(rawInput -> rawInput != null && rawInput.getVOut() != null && rawInput.getTxId() != null) .map(rawInput -> new TxInput(new TxInputVo(rawInput.getTxId(), rawInput.getVOut()))) .collect(Collectors.toList()); final List<TxOutput> txOutputs = rawTransaction.getVOut() .stream() .filter(e -> e != null && e.getN() != null && e.getValue() != null && e.getScriptPubKey() != null) .map(rawOutput -> { byte[] opReturnData = null; final com.neemre.btcdcli4j.core.domain.PubKeyScript scriptPubKey = rawOutput.getScriptPubKey(); if (scriptPubKey.getType().equals(ScriptTypes.NULL_DATA)) { String[] chunks = scriptPubKey.getAsm().split(" "); // TODO only store BSQ OP_RETURN date filtered by type byte if (chunks.length == 2 && chunks[0].equals("OP_RETURN")) { try { opReturnData = Utils.HEX.decode(chunks[1]); } catch (Throwable t) { // We get sometimes exceptions, seems BitcoinJ // cannot handle all existing OP_RETURN data, but we ignore them // anyway as our OP_RETURN data is valid in BitcoinJ log.warn(t.toString()); } } } // We dont support raw MS which are the only case where scriptPubKey.getAddresses()>1 String address = scriptPubKey.getAddresses() != null && scriptPubKey.getAddresses().size() == 1 ? scriptPubKey.getAddresses().get(0) : null; final PubKeyScript pubKeyScript = dumpBlockchainData ? new PubKeyScript(scriptPubKey) : null; final TxOutputVo txOutputVo = new TxOutputVo(rawOutput.getN(), rawOutput.getValue().movePointRight(8).longValue(), rawTransaction.getTxId(), pubKeyScript, address, opReturnData, blockHeight); return new TxOutput(txOutputVo); } ) .collect(Collectors.toList()); final TxVo txVo = new TxVo(txId, blockHeight, rawTransaction.getBlockHash(), time); return new Tx(txVo, ImmutableList.copyOf(txInputs), ImmutableList.copyOf(txOutputs)); } catch (BitcoindException | CommunicationException e) { log.error("error at requestTx with txId={}, blockHeight={}", txId, blockHeight); throw new BsqBlockchainException(e.getMessage(), e); } } RawTransaction requestRawTransaction(String txId) throws BitcoindException, CommunicationException { return (RawTransaction) client.getRawTransaction(txId, 1); } Transaction requestTx(String txId) throws BitcoindException, CommunicationException { return client.getTransaction(txId); } }
agpl-3.0
jitsni/k3po
lang/src/test/java/org/kaazing/robot/lang/parser/RobotScriptLexerTest.java
3184
/* * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com) * * This file is part of Robot. * * Robot 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 org.kaazing.robot.lang.parser; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStream; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.Token; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kaazing.robot.lang.parser.v2.RobotLexer; public class RobotScriptLexerTest { private File scriptFile; private RobotLexer lexer; @Before public void setUp() throws Exception { scriptFile = File.createTempFile("lexer", ".tmp"); } @After public void tearDown() throws Exception { if (scriptFile != null) { scriptFile.delete(); scriptFile = null; } } @Test public void shouldScanEmptyScript() throws Exception { InputStream is = new FileInputStream(scriptFile); ANTLRInputStream ais = new ANTLRInputStream(is); lexer = new RobotLexer(ais); Token token = lexer.nextToken(); Assert.assertTrue(String.format("Expected EOF token, got %d (%s)", token.getType(), token), token.getType() == RobotLexer.EOF); } @Test public void shouldSkipLineComment() throws Exception { String text = "# tcp.test\n"; FileWriter writer = new FileWriter(scriptFile); writer.write(String.format("%s", text)); writer.close(); InputStream is = new FileInputStream(scriptFile); ANTLRInputStream ais = new ANTLRInputStream(is); lexer = new RobotLexer(ais); Token token = lexer.nextToken(); Assert.assertTrue(String.format("Expected token type %d, got %d (%s)", Token.EOF, token.getType(), token.getText()), token.getType() == Token.EOF); } @Test public void shouldScanKeyword() throws Exception { String text = "close"; FileWriter writer = new FileWriter(scriptFile); writer.write(String.format("%s\n", text)); writer.close(); InputStream is = new FileInputStream(scriptFile); ANTLRInputStream ais = new ANTLRInputStream(is); lexer = new RobotLexer(ais); Token token = lexer.nextToken(); Assert.assertTrue(String.format("Expected keyword token, got type %d: %s", token.getType(), token.getText()), token.getType() == RobotLexer.CloseKeyword); } }
agpl-3.0
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/contribution/content/form/filter/GreaterThenFilter.java
1964
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 org.silverpeas.core.contribution.content.form.filter; import org.silverpeas.core.contribution.content.form.Field; import org.silverpeas.core.contribution.content.form.FieldDisplayer; /** * A GreaterThenFilter test if a given field is greater then a reference field. * @see Field * @see FieldDisplayer */ public class GreaterThenFilter implements FieldFilter { /** * An GreaterThen Filter is built upon a reference field */ public GreaterThenFilter(Field reference) { this.reference = reference; } /** * Returns true if the given field is greater then the reference. */ public boolean match(Field tested) { return reference.isNull() || tested.compareTo(reference) >= 0; } /** * The reference field against which tests will be performed. */ private final Field reference; }
agpl-3.0
zjujunge/funambol
src/com/funambol/android/AndroidConfiguration.java
9517
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2009 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.android; import android.content.ContentResolver; import android.os.Build; import android.content.SharedPreferences; import android.telephony.TelephonyManager; import android.content.Context; import com.funambol.syncml.spds.DeviceConfig; import com.funambol.client.configuration.Configuration; import com.funambol.client.customization.Customization; import com.funambol.client.source.AppSyncSourceManager; import com.funambol.util.Base64; /** * Container for the main client client configuration information. Relized using * the singleton pattern. Access this class using the getInstance() metod * invocation */ public class AndroidConfiguration extends Configuration { private static final String TAG_LOG = "AndroidConfiguration"; public static final String KEY_FUNAMBOL_PREFERENCES = "fnblPref"; private static AndroidConfiguration instance = null; private Context context; protected SharedPreferences settings; protected SharedPreferences.Editor editor; private DeviceConfig devconf; /** * Private contructor to enforce the Singleton implementation * @param context the application Context * @param customization the Customization object passed by the getInstance * call * @param appSyncSourceManager the AppSyncSourceManager object. Better to * use an AndroidAppSyncSourceManager or an extension of its super class */ private AndroidConfiguration(Context context, Customization customization, AppSyncSourceManager appSyncSourceManager) { super(customization, appSyncSourceManager); this.context = context; settings = context.getSharedPreferences(KEY_FUNAMBOL_PREFERENCES, 0); editor = settings.edit(); } /** * Static method that returns the AndroidConfiguration unique instance * @param context the application Context object * @param customization the AndoidCustomization object used in this client * @param appSyncSourceManager the AppSyncSourceManager object. Better to * use an AndroidAppSyncSourceManager or an extension of its super class * @return AndroidConfiguration an AndroidConfiguration unique instance */ public static AndroidConfiguration getInstance(Context context, Customization customization, AppSyncSourceManager appSyncSourceManager) { if (instance == null) { instance = new AndroidConfiguration(context, customization, appSyncSourceManager); } return instance; } /** * Dispose this object referencing it with the null object */ public static void dispose() { instance = null; } /** * Load the value referred to the configuration given the key * @param key the String formatted key representing the value to be loaded * @return String String formatted vlaue related to the give key */ protected String loadKey(String key) { return settings.getString(key, null); } /** * Save the loaded twin key-value using the android context package * SharedPreferences.Editor instance * @param key the key to be saved * @param value the value related to the key String formatted */ protected void saveKey(String key, String value) { editor.putString(key, value); } /** * Save the loaded twin key-value using the android context package * SharedPreferences.Editor instance * @param key the key to be saved * @param value the value related to the key byte[] formatted */ public void saveByteArrayKey(String key, byte[] value) { String b64 = new String(Base64.encode(value)); saveKey(key, b64); } /** * Load the value referred to the configuration given the key and the * default value * @param key the String formatted key representing the value to be loaded * @param defaultValue the default byte[] formatted value related to the * given key * @return byte[] String formatted vlaue related to the give key byte[] * formatted */ public byte[] loadByteArrayKey(String key, byte[] defaultValue) { String b64 = loadKey(key); if (b64 != null) { return Base64.decode(b64); } else { return defaultValue; } } /** * Commit the changes * @return true if new values were correctly written into the persistent * storage */ public boolean commit() { return editor.commit(); } /** * Get the device id related to this client. Useful when doing syncml * requests * @return String the device id that is formatted as the string "fac-" plus * the information of the deviceId field got by the TelephonyManager service */ protected String getDeviceId() { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // must have android.permission.READ_PHONE_STATE String deviceId = tm.getDeviceId(); return ((AndroidCustomization)customization).getDeviceIdPrefix() + deviceId; } /** * Get the device related configuration * @return DeviceConfig the DeviceConfig object related to this device */ public DeviceConfig getDeviceConfig() { if (devconf != null) { return devconf; } devconf = new DeviceConfig(); devconf.setMan(Build.MANUFACTURER); devconf.setMod(Build.MODEL); // See here for possible values of SDK_INT // http://developer.android.com/reference/android/os/Build.VERSION_CODES.html devconf.setSwV(Build.VERSION.CODENAME + "(" + Build.VERSION.SDK_INT + ")"); devconf.setFwV(devconf.getSwV()); devconf.setHwV(Build.FINGERPRINT); devconf.setDevID(getDeviceId()); devconf.setMaxMsgSize(64 * 1024); devconf.setLoSupport(true); devconf.setUtc(true); devconf.setNocSupport(true); devconf.setWBXML(customization.getUseWbxml()); return devconf; } /** * Get the user agent id related to this client. Useful when doing syncml * requests * @return String the user agent that is formatted as the string * "Funambol Android Sync Client " plus the version of the client */ protected String getUserAgent() { StringBuffer ua = new StringBuffer( ((AndroidCustomization)customization).getUserAgentName()); ua.append(" "); ua.append(BuildInfo.VERSION); return ua.toString(); } /** * Migrate the configuration (anything specific to the client) */ @Override protected void migrateConfig() { // From 6 to 7 means from Diablo to Gallardo, where we introduced a new // mechanism for picture sync. We need to check what the server supports // to switch to the new method. if ("6".equals(version)) { setForceServerCapsRequest(true); } // In version 11 we introduced the c2sPushEnabled property. On Android // we can use the master auto sync in order to initialize it to a proper // value. int versionNumber = Integer.parseInt(version); if(versionNumber < 11) { boolean masterAutoSync = ContentResolver.getMasterSyncAutomatically(); setC2SPushEnabled(masterAutoSync); } // Now migrate the basic configuration (this will update version) super.migrateConfig(); } }
agpl-3.0
JHierrot/openprodoc
OPDAPIRest/src/java/Sessions/CurrentSession.java
1838
/* * OpenProdoc * * See the help doc files distributed with * this work for additional information regarding copyright ownership. * Joaquin Hierro licenses this file to You under: * * License GNU Affero GPL v3 http://www.gnu.org/licenses/agpl.html * * you may not use this file except in compliance with the License. * Unless agreed to in writing, software 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. * * author: Joaquin Hierro 2019 * */ package Sessions; import java.util.Date; import prodoc.DriverGeneric; public class CurrentSession { private final String UserName; private final Date LoginTime; private Date LastUse; private final String Host; private final DriverGeneric Drv; public CurrentSession(String pUserName,Date pLoginTime, String pHost, DriverGeneric pD) { UserName=pUserName; LoginTime=pLoginTime; LastUse=pLoginTime; Host=pHost; Drv=pD; } //----------------------------------------------------------------------------------------------- /** * @return the UserName */ public String getUserName() { return UserName; } /** * @return the LoginTime */ public Date getLoginTime() { return LoginTime; } /** * @return the Host */ public String getHost() { return Host; } /** * @return the LastUse */ public Date getLastUse() { return LastUse; } /** * @param LastUse the LastUse to set */ public void setLastUse(Date LastUse) { this.LastUse = LastUse; } /** * @return the Drv */ public DriverGeneric getDrv() { return Drv; } }
agpl-3.0
oregami/oregami-server
src/main/java/org/oregami/data/LanguageDao.java
650
package org.oregami.data; import com.google.inject.Inject; import com.google.inject.Provider; import org.oregami.entities.Language; import javax.persistence.EntityManager; public class LanguageDao extends GenericDAOUUIDImpl<Language, String>{ @Inject public LanguageDao(Provider<EntityManager> emf) { super(emf); entityClass=Language.class; } public Language findByExactName(String name) { Language l = (Language) getEntityManager() .createNativeQuery("SELECT * FROM Language t where lower(t.name) = :value ", Language.class).setParameter("value", name.toLowerCase()).getSingleResult(); return l; } }
agpl-3.0
deerwalk/voltdb
tests/test_apps/txnid-selfcheck2/src/txnIdSelfCheck/procedures/DeleteOnlyLoadBase.java
1578
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package txnIdSelfCheck.procedures; import org.voltdb.*; public class DeleteOnlyLoadBase extends ValidateLoadBase { public VoltTable[] doWork(SQLStmt selectStmt, SQLStmt deleteStmt, long cid, VoltTable vt) { VoltTable[] results = doValidate(selectStmt, cid, vt); voltQueueSQL(deleteStmt, cid); return voltExecuteSQL(false); } public long run() { return 0; // never called in base procedure } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-admin/src/main/java/com/ephesoft/gxt/admin/client/view/document/testextraction/TestExtractionView.java
2148
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.admin.client.view.document.testextraction; import com.google.gwt.user.client.ui.Composite; public class TestExtractionView extends Composite { }
agpl-3.0
Kevin-Jin/argonms-server
src/argonms/game/character/inventory/ItemTools.java
7084
/* * ArgonMS MapleStory server emulator written in Java * Copyright (C) 2011-2013 GoldenKevin * * 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 argonms.game.character.inventory; import argonms.common.GlobalConstants; import argonms.common.character.PlayerStatusEffect; import argonms.common.character.Skills; import argonms.common.character.inventory.InventoryTools; import argonms.common.loading.item.ItemDataLoader; import argonms.common.loading.item.ItemEffectsData; import argonms.common.util.Scheduler; import argonms.game.character.ClientUpdateKey; import argonms.game.character.DiseaseTools; import argonms.game.character.GameCharacter; import argonms.game.character.PlayerStatusEffectValues; import argonms.game.character.StatusEffectTools; import argonms.game.loading.skill.PlayerSkillEffectsData; import argonms.game.loading.skill.SkillDataLoader; import argonms.game.net.external.GamePackets; import java.util.EnumMap; import java.util.Map; /** * * @author GoldenKevin */ public final class ItemTools { public static short getPersonalSlotMax(GameCharacter p, int itemid) { short max = ItemDataLoader.getInstance().getSlotMax(Integer.valueOf(itemid)); int skillId; byte level; if (InventoryTools.isThrowingStar(itemid) && (level = p.getSkillLevel(skillId = Skills.CLAW_MASTERY)) > 0 || InventoryTools.isBullet(itemid) && (level = p.getSkillLevel(skillId = Skills.GUN_MASTERY)) > 0) max += SkillDataLoader.getInstance().getSkill(skillId).getLevel(level).getY(); return max; } private static Map<ClientUpdateKey, Number> itemRecovers(GameCharacter p, ItemEffectsData e, int statIncreasePercent) { //might as well save ourself some bandwidth and don't send an individual //packet for each changed stat Map<ClientUpdateKey, Number> ret = new EnumMap<ClientUpdateKey, Number>(ClientUpdateKey.class); if (e.getHpRecover() != 0) { p.setLocalHp((short) Math.min(p.getHp() + e.getHpRecover() * statIncreasePercent / 100, p.getCurrentMaxHp())); ret.put(ClientUpdateKey.HP, Short.valueOf(p.getHp())); } if (e.getHpRecoverPercent() != 0) { short maxHp = p.getCurrentMaxHp(); int hpGain = Math.round(e.getHpRecoverPercent() * maxHp / 100f); p.setLocalHp((short) Math.min(p.getHp() + hpGain, maxHp)); ret.put(ClientUpdateKey.HP, Short.valueOf(p.getHp())); } if (e.getMpRecover() != 0) { p.setLocalMp((short) Math.min(p.getMp() + e.getMpRecover() * statIncreasePercent / 100, p.getCurrentMaxMp())); ret.put(ClientUpdateKey.MP, Short.valueOf(p.getMp())); } if (e.getMpRecoverPercent() != 0) { short maxMp = p.getCurrentMaxMp(); int mpGain = Math.round(e.getMpRecoverPercent() * maxMp / 100f); p.setLocalMp((short) Math.min(p.getMp() + mpGain, maxMp)); ret.put(ClientUpdateKey.MP, Short.valueOf(p.getMp())); } if (e.curesCurse()) { PlayerStatusEffectValues v = p.getEffectValue(PlayerStatusEffect.CURSE); if (v != null) DiseaseTools.cancelDebuff(p, (short) v.getSource(), v.getLevelWhenCast()); } if (e.curesDarkness()) { PlayerStatusEffectValues v = p.getEffectValue(PlayerStatusEffect.DARKNESS); if (v != null) DiseaseTools.cancelDebuff(p, (short) v.getSource(), v.getLevelWhenCast()); } if (e.curesPoison()) { PlayerStatusEffectValues v = p.getEffectValue(PlayerStatusEffect.POISON); if (v != null) DiseaseTools.cancelDebuff(p, (short) v.getSource(), v.getLevelWhenCast()); } if (e.curesSeal()) { PlayerStatusEffectValues v = p.getEffectValue(PlayerStatusEffect.SEAL); if (v != null) DiseaseTools.cancelDebuff(p, (short) v.getSource(), v.getLevelWhenCast()); } if (e.curesWeakness()) { PlayerStatusEffectValues v = p.getEffectValue(PlayerStatusEffect.WEAKNESS); if (v != null) DiseaseTools.cancelDebuff(p, (short) v.getSource(), v.getLevelWhenCast()); } if (e.getMoveTo() != 0) { if (e.getMoveTo() == GlobalConstants.NULL_MAP) p.changeMap(p.getMap().getReturnMap()); else p.changeMap(e.getMoveTo()); } return ret; } /** * Consume a item of the specified item id. * @param p the Player that will consume the item * @param itemId the identifier of the item to use */ public static void useItem(final GameCharacter p, final int itemId) { ItemEffectsData e = ItemDataLoader.getInstance().getEffect(itemId); byte alchemistLevel = p.getSkillLevel(Skills.ALCHEMIST); int statIncreasePercent; int duration; if (alchemistLevel == 0) { statIncreasePercent = 100; duration = e.getDuration(); } else { PlayerSkillEffectsData alc = SkillDataLoader.getInstance().getSkill(Skills.ALCHEMIST).getLevel(alchemistLevel); statIncreasePercent = alc.getX(); duration = e.getDuration() * alc.getY() / 100; } Map<ClientUpdateKey, Number> statChanges = itemRecovers(p, e, statIncreasePercent); if (!statChanges.isEmpty()) p.getClient().getSession().send(GamePackets.writeUpdatePlayerStats(statChanges, false)); if (duration > 0) { //buff item StatusEffectTools.applyEffectsAndShowVisuals(p, StatusEffectTools.ACTIVE_BUFF, e, (byte) -1, duration); p.addCancelEffectTask(e, Scheduler.getInstance().runAfterDelay(new Runnable() { @Override public void run() { cancelBuffItem(p, itemId); } }, duration), (byte) 0, System.currentTimeMillis() + duration); } } /** * Only recognize the stat increases of a buff item on the server. Does not * send any notifications to the client or any other players in the same map * upon the use of a item. Useful for resuming a buff item when a player has * changed channels because we have to recognize stat increases locally. * @param p the Player that consumed the item * @param itemId the identifier of the item that was used * @param remainingTime the amount of time left before the item expires */ public static void localUseBuffItem(final GameCharacter p, final int itemId, long endTime) { ItemEffectsData e = ItemDataLoader.getInstance().getEffect(itemId); StatusEffectTools.applyEffects(p, e); p.addCancelEffectTask(e, Scheduler.getInstance().runAfterDelay(new Runnable() { @Override public void run() { cancelBuffItem(p, itemId); } }, endTime - System.currentTimeMillis()), (byte) 0, endTime); } public static void cancelBuffItem(GameCharacter p, int itemId) { ItemEffectsData e = ItemDataLoader.getInstance().getEffect(itemId); StatusEffectTools.dispelEffectsAndShowVisuals(p, e); } private ItemTools() { //uninstantiable... } }
agpl-3.0
WebDataConsulting/billing
src/java/com/sapienter/jbilling/server/metafields/db/MetaFieldGroupDAS.java
2810
/* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jbilling is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with jbilling. If not, see <http://www.gnu.org/licenses/>. This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015. You may download the latest source from webdataconsulting.github.io. */ package com.sapienter.jbilling.server.metafields.db; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import com.sapienter.jbilling.server.metafields.EntityType; import com.sapienter.jbilling.server.user.db.CompanyDTO; import com.sapienter.jbilling.server.util.db.AbstractDAS; /** * @author Oleg Baskakov * @since 18-Apr-2013 */ public class MetaFieldGroupDAS extends AbstractDAS<MetaFieldGroup> { @SuppressWarnings("unchecked") public List<MetaFieldGroup> getAvailableFieldGroups(Integer entityId, EntityType entityType){ DetachedCriteria query = DetachedCriteria.forClass(MetaFieldGroup.class); CompanyDTO company = new CompanyDTO(entityId); query.add(Restrictions.eq("entity", company)); query.add(Restrictions.eq("entityType", entityType)); query.add(Restrictions.eq("class", MetaFieldGroup.class)); query.addOrder(Order.asc("displayOrder")); return (List<MetaFieldGroup>)getHibernateTemplate().findByCriteria(query); } @SuppressWarnings("unchecked") public MetaFieldGroup getGroupByName(Integer entityId, EntityType entityType, String name) { if(name==null||name.trim().length()==0){ return null; } DetachedCriteria query = DetachedCriteria.forClass(MetaFieldGroup.class); query.add(Restrictions.eq("entity.id", entityId)); query.add(Restrictions.eq("entityType", entityType)); query.add(Restrictions.eq("description", name)); query.add(Restrictions.eq("class", MetaFieldGroup.class)); List<MetaFieldGroup> fields = (List<MetaFieldGroup>)getHibernateTemplate().findByCriteria(query); return !fields.isEmpty() ? fields.get(0) : null; } }
agpl-3.0
accesstest3/AndroidFunambol
externals/jme-sdk/syncml/src/com/funambol/syncml/client/TwoPhasesFileSyncSource.java
20376
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2010 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.syncml.client; import java.util.Enumeration; import java.util.Vector; import java.util.Hashtable; import java.util.Date; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import com.funambol.syncml.spds.SourceConfig; import com.funambol.syncml.spds.SyncItem; import com.funambol.syncml.spds.SyncSource; import com.funambol.syncml.spds.SyncException; import com.funambol.syncml.spds.SyncListener; import com.funambol.syncml.spds.SyncReport; import com.funambol.syncml.spds.SyncConfig; import com.funambol.syncml.protocol.SyncFilter; import com.funambol.syncml.protocol.SyncML; import com.funambol.syncml.protocol.SyncMLStatus; import com.funambol.syncml.protocol.DevInf; import com.funambol.platform.FileAdapter; import com.funambol.platform.HttpConnectionAdapter; import com.funambol.util.ConnectionManager; import com.funambol.util.Base64; import com.funambol.util.DateUtil; import com.funambol.util.StringUtil; import com.funambol.util.XmlUtil; import com.funambol.util.Log; /** * An implementation of TrackableSyncSource, providing * the ability to sync briefcases (files). The source can handle both raw files * and OMA files (file objects). By default the source formats items according * to the OMA file object spec, but it is capable of receiving also raw files, * if their MIME type is not OMA file objects. */ public class TwoPhasesFileSyncSource extends FileSyncSource { private static final String TAG_LOG = "TwoPhasesFileSyncSource"; private static final int DEFAULT_NUM_RETRIES = 3; protected int numRetries = DEFAULT_NUM_RETRIES; protected String directory; protected Vector itemsToUpload; protected String uploadUrl; protected ProxySyncListener proxyListener; protected SyncConfig syncConfig; protected Hashtable itemsToDelete; //------------------------------------------------------------- Constructors /** * FileSyncSource constructor: initialize source config. * @param config the source configuration * @param tracker the changes tracker * @param directory the directory containing the files * @param syncConfig the SyncConfig. Note that this must be updated with the * current credentials of the user. If this is not the case, then the method * createUploader shall be redefined so that the HttpUploader is created * with an updated SyncConfig * @param uploadUrl the upload url suffix (this is added to the sync url) */ public TwoPhasesFileSyncSource(SourceConfig config, ChangesTracker tracker, String directory, SyncConfig syncConfig, String uploadUrl) { super(config, tracker, directory); this.syncConfig = syncConfig; this.uploadUrl = uploadUrl; } public void beginSync(int syncMode) throws SyncException { super.beginSync(syncMode); itemsToUpload = new Vector(); itemsToDelete = new Hashtable(); // Replace the listener if (getListener() != null) { proxyListener = new ProxySyncListener(getListener()); setListener(proxyListener); } } /** * Add an item to the local store. The item has already been received and * the content written into the output stream. The purpose of this method * is to simply apply the file object meta data properties to the file used * to store the output stream. In particular we set the proper name and * modification timestamp. * * @param item the received item * @throws SyncException if an error occurs while applying the file * attributes * */ public int addItem(SyncItem item) throws SyncException { Log.error(TAG_LOG, "addItem not implemented"); throw new SyncException(SyncException.CLIENT_ERROR, "addItem not implemented"); } /** * Update an item in the local store. The item has already been received and * the content written into the output stream. The purpose of this method * is to simply apply the file object meta data properties to the file used * to store the output stream. In particular we set the proper name and * modification timestamp. * * @param item the received item * @throws SyncException if an error occurs while applying the file * attributes * */ public int updateItem(SyncItem item) throws SyncException { Log.error(TAG_LOG, "updateItem not implemented"); throw new SyncException(SyncException.CLIENT_ERROR, "updateItem not implemented"); } public void setItemStatus(String key, int status) throws SyncException { Log.info(TAG_LOG, "setItemStatus for " + key + " status " + status); boolean deleted = itemsToDelete.get(key) != null; if (deleted) { Log.trace(TAG_LOG, "item was deleted"); super.setItemStatus(key, status); } else { if (SyncMLStatus.isSuccess(status)) { // We can upload the item in the 2nd phase itemsToUpload.addElement(key); } else { Log.error(TAG_LOG, "Server refused item: " + key); } } } public SyncItem getNextDeletedItem() throws SyncException { SyncItem nextDelete = super.getNextDeletedItem(); if (nextDelete != null) { Log.trace(TAG_LOG, "next item to delete: " + nextDelete.getKey()); itemsToDelete.put(nextDelete.getKey(), nextDelete); } return nextDelete; } public void endSync() throws SyncException { uploadItems(); super.endSync(); } protected void uploadItems() throws SyncException { // This is the beginning of the 2nd phase. Start to upload/download // items if (itemsToUpload.size() > 0) { Log.info(TAG_LOG, "Beginning upload/download phase"); if (proxyListener != null) { proxyListener.beginSecondPhase(); } HttpUploader uploader = createUploader(syncConfig, uploadUrl, getSourceUri(), proxyListener); for(int i=0;i<itemsToUpload.size();++i) { String fileName = (String)itemsToUpload.elementAt(i); boolean uploaded = false; IOException lastIoe = null; int lastHttpError = -1; HttpUploader.HttpUploadStatus uploadRes = uploader.new HttpUploadStatus(); for(int r=0;r<numRetries;++r) { FileProperties fProp = null; try { fProp = openFile(fileName); } catch (IOException ioe) { Log.error(TAG_LOG, "Cannot upload file: " + fileName, ioe); } if (fProp != null) { try { // TODO: we should allow the client to customize the // content type uploader.upload(fileName, fProp.stream, fProp.size, "application/octet-stream", uploadRes); super.setItemStatus(fileName, uploadRes.getStatus()); // If we get here, the item was transferred successfully uploaded = true; break; } catch (HttpUploaderException fue) { if (fue.cancelled()) { throw new SyncException(SyncException.CANCELLED, "Upload cancelled by the user"); } lastIoe = fue.getIOException(); if (lastIoe != null) { Log.error(TAG_LOG, "Network error uploading file", lastIoe); } else { Log.error(TAG_LOG, "Network error uploading file"); } if (fue.isHttpError()) { lastHttpError = fue.getHttpErrorCode(); } } catch (Throwable e) { Log.error(TAG_LOG, "Internal error uploading file", e); throw new SyncException(SyncException.CLIENT_ERROR, e.toString()); } finally { // Close everthing related to the input stream. // Note that the closing sequence must follow a // particular order to work properly on BlackBerry. // See here for more details: // http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800451/800563/How_To_-_Close_connections.html?nodeid=1261294&vernum=0 closeFileProperties(fProp); } } } if (!uploaded) { if (lastHttpError != -1) { // Generate a proper sync exception, depending on the last // error SyncException syncException; if (lastHttpError == HttpConnectionAdapter.HTTP_FORBIDDEN) { syncException = new SyncException(SyncException.FORBIDDEN_ERROR, "User not authorized"); } else { syncException = new SyncException(SyncException.WRITE_SERVER_REQUEST_ERROR, "Error uploading item"); } throw syncException; } else { // If we could not open the connection at all, this is a // network error throw new SyncException(SyncException.CONN_NOT_FOUND, "Cannot establish connection to server"); } // If this is not the last attempt, we may wait a bit } } } Log.info(TAG_LOG, "Upload/download phase completed"); } /** * This method opens a file and store its input stream and size into a * FileProperties object. * * @param fileName the file name * @return a descriptor of the file (stream to read content and file size) */ protected FileProperties openFile(String fileName) throws IOException { FileAdapter fa = new FileAdapter(fileName, true); FileProperties res = new FileProperties(); res.adapter = fa; // If we were able to open the connection but not the stream, we shall // make sure the connection gets closed before returning try { res.stream = fa.openInputStream(); res.size = (int)fa.getSize(); return res; } catch (IOException ioe) { closeFileProperties(res); throw ioe; } } protected void closeFileProperties(FileProperties fProp) { if (fProp != null) { if (fProp.stream != null) { try { fProp.stream.close(); } catch (IOException e) {} fProp.stream = null; } if (fProp.adapter != null) { try { fProp.adapter.close(); } catch (IOException e) {} fProp.adapter = null; } } } protected HttpUploader createUploader(SyncConfig config, String uploadUrl, String sourceUri, SyncListener listener) { HttpUploader uploader = new HttpUploader(config, uploadUrl, sourceUri, listener); return uploader; } protected class FileProperties { public InputStream stream = null; public int size = 0; public FileAdapter adapter = null; public FileProperties() { } } protected class ProxySyncListener implements SyncListener { private SyncListener lis; private boolean secondPhase = false; public ProxySyncListener(SyncListener lis) { this.lis = lis; } public void beginSecondPhase() { secondPhase = true; } public void startSession() { lis.startSession(); } public void endSession(SyncReport report) { // Restore the original listener because we are done TwoPhasesFileSyncSource.this.setListener(lis); // Propagate the event lis.endSession(report); } public void startConnecting() { lis.startConnecting(); } public void endConnecting(int action) { lis.endConnecting(action); } public void syncStarted(int alertCode) { lis.syncStarted(alertCode); } public void endSyncing() { //lis.endSyncing(); } public void startMapping() { //lis.startMapping(); } public void endMapping() { //lis.endMapping(); } public void startReceiving(int number) { lis.startReceiving(number); } public void endReceiving() { lis.endReceiving(); } public void itemReceived(Object item) { lis.itemReceived(item); } public void itemDeleted(Object item) { lis.itemDeleted(item); } public void itemUpdated(Object item, Object update) { lis.itemUpdated(item, update); } public void itemUpdated(Object item) { lis.itemUpdated(item); } public void dataReceived(String date, int size) { lis.dataReceived(date, size); } public void startSending(int numNewItems, int numUpdItems, int numDelItems) { lis.startSending(numNewItems, numUpdItems, numDelItems); } public void itemAddSendingStarted(String key, String parent, int size) { // During the SyncML phase, we filter it out if (secondPhase) { lis.itemAddSendingStarted(key, parent, size); } } public void itemAddSendingEnded(String key, String parent, int size) { if (secondPhase) { lis.itemAddSendingEnded(key, parent, size); } } public void itemAddChunkSent(String key, String parent, int size) { if (secondPhase) { lis.itemAddChunkSent(key, parent, size); } } public void itemReplaceSendingStarted(String key, String parent, int size) { if (secondPhase) { lis.itemReplaceSendingStarted(key, parent, size); } } public void itemReplaceSendingEnded(String key, String parent, int size) { if (secondPhase) { lis.itemReplaceSendingEnded(key, parent, size); } } public void itemReplaceChunkSent(String key, String parent, int size) { if (secondPhase) { lis.itemReplaceChunkSent(key, parent, size); } } public void itemDeleteSent(Object item) { lis.itemDeleteSent(item); } public void endSending() { lis.endSending(); } public boolean startSyncing(int alertCode, DevInf devInf) { return lis.startSyncing(alertCode, devInf); } } /** * TODO: is this still needed? * This is still kind of strange, we don't really need to get the item * content any longer but we just need to create a proper item from which * the content can be read */ protected SyncItem getItemContent(final SyncItem item) throws SyncException { Log.trace(TAG_LOG, "getItemContent for: " + item.getKey()); // We send the item with the type of the SS SourceConfig config = getConfig(); String type = config.getType(); String fileName = item.getKey(); try { EmptyFileSyncItem fsi = new EmptyFileSyncItem(fileName, item.getKey(), type, item.getState(), item.getParent()); return fsi; } catch (IOException ioe) { throw new SyncException(SyncException.CLIENT_ERROR, "Cannot create EmptyFileSyncItem: " + ioe.toString()); } } protected class EmptyFileSyncItem extends SyncItem { private String fileName; private OutputStream os = null; private String content; public EmptyFileSyncItem(String fileName, String key) throws IOException { this(fileName, key, null, SyncItem.STATE_NEW, null); } public EmptyFileSyncItem(String fileName, String key, String type, char state, String parent) throws IOException { super(key, type, state, parent); this.fileName = fileName; FileAdapter file = new FileAdapter(fileName); // Initialize the prologue FileObject fo = new FileObject(); fo.setName(file.getName()); fo.setModified(new Date(file.lastModified())); fo.setSize((int)file.getSize()); // Print all the item without body content = fo.formatPrologue(false); content = content + fo.formatEpilogue(false); // Set the size setObjectSize(content.length()); // Release the file object file.close(); } /** * Creates a new input stream to read from. If the source is configured * to handle File Data Object, then the stream returns the XML * description of the file. @see FileObjectInputStream for more details. */ public InputStream getInputStream() throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes()); return is; } public String getFileName() { return fileName; } // If we do not reimplement the getContent, it will return a null // content, but this is not used in the ss, so there's no need to // redefine it } }
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_core_entity/src/main/java/com/x/processplatform/core/entity/element/Activity.java
7414
package com.x.processplatform.core.entity.element; import java.util.List; import com.google.gson.JsonElement; import com.x.base.core.entity.SliceJpaObject; public abstract class Activity extends SliceJpaObject { private static final long serialVersionUID = 4981905102396583697L; public abstract String getName(); public abstract String getDescription(); public abstract String getProcess(); public abstract String getAlias(); public abstract String getPosition(); public abstract void setName(String str); public abstract void setDescription(String str); public abstract void setProcess(String str); public abstract void setAlias(String str); public abstract void setPosition(String str); public abstract String getForm(); public abstract void setForm(String str); public abstract List<String> getReadIdentityList(); public abstract void setReadIdentityList(List<String> readIdentityList); public abstract List<String> getReadUnitList(); public abstract void setReadUnitList(List<String> readUnitList); public abstract List<String> getReadGroupList(); public abstract void setReadGroupList(List<String> readGroupList); public abstract String getReadScript(); public abstract void setReadScript(String readScript); public abstract String getReadScriptText(); public abstract void setReadScriptText(String readScriptText); public abstract String getReadDuty(); public abstract List<String> getReadDataPathList(); public abstract void setReadDataPathList(List<String> readDataPathList); public abstract String getReviewDuty(); public abstract void setReviewDuty(String reviewDuty); public abstract List<String> getReviewDataPathList(); public abstract void setReviewDataPathList(List<String> reviewDataPathList); public abstract List<String> getReviewIdentityList(); public abstract void setReviewIdentityList(List<String> reviewIdentityList); public abstract List<String> getReviewUnitList(); public abstract void setReviewUnitList(List<String> reviewUnitList); public abstract List<String> getReviewGroupList(); public abstract void setReviewGroupList(List<String> reviewGroupList); public abstract String getReviewScript(); public abstract void setReviewScript(String reviewScript); public abstract String getReviewScriptText(); public abstract void setReviewScriptText(String reviewScriptText); public abstract String getDisplayLogScript(); public abstract void setDisplayLogScript(String displayLogScript); public abstract String getDisplayLogScriptText(); public abstract void setDisplayLogScriptText(String displayLogScriptText); public abstract String getGroup(); public abstract void setGroup(String group); public abstract String getOpinionGroup(); public abstract List<String> getRouteList(); public abstract void setOpinionGroup(String opinionGroup); // 是否允许调度 public abstract Boolean getAllowReroute(); public abstract void setAllowReroute(Boolean allowReroute); // 是否允许调度到此节点 public abstract Boolean getAllowRerouteTo(); public abstract void setAllowRerouteTo(Boolean allowReroute); // 是否允许挂起 public abstract Boolean getAllowSuspend(); public abstract void setAllowSuspend(Boolean allowSuspend); public abstract JsonElement getCustomData(); public abstract void setCustomData(JsonElement customData); public ActivityType getActivityType() throws Exception { if (this instanceof Agent) { return ActivityType.agent; } else if (this instanceof Begin) { return ActivityType.begin; } else if (this instanceof Cancel) { return ActivityType.cancel; } else if (this instanceof Choice) { return ActivityType.choice; } else if (this instanceof Delay) { return ActivityType.delay; } else if (this instanceof Embed) { return ActivityType.embed; } else if (this instanceof End) { return ActivityType.end; } else if (this instanceof Invoke) { return ActivityType.invoke; } else if (this instanceof Manual) { return ActivityType.manual; } else if (this instanceof Merge) { return ActivityType.merge; } else if (this instanceof Parallel) { return ActivityType.parallel; } else if (this instanceof Service) { return ActivityType.service; } else if (this instanceof Split) { return ActivityType.split; } throw new Exception("invalid actvityType."); } public static final String group_FIELDNAME = "group"; public static final String opinionGroup_FIELDNAME = "opinionGroup"; public static final String name_FIELDNAME = "name"; public static final String alias_FIELDNAME = "alias"; public static final String description_FIELDNAME = "description"; public static final String process_FIELDNAME = "process"; public static final String position_FIELDNAME = "position"; public static final String extension_FIELDNAME = "extension"; public static final String form_FIELDNAME = "form"; public static final String readIdentityList_FIELDNAME = "readIdentityList"; public static final String readUnitList_FIELDNAME = "readUnitList"; public static final String readGroupList_FIELDNAME = "readGroupList"; public static final String readScript_FIELDNAME = "readScript"; public static final String readScriptText_FIELDNAME = "readScriptText"; public static final String readDuty_FIELDNAME = "readDuty"; public static final String readDataPathList_FIELDNAME = "readDataPathList"; public static final String reviewIdentityList_FIELDNAME = "reviewIdentityList"; public static final String reviewUnitList_FIELDNAME = "reviewUnitList"; public static final String reviewGroupList_FIELDNAME = "reviewGroupList"; public static final String reviewScript_FIELDNAME = "reviewScript"; public static final String reviewScriptText_FIELDNAME = "reviewScriptText"; public static final String reviewDuty_FIELDNAME = "reviewDuty"; public static final String reviewDataPathList_FIELDNAME = "reviewDataPathList"; public static final String beforeArriveScript_FIELDNAME = "beforeArriveScript"; public static final String beforeArriveScriptText_FIELDNAME = "beforeArriveScriptText"; public static final String afterArriveScript_FIELDNAME = "afterArriveScript"; public static final String afterArriveScriptText_FIELDNAME = "afterArriveScriptText"; public static final String beforeExecuteScript_FIELDNAME = "beforeExecuteScript"; public static final String beforeExecuteScriptText_FIELDNAME = "beforeExecuteScriptText"; public static final String afterExecuteScript_FIELDNAME = "afterExecuteScript"; public static final String afterExecuteScriptText_FIELDNAME = "afterExecuteScriptText"; public static final String beforeInquireScript_FIELDNAME = "beforeInquireScript"; public static final String beforeInquireScriptText_FIELDNAME = "beforeInquireScriptText"; public static final String afterInquireScript_FIELDNAME = "afterInquireScript"; public static final String afterInquireScriptText_FIELDNAME = "afterInquireScriptText"; public static final String allowReroute_FIELDNAME = "allowReroute"; public static final String allowRerouteTo_FIELDNAME = "allowRerouteTo"; public static final String allowSuspend_FIELDNAME = "allowSuspend"; public static final String displayLogScript_FIELDNAME = "displayLogScript"; public static final String displayLogScriptText_FIELDNAME = "displayLogScriptText"; public static final String resetRangeScriptText_FIELDNAME = "resetRangeScriptText"; }
agpl-3.0
simonzhangsm/voltdb
tests/test_apps/genqa/src/genqa2/procedures/JiggleExportDoneTable.java
1581
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package genqa2.procedures; import org.voltdb.SQLStmt; import org.voltdb.VoltProcedure; public class JiggleExportDoneTable extends VoltProcedure { public final SQLStmt export = new SQLStmt("INSERT INTO export_done_table (txnid) VALUES (?)"); public long run(long txid) { voltQueueSQL(export, txid); // Execute last statement batch voltExecuteSQL(true); // Retun to caller return txid; } }
agpl-3.0
o2oa/o2oa
o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/invoke/ActionUpdate.java
1646
package com.x.program.center.jaxrs.invoke; import com.x.base.core.project.exception.ExceptionAccessDenied; import com.x.program.center.Business; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.project.exception.ExceptionWhen; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WoId; import com.x.base.core.project.tools.DefaultCharset; import com.x.program.center.core.entity.Invoke; class ActionUpdate extends BaseAction { ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, byte[] bytes, FormDataContentDisposition disposition) throws Exception { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); /* 判断当前用户是否有权限访问 */ if(!business.serviceControlAble(effectivePerson)) { throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName()); } ActionResult<Wo> result = new ActionResult<>(); Wo wo = new Wo(); Invoke invoke = emc.flag(flag, Invoke.class); if (null == invoke) { throw new ExceptionInvokeNotExist(flag); } String text = new String(bytes, DefaultCharset.name); emc.beginTransaction(Invoke.class); invoke.setText(text); // this.addComment(invoke); emc.commit(); wo.setId(invoke.getId()); result.setData(wo); return result; } } public static class Wo extends WoId { } }
agpl-3.0
mtackes/SecureNote
src/edu/mtackes/securenote/persistence/NoteDAO.java
4448
package edu.mtackes.securenote.persistence; import com.sun.istack.Nullable; import edu.mtackes.securenote.model.entity.CryptoNote; import java.util.*; import edu.mtackes.securenote.model.entity.User; import org.hibernate.*; /** * Created by mtackes on 12/15/15. */ public class NoteDAO { public Integer createNote(CryptoNote note) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; Integer noteId = null; try { tx = session.beginTransaction(); noteId = (Integer)session.save(note); tx.commit(); } catch (HibernateException hex) { if (tx != null) { tx.rollback(); } hex.printStackTrace(); } finally { session.close(); } return noteId; } @Nullable public CryptoNote getNoteByUuid(UUID uuid) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; CryptoNote result = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from edu.mtackes.securenote.model.entity.CryptoNote Note where Note.uuid = :uuid"); query.setParameter("uuid", uuid); List<CryptoNote> retrievedNotes = query.list(); result = retrievedNotes.isEmpty() ? null : retrievedNotes.get(0); } catch (HibernateException hex) { hex.printStackTrace(); } finally { session.close(); } return result; } public List<CryptoNote> getAllNotes() { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; List<CryptoNote> notes = new ArrayList<CryptoNote>(); try { tx = session.beginTransaction(); notes = session.createQuery("from notes").list(); } catch (HibernateException hex) { hex.printStackTrace(); } finally { session.close(); } return notes; } public List<CryptoNote> getNotesForUserId(int userId) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; List<CryptoNote> notes = new ArrayList<CryptoNote>(); try { tx = session.beginTransaction(); Query query = session.createQuery("from notes where user_id = :userId"); query.setInteger("userId", userId); notes = query.list(); } catch (HibernateException hex) { hex.printStackTrace(); } finally { session.close(); } return notes; } public void updateNote(CryptoNote note) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.update(note); tx.commit(); } catch (HibernateException hex) { hex.printStackTrace(); } finally { session.close(); } } public void deleteNote(int noteId) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // TODO: Does this work? From the docs, it looks like it should ... // ... or a transient instance with an identifier associated with existing persistent state. CryptoNote note = new CryptoNote(); note.setId(noteId); session.delete(note); tx.commit(); } catch (HibernateException hex) { if (tx != null) { tx.rollback(); } hex.printStackTrace(); } finally { session.close(); } } public void deleteNote(CryptoNote note) { Session session = SessionFactoryProvider.getSessionFactory().openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.delete(note); tx.commit(); } catch (HibernateException hex) { if (tx != null) { tx.rollback(); } hex.printStackTrace(); } finally { session.close(); } } }
agpl-3.0
vogler75/oa4j
Java/src/main/java/at/rocworks/oa4j/base/IAnswer.java
891
/* OA4J - WinCC Open Architecture for Java Copyright (C) 2017 Andreas Vogler 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 <https://www.gnu.org/licenses/>. */ package at.rocworks.oa4j.base; /** * * @author vogler */ public interface IAnswer { void answer(JDpMsgAnswer answer); }
agpl-3.0
adamabeshouse/cbioportal
persistence/persistence-mybatis/src/main/java/org/cbioportal/persistence/mybatis/GeneticProfileMyBatisRepository.java
2483
package org.cbioportal.persistence.mybatis; import org.cbioportal.model.GeneticProfile; import org.cbioportal.model.meta.BaseMeta; import org.cbioportal.persistence.GeneticProfileRepository; import org.cbioportal.persistence.PersistenceConstants; import org.cbioportal.persistence.mybatis.util.OffsetCalculator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class GeneticProfileMyBatisRepository implements GeneticProfileRepository { @Autowired private GeneticProfileMapper geneticProfileMapper; @Autowired private OffsetCalculator offsetCalculator; @Override public List<GeneticProfile> getAllGeneticProfiles(String projection, Integer pageSize, Integer pageNumber, String sortBy, String direction) { return geneticProfileMapper.getAllGeneticProfiles(null, projection, pageSize, offsetCalculator.calculate(pageSize, pageNumber), sortBy, direction); } @Override public BaseMeta getMetaGeneticProfiles() { return geneticProfileMapper.getMetaGeneticProfiles(null); } @Override public GeneticProfile getGeneticProfile(String geneticProfileId) { return geneticProfileMapper.getGeneticProfile(geneticProfileId, PersistenceConstants.DETAILED_PROJECTION); } @Override public List<GeneticProfile> getAllGeneticProfilesInStudy(String studyId, String projection, Integer pageSize, Integer pageNumber, String sortBy, String direction) { return geneticProfileMapper.getAllGeneticProfiles(studyId, projection, pageSize, offsetCalculator.calculate(pageSize, pageNumber), sortBy, direction); } @Override public BaseMeta getMetaGeneticProfilesInStudy(String studyId) { return geneticProfileMapper.getMetaGeneticProfiles(studyId); } @Override public List<GeneticProfile> getGeneticProfilesReferredBy(String referringGeneticProfileId) { return geneticProfileMapper.getGeneticProfilesReferredBy(referringGeneticProfileId, PersistenceConstants.DETAILED_PROJECTION); } @Override public List<GeneticProfile> getGeneticProfilesReferringTo(String referredGeneticProfileId) { return geneticProfileMapper.getGeneticProfilesReferringTo(referredGeneticProfileId, PersistenceConstants.DETAILED_PROJECTION); } }
agpl-3.0
lysid/scales
scales-query/src/main/java/studio/lysid/scales/query/scale/QueryScaleServiceImpl.java
1957
/* * Copyright (C) 2017 Frederic Monjo * * 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 studio.lysid.scales.query.scale; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.mongo.MongoClient; public class QueryScaleServiceImpl implements QueryScaleService { private static final Logger logger = LoggerFactory.getLogger(QueryScaleServiceImpl.class); private static final String ScaleCollection = "scale"; private final MongoClient db; public QueryScaleServiceImpl(MongoClient db) { super(); this.db = db; } @Override public void findScaleById(int id, Handler<AsyncResult<JsonObject>> handler) { logger.debug("findScaleById called with parameters: id={0}", id); db.findOne(ScaleCollection, new JsonObject().put("_id", Integer.toString(id)), new JsonObject(), res -> { if (res.succeeded() && res.result() != null) { handler.handle(Future.succeededFuture(res.result())); } else { handler.handle(Future.failedFuture("Scale #" + id + " does not exist")); } }); } }
agpl-3.0
diqube/diqube
diqube-util/src/main/java/org/diqube/util/TopologicalSort.java
3888
/** * diqube: Distributed Query Base. * * Copyright (C) 2015 Bastian Gloeckle * * This file is part of diqube. * * diqube 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 org.diqube.util; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; /** * Executes a simple topological sort based on a few helper functions. * * @author Bastian Gloeckle */ public class TopologicalSort<T> { private Function<T, List<T>> allSuccessorsFunction; private Function<T, Long> idFunction; private BiConsumer<T, Integer> newIndexConsumer; /** * * @param allSuccessorsFunction * Find and return all successors to a specific object. * @param idFunction * Return a unique ID for a specific object. * @param newIndexConsumer * Will be called when the final position for one of the objects was found. */ public TopologicalSort(Function<T, List<T>> allSuccessorsFunction, Function<T, Long> idFunction, BiConsumer<T, Integer> newIndexConsumer) { this.allSuccessorsFunction = allSuccessorsFunction; this.idFunction = idFunction; this.newIndexConsumer = newIndexConsumer; } /** * Topologically sort the given values. * * @return A topologically sorted list of the objects * @throws IllegalArgumentException * If the values cannot be sorted topologically. */ public List<T> sort(List<T> values) throws IllegalArgumentException { List<T> res = new ArrayList<>(values.size()); Map<Long, T> idToValueMap = new HashMap<>(); Map<Long, List<Long>> successors = new HashMap<>(); for (T value : values) { long id = idFunction.apply(value); idToValueMap.put(id, value); successors.put(id, allSuccessorsFunction.apply(value).stream().map(idFunction).collect(Collectors.toList())); } Map<Long, Set<Long>> predecessors = new HashMap<>(); for (Long id : successors.keySet()) predecessors.put(id, new HashSet<>()); for (Entry<Long, List<Long>> successorEntry : successors.entrySet()) { for (Long successor : successorEntry.getValue()) predecessors.get(successor).add(successorEntry.getKey()); } Deque<Long> emptyPredecessors = new LinkedList<Long>(predecessors.entrySet().stream() .filter(entry -> entry.getValue().isEmpty()).map(entry -> entry.getKey()).collect(Collectors.toList())); while (!emptyPredecessors.isEmpty()) { Long id = emptyPredecessors.poll(); for (Long successorId : successors.get(id)) { predecessors.get(successorId).remove(id); if (predecessors.get(successorId).isEmpty()) emptyPredecessors.add(successorId); } predecessors.remove(id); if (newIndexConsumer != null) newIndexConsumer.accept(idToValueMap.get(id), res.size()); res.add(idToValueMap.get(id)); } if (!predecessors.isEmpty()) throw new IllegalArgumentException("Cyclic dependencies, cannot sort topologically."); return res; } }
agpl-3.0
BrunoEberhard/open-ech
src/main/model/ch/ech/ech0129/TypeOfPermit.java
340
package ch.ech.ech0129; import javax.annotation.Generated; @Generated(value="org.minimalj.metamodel.generator.ClassGenerator") public enum TypeOfPermit { _5000, _5001, _5002, _5003, _5004, _5005, _5006, _5007, _5008, _5009, _5011, _5012, _5015, _5021, _5022, _5023, _5031, _5041, _5043, _5044, _5051, _5061, _5062, _5063, _5064, _5071; }
agpl-3.0
heniancheng/FRODO
src/frodo2/algorithms/maxsum/MaxSum.java
24965
/* FRODO: a FRamework for Open/Distributed Optimization Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek FRODO 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. FRODO 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/>. How to contact the authors: <http://frodo2.sourceforge.net/> */ package frodo2.algorithms.maxsum; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.jdom2.Element; import frodo2.algorithms.AgentInterface; import frodo2.algorithms.StatsReporterWithConvergence; import frodo2.algorithms.varOrdering.factorgraph.FactorGraphGen; import frodo2.algorithms.varOrdering.factorgraph.FunctionNode; import frodo2.algorithms.varOrdering.factorgraph.VariableNode; import frodo2.communication.Message; import frodo2.communication.MessageWith2Payloads; import frodo2.communication.Queue; import frodo2.solutionSpaces.Addable; import frodo2.solutionSpaces.AddableDelayed; import frodo2.solutionSpaces.DCOPProblemInterface; import frodo2.solutionSpaces.UtilitySolutionSpace; import frodo2.solutionSpaces.hypercube.Hypercube; /** The Max-Sum Algorithm * * Max-Sum Implementation mostly based on "Decentralised Coordination of Low-Power Embedded * Devices Using the Max-Sum Algorithm" by * A. Farinelli, A. Rogers, A. Petcu, N. R. Jennings * * Each function node is simulated by the agent owning the first variable in its scope. * * @author Thomas Leaute, remotely based on a preliminary contribution by Sokratis Vavilis and George Vouros (AI-Lab of the University of the Aegean) * * @param <V> the type used for variable values * @param <U> the type used for utility values in stats gatherer mode */ public class MaxSum < V extends Addable<V>, U extends Addable<U> > implements StatsReporterWithConvergence<V> { /** The type of the messages received from function nodes of the graph */ public static final String FUNCTION_MSG_TYPE = FunctionMsg.FUNCTION_MSG_TYPE; /** The type of the messages received from variable nodes of the graph */ public static final String VARIABLE_MSG_TYPE = VariableMsg.VARIABLE_MSG_TYPE; /** The type of the messages containing the assignment history */ private static final String CONV_STATS_MSG_TYPE = "MaxSumConvStatsMsg"; /** The type of the messages containing the final assignment to a variable */ private static final String SOLUTION_MSG_TYPE = "MaxSumSolMsg"; /** Information about an internal variable */ private class VarInfo extends VariableNode<V, U> { /** The last marginal utility received from each function node */ private HashMap< String, UtilitySolutionSpace<V, U> > lastMsgsIn = new HashMap< String, UtilitySolutionSpace<V, U> > (); /** The remaining number of iterations for this node */ private int nbrIter; /** The current optimal value for this variable */ private V optVal; /** Constructor * @param varName The name of this variable * @param agent The agent controlling this variable node * @param functions The list of neighboring function nodes */ private VarInfo (String varName, String agent, ArrayList< FunctionNode<V, U> > functions) { super(varName, agent, problem.getDomain(varName)); if (agent.equals(problem.getAgent())) { // I control this variable node this.nbrIter = maxNbrIter; // Pick the first possible value for the variable this.optVal = this.dom[0]; // Initialize the last messages received from and sent to the neighboring function nodes for (FunctionNode<V, U> funct : functions) { this.addFunction(funct); this.lastMsgsIn.put(funct.getName(), zeroSpace(this.varName, this.dom)); } } } } /** Returns a single-variable space full of zeros * @param varName the name of the variable * @param dom the variable domain * @return the space */ @SuppressWarnings("unchecked") private Hypercube<V, U> zeroSpace (String varName, V[] dom) { U[] utils = (U[]) Array.newInstance(this.zero.getClass(), dom.length); Arrays.fill(utils, this.zero); V[][] doms = (V[][]) Array.newInstance(dom.getClass(), 1); doms[0] = dom; return new Hypercube<V, U> (new String[] { varName }, doms, utils, infeasibleUtil); } /** Returns a scaled random space * @param varName the name of the (only) variable * @param dom the domain of the variable * @return a scaled random space over the variable */ @SuppressWarnings("unchecked") private Hypercube<V, U> scaledRandSpace (String varName, V[] dom) { // Randomly fill in the utilities final int domSize = dom.length; U[] utils = (U[]) Array.newInstance(this.zero.getClass(), domSize); AddableDelayed<U> sum = this.zero.addDelayed(); Random rand = new Random (); for (int i = 0; i < domSize; i++) sum.addDelayed(utils[i] = this.zero.fromString(Integer.toString(rand.nextInt(100)))); // Rescale the random utilities so that they sum up to 0 U scalar = sum.resolve().divide(this.zero.fromString(Integer.toString(domSize))); for (int i = 0; i < domSize; i++) utils[i] = utils[i].subtract(scalar); V[][] doms = (V[][]) Array.newInstance(dom.getClass(), 1); doms[0] = dom; return new Hypercube<V, U> (new String[] { varName }, doms, utils, infeasibleUtil); } /** For each internal variable, its VarInfo */ private HashMap<String, VarInfo> varInfos; /** Information about each neighboring function node */ private class FunctionInfo extends FunctionNode<V, U> { /** The last marginal utility received from each variable node */ private HashMap< String, UtilitySolutionSpace<V, U> > lastMsgsIn = new HashMap< String, UtilitySolutionSpace<V, U> > (); /** The remaining number of iterations for this node */ private int nbrIter; /** Constructor * @param name The name of the constraint * @param space The constraint * @param agent The agent responsible for simulating this function node */ private FunctionInfo (String name, UtilitySolutionSpace<V, U> space, String agent) { super(name, space, agent); this.nbrIter = maxNbrIter; if (space != null) for (String var : space.getVariables()) this.addVariable(var, problem.getDomain(var)); } /** Adds a variable to this FunctionInfo * @param varName the variable name * @param dom the variable domain */ private void addVariable (String varName, V[] dom) { // Initialize the last messages received from and sent to this variable node this.lastMsgsIn.put(varName, zeroSpace(varName, dom)); } } /** For each constraint in the agent's subproblem, its FunctionInfo */ private HashMap<String, FunctionInfo> functionInfos; /** The algorithm will terminate when ALL function nodes have gone through that many iterations */ private final int maxNbrIter; /** This module's queue */ private Queue queue; /** The problem */ private DCOPProblemInterface<V, U> problem; /** Whether the stats gatherer should display the solution found */ private boolean silent = false; /** Whether the module has already started the algorithm */ private boolean started = false; /** The 0 cost */ private U zero; /** The solution */ private HashMap<String, V> solution; /** The optimal cost */ private U optCost; /** Whether to maximize utility or minimize cost */ private final boolean maximize; /** The infeasible utility */ private final U infeasibleUtil; /** Whether to initialize the algorithm with random messages, or with messages full of zeros */ private final boolean randomInit; /** Whether the listener should record the assignment history or not */ private final boolean convergence; /** For each variable its assignment history */ private final HashMap< String, ArrayList< CurrentAssignment<V> > > assignmentHistoriesMap; /** For each recipient (variable or function), the last message received and waiting to be processed */ private HashMap<String, Message> pendingMsgs = new HashMap<String, Message> (); /** Constructor * @param problem this agent's problem * @param parameters the parameters for this module */ public MaxSum (DCOPProblemInterface<V, U> problem, Element parameters) { this.problem = (DCOPProblemInterface<V, U>) problem; this.maximize = problem.maximize(); this.infeasibleUtil = (this.maximize ? problem.getMinInfUtility() : problem.getPlusInfUtility()); this.zero = this.problem.getZeroUtility(); String convergence = parameters.getAttributeValue("convergence"); if(convergence != null) this.convergence = Boolean.parseBoolean(convergence); else this.convergence = false; this.assignmentHistoriesMap = (this.convergence ? new HashMap< String, ArrayList< CurrentAssignment<V> > >() : null); String maxNbrIter = parameters.getAttributeValue("maxNbrIter"); if(maxNbrIter == null) this.maxNbrIter = 200; else this.maxNbrIter = Integer.parseInt(maxNbrIter); String randomInitStr = parameters.getAttributeValue("randomInit"); if (randomInitStr != null) this.randomInit = Boolean.parseBoolean(randomInitStr); else this.randomInit = true; } /** The constructor called in "statistics gatherer" mode * @param parameters the description of what statistics should be reported (currently unused) * @param problem the overall problem */ public MaxSum (Element parameters, DCOPProblemInterface<V, U> problem) { this.problem = problem; this.solution = new HashMap<String, V> (); this.optCost = problem.getZeroUtility(); this.started = true; this.maximize = this.problem.maximize(); this.infeasibleUtil = (this.maximize ? problem.getMinInfUtility() : problem.getPlusInfUtility()); this.maxNbrIter = 0; this.randomInit = false; this.convergence = false; this.assignmentHistoriesMap = new HashMap< String, ArrayList< CurrentAssignment<V> > > (); } /** Parses the problem */ private void start () { this.started = true; // Start the algorithm by having each of my variable nodes send a fake message to each of its neighboring function nodes for (VarInfo varInfo : this.varInfos.values()) { // Skip the variable nodes I do not control if (varInfo.optVal == null) continue; // Check if this variable is unconstrained if (varInfo.getFunctions().isEmpty()) { this.queue.sendMessage(AgentInterface.STATS_MONITOR, new MessageWith2Payloads<String, V> (SOLUTION_MSG_TYPE, varInfo.getVarName(), varInfo.optVal)); if(convergence) { ArrayList< CurrentAssignment<V> > history = this.assignmentHistoriesMap.get(varInfo.getVarName()); history.add(new CurrentAssignment<V>(queue.getCurrentTime(), 0, varInfo.optVal)); queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsReporterWithConvergence.ConvStatMessage<V>(CONV_STATS_MSG_TYPE, varInfo.getVarName(), history)); } varInfo.nbrIter = 0; this.checkForTermination(); } else { // constrained variable for (FunctionNode<V, U> function : varInfo.getFunctions()) { UtilitySolutionSpace<V, U> space = (this.randomInit ? this.scaledRandSpace(varInfo.getVarName(), varInfo.getDom()) : zeroSpace (varInfo.getVarName(), varInfo.getDom())); space.setName("start"); this.queue.sendMessage(function.getAgent(), new VariableMsg<V, U> (function.getName(), space)); } } } // Process pending messages for (Message msg : this.pendingMsgs.values()) this.notifyIn(msg); this.pendingMsgs.clear(); } /** @see StatsReporterWithConvergence#reset() */ public void reset() { /// @todo To be implemented } /** @see StatsReporterWithConvergence#getMsgTypes() */ public Collection<String> getMsgTypes() { ArrayList<String> types = new ArrayList<String> (4); types.add(FactorGraphGen.OUTPUT_MSG_TYPE); types.add(FUNCTION_MSG_TYPE); types.add(VARIABLE_MSG_TYPE); types.add(AgentInterface.ALL_AGENTS_IDLE); return types; } /** @see StatsReporterWithConvergence#getStatsFromQueue(Queue) */ public void getStatsFromQueue(Queue queue) { queue.addIncomingMessagePolicy(SOLUTION_MSG_TYPE, this); queue.addIncomingMessagePolicy(CONV_STATS_MSG_TYPE, this); } /** @see StatsReporterWithConvergence#setSilent(boolean) */ public void setSilent(boolean silent) { this.silent = silent; } /** @see StatsReporterWithConvergence#setQueue(Queue) */ public void setQueue(Queue queue) { this.queue = queue; } /** @see StatsReporterWithConvergence#notifyIn(Message) */ public void notifyIn(Message msg) { String msgType = msg.getType(); if (msgType.equals(CONV_STATS_MSG_TYPE)) { // in stats gatherer mode, the message sent by a variable containing the assignment history @SuppressWarnings("unchecked") StatsReporterWithConvergence.ConvStatMessage<V> msgCast = (StatsReporterWithConvergence.ConvStatMessage<V>)msg; assignmentHistoriesMap.put(msgCast.getVar(), msgCast.getAssignmentHistory()); return; } else if (msgType.equals(SOLUTION_MSG_TYPE)) { // in stats gatherer mode, the final assignment to a variable @SuppressWarnings("unchecked") MessageWith2Payloads<String, V> msgCast = (MessageWith2Payloads<String, V>) msg; String var = msgCast.getPayload1(); V val = msgCast.getPayload2(); this.solution.put(var, val); if (! this.silent) System.out.println("var `" + var + "' = " + val); if (this.solution.size() == this.problem.getNbrVars()) { this.optCost = this.problem.getUtility(this.solution, true).getUtility(0); if (! this.silent) System.out.println((this.maximize ? "Utility" : "Cost") + " of solution found: " + this.optCost); } return; } // System.out.println(this.problem.getAgent() + " got " + msg); if (msgType.equals(FactorGraphGen.OUTPUT_MSG_TYPE)) { // the factor graph @SuppressWarnings("unchecked") MessageWith2Payloads < HashMap< String, VariableNode<V, U> >, HashMap< String, FunctionNode<V, U> > > msgCast = (MessageWith2Payloads < HashMap< String, VariableNode<V, U> >, HashMap< String, FunctionNode<V, U> > >) msg; // Record the variable nodes this.varInfos = new HashMap<String, VarInfo> (); for (Map.Entry< String, VariableNode<V, U> > entry : msgCast.getPayload1().entrySet()) { VariableNode<V, U> node = entry.getValue(); this.varInfos.put(entry.getKey(), new VarInfo (node.getVarName(), node.getAgent(), node.getFunctions())); } // Record the function nodes this.functionInfos = new HashMap<String, FunctionInfo> (); for (Map.Entry< String, FunctionNode<V, U> > entry : msgCast.getPayload2().entrySet()) { FunctionNode<V, U> node = entry.getValue(); this.functionInfos.put(entry.getKey(), new FunctionInfo (node.getName(), node.getSpace(), node.getAgent())); } this.start(); return; } if (this.varInfos == null) // the agent has already terminated return; if (msgType.equals(FUNCTION_MSG_TYPE)) { // a message sent by a function node // Retrieve the information from the message @SuppressWarnings("unchecked") FunctionMsg<V, U> msgCast = (FunctionMsg<V, U>) msg; UtilitySolutionSpace<V, U> marginalUtil = msgCast.getMarginalUtil(); assert marginalUtil.getNumberOfVariables() == 1 : "Multi-variable marginal utility: " + marginalUtil; String var = marginalUtil.getVariable(0); // Postpone message if necessary if (! this.started) { this.pendingMsgs.put(var, msg); return; } VarInfo varInfo = this.varInfos.get(var); assert varInfo.optVal != null : "Received a message for a variable node I do not control"; String functionNode = msgCast.getFunctionNode(); // If this message hasn't changed since the last message received from this function node, don't respond if (marginalUtil.equivalent(varInfo.lastMsgsIn.put(functionNode, marginalUtil))) { if (--varInfo.nbrIter == 0) { this.queue.sendMessage(AgentInterface.STATS_MONITOR, new MessageWith2Payloads<String, V> (SOLUTION_MSG_TYPE, varInfo.getVarName(), varInfo.optVal)); if(convergence) queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsReporterWithConvergence.ConvStatMessage<V>(CONV_STATS_MSG_TYPE, var, assignmentHistoriesMap.get(varInfo.getVarName()))); this.checkForTermination(); } return; } // Compute the new optimal assignment to the destination variable, as the argmax of the join of the marginal utilities received from all function nodes int newOptIndex = 0; U newOpt = this.infeasibleUtil; final int domSize = (int) marginalUtil.getNumberOfSolutions(); for (int i = 0; i < domSize; i++) { // for each possible assignment to my variable AddableDelayed<U> sumDelayed = this.zero.addDelayed(); for (UtilitySolutionSpace<V, U> space : varInfo.lastMsgsIn.values()) sumDelayed.addDelayed(space.getUtility(i)); U sum = sumDelayed.resolve(); if (this.maximize ? sum.compareTo(newOpt) >= 0 : sum.compareTo(newOpt) <= 0) { newOpt = sum; newOptIndex = i; } } V newOptVal = varInfo.getDom()[newOptIndex]; // Report the new optimal assignment if it has changed if (! newOptVal.equals(varInfo.optVal)) { varInfo.optVal = newOptVal; // System.out.println("var `" + varInfo.varName + "' gets assigned " + varInfo.optVal); if (this.convergence) assignmentHistoriesMap.get(var).add(new CurrentAssignment<V>(queue.getCurrentTime(), 0, newOptVal)); if (--varInfo.nbrIter <= 0) { this.queue.sendMessage(AgentInterface.STATS_MONITOR, new MessageWith2Payloads<String, V> (SOLUTION_MSG_TYPE, varInfo.getVarName(), varInfo.optVal)); if(convergence) queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsReporterWithConvergence.ConvStatMessage<V>(CONV_STATS_MSG_TYPE, var, assignmentHistoriesMap.get(varInfo.getVarName()))); if (varInfo.nbrIter == 0) this.checkForTermination(); return; } } else if (--varInfo.nbrIter == 0) { this.queue.sendMessage(AgentInterface.STATS_MONITOR, new MessageWith2Payloads<String, V> (SOLUTION_MSG_TYPE, varInfo.getVarName(), varInfo.optVal)); if(convergence) queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsReporterWithConvergence.ConvStatMessage<V>(CONV_STATS_MSG_TYPE, var, assignmentHistoriesMap.get(varInfo.getVarName()))); this.checkForTermination(); return; } else if (varInfo.nbrIter < 0) return; // Compute and send a new message to each neighboring function node for (FunctionNode<V, U> function : varInfo.getFunctions()) { // Join all last marginal utilities received from all neighboring function nodes except the current one marginalUtil = this.zeroSpace(varInfo.getVarName(), varInfo.getDom()); for (Map.Entry< String, UtilitySolutionSpace<V, U> > entry : varInfo.lastMsgsIn.entrySet()) { if (! function.getName().equals(entry.getKey())) { UtilitySolutionSpace<V, U> space = entry.getValue(); for (int i = 0; i < domSize; i++) { U util = space.getUtility(i); marginalUtil.setUtility(i, marginalUtil.getUtility(i).add(util)); } } } // Look up the number of feasible utilities AddableDelayed<U> scalarDelayed = this.zero.addDelayed(); int nbrNonINFutils = 0; U util; for (int i = 0; i < domSize; i++) { if (! this.infeasibleUtil.equals(util = marginalUtil.getUtility(i))) { scalarDelayed.addDelayed(util); nbrNonINFutils++; } } // Rescale the join such that its utilities sum up to zero (ignoring infeasible ones) if (nbrNonINFutils > 0) { U scalar = scalarDelayed.resolve(); scalar = scalar.divide(scalar.fromString(Integer.toString(nbrNonINFutils))); for (int i = 0; i < domSize; i++) marginalUtil.setUtility(i, marginalUtil.getUtility(i).subtract(scalar)); } // Send the message this.queue.sendMessage(function.getAgent(), new VariableMsg<V, U> (function.getName(), marginalUtil)); } } else if (msgType.equals(VARIABLE_MSG_TYPE)) { // a message sent by a variable node // Retrieve the information from the message @SuppressWarnings("unchecked") VariableMsg<V, U> msgCast = (VariableMsg<V, U>) msg; String functionName = msgCast.getFunctionNode(); // Postpone message if necessary if (! this.started) { this.pendingMsgs.put(functionName, msg); return; } FunctionInfo functionInfo = this.functionInfos.get(functionName); UtilitySolutionSpace<V, U> marginalUtil = msgCast.getMarginalUtil(); assert marginalUtil.getNumberOfVariables() == 1 : "Multi-variable marginal utility: " + marginalUtil; String senderVar = marginalUtil.getVariable(0); if (! "start".equals(marginalUtil.getName())) { // not the foo message sent at startup // If this message hasn't changed since the last message received from this function node, don't react functionInfo.nbrIter--; if (marginalUtil.equivalent(functionInfo.lastMsgsIn.put(senderVar, marginalUtil))) return; } // If I have exhausted all my iterations, only respond to variable nodes ArrayList<String> destinations = new ArrayList<String> (functionInfo.lastMsgsIn.keySet()); if (functionInfo.nbrIter <= 0) destinations.retainAll(Arrays.asList(senderVar)); // Compute and send a message to each neighboring variable node final int nbrOtherSpaces = functionInfo.lastMsgsIn.size() - 1; for (String var : destinations) { marginalUtil = functionInfo.getSpace(); // Join with the last marginal utilities received from all variables except the destination variable if (nbrOtherSpaces > 0) { @SuppressWarnings("unchecked") UtilitySolutionSpace<V, U>[] otherSpaces = new UtilitySolutionSpace [nbrOtherSpaces]; int i = 0; for (Map.Entry< String, UtilitySolutionSpace<V, U> > entry : functionInfo.lastMsgsIn.entrySet()) if (! var.equals(entry.getKey())) otherSpaces[i++] = entry.getValue(); marginalUtil = marginalUtil.join(otherSpaces); } // Blindly project all variables except the destination one String[] vars = new String [marginalUtil.getNumberOfVariables() - 1]; int i = 0; for (String otherVar : marginalUtil.getVariables()) if (! otherVar.equals(var)) vars[i++] = otherVar; marginalUtil = marginalUtil.blindProject(vars, this.maximize); // Send the message this.queue.sendMessage(this.varInfos.get(var).getAgent(), new FunctionMsg<V, U> (functionInfo.getName(), marginalUtil.resolve())); } } else if (msgType.equals(AgentInterface.ALL_AGENTS_IDLE)) { // Send the stats for (VarInfo varInfo : this.varInfos.values()) { if (varInfo.nbrIter > 0 && ! varInfo.getFunctions().isEmpty()) { // unconstrained variables and variables with exhausted iterations have already been terminated assert varInfo.optVal != null; this.queue.sendMessage(AgentInterface.STATS_MONITOR, new MessageWith2Payloads<String, V> (SOLUTION_MSG_TYPE, varInfo.getVarName(), varInfo.optVal)); if(convergence) queue.sendMessage(AgentInterface.STATS_MONITOR, new StatsReporterWithConvergence.ConvStatMessage<V>(CONV_STATS_MSG_TYPE, varInfo.getVarName(), assignmentHistoriesMap.get(varInfo.getVarName()))); } } this.queue.sendMessageToSelf(new Message (AgentInterface.AGENT_FINISHED)); this.varInfos = null; } } /** Checks if all my variable nodes have finished */ private void checkForTermination() { for (VarInfo info : this.varInfos.values()) if (info.nbrIter > 0) return; this.queue.sendMessageToSelf(new Message (AgentInterface.AGENT_FINISHED)); } /** @return for each variable in the problem, its chosen value */ public HashMap<String, V> getOptAssignments () { return this.solution; } /** @return the cost of the optimal solution found */ public U getOptCost () { return this.optCost; } /** @see StatsReporterWithConvergence#getAssignmentHistories() */ public HashMap< String, ArrayList< CurrentAssignment<V> > > getAssignmentHistories() { return this.assignmentHistoriesMap; } /** @see StatsReporterWithConvergence#getCurrentSolution() */ public Map<String, V> getCurrentSolution() { /// @todo Auto-generated method stub assert false: "Not Implemented"; return null; } }
agpl-3.0
jitsni/k3po
lang/src/main/java/org/kaazing/robot/lang/ast/AstReadHttpHeaderNode.java
2438
/* * Copyright (c) 2014 "Kaazing Corporation," (www.kaazing.com) * * This file is part of Robot. * * Robot 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 org.kaazing.robot.lang.ast; import static org.kaazing.robot.lang.ast.util.AstUtil.equivalent; import org.kaazing.robot.lang.ast.matcher.AstValueMatcher; import org.kaazing.robot.lang.ast.value.AstLiteralTextValue; public class AstReadHttpHeaderNode extends AstEventNode { private AstLiteralTextValue name; private AstValueMatcher value; @Override public <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception { return visitor.visit(this, parameter); } @Override public int hashCode() { int hashCode = super.hashTo(); if (name != null) { hashCode <<= 4; hashCode ^= name.hashCode(); } if (value != null) { hashCode <<= 4; hashCode ^= value.hashCode(); } return hashCode; } @Override public boolean equals(Object obj) { return (this == obj) || ((obj instanceof AstReadHttpHeaderNode) && equals((AstReadHttpHeaderNode) obj)); } protected boolean equals(AstReadHttpHeaderNode that) { return super.equalTo(that) && equivalent(this.name, that.name) && equivalent(this.value, that.value); } @Override protected void formatNode(StringBuilder sb) { super.formatNode(sb); sb.append(String.format("read header %s %s\n", name, value)); } public AstValueMatcher getValue() { return value; } public void setValue(AstValueMatcher value) { this.value = value; } public AstLiteralTextValue getName() { return name; } public void setName(AstLiteralTextValue name) { this.name = name; } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/dcma-data-access/src/main/java/com/ephesoft/dcma/da/domain/IndexFieldDBExportMapping.java
5805
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.da.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import com.ephesoft.dcma.core.common.OptionalExportParameters; @Entity @Table(name = "index_field_db_export_mapping") @org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) public class IndexFieldDBExportMapping extends DatabaseMapping { /** * Serialised version UID of the class. */ private static final long serialVersionUID = 1L; /** * {@link FieldType} to which DB Export Mapping is binded to. */ @JoinColumn(name = "field_type_id") @ManyToOne private FieldType bindedField; /** * {@link List}<{@link OptionalExportParameters}> optionalExportParametersList which are to be exported with field. */ @OneToMany @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN, CascadeType.MERGE, CascadeType.EVICT}) @JoinColumn(name = "field_type_mapping_id") private List<IndexFieldOptionalParameters> optionalDBExportParameters = new ArrayList<IndexFieldDBExportMapping.IndexFieldOptionalParameters>(); /** * @return the bindedField */ public FieldType getBindedField() { return bindedField; } /** * @param bindedField the bindedField to set */ public void setBindedField(FieldType bindedField) { this.bindedField = bindedField; } /** * @return the optionalDBExportParameters */ public List<IndexFieldOptionalParameters> getOptionalDBExportParameters() { return optionalDBExportParameters; } /** * @param optionalDBExportParameters the optionalDBExportParameters to set */ public void setOptionalDBExportParameters(List<IndexFieldOptionalParameters> optionalDBExportParameters) { this.optionalDBExportParameters = optionalDBExportParameters; } public void addOptionalParam(final IndexFieldOptionalParameters optionalParam) { if (null != optionalParam) { if (null == optionalDBExportParameters) { optionalDBExportParameters = new ArrayList<IndexFieldDBExportMapping.IndexFieldOptionalParameters>(); } optionalDBExportParameters.add(optionalParam); } } public IndexFieldOptionalParameters getOptionalParamById(final long id) { IndexFieldOptionalParameters bindedOptionalParam = null; if (null != optionalDBExportParameters) { for (IndexFieldOptionalParameters optionalParam : optionalDBExportParameters) { if (null != optionalParam && optionalParam.getId() == id) { bindedOptionalParam = optionalParam; break; } } } return bindedOptionalParam; } public void removeOptionalParamById(final long id) { IndexFieldOptionalParameters bindedOptionalParam = getOptionalParamById(id); if (null != bindedOptionalParam) { optionalDBExportParameters.remove(bindedOptionalParam); } } @Entity @Table(name = "field_type_optional_paramter") @org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) public static class IndexFieldOptionalParameters extends DBExportOptionalParameters { private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name = "field_type_mapping_id") private IndexFieldDBExportMapping tableColumnMapping; /** * @return the tableColumnMapping */ public IndexFieldDBExportMapping getTableColumnMapping() { return tableColumnMapping; } /** * @param tableColumnMapping the tableColumnMapping to set */ public void setTableColumnMapping(IndexFieldDBExportMapping tableColumnMapping) { this.tableColumnMapping = tableColumnMapping; } } }
agpl-3.0
bitblit11/yamcs
yamcs-core/src/test/java/org/yamcs/yarch/rocksdb/HistogramRebuilderTest.java
5051
package org.yamcs.yarch.rocksdb; import static org.junit.Assert.*; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.rocksdb.ColumnFamilyHandle; import org.yamcs.TimeInterval; import org.yamcs.utils.TimeEncoding; import org.yamcs.yarch.HistogramRecord; import org.yamcs.yarch.Partition; import org.yamcs.yarch.TableDefinition; import org.yamcs.yarch.TableWriter; import org.yamcs.yarch.Tuple; import org.yamcs.yarch.YarchTestCase; import org.yamcs.yarch.TableWriter.InsertMode; public class HistogramRebuilderTest extends YarchTestCase { String tblName = "HistogramRebuilderTest"; TableDefinition tblDef; RdbStorageEngine rse; long t1 = TimeEncoding.parse("2016-12-16T00:00:00"); @Before public void populate() throws Exception { String query="create table "+tblName+"(gentime timestamp, seqNum int, name string, primary key(gentime, seqNum)) histogram(name) partition by time(gentime) table_format=compressed"; ydb.execute(query); tblDef= ydb.getTable(tblName); rse = (RdbStorageEngine) ydb.getStorageEngine(tblDef); TableWriter tw = rse.newTableWriter(tblDef, InsertMode.INSERT); tw.onTuple(null, new Tuple(tblDef.getTupleDefinition(), new Object[]{1000L, 10, "p1"})); tw.onTuple(null, new Tuple(tblDef.getTupleDefinition(), new Object[]{2000L, 20, "p1"})); tw.onTuple(null, new Tuple(tblDef.getTupleDefinition(), new Object[]{3000L, 30, "p2"})); tw.onTuple(null, new Tuple(tblDef.getTupleDefinition(), new Object[]{t1, 30, "p2"})); tw.close(); } @After public void dropTable() throws Exception { ydb.execute("drop table "+tblName); } @Test public void testDeleteValues() throws Exception { TimeInterval interval = new TimeInterval(); Iterator<HistogramRecord> iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); HistogramRebuilder rebuilder = new HistogramRebuilder(ydb, tblName); rebuilder.deleteHistograms(new TimeInterval(1000L, 1000L)); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 1); assertNotNull(getHistoCf(1000L, "name")); rebuilder.rebuild(new TimeInterval(0, 2000)).get(); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); } @Test public void testDeleteCfh() throws Exception { TimeInterval interval = new TimeInterval(); Iterator<HistogramRecord> iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); HistogramRebuilder rebuilder = new HistogramRebuilder(ydb, tblName); rebuilder.deleteHistograms(TimeInterval.openStart(1000L)); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 1); assertNull(getHistoCf(1000L, "name")); assertNull(getHistoCf(t1, "name")); rebuilder.rebuild(TimeInterval.openStart(t1)).get(); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); } @Test public void testRebuildAll() throws Exception { TimeInterval interval = new TimeInterval(); Iterator<HistogramRecord> iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); HistogramRebuilder rebuilder = new HistogramRebuilder(ydb, tblName); rebuilder.deleteHistograms(new TimeInterval()); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 0); assertNull(getHistoCf(1000L, "name")); assertNull(getHistoCf(t1, "name")); rebuilder.rebuild(new TimeInterval()).get(); iter = rse.getHistogramIterator(tblDef, "name", interval, 0); assertNumElementsEqual(iter, 3); } private void assertNumElementsEqual(Iterator<HistogramRecord> iter, int k) { int num =0; while(iter.hasNext()) { num++; iter.next(); } assertEquals(k, num); } private ColumnFamilyHandle getHistoCf(long start, String colName) throws Exception { String cfHistoName = AbstractTableWriter.getHistogramColumnFamilyName(colName); RdbPartition p0 = getFirstPartition(1000L); YRDB rdb = RDBFactory.getInstance(ydb.getName()).getRdb(tblDef.getDataDir()+"/"+p0.dir, false); return rdb.getColumnFamilyHandle(cfHistoName); } private RdbPartition getFirstPartition(long start) { Iterator<List<Partition>> it = rse.getPartitionManager(tblDef).iterator(start, null); if(!it.hasNext()) return null; return (RdbPartition) it.next().get(0); } }
agpl-3.0
rahuldhote/jpmml-evaluator
pmml-evaluator/src/main/java/org/jpmml/evaluator/HasEntityRegistry.java
1090
/* * Copyright (c) 2013 Villu Ruusmann * * This file is part of JPMML-Evaluator * * JPMML-Evaluator 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. * * JPMML-Evaluator 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 JPMML-Evaluator. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.evaluator; import com.google.common.collect.BiMap; import org.dmg.pmml.Entity; public interface HasEntityRegistry<E extends Entity> { /** * @return A bidirectional map between {@link Entity#getId() Entity identifiers} and {@link Entity Entity instances}. */ BiMap<String, E> getEntityRegistry(); }
agpl-3.0
torakiki/pdfsam
pdfsam-core/src/main/java/org/pdfsam/support/params/MultipleOutputTaskParametersBuilder.java
1492
/* * This file is part of the PDF Split And Merge source code * Created on 26/giu/2014 * Copyright 2017 by Sober Lemur S.a.s. di Vacondio Andrea (info@pdfsam.org). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pdfsam.support.params; import org.apache.commons.lang3.builder.Builder; import org.sejda.model.output.SingleOrMultipleTaskOutput; import org.sejda.model.parameter.base.MultipleOutputTaskParameters; import org.sejda.model.parameter.base.SingleOrMultipleOutputTaskParameters; /** * Builder for a {@link MultipleOutputTaskParameters} * * @author Andrea Vacondio * @param <P> * type of parameters built * */ public interface MultipleOutputTaskParametersBuilder<P extends SingleOrMultipleOutputTaskParameters> extends Builder<P> { void prefix(String prefix); void output(SingleOrMultipleTaskOutput output); }
agpl-3.0
urvaius/BuffyMod
src/main/java/com/arne5/buffymod/ItemTest.java
220
package com.arne5.buffymod; import net.minecraft.item.Item; /** * Created by urvaius on 8/2/14. */ public class ItemTest extends Item { protected ItemTest() { this.setCreativeTab(BuffyMod.tabBuffyMod); } }
lgpl-2.1
lucee/Lucee
core/src/main/java/lucee/runtime/functions/math/Pi.java
1037
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ /** * Implements the CFML Function pi */ package lucee.runtime.functions.math; import lucee.runtime.PageContext; import lucee.runtime.ext.function.Function; public final class Pi implements Function { public static double call(PageContext pc) { return StrictMath.PI; } }
lgpl-2.1
phoenixctms/ctsms
core/src/test/java/org/phoenixctms/ctsms/service/shared/test/SelectionSetService_getAllDepartmentsTest.java
1311
// This file is part of the Phoenix CTMS project (www.phoenixctms.org), // distributed under LGPL v2.1. Copyright (C) 2011 - 2017. // package org.phoenixctms.ctsms.service.shared.test; import org.testng.Assert; import org.testng.annotations.Test; /** * <p> * Test case for method <code>getAllDepartments</code> of service <code>SelectionSetService</code>. * </p> * * @see org.phoenixctms.ctsms.service.shared.SelectionSetService#getAllDepartments(org.phoenixctms.ctsms.vo.AuthenticationVO) */ @Test(groups={"service","SelectionSetService"}) public class SelectionSetService_getAllDepartmentsTest extends SelectionSetServiceBaseTest { /** * Test succes path for service method <code>getAllDepartments</code> * * Tests expected behaviour of service method. */ @Test public void testSuccessPath() { Assert.fail( "Test 'SelectionSetService_getAllDepartmentsTest.testSuccessPath()}' not implemented." ); } /* * Add test methods for each test case of the 'SelectionSetService.org.andromda.cartridges.spring.metafacades.SpringServiceOperationLogicImpl[org.phoenixctms.ctsms.service.shared.SelectionSetService.getAllDepartments]()' service method. */ /** * Test special case XYZ for service method <code></code> */ /* @Test public void testCaseXYZ() { } */ }
lgpl-2.1
mcarniel/oswing
srcdemo/demo18/client/DemoClientFacade.java
610
package demo18.client; import org.openswing.swing.mdi.client.*; import java.sql.Connection; /** * <p>Title: OpenSwing Framework</p> * <p>Description: Client Facade, called by the MDI Tree.</p> * <p>Copyright: Copyright (C) 2006 Mauro Carniel</p> * <p> </p> * @author Mauro Carniel * @version 1.0 */ public class DemoClientFacade implements ClientFacade { public DemoClientFacade() { } public void getEmployees() { new EmpGridFrameController(); } public void getDepts() { new DeptFrameController(); } public void getTasks() { new TaskGridFrameController(); } }
lgpl-2.1
plast-lab/soot
src/main/java/soot/coffi/CONSTANT_Methodref_info.java
4490
package soot.coffi; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1997 Clark Verbrugge * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.List; import soot.Scene; import soot.Type; import soot.Value; import soot.jimple.Jimple; /** * A constant pool entry of type CONSTANT_Methodref * * @see cp_info * @author Clark Verbrugge */ class CONSTANT_Methodref_info extends cp_info implements ICONSTANT_Methodref_info { /** * Constant pool index of a CONSTANT_Class object. * * @see CONSTANT_Class_info */ public int class_index; /** * Constant pool index of a CONSTANT_NameAndType object. * * @see CONSTANT_NameAndType_info */ public int name_and_type_index; /** * Returns the size of this cp_info object. * * @return number of bytes occupied by this object. * @see cp_info#size */ public int size() { return 5; } /** * Returns a String representation of this entry. * * @param constant_pool * constant pool of ClassFile. * @return String representation of this entry. * @see cp_info#toString */ public String toString(cp_info constant_pool[]) { CONSTANT_Class_info cc = (CONSTANT_Class_info) (constant_pool[class_index]); CONSTANT_NameAndType_info cn = (CONSTANT_NameAndType_info) (constant_pool[name_and_type_index]); return cc.toString(constant_pool) + "." + cn.toString(constant_pool); } /** * Returns a String description of what kind of entry this is. * * @return the String "methodref". * @see cp_info#typeName */ public String typeName() { return "methodref"; } /** * Compares this entry with another cp_info object (which may reside in a different constant pool). * * @param constant_pool * constant pool of ClassFile for this. * @param cp * constant pool entry to compare against. * @param cp_constant_pool * constant pool of ClassFile for cp. * @return a value <0, 0, or >0 indicating whether this is smaller, the same or larger than cp. * @see cp_info#compareTo */ public int compareTo(cp_info constant_pool[], cp_info cp, cp_info cp_constant_pool[]) { int i; if (tag != cp.tag) { return tag - cp.tag; } CONSTANT_Methodref_info cu = (CONSTANT_Methodref_info) cp; i = constant_pool[class_index].compareTo(constant_pool, cp_constant_pool[cu.class_index], cp_constant_pool); if (i != 0) { return i; } return constant_pool[name_and_type_index].compareTo(constant_pool, cp_constant_pool[cu.name_and_type_index], cp_constant_pool); } public Value createJimpleConstantValue(cp_info[] constant_pool) { CONSTANT_Class_info cc = (CONSTANT_Class_info) (constant_pool[class_index]); CONSTANT_NameAndType_info cn = (CONSTANT_NameAndType_info) (constant_pool[name_and_type_index]); String className = cc.toString(constant_pool); String nameAndType = cn.toString(constant_pool); String name = nameAndType.substring(0, nameAndType.indexOf(":")); String typeName = nameAndType.substring(nameAndType.indexOf(":") + 1); List parameterTypes; Type returnType; // Generate parameters & returnType & parameterTypes { Type[] types = Util.v().jimpleTypesOfFieldOrMethodDescriptor(typeName); parameterTypes = new ArrayList(); for (int k = 0; k < types.length - 1; k++) { parameterTypes.add(types[k]); } returnType = types[types.length - 1]; } return Jimple.v().newStaticInvokeExpr( Scene.v().makeMethodRef(Scene.v().getSootClass(className), name, parameterTypes, returnType, true)); } public int getClassIndex() { return class_index; } public int getNameAndTypeIndex() { return name_and_type_index; } }
lgpl-2.1
jodygarnett/GeoGig
src/api/src/main/java/org/locationtech/geogig/storage/StorageProvider.java
2164
/* Copyright (c) 2015 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.storage; import java.util.ServiceLoader; import com.google.common.collect.ImmutableList; /** * A plug-in mechanism for providers of storage backends for the different kinds of geogig * databases. * <p> * Realizations of this interface are looked up in the classpath using the standard Java * {@link ServiceLoader service provider interface (SPI)} mechanism, by loading the classes defined * in all {@code META-INF/services/org.locationtech.geogig.storage.StorageProvider} text files. * * @since 1.0 */ public abstract class StorageProvider { /** * @return a short name of the storage backend */ public abstract String getName(); /** * @return an application level version for the storage backend, may denote a serialization * format or storage mechanism */ public abstract String getVersion(); /** * @return a human readable description of the storage backend */ public abstract String getDescription(); /** * @return the format of the {@link ObjectDatabase} */ public abstract VersionedFormat getObjectDatabaseFormat(); /** * @return the format of the {@link GraphDatabase} */ public abstract VersionedFormat getGraphDatabaseFormat(); /** * @return the format of the {@link RefDatabase} */ public abstract VersionedFormat getRefsDatabaseFormat(); /** * @return the available providers as found by {@link ServiceLoader} under the * {@link StorageProvider} key. */ public static Iterable<StorageProvider> findProviders() { ServiceLoader<StorageProvider> loader = ServiceLoader.load(StorageProvider.class); return ImmutableList.copyOf(loader.iterator()); } }
lgpl-2.1