repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
hispindia/his-tb-emr | api/src/main/java/org/openmrs/module/kenyaemr/calculation/library/hiv/InCareHasAtLeast2VisitsCalculation.java | 3983 | /**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://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.kenyaemr.calculation.library.hiv;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.openmrs.Program;
import org.openmrs.Visit;
import org.openmrs.api.context.Context;
import org.openmrs.calculation.patient.PatientCalculationContext;
import org.openmrs.calculation.result.CalculationResultMap;
import org.openmrs.module.kenyacore.calculation.AbstractPatientCalculation;
import org.openmrs.module.kenyacore.calculation.BooleanResult;
import org.openmrs.module.kenyacore.calculation.Filters;
import org.openmrs.module.kenyaemr.metadata.HivMetadata;
import org.openmrs.module.metadatadeploy.MetadataUtils;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Patients who are in care and have at least 2 visits 3 months a part
*/
public class InCareHasAtLeast2VisitsCalculation extends AbstractPatientCalculation {
@Override
public CalculationResultMap evaluate(Collection<Integer> cohort, Map<String, Object> params, PatientCalculationContext context) {
Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
Set<Integer> inHivProgram = Filters.inProgram(hivProgram, cohort, context);
CalculationResultMap ret = new CalculationResultMap();
for (Integer ptId: cohort){
boolean has2VisitsWithin3Months = false;
List<Visit> visits = Context.getVisitService().getVisitsByPatient(Context.getPatientService().getPatient(ptId));
List<Date> visitDates = new ArrayList<Date>();
if(inHivProgram.contains(ptId) && visits.size() > 1){
for (Visit visit: visits) {
visitDates.add(visit.getStartDatetime());
}
//check if the list is NOT empty and the visits exceed 2
if (dateThatAre6MonthsOldFromNow(visitDates, context).size() > 1 && !(dateThatAre6MonthsOldFromNow(visitDates, context).isEmpty())) {
if(checkIfAnyVisit3MonthsApart(dateThatAre6MonthsOldFromNow(visitDates, context))) {
has2VisitsWithin3Months = true;
}
}
}
ret.put(ptId, new BooleanResult(has2VisitsWithin3Months, this, context));
}
return ret;
}
private List<Date> dateThatAre6MonthsOldFromNow(List<Date> dates, PatientCalculationContext context){
List<Date> returnDates = new ArrayList<Date>();
Date reportingTime = context.getNow();//to hold the date when reporting is done
Date startDate;// to handle the date we expect our visits to have started
Calendar calendar = Calendar.getInstance();
calendar.setTime(reportingTime);
calendar.add(Calendar.MONTH, -6);
startDate = calendar.getTime();
for (Date date: dates){
if(date.after(startDate) && date.before(reportingTime)) {
returnDates.add(date);
}
}
return returnDates;
}
private boolean checkIfAnyVisit3MonthsApart(List<Date> dateList) {
boolean isTrue = false;
Collections.reverse(dateList);
//finding if any of the dates in a list is 3 months a part
for (int i = 0; i < dateList.size(); i++) {
for (int j = i+1; j < dateList.size(); j++){
if(daysSince(dateList.get(i), dateList.get(j)) >= 85) {
isTrue = true;
break;
}
}
}
return isTrue;
}
private int daysSince(Date date1, Date date2) {
DateTime d1 = new DateTime(date1.getTime());
DateTime d2 = new DateTime(date2.getTime());
return Days.daysBetween(d1, d2).getDays();
}
}
| gpl-3.0 |
sirsavary/Realistic-Terrain-Generation | src/main/java/rtg/world/gen/surface/SurfaceGeneric.java | 1236 | package rtg.world.gen.surface;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.ChunkPrimer;
import rtg.api.world.RTGWorld;
import rtg.api.config.BiomeConfig;
public class SurfaceGeneric extends SurfaceBase {
public SurfaceGeneric(BiomeConfig config, IBlockState top, IBlockState filler) {
super(config, top, filler);
}
@Override
public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) {
Random rand = rtgWorld.rand;
for (int k = 255; k > -1; k--) {
Block b = primer.getBlockState(x, k, z).getBlock();
if (b == Blocks.AIR) {
depth = -1;
}
else if (b == Blocks.STONE) {
depth++;
if (depth == 0 && k > 61) {
primer.setBlockState(x, k, z, topBlock);
}
else if (depth < 4) {
primer.setBlockState(x, k, z, fillerBlock);
}
}
}
}
}
| gpl-3.0 |
Lawrence-Windsor/DroidTextSecure | src/org/thoughtcrime/securesms/sms/MessageSender.java | 4841 | /**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.sms;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.mms.SlideDeck;
import org.thoughtcrime.securesms.mms.TextSlide;
import org.thoughtcrime.securesms.recipients.Recipients;
import org.thoughtcrime.securesms.service.SendReceiveService;
import java.util.List;
import ws.com.google.android.mms.ContentType;
import ws.com.google.android.mms.MmsException;
import ws.com.google.android.mms.pdu.EncodedStringValue;
import ws.com.google.android.mms.pdu.PduBody;
import ws.com.google.android.mms.pdu.SendReq;
public class MessageSender {
public static long sendMms(Context context, MasterSecret masterSecret, Recipients recipients,
long threadId, SlideDeck slideDeck, String message, int distributionType,
boolean secure)
throws MmsException
{
if (threadId == -1)
threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipients, distributionType);
if (message.trim().length() > 0)
slideDeck.addSlide(new TextSlide(context, message));
SendReq sendRequest = new SendReq();
PduBody body = slideDeck.toPduBody();
sendRequest.setDate(System.currentTimeMillis() / 1000L);
sendRequest.setBody(body);
sendRequest.setContentType(ContentType.MULTIPART_MIXED.getBytes());
// Recipients secureRecipients = recipients.getSecureSessionRecipients(context);
// Recipients insecureRecipients = recipients.getInsecureSessionRecipients(context);
// for (Recipient secureRecipient : secureRecipients.getRecipientsList()) {
// sendMms(context, new Recipients(secureRecipient), masterSecret,
// sendRequest, threadId, !forcePlaintext);
// }
//
// if (!insecureRecipients.isEmpty()) {
// sendMms(context, insecureRecipients, masterSecret, sendRequest, threadId, false);
// }
sendMms(context, recipients, masterSecret, sendRequest, threadId, distributionType, secure);
return threadId;
}
public static long send(Context context, MasterSecret masterSecret,
OutgoingTextMessage message, long threadId)
{
if (threadId == -1)
threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(message.getRecipients());
List<Long> messageIds = DatabaseFactory.getEncryptingSmsDatabase(context)
.insertMessageOutbox(masterSecret, threadId, message);
for (long messageId : messageIds) {
Log.w("SMSSender", "Got message id for new message: " + messageId);
Intent intent = new Intent(SendReceiveService.SEND_SMS_ACTION, null,
context, SendReceiveService.class);
intent.putExtra("message_id", messageId);
context.startService(intent);
}
return threadId;
}
private static void sendMms(Context context, Recipients recipients, MasterSecret masterSecret,
SendReq sendRequest, long threadId, int distributionType, boolean secure)
throws MmsException
{
String[] recipientsArray = recipients.toNumberStringArray(true);
EncodedStringValue[] encodedNumbers = EncodedStringValue.encodeStrings(recipientsArray);
if (recipients.isSingleRecipient()) {
sendRequest.setTo(encodedNumbers);
} else if (distributionType == ThreadDatabase.DistributionTypes.BROADCAST) {
sendRequest.setBcc(encodedNumbers);
} else if (distributionType == ThreadDatabase.DistributionTypes.CONVERSATION) {
sendRequest.setCc(encodedNumbers);
}
long messageId = DatabaseFactory.getMmsDatabase(context)
.insertMessageOutbox(masterSecret, sendRequest, threadId, secure);
Intent intent = new Intent(SendReceiveService.SEND_MMS_ACTION, null,
context, SendReceiveService.class);
intent.putExtra("message_id", messageId);
context.startService(intent);
}
}
| gpl-3.0 |
kazoompa/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/plugins/PluginsAdministrationPresenter.java | 13163 | /*
* Copyright (c) 2021 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.administration.plugins;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyStandard;
import com.gwtplatform.mvp.client.annotations.TitleFunction;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import org.obiba.opal.web.gwt.app.client.administration.presenter.ItemAdministrationPresenter;
import org.obiba.opal.web.gwt.app.client.administration.presenter.RequestAdministrationPermissionEvent;
import org.obiba.opal.web.gwt.app.client.event.NotificationEvent;
import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionEvent;
import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionRequestEvent;
import org.obiba.opal.web.gwt.app.client.fs.presenter.FileSelectorPresenter;
import org.obiba.opal.web.gwt.app.client.place.Places;
import org.obiba.opal.web.gwt.app.client.presenter.HasBreadcrumbs;
import org.obiba.opal.web.gwt.app.client.presenter.ModalProvider;
import org.obiba.opal.web.gwt.app.client.support.DefaultBreadcrumbsBuilder;
import org.obiba.opal.web.gwt.rest.client.ResourceCallback;
import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory;
import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback;
import org.obiba.opal.web.gwt.rest.client.UriBuilders;
import org.obiba.opal.web.gwt.rest.client.authorization.HasAuthorization;
import org.obiba.opal.web.model.client.opal.PluginDto;
import org.obiba.opal.web.model.client.opal.PluginPackagesDto;
import static com.google.gwt.http.client.Response.SC_INTERNAL_SERVER_ERROR;
public class PluginsAdministrationPresenter extends ItemAdministrationPresenter<PluginsAdministrationPresenter.Display, PluginsAdministrationPresenter.Proxy>
implements PluginsAdministrationUiHandlers {
private final DefaultBreadcrumbsBuilder breadcrumbsHelper;
private final ModalProvider<PluginServiceConfigurationModalPresenter> pluginServiceConfigurationModalPresenterModalProvider;
@Inject
public PluginsAdministrationPresenter(EventBus eventBus, Display display, Proxy proxy,
DefaultBreadcrumbsBuilder breadcrumbsHelper,
ModalProvider<PluginServiceConfigurationModalPresenter> pluginServiceConfigurationModalPresenterModalProvider) {
super(eventBus, display, proxy);
this.breadcrumbsHelper = breadcrumbsHelper;
this.pluginServiceConfigurationModalPresenterModalProvider = pluginServiceConfigurationModalPresenterModalProvider.setContainer(this);
getView().setUiHandlers(this);
}
@Override
@TitleFunction
public String getTitle() {
return translations.pagePluginsTitle();
}
@Override
protected void onBind() {
addRegisteredHandler(FileSelectionEvent.getType(), new FileSelectionEvent.Handler() {
@Override
public void onFileSelection(FileSelectionEvent event) {
if (!PluginsAdministrationPresenter.this.equals(event.getSource())) return;
installPluginArchive(event.getSelectedFile().getSelectionPath());
}
});
}
@Override
protected void onReveal() {
breadcrumbsHelper.setBreadcrumbView(getView().getBreadcrumbs()).build();
getView().refresh();
}
@Override
public void onAdministrationPermissionRequest(RequestAdministrationPermissionEvent event) {
}
@Override
public String getName() {
return getTitle();
}
@Override
public void authorize(HasAuthorization authorizer) {
}
@Override
public void getInstalledPlugins() {
ResourceRequestBuilderFactory.<PluginPackagesDto>newBuilder() //
.forResource(UriBuilders.PLUGINS.create().build()) //
.withCallback(new ResourceCallback<PluginPackagesDto>() {
@Override
public void onResource(Response response, PluginPackagesDto resource) {
getView().showInstalledPackages(resource);
}
}) //
.withCallback(SC_INTERNAL_SERVER_ERROR, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
fireEvent(NotificationEvent.newBuilder().error("PluginsServiceError").build());
}
}) //
.get().send();
}
@Override
public void getAvailablePlugins() {
ResourceRequestBuilderFactory.<PluginPackagesDto>newBuilder() //
.forResource(UriBuilders.PLUGINS_AVAILABLE.create().build()) //
.withCallback(new ResourceCallback<PluginPackagesDto>() {
@Override
public void onResource(Response response, PluginPackagesDto resource) {
getView().showAvailablePackages(resource);
}
}) //
.withCallback(SC_INTERNAL_SERVER_ERROR, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
fireEvent(NotificationEvent.newBuilder().error("PluginUpdateSiteError").build());
}
}) //
.get().send();
}
@Override
public void getUpdatablePlugins() {
ResourceRequestBuilderFactory.<PluginPackagesDto>newBuilder() //
.forResource(UriBuilders.PLUGINS_UPDATES.create().build()) //
.withCallback(new ResourceCallback<PluginPackagesDto>() {
@Override
public void onResource(Response response, PluginPackagesDto resource) {
getView().showUpdatablePackages(resource);
}
}) //
.withCallback(SC_INTERNAL_SERVER_ERROR, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
fireEvent(NotificationEvent.newBuilder().error("PluginUpdateSiteError").build());
}
}) //
.get().send();
}
@Override
public void onUninstall(final String name) {
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGIN.create().build(name))
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK || response.getStatusCode() == Response.SC_NO_CONTENT)
fireEvent(NotificationEvent.newBuilder().info("PluginRemoved").args(name).build());
else
fireEvent(NotificationEvent.newBuilder().error("PluginRemovalFailed").build());
getInstalledPlugins();
}
},
Response.SC_OK, Response.SC_NO_CONTENT, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND)
.delete().send();
}
@Override
public void onCancelUninstall(final String name) {
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGIN.create().build(name))
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK || response.getStatusCode() == Response.SC_NO_CONTENT)
fireEvent(NotificationEvent.newBuilder().info("PluginReinstated").args(name).build());
else
fireEvent(NotificationEvent.newBuilder().error("PluginReinstateFailed").build());
getInstalledPlugins();
}
},
Response.SC_OK, Response.SC_NO_CONTENT, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND)
.put().send();
}
@Override
public void onInstall(final String name, final String version) {
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGINS.create()
.query("name", name)
.query("version", version).build())
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK)
fireEvent(NotificationEvent.newBuilder().info("PluginInstalled").args(name, version).build());
else
fireEvent(NotificationEvent.newBuilder().error("PluginInstallationFailed").build());
getInstalledPlugins();
}
},
Response.SC_OK, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND) //
.post().send();
}
@Override
public void onRestart(final String name) {
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGIN_SERVICE.create().build(name))
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK || response.getStatusCode() == Response.SC_NO_CONTENT)
onStart(name);
else
fireEvent(NotificationEvent.newBuilder().error("PluginStopFailed").build());
}
},
Response.SC_OK, Response.SC_NO_CONTENT, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND)
.delete().send();
}
private void onStart(final String name) {
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGIN_SERVICE.create().build(name))
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK || response.getStatusCode() == Response.SC_NO_CONTENT)
fireEvent(NotificationEvent.newBuilder().info("PluginRestarted").args(name).build());
else
fireEvent(NotificationEvent.newBuilder().error("PluginStartFailed").build());
}
},
Response.SC_OK, Response.SC_NO_CONTENT, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND)
.put().send();
}
@Override
public void onConfigure(final String name) {
ResourceRequestBuilderFactory.<PluginDto>newBuilder() //
.forResource(UriBuilders.PLUGIN.create().build(name)) //
.withCallback(new ResourceCallback<PluginDto>() {
@Override
public void onResource(Response response, PluginDto resource) {
PluginServiceConfigurationModalPresenter p = pluginServiceConfigurationModalPresenterModalProvider.get();
p.initialize(name, resource.getSiteProperties());
}
}) //
.withCallback(SC_INTERNAL_SERVER_ERROR, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
fireEvent(NotificationEvent.newBuilder().error("PluginsServiceError").build());
}
}) //
.get().send();
}
private void installPluginArchive(final String file) {
if (!file.endsWith("-dist.zip")) {
fireEvent(NotificationEvent.newBuilder().error("NotPluginArchive").build());
return;
}
ResourceRequestBuilderFactory.newBuilder().forResource(UriBuilders.PLUGINS.create()
.query("file", file).build())
.withCallback(
new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == Response.SC_OK)
fireEvent(NotificationEvent.newBuilder().info("PluginPackageInstalled").args(file).build());
else
fireEvent(NotificationEvent.newBuilder().error("PluginInstallationFailed").build());
getInstalledPlugins();
}
},
Response.SC_OK, Response.SC_INTERNAL_SERVER_ERROR,//
Response.SC_NOT_FOUND) //
.post().send();
}
@Override
public void onPluginFileSelection() {
fireEvent(new FileSelectionRequestEvent(this, FileSelectorPresenter.FileSelectionType.FILE));
}
@ProxyStandard
@NameToken(Places.PLUGINS)
public interface Proxy extends ProxyPlace<PluginsAdministrationPresenter> {
}
public interface Display extends View, HasBreadcrumbs, HasUiHandlers<PluginsAdministrationUiHandlers> {
void showInstalledPackages(PluginPackagesDto pluginPackagesDto);
void showAvailablePackages(PluginPackagesDto pluginPackagesDto);
void showUpdatablePackages(PluginPackagesDto pluginPackagesDto);
void refresh();
}
}
| gpl-3.0 |
wiki2014/Learning-Summary | alps/cts/tools/vm-tests-tf/src/dot/junit/opcodes/invoke_interface_range/d/T_invoke_interface_range_23.java | 747 | /*
* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dot.junit.opcodes.invoke_interface_range.d;
public class T_invoke_interface_range_23 {
public void run() {
}
}
| gpl-3.0 |
CellularPrivacy/Android-IMSI-Catcher-Detector | AIMSICD/src/main/java/com/secupwn/aimsicd/utils/atcmd/TtyPrivFile.java | 1525 | /* Android IMSI-Catcher Detector | (c) AIMSICD Privacy Project
* -----------------------------------------------------------
* LICENSE: http://git.io/vki47 | TERMS: http://git.io/vki4o
* -----------------------------------------------------------
*/
package com.secupwn.aimsicd.utils.atcmd;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TtyPrivFile extends TtyStream {
protected Process mReadProc;
protected Process mWriteProc;
public TtyPrivFile(String ttyPath) throws IOException {
// TODO robustify su detection?
this(
new ProcessBuilder("su", "-c", "\\exec cat <" + ttyPath).start(),
new ProcessBuilder("su", "-c", "\\exec cat >" + ttyPath).start()
);
}
private TtyPrivFile(Process read, Process write) {
super(read.getInputStream(), write.getOutputStream());
mReadProc = read;
mWriteProc = write;
log.debug("mReadProc={}, mWriteProc={}", mReadProc, mWriteProc);
}
@Override
public void dispose() {
super.dispose();
try {
// Have to do this to get readproc to exit.
// I guess it gets blocked waiting for input, so let's give it some.
mOutputStream.write("ATE0\r".getBytes("ASCII")); // disable local Echo
mOutputStream.flush();
} catch (IOException e) {
log.error("moutputstream didnt close", e);
}
mReadProc.destroy();
mWriteProc.destroy();
}
}
| gpl-3.0 |
GeorgeWalker/sbc-qsystem | QSystem/src/ru/apertum/qsystem/common/exceptions/ReportException.java | 1578 | /*
* Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.apertum.qsystem.common.exceptions;
import ru.apertum.qsystem.common.QLog;
/**
* Этот класс исключения использовать для програмной генерации исклюсений.
* Записывает StackTrace и само исключение в лог.
* Это исключение не показывает диологовое окно при возникновении ошибки
* @author Evgeniy Egorov
*/
public class ReportException extends RuntimeException {
public ReportException(String textException) {
super(textException);
//StringWriter out = new StringWriter();
//printStackTrace(new PrintWriter(out));
//log.logger.error("Error!\n"+out.toString(), this);
QLog.l().logRep().error("Error!", this);
}
}
| gpl-3.0 |
2300206764/Nukkit | src/main/java/cn/nukkit/level/generator/noise/Simplex.java | 10500 | package cn.nukkit.level.generator.noise;
import cn.nukkit.math.NukkitRandom;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Simplex extends Perlin {
protected static double SQRT_3;
protected static double SQRT_5;
protected static double F2;
protected static double G2;
protected static double G22;
protected static double F3;
protected static double G3;
protected static double F4;
protected static double G4;
protected static double G42;
protected static double G43;
protected static double G44;
protected static int[][] grad4 = {{0, 1, 1, 1}, {0, 1, 1, -1}, {0, 1, -1, 1}, {0, 1, -1, -1},
{0, -1, 1, 1}, {0, -1, 1, -1}, {0, -1, -1, 1}, {0, -1, -1, -1},
{1, 0, 1, 1}, {1, 0, 1, -1}, {1, 0, -1, 1}, {1, 0, -1, -1},
{-1, 0, 1, 1}, {-1, 0, 1, -1}, {-1, 0, -1, 1}, {-1, 0, -1, -1},
{1, 1, 0, 1}, {1, 1, 0, -1}, {1, -1, 0, 1}, {1, -1, 0, -1},
{-1, 1, 0, 1}, {-1, 1, 0, -1}, {-1, -1, 0, 1}, {-1, -1, 0, -1},
{1, 1, 1, 0}, {1, 1, -1, 0}, {1, -1, 1, 0}, {1, -1, -1, 0},
{-1, 1, 1, 0}, {-1, 1, -1, 0}, {-1, -1, 1, 0}, {-1, -1, -1, 0}};
protected static int[][] simplex = {
{0, 1, 2, 3}, {0, 1, 3, 2}, {0, 0, 0, 0}, {0, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 2, 3, 0},
{0, 2, 1, 3}, {0, 0, 0, 0}, {0, 3, 1, 2}, {0, 3, 2, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {1, 3, 2, 0},
{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
{1, 2, 0, 3}, {0, 0, 0, 0}, {1, 3, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 3, 0, 1}, {2, 3, 1, 0},
{1, 0, 2, 3}, {1, 0, 3, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {2, 0, 3, 1}, {0, 0, 0, 0}, {2, 1, 3, 0},
{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0},
{2, 0, 1, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 0, 1, 2}, {3, 0, 2, 1}, {0, 0, 0, 0}, {3, 1, 2, 0},
{2, 1, 0, 3}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {3, 1, 0, 2}, {0, 0, 0, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}};
protected double offsetW;
public Simplex(NukkitRandom random, double octaves, double persistence) {
super(random, octaves, persistence);
this.offsetW = random.nextDouble() * 256;
SQRT_3 = Math.sqrt(3);
SQRT_5 = Math.sqrt(5);
F2 = 0.5 * (SQRT_3 - 1);
G2 = (3 - SQRT_3) / 6;
G22 = G2 * 2.0 - 1;
F3 = 1.0 / 3.0;
G3 = 1.0 / 6.0;
F4 = (SQRT_5 - 1.0) / 4.0;
G4 = (5.0 - SQRT_5) / 20.0;
G42 = G4 * 2.0;
G43 = G4 * 3.0;
G44 = G4 * 4.0 - 1.0;
}
public Simplex(NukkitRandom random, double octaves, double persistence, double expansion) {
super(random, octaves, persistence, expansion);
this.offsetW = random.nextDouble() * 256;
SQRT_3 = Math.sqrt(3);
SQRT_5 = Math.sqrt(5);
F2 = 0.5 * (SQRT_3 - 1);
G2 = (3 - SQRT_3) / 6;
G22 = G2 * 2.0 - 1;
F3 = 1.0 / 3.0;
G3 = 1.0 / 6.0;
F4 = (SQRT_5 - 1.0) / 4.0;
G4 = (5.0 - SQRT_5) / 20.0;
G42 = G4 * 2.0;
G43 = G4 * 3.0;
G44 = G4 * 4.0 - 1.0;
}
protected static double dot2D(int[] g, double x, double y) {
return g[0] * x + g[1] * y;
}
protected static double dot3D(int[] g, double x, double y, double z) {
return g[0] * x + g[1] * y + g[2] * z;
}
protected static double dot4D(int[] g, double x, double y, double z, double w) {
return g[0] * x + g[1] * y + g[2] * z + g[3] * w;
}
@Override
public double getNoise3D(double x, double y, double z) {
x += this.offsetX;
y += this.offsetY;
z += this.offsetZ;
// Skew the input space to determine which simplex cell we're in
double s = (x + y + z) * F3; // Very nice and simple skew factor for 3D
int i = (int) (x + s);
int j = (int) (y + s);
int k = (int) (z + s);
double t = (i + j + k) * G3;
// Unskew the cell origin back to (x,y,z) space
double x0 = x - (i - t); // The x,y,z distances from the cell origin
double y0 = y - (j - t);
double z0 = z - (k - t);
// For the 3D case, the simplex shape is a slightly irregular tetrahedron.
int i1 = 0;
int j1 = 0;
int k1 = 0;
int i2 = 0;
int j2 = 0;
int k2 = 0;
// Determine which simplex we are in.
if (x0 >= y0) {
if (y0 >= z0) {
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
} // X Y Z order
else if (x0 >= z0) {
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 0;
k2 = 1;
} // X Z Y order
else {
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 1;
j2 = 0;
k2 = 1;
}
// Z X Y order
} else { // x0<y0
if (y0 < z0) {
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 0;
j2 = 1;
k2 = 1;
} // Z Y X order
else if (x0 < z0) {
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 0;
j2 = 1;
k2 = 1;
} // Y Z X order
else {
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
}
// Y X Z order
}
// A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
// a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
// a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
// c = 1/6.
double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
double y1 = y0 - j1 + G3;
double z1 = z0 - k1 + G3;
double x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords
double y2 = y0 - j2 + 2.0 * G3;
double z2 = z0 - k2 + 2.0 * G3;
double x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords
double y3 = y0 - 1.0 + 3.0 * G3;
double z3 = z0 - 1.0 + 3.0 * G3;
// Work out the hashed gradient indices of the four simplex corners
int ii = i & 255;
int jj = j & 255;
int kk = k & 255;
double n = 0;
// Calculate the contribution from the four corners
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
if (t0 > 0) {
int[] gi0 = grad3[this.perm[ii + this.perm[jj + this.perm[kk]]] % 12];
n += t0 * t0 * t0 * t0 * (gi0[0] * x0 + gi0[1] * y0 + gi0[2] * z0);
}
double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
if (t1 > 0) {
int[] gi1 = grad3[this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12];
n += t1 * t1 * t1 * t1 * (gi1[0] * x1 + gi1[1] * y1 + gi1[2] * z1);
}
double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
if (t2 > 0) {
int[] gi2 = grad3[this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12];
n += t2 * t2 * t2 * t2 * (gi2[0] * x2 + gi2[1] * y2 + gi2[2] * z2);
}
double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
if (t3 > 0) {
int[] gi3 = grad3[this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12];
n += t3 * t3 * t3 * t3 * (gi3[0] * x3 + gi3[1] * y3 + gi3[2] * z3);
}
// Add contributions from each corner to get the noise value.
// The result is scaled to stay just inside [-1,1]
return 32.0 * n;
}
@Override
public double getNoise2D(double x, double y) {
x += this.offsetX;
y += this.offsetY;
// Skew the input space to determine which simplex cell we're in
double s = (x + y) * F2; // Hairy factor for 2D
int i = (int) (x + s);
int j = (int) (y + s);
double t = (i + j) * G2;
// Unskew the cell origin back to (x,y) space
double x0 = x - (i - t); // The x,y distances from the cell origin
double y0 = y - (j - t);
// For the 2D case, the simplex shape is an equilateral triangle.
int i1 = 0;
int j1 = 0;
// Determine which simplex we are in.
if (x0 > y0) {
i1 = 1;
j1 = 0;
} // lower triangle, XY order: (0,0).(1,0).(1,1)
else {
i1 = 0;
j1 = 1;
}
// upper triangle, YX order: (0,0).(0,1).(1,1)
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
double y1 = y0 - j1 + G2;
double x2 = x0 + G22; // Offsets for last corner in (x,y) unskewed coords
double y2 = y0 + G22;
// Work out the hashed gradient indices of the three simplex corners
int ii = i & 255;
int jj = j & 255;
double n = 0;
// Calculate the contribution from the three corners
double t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 > 0) {
int[] gi0 = grad3[this.perm[ii + this.perm[jj]] % 12];
n += t0 * t0 * t0 * t0 * (gi0[0] * x0 + gi0[1] * y0); // (x,y) of grad3 used for 2D gradient
}
double t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 > 0) {
int[] gi1 = grad3[this.perm[ii + i1 + this.perm[jj + j1]] % 12];
n += t1 * t1 * t1 * t1 * (gi1[0] * x1 + gi1[1] * y1);
}
double t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 > 0) {
int[] gi2 = grad3[this.perm[ii + 1 + this.perm[jj + 1]] % 12];
n += t2 * t2 * t2 * t2 * (gi2[0] * x2 + gi2[1] * y2);
}
// Add contributions from each corner to get the noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0 * n;
}
}
| gpl-3.0 |
pR0Ps/TextSecureSMP | src/org/thoughtcrime/SMP/RegistrationActivity.java | 10957 | package org.thoughtcrime.SMP;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.i18n.phonenumbers.AsYouTypeFormatter;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.thoughtcrime.SMP.crypto.MasterSecret;
import org.thoughtcrime.SMP.util.Dialogs;
import org.thoughtcrime.SMP.util.TextSecurePreferences;
import org.thoughtcrime.SMP.util.Util;
import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
/**
* The register account activity. Prompts ths user for their registration information
* and begins the account registration process.
*
* @author Moxie Marlinspike
*
*/
public class RegistrationActivity extends BaseActionBarActivity {
private static final int PICK_COUNTRY = 1;
private AsYouTypeFormatter countryFormatter;
private ArrayAdapter<String> countrySpinnerAdapter;
private Spinner countrySpinner;
private TextView countryCode;
private TextView number;
private Button createButton;
private Button skipButton;
private MasterSecret masterSecret;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.registration_activity);
getSupportActionBar().setTitle(getString(R.string.RegistrationActivity_connect_with_textsecure));
initializeResources();
initializeSpinner();
initializeNumber();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_COUNTRY && resultCode == RESULT_OK && data != null) {
this.countryCode.setText(data.getIntExtra("country_code", 1)+"");
setCountryDisplay(data.getStringExtra("country_name"));
setCountryFormatter(data.getIntExtra("country_code", 1));
}
}
private void initializeResources() {
this.masterSecret = getIntent().getParcelableExtra("master_secret");
this.countrySpinner = (Spinner)findViewById(R.id.country_spinner);
this.countryCode = (TextView)findViewById(R.id.country_code);
this.number = (TextView)findViewById(R.id.number);
this.createButton = (Button)findViewById(R.id.registerButton);
this.skipButton = (Button)findViewById(R.id.skipButton);
this.countryCode.addTextChangedListener(new CountryCodeChangedListener());
this.number.addTextChangedListener(new NumberChangedListener());
this.createButton.setOnClickListener(new CreateButtonListener());
this.skipButton.setOnClickListener(new CancelButtonListener());
if (getIntent().getBooleanExtra("cancel_button", false)) {
this.skipButton.setVisibility(View.VISIBLE);
} else {
this.skipButton.setVisibility(View.INVISIBLE);
}
}
private void initializeSpinner() {
this.countrySpinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
this.countrySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
setCountryDisplay(getString(R.string.RegistrationActivity_select_your_country));
this.countrySpinner.setAdapter(this.countrySpinnerAdapter);
this.countrySpinner.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Intent intent = new Intent(RegistrationActivity.this, CountrySelectionActivity.class);
startActivityForResult(intent, PICK_COUNTRY);
}
return true;
}
});
}
private void initializeNumber() {
PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
String localNumber = Util.getDeviceE164Number(this);
try {
if (!TextUtils.isEmpty(localNumber)) {
Phonenumber.PhoneNumber localNumberObject = numberUtil.parse(localNumber, null);
if (localNumberObject != null) {
this.countryCode.setText(localNumberObject.getCountryCode()+"");
this.number.setText(localNumberObject.getNationalNumber()+"");
}
} else {
String simCountryIso = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getSimCountryIso();
if (!TextUtils.isEmpty(simCountryIso)) {
this.countryCode.setText(numberUtil.getCountryCodeForRegion(simCountryIso.toUpperCase())+"");
}
}
} catch (NumberParseException npe) {
Log.w("CreateAccountActivity", npe);
}
}
private void setCountryDisplay(String value) {
this.countrySpinnerAdapter.clear();
this.countrySpinnerAdapter.add(value);
}
private void setCountryFormatter(int countryCode) {
PhoneNumberUtil util = PhoneNumberUtil.getInstance();
String regionCode = util.getRegionCodeForCountryCode(countryCode);
if (regionCode == null) this.countryFormatter = null;
else this.countryFormatter = util.getAsYouTypeFormatter(regionCode);
}
private String getConfiguredE164Number() {
return PhoneNumberFormatter.formatE164(countryCode.getText().toString(),
number.getText().toString());
}
private class CreateButtonListener implements View.OnClickListener {
@Override
public void onClick(View v) {
final RegistrationActivity self = RegistrationActivity.this;
if (TextUtils.isEmpty(countryCode.getText())) {
Toast.makeText(self,
getString(R.string.RegistrationActivity_you_must_specify_your_country_code),
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(number.getText())) {
Toast.makeText(self,
getString(R.string.RegistrationActivity_you_must_specify_your_phone_number),
Toast.LENGTH_LONG).show();
return;
}
final String e164number = getConfiguredE164Number();
if (!PhoneNumberFormatter.isValidNumber(e164number)) {
Dialogs.showAlertDialog(self,
getString(R.string.RegistrationActivity_invalid_number),
String.format(getString(R.string.RegistrationActivity_the_number_you_specified_s_is_invalid),
e164number));
return;
}
int gcmStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(self);
if (gcmStatus != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(gcmStatus)) {
GooglePlayServicesUtil.getErrorDialog(gcmStatus, self, 9000).show();
} else {
Dialogs.showAlertDialog(self, getString(R.string.RegistrationActivity_unsupported),
getString(R.string.RegistrationActivity_sorry_this_device_is_not_supported_for_data_messaging));
}
return;
}
AlertDialogWrapper.Builder dialog = new AlertDialogWrapper.Builder(self);
dialog.setTitle(PhoneNumberFormatter.getInternationalFormatFromE164(e164number));
dialog.setMessage(R.string.RegistrationActivity_we_will_now_verify_that_the_following_number_is_associated_with_your_device_s);
dialog.setPositiveButton(getString(R.string.RegistrationActivity_continue),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(self, RegistrationProgressActivity.class);
intent.putExtra("e164number", e164number);
intent.putExtra("master_secret", masterSecret);
startActivity(intent);
finish();
}
});
dialog.setNegativeButton(getString(R.string.RegistrationActivity_edit), null);
dialog.show();
}
}
private class CountryCodeChangedListener implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
if (TextUtils.isEmpty(s)) {
setCountryDisplay(getString(R.string.RegistrationActivity_select_your_country));
countryFormatter = null;
return;
}
int countryCode = Integer.parseInt(s.toString());
String regionCode = PhoneNumberUtil.getInstance().getRegionCodeForCountryCode(countryCode);
setCountryFormatter(countryCode);
setCountryDisplay(PhoneNumberFormatter.getRegionDisplayName(regionCode));
if (!TextUtils.isEmpty(regionCode) && !regionCode.equals("ZZ")) {
number.requestFocus();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
private class NumberChangedListener implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
if (countryFormatter == null)
return;
if (TextUtils.isEmpty(s))
return;
countryFormatter.clear();
String number = s.toString().replaceAll("[^\\d.]", "");
String formattedNumber = null;
for (int i=0;i<number.length();i++) {
formattedNumber = countryFormatter.inputDigit(number.charAt(i));
}
if (formattedNumber != null && !s.toString().equals(formattedNumber)) {
s.replace(0, s.length(), formattedNumber);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}
private class CancelButtonListener implements View.OnClickListener {
@Override
public void onClick(View v) {
TextSecurePreferences.setPromptedPushRegistration(RegistrationActivity.this, true);
Intent nextIntent = getIntent().getParcelableExtra("next_intent");
if (nextIntent == null) {
nextIntent = new Intent(RegistrationActivity.this, ConversationListActivity.class);
}
startActivity(nextIntent);
finish();
}
}
}
| gpl-3.0 |
thelinuxgeekcommunity/simpleirc | application/src/main/java/tk/jordynsmediagroup/simpleirc/adapter/ConversationPagerAdapter.java | 8750 | package tk.jordynsmediagroup.simpleirc.adapter;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.viewpagerindicator.TitlePageIndicator;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import tk.jordynsmediagroup.simpleirc.App;
import tk.jordynsmediagroup.simpleirc.indicator.ConversationStateProvider;
import tk.jordynsmediagroup.simpleirc.listener.MessageClickListener;
import tk.jordynsmediagroup.simpleirc.model.Conversation;
import tk.jordynsmediagroup.simpleirc.model.Server;
import tk.jordynsmediagroup.simpleirc.view.MessageListView;
/**
* Adapter for displaying a pager of conversations.
*/
public class ConversationPagerAdapter extends PagerAdapter implements ConversationStateProvider {
public static final int COLOR_NONE = -1;
private final Server server;
private LinkedList<ConversationInfo> conversations;
private final HashMap<Integer, View> views;
/**
* Container class to remember conversation and view association.
*/
public class ConversationInfo implements Comparable<ConversationInfo> {
public Conversation conv;
public MessageListAdapter adapter;
public MessageListView view;
public ConversationInfo(Conversation conv) {
this.conv = conv;
this.adapter = null;
this.view = null;
}
/**
* Compares this ConversationInfo with another ConversationInfo.
* This compares the two ConversationInfos by their Conversations.
*
* @param convInfo The ConversationInfo to compare
*/
@Override
public int compareTo(ConversationInfo convInfo) {
return conv.compareTo(convInfo.conv);
}
}
/**
* Create a new {@link ConversationPagerAdapter} instance.
*/
public ConversationPagerAdapter(Context context, Server server) {
this.server = server;
conversations = new LinkedList<ConversationInfo>();
views = new HashMap<Integer, View>();
}
/**
* Add a conversation to the adapter.
*
* @param conversation
*/
public void addConversation(Conversation conversation) {
conversations.add(new ConversationInfo(conversation));
Collections.sort(conversations);
notifyDataSetChanged();
}
/**
* Remove the conversation at the given position from the adapter.
*
* @param position
*/
public void removeConversation(int position) {
conversations.remove(position);
notifyDataSetChanged();
}
/**
* Get position of given item.
*/
@Override
public int getItemPosition(Object object) {
if( views.containsKey(object) ) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
/**
* Get item at position
*/
public Conversation getItem(int position) {
ConversationInfo convInfo = getItemInfo(position);
if( convInfo != null ) {
return convInfo.conv;
} else {
return null;
}
}
/**
* Get the adapter of the {@link MessageListView} at the given position.
*
* @param position
* @return
*/
public MessageListAdapter getItemAdapter(int position) {
ConversationInfo convInfo = getItemInfo(position);
if( convInfo != null ) {
return convInfo.adapter;
} else {
return null;
}
}
/**
* Get the adapter of the {@link MessageListView} for the conversation
* with the given name.
*
* @param name
* @return
*/
public MessageListAdapter getItemAdapter(String name) {
return getItemAdapter(getPositionByName(name));
}
/**
* Get ConversationInfo on item at position
*
* @param position
*/
private ConversationInfo getItemInfo(int position) {
if( position >= 0 && position < conversations.size() ) {
return conversations.get(position);
}
return null;
}
/**
* Get an item by the channel's name
*
* @param name
* @return The item
*/
public int getPositionByName(String name) {
// Optimization - cache field lookups
int mSize = conversations.size();
LinkedList<ConversationInfo> mItems = this.conversations;
name = name.toLowerCase(Locale.US);
for( int i = 0; i < mSize; i++ ) {
ConversationInfo ci = mItems.get(i);
if( ci.conv.getName().toLowerCase(Locale.US).equals(name) ) {
return i;
}
}
return -1;
}
/**
* Remove all conversations.
*/
public void clearConversations() {
conversations = new LinkedList<ConversationInfo>();
}
/**
* Get number of conversations from this adapter.
*/
@Override
public int getCount() {
return conversations.size();
}
/**
* Determines whether a page View is associated with a specific key object.
*/
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
/**
* Create a view object for the conversation at the given position.
*/
@Override
public Object instantiateItem(View collection, int position) {
// ConversationInfo convInfo = getItemInfo(position);
ConversationInfo convInfo = conversations.get(position);
View view;
if( convInfo.view != null ) {
view = convInfo.view;
} else {
view = renderConversation(convInfo, collection);
}
views.put(position, view);
((ViewPager)collection).addView(view);
return view;
}
/**
* Render the given conversation and return the new view.
*
* @param convInfo
* @param parent
* @return
*/
private MessageListView renderConversation(ConversationInfo convInfo, View parent) {
MessageListView list = new MessageListView(parent.getContext());
convInfo.view = list;
list.setOnItemClickListener(MessageClickListener.getInstance());
MessageListAdapter adapter = convInfo.adapter;
if( adapter == null ) {
adapter = new MessageListAdapter(convInfo.conv, parent.getContext());
convInfo.adapter = adapter;
}
list.setAdapter(adapter);
list.setSelection(adapter.getCount() - 1); // scroll to bottom
return list;
}
/**
* Remove the given view from the adapter and collection.
*/
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager)collection).removeView((View)view);
views.remove(position);
}
/**
* Get the title for the given position. Used by the {@link TitlePageIndicator}.
*/
@Override
public String getPageTitle(int position) {
Conversation conversation = getItem(position);
if( conversation.getType() == Conversation.TYPE_SERVER ) {
return server.getTitle();
} else {
return conversation.getName();
}
}
@Override
public int getColorAt(int position) {
Conversation conversation = getItem(position);
switch ( conversation.getStatus() ) {
case Conversation.STATUS_HIGHLIGHT:
return App.getColorScheme().getHighlight();
case Conversation.STATUS_MESSAGE:
return App.getColorScheme().getUserEvent();
case Conversation.STATUS_MISC:
return App.getColorScheme().getChannelEvent();
default:
return App.getColorScheme().getForeground();
}
}
@Override
public Boolean isGreaterSpecial(int position) {
for(int i = conversations.size()-1; i >position; i--) {
int status = getItem(i).getStatus();
if(status == Conversation.STATUS_HIGHLIGHT) return true;
}
return false;
}
@Override
public Boolean isLowerSpecial(int position) {
for( int i = 0; i < position; i++) {
int status = getItem(i).getStatus();
if(status == Conversation.STATUS_HIGHLIGHT) return true;
}
return false;
}
/**
* Get the state color for all conversations lower than the given position.
*/
@Override
public int getColorForLowerThan(int position) {
int color = COLOR_NONE;
for(int i = 0; i < position ; i++) {
int status = getItem(i).getStatus();
if (status == Conversation.STATUS_HIGHLIGHT) {
return App.getColorScheme().getHighlight();
} else if (color == COLOR_NONE && getColorAt(i) != COLOR_NONE) {
color = getColorAt(i);
}
}
return color;
}
/**
* Get the state color for all conversations greater than the given position.
*/
@Override
public int getColorForGreaterThan(int position) {
int color = COLOR_NONE;
for(int i = conversations.size()-1; i > position; i--) {
int status = getItem(i).getStatus();
if (status == Conversation.STATUS_HIGHLIGHT) {
return App.getColorScheme().getHighlight();
} else if (color == COLOR_NONE && getColorAt(i) != COLOR_NONE) {
color = getColorAt(i);
}
}
return COLOR_NONE;
}
}
| gpl-3.0 |
mapsquare/osm-contributor | src/main/java/io/jawg/osmcontributor/ui/events/type/PoiTypeDeletedEvent.java | 984 | /**
* Copyright (C) 2019 Takima
*
* This file is part of OSM Contributor.
*
* OSM Contributor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OSM Contributor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OSM Contributor. If not, see <http://www.gnu.org/licenses/>.
*/
package io.jawg.osmcontributor.ui.events.type;
import io.jawg.osmcontributor.model.entities.PoiType;
public class PoiTypeDeletedEvent extends BasePoiTypeEvent {
public PoiTypeDeletedEvent(PoiType poiType) {
super(poiType);
}
}
| gpl-3.0 |
jtracey/Signal-Android | test/unitTest/java/org/thoughtcrime/securesms/conversation/ConversationAdapterTest.java | 1436 | package org.thoughtcrime.securesms.conversation;
import android.database.Cursor;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.thoughtcrime.securesms.BaseUnitTest;
import org.thoughtcrime.securesms.conversation.ConversationAdapter;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
public class ConversationAdapterTest extends BaseUnitTest {
private Cursor cursor = mock(Cursor.class);
private ConversationAdapter adapter;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
adapter = new ConversationAdapter(context, cursor);
when(cursor.getColumnIndexOrThrow(anyString())).thenReturn(0);
}
@Test
@Ignore("TODO: Fix test")
public void testGetItemIdEquals() throws Exception {
when(cursor.getString(anyInt())).thenReturn(null).thenReturn("SMS::1::1");
long firstId = adapter.getItemId(cursor);
when(cursor.getString(anyInt())).thenReturn(null).thenReturn("MMS::1::1");
long secondId = adapter.getItemId(cursor);
assertNotEquals(firstId, secondId);
when(cursor.getString(anyInt())).thenReturn(null).thenReturn("MMS::2::1");
long thirdId = adapter.getItemId(cursor);
assertNotEquals(secondId, thirdId);
}
} | gpl-3.0 |
jesselix/zz-algorithms | algorithms-questions/src/main/java/li/jesse/leetcode/BestTimeToBuyAndSellStockII.java | 138 | package li.jesse.leetcode;
public class BestTimeToBuyAndSellStockII {
public int maxProfit(int[] prices) {
return 0;
}
}
| gpl-3.0 |
xiaoligit/hypersocket-framework | hypersocket-tests/src/test/java/com/hypersocket/tests/json/realms/NoPermissionTests.java | 2756 | package com.hypersocket.tests.json.realms;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hypersocket.auth.AuthenticationPermission;
import com.hypersocket.properties.json.PropertyItem;
import com.hypersocket.realm.json.RealmUpdate;
import com.hypersocket.tests.AbstractServerTest;
public class NoPermissionTests extends AbstractServerTest {
@BeforeClass
public static void logOn() throws Exception {
logOnNewUser(new String[] { AuthenticationPermission.LOGON
.getResourceKey() });
}
@AfterClass
public static void logOff() throws JsonParseException,
JsonMappingException, IOException {
logoff();
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmId() throws ClientProtocolException,
IOException {
doGet("/hypersocket/api/realms/realm/"
+ getSession().getCurrentRealm().getId());
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmList() throws ClientProtocolException,
IOException {
doGet("/hypersocket/api/realms/list");
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmsTable() throws ClientProtocolException,
IOException {
doGet("/hypersocket/api/realms/table");
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmsTemplate() throws ClientProtocolException,
IOException {
doGet("/hypersocket/api/realms/template/local");
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmPropertiesId()
throws ClientProtocolException, IOException {
doGet("/hypersocket/api/realms/realm/properties/"
+ getSession().getCurrentRealm().getId());
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmPost() throws ClientProtocolException,
IOException, IllegalStateException, URISyntaxException {
RealmUpdate realm = new RealmUpdate();
realm.setName("newRealm");
realm.setProperties(new PropertyItem[0]);
realm.setType("local");
doPostJson("/hypersocket/realms/realm", realm);
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmProviders() throws ClientProtocolException,
IOException {
doGet("/hypersocket/api/realms/providers");
}
@Test(expected = ClientProtocolException.class)
public void tryNoPermissionRealmDeleteId() throws ClientProtocolException,
IOException {
doDelete("/hypersocket/api/realms/realm/"
+ getSession().getCurrentRealm().getId());
}
}
| gpl-3.0 |
gunjankhandelwalsjsu/android-final | app/src/main/java/org/project/healthMeter/Scan/ZBarScannerView.java | 3452 | package org.project.healthMeter.Scan;
/**
* Created by rajeshkhandelwal on 9/10/15.
*/
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.text.TextUtils;
import android.util.AttributeSet;
import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import java.util.Collection;
import java.util.List;
public class ZBarScannerView extends BarcodeScannerView {
public interface ResultHandler {
public void handleResult(Result rawResult);
}
static {
System.loadLibrary("iconv");
}
private ImageScanner mScanner;
private List<BarcodeFormat> mFormats;
private ResultHandler mResultHandler;
public ZBarScannerView(Context context) {
super(context);
setupScanner();
}
public ZBarScannerView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setupScanner();
}
public void setFormats(List<BarcodeFormat> formats) {
mFormats = formats;
setupScanner();
}
public void setResultHandler(ResultHandler resultHandler) {
mResultHandler = resultHandler;
}
public Collection<BarcodeFormat> getFormats() {
if(mFormats == null) {
return BarcodeFormat.ALL_FORMATS;
}
return mFormats;
}
public void setupScanner() {
mScanner = new ImageScanner();
mScanner.setConfig(0, Config.X_DENSITY, 3);
mScanner.setConfig(0, Config.Y_DENSITY, 3);
mScanner.setConfig(Symbol.NONE, Config.ENABLE, 0);
for(BarcodeFormat format : getFormats()) {
mScanner.setConfig(format.getId(), Config.ENABLE, 1);
}
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = parameters.getPreviewSize();
int width = size.width;
int height = size.height;
if(DisplayUtils.getScreenOrientation(getContext()) == Configuration.ORIENTATION_PORTRAIT) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width;
width = height;
height = tmp;
data = rotatedData;
}
Image barcode = new Image(width, height, "Y800");
barcode.setData(data);
int result = mScanner.scanImage(barcode);
if (result != 0) {
stopCamera();
if(mResultHandler != null) {
SymbolSet syms = mScanner.getResults();
Result rawResult = new Result();
for (Symbol sym : syms) {
String symData = sym.getData();
if (!TextUtils.isEmpty(symData)) {
rawResult.setContents(symData);
rawResult.setBarcodeFormat(BarcodeFormat.getFormatById(sym.getType()));
break;
}
}
mResultHandler.handleResult(rawResult);
}
} else {
camera.setOneShotPreviewCallback(this);
}
}
} | gpl-3.0 |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/payments/preferences/viewholder/SeeAllViewHolder.java | 961 | package org.thoughtcrime.securesms.payments.preferences.viewholder;
import android.view.View;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.payments.preferences.PaymentsHomeAdapter;
import org.thoughtcrime.securesms.payments.preferences.model.SeeAll;
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder;
public class SeeAllViewHolder extends MappingViewHolder<SeeAll> {
private final PaymentsHomeAdapter.Callbacks callbacks;
private final View seeAllButton;
public SeeAllViewHolder(@NonNull View itemView, PaymentsHomeAdapter.Callbacks callbacks) {
super(itemView);
this.callbacks = callbacks;
this.seeAllButton = itemView.findViewById(R.id.payments_home_see_all_item_button);
}
@Override
public void bind(@NonNull SeeAll model) {
seeAllButton.setOnClickListener(v -> callbacks.onSeeAll(model.getPaymentType()));
}
}
| gpl-3.0 |
arielsiles/sisk1 | src/main/com/encens/khipus/model/employees/ExperienceType.java | 544 | package com.encens.khipus.model.employees;
/**
* Encens Team
*
* @author
* @version : WorkExperienceType, 26-11-2009 08:08:52 PM
*/
public enum ExperienceType {
LABORAL("ExperienceType.laboral"),
PROFESSOR("ExperienceType.professor");
private String resourceKey;
ExperienceType(String resourceKey) {
this.resourceKey = resourceKey;
}
public String getResourceKey() {
return resourceKey;
}
public void setResourceKey(String resourceKey) {
this.resourceKey = resourceKey;
}
}
| gpl-3.0 |
tobiasschuelke/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/LruCache.java | 512 | package org.sufficientlysecure.keychain.util;
import java.util.LinkedHashMap;
import java.util.Map;
// Source: http://stackoverflow.com/a/1953516
public class LruCache<A, B> extends LinkedHashMap<A, B> {
private final int maxEntries;
public LruCache(final int maxEntries) {
super(maxEntries + 1, 1.0f, true);
this.maxEntries = maxEntries;
}
@Override
protected boolean removeEldestEntry(final Map.Entry<A, B> eldest) {
return super.size() > maxEntries;
}
}
| gpl-3.0 |
tobiasstraub/bwinf-releases | BwInf 33 (2014-2015)/Runde 2/Aufgabe 2/msrd0/Source/Cone.java | 1239 | /*
* Cone
*
* Copyright (C) 2015 Dominic S. Meiser <meiserdo@web.de>
*
* This work is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or any later
* version.
*
* This work 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 version 2 and version 3 of the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bwinf33_2.aufgabe2;
import lombok.*;
@AllArgsConstructor
@RequiredArgsConstructor
@EqualsAndHashCode
@ToString(exclude = { "state" })
public class Cone
{
public static final int STANDING = 0b00_00_00_01;
public static final int OVERTHROWN = 0b00_00_00_10;
public static final int OVERTHROWING = 0b00_00_00_11;
@Getter @Setter
@NonNull
public double x, y;
@Getter @Setter
private int state = STANDING;
public boolean isOverthrown ()
{
return ((getState() & OVERTHROWN) != 0);
}
}
| gpl-3.0 |
eziosoft/MultiWii_EZ_GUI | src/com/ezio/multiwii/helpers/MyBase64.java | 3043 | /* MultiWii EZ-GUI
Copyright (C) <2012> Bartosz Szczygiel (eziosoft)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ezio.multiwii.helpers;
public class MyBase64 {
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static int[] toInt = new int[128];
static {
for(int i=0; i< ALPHABET.length; i++){
toInt[ALPHABET[i]]= i;
}
}
/**
* Translates the specified byte array into Base64 string.
*
* @param buf the byte array (not null)
* @return the translated Base64 string (not null)
*/
public static String encode(byte[] buf){
int size = buf.length;
char[] ar = new char[((size + 2) / 3) * 4];
int a = 0;
int i=0;
while(i < size){
byte b0 = buf[i++];
byte b1 = (i < size) ? buf[i++] : 0;
byte b2 = (i < size) ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
switch(size % 3){
case 1: ar[--a] = '=';
case 2: ar[--a] = '=';
}
return new String(ar);
}
/**
* Translates the specified Base64 string into a byte array.
*
* @param s the Base64 string (not null)
* @return the byte array (not null)
*/
public static byte[] decode(String s){
int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0;
byte[] buffer = new byte[s.length()*3/4 - delta];
int mask = 0xFF;
int index = 0;
for(int i=0; i< s.length(); i+=4){
int c0 = toInt[s.charAt( i )];
int c1 = toInt[s.charAt( i + 1)];
buffer[index++]= (byte)(((c0 << 2) | (c1 >> 4)) & mask);
if(index >= buffer.length){
return buffer;
}
int c2 = toInt[s.charAt( i + 2)];
buffer[index++]= (byte)(((c1 << 4) | (c2 >> 2)) & mask);
if(index >= buffer.length){
return buffer;
}
int c3 = toInt[s.charAt( i + 3 )];
buffer[index++]= (byte)(((c2 << 6) | c3) & mask);
}
return buffer;
}
} | gpl-3.0 |
parthiban-samykutti/soapRestWebService | springSoapWsSecurity/src/main/java/com/parthi/spring/ws/soap/interceptor/AccountMessageInterceptor.java | 2992 | package com.parthi.spring.ws.soap.interceptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.log4j.Logger;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.server.SoapEndpointInterceptor;
/**
* Intercepts the incoming and outgoing SOAP messages.
*
* @author Parthiban Samykutti
* @since 06/Oct/2016
*
*/
public class AccountMessageInterceptor implements SoapEndpointInterceptor {
private static final Logger LOG = Logger.getLogger(AccountMessageInterceptor.class);
/*
* (non-Javadoc)
*
* @see org.springframework.ws.server.EndpointInterceptor#handleRequest(org.
* springframework.ws.context.MessageContext, java.lang.Object)
*/
public boolean handleRequest(final MessageContext messageContext, final Object endpoint) throws Exception {
LOG.trace("AccountMessageInterceptor.handleRequest.....");
final File file = new File("..\\logs\\springSoapWs-request.xml");
if (!file.exists()) {
file.createNewFile();
}
final OutputStream outputStream = new FileOutputStream(file);
messageContext.getRequest().writeTo(outputStream);
LOG.trace("AccountMessageInterceptor.getPayloadSource: " + messageContext.getRequest().getPayloadSource());
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.ws.server.EndpointInterceptor#handleResponse(org.
* springframework.ws.context.MessageContext, java.lang.Object)
*/
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
LOG.trace("AccountMessageInterceptor.handleResponse.....");
final File file = new File("..\\logs\\springSoapWs-response.xml");
if (!file.exists()) {
file.createNewFile();
}
final OutputStream outputStream = new FileOutputStream(file);
messageContext.getResponse().writeTo(outputStream);
LOG.trace("AccountMessageInterceptor.getPayloadResult: " + messageContext.getRequest().getPayloadResult());
return true;
}
/*
* (non-Javadoc)
*
* @see org.springframework.ws.server.EndpointInterceptor#handleFault(org.
* springframework.ws.context.MessageContext, java.lang.Object)
*/
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.ws.server.EndpointInterceptor#afterCompletion(org.
* springframework.ws.context.MessageContext, java.lang.Object,
* java.lang.Exception)
*/
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
/*
* (non-Javadoc)
*
* @see
* org.springframework.ws.soap.server.SoapEndpointInterceptor#understands(
* org.springframework.ws.soap.SoapHeaderElement)
*/
public boolean understands(SoapHeaderElement header) {
return true;
}
}
| gpl-3.0 |
14mRh4X0r/Bukkit | src/main/java/org/bukkit/block/Dispenser.java | 416 | package org.bukkit.block;
/**
* Represents a dispenser.
*
* @author sk89q
*/
public interface Dispenser extends BlockState, ContainerBlock {
/**
* Attempts to dispense the contents of this block<br />
* <br />
* If the block is no longer a dispenser, this will return false
*
* @return true if successful, otherwise false
*/
public boolean dispense();
}
| gpl-3.0 |
chrberndt/ch-inofix-timetracker | timetracker-service/src/main/java/ch/inofix/timetracker/controller/TaskRecordExportController.java | 6991 | package ch.inofix.timetracker.controller;
import static ch.inofix.timetracker.internal.exportimport.util.ExportImportLifecycleConstants.EVENT_TASK_RECORDS_EXPORT_FAILED;
import static ch.inofix.timetracker.internal.exportimport.util.ExportImportLifecycleConstants.EVENT_TASK_RECORDS_EXPORT_STARTED;
import static ch.inofix.timetracker.internal.exportimport.util.ExportImportLifecycleConstants.EVENT_TASK_RECORDS_EXPORT_SUCCEEDED;
import static ch.inofix.timetracker.internal.exportimport.util.ExportImportLifecycleConstants.PROCESS_FLAG_TASK_RECORDS_EXPORT_IN_PROCESS;
import java.io.File;
import java.io.Serializable;
import java.util.Map;
import org.apache.commons.lang.time.StopWatch;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.liferay.exportimport.kernel.controller.ExportController;
import com.liferay.exportimport.kernel.controller.ExportImportController;
import com.liferay.exportimport.kernel.lar.ExportImportDateUtil;
import com.liferay.exportimport.kernel.lar.ExportImportHelperUtil;
import com.liferay.exportimport.kernel.lar.PortletDataContext;
import com.liferay.exportimport.kernel.lar.PortletDataContextFactoryUtil;
import com.liferay.exportimport.kernel.lifecycle.ExportImportLifecycleManager;
import com.liferay.exportimport.kernel.model.ExportImportConfiguration;
import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.DateRange;
import com.liferay.portal.kernel.util.MapUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.zip.ZipWriter;
import ch.inofix.timetracker.internal.exportimport.util.ExportImportThreadLocal;
import ch.inofix.timetracker.model.TaskRecord;
import ch.inofix.timetracker.service.TaskRecordLocalService;
/**
* @author Christian Berndt
* @created 2017-04-21 19:23
* @modified 2017-11-17 22:39
* @version 1.0.5
*/
@Component(
immediate = true,
property = { "model.class.name=ch.inofix.timetracker.model.TaskRecord" },
service = {
ExportImportController.class,
TaskRecordExportController.class
}
)
public class TaskRecordExportController extends BaseExportImportController implements ExportController {
public TaskRecordExportController() {
initXStream();
}
@Override
public File export(ExportImportConfiguration exportImportConfiguration) throws Exception {
PortletDataContext portletDataContext = null;
try {
ExportImportThreadLocal.setTaskRecordExportInProcess(true);
portletDataContext = getPortletDataContext(exportImportConfiguration);
exportImportConfiguration.getSettingsMap();
_exportImportLifecycleManager.fireExportImportLifecycleEvent(EVENT_TASK_RECORDS_EXPORT_STARTED,
getProcessFlag(), PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));
File file = doExport(portletDataContext);
ExportImportThreadLocal.setTaskRecordExportInProcess(false);
_exportImportLifecycleManager.fireExportImportLifecycleEvent(EVENT_TASK_RECORDS_EXPORT_SUCCEEDED,
getProcessFlag(), PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));
return file;
} catch (Throwable t) {
_log.error(t);
ExportImportThreadLocal.setTaskRecordExportInProcess(false);
_exportImportLifecycleManager.fireExportImportLifecycleEvent(EVENT_TASK_RECORDS_EXPORT_FAILED,
getProcessFlag(), PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext), t);
throw t;
}
}
protected File doExport(PortletDataContext portletDataContext) throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final StringBuilder sb = new StringBuilder();
sb.append("<TaskRecords>");
sb.append(StringPool.NEW_LINE);
ActionableDynamicQuery actionableDynamicQuery = _taskRecordLocalService.getActionableDynamicQuery();
actionableDynamicQuery.setGroupId(portletDataContext.getGroupId());
// TODO: process date-range of portletDataContext
actionableDynamicQuery.setPerformActionMethod(new ActionableDynamicQuery.PerformActionMethod<TaskRecord>() {
@Override
public void performAction(TaskRecord taskRecord) {
String xml = _xStream.toXML(taskRecord);
sb.append(xml);
sb.append(StringPool.NEW_LINE);
}
});
actionableDynamicQuery.performActions();
sb.append("</TaskRecords>");
if (_log.isInfoEnabled()) {
_log.info("Exporting taskRecords takes " + stopWatch.getTime() + " ms");
}
portletDataContext.addZipEntry("/TaskRecords.xml", sb.toString());
ZipWriter zipWriter = portletDataContext.getZipWriter();
return zipWriter.getFile();
}
protected PortletDataContext getPortletDataContext(ExportImportConfiguration exportImportConfiguration)
throws PortalException {
Map<String, Serializable> settingsMap = exportImportConfiguration.getSettingsMap();
long companyId = MapUtil.getLong(settingsMap, "companyId");
long sourceGroupId = MapUtil.getLong(settingsMap, "sourceGroupId");
String portletId = MapUtil.getString(settingsMap, "portletId");
Map<String, String[]> parameterMap = (Map<String, String[]>) settingsMap.get("parameterMap");
DateRange dateRange = ExportImportDateUtil.getDateRange(exportImportConfiguration);
ZipWriter zipWriter = ExportImportHelperUtil.getPortletZipWriter(portletId);
PortletDataContext portletDataContext = PortletDataContextFactoryUtil.createExportPortletDataContext(companyId,
sourceGroupId, parameterMap, dateRange.getStartDate(), dateRange.getEndDate(), zipWriter);
portletDataContext.setPortletId(portletId);
return portletDataContext;
}
protected int getProcessFlag() {
return PROCESS_FLAG_TASK_RECORDS_EXPORT_IN_PROCESS;
}
@Reference(unbind = "-")
protected void setExportImportLifecycleManager(ExportImportLifecycleManager exportImportLifecycleManager) {
_exportImportLifecycleManager = exportImportLifecycleManager;
}
@Reference(unbind = "-")
protected void setTaskRecordLocalService(TaskRecordLocalService taskRecordLocalService) {
_taskRecordLocalService = taskRecordLocalService;
}
private static final Log _log = LogFactoryUtil.getLog(TaskRecordExportController.class);
private ExportImportLifecycleManager _exportImportLifecycleManager;
private TaskRecordLocalService _taskRecordLocalService;
}
| gpl-3.0 |
GFI-Informatique/georchestra | extractorapp/src/main/java/org/georchestra/extractorapp/ws/extractor/KMLFeatureWriter.java | 2838 | /*
* Copyright (C) 2009 by the geOrchestra PSC
*
* This file is part of geOrchestra.
*
* geOrchestra is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* geOrchestra is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* geOrchestra. If not, see <http://www.gnu.org/licenses/>.
*/
package org.georchestra.extractorapp.ws.extractor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.kml.KML;
import org.geotools.kml.KMLConfiguration;
import org.geotools.xsd.Encoder;
import org.opengis.feature.simple.SimpleFeatureType;
/**
* This class implements the KML file writing strategy
*
* @author Florent Gravin
*
*/
final class KMLFeatureWriter extends FileFeatureWriter {
/**
* New instance of {@link OGRFeatureWriter}
*
* @param basedir output folder
* @param features input the set of Features to write
*/
public KMLFeatureWriter(File basedir, SimpleFeatureCollection features) {
super(basedir, features);
}
/**
*
* @return Format file extension
*/
protected String extension() {
return "kml";
}
/**
* Generates a vector files in the specified format
*
* @throws IOException
*/
@Override
public List<File> generateFiles() throws IOException {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
SimpleFeatureType schema = features.getSchema();
builder.setName(schema.getName());
File file = new File(basedir, builder.getName() + "." + extension());
try (FileOutputStream fop = new FileOutputStream(file)) {
Encoder encoder = new Encoder(new KMLConfiguration());
encoder.setIndenting(true);
encoder.encode(features, KML.kml, fop);
if (LOG.isDebugEnabled()) {
LOG.debug("Generated file: " + file.getAbsolutePath());
}
fop.flush();
return Collections.singletonList(file);
} catch (IOException e) {
final String message = "Failed generation: " + schema.getName() + " - " + e.getMessage();
LOG.error(message);
throw e;
}
}
}
| gpl-3.0 |
TFG-RL-Starcraft/TFGStarcraft | src/laberinto/actions/MoveUp.java | 380 | package laberinto.actions;
public class MoveUp extends LaberintoAction {
MoveUp(int value) {
super(value);
}
@Override
public void execute() {
// Current position
int posX = getState().getPosX();
int posY = getState().getPosY();
posY--;
//mueve la casilla y comprueba si es el final
if (esValida(posX, posY))
{
getGame().mover(posX, posY);
}
}
}
| gpl-3.0 |
borboton13/sisk13 | src/main/com/encens/khipus/service/employees/ChristmasPayrollService.java | 1012 | package com.encens.khipus.service.employees;
import com.encens.khipus.framework.service.GenericService;
import com.encens.khipus.model.employees.*;
import com.encens.khipus.model.finances.BankAccount;
import javax.ejb.Local;
import java.math.BigDecimal;
import java.util.Date;
/**
* @author
* @version 3.2
*/
@Local
public interface ChristmasPayrollService extends GenericService {
ChristmasPayroll buildChristmasPayroll(GeneratedPayroll generatedPayroll, GestionPayroll gestionPayroll,
Employee employee, Date initContractDate, BigDecimal salary,
int workedDays, ManagersPayroll novemberManagersPayroll,
BigDecimal septemberTotalIncome, BigDecimal octoberTotalIncome,
BigDecimal novemberTotalIncome, BigDecimal averageSalary,
BigDecimal contributableSalary, BankAccount bankAccount);
}
| gpl-3.0 |
pslusarz/gnubridge | src/main/java/org/gnubridge/core/bidding/Call.java | 753 | package org.gnubridge.core.bidding;
import org.gnubridge.core.Direction;
import org.gnubridge.core.deck.Trump;
public class Call {
private final Bid bid;
private final Direction direction;
public Call(Bid b, Direction d) {
bid = b;
direction = d;
}
public Bid getBid() {
return bid;
}
public Direction getDirection() {
return direction;
}
@Override
public String toString() {
return direction.toString() + ": " + bid;
}
public Trump getTrump() {
return bid.getTrump();
}
public boolean isPass() {
return new Pass().equals(bid);
}
public boolean pairMatches(Direction candidate) {
if (direction.equals(candidate) || direction.opposite().equals(candidate)) {
return true;
} else {
return false;
}
}
}
| gpl-3.0 |
TFG-RL-Starcraft/TFGStarcraft | src/laberinto/actions/LaberintoAction.java | 1002 | package laberinto.actions;
import laberinto.LaberintoState;
import laberinto.PresenterLaberinto;
import laberinto.VentanaLaberinto;
import q_learning.Action;
public abstract class LaberintoAction extends Action{
LaberintoAction(int value) {
super(value);
}
//auxiliary methods and variables for execute()
private VentanaLaberinto game;
private LaberintoState state;
// Implement the configureContext() method here because it's the same for all the Actions
public void configureContext() {
this.game = PresenterLaberinto.getInstance().getGame();
this.state = game.getEstadoActual();
}
public VentanaLaberinto getGame() {
return this.game;
}
public LaberintoState getState() {
return this.state;
}
protected boolean esValida(int x, int y) {
int ancho = PresenterLaberinto.getInstance().getAncho();
int alto = PresenterLaberinto.getInstance().getAlto();
return (0 <= x) && (x < ancho) &&
(0 <= y) && (y < alto) &&
!game.getCasilla(x, y).esPared();
}
}
| gpl-3.0 |
TheMurderer/keel | src/keel/Algorithms/SVM/SMO/supportVector/RegSMO.java | 27869 | /***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* RegSMO.java
* Copyright (C) 2006 University of Waikato, Hamilton, New Zealand
*
*/
package keel.Algorithms.SVM.SMO.supportVector;
import keel.Algorithms.SVM.SMO.core.Instances;
import keel.Algorithms.SVM.SMO.core.Option;
import keel.Algorithms.SVM.SMO.core.Utils;
import keel.Algorithms.SVM.SMO.core.TechnicalInformation;
import keel.Algorithms.SVM.SMO.core.TechnicalInformationHandler;
import keel.Algorithms.SVM.SMO.core.TechnicalInformation.Field;
import keel.Algorithms.SVM.SMO.core.TechnicalInformation.Type;
import java.util.Enumeration;
import java.util.Vector;
/**
<!-- globalinfo-start -->
* Implementation of SMO for support vector regression as described in :<br/>
* <br/>
* A.J. Smola, B. Schoelkopf (1998). A tutorial on support vector regression.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @misc{Smola1998,
* author = {A.J. Smola and B. Schoelkopf},
* note = {NeuroCOLT2 Technical Report NC2-TR-1998-030},
* title = {A tutorial on support vector regression},
* year = {1998}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -P <double>
* The epsilon for round-off error.
* (default 1.0e-12)</pre>
*
* <pre> -L <double>
* The epsilon parameter in epsilon-insensitive loss function.
* (default 1.0e-3)</pre>
*
* <pre> -W <double>
* The random number seed.
* (default 1)</pre>
*
<!-- options-end -->
*
* @author Remco Bouckaert (remco@cs.waikato.ac.nz,rrb@xm.co.nz)
* @version $Revision: 1.1 $
*/
public class RegSMO
extends RegOptimizer
implements TechnicalInformationHandler {
/** for serialization */
private static final long serialVersionUID = -7504070793279598638L;
/** tolerance parameter, smaller changes on alpha in inner loop will be ignored **/
protected double m_eps = 1.0e-12;
/** Precision constant for updating sets */
protected final static double m_Del = 1e-10; //1000 * Double.MIN_VALUE;
/** error cache containing m_error[i] = SVMOutput(i) - m_target[i] - m_b <br/>
* note, we don't need m_b in the cache, since if we do, we need to maintain
* it when m_b is updated */
double[] m_error;
/** alpha value for first candidate **/
protected double m_alpha1;
/** alpha* value for first candidate **/
protected double m_alpha1Star;
/** alpha value for second candidate **/
protected double m_alpha2;
/** alpha* value for second candidate **/
protected double m_alpha2Star;
/**
* default constructor
*/
public RegSMO() {
super();
}
/**
* Returns a string describing classifier
*
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Implementation of SMO for support vector regression as described "
+ "in :\n\n"
+ getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.MISC);
result.setValue(Field.AUTHOR, "A.J. Smola and B. Schoelkopf");
result.setValue(Field.TITLE, "A tutorial on support vector regression");
result.setValue(Field.NOTE, "NeuroCOLT2 Technical Report NC2-TR-1998-030");
result.setValue(Field.YEAR, "1998");
return result;
}
/**
* Returns an enumeration describing the available options
*
* @return an enumeration of all the available options
*/
public Enumeration listOptions() {
Vector result = new Vector();
result.addElement(new Option(
"\tThe epsilon for round-off error.\n"
+ "\t(default 1.0e-12)",
"P", 1, "-P <double>"));
Enumeration enm = super.listOptions();
while (enm.hasMoreElements()) {
result.addElement(enm.nextElement());
}
return result.elements();
}
/**
* Parses a given list of options. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -P <double>
* The epsilon for round-off error.
* (default 1.0e-12)</pre>
*
* <pre> -L <double>
* The epsilon parameter in epsilon-insensitive loss function.
* (default 1.0e-3)</pre>
*
* <pre> -W <double>
* The random number seed.
* (default 1)</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('P', options);
if (tmpStr.length() != 0) {
setEpsilon(Double.parseDouble(tmpStr));
} else {
setEpsilon(1.0e-12);
}
super.setOptions(options);
}
/**
* Gets the current settings of the classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
public String[] getOptions() {
int i;
Vector result;
String[] options;
result = new Vector();
options = super.getOptions();
for (i = 0; i < options.length; i++)
result.add(options[i]);
result.add("-P");
result.add("" + getEpsilon());
return (String[]) result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String epsilonTipText() {
return "The epsilon for round-off error (shouldn't be changed).";
}
/**
* Get the value of epsilon.
*
* @return Value of epsilon.
*/
public double getEpsilon() {
return m_eps;
}
/**
* Set the value of epsilon.
*
* @param v Value to assign to epsilon.
*/
public void setEpsilon(double v) {
m_eps = v;
}
/** initialize various variables before starting the actual optimizer
*
* @param data data set used for learning
* @throws Exception if something goes wrong
*/
protected void init(Instances data) throws Exception {
super.init(data);
//init error cache
m_error = new double[m_nInstances];
for (int i = 0; i < m_nInstances; i++) {
m_error[i] = -m_target[i];
}
}
/**
* wrap up various variables to save memeory and do some housekeeping after optimization
* has finished.
*
* @throws Exception if something goes wrong
*/
protected void wrapUp() throws Exception {
m_error = null;
super.wrapUp();
}
/**
* Finds optimal point on line constrained by first (i1) and second (i2)
* candidate. Parameters correspond to pseudocode (see technicalinformation)
*
* @param i1
* @param alpha1
* @param alpha1Star
* @param C1
* @param i2
* @param alpha2
* @param alpha2Star
* @param C2
* @param gamma
* @param eta
* @param deltaPhi
* @return
*/
protected boolean findOptimalPointOnLine(int i1, double alpha1, double alpha1Star, double C1,
int i2, double alpha2, double alpha2Star, double C2,
double gamma, double eta, double deltaPhi) {
if (eta <= 0) {
// this may happen due to numeric instability
// due to Mercer's condition, this should not happen, hence we give up
return false;
}
boolean case1 = false;
boolean case2 = false;
boolean case3 = false;
boolean case4 = false;
boolean finished = false;
// while !finished
// % this loop is passed at most three times
// % case variables needed to avoid attempting small changes twice
while (!finished) {
// if (case1 == 0) &&
// (alpha1 > 0 || (alpha1* == 0 && deltaPhi > 0)) &&
// (alpha2 > 0 || (alpha2* == 0 && deltaPhi < 0))
// compute L, H (wrt. alpha1, alpha2)
// if L < H
// a2 = alpha2 ? - deltaPhi/eta
// a2 = min(a2, H)
// a2 = max(L, a2)
// a1 = alpha1 ? - (a2 ? alpha2)
// update alpha1, alpha2 if change is larger than some eps
// else
// finished = 1
// endif
// case1 = 1;
if ((case1 == false) &&
(alpha1 > 0 || (alpha1Star == 0 && deltaPhi > 0)) &&
(alpha2 > 0 || (alpha2Star == 0 && deltaPhi < 0))) {
// compute L, H (wrt. alpha1, alpha2)
double L = Math.max(0, gamma - C1);
double H = Math.min(C2, gamma);
if (L < H) {
double a2 = alpha2 - deltaPhi / eta;
a2 = Math.min(a2, H);
a2 = Math.max(L, a2);
// To prevent precision problems
if (a2 > C2 - m_Del * C2) {
a2 = C2;
} else if (a2 <= m_Del * C2) {
a2 = 0;
}
double a1 = alpha1 - (a2 - alpha2);
if (a1 > C1 - m_Del * C1) {
a1 = C1;
} else if (a1 <= m_Del * C1) {
a1 = 0;
}
// update alpha1, alpha2 if change is larger than some eps
if (Math.abs(alpha1 - a1) > m_eps) {
deltaPhi += eta * (a2 - alpha2);
alpha1 = a1;
alpha2 = a2;
}
} else {
finished = true;
}
case1 = true;
}
// elseif (case2 == 0) &&
// (alpha1 > 0 || (alpha1* == 0 && deltaPhi > 2 epsilon)) &&
// (alpha2* > 0 || (alpha2 == 0 && deltaPhi > 2 epsilon))
// compute L, H (wrt. alpha1, alpha2*)
// if L < H
// a2 = alpha2* + (deltaPhi ?- 2 epsilon)/eta
// a2 = min(a2, H)
// a2 = max(L, a2)
// a1 = alpha1 + (a2 ? alpha2*)
// update alpha1, alpha2* if change is larger than some eps
// else
// finished = 1
// endif
// case2 = 1;
else if (
(case2 == false)
&& (alpha1 > 0 || (alpha1Star == 0 && deltaPhi > 2 * m_epsilon))
&& (alpha2Star > 0 || (alpha2 == 0 && deltaPhi > 2 * m_epsilon))) {
// compute L, H (wrt. alpha1, alpha2*)
double L = Math.max(0, -gamma);
double H = Math.min(C2, -gamma + C1);
if (L < H) {
double a2 = alpha2Star + (deltaPhi - 2 * m_epsilon) / eta;
a2 = Math.min(a2, H);
a2 = Math.max(L, a2);
// To prevent precision problems
if (a2 > C2 - m_Del * C2) {
a2 = C2;
} else if (a2 <= m_Del * C2) {
a2 = 0;
}
double a1 = alpha1 + (a2 - alpha2Star);
if (a1 > C1 - m_Del * C1) {
a1 = C1;
} else if (a1 <= m_Del * C1) {
a1 = 0;
}
// update alpha1, alpha2* if change is larger than some eps
if (Math.abs(alpha1 - a1) > m_eps) {
deltaPhi += eta * (-a2 + alpha2Star);
alpha1 = a1;
alpha2Star = a2;
}
} else {
finished = true;
}
case2 = true;
}
// elseif (case3 == 0) &&
// (alpha1* > 0 || (alpha1 == 0 && deltaPhi < -2 epsilon)) &&
// (alpha2 > 0 || (alpha2* == 0 && deltaPhi < -2 epsilon))
// compute L, H (wrt. alpha1*, alpha2)
// if L < H
// a2 = alpha2 ?- (deltaPhi ?+ 2 epsilon)/eta
// a2 = min(a2, H)
// a2 = max(L, a2)
// a1 = alpha1* + (a2 ? alpha2)
// update alpha1*, alpha2 if change is larger than some eps
// else
// finished = 1
// endif
// case3 = 1;
else if (
(case3 == false)
&& (alpha1Star > 0 || (alpha1 == 0 && deltaPhi < - 2 * m_epsilon))
&& (alpha2 > 0 || (alpha2Star == 0 && deltaPhi < - 2 * m_epsilon))) {
// compute L, H (wrt. alpha1*, alpha2)
double L = Math.max(0, gamma);
double H = Math.min(C2, C1 + gamma);
if (L < H) {
// note Smola's psuedocode has a minus, where there should be a plus in the following line, Keerthi's is correct
double a2 = alpha2 - (deltaPhi + 2 * m_epsilon) / eta;
a2 = Math.min(a2, H);
a2 = Math.max(L, a2);
// To prevent precision problems
if (a2 > C2 - m_Del * C2) {
a2 = C2;
} else if (a2 <= m_Del * C2) {
a2 = 0;
}
double a1 = alpha1Star + (a2 - alpha2);
if (a1 > C1 - m_Del * C1) {
a1 = C1;
} else if (a1 <= m_Del * C1) {
a1 = 0;
}
// update alpha1*, alpha2 if change is larger than some eps
if (Math.abs(alpha1Star - a1) > m_eps) {
deltaPhi += eta * (a2 - alpha2);
alpha1Star = a1;
alpha2 = a2;
}
} else {
finished = true;
}
case3 = true;
}
// elseif (case4 == 0) &&
// (alpha1* > 0 || (alpha1 == 0 && deltaPhi < 0)) &&
// (alpha2* > 0 || (alpha2 == 0 && deltaPhi > 0))
// compute L, H (wrt. alpha1*, alpha2*)
// if L < H
// a2 = alpha2* + deltaPhi/eta
// a2 = min(a2, H)
// a2 = max(L, a2)
// a1 = alpha1* ? (a2 ? alpha2*)
// update alpha1*, alpha2* if change is larger than some eps
// else
// finished = 1
// endif
// case4 = 1;
// else
// finished = 1
// endif
else if ((case4 == false) &&
(alpha1Star > 0 || (alpha1 == 0 && deltaPhi < 0)) &&
(alpha2Star > 0 || (alpha2 == 0 && deltaPhi > 0))) {
// compute L, H (wrt. alpha1*, alpha2*)
double L = Math.max(0, -gamma - C1);
double H = Math.min(C2, -gamma);
if (L < H) {
double a2 = alpha2Star + deltaPhi / eta;
a2 = Math.min(a2, H);
a2 = Math.max(L, a2);
// To prevent precision problems
if (a2 > C2 - m_Del * C2) {
a2 = C2;
} else if (a2 <= m_Del * C2) {
a2 = 0;
}
double a1 = alpha1Star - (a2 - alpha2Star);
if (a1 > C1 - m_Del * C1) {
a1 = C1;
} else if (a1 <= m_Del * C1) {
a1 = 0;
}
// update alpha1*, alpha2* if change is larger than some eps
if (Math.abs(alpha1Star - a1) > m_eps) {
deltaPhi += eta * (-a2 + alpha2Star);
alpha1Star = a1;
alpha2Star = a2;
}
} else {
finished = true;
}
case4 = true;
} else {
finished = true;
}
// update deltaPhi
// using 4.36 from Smola's thesis:
// deltaPhi = deltaPhi - eta * ((alpha1New-alpha1StarNew)-(alpha1-alpha1Star));
// the update is done inside the loop, saving us to remember old values of alpha1(*)
//deltaPhi += eta * ((alpha2 - alpha2Star) - dAlpha2Old);
//dAlpha2Old = (alpha2 - alpha2Star);
// endwhile
}
if (Math.abs(alpha1 - m_alpha[i1]) > m_eps
|| Math.abs(alpha1Star - m_alphaStar[i1]) > m_eps
|| Math.abs(alpha2 - m_alpha[i2]) > m_eps
|| Math.abs(alpha2Star - m_alphaStar[i2]) > m_eps) {
if (alpha1 > C1 - m_Del * C1) {
alpha1 = C1;
} else if (alpha1 <= m_Del * C1) {
alpha1 = 0;
}
if (alpha1Star > C1 - m_Del * C1) {
alpha1Star = C1;
} else if (alpha1Star <= m_Del * C1) {
alpha1Star = 0;
}
if (alpha2 > C2 - m_Del * C2) {
alpha2 = C2;
} else if (alpha2 <= m_Del * C2) {
alpha2 = 0;
}
if (alpha2Star > C2 - m_Del * C2) {
alpha2Star = C2;
} else if (alpha2Star <= m_Del * C2) {
alpha2Star = 0;
}
// store new alpha's
m_alpha[i1] = alpha1;
m_alphaStar[i1] = alpha1Star;
m_alpha[i2] = alpha2;
m_alphaStar[i2] = alpha2Star;
// update supportvector set
if (alpha1 != 0 || alpha1Star != 0){
if (!m_supportVectors.contains(i1)) {
m_supportVectors.insert(i1);
}
} else {
m_supportVectors.delete(i1);
}
if (alpha2 != 0 || alpha2Star != 0){
if (!m_supportVectors.contains(i2)) {
m_supportVectors.insert(i2);
}
} else {
m_supportVectors.delete(i2);
}
return true;
}
return false;
}
/**
* takeStep method from pseudocode.
* Parameters correspond to pseudocode (see technicalinformation)
*
* @param i1
* @param i2
* @param alpha2
* @param alpha2Star
* @param phi2
* @return
* @throws Exception
*/
protected int takeStep(int i1, int i2, double alpha2, double alpha2Star, double phi2) throws Exception {
// if (i1 == i2) return 0
if (i1 == i2) {
return 0;
}
double C1 = m_C * m_data.instance(i1).weight();
double C2 = m_C * m_data.instance(i2).weight();
// alpha1, alpha1* = Lagrange multipliers for i1
// y1 = target[i1]
// phi1 = SVM output on point[i1] ? y1 (in error cache)
double alpha1 = m_alpha[i1];
double alpha1Star = m_alphaStar[i1];
double y1 = m_target[i1];
double phi1 = m_error[i1];
// k11 = kernel(point[i1],point[i1])
// k12 = kernel(point[i1],point[i2])
// k22 = kernel(point[i2],point[i2])
// eta = 2*k12? - k11? - k22
// gamma = alpha1 ?- alpha1* + alpha2 ?- alpha2*
double k11 = m_kernel.eval(i1, i1, m_data.instance(i1));
double k12 = m_kernel.eval(i1, i2, m_data.instance(i1));
double k22 = m_kernel.eval(i2, i2, m_data.instance(i2));
double eta = -2 * k12 + k11 + k22; // note, Smola's psuedocode has signs swapped, Keerthi's doesn't
if (eta < 0) {
// this may happen due to numeric instability
// due to Mercer's condition, this should not happen, hence we give up
return 0;
}
double gamma = alpha1 - alpha1Star + alpha2 - alpha2Star;
// % we assume eta < 0. otherwise one has to repeat the complete
// % reasoning similarly (compute objective function for L and H
// % and decide which one is largest
// case1 = case2 = case3 = case4 = finished = 0
// alpha1old = alpha1, alpha1old* = alpha1*
// alpha2old = alpha2, alpha2old* = alpha2*
// deltaPhi = phi1 ?- phi2
double alpha1old = alpha1;
double alpha1Starold = alpha1Star;
double alpha2old = alpha2;
double alpha2Starold = alpha2Star;
double deltaPhi = phi2 - phi1;
if (findOptimalPointOnLine(i1, alpha1, alpha1Star, C1, i2, alpha2, alpha2Star, C2, gamma, eta, deltaPhi)) {
alpha1 = m_alpha[i1];
alpha1Star = m_alphaStar[i1];
alpha2 = m_alpha[i2];
alpha2Star = m_alphaStar[i2];
// Update error cache using new Lagrange multipliers
double dAlpha1 = alpha1 - alpha1old - (alpha1Star - alpha1Starold);
double dAlpha2 = alpha2 - alpha2old - (alpha2Star - alpha2Starold);
for (int j = 0; j < m_nInstances; j++) {
if ((j != i1) && (j != i2)/* && m_error[j] != MAXERR*/) {
m_error[j] += dAlpha1 * m_kernel.eval(i1, j, m_data.instance(i1)) + dAlpha2 * m_kernel.eval(i2, j, m_data.instance(i2));
}
}
m_error[i1] += dAlpha1 * k11 + dAlpha2 * k12;
m_error[i2] += dAlpha1 * k12 + dAlpha2 * k22;
// Update threshold to reflect change in Lagrange multipliers
double b1 = Double.MAX_VALUE;
double b2 = Double.MAX_VALUE;
if ((0 < alpha1 && alpha1 < C1) || (0 < alpha1Star && alpha1Star < C1) ||(0 < alpha2 && alpha2 < C2) || (0 < alpha2Star && alpha2Star < C2)) {
if (0 < alpha1 && alpha1 < C1) {
b1 = m_error[i1] - m_epsilon;
} else if (0 < alpha1Star && alpha1Star < C1) {
b1 = m_error[i1] + m_epsilon;
}
if (0 < alpha2 && alpha2 < C2) {
b2 = m_error[i2] - m_epsilon;
} else if (0 < alpha2Star && alpha2Star < C2) {
b2 = m_error[i2] + m_epsilon;
}
if (b1 < Double.MAX_VALUE) {
m_b = b1;
if (b2 < Double.MAX_VALUE) {
m_b = (b1 + b2) / 2.0;
}
} else if (b2 < Double.MAX_VALUE) {
m_b = b2;
}
} else if (m_b == 0) {
// both alpha's are on the boundary, and m_b is not initialized
m_b = (m_error[i1] + m_error[i2])/2.0;
}
// if changes in alpha1(*), alpha2(*) are larger than some eps
// return 1
// else
// return 0
// endif
return 1;
} else {
return 0;
}
// endprocedure
}
/**
* examineExample method from pseudocode.
* Parameters correspond to pseudocode (see technicalinformation)
*
* @param i2
* @return
* @throws Exception
*/
protected int examineExample(int i2) throws Exception {
// procedure examineExample(i2)
// y2 = target[i2]
double y2 = m_target[i2];
// alpha2, alpha2* = Lagrange multipliers for i2
double alpha2 = m_alpha[i2];
double alpha2Star = m_alphaStar[i2];
// C2, C2* = Constraints for i2
double C2 = m_C;
double C2Star = m_C;
// phi2 = SVM output on point[i2] ? y2 (in error cache)
double phi2 = m_error[i2];
// phi2b contains the error, taking the offset in account
double phi2b = phi2 - m_b;
// if ((phi2 > epsilon && alpha2* < C2*) ||
// (phi2 < epsilon && alpha2* > 0 ) ||
// (-?phi2 > epsilon && alpha2 < C2 ) ||
// (?-phi2 > epsilon && alpha2 > 0 ))
if ((phi2b > m_epsilon && alpha2Star < C2Star)
|| (phi2b < m_epsilon && alpha2Star > 0)
|| (-phi2b > m_epsilon && alpha2 < C2)
|| (-phi2b > m_epsilon && alpha2 > 0)) {
// if (number of non?zero & non?C alpha > 1)
// i1 = result of second choice heuristic
// if takeStep(i1,i2) return 1
// endif
int i1 = secondChoiceHeuristic(i2);
if (i1 >= 0 && (takeStep(i1, i2, alpha2, alpha2Star, phi2) > 0)) {
return 1;
}
// loop over all non?zero and non?C alpha, random start
// i1 = identity of current alpha
// if takeStep(i1,i2) return 1
// endloop
for (i1 = 0; i1 < m_target.length; i1++) {
if ((m_alpha[i1] > 0 && m_alpha[i1] < m_C) || (m_alphaStar[i1] > 0 && m_alphaStar[i1] < m_C)) {
if (takeStep(i1, i2, alpha2, alpha2Star, phi2) > 0) {
return 1;
}
}
}
// loop over all possible i1, with random start
// i1 = loop variable
// if takeStep(i1,i2) return 1
// endloop
for (i1 = 0; i1 < m_target.length; i1++) {
if (takeStep(i1, i2, alpha2, alpha2Star, phi2) > 0) {
return 1;
}
}
// endif
}
// return 0
return 0;
// endprocedure
}
/**
* applies heuristic for finding candidate that is expected to lead to
* good gain when applying takeStep together with second candidate.
*
* @param i2 index of second candidate
* @return
*/
protected int secondChoiceHeuristic(int i2) {
// randomly select an index i1 (not equal to i2) with non?zero and non?C alpha, if any
for (int i = 0; i < 59; i++) {
int i1 = m_random.nextInt(m_nInstances);
if ((i1 != i2) && (m_alpha[i1] > 0 && m_alpha[i1] < m_C) || (m_alphaStar[i1] > 0 && m_alphaStar[i1] < m_C)) {
return i1;
}
}
return -1;
}
/**
* finds alpha and alpha* parameters that optimize the SVM target function
*
* @throws Exception
*/
public void optimize() throws Exception {
// main routine:
// initialize threshold to zero
// numChanged = 0
// examineAll = 1
// SigFig = -100
// LoopCounter = 0
int numChanged = 0;
int examineAll = 1;
int sigFig = -100;
int loopCounter = 0;
// while ((numChanged > 0 | examineAll) | (SigFig < 3))
while ((numChanged > 0 || (examineAll > 0)) | (sigFig < 3)) {
// LoopCounter++
// numChanged = 0;
loopCounter++;
numChanged = 0;
// if (examineAll)
// loop I over all training examples
// numChanged += examineExample(I)
// else
// loop I over examples where alpha is not 0 & not C
// numChanged += examineExample(I)
// endif
int numSamples = 0;
if (examineAll > 0) {
for (int i = 0; i < m_nInstances; i++) {
numChanged += examineExample(i);
}
} else {
for (int i = 0; i < m_target.length; i++) {
if ((m_alpha[i] > 0 && m_alpha[i] < m_C * m_data.instance(i).weight()) ||
(m_alphaStar[i] > 0 && m_alphaStar[i] < m_C * m_data.instance(i).weight())) {
numSamples++;
numChanged += examineExample(i);
}
}
}
//
// if (mod(LoopCounter, 2) == 0)
// MinimumNumChanged = max(1, 0.1*NumSamples)
// else
// MinimumNumChanged = 1
// endif
int minimumNumChanged = 1;
if (loopCounter % 2 == 0) {
minimumNumChanged = (int) Math.max(1, 0.1 * numSamples);
}
// if (examineAll == 1)
// examineAll = 0
// elseif (numChanged < MinimumNumChanged)
// examineAll = 1
// endif
if (examineAll == 1) {
examineAll = 0;
} else if (numChanged < minimumNumChanged) {
examineAll = 1;
}
// endwhile
if (loopCounter == 2500) {
break;
}
}
// endmain
}
/**
* learn SVM parameters from data using Smola's SMO algorithm.
* Subclasses should implement something more interesting.
*
* @param instances the data to learn from
* @throws Exception if something goes wrong
*/
public void buildClassifier(Instances instances) throws Exception {
// initialize variables
init(instances);
// solve optimization problem
optimize();
// clean up
wrapUp();
}
}
| gpl-3.0 |
frogocomics/WorldPainter | WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/plugins/CustomLayerProvider.java | 283 | package org.pepsoft.worldpainter.plugins;
import org.pepsoft.worldpainter.layers.CustomLayer;
import java.util.List;
/**
* Created by Pepijn Schmitz on 19-08-16.
*/
public interface CustomLayerProvider extends Plugin {
List<Class<? extends CustomLayer>> getCustomLayers();
} | gpl-3.0 |
jln-ho/sipdroid-pro | src/org/sipdroid/media/file/Mp3File.java | 3935 | /*
* Copyright (C) 2009 The Sipdroid Open Source Project
*
* This file is part of Sipdroid (http://www.sipdroid.org)
*
* Sipdroid is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.sipdroid.media.file;
import org.sipdroid.media.file.AudioFileInformations.FileType;
/**
* Abstract class for native implementations
*
* All native functions will be called through this class.
*
* Controlling the MPG123 library need to be done through the service
* AIDL interface!
*
*
*/
public class Mp3File extends AudioFile {
private static final int MPG123_OK = 0;
private static final int MPG123_NEW_FORMAT = -11;
static{
System.loadLibrary("mp3");
}
public Mp3File(String path, int sampleRate){
Mp3File.initLib(sampleRate);
Mp3File.initMP3(path);
this.fileInfo = getAudioInformations();
this.fileInfo.fileType = FileType.MP3;
}
public static boolean initLib(int sampleRate) {
return ninitLib(sampleRate);
}
public static void cleanupLib() {
ncleanupLib();
}
public static String getError() {
return ngetError();
}
public static int initMP3(String filename) {
return ninitMP3(filename);
}
public static void cleanupMP3() {
ncleanupMP3();
}
public static boolean setEQ(int channel, double vol) {
return nsetEQ(channel, vol);
}
public static void resetEQ() {
nresetEQ();
}
public static AudioFileInformations getAudioInformations() {
return ngetAudioInformations();
}
public static int decodeMP3(int bufferLen, short[] buffer) {
return ndecodeMP3(bufferLen, buffer);
}
public static void seekTo(int frames) {
nseekTo(frames);
}
/**
*
* @return
*/
private static native boolean ninitLib(int sampleRate);
/**
*
*/
private static native void ncleanupLib();
/**
*
* @return String explaining what went wrong
*/
private static native String ngetError();
/**
* Initialize one MP3 file
* @param filename
* @return MPG123_OK
*/
private static native int ninitMP3(String filename);
/**
* Cleanup all native needed resources for one MP3 file
*/
private static native void ncleanupMP3();
/**
*
* @param channel
* @param vol
* @return
*/
private static native boolean nsetEQ(int channel, double vol);
/**
*
*/
private static native void nresetEQ();
/**
*
* @return
*/
private static native AudioFileInformations ngetAudioInformations();
/**
* Read, decode and write PCM data to our java application
*
* @param bufferLen
* @param buffer
* @return
*/
private static native int ndecodeMP3(int bufferLen, short[] buffer);
/**
*
* @param frames
*/
private static native void nseekTo(int frames);
/**
* Our native MPEG (1,2 and 3) decoder library
*/
@Override
public boolean isSupported() {
return true;
}
@Override
protected boolean getFrame(short[] frameBuf) {
int code = ndecodeMP3(frameBuf.length * 2, frameBuf);
return code == MPG123_OK || code == MPG123_NEW_FORMAT;
}
@Override
public void cleanup() {
ncleanupMP3();
ncleanupLib();
}
}
| gpl-3.0 |
superzadeh/processdash | src/net/sourceforge/processdash/tool/bridge/ResourceCollectionInfo.java | 1948 | // Copyright (C) 2008 Tuma Solutions, LLC
// Process Dashboard - Data Automation Tool for high-maturity processes
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// Additional permissions also apply; see the README-license.txt
// file in the project root directory for more information.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
// The author(s) may be contacted at:
// processdash@tuma-solutions.com
// processdash-devel@lists.sourceforge.net
package net.sourceforge.processdash.tool.bridge;
import java.util.List;
public interface ResourceCollectionInfo {
/**
* Get a list of the resources known to this collection.
*/
public List<String> listResourceNames();
/**
* Return the timestamp when the named resource was last modified.
*
* @param resourceName
* the name of a resource
* @return the timestamp when the named resource was last modified, or 0 if
* no such resource is known to this object.
*/
public long getLastModified(String resourceName);
/**
* Return a checksum of the content of this resource
*
* @param resourceName
* the name of a resource
* @return the checksum of the named resource, or null if the resource does
* not exist or could not be read
*/
public Long getChecksum(String resourceName);
}
| gpl-3.0 |
usrflo/yajsync | src/main/com/github/perlundq/yajsync/channels/net/DuplexByteChannel.java | 1125 | /*
* Copyright (C) 2014 Per Lundqvist
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.perlundq.yajsync.channels.net;
import java.net.InetAddress;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.Principal;
public interface DuplexByteChannel extends ReadableByteChannel,
WritableByteChannel
{
InetAddress peerAddress();
boolean isPeerAuthenticated();
Principal peerPrincipal();
}
| gpl-3.0 |
kazoompa/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/report/event/ReportTemplateCreated.java | 584 | /*
* Copyright (c) 2021 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.report.event;
import org.obiba.opal.web.model.client.opal.ReportTemplateDto;
import com.gwtplatform.dispatch.annotation.GenEvent;
@GenEvent
public class ReportTemplateCreated {
ReportTemplateDto reportTemplate;
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/cpa/smg/SMGAbstractionFinder.java | 981 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.smg;
import java.util.Set;
public interface SMGAbstractionFinder {
public Set<SMGAbstractionCandidate> traverse(CLangSMG pSmg);
} | gpl-3.0 |
ajt986/QuIN | src/upkeep/clinvarimport/ClinvarTraitImportMain.java | 573 | package upkeep.clinvarimport;
import java.io.IOException;
import java.sql.SQLException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class ClinvarTraitImportMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ImportTraitSNP its = new ImportTraitSNP();
try {
String tablename = "clinvar.clinvar";
its.run(args[0], tablename);
} catch (ParserConfigurationException | SAXException | IOException | SQLException e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
OpenSilk/Orpheus | app/src/main/java/org/opensilk/music/ui2/welcome/TipsScreenPresenter.java | 1699 | /*
* Copyright (c) 2015 OpenSilk Productions LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opensilk.music.ui2.welcome;
import android.content.Context;
import android.os.Bundle;
import org.opensilk.common.flow.AppFlow;
import org.opensilk.music.R;
import org.opensilk.music.ui2.core.android.ActionBarOwner;
import javax.inject.Inject;
import javax.inject.Singleton;
import mortar.ViewPresenter;
/**
* Created by drew on 4/20/15.
*/
@Singleton
public class TipsScreenPresenter extends ViewPresenter<TipsView> {
final ActionBarOwner actionBarOwner;
@Inject
public TipsScreenPresenter(ActionBarOwner actionBarOwner) {
this.actionBarOwner = actionBarOwner;
}
@Override
protected void onLoad(Bundle savedInstanceState) {
super.onLoad(savedInstanceState);
actionBarOwner.setConfig(
new ActionBarOwner.Config.Builder()
.setTitle(R.string.demo_title)
.build()
);
}
void goBack(Context context) {
AppFlow.get(context).goBack();
}
}
| gpl-3.0 |
kazoompa/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/ui/celltable/MultilineTextRenderer.java | 848 | /*
* Copyright (c) 2021 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.ui.celltable;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
public class MultilineTextRenderer extends AbstractSafeHtmlRenderer<String> {
@Override
public SafeHtml render(String object) {
if(object == null || object.trim().isEmpty()) return new SafeHtmlBuilder().toSafeHtml();
return new SafeHtmlBuilder().appendEscapedLines(object).toSafeHtml();
}
} | gpl-3.0 |
makings/mst | src/org/qii/weiciyuan/support/http/HttpUtility.java | 1251 | package org.qii.weiciyuan.support.http;
import org.qii.weiciyuan.support.error.WeiboException;
import org.qii.weiciyuan.support.file.FileDownloaderHttpHelper;
import org.qii.weiciyuan.support.file.FileUploaderHttpHelper;
import java.util.Map;
public class HttpUtility {
private static HttpUtility httpUtility = new HttpUtility();
private HttpUtility() {
}
public static HttpUtility getInstance() {
return httpUtility;
}
public String executeNormalTask(HttpMethod httpMethod, String url, Map<String, String> param) throws WeiboException {
return new JavaHttpUtility().executeNormalTask(httpMethod, url, param);
}
public boolean executeDownloadTask(String url, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) {
return !Thread.currentThread().isInterrupted() && new JavaHttpUtility().doGetSaveFile(url, path, downloadListener);
}
public boolean executeUploadTask(String url, Map<String, String> param, String path, FileUploaderHttpHelper.ProgressListener listener) throws WeiboException {
return !Thread.currentThread().isInterrupted() && new JavaHttpUtility().doUploadFile(url, param, path, listener);
}
}
| gpl-3.0 |
Pr0grammer264589/silvertrout | source/silvertrout/plugins/versioncontroleater/VersionControlEater.java | 10487 | /* _______ __ __ _______ __
* | __|__| |.--.--.-----.----.|_ _|.----.-----.--.--.| |_
* |__ | | || | | -__| _| | | | _| _ | | || _|
* |_______|__|__| \___/|_____|__| |___| |__| |_____|_____||____|
*
* Copyright 2008 - Gustav Tiger, Henrik Steen and Gustav "Gussoh" Sohtell
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package silvertrout.plugins.versioncontroleater;
import java.util.ArrayList;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import silvertrout.commons.EscapeUtils;
import silvertrout.Channel;
import silvertrout.User;
// TODO: save config
/**
*
**
*/
public class VersionControlEater extends silvertrout.Plugin {
// Check interval (in minutes)
final int checkInterval = 3;
// Binary locations
final String binarySVN = "/usr/bin/svn";
final String binaryCVS = "/usr/local/cvs";
final String binaryGIT = "/usr/local/git";
// Prepository list
final ArrayList<Repository> reps = new ArrayList<Repository>();
// Thread list
final ArrayList<CheckThread> threads = new ArrayList<CheckThread>();
/**
*
*/
public class Repository {
String type;
String path;
String username;
String password;
String lastId;
Channel channel;
}
/**
*
*/
public class CheckThread extends Thread {
final ArrayList<String> messages = new ArrayList<String>();
Repository repository;
CheckThread(Repository r) {
repository = r;
}
// TODO: SVN; use xml instead?
// TODO: GIT, implement
// TODO: CVS, implement
public void run() {
// SVN
// =================================================================
// I reccommend using anonymous SVN, a public guest account with
// read only access or a public svn key. These are safe the safe
// choises. Other methods might not work or have security issues.
// Read on for more information about this.
//
//
// Tunneled SVN + SSH - This is only going to work with public keys.
// When using password open ssh opens a password input prompt in
// TTY. This is not trivial to solve, but a solution could be to use
// an external library like Trilead SSH or some other native Java
// code library.
//
// There might also be possible to directly access the TTYwith some
// kind of library or perhaps something that can be written from
// scratch.
//
// A third option might be to try to hack something together with
// SSH_ASKPASS and stuff. One would need to make sure there is no
// TTY present (no idea how to do that) and then set the SSH_ASKPASS
// and the DISPLAY environment variables to something.
//
//
// Authorization for SVN - This works well altough there might be a
// secrity issue with it. The password could be seen with a simple
// comamnd like 'ps' due to the fact that it is sent as an argument
// to the svn program.
//
//
// Ordinary anonymous SVN - No problem here.
//
//
//
if(repository.type.equals("SVN")) {
try {
ProcessBuilder pb = null;
if(repository.path.startsWith("svn+ssh")) {
pb = new ProcessBuilder(binarySVN, "log", repository.path, "--limit", "10", "--incremental");
} else if(repository.username != null && repository.password != null) {
pb = new ProcessBuilder(binarySVN, "log", repository.path, "--limit", "10", "--incremental",
"--username", repository.username, "--password", repository.password);
} else {
pb = new ProcessBuilder(binarySVN, "log", repository.path, "--limit", "10", "--incremental");
}
pb = pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String newLastId = null;
for(int item = 0; item < 10; item++) {
String line = reader.readLine();
if(line != null && line.equals("------------------------------------------------------------------------")) {
String info = reader.readLine();
String[] infoParts = info.split(" \\| ");
int rev = Integer.parseInt(infoParts[0].substring(1));
String user = infoParts[1];
String date = infoParts[2];
int lines = Integer.parseInt(infoParts[3].substring(0, infoParts[3].lastIndexOf(" ")));
String message = reader.readLine();
for(int i = 0; i < lines; i++) {
message += reader.readLine() + "\n";
}
// No last
if(repository.lastId == null) {
newLastId = String.valueOf(rev);
break;
} else {
if(Integer.parseInt(repository.lastId) < rev) {
if(newLastId == null)newLastId = String.valueOf(rev);
// New item! - TODO
messages.add("r" + rev + " - " + user + " - " + date
+ message + "\n");
} else {
break;
}
}
} else {
if(line != null) {
System.out.println("Error occured?:");
System.out.println(line);
}
break;
}
}
// Update last id (latest revision)
if(newLastId != null) {
repository.lastId = newLastId;
}
// Wait for program end
p.waitFor();
System.out.println(p.exitValue());
} catch(java.io.IOException e) {
e.printStackTrace();
} catch( java.lang.InterruptedException e) {
e.printStackTrace();
}
// Unsupported Version Control System
// =================================================================
} else {
messages.add("Unsupported repository type: " + repository.type);
}
}
}
/**
*
*/
public VersionControlEater() {
}
// TODO: load reps.. save reps?
@Override
public void onLoad(Map<String,String> settings) {
}
/**
* Check the specified repository for new commits. Creates a new
* CheckThread for the repository, adds it to the thread list and then
* starts it.
*
* @param repository The repository to check
*/
void checkRepository(Repository repository) {
CheckThread checkThread = new CheckThread(repository);
threads.add(checkThread);
checkThread.start();
}
/**
* Check all repositorys for new commits.
* @see checkRepository
*/
void checkRepositorys() {
for(Repository rep: reps) {
checkRepository(rep);
}
}
void checkDoneMessages() {
for(CheckThread ct: threads) {
// Thread is done:
if(!ct.isAlive()) {
// Print messages (if any)
if(!ct.messages.isEmpty()) {
ct.repository.channel.sendPrivmsg("New commit in repository:\n");
for(String message: ct.messages) {
ct.repository.channel.sendPrivmsg(message);
}
}
threads.remove(ct);
break;
}
}
}
/**
*
* @param type
* @param path
* @param username
* @param password
* @param channel
*/
public void addRepository(String type, String path, String username, String password, Channel channel) {
Repository r = new Repository();
r.type = type;
r.path = path;
r.username = username;
r.password = password;
r.lastId = null;
r.channel = channel;
reps.add(r);
}
// TODO: last commit, revision,
// TODO: more ideas?
// TODO: add
@Override
public void onPrivmsg(User from, Channel to, String message) {
// Add new repository
if(message.startsWith("!vce")) {
String[] params = message.split("\\s");
addRepository("SVN", params[1], null, null, to);
}
}
@Override
public void onTick(int t) {
System.out.print(".");
if(t % (60 * checkInterval) == 0) {
checkRepositorys();
}
checkDoneMessages();
}
}
| gpl-3.0 |
juergenchrist/smtinterpol | SMTInterpol/src/de/uni_freiburg/informatik/ultimate/smtinterpol/theory/linar/CompositeReason.java | 5229 | /*
* Copyright (C) 2009-2012 University of Freiburg
*
* This file is part of SMTInterpol.
*
* SMTInterpol is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SMTInterpol 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 SMTInterpol. If not, see <http://www.gnu.org/licenses/>.
*/
package de.uni_freiburg.informatik.ultimate.smtinterpol.theory.linar;
import java.util.Map.Entry;
import de.uni_freiburg.informatik.ultimate.logic.Rational;
import de.uni_freiburg.informatik.ultimate.smtinterpol.dpll.Literal;
public class CompositeReason extends LAReason {
private final LAReason[] mReasons;
private final Rational[] mCoeffs;
private final InfinitesimalNumber mExactBound;
public CompositeReason(LinVar var, InfinitesimalNumber bound, boolean isUpper,
LAReason[] reasons, Rational[] coeffs, LiteralReason lastLiteral) {
super(var, bound, isUpper, lastLiteral);
assert (lastLiteral != null);
mReasons = reasons;
mCoeffs = coeffs;
mExactBound = bound;
if (var.mIsInt) {
if (isUpper) {
mBound = bound.floor();
} else {
mBound = bound.ceil();
}
} else {
mBound = bound;
}
assert (!getVar().mIsInt || mBound.isIntegral());
}
@Override
public InfinitesimalNumber getExactBound() {
return mExactBound;
}
@Override
InfinitesimalNumber explain(Explainer explainer,
InfinitesimalNumber slack, Rational factor) {
// First check, if there is already a literal with a weaker bound
// that is strong enough to explain the conflict/unit clause.
// However, make sure that this literal was set before the literal
// for which we want to generate a unit clause.
//
// needToExplain is set to true, if there is a weaker literal
// that was not set before the current conflict/unit clause. Usually,
// this means that we want to generate a unit clause for such a
// weaker literal. Therefore, it does not make sense to create a
// composite literal.
boolean needToExplain = false;
if (isUpper()) {
final Entry<InfinitesimalNumber, BoundConstraint> nextEntry =
getVar().mConstraints.ceilingEntry(getBound());
if (nextEntry != null) {
final BoundConstraint nextBound = nextEntry.getValue();
if (nextBound.getDecideStatus() == nextBound
&& explainer.canExplainWith(nextBound)) {
final InfinitesimalNumber diff = nextBound.getBound().sub(getBound());
if (slack.compareTo(diff) > 0) {
explainer.addLiteral(nextBound.negate(), factor);
return slack.sub(diff);
}
} else {
needToExplain = true;
}
}
} else {
final Entry<InfinitesimalNumber, BoundConstraint> nextEntry =
getVar().mConstraints.lowerEntry(getBound());
if (nextEntry != null) {
final BoundConstraint nextBound = nextEntry.getValue();
if (nextBound.getDecideStatus() == nextBound.negate()
&& explainer.canExplainWith(nextBound)) {
final InfinitesimalNumber diff =
getBound().sub(nextBound.getInverseBound());
if (slack.compareTo(diff) > 0) {
explainer.addLiteral(nextBound, factor);
return slack.sub(diff);
}
} else {
needToExplain = true;
}
}
}
final InfinitesimalNumber diff = !getVar().mIsInt ? InfinitesimalNumber.ZERO // NOPMD
: isUpper()
? mExactBound.sub(getBound())
: getBound().sub(mExactBound);
final int decideLevel = explainer.getDecideLevel();
// Should we create a composite literal? We do this only, if there
// is not already a weaker usable bound (needToExplain is true), and
// if we do not have enough slack to avoid the composite literal
// completely or if the composite literal would appear on the same
// decideLevel (and therefore would be immediately removed anyway).
if (needToExplain
|| (slack.compareTo(diff) > 0
&& getLastLiteral().getDecideLevel() >= decideLevel)) {
// Here, we do not create a composite literal.
final boolean enoughSlack = slack.compareTo(diff) > 0;
if (!enoughSlack) {
// we have not have enough slack to just use the proof of
// the exact bound. Create a sub-annotation.
explainer.addAnnotation(this, factor);
return slack;
}
// Just explain the exact bound using the reason array.
slack = slack.sub(diff);
assert (slack.compareTo(InfinitesimalNumber.ZERO) > 0);
for (int i = 0; i < mReasons.length; i++) {
final Rational coeff = mCoeffs[i];
slack = slack.div(coeff.abs());
slack = mReasons[i].explain(explainer,
slack, factor.mul(coeff));
slack = slack.mul(coeff.abs());
assert (slack.compareTo(InfinitesimalNumber.ZERO) > 0);
}
return slack;
}
final Literal lit = explainer.createComposite(this);
assert (lit.getAtom().getDecideStatus() == lit);
explainer.addLiteral(lit.negate(), factor);
return slack;
}
}
| gpl-3.0 |
drugis/addis | application/src/main/java/org/drugis/addis/presentation/VariablePresentation.java | 4946 | /*
* This file is part of ADDIS (Aggregate Data Drug Information System).
* ADDIS is distributed from http://drugis.org/.
* Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen.
* Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels,
* Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel
* Reid.
* Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin
* Schimbinschi.
* Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter
* Reckman.
* Copyright © 2013 Gert van Valkenhoef, Joël Kuiper.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.drugis.addis.presentation;
import java.util.List;
import org.drugis.addis.entities.CategoricalVariableType;
import org.drugis.addis.entities.ContinuousVariableType;
import org.drugis.addis.entities.PopulationCharacteristic;
import org.drugis.addis.entities.RateVariableType;
import org.drugis.addis.entities.Study;
import org.drugis.addis.entities.Variable;
import org.drugis.addis.entities.VariableType;
import org.drugis.addis.gui.CategoryKnowledgeFactory;
import com.jgoodies.binding.PresentationModel;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.binding.list.ObservableList;
import com.jgoodies.binding.value.AbstractValueModel;
import com.jgoodies.binding.value.ValueModel;
@SuppressWarnings("serial")
public class VariablePresentation extends PresentationModel<Variable> implements LabeledPresentation {
private ContinuousVariableType d_continuousVariableType = new ContinuousVariableType();
private RateVariableType d_rateVariableType = new RateVariableType();
private CategoricalVariableType d_categoricalVariableType = new CategoricalVariableType();
private StudyListPresentation d_studyListPresentation;
public VariablePresentation(Variable bean, ObservableList<Study> studies, PresentationModelFactory pmf) {
super(bean);
if (bean.getVariableType() instanceof ContinuousVariableType) {
d_continuousVariableType = (ContinuousVariableType) bean.getVariableType();
}
if (bean.getVariableType() instanceof CategoricalVariableType) {
d_categoricalVariableType = (CategoricalVariableType) bean.getVariableType();
}
if (bean.getVariableType() instanceof RateVariableType) {
d_rateVariableType = (RateVariableType) bean.getVariableType();
}
d_studyListPresentation = new StudyListPresentation(studies);
}
public StudyListPresentation getStudyListPresentation() {
return d_studyListPresentation;
}
public AbstractValueModel getLabelModel() {
return new DefaultLabelModel(getBean());
}
public static String getEntityName(Variable om) throws IllegalArgumentException{
return CategoryKnowledgeFactory.getCategoryKnowledge(om.getClass()).getSingularCapitalized();
}
public String getCategoryName() throws IllegalArgumentException{
return getEntityName(getBean());
}
public ValueModel getTypeModel() {
return new PropertyAdapter<Variable>(getBean(), Variable.PROPERTY_VARIABLE_TYPE);
}
public ObservableList<String> getCategoriesListModel() {
assertCategorical();
return ((CategoricalVariableType)getBean().getVariableType()).getCategories();
}
private void assertCategorical() {
if (!(getBean().getVariableType() instanceof CategoricalVariableType))
throw new IllegalStateException(getBean() + " is not categorical");
}
public void addNewCategory (String category) {
assertCategorical();
List<String> catsList = d_categoricalVariableType.getCategories();
if (!catsList.contains(category))
catsList.add(category);
}
public VariableType[] getVariableTypes() {
if (getBean() instanceof PopulationCharacteristic) {
return new VariableType[] { d_continuousVariableType, d_rateVariableType, d_categoricalVariableType };
} else {
return new VariableType[] { d_continuousVariableType, d_rateVariableType };
}
}
public PresentationModel<ContinuousVariableType> getContinuousModel() {
return new PresentationModel<ContinuousVariableType>(d_continuousVariableType);
}
public PresentationModel<CategoricalVariableType> getCategoricalModel() {
return new PresentationModel<CategoricalVariableType>(d_categoricalVariableType);
}
public PresentationModel<RateVariableType> getRateModel() {
return new PresentationModel<RateVariableType>(d_rateVariableType);
}
}
| gpl-3.0 |
TheRoss8/IT | StopFinderBinaryTree/src/Test.java | 696 | import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
try {
Map map = new Map("stops.txt");
System.out.println("\tACTV stops finder");
Scanner in = new Scanner(System.in);
System.out.print("Input latitude: ");
double latitude = in.nextDouble();
System.out.print("Input longitude: ");
double longitude = in.nextDouble();
System.out.println("\nYou are near:\n" + map.search(latitude, longitude).toString());
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
}
}
| gpl-3.0 |
Lucas-C/hesperides | core/presentation/src/main/java/org/hesperides/core/presentation/io/platforms/properties/PlatformPasswordsOutput.java | 2941 | /*
*
* This file is part of the Hesperides distribution.
* (https://github.com/voyages-sncf-technologies/hesperides)
* Copyright (c) 2016 VSCT.
*
* Hesperides is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 3.
*
* Hesperides is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.hesperides.core.presentation.io.platforms.properties;
import lombok.Value;
import org.hesperides.core.domain.platforms.queries.views.properties.PlatformPropertiesView;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Value
public class PlatformPasswordsOutput {
String applicationName;
String platformName;
boolean isProductionPlatform;
List<DeployedModule> deployedModules;
public PlatformPasswordsOutput(PlatformPropertiesView platform) {
applicationName = platform.getApplicationName();
platformName = platform.getPlatformName();
isProductionPlatform = platform.isProductionPlatform();
deployedModules = DeployedModule.fromViews(platform.getDeployedModules());
}
public static List<PlatformPasswordsOutput> fromViews(List<PlatformPropertiesView> platformsPasswords) {
return platformsPasswords.stream()
.map(PlatformPasswordsOutput::new)
.collect(toList());
}
@Value
public static class DeployedModule {
String propertiesPath;
boolean isArchivedModule;
List<Password> passwords;
public DeployedModule(PlatformPropertiesView.DeployedModule deployedModule) {
propertiesPath = deployedModule.getPropertiesPath();
isArchivedModule = deployedModule.isArchivedModule();
passwords = Password.fromViews(deployedModule.getProperties());
}
public static List<DeployedModule> fromViews(List<PlatformPropertiesView.DeployedModule> deployedModules) {
return deployedModules.stream().map(DeployedModule::new).collect(toList());
}
}
@Value
public static class Password {
String propertyName;
String propertyValue;
public Password(PlatformPropertiesView.Property password) {
propertyName = password.getName();
propertyValue = password.getValue();
}
public static List<Password> fromViews(List<PlatformPropertiesView.Property> passwords) {
return passwords.stream()
.map(Password::new)
.collect(toList());
}
}
}
| gpl-3.0 |
dewtx29/my_game_ai | my_game_ai/ann/test_graphic_radius/src/TestGraphic/GameView.java | 4912 | // I.Love(I.Love(you+1))
// Copyright (C) 2016 Mr.Patiphat Mana-u-krid (Dew)
// E-mail : dewtx29@gmail.com
// All rights reserved
package TestGraphic;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import print_api.r;
public class GameView extends JPanel implements KeyListener, ActionListener, MouseListener, ComponentListener, MouseMotionListener , ResizeEventInterface{
private static final long serialVersionUID = 1L;
private ResizeEventHost resizeEventHost = new ResizeEventHost();
private BufferedImage bImage;
private BufferedImage pngCredit = null;
private SpriteNN spriteCredit = null;
private Render render = null;
public static int mousePosX = 0;
public static int mousePosY = 0;
private boolean isRunning = true;
public static void main(String abc[]) {
Render render = new Render();
//GameView mv = new GameView(render);
GameLoopThread glt = new GameLoopThread(render.mainView);
Thread th3 = new Thread(glt);
th3.start();
// Thread th = new Thread(mv);
// th.start();
// Thread th2 = new Thread(render);
// th2.start();
}
public GameView(Render render) {
this.render = render;
this.setSize(Render.renderWidth, Render.renderHeight);
this.bImage = new BufferedImage(this.getWidth(), this.getHeight(),
BufferedImage.TYPE_INT_RGB);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.addComponentListener(this);
this.addKeyListener(this);
this.setVisible(true);
this.spriteCredit = new SpriteNN(this);
// add resize Event
this.resizeEventHost.addListener(this.spriteCredit);
this.resizeEventHost.resizeEvent(Render.renderWidth,
Render.renderHeight);
}
@Override
public void actionPerformed(ActionEvent ae) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentResized(ComponentEvent e) {
Render.renderWidth = e.getComponent().getWidth();
Render.renderHeight = e.getComponent().getHeight();
this.resizeEventHost.resizeEvent(Render.renderWidth,
Render.renderHeight);
r.pl("resizing " + Render.renderWidth + " , " + Render.renderHeight);
}
@Override
public void componentShown(ComponentEvent e) {
}
public Render getRender() {
return this.render;
}
public boolean getRunning() {
return this.isRunning;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
mousePosX = x;
mousePosY = y;
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
protected void paintComponent(Graphics g) {
// super.paint(g);
this.bImage = new BufferedImage(this.getWidth(), this.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = this.bImage.createGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, Render.renderWidth, Render.renderHeight);
g2.setColor(Color.BLACK);
// g2.drawImage(this.pngBlocksTest2, 150, 50, null);
try {
this.spriteCredit.onDraw(g2);
}
catch (NullPointerException e) {
// r.pl(e.getMessage());
}
g.drawImage(this.bImage, 0, 0, null);
// g.dispose();
}
public void run() {
r.pl("<CreditView> thread start");
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
this.resizeEventHost.resizeEvent(Render.renderWidth,
Render.renderHeight);
while (true) {
r.pl("gameview thread");
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
// r.pl("credit ... ");
if (this.isRunning == true) {
this.repaint();
}
else {
r.pl("<CreditView> thread break");
break;
}
}
}
public void setRunning(boolean isRunnable) {
this.isRunning = isRunnable;
}
@Override
public void resizeEvent(int x, int y) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
r.pl("key press " + e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
| gpl-3.0 |
jennparise/openmrs-module-legacyui | omod/src/test/java/org/openmrs/web/controller/concept/ConceptProposalFormControllerTest.java | 6086 | /**
* 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/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.web.controller.concept;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.Assert;
import org.junit.Test;
import org.openmrs.Concept;
import org.openmrs.ConceptProposal;
import org.openmrs.api.ConceptService;
import org.openmrs.api.ObsService;
import org.openmrs.api.context.Context;
import org.openmrs.test.Verifies;
import org.openmrs.web.test.BaseModuleWebContextSensitiveTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
public class ConceptProposalFormControllerTest extends BaseModuleWebContextSensitiveTest {
/**
* @see ConceptProposalFormController#onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)
*/
@Test
@Verifies(value = "should create a single unique synonym and obs for all similar proposals", method = "onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)")
public void onSubmit_shouldCreateASingleUniqueSynonymAndObsForAllSimilarProposals() throws Exception {
executeDataSet("org/openmrs/api/include/ConceptServiceTest-proposals.xml");
ConceptService cs = Context.getConceptService();
ObsService os = Context.getObsService();
final Integer conceptproposalId = 5;
ConceptProposal cp = cs.getConceptProposal(conceptproposalId);
Concept obsConcept = cp.getObsConcept();
Concept conceptToMap = cs.getConcept(5);
Locale locale = Locale.ENGLISH;
//sanity checks
Assert.assertFalse(conceptToMap.hasName(cp.getOriginalText(), locale));
Assert.assertEquals(0, os.getObservationsByPersonAndConcept(cp.getEncounter().getPatient(), obsConcept).size());
List<ConceptProposal> proposals = cs.getConceptProposals(cp.getOriginalText());
Assert.assertEquals(5, proposals.size());
for (ConceptProposal conceptProposal : proposals) {
Assert.assertNull(conceptProposal.getObs());
}
// set up the controller
ConceptProposalFormController controller = (ConceptProposalFormController) applicationContext
.getBean("conceptProposalForm");
controller.setApplicationContext(applicationContext);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockHttpSession(null));
request.setMethod("POST");
request.addParameter("conceptProposalId", conceptproposalId.toString());
request.addParameter("finalText", cp.getOriginalText());
request.addParameter("conceptId", conceptToMap.getConceptId().toString());
request.addParameter("conceptNamelocale", locale.toString());
request.addParameter("action", "");
request.addParameter("actionToTake", "saveAsSynonym");
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = controller.handleRequest(request, response);
assertNotNull(mav);
assertTrue(mav.getModel().isEmpty());
Assert.assertEquals(cp.getOriginalText(), cp.getFinalText());
Assert.assertTrue(conceptToMap.hasName(cp.getOriginalText(), locale));
Assert.assertNotNull(cp.getObs());
//Obs should have been created for the 2 proposals with same text, obsConcept but different encounters
Assert.assertEquals(2, os.getObservationsByPersonAndConcept(cp.getEncounter().getPatient(), obsConcept).size());
//The proposal with a different obs concept should have been skipped
proposals = cs.getConceptProposals(cp.getFinalText());
Assert.assertEquals(1, proposals.size());
Assert.assertEquals(21, proposals.get(0).getObsConcept().getConceptId().intValue());
}
/**
* @see ConceptProposalFormController#onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)
*/
@Test
@Verifies(value = "should work properly for country locales", method = "onSubmit(HttpServletRequest,HttpServletResponse,Object,BindException)")
public void onSubmit_shouldWorkProperlyForCountryLocales() throws Exception {
executeDataSet("org/openmrs/api/include/ConceptServiceTest-proposals.xml");
ConceptService cs = Context.getConceptService();
final Integer conceptproposalId = 5;
ConceptProposal cp = cs.getConceptProposal(conceptproposalId);
Concept conceptToMap = cs.getConcept(4);
Locale locale = new Locale("en", "GB");
Assert.assertFalse(conceptToMap.hasName(cp.getOriginalText(), locale));
ConceptProposalFormController controller = (ConceptProposalFormController) applicationContext
.getBean("conceptProposalForm");
controller.setApplicationContext(applicationContext);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockHttpSession(null));
request.setMethod("POST");
request.addParameter("conceptProposalId", conceptproposalId.toString());
request.addParameter("finalText", cp.getOriginalText());
request.addParameter("conceptId", conceptToMap.getConceptId().toString());
request.addParameter("conceptNamelocale", locale.toString());
request.addParameter("action", "");
request.addParameter("actionToTake", "saveAsSynonym");
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mav = controller.handleRequest(request, response);
assertNotNull(mav);
assertTrue(mav.getModel().isEmpty());
Assert.assertEquals(cp.getOriginalText(), cp.getFinalText());
Assert.assertTrue(conceptToMap.hasName(cp.getOriginalText(), locale));
}
}
| mpl-2.0 |
fayder/restcountries | src/main/java/eu/fayder/restcountries/domain/BaseCountry.java | 1938 | package eu.fayder.restcountries.domain;
import java.util.List;
public class BaseCountry {
protected String name;
private List<String> topLevelDomain;
protected String alpha2Code;
private String alpha3Code;
private List<String> callingCodes;
protected String capital;
private List<String> altSpellings;
protected String region;
protected String subregion;
protected Integer population;
private List<Double> latlng;
private String demonym;
private Double area;
protected Double gini;
private List<String> timezones;
protected List<String> borders;
protected String nativeName;
private String numericCode;
public String getName() {
return name;
}
public List<String> getTopLevelDomain() {
return topLevelDomain;
}
public String getAlpha2Code() {
return alpha2Code;
}
public String getAlpha3Code() {
return alpha3Code;
}
public List<String> getCallingCodes() {
return callingCodes;
}
public String getCapital() {
return capital;
}
public List<String> getAltSpellings() {
return altSpellings;
}
public String getRegion() {
return region;
}
public String getSubregion() {
return subregion;
}
public Integer getPopulation() {
return population;
}
public List<Double> getLatlng() {
return latlng;
}
public String getDemonym() {
return demonym;
}
public Double getArea() {
return area;
}
public Double getGini() {
return gini;
}
public List<String> getTimezones() {
return timezones;
}
public List<String> getBorders() {
return borders;
}
public String getNativeName() {
return nativeName;
}
public String getNumericCode() {
return numericCode;
}
}
| mpl-2.0 |
helicaldev/DataQuality | PCNI/src/main/java/com/helicaltech/pcni/exceptions/ImproperXMLConfigurationException.java | 1198 | package com.helicaltech.pcni.exceptions;
/**
* Thrown when the setting.xml in the System/Admin directory is mal formed or
* consists or inadequate information
*
* @author Rajasekhar
* @since 1.0
*/
public class ImproperXMLConfigurationException extends Exception {
private static final long serialVersionUID = 1L;
/**
* No-Arg constructor
*/
public ImproperXMLConfigurationException() {
super();
}
/**
* Convenient constructor that explains the exception with a user provided
* message, and cause
*
* @param message
* user provided message
* @param cause
* The cause of the exception
*/
public ImproperXMLConfigurationException(String message, Throwable cause) {
super(message, cause);
}
/**
* Convenient constructor that explains the exception with a user provided
* message
*
* @param message
* user provided message
*/
public ImproperXMLConfigurationException(String message) {
super(message);
}
/**
* Convenient constructor that explains the cause
*
* @param cause
* The cause of the exception
*/
public ImproperXMLConfigurationException(Throwable cause) {
super(cause);
}
}
| mpl-2.0 |
phassoa/openelisglobal-core | app/src/us/mn/state/health/lims/requester/daoimpl/RequesterTypeDAOImpl.java | 1638 | /**
* 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 OpenELIS code.
*
* Copyright (C) CIRG, University of Washington, Seattle WA. All Rights Reserved.
*
*/
package us.mn.state.health.lims.requester.daoimpl;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import us.mn.state.health.lims.common.daoimpl.BaseDAOImpl;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.requester.dao.RequesterTypeDAO;
import us.mn.state.health.lims.requester.valueholder.RequesterType;
/*
*/
public class RequesterTypeDAOImpl extends BaseDAOImpl implements RequesterTypeDAO {
//@Override
public RequesterType getRequesterTypeByName(String typeName) throws LIMSRuntimeException {
String sql = "from RequesterType rt where rt.requesterType = :typeName";
try{
Query query = HibernateUtil.getSession().createQuery(sql);
query.setParameter("typeName", typeName);
RequesterType type = (RequesterType) query.uniqueResult();
closeSession();
return type;
}catch(HibernateException e){
handleException(e, "getRequesterTypeByName");
}
return null;
}
} | mpl-2.0 |
PawelGutkowski/openmrs-sdk | archetype-module-refapp/src/main/resources/archetype-resources/omod/src/main/java/web/controller/__moduleClassnamePrefix__Controller.java | 2822 | /**
* 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/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package ${package}.web.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.User;
import org.openmrs.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* This class configured as controller using annotation and mapped with the URL of
* 'module/${rootArtifactId}/${rootArtifactId}Link.form'.
*/
@Controller("${rootrootArtifactId}.${moduleClassnamePrefix}Controller")
@RequestMapping(value = "module/${rootArtifactId}/${rootArtifactId}.form")
public class ${moduleClassnamePrefix}Controller {
/** Logger for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
@Autowired
UserService userService;
/** Success form view name */
private final String VIEW = "/module/${rootArtifactId}/${rootArtifactId}";
/**
* Initially called after the getUsers method to get the landing form name
*
* @return String form view name
*/
@RequestMapping(method = RequestMethod.GET)
public String onGet() {
return VIEW;
}
/**
* All the parameters are optional based on the necessity
*
* @param httpSession
* @param anyRequestObject
* @param errors
* @return
*/
@RequestMapping(method = RequestMethod.POST)
public String onPost(HttpSession httpSession, @ModelAttribute("anyRequestObject") Object anyRequestObject,
BindingResult errors) {
if (errors.hasErrors()) {
// return error view
}
return VIEW;
}
/**
* This class returns the form backing object. This can be a string, a boolean, or a normal java
* pojo. The bean name defined in the ModelAttribute annotation and the type can be just defined
* by the return type of this method
*/
@ModelAttribute("users")
protected List<User> getUsers() throws Exception {
List<User> users = userService.getAllUsers();
// this object will be made available to the jsp page under the variable name
// that is defined in the @ModuleAttribute tag
return users;
}
}
| mpl-2.0 |
auroreallibe/Silverpeas-Core | core-library/src/main/java/org/silverpeas/core/node/model/NodeI18NPK.java | 3304 | /*
* Copyright (C) 2000 - 2016 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/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.node.model;
import org.silverpeas.core.WAPrimaryKey;
import java.io.Serializable;
/**
* It's the Node PrimaryKey object It identify a Node
* @author Nicolas Eysseric
* @version 1.0
*/
public class NodeI18NPK extends WAPrimaryKey implements Serializable {
private static final long serialVersionUID = 4343441299362454324L;
// to apply the fat key pattern
transient public NodeI18NDetail nodeI18NDetail = null;
/**
* Constructor which set only the id
* @param id
* @since 1.0
*/
public NodeI18NPK(String id) {
super(id);
}
/**
* Constructor which set id, space and component name
* @param id
* @param space
* @param componentName
* @since 1.0
*/
public NodeI18NPK(String id, String space, String componentName) {
super(id, space, componentName);
}
public NodeI18NPK(String id, String componentId) {
super(id, componentId);
}
/**
* Constructor which set the id The WAPrimaryKey provides space and component name
* @param id
* @param pk
* @since 1.0
*/
public NodeI18NPK(String id, WAPrimaryKey pk) {
super(id, pk);
}
/**
* Return the object root table name
* @return the root table name of the object
* @since 1.0
*/
@Override
public String getRootTableName() {
return "NodeI18N";
}
/**
* Return the object table name
* @return the table name of the object
* @since 1.0
*/
@Override
public String getTableName() {
return "SB_Node_NodeI18N";
}
/**
* Check if an another object is equal to this object
* @return true if other is equals to this object
* @param other the object to compare to this NodePK
* @since 1.0
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof NodeI18NPK)) {
return false;
}
return (id.equals(((NodeI18NPK) other).getId()))
&& (componentName.equals(((NodeI18NPK) other).getComponentName()));
}
/**
* Returns a hash code for the key
* @return A hash code for this object
*/
@Override
public int hashCode() {
return this.id.hashCode() ^ this.componentName.hashCode();
}
} | agpl-3.0 |
schwadorf/IRIS | interaction-media-odata-xml/src/main/java/com/temenos/interaction/media/odata/xml/atom/AtomXMLProvider.java | 28658 | package com.temenos.interaction.media.odata.xml.atom;
/*
* #%L
* interaction-media-odata-xml
* %%
* Copyright (C) 2012 - 2013 Temenos Holdings N.V.
* %%
* 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/>.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PushbackInputStream;
import java.io.Reader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import org.odata4j.core.OEntities;
import org.odata4j.core.OEntity;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OLink;
import org.odata4j.core.OLinks;
import org.odata4j.edm.EdmDataServices;
import org.odata4j.edm.EdmEntitySet;
import org.odata4j.edm.EdmEntityType;
import org.odata4j.exceptions.NotFoundException;
import org.odata4j.exceptions.ODataProducerException;
import org.odata4j.format.Entry;
import org.odata4j.format.xml.AtomEntryFormatParserExt;
import org.odata4j.internal.InternalUtil;
import org.odata4j.producer.Responses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.temenos.interaction.core.UriInfoImpl;
import com.temenos.interaction.core.ExtendedMediaTypes;
import com.temenos.interaction.core.command.InteractionContext;
import com.temenos.interaction.core.entity.Entity;
import com.temenos.interaction.core.entity.EntityProperties;
import com.temenos.interaction.core.entity.EntityProperty;
import com.temenos.interaction.core.entity.Metadata;
import com.temenos.interaction.core.hypermedia.BeanTransformer;
import com.temenos.interaction.core.hypermedia.CollectionResourceState;
import com.temenos.interaction.core.hypermedia.DefaultResourceStateProvider;
import com.temenos.interaction.core.hypermedia.Event;
import com.temenos.interaction.core.hypermedia.HypermediaTemplateHelper;
import com.temenos.interaction.core.hypermedia.Link;
import com.temenos.interaction.core.hypermedia.ResourceState;
import com.temenos.interaction.core.hypermedia.ResourceStateMachine;
import com.temenos.interaction.core.hypermedia.ResourceStateProvider;
import com.temenos.interaction.core.hypermedia.Transformer;
import com.temenos.interaction.core.hypermedia.Transition;
import com.temenos.interaction.core.resource.CollectionResource;
import com.temenos.interaction.core.resource.EntityResource;
import com.temenos.interaction.core.resource.RESTResource;
import com.temenos.interaction.core.resource.ResourceTypeHelper;
import com.temenos.interaction.core.web.RequestContext;
import com.temenos.interaction.odataext.entity.MetadataOData4j;
@Provider
@Consumes({MediaType.APPLICATION_ATOM_XML})
@Produces({ExtendedMediaTypes.APPLICATION_ATOMSVC_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML})
public class AtomXMLProvider implements MessageBodyReader<RESTResource>, MessageBodyWriter<RESTResource> {
private static final String UTF_8 = "UTF-8";
private final static Logger logger = LoggerFactory.getLogger(AtomXMLProvider.class);
private final static Pattern STRING_KEY_RESOURCE_PATTERN = Pattern.compile("(\\('.*'\\))");
@Context
private UriInfo uriInfo;
@Context
private Request requestContext;
private AtomEntryFormatWriter entryWriter;
private AtomFeedFormatWriter feedWriter;
private AtomEntityEntryFormatWriter entityEntryWriter;
private final MetadataOData4j metadataOData4j;
private final Metadata metadata;
private final ResourceStateProvider resourceStateProvider;
private final ResourceState serviceDocument;
private final Transformer transformer;
private final LinkInterceptor linkInterceptor = new ODataLinkInterceptor(this);
/**
* Construct the jax-rs Provider for OData media type.
* @param metadataOData4j
* The entity metadata for reading and writing OData entities.
* @param metadata
* The entity metadata for reading and writing Entity entities.
* @param hypermediaEngine
* The hypermedia engine contains all the resource to entity mappings
* @param transformer
* Transformer to convert an entity to a properties map
*/
public AtomXMLProvider(MetadataOData4j metadataOData4j, Metadata metadata, ResourceStateMachine hypermediaEngine, Transformer transformer) {
this(metadataOData4j, metadata, new DefaultResourceStateProvider(hypermediaEngine), hypermediaEngine.getResourceStateByName("ServiceDocument"), transformer);
}
public AtomXMLProvider(MetadataOData4j metadataOData4j, Metadata metadata, ResourceStateProvider resourceStateProvider, ResourceState serviceDocument, Transformer transformer) {
this.metadataOData4j = metadataOData4j;
this.metadata = metadata;
this.resourceStateProvider = resourceStateProvider;
assert(resourceStateProvider != null);
this.serviceDocument = serviceDocument;
if (serviceDocument == null)
throw new RuntimeException("No 'ServiceDocument' found.");
assert(metadata != null);
this.transformer = transformer;
entryWriter = new AtomEntryFormatWriter(serviceDocument);
feedWriter = new AtomFeedFormatWriter(serviceDocument);
entityEntryWriter = new AtomEntityEntryFormatWriter(serviceDocument, metadata);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
if (mediaType.isCompatible(MediaType.APPLICATION_ATOM_XML_TYPE)
// good old Microsoft Excel 2013 has forced us to need to accept this media type (which is completely wrong) https://github.com/temenostech/IRIS/issues/154
|| mediaType.equals(ExtendedMediaTypes.APPLICATION_ATOMSVC_XML_TYPE)
|| mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
return ResourceTypeHelper.isType(type, genericType, EntityResource.class) ||
ResourceTypeHelper.isType(type, genericType, CollectionResource.class, OEntity.class) ||
ResourceTypeHelper.isType(type, genericType, CollectionResource.class, Entity.class);
}
return false;
}
@Override
public long getSize(RESTResource t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
/**
* Writes a Atom (OData) representation of {@link EntityResource} to the output stream.
*
* @precondition supplied {@link EntityResource} is non null
* @precondition {@link EntityResource#getEntity()} returns a valid OEntity, this
* provider only supports serialising OEntities
* @postcondition non null Atom (OData) XML document written to OutputStream
* @invariant valid OutputStream
*/
@SuppressWarnings("unchecked")
@Override
public void writeTo(RESTResource resource, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
assert (resource != null);
assert(uriInfo != null);
//Set response headers
if(httpHeaders != null) {
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_ATOM_XML); //Workaround for https://issues.apache.org/jira/browse/WINK-374
}
try {
RESTResource restResource = processLinks((RESTResource) resource);
Collection<Link> processedLinks = restResource.getLinks();
if(ResourceTypeHelper.isType(type, genericType, EntityResource.class, OEntity.class)) {
EntityResource<OEntity> entityResource = (EntityResource<OEntity>) resource;
OEntity tempEntity = entityResource.getEntity();
EdmEntitySet entitySet = getEdmEntitySet(entityResource.getEntityName());
List<OLink> olinks = formOLinks(entityResource);
//Write entry
// create OEntity with our EdmEntitySet see issue https://github.com/aphethean/IRIS/issues/20
OEntity oentity = OEntities.create(entitySet, tempEntity.getEntityKey(), tempEntity.getProperties(), null);
entryWriter.write(uriInfo, new OutputStreamWriter(entityStream, UTF_8), Responses.entity(oentity), entitySet, olinks);
} else if(ResourceTypeHelper.isType(type, genericType, EntityResource.class, Entity.class)) {
EntityResource<Entity> entityResource = (EntityResource<Entity>) resource;
//Write entry
Entity entity = entityResource.getEntity();
String entityName = entityResource.getEntityName();
// Write Entity object with Abdera implementation
entityEntryWriter.write(uriInfo, new OutputStreamWriter(entityStream, UTF_8), entityName, entity, processedLinks, entityResource.getEmbedded());
} else if(ResourceTypeHelper.isType(type, genericType, EntityResource.class)) {
EntityResource<Object> entityResource = (EntityResource<Object>) resource;
//Links and entity properties
Object entity = entityResource.getEntity();
String entityName = entityResource.getEntityName();
EntityProperties props = new EntityProperties();
if(entity != null) {
Map<String, Object> objProps = (transformer != null ? transformer : new BeanTransformer()).transform(entity);
if (objProps != null) {
for(String propName : objProps.keySet()) {
props.setProperty(new EntityProperty(propName, objProps.get(propName)));
}
}
}
entityEntryWriter.write(uriInfo, new OutputStreamWriter(entityStream, UTF_8), entityName, new Entity(entityName, props), processedLinks, entityResource.getEmbedded());
} else if(ResourceTypeHelper.isType(type, genericType, CollectionResource.class, OEntity.class)) {
CollectionResource<OEntity> collectionResource = ((CollectionResource<OEntity>) resource);
EdmEntitySet entitySet = getEdmEntitySet(collectionResource.getEntityName());
List<EntityResource<OEntity>> collectionEntities = (List<EntityResource<OEntity>>) collectionResource.getEntities();
List<OEntity> entities = new ArrayList<OEntity>();
Map<OEntity, Collection<Link>> linkId = new HashMap<OEntity, Collection<Link>>();
for (EntityResource<OEntity> collectionEntity : collectionEntities) {
// create OEntity with our EdmEntitySet see issue https://github.com/aphethean/IRIS/issues/20
OEntity tempEntity = collectionEntity.getEntity();
List<OLink> olinks = formOLinks(collectionEntity);
Collection<Link> links = collectionEntity.getLinks();
OEntity entity = OEntities.create(entitySet, null, tempEntity.getEntityKey(), tempEntity.getEntityTag(), tempEntity.getProperties(), olinks);
entities.add(entity);
linkId.put(entity, links);
}
// TODO implement collection properties and get transient values for inlinecount and skiptoken
Integer inlineCount = null;
String skipToken = null;
feedWriter.write(uriInfo, new OutputStreamWriter(entityStream, UTF_8),
processedLinks,
Responses.entities(entities, entitySet, inlineCount, skipToken),
metadata.getModelName(), linkId);
} else if(ResourceTypeHelper.isType(type, genericType, CollectionResource.class, Entity.class)) {
CollectionResource<Entity> collectionResource = ((CollectionResource<Entity>) resource);
// TODO implement collection properties and get transient values for inlinecount and skiptoken
Integer inlineCount = null;
String skipToken = null;
//Write feed
AtomEntityFeedFormatWriter entityFeedWriter = new AtomEntityFeedFormatWriter(serviceDocument, metadata);
entityFeedWriter.write(uriInfo, new OutputStreamWriter(entityStream, UTF_8), collectionResource, inlineCount, skipToken, metadata.getModelName());
} else {
logger.error("Accepted object for writing in isWriteable, but type not supported in writeTo method");
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
} catch (ODataProducerException e) {
logger.error("An error occurred while writing " + mediaType + " resource representation", e);
}
}
public RESTResource processLinks(RESTResource restResource) {
Collection<Link> linksCollection = restResource.getLinks();
List<Link> processedLinks = new ArrayList<Link>();
if (linksCollection != null) {
for (Link linkToAdd : linksCollection) {
Link link = linkInterceptor.addingLink(restResource, linkToAdd);
if (link != null) {
processedLinks.add(link);
}
}
}
restResource.setLinks(processedLinks);
// process embedded resources
if (restResource.getEmbedded() != null) {
Map<Transition,RESTResource> embeddedResources = restResource.getEmbedded();
for (RESTResource embeddedResource : embeddedResources.values()) {
processLinks(embeddedResource);
}
}
// process entities in collection resource
if (restResource instanceof CollectionResource) {
CollectionResource<?> collectionResource = (CollectionResource<?>) restResource;
for (EntityResource<?> entityResource : collectionResource.getEntities()) {
processLinks(entityResource);
}
}
return restResource;
}
public List<OLink> formOLinks(EntityResource<OEntity> entityResource) {
// Create embedded resources from $expand
addExpandedLinks(entityResource);
//Add entity links
List<OLink> olinks = new ArrayList<OLink>();
if (entityResource.getLinks() != null && entityResource.getLinks().size() > 0) {
for(Link link : entityResource.getLinks()) {
addLinkToOLinks(olinks, link, entityResource);
}
}
return olinks;
}
/*
* Using the supplied EntityResource, add the embedded resources
* from the OEntity embedded resources. NB - only an OEntity can
* carry OLinks.
*/
public void addExpandedLinks(EntityResource<OEntity> entityResource) {
RequestContext requestContext = RequestContext.getRequestContext();
Collection<Link> links = entityResource.getLinks();
if (links != null) {
OEntity oentity = entityResource.getEntity();
List<OLink> olinks = oentity.getLinks();
for (OLink olink : olinks) {
if (olink.isInline()) {
String relid = InternalUtil.getEntityRelId(oentity);
String href = relid + "/" + olink.getTitle();
for (Link link : links) {
String linkHref = link.getHref();
if(requestContext != null) {
//Extract the transition fragment from the URI path
linkHref = link.getRelativeHref(getBaseUri(serviceDocument, uriInfo));
}
if (href.equals(linkHref)) {
if (entityResource.getEmbedded() == null) {
entityResource.setEmbedded(new HashMap<Transition, RESTResource>());
}
if (olink.isCollection()) {
List<OEntity> oentities = olink.getRelatedEntities();
Collection<EntityResource<OEntity>> entityResources = new ArrayList<EntityResource<OEntity>>();
for (OEntity oe : oentities) {
entityResources.add(new EntityResource<OEntity>(oe));
}
entityResource.getEmbedded().put(link.getTransition(), new CollectionResource<OEntity>(entityResources));
} else {
// replace the OLink's on the current entity
OEntity inlineOentity = olink.getRelatedEntity();
List<OLink> inlineResourceOlinks = formOLinks(new EntityResource<OEntity>(inlineOentity));
OEntity newInlineOentity = OEntities.create(inlineOentity.getEntitySet(), inlineOentity.getEntityKey(), inlineOentity.getProperties(), inlineResourceOlinks);
entityResource.getEmbedded().put(link.getTransition(), new EntityResource<OEntity>(newInlineOentity));
}
}
}
}
}
}
}
private void addLinkToOLinks(List<OLink> olinks, Link link, RESTResource resource) {
RequestContext requestContext = RequestContext.getRequestContext();
assert(link != null);
assert(link.getTransition() != null);
Map<Transition,RESTResource> embeddedResources = resource.getEmbedded();
String rel = link.getRel();
String href = link.getHref();
if(requestContext != null) {
//Extract the transition fragment from the URI path
href = link.getRelativeHref(getBaseUri(serviceDocument, uriInfo));
}
String title = link.getTitle();
OLink olink = null;
Transition linkTransition = link.getTransition();
if(linkTransition != null) {
if (embeddedResources != null && embeddedResources.get(linkTransition) != null
&&embeddedResources.get(linkTransition) instanceof EntityResource) {
@SuppressWarnings("unchecked")
EntityResource<OEntity> embeddedResource = (EntityResource<OEntity>) embeddedResources.get(linkTransition);
// replace the OLink's on the embedded entity
OEntity newEmbeddedEntity = processOEntity(embeddedResource);
olink = OLinks.relatedEntityInline(rel, title, href, newEmbeddedEntity);
} else if (embeddedResources != null && embeddedResources.get(linkTransition) != null
&&embeddedResources.get(linkTransition) instanceof CollectionResource) {
@SuppressWarnings("unchecked")
CollectionResource<OEntity> embeddedCollectionResource = (CollectionResource<OEntity>) embeddedResources.get(linkTransition);
List<OEntity> entities = new ArrayList<OEntity>();
for (EntityResource<OEntity> embeddedResource : embeddedCollectionResource.getEntities()) {
// replace the OLink's on the embedded entity
OEntity newEmbeddedEntity = processOEntity(embeddedResource);
entities.add(newEmbeddedEntity);
}
olink = OLinks.relatedEntitiesInline(rel, title, href, entities);
}
if (olink == null) {
if (linkTransition.getTarget() instanceof CollectionResourceState) {
olink = OLinks.relatedEntities(rel, title, href);
} else {
olink = OLinks.relatedEntity(rel, title, href);
}
}
}
olinks.add(olink);
}
private OEntity processOEntity(EntityResource<OEntity> entityResource) {
List<OLink> embeddedLinks = formOLinks(entityResource);
OEntity embeddedEntity = entityResource.getEntity();
// replace the OLink's on the embedded entity
OEntity newOEntity = OEntities.create(embeddedEntity.getEntitySet(), embeddedEntity.getEntityKey(), embeddedEntity.getProperties(), embeddedLinks);
return newOEntity;
}
@Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
// this class can only deserialise EntityResource with OEntity
return ResourceTypeHelper.isType(type, genericType, EntityResource.class);
}
/**
* Reads a Atom (OData) representation of {@link EntityResource} from the input stream.
*
* @precondition {@link InputStream} contains a valid Atom (OData) Entity enclosed in a <resource/> document
* @postcondition {@link EntityResource} will be constructed and returned.
* @invariant valid InputStream
*/
@Override
public EntityResource<OEntity> readFrom(Class<RESTResource> type,
Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
// check media type can be handled, isReadable must have been called
assert(ResourceTypeHelper.isType(type, genericType, EntityResource.class));
assert(mediaType.isCompatible(MediaType.APPLICATION_ATOM_XML_TYPE));
try {
OEntityKey entityKey = null;
uriInfo = new UriInfoImpl(uriInfo);
// work out the entity name using resource path from UriInfo
String baseUri = AtomXMLProvider.getBaseUri(serviceDocument, uriInfo);
String absoluteUri = AtomXMLProvider.getAbsolutePath(uriInfo);
logger.info("Reading atom xml content for [" + absoluteUri + "]");
String resourcePath = null;
StringBuffer regex = new StringBuffer("(?<=" + baseUri + ")\\S+");
Pattern p = Pattern.compile(regex.toString());
Matcher m = p.matcher(absoluteUri);
while (m.find()) {
resourcePath = m.group();
}
if (resourcePath == null)
throw new IllegalStateException("No resource found");
ResourceState currentState = getCurrentState(serviceDocument, resourcePath);
if (currentState == null)
throw new IllegalStateException("No state found");
String pathIdParameter = getPathIdParameter(currentState);
MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
if (pathParameters != null && pathParameters.getFirst(pathIdParameter) != null) {
if (STRING_KEY_RESOURCE_PATTERN.matcher(resourcePath).find()) {
entityKey = OEntityKey.create(pathParameters.getFirst(pathIdParameter));
} else {
entityKey = OEntityKey.parse(pathParameters.getFirst(pathIdParameter));
}
}
if (currentState.getEntityName() == null) {
throw new IllegalStateException("Entity name could not be determined");
}
/*
* get the entity set name using the metadata
*/
String entitySetName = getEntitySet(currentState);
// Check contents of the stream, if empty or null then return empty resource
InputStream verifiedStream = verifyContentReceieved(entityStream);
if (verifiedStream == null) {
return new EntityResource<OEntity>();
}
// Lets parse the request content
Reader reader = new InputStreamReader(verifiedStream);
assert(entitySetName != null) : "Must have found a resource or thrown exception";
Entry e = new AtomEntryFormatParserExt(metadataOData4j, entitySetName, entityKey, null).parse(reader);
return new EntityResource<OEntity>(e.getEntity());
} catch (IllegalStateException e) {
logger.warn("Malformed request from client", e);
throw new WebApplicationException(Status.BAD_REQUEST);
}
}
/*
* Find the entity set name for this resource
*/
public String getEntitySet(ResourceState state) {
String entitySetName = null;
String fqTargetEntityName = metadata.getModelName() + Metadata.MODEL_SUFFIX + "." + state.getEntityName();
try {
EdmEntityType targetEntityType = (EdmEntityType) getEdmDataService().findEdmEntityType(fqTargetEntityName);
if (targetEntityType != null) {
EdmEntitySet targetEntitySet = getEdmDataService().getEdmEntitySet(targetEntityType);
if (targetEntitySet != null)
entitySetName = targetEntitySet.getName();
}
} catch (NotFoundException e) {}
if (entitySetName == null) {
try {
entitySetName = getEdmEntitySet(state.getEntityName()).getName();
} catch (NotFoundException e) {
logger.warn("Entity [" + fqTargetEntityName + "] is not an entity set.");
}
if(entitySetName == null) {
entitySetName = state.getName();
}
}
return entitySetName;
}
protected ResourceState getCurrentState(ResourceState serviceDocument, String resourcePath) {
ResourceState state = null;
if (resourcePath != null) {
/*
* add a leading '/' if it needs it (when defining resources we must use a
* full path, but requests can be relative, i.e. without a '/'
*/
if (!resourcePath.startsWith("/")) {
resourcePath = "/" + resourcePath;
}
// add service document path to resource path
String serviceDocumentPath = serviceDocument.getPath();
if (serviceDocumentPath.endsWith("/")) {
serviceDocumentPath = serviceDocumentPath.substring(0, serviceDocumentPath.lastIndexOf("/"));
}
resourcePath = serviceDocumentPath + resourcePath;
// turn the uri back into a template uri
MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
if (pathParameters != null) {
for (String key : pathParameters.keySet()) {
List<String> values = pathParameters.get(key);
for (String value : values) {
resourcePath = resourcePath.replace(value, "{" + key + "}");
}
}
}
String httpMethod = requestContext.getMethod();
Event event = new Event(httpMethod, httpMethod);
state = resourceStateProvider.determineState(event, resourcePath);
if (state == null) {
logger.warn("No state found, dropping back to path matching " + resourcePath);
// escape the braces in the regex
resourcePath = Pattern.quote(resourcePath);
Map<String, Set<String>> pathToResourceStates = resourceStateProvider.getResourceStatesByPath();
for (String path : pathToResourceStates.keySet()) {
for (String name : pathToResourceStates.get(path)) {
ResourceState s = resourceStateProvider.getResourceState(name);
String pattern = null;
if (s instanceof CollectionResourceState) {
pattern = resourcePath + "(|\\(\\))";
Matcher matcher = Pattern.compile(pattern).matcher(path);
if (matcher.matches()) {
state = s;
}
}
}
}
}
}
return state;
}
/*
* For a given resource state, get the path parameter used for the id.
* @param state
* @return
*/
private String getPathIdParameter(ResourceState state) {
String pathIdParameter = InteractionContext.DEFAULT_ID_PATH_ELEMENT;
if (state.getPathIdParameter() != null) {
pathIdParameter = state.getPathIdParameter();
}
return pathIdParameter;
}
/* Ugly testing support :-( */
protected void setUriInfo(UriInfo uriInfo) {
this.uriInfo = uriInfo;
}
protected void setRequestContext(Request request) {
this.requestContext = request;
}
/**
* Method to verify if receieved stream has content or its empty
* @param stream Stream to check
* @return verified stream
* @throws IOException
*/
private InputStream verifyContentReceieved(InputStream stream) throws IOException {
if (stream == null) { // Check if its null
logger.debug("Request stream received as null");
return null;
} else if (stream.markSupported()) { // Check stream supports mark/reset
// mark() and read the first byte just to check
stream.mark(1);
final int bytesRead = stream.read(new byte[1]);
if (bytesRead != -1) {
//stream not empty
stream.reset(); // reset the stream as if untouched
return stream;
} else {
//stream empty
logger.debug("Request received with empty body");
return null;
}
} else {
// Panic! this stream does not support mark/reset, try with PushbackInputStream as a last resort
int bytesRead;
PushbackInputStream pbs = new PushbackInputStream(stream);
if ((bytesRead = pbs.read()) != -1) {
// Contents detected, unread and return
pbs.unread(bytesRead);
return pbs;
} else {
// Empty stream detected
logger.debug("Request received with empty body!");
return null;
}
}
}
/**
* Our base uri is the uri to the service document.
* @param serviceDocument
* @param uriInfo
* @return
*/
public static String getBaseUri(ResourceState serviceDocument, UriInfo uriInfo) {
String baseUri = uriInfo.getBaseUri().toString();
if (serviceDocument.getPath() != null) {
if (baseUri.endsWith("/")) {
baseUri = baseUri.substring(0, baseUri.lastIndexOf("/"));
}
baseUri = baseUri + serviceDocument.getPath();
String absPath = getAbsolutePath(uriInfo);
baseUri = HypermediaTemplateHelper.getTemplatedBaseUri(baseUri, absPath);
if (!baseUri.endsWith("/")) {
baseUri += "/";
}
}
return baseUri;
}
public static String getAbsolutePath(UriInfo uriInfo) {
return uriInfo.getBaseUri() + uriInfo.getPath();
}
private EdmDataServices getEdmDataService() {
return metadataOData4j.getMetadata();
}
/*
* get edmEntitySet
*/
public EdmEntitySet getEdmEntitySet(String entityName) {
EdmEntityType entityType = (EdmEntityType) getEdmDataService().findEdmEntityType(entityName);
EdmEntitySet entitySet = null;
try {
entitySet = getEdmDataService().getEdmEntitySet(entityType);
} catch (Exception e) {
//logger.error("Unable to find entity set for [" +entityName + "]");
}
if(entitySet == null) {
return metadataOData4j.getEdmEntitySetByEntityName(entityName);
}
return entitySet;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/pci/vo/domain/ClientVoAssembler.java | 49598 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:24
*
*/
package ims.pci.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Marius Mihalec
*/
public class ClientVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.pci.vo.ClientVo copy(ims.pci.vo.ClientVo valueObjectDest, ims.pci.vo.ClientVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Patient(valueObjectSrc.getID_Patient());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// addresses
valueObjectDest.setAddresses(valueObjectSrc.getAddresses());
// gp
valueObjectDest.setGp(valueObjectSrc.getGp());
// gpSurgery
valueObjectDest.setGpSurgery(valueObjectSrc.getGpSurgery());
// clientParent
valueObjectDest.setClientParent(valueObjectSrc.getClientParent());
// CommunityCare
valueObjectDest.setCommunityCare(valueObjectSrc.getCommunityCare());
// otherNames
valueObjectDest.setOtherNames(valueObjectSrc.getOtherNames());
// ConfidentialReason
valueObjectDest.setConfidentialReason(valueObjectSrc.getConfidentialReason());
// isChild
valueObjectDest.setIsChild(valueObjectSrc.getIsChild());
// Nationality
valueObjectDest.setNationality(valueObjectSrc.getNationality());
// DodSource
valueObjectDest.setDodSource(valueObjectSrc.getDodSource());
// name
valueObjectDest.setName(valueObjectSrc.getName());
// sex
valueObjectDest.setSex(valueObjectSrc.getSex());
// address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// dob
valueObjectDest.setDob(valueObjectSrc.getDob());
// dod
valueObjectDest.setDod(valueObjectSrc.getDod());
// ward
valueObjectDest.setWard(valueObjectSrc.getWard());
// religion
valueObjectDest.setReligion(valueObjectSrc.getReligion());
// identifiers
valueObjectDest.setIdentifiers(valueObjectSrc.getIdentifiers());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// associatedPatient
valueObjectDest.setAssociatedPatient(valueObjectSrc.getAssociatedPatient());
// CommChannels
valueObjectDest.setCommChannels(valueObjectSrc.getCommChannels());
// ethnicOrigin
valueObjectDest.setEthnicOrigin(valueObjectSrc.getEthnicOrigin());
// maritalStatus
valueObjectDest.setMaritalStatus(valueObjectSrc.getMaritalStatus());
// SCN
valueObjectDest.setSCN(valueObjectSrc.getSCN());
// SourceOfInformation
valueObjectDest.setSourceOfInformation(valueObjectSrc.getSourceOfInformation());
// SysInfo
valueObjectDest.setSysInfo(valueObjectSrc.getSysInfo());
// TimeOfDeath
valueObjectDest.setTimeOfDeath(valueObjectSrc.getTimeOfDeath());
// IsQuickRegistrationPatient
valueObjectDest.setIsQuickRegistrationPatient(valueObjectSrc.getIsQuickRegistrationPatient());
// OCSNotification
valueObjectDest.setOCSNotification(valueObjectSrc.getOCSNotification());
// CurrentResponsibleConsultant
valueObjectDest.setCurrentResponsibleConsultant(valueObjectSrc.getCurrentResponsibleConsultant());
// DementiaBreachDateTime
valueObjectDest.setDementiaBreachDateTime(valueObjectSrc.getDementiaBreachDateTime());
// DementiaWorklistStatus
valueObjectDest.setDementiaWorklistStatus(valueObjectSrc.getDementiaWorklistStatus());
// MRNStatus
valueObjectDest.setMRNStatus(valueObjectSrc.getMRNStatus());
// hasScannedCaseNoteFolders
valueObjectDest.setHasScannedCaseNoteFolders(valueObjectSrc.getHasScannedCaseNoteFolders());
// IsConfidential
valueObjectDest.setIsConfidential(valueObjectSrc.getIsConfidential());
// TimeOfBirth
valueObjectDest.setTimeOfBirth(valueObjectSrc.getTimeOfBirth());
// PatientCategory
valueObjectDest.setPatientCategory(valueObjectSrc.getPatientCategory());
// PDSPatientGP
valueObjectDest.setPDSPatientGP(valueObjectSrc.getPDSPatientGP());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createClientVoCollectionFromPatient(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.patient.domain.objects.Patient objects.
*/
public static ims.pci.vo.ClientVoCollection createClientVoCollectionFromPatient(java.util.Set domainObjectSet)
{
return createClientVoCollectionFromPatient(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.patient.domain.objects.Patient objects.
*/
public static ims.pci.vo.ClientVoCollection createClientVoCollectionFromPatient(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.pci.vo.ClientVoCollection voList = new ims.pci.vo.ClientVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.patient.domain.objects.Patient domainObject = (ims.core.patient.domain.objects.Patient) iterator.next();
ims.pci.vo.ClientVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.patient.domain.objects.Patient objects.
*/
public static ims.pci.vo.ClientVoCollection createClientVoCollectionFromPatient(java.util.List domainObjectList)
{
return createClientVoCollectionFromPatient(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.patient.domain.objects.Patient objects.
*/
public static ims.pci.vo.ClientVoCollection createClientVoCollectionFromPatient(DomainObjectMap map, java.util.List domainObjectList)
{
ims.pci.vo.ClientVoCollection voList = new ims.pci.vo.ClientVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.patient.domain.objects.Patient domainObject = (ims.core.patient.domain.objects.Patient) domainObjectList.get(i);
ims.pci.vo.ClientVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.patient.domain.objects.Patient set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractPatientSet(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVoCollection voCollection)
{
return extractPatientSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractPatientSet(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.pci.vo.ClientVo vo = voCollection.get(i);
ims.core.patient.domain.objects.Patient domainObject = ClientVoAssembler.extractPatient(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.patient.domain.objects.Patient list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractPatientList(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVoCollection voCollection)
{
return extractPatientList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractPatientList(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.pci.vo.ClientVo vo = voCollection.get(i);
ims.core.patient.domain.objects.Patient domainObject = ClientVoAssembler.extractPatient(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.patient.domain.objects.Patient object.
* @param domainObject ims.core.patient.domain.objects.Patient
*/
public static ims.pci.vo.ClientVo create(ims.core.patient.domain.objects.Patient domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.patient.domain.objects.Patient object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.pci.vo.ClientVo create(DomainObjectMap map, ims.core.patient.domain.objects.Patient domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.pci.vo.ClientVo valueObject = (ims.pci.vo.ClientVo) map.getValueObject(domainObject, ims.pci.vo.ClientVo.class);
if ( null == valueObject )
{
valueObject = new ims.pci.vo.ClientVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.patient.domain.objects.Patient
*/
public static ims.pci.vo.ClientVo insert(ims.pci.vo.ClientVo valueObject, ims.core.patient.domain.objects.Patient domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.patient.domain.objects.Patient
*/
public static ims.pci.vo.ClientVo insert(DomainObjectMap map, ims.pci.vo.ClientVo valueObject, ims.core.patient.domain.objects.Patient domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Patient(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// addresses
valueObject.setAddresses(ims.core.vo.domain.PersonAddressAssembler.createPersonAddressCollectionFromAddress(map, domainObject.getAddresses()) );
// gp
valueObject.setGp(ims.core.vo.domain.GpShortVoAssembler.create(map, domainObject.getGp()) );
// gpSurgery
if (domainObject.getGpSurgery() != null)
{
if(domainObject.getGpSurgery() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getGpSurgery();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setGpSurgery(new ims.core.resource.place.vo.LocSiteRefVo(id, -1));
}
else
{
valueObject.setGpSurgery(new ims.core.resource.place.vo.LocSiteRefVo(domainObject.getGpSurgery().getId(), domainObject.getGpSurgery().getVersion()));
}
}
// clientParent
if (domainObject.getClientParent() != null)
{
if(domainObject.getClientParent() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getClientParent();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setClientParent(new ims.core.patient.vo.PatientRefVo(id, -1));
}
else
{
valueObject.setClientParent(new ims.core.patient.vo.PatientRefVo(domainObject.getClientParent().getId(), domainObject.getClientParent().getVersion()));
}
}
// CommunityCare
valueObject.setCommunityCare(ims.pci.vo.domain.CommunityCareVoAssembler.create(map, domainObject.getCommunityCare()) );
// otherNames
valueObject.setOtherNames(ims.core.vo.domain.PersonNameAssembler.createPersonNameCollectionFromPersonName(map, domainObject.getOtherNames()) );
// ConfidentialReason
ims.domain.lookups.LookupInstance instance7 = domainObject.getConfidentialReason();
if ( null != instance7 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance7.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance7.getImage().getImageId(), instance7.getImage().getImagePath());
}
color = instance7.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.ConfidentialReason voLookup7 = new ims.core.vo.lookups.ConfidentialReason(instance7.getId(),instance7.getText(), instance7.isActive(), null, img, color);
ims.core.vo.lookups.ConfidentialReason parentVoLookup7 = voLookup7;
ims.domain.lookups.LookupInstance parent7 = instance7.getParent();
while (parent7 != null)
{
if (parent7.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent7.getImage().getImageId(), parent7.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent7.getColor();
if (color != null)
color.getValue();
parentVoLookup7.setParent(new ims.core.vo.lookups.ConfidentialReason(parent7.getId(),parent7.getText(), parent7.isActive(), null, img, color));
parentVoLookup7 = parentVoLookup7.getParent();
parent7 = parent7.getParent();
}
valueObject.setConfidentialReason(voLookup7);
}
// isChild
valueObject.setIsChild( domainObject.isIsChild() );
// Nationality
ims.domain.lookups.LookupInstance instance9 = domainObject.getNationality();
if ( null != instance9 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance9.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance9.getImage().getImageId(), instance9.getImage().getImagePath());
}
color = instance9.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Nationality voLookup9 = new ims.core.vo.lookups.Nationality(instance9.getId(),instance9.getText(), instance9.isActive(), null, img, color);
ims.core.vo.lookups.Nationality parentVoLookup9 = voLookup9;
ims.domain.lookups.LookupInstance parent9 = instance9.getParent();
while (parent9 != null)
{
if (parent9.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent9.getImage().getImageId(), parent9.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent9.getColor();
if (color != null)
color.getValue();
parentVoLookup9.setParent(new ims.core.vo.lookups.Nationality(parent9.getId(),parent9.getText(), parent9.isActive(), null, img, color));
parentVoLookup9 = parentVoLookup9.getParent();
parent9 = parent9.getParent();
}
valueObject.setNationality(voLookup9);
}
// DodSource
ims.domain.lookups.LookupInstance instance10 = domainObject.getDodSource();
if ( null != instance10 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance10.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance10.getImage().getImageId(), instance10.getImage().getImagePath());
}
color = instance10.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.DodSource voLookup10 = new ims.core.vo.lookups.DodSource(instance10.getId(),instance10.getText(), instance10.isActive(), null, img, color);
ims.core.vo.lookups.DodSource parentVoLookup10 = voLookup10;
ims.domain.lookups.LookupInstance parent10 = instance10.getParent();
while (parent10 != null)
{
if (parent10.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent10.getImage().getImageId(), parent10.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent10.getColor();
if (color != null)
color.getValue();
parentVoLookup10.setParent(new ims.core.vo.lookups.DodSource(parent10.getId(),parent10.getText(), parent10.isActive(), null, img, color));
parentVoLookup10 = parentVoLookup10.getParent();
parent10 = parent10.getParent();
}
valueObject.setDodSource(voLookup10);
}
// name
valueObject.setName(ims.core.vo.domain.PersonNameAssembler.create(map, domainObject.getName()) );
// sex
ims.domain.lookups.LookupInstance instance12 = domainObject.getSex();
if ( null != instance12 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance12.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance12.getImage().getImageId(), instance12.getImage().getImagePath());
}
color = instance12.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Sex voLookup12 = new ims.core.vo.lookups.Sex(instance12.getId(),instance12.getText(), instance12.isActive(), null, img, color);
ims.core.vo.lookups.Sex parentVoLookup12 = voLookup12;
ims.domain.lookups.LookupInstance parent12 = instance12.getParent();
while (parent12 != null)
{
if (parent12.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent12.getImage().getImageId(), parent12.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent12.getColor();
if (color != null)
color.getValue();
parentVoLookup12.setParent(new ims.core.vo.lookups.Sex(parent12.getId(),parent12.getText(), parent12.isActive(), null, img, color));
parentVoLookup12 = parentVoLookup12.getParent();
parent12 = parent12.getParent();
}
valueObject.setSex(voLookup12);
}
// address
valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) );
// dob
Integer dob = domainObject.getDob();
if ( null != dob )
{
valueObject.setDob(new ims.framework.utils.PartialDate(dob) );
}
// dod
java.util.Date dod = domainObject.getDod();
if ( null != dod )
{
valueObject.setDod(new ims.framework.utils.Date(dod) );
}
// ward
valueObject.setWard(ims.core.vo.domain.LocationLiteVoAssembler.create(map, domainObject.getWard()) );
// religion
ims.domain.lookups.LookupInstance instance17 = domainObject.getReligion();
if ( null != instance17 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance17.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance17.getImage().getImageId(), instance17.getImage().getImagePath());
}
color = instance17.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Religion voLookup17 = new ims.core.vo.lookups.Religion(instance17.getId(),instance17.getText(), instance17.isActive(), null, img, color);
ims.core.vo.lookups.Religion parentVoLookup17 = voLookup17;
ims.domain.lookups.LookupInstance parent17 = instance17.getParent();
while (parent17 != null)
{
if (parent17.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent17.getImage().getImageId(), parent17.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent17.getColor();
if (color != null)
color.getValue();
parentVoLookup17.setParent(new ims.core.vo.lookups.Religion(parent17.getId(),parent17.getText(), parent17.isActive(), null, img, color));
parentVoLookup17 = parentVoLookup17.getParent();
parent17 = parent17.getParent();
}
valueObject.setReligion(voLookup17);
}
// identifiers
valueObject.setIdentifiers(ims.core.vo.domain.PatientIdAssembler.createPatientIdCollectionFromPatientId(map, domainObject.getIdentifiers()) );
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// associatedPatient
valueObject.setAssociatedPatient(ims.core.vo.domain.PatientShortAssembler.create(map, domainObject.getAssociatedPatient()) );
// CommChannels
valueObject.setCommChannels(ims.core.vo.domain.CommChannelVoAssembler.createCommChannelVoCollectionFromCommunicationChannel(map, domainObject.getCommChannels()) );
// ethnicOrigin
ims.domain.lookups.LookupInstance instance22 = domainObject.getEthnicOrigin();
if ( null != instance22 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance22.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance22.getImage().getImageId(), instance22.getImage().getImagePath());
}
color = instance22.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.EthnicOrigin voLookup22 = new ims.core.vo.lookups.EthnicOrigin(instance22.getId(),instance22.getText(), instance22.isActive(), null, img, color);
ims.core.vo.lookups.EthnicOrigin parentVoLookup22 = voLookup22;
ims.domain.lookups.LookupInstance parent22 = instance22.getParent();
while (parent22 != null)
{
if (parent22.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent22.getImage().getImageId(), parent22.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent22.getColor();
if (color != null)
color.getValue();
parentVoLookup22.setParent(new ims.core.vo.lookups.EthnicOrigin(parent22.getId(),parent22.getText(), parent22.isActive(), null, img, color));
parentVoLookup22 = parentVoLookup22.getParent();
parent22 = parent22.getParent();
}
valueObject.setEthnicOrigin(voLookup22);
}
// maritalStatus
ims.domain.lookups.LookupInstance instance23 = domainObject.getMaritalStatus();
if ( null != instance23 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance23.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance23.getImage().getImageId(), instance23.getImage().getImagePath());
}
color = instance23.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.MaritalStatus voLookup23 = new ims.core.vo.lookups.MaritalStatus(instance23.getId(),instance23.getText(), instance23.isActive(), null, img, color);
ims.core.vo.lookups.MaritalStatus parentVoLookup23 = voLookup23;
ims.domain.lookups.LookupInstance parent23 = instance23.getParent();
while (parent23 != null)
{
if (parent23.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent23.getImage().getImageId(), parent23.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent23.getColor();
if (color != null)
color.getValue();
parentVoLookup23.setParent(new ims.core.vo.lookups.MaritalStatus(parent23.getId(),parent23.getText(), parent23.isActive(), null, img, color));
parentVoLookup23 = parentVoLookup23.getParent();
parent23 = parent23.getParent();
}
valueObject.setMaritalStatus(voLookup23);
}
// SCN
valueObject.setSCN(domainObject.getSCN());
// SourceOfInformation
ims.domain.lookups.LookupInstance instance25 = domainObject.getSourceOfInformation();
if ( null != instance25 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance25.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance25.getImage().getImageId(), instance25.getImage().getImagePath());
}
color = instance25.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.RegistrationSourceOfInfo voLookup25 = new ims.core.vo.lookups.RegistrationSourceOfInfo(instance25.getId(),instance25.getText(), instance25.isActive(), null, img, color);
ims.core.vo.lookups.RegistrationSourceOfInfo parentVoLookup25 = voLookup25;
ims.domain.lookups.LookupInstance parent25 = instance25.getParent();
while (parent25 != null)
{
if (parent25.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent25.getImage().getImageId(), parent25.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent25.getColor();
if (color != null)
color.getValue();
parentVoLookup25.setParent(new ims.core.vo.lookups.RegistrationSourceOfInfo(parent25.getId(),parent25.getText(), parent25.isActive(), null, img, color));
parentVoLookup25 = parentVoLookup25.getParent();
parent25 = parent25.getParent();
}
valueObject.setSourceOfInformation(voLookup25);
}
// SysInfo
// set system information
valueObject.setSysInfo(ims.vo.domain.SystemInformationAssembler.create(domainObject.getSystemInformation()));
// TimeOfDeath
String TimeOfDeath = domainObject.getTimeOfDeath();
if ( null != TimeOfDeath )
{
valueObject.setTimeOfDeath(new ims.framework.utils.Time(TimeOfDeath) );
}
// IsQuickRegistrationPatient
valueObject.setIsQuickRegistrationPatient( domainObject.isIsQuickRegistrationPatient() );
// OCSNotification
valueObject.setOCSNotification(ims.core.vo.domain.PatientNotificationsFillerOnlyVoAssembler.create(map, domainObject.getOCSNotification()) );
// CurrentResponsibleConsultant
if (domainObject.getCurrentResponsibleConsultant() != null)
{
if(domainObject.getCurrentResponsibleConsultant() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getCurrentResponsibleConsultant();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setCurrentResponsibleConsultant(new ims.core.resource.people.vo.MedicRefVo(id, -1));
}
else
{
valueObject.setCurrentResponsibleConsultant(new ims.core.resource.people.vo.MedicRefVo(domainObject.getCurrentResponsibleConsultant().getId(), domainObject.getCurrentResponsibleConsultant().getVersion()));
}
}
// DementiaBreachDateTime
java.util.Date DementiaBreachDateTime = domainObject.getDementiaBreachDateTime();
if ( null != DementiaBreachDateTime )
{
valueObject.setDementiaBreachDateTime(new ims.framework.utils.DateTime(DementiaBreachDateTime) );
}
// DementiaWorklistStatus
ims.domain.lookups.LookupInstance instance32 = domainObject.getDementiaWorklistStatus();
if ( null != instance32 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance32.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance32.getImage().getImageId(), instance32.getImage().getImagePath());
}
color = instance32.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.DementiaWorklistStatus voLookup32 = new ims.core.vo.lookups.DementiaWorklistStatus(instance32.getId(),instance32.getText(), instance32.isActive(), null, img, color);
ims.core.vo.lookups.DementiaWorklistStatus parentVoLookup32 = voLookup32;
ims.domain.lookups.LookupInstance parent32 = instance32.getParent();
while (parent32 != null)
{
if (parent32.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent32.getImage().getImageId(), parent32.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent32.getColor();
if (color != null)
color.getValue();
parentVoLookup32.setParent(new ims.core.vo.lookups.DementiaWorklistStatus(parent32.getId(),parent32.getText(), parent32.isActive(), null, img, color));
parentVoLookup32 = parentVoLookup32.getParent();
parent32 = parent32.getParent();
}
valueObject.setDementiaWorklistStatus(voLookup32);
}
// MRNStatus
ims.domain.lookups.LookupInstance instance33 = domainObject.getMRNStatus();
if ( null != instance33 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance33.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance33.getImage().getImageId(), instance33.getImage().getImagePath());
}
color = instance33.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.MRNStatus voLookup33 = new ims.core.vo.lookups.MRNStatus(instance33.getId(),instance33.getText(), instance33.isActive(), null, img, color);
ims.core.vo.lookups.MRNStatus parentVoLookup33 = voLookup33;
ims.domain.lookups.LookupInstance parent33 = instance33.getParent();
while (parent33 != null)
{
if (parent33.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent33.getImage().getImageId(), parent33.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent33.getColor();
if (color != null)
color.getValue();
parentVoLookup33.setParent(new ims.core.vo.lookups.MRNStatus(parent33.getId(),parent33.getText(), parent33.isActive(), null, img, color));
parentVoLookup33 = parentVoLookup33.getParent();
parent33 = parent33.getParent();
}
valueObject.setMRNStatus(voLookup33);
}
// hasScannedCaseNoteFolders
valueObject.setHasScannedCaseNoteFolders( domainObject.isHasScannedCaseNoteFolders() );
// IsConfidential
valueObject.setIsConfidential( domainObject.isIsConfidential() );
// TimeOfBirth
String TimeOfBirth = domainObject.getTimeOfBirth();
if ( null != TimeOfBirth )
{
valueObject.setTimeOfBirth(new ims.framework.utils.Time(TimeOfBirth) );
}
// PatientCategory
ims.domain.lookups.LookupInstance instance37 = domainObject.getPatientCategory();
if ( null != instance37 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance37.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance37.getImage().getImageId(), instance37.getImage().getImagePath());
}
color = instance37.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.PatientStatus voLookup37 = new ims.core.vo.lookups.PatientStatus(instance37.getId(),instance37.getText(), instance37.isActive(), null, img, color);
ims.core.vo.lookups.PatientStatus parentVoLookup37 = voLookup37;
ims.domain.lookups.LookupInstance parent37 = instance37.getParent();
while (parent37 != null)
{
if (parent37.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent37.getImage().getImageId(), parent37.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent37.getColor();
if (color != null)
color.getValue();
parentVoLookup37.setParent(new ims.core.vo.lookups.PatientStatus(parent37.getId(),parent37.getText(), parent37.isActive(), null, img, color));
parentVoLookup37 = parentVoLookup37.getParent();
parent37 = parent37.getParent();
}
valueObject.setPatientCategory(voLookup37);
}
// PDSPatientGP
valueObject.setPDSPatientGP(ims.core.vo.domain.PDSPatientGPVoAssembler.create(map, domainObject.getPDSPatientGP()) );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.patient.domain.objects.Patient extractPatient(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVo valueObject)
{
return extractPatient(domainFactory, valueObject, new HashMap());
}
public static ims.core.patient.domain.objects.Patient extractPatient(ims.domain.ILightweightDomainFactory domainFactory, ims.pci.vo.ClientVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Patient();
ims.core.patient.domain.objects.Patient domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.patient.domain.objects.Patient)domMap.get(valueObject);
}
// ims.pci.vo.ClientVo ID_Patient field is unknown
domainObject = new ims.core.patient.domain.objects.Patient();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Patient());
if (domMap.get(key) != null)
{
return (ims.core.patient.domain.objects.Patient)domMap.get(key);
}
domainObject = (ims.core.patient.domain.objects.Patient) domainFactory.getDomainObject(ims.core.patient.domain.objects.Patient.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Patient());
domainObject.setAddresses(ims.core.vo.domain.PersonAddressAssembler.extractAddressList(domainFactory, valueObject.getAddresses(), domainObject.getAddresses(), domMap));
domainObject.setGp(ims.core.vo.domain.GpShortVoAssembler.extractGp(domainFactory, valueObject.getGp(), domMap));
ims.core.resource.place.domain.objects.LocSite value3 = null;
if ( null != valueObject.getGpSurgery() )
{
if (valueObject.getGpSurgery().getBoId() == null)
{
if (domMap.get(valueObject.getGpSurgery()) != null)
{
value3 = (ims.core.resource.place.domain.objects.LocSite)domMap.get(valueObject.getGpSurgery());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value3 = domainObject.getGpSurgery();
}
else
{
value3 = (ims.core.resource.place.domain.objects.LocSite)domainFactory.getDomainObject(ims.core.resource.place.domain.objects.LocSite.class, valueObject.getGpSurgery().getBoId());
}
}
domainObject.setGpSurgery(value3);
ims.core.patient.domain.objects.Patient value4 = null;
if ( null != valueObject.getClientParent() )
{
if (valueObject.getClientParent().getBoId() == null)
{
if (domMap.get(valueObject.getClientParent()) != null)
{
value4 = (ims.core.patient.domain.objects.Patient)domMap.get(valueObject.getClientParent());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value4 = domainObject.getClientParent();
}
else
{
value4 = (ims.core.patient.domain.objects.Patient)domainFactory.getDomainObject(ims.core.patient.domain.objects.Patient.class, valueObject.getClientParent().getBoId());
}
}
domainObject.setClientParent(value4);
domainObject.setCommunityCare(ims.pci.vo.domain.CommunityCareVoAssembler.extractCommunityCareDetail(domainFactory, valueObject.getCommunityCare(), domMap));
domainObject.setOtherNames(ims.core.vo.domain.PersonNameAssembler.extractPersonNameList(domainFactory, valueObject.getOtherNames(), domainObject.getOtherNames(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value7 = null;
if ( null != valueObject.getConfidentialReason() )
{
value7 =
domainFactory.getLookupInstance(valueObject.getConfidentialReason().getID());
}
domainObject.setConfidentialReason(value7);
domainObject.setIsChild(valueObject.getIsChild());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value9 = null;
if ( null != valueObject.getNationality() )
{
value9 =
domainFactory.getLookupInstance(valueObject.getNationality().getID());
}
domainObject.setNationality(value9);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value10 = null;
if ( null != valueObject.getDodSource() )
{
value10 =
domainFactory.getLookupInstance(valueObject.getDodSource().getID());
}
domainObject.setDodSource(value10);
domainObject.setName(ims.core.vo.domain.PersonNameAssembler.extractPersonName(domainFactory, valueObject.getName(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value12 = null;
if ( null != valueObject.getSex() )
{
value12 =
domainFactory.getLookupInstance(valueObject.getSex().getID());
}
domainObject.setSex(value12);
domainObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.extractAddress(domainFactory, valueObject.getAddress(), domMap));
ims.framework.utils.PartialDate dob = valueObject.getDob();
Integer value14 = null;
if ( null != dob )
{
value14 = dob.toInteger();
}
domainObject.setDob(value14);
java.util.Date value15 = null;
ims.framework.utils.Date date15 = valueObject.getDod();
if ( date15 != null )
{
value15 = date15.getDate();
}
domainObject.setDod(value15);
domainObject.setWard(ims.core.vo.domain.LocationLiteVoAssembler.extractLocation(domainFactory, valueObject.getWard(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value17 = null;
if ( null != valueObject.getReligion() )
{
value17 =
domainFactory.getLookupInstance(valueObject.getReligion().getID());
}
domainObject.setReligion(value17);
domainObject.setIdentifiers(ims.core.vo.domain.PatientIdAssembler.extractPatientIdList(domainFactory, valueObject.getIdentifiers(), domainObject.getIdentifiers(), domMap));
domainObject.setIsActive(valueObject.getIsActive());
domainObject.setAssociatedPatient(ims.core.vo.domain.PatientShortAssembler.extractPatient(domainFactory, valueObject.getAssociatedPatient(), domMap));
domainObject.setCommChannels(ims.core.vo.domain.CommChannelVoAssembler.extractCommunicationChannelList(domainFactory, valueObject.getCommChannels(), domainObject.getCommChannels(), domMap));
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value22 = null;
if ( null != valueObject.getEthnicOrigin() )
{
value22 =
domainFactory.getLookupInstance(valueObject.getEthnicOrigin().getID());
}
domainObject.setEthnicOrigin(value22);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value23 = null;
if ( null != valueObject.getMaritalStatus() )
{
value23 =
domainFactory.getLookupInstance(valueObject.getMaritalStatus().getID());
}
domainObject.setMaritalStatus(value23);
domainObject.setSCN(valueObject.getSCN());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value25 = null;
if ( null != valueObject.getSourceOfInformation() )
{
value25 =
domainFactory.getLookupInstance(valueObject.getSourceOfInformation().getID());
}
domainObject.setSourceOfInformation(value25);
ims.framework.utils.Time time27 = valueObject.getTimeOfDeath();
String value27 = null;
if ( time27 != null )
{
value27 = time27.toString();
}
domainObject.setTimeOfDeath(value27);
domainObject.setIsQuickRegistrationPatient(valueObject.getIsQuickRegistrationPatient());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.clinical.domain.objects.PatientNotification value29 = null;
if ( null != valueObject.getOCSNotification() )
{
if (valueObject.getOCSNotification().getBoId() == null)
{
if (domMap.get(valueObject.getOCSNotification()) != null)
{
value29 = (ims.core.clinical.domain.objects.PatientNotification)domMap.get(valueObject.getOCSNotification());
}
}
else
{
value29 = (ims.core.clinical.domain.objects.PatientNotification)domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientNotification.class, valueObject.getOCSNotification().getBoId());
}
}
domainObject.setOCSNotification(value29);
ims.core.resource.people.domain.objects.Medic value30 = null;
if ( null != valueObject.getCurrentResponsibleConsultant() )
{
if (valueObject.getCurrentResponsibleConsultant().getBoId() == null)
{
if (domMap.get(valueObject.getCurrentResponsibleConsultant()) != null)
{
value30 = (ims.core.resource.people.domain.objects.Medic)domMap.get(valueObject.getCurrentResponsibleConsultant());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value30 = domainObject.getCurrentResponsibleConsultant();
}
else
{
value30 = (ims.core.resource.people.domain.objects.Medic)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Medic.class, valueObject.getCurrentResponsibleConsultant().getBoId());
}
}
domainObject.setCurrentResponsibleConsultant(value30);
ims.framework.utils.DateTime dateTime31 = valueObject.getDementiaBreachDateTime();
java.util.Date value31 = null;
if ( dateTime31 != null )
{
value31 = dateTime31.getJavaDate();
}
domainObject.setDementiaBreachDateTime(value31);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value32 = null;
if ( null != valueObject.getDementiaWorklistStatus() )
{
value32 =
domainFactory.getLookupInstance(valueObject.getDementiaWorklistStatus().getID());
}
domainObject.setDementiaWorklistStatus(value32);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value33 = null;
if ( null != valueObject.getMRNStatus() )
{
value33 =
domainFactory.getLookupInstance(valueObject.getMRNStatus().getID());
}
domainObject.setMRNStatus(value33);
domainObject.setHasScannedCaseNoteFolders(valueObject.getHasScannedCaseNoteFolders());
domainObject.setIsConfidential(valueObject.getIsConfidential());
ims.framework.utils.Time time36 = valueObject.getTimeOfBirth();
String value36 = null;
if ( time36 != null )
{
value36 = time36.toString();
}
domainObject.setTimeOfBirth(value36);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value37 = null;
if ( null != valueObject.getPatientCategory() )
{
value37 =
domainFactory.getLookupInstance(valueObject.getPatientCategory().getID());
}
domainObject.setPatientCategory(value37);
domainObject.setPDSPatientGP(ims.core.vo.domain.PDSPatientGPVoAssembler.extractPatientGP(domainFactory, valueObject.getPDSPatientGP(), domMap));
return domainObject;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/EpisodeOfCareListVoCollection.java | 8755 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.admin.EpisodeOfCare business object (ID: 1004100018).
*/
public class EpisodeOfCareListVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<EpisodeOfCareListVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<EpisodeOfCareListVo> col = new ArrayList<EpisodeOfCareListVo>();
public String getBoClassName()
{
return "ims.core.admin.domain.objects.EpisodeOfCare";
}
public boolean add(EpisodeOfCareListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, EpisodeOfCareListVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(EpisodeOfCareListVo instance)
{
return col.indexOf(instance);
}
public EpisodeOfCareListVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, EpisodeOfCareListVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(EpisodeOfCareListVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(EpisodeOfCareListVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
EpisodeOfCareListVoCollection clone = new EpisodeOfCareListVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((EpisodeOfCareListVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public EpisodeOfCareListVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public EpisodeOfCareListVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public EpisodeOfCareListVoCollection sort(SortOrder order)
{
return sort(new EpisodeOfCareListVoComparator(order));
}
public EpisodeOfCareListVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new EpisodeOfCareListVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public EpisodeOfCareListVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.admin.vo.EpisodeOfCareRefVoCollection toRefVoCollection()
{
ims.core.admin.vo.EpisodeOfCareRefVoCollection result = new ims.core.admin.vo.EpisodeOfCareRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public EpisodeOfCareListVo[] toArray()
{
EpisodeOfCareListVo[] arr = new EpisodeOfCareListVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<EpisodeOfCareListVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class EpisodeOfCareListVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public EpisodeOfCareListVoComparator()
{
this(SortOrder.ASCENDING);
}
public EpisodeOfCareListVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public EpisodeOfCareListVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
EpisodeOfCareListVo voObj1 = (EpisodeOfCareListVo)obj1;
EpisodeOfCareListVo voObj2 = (EpisodeOfCareListVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.core.vo.beans.EpisodeOfCareListVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.core.vo.beans.EpisodeOfCareListVoBean[] getBeanCollectionArray()
{
ims.core.vo.beans.EpisodeOfCareListVoBean[] result = new ims.core.vo.beans.EpisodeOfCareListVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
EpisodeOfCareListVo vo = ((EpisodeOfCareListVo)col.get(i));
result[i] = (ims.core.vo.beans.EpisodeOfCareListVoBean)vo.getBean();
}
return result;
}
public static EpisodeOfCareListVoCollection buildFromBeanCollection(java.util.Collection beans)
{
EpisodeOfCareListVoCollection coll = new EpisodeOfCareListVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.EpisodeOfCareListVoBean)iter.next()).buildVo());
}
return coll;
}
public static EpisodeOfCareListVoCollection buildFromBeanCollection(ims.core.vo.beans.EpisodeOfCareListVoBean[] beans)
{
EpisodeOfCareListVoCollection coll = new EpisodeOfCareListVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
auroreallibe/Silverpeas-Core | core-web/src/test-awaiting/java/org/silverpeas/admin/web/SpaceResourceMock.java | 9514 | /*
* Copyright (C) 2000 - 2013 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 recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/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.admin.web;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.silverpeas.admin.web.AdminResourceURIs.SPACES_BASE_URI;
import java.util.ArrayList;
import java.util.Collection;
import javax.ws.rs.Path;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.silverpeas.core.webapi.admin.delegate.AdminPersonalWebDelegate;
import org.silverpeas.core.webapi.admin.tools.AbstractTool;
import org.silverpeas.core.webapi.look.delegate.LookWebDelegate;
import com.silverpeas.admin.components.WAComponent;
import com.silverpeas.annotation.Authenticated;
import com.silverpeas.annotation.RequestScoped;
import com.silverpeas.annotation.Service;
import com.stratelia.webactiv.beans.admin.AdminException;
import com.stratelia.webactiv.beans.admin.ComponentInst;
import com.stratelia.webactiv.beans.admin.SpaceInstLight;
/**
* @author Yohann Chastagnier
*/
@Service
@RequestScoped
@Path(SPACES_BASE_URI)
@Authenticated
public class SpaceResourceMock extends org.silverpeas.admin.web.SpaceResource {
AdminPersonalWebDelegate adminPersonalWebDelegateMock = null;
LookWebDelegate lookWebServiceMock = null;
/* (non-Javadoc)
* @see org.silverpeas.core.webapi.admin.AbstractAdminResource#isUserAuthorizedToAccessLookContext()
*/
@Override
protected boolean isUserAuthorizedToAccessLookContext() {
return true;
}
/*
* (non-Javadoc)
* @see org.silverpeas.core.webapi.admin.AbstractAdminResource#getLookServices()
*/
@Override
protected LookWebDelegate getLookDelegate() {
if (lookWebServiceMock == null) {
lookWebServiceMock = mock(LookWebDelegate.class);
// getUserFavorite
when(lookWebServiceMock.getUserFavorite(any(SpaceInstLight.class), anyBoolean())).thenAnswer(
new Answer<String>() {
@Override
public String answer(final InvocationOnMock invocation) throws Throwable {
final SpaceInstLight space = (SpaceInstLight) invocation.getArguments()[0];
final boolean forcingSearch = (Boolean) invocation.getArguments()[1];
String result = "false";
if (forcingSearch) {
if ("2".equals(space.getShortId())) {
result = "true";
} else if ("3".equals(space.getShortId())) {
result = "contains";
}
}
return result;
}
});
// getLook
when(lookWebServiceMock.getLook(any(SpaceInstLight.class))).thenAnswer(new Answer<String>() {
@Override
public String answer(final InvocationOnMock invocation) throws Throwable {
final SpaceInstLight space = (SpaceInstLight) invocation.getArguments()[0];
String result = "";
if ("2".equals(space.getShortId())) {
result = "look2";
}
return result;
}
});
// getWallpaper
when(lookWebServiceMock.getWallpaper(any(SpaceInstLight.class))).thenAnswer(
new Answer<String>() {
@Override
public String answer(final InvocationOnMock invocation) throws Throwable {
final SpaceInstLight space = (SpaceInstLight) invocation.getArguments()[0];
String result = "";
if ("2".equals(space.getShortId())) {
result = "wallpaper2";
}
return result;
}
});
}
return lookWebServiceMock;
}
/*
* (non-Javadoc)
* @see org.silverpeas.core.webapi.admin.AbstractAdminResource#getAdminPersonalDelegate()
*/
@Override
protected AdminPersonalWebDelegate getAdminPersonalDelegate() {
if (adminPersonalWebDelegateMock == null) {
adminPersonalWebDelegateMock = mock(AdminPersonalWebDelegate.class);
// getNotUsedComponents
when(adminPersonalWebDelegateMock.getNotUsedComponents()).thenAnswer(
new Answer<Collection<WAComponent>>() {
@Override
public Collection<WAComponent> answer(final InvocationOnMock invocation)
throws Throwable {
final Collection<WAComponent> components = new ArrayList<WAComponent>();
WAComponent component;
for (int i = 1; i <= 3; i++) {
component = new WAComponent();
component.setName("personalComponentName" + i);
components.add(component);
}
return components;
}
});
// getUsedComponent
when(adminPersonalWebDelegateMock.getUsedComponents()).thenAnswer(
new Answer<Collection<ComponentInst>>() {
/*
* (non-Javadoc)
* @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
*/
@Override
public Collection<ComponentInst> answer(final InvocationOnMock invocation)
throws Throwable {
final Collection<ComponentInst> components = new ArrayList<ComponentInst>();
ComponentInst component;
for (int i = 1; i <= 1; i++) {
component = new ComponentInst();
component.setName("personalComponentName" + i);
components.add(component);
}
return components;
}
});
// getUsedTool
when(adminPersonalWebDelegateMock.getUsedTools()).thenAnswer(
new Answer<Collection<AbstractTool>>() {
@Override
public Collection<AbstractTool> answer(final InvocationOnMock invocation)
throws Throwable {
final Collection<AbstractTool> tools = new ArrayList<AbstractTool>();
for (int i = 1; i <= 7; i++) {
final AbstractTool tool = mock(AbstractTool.class);
when(tool.getId()).thenReturn("personalToolId" + i);
tools.add(tool);
}
return tools;
}
});
// useComponent
try {
when(adminPersonalWebDelegateMock.useComponent(anyString())).thenAnswer(
new Answer<ComponentInst>() {
/*
* (non-Javadoc)
* @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
*/
@Override
public ComponentInst answer(final InvocationOnMock invocation) throws Throwable {
final String componentName = (String) invocation.getArguments()[0];
if ("<exception>".equals(componentName)) {
throw new AdminException(true);
}
final ComponentInst component = new ComponentInst();
component.setId("anId");
component.setName(componentName);
return component;
}
});
} catch (final Exception e) {
// There is no reason to have a "try catch" here, but thanks to that there is no compile
// error.
e.printStackTrace();
}
// discardComponent
try {
when(adminPersonalWebDelegateMock.discardComponent(anyString())).thenAnswer(
new Answer<WAComponent>() {
/*
* (non-Javadoc)
* @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
*/
@Override
public WAComponent answer(final InvocationOnMock invocation) throws Throwable {
final String componentName = (String) invocation.getArguments()[0];
if ("<exception>".equals(componentName)) {
throw new AdminException(true);
}
final WAComponent component = new WAComponent();
component.setName(componentName);
return component;
}
});
} catch (final Exception e) {
// There is no reason to have a "try catch" here, but thanks to that there is no compile
// error.
e.printStackTrace();
}
}
return adminPersonalWebDelegateMock;
}
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/accessiweb2.2/src/test/java/org/tanaguru/rules/accessiweb22/Aw22Rule12114Test.java | 3524 | /*
* 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.accessiweb22;
import org.tanaguru.entity.audit.TestSolution;
import org.tanaguru.rules.accessiweb22.test.Aw22RuleImplementationTestCase;
/**
* Unit test class for the implementation of the rule 12.11.4 of the referential Accessiweb 2.2.
*
* @author jkowalczyk
*/
public class Aw22Rule12114Test extends Aw22RuleImplementationTestCase {
/**
* Default constructor
*/
public Aw22Rule12114Test (String testName){
super(testName);
}
@Override
protected void setUpRuleImplementationClassName() {
setRuleImplementationClassName(
"org.tanaguru.rules.accessiweb22.Aw22Rule12114");
}
@Override
protected void setUpWebResourceMap() {
// getWebResourceMap().put("AW22.Test.12.11.4-1Passed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule12114/AW22.Test.12.11.4-1Passed-01.html"));
// getWebResourceMap().put("AW22.Test.12.11.4-2Failed-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule12114/AW22.Test.12.11.4-2Failed-01.html"));
getWebResourceMap().put("AW22.Test.12.11.4-3NMI-01",
getWebResourceFactory().createPage(
getTestcasesFilePath() + "accessiweb22/Aw22Rule12114/AW22.Test.12.11.4-3NMI-01.html"));
// getWebResourceMap().put("AW22.Test.12.11.4-4NA-01",
// getWebResourceFactory().createPage(
// getTestcasesFilePath() + "accessiweb22/Aw22Rule12114/AW22.Test.12.11.4-4NA-01.html"));
}
@Override
protected void setProcess() {
// assertEquals(TestSolution.PASSED,
// processPageTest("AW22.Test.12.11.4-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// processPageTest("AW22.Test.12.11.4-2Failed-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
processPageTest("AW22.Test.12.11.4-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// processPageTest("AW22.Test.12.11.4-4NA-01").getValue());
}
@Override
protected void setConsolidate() {
// assertEquals(TestSolution.PASSED,
// consolidate("AW22.Test.12.11.4-1Passed-01").getValue());
// assertEquals(TestSolution.FAILED,
// consolidate("AW22.Test.12.11.4-2Failed-01").getValue());
assertEquals(TestSolution.NOT_TESTED,
consolidate("AW22.Test.12.11.4-3NMI-01").getValue());
// assertEquals(TestSolution.NOT_APPLICABLE,
// consolidate("AW22.Test.12.11.4-4NA-01").getValue());
}
} | agpl-3.0 |
stephaneperry/Silverpeas-Components | question-reply/question-reply-jar/src/main/java/com/silverpeas/questionReply/QuestionReplyInstanciator.java | 3367 | /**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.questionReply;
import com.silverpeas.admin.components.ComponentsInstanciatorIntf;
import com.silverpeas.admin.components.InstanciationException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.beans.admin.SQLRequest;
import com.stratelia.webactiv.util.exception.SilverpeasException;
public class QuestionReplyInstanciator extends SQLRequest implements ComponentsInstanciatorIntf {
/** Creates new QuestionReplyInstanciator */
public QuestionReplyInstanciator() {
super("com.silverpeas.questionReply");
}
@Override
public void create(Connection con, String spaceId, String componentId, String userId) throws
InstanciationException {
}
@Override
public void delete(Connection con, String spaceId, String componentId, String userId) throws
InstanciationException {
setDeleteQueries();
deleteDataOfInstance(con, componentId, "RECIPIENT");
deleteDataOfInstance(con, componentId, "REPLY");
deleteDataOfInstance(con, componentId, "QUESTION");
}
/**
* Delete all data of one website instance from the website table.
* @param con (Connection) the connection to the data base
* @param componentId (String) the instance id of the Silverpeas component website.
* @param suffixName (String) the suffixe of a website table
*/
private void deleteDataOfInstance(Connection con, String componentId, String suffixName) throws
InstanciationException {
Statement stmt = null;
String deleteQuery = getDeleteQuery(componentId, suffixName);
try {
stmt = con.createStatement();
stmt.executeUpdate(deleteQuery);
stmt.close();
} catch (SQLException se) {
throw new InstanciationException("QuestionReplyInstanciator.deleteDataOfInstance()",
SilverpeasException.ERROR, "root.EX_SQL_QUERY_FAILED", se);
} finally {
try {
stmt.close();
} catch (SQLException err_closeStatement) {
SilverTrace.error("questionReply", "QuestionReplyInstanciator.deleteDataOfInstance()",
"root.EX_RESOURCE_CLOSE_FAILED", "", err_closeStatement);
}
}
}
} | agpl-3.0 |
ebonnet/Silverpeas-Core | core-library/src/main/java/org/silverpeas/core/personalization/notification/PersonalizationSpaceEventListener.java | 1850 | /*
* Copyright (C) 2000 - 2014 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/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.personalization.notification;
import org.silverpeas.core.personalization.service.PersonalizationService;
import org.silverpeas.core.admin.space.SpaceInst;
import org.silverpeas.core.admin.space.notification.SpaceEvent;
import org.silverpeas.core.notification.system.CDIResourceEventListener;
import javax.inject.Inject;
/**
* @author mmoquillon
*/
public class PersonalizationSpaceEventListener extends CDIResourceEventListener<SpaceEvent> {
@Inject
private PersonalizationService service;
@Override
public void onRemoving(final SpaceEvent event) throws Exception {
SpaceInst space = event.getTransition().getBefore();
service.resetDefaultSpace(space.getId());
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/domain/TheatreList.java | 8672 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.domain;
// Generated from form domain impl
public interface TheatreList extends ims.domain.DomainInterface
{
// Generated from form domain interface definition
/**
* List active locations where the location type is hospital
*/
public ims.core.vo.LocShortMappingsVoCollection listActiveHospitals(ims.core.resource.people.vo.MemberOfStaffRefVo memberOfStaff);
// Generated from form domain interface definition
public ims.core.vo.LocShortMappingsVoCollection listTheatresForHospital(ims.core.resource.place.vo.LocationRefVo hospital);
// Generated from form domain interface definition
public ims.scheduling.vo.SessionShortVoCollection listSession(ims.framework.utils.Date sessionDate, ims.core.resource.people.vo.HcpRefVo listOwner, ims.core.resource.place.vo.LocationRefVo hospital, ims.scheduling.vo.lookups.TheatreType theatreType, ims.scheduling.vo.lookups.ProfileListType listType);
// Generated from form domain interface definition
/**
* listAppointments
*/
public ims.RefMan.vo.TheatreListBookingAppointmentVoCollection listAppointments(ims.scheduling.vo.Sch_SessionRefVo session);
// Generated from form domain interface definition
/**
* listAppointments
*/
public ims.RefMan.vo.TheatreListBookingAppointmentVoCollection listAppointments(ims.core.resource.people.vo.HcpRefVo hcp, ims.core.resource.people.vo.MemberOfStaffRefVo mosUser, ims.framework.utils.Date date);
// Generated from form domain interface definition
/**
* Get PatientShort
*/
public ims.core.vo.PatientShort getPatientShort(ims.core.patient.vo.PatientRefVo voPatientRef);
// Generated from form domain interface definition
public ims.scheduling.vo.Booking_AppointmentVo getBookingAppt(ims.scheduling.vo.Booking_AppointmentRefVo bookingApptRefVo);
// Generated from form domain interface definition
/**
* listAppointments
*/
public ims.RefMan.vo.TheatreListBookingAppointmentVoCollection listAllAppointments(ims.RefMan.vo.TheatreListFilterVo filterVo);
// Generated from form domain interface definition
public ims.core.vo.ProcedureVo getProcedureLOS(ims.core.clinical.vo.ProcedureRefVo procedureRefVo);
// Generated from form domain interface definition
public ims.scheduling.vo.Sch_Session_Appointment_OrderVo getSessionOrder(ims.scheduling.vo.Sch_SessionRefVo schSessionRefVo);
// Generated from form domain interface definition
public ims.RefMan.vo.CatsReferralWizardVo getCatsReferral(ims.scheduling.vo.Booking_AppointmentRefVo voBookingRefVo);
// Generated from form domain interface definition
public Boolean isReferralAccepted(ims.scheduling.vo.Booking_AppointmentRefVo voBookingRefVo);
// Generated from form domain interface definition
public Boolean isNotACurrentInpatient(ims.core.patient.vo.PatientRefVo voPatRef);
// Generated from form domain interface definition
/**
* saveTheatreAppointment
*/
public void saveTheatreAppointment(ims.RefMan.vo.TheatreListBookingAppointmentVo appt, ims.RefMan.vo.CatsReferralWizardVo voCatsReferral, ims.scheduling.vo.SessionTheatreTCISlotLiteVo sessionSlot, ims.RefMan.vo.PatientElectiveListForDNAAppointmentsVo electiveList) throws ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
public ims.scheduling.vo.SessionTheatreTCISlotLiteVo getSessionSlot(ims.scheduling.vo.SessionTheatreTCISlotRefVo sessionSlot);
// Generated from form domain interface definition
public ims.RefMan.vo.TrackingStatusConfigVo getTrackingStatus();
// Generated from form domain interface definition
public ims.RefMan.vo.CatsReferralRefVo getCatsReferralRef(ims.scheduling.vo.Booking_AppointmentRefVo voBookingRefVo);
// Generated from form domain interface definition
public ims.RefMan.vo.TheatreTrackingIdleConfigVo getTheatreTrackingIdleConfig();
// Generated from form domain interface definition
public ims.core.vo.InpatientEpisodeVo getInpatientEpisode(ims.core.patient.vo.PatientRefVo patient);
// Generated from form domain interface definition
public ims.RefMan.vo.TheatreProcedureServiceAndConsultantLiteVo getTheatreServiceProcedureAndConsultant(ims.scheduling.vo.Booking_AppointmentRefVo appt);
// Generated from form domain interface definition
public ims.scheduling.vo.Booking_AppointmentVo cancelAppt(ims.scheduling.vo.Booking_AppointmentVo appt, ims.chooseandbook.vo.lookups.ActionRequestType requestType, String requestSource) throws ims.domain.exceptions.DomainInterfaceException, ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
public void updateCatsReferralAdditionalInvStatus(ims.RefMan.vo.CatsReferralRefVo catsReferral) throws ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
public void updateCatsReferralAdditionalInvStatus(ims.RefMan.vo.CatsReferralRefVo catsReferral, ims.scheduling.vo.Booking_AppointmentRefVo appt) throws ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
public ims.RefMan.vo.CatsReferralForTheatreListVo getCatsReferralForCancel(ims.scheduling.vo.Booking_AppointmentRefVo appointmentRef);
// Generated from form domain interface definition
public ims.scheduling.vo.BookingAppointmentTheatreVo getBookingAppointmentTheatre(ims.scheduling.vo.Booking_AppointmentRefVo appRef);
// Generated from form domain interface definition
public ims.RefMan.vo.CatsReferralRttDateForTheatreListVo getReferralWithRttDate(ims.scheduling.vo.Booking_AppointmentRefVo appRef);
// Generated from form domain interface definition
public void cancelTCIAndReferralEROD(ims.RefMan.vo.CatsReferralRefVo catsReferral, ims.scheduling.vo.Booking_AppointmentRefVo apptRef, ims.scheduling.vo.lookups.CancelAppointmentReason cancellationReason, String cancellationComment, Boolean isProviderCancellation, Boolean isPatientCancellation, Boolean cancelledForNonmedicalReason) throws ims.domain.exceptions.StaleObjectException;
// Generated from form domain interface definition
public Boolean hasTCI(ims.scheduling.vo.Booking_AppointmentRefVo appointment);
// Generated from form domain interface definition
public ims.RefMan.vo.PatientElectiveListForDNAAppointmentsVo getPatientElectiveList(ims.scheduling.vo.Booking_AppointmentRefVo appointment);
// Generated from form domain interface definition
public ims.core.vo.TCIForPatElectListForWardLiteVo getTCIForPatElectiveList(ims.scheduling.vo.Booking_AppointmentRefVo bookAppt);
}
| agpl-3.0 |
JanMarvin/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/prefs/model/SpellingPrefsContext.java | 1337 | /*
* SpellingPrefsContext.java
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.prefs.model;
import org.rstudio.studio.client.common.spelling.model.SpellingLanguage;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
public class SpellingPrefsContext extends JavaScriptObject
{
protected SpellingPrefsContext() {}
public native final boolean getAllLanguagesInstalled() /*-{
return this.all_languages_installed;
}-*/;
public native final JsArray<SpellingLanguage> getAvailableLanguages() /*-{
return this.available_languages;
}-*/;
public native final JsArrayString getCustomDictionaries() /*-{
return this.custom_dictionaries;
}-*/;
}
| agpl-3.0 |
liquidJbilling/LT-Jbilling-MsgQ-3.1 | src/java/com/sapienter/jbilling/server/user/db/CompanyDTO.java | 13752 | /*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.server.user.db;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Transient;
import javax.persistence.Version;
import com.sapienter.jbilling.server.report.db.ReportDTO;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.OrderBy;
import com.sapienter.jbilling.server.invoice.db.InvoiceDeliveryMethodDTO;
import com.sapienter.jbilling.server.item.db.ItemDTO;
import com.sapienter.jbilling.server.item.db.ItemTypeDTO;
import com.sapienter.jbilling.server.notification.db.NotificationMessageDTO;
import com.sapienter.jbilling.server.order.db.OrderPeriodDTO;
import com.sapienter.jbilling.server.payment.db.PaymentMethodDTO;
import com.sapienter.jbilling.server.process.db.AgeingEntityStepDTO;
import com.sapienter.jbilling.server.process.db.BillingProcessConfigurationDTO;
import com.sapienter.jbilling.server.process.db.BillingProcessDTO;
import com.sapienter.jbilling.server.user.contact.db.ContactTypeDTO;
import com.sapienter.jbilling.server.util.audit.db.EventLogDTO;
import com.sapienter.jbilling.server.util.db.CurrencyDTO;
import com.sapienter.jbilling.server.util.db.LanguageDTO;
@Entity
@Table(name = "entity")
@TableGenerator(
name = "entity_GEN",
table = "jbilling_seqs",
pkColumnName = "name",
valueColumnName = "next_id",
pkColumnValue = "entity",
allocationSize = 10
)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CompanyDTO implements java.io.Serializable {
private int id;
private CurrencyDTO currencyDTO;
private LanguageDTO language;
private String externalId;
private String description;
private Date createDatetime;
private Set<AgeingEntityStepDTO> ageingEntitySteps = new HashSet<AgeingEntityStepDTO>(0);
private Set<PaymentMethodDTO> paymentMethods = new HashSet<PaymentMethodDTO>(0);
private Set<OrderPeriodDTO> orderPeriodDTOs = new HashSet<OrderPeriodDTO>(0);
private Set<BillingProcessDTO> billingProcesses = new HashSet<BillingProcessDTO>(0);
private Set<UserDTO> baseUsers = new HashSet<UserDTO>(0);
private Set<ContactTypeDTO> contactTypes = new HashSet<ContactTypeDTO>(0);
private Set<ItemDTO> items = new HashSet<ItemDTO>(0);
private Set<EventLogDTO> eventLogs = new HashSet<EventLogDTO>(0);
private Set<NotificationMessageDTO> notificationMessages = new HashSet<NotificationMessageDTO>(0);
private Set<CurrencyDTO> currencyDTOs = new HashSet<CurrencyDTO>(0);
private Set<ItemTypeDTO> itemTypes = new HashSet<ItemTypeDTO>(0);
private Set<BillingProcessConfigurationDTO> billingProcessConfigurations = new HashSet<BillingProcessConfigurationDTO>(0);
private Set<InvoiceDeliveryMethodDTO> invoiceDeliveryMethods = new HashSet<InvoiceDeliveryMethodDTO>(0);
private Set<ReportDTO> reports = new HashSet<ReportDTO>();
private int versionNum;
public CompanyDTO() {
}
public CompanyDTO(int i) {
id = i;
}
public CompanyDTO(int id, CurrencyDTO currencyDTO, LanguageDTO language, String description, Date createDatetime) {
this.id = id;
this.currencyDTO = currencyDTO;
this.language = language;
this.description = description;
this.createDatetime = createDatetime;
}
public CompanyDTO(int id, CurrencyDTO currencyDTO, LanguageDTO language, String externalId, String description,
Date createDatetime, Set<AgeingEntityStepDTO> ageingEntitySteps,
Set<PaymentMethodDTO> paymentMethods, Set<OrderPeriodDTO> orderPeriodDTOs,
Set<BillingProcessDTO> billingProcesses, Set<UserDTO> baseUsers, Set<ContactTypeDTO> contactTypes,
Set<ItemDTO> items, Set<EventLogDTO> eventLogs, Set<NotificationMessageDTO> notificationMessages,
Set<CurrencyDTO> currencyDTOs,
Set<ItemTypeDTO> itemTypes, Set<BillingProcessConfigurationDTO> billingProcessConfigurations,
Set<InvoiceDeliveryMethodDTO> invoiceDeliveryMethods) {
this.id = id;
this.currencyDTO = currencyDTO;
this.language = language;
this.externalId = externalId;
this.description = description;
this.createDatetime = createDatetime;
this.ageingEntitySteps = ageingEntitySteps;
this.paymentMethods = paymentMethods;
this.orderPeriodDTOs = orderPeriodDTOs;
this.billingProcesses = billingProcesses;
this.baseUsers = baseUsers;
this.contactTypes = contactTypes;
this.items = items;
this.eventLogs = eventLogs;
this.notificationMessages = notificationMessages;
this.currencyDTOs = currencyDTOs;
this.itemTypes = itemTypes;
this.billingProcessConfigurations = billingProcessConfigurations;
this.invoiceDeliveryMethods = invoiceDeliveryMethods;
}
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "entity_GEN")
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "currency_id", nullable = false)
public CurrencyDTO getCurrency() {
return this.currencyDTO;
}
public void setCurrency(CurrencyDTO currencyDTO) {
this.currencyDTO = currencyDTO;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "language_id", nullable = false)
public LanguageDTO getLanguage() {
return this.language;
}
public void setLanguage(LanguageDTO language) {
this.language = language;
}
@Column(name = "external_id", length = 20)
public String getExternalId() {
return this.externalId;
}
public void setExternalId(String externalId) {
this.externalId = externalId;
}
@Column(name = "description", nullable = false, length = 100)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "create_datetime", nullable = false, length = 29)
public Date getCreateDatetime() {
return this.createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "company")
@OrderBy(
clause = "status_id"
)
public Set<AgeingEntityStepDTO> getAgeingEntitySteps() {
return this.ageingEntitySteps;
}
public void setAgeingEntitySteps(Set<AgeingEntityStepDTO> ageingEntitySteps) {
this.ageingEntitySteps = ageingEntitySteps;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "entity_payment_method_map", joinColumns = {
@JoinColumn(name = "entity_id", updatable = false)
}, inverseJoinColumns = {
@JoinColumn(name = "payment_method_id", updatable = false)
})
public Set<PaymentMethodDTO> getPaymentMethods() {
return this.paymentMethods;
}
public void setPaymentMethods(Set<PaymentMethodDTO> paymentMethods) {
this.paymentMethods = paymentMethods;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "company")
public Set<OrderPeriodDTO> getOrderPeriods() {
return this.orderPeriodDTOs;
}
public void setOrderPeriods(Set<OrderPeriodDTO> orderPeriodDTOs) {
this.orderPeriodDTOs = orderPeriodDTOs;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
public Set<BillingProcessDTO> getBillingProcesses() {
return this.billingProcesses;
}
public void setBillingProcesses(Set<BillingProcessDTO> billingProcesses) {
this.billingProcesses = billingProcesses;
}
/**
* Never use this method. It will run out of memory. Instead use UserDAS().findByEntityId
*
* @return
*/
@OneToMany(cascade = CascadeType.ALL, mappedBy = "company")
@LazyCollection(value = LazyCollectionOption.EXTRA)
@BatchSize(size = 100)
public Set<UserDTO> getBaseUsers() {
return this.baseUsers;
}
public void setBaseUsers(Set<UserDTO> baseUsers) {
this.baseUsers = baseUsers;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
@OrderBy(
clause = "id"
)
public Set<ContactTypeDTO> getContactTypes() {
return this.contactTypes;
}
public void setContactTypes(Set<ContactTypeDTO> contactTypes) {
this.contactTypes = contactTypes;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
public Set<ItemDTO> getItems() {
return this.items;
}
public void setItems(Set<ItemDTO> items) {
this.items = items;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "company")
public Set<EventLogDTO> getEventLogs() {
return this.eventLogs;
}
public void setEventLogs(Set<EventLogDTO> eventLogs) {
this.eventLogs = eventLogs;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
public Set<NotificationMessageDTO> getNotificationMessages() {
return this.notificationMessages;
}
public void setNotificationMessages(Set<NotificationMessageDTO> notificationMessages) {
this.notificationMessages = notificationMessages;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "currency_entity_map", joinColumns = {
@JoinColumn(name = "entity_id", updatable = false)
}, inverseJoinColumns = {
@JoinColumn(name = "currency_id", updatable = false)
})
public Set<CurrencyDTO> getCurrencies() {
return this.currencyDTOs;
}
public void setCurrencies(Set<CurrencyDTO> currencyDTOs) {
this.currencyDTOs = currencyDTOs;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
public Set<ItemTypeDTO> getItemTypes() {
return this.itemTypes;
}
public void setItemTypes(Set<ItemTypeDTO> itemTypes) {
this.itemTypes = itemTypes;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "entity")
public Set<BillingProcessConfigurationDTO> getBillingProcessConfigurations() {
return this.billingProcessConfigurations;
}
public void setBillingProcessConfigurations(Set<BillingProcessConfigurationDTO> billingProcessConfigurations) {
this.billingProcessConfigurations = billingProcessConfigurations;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "entity_delivery_method_map", joinColumns = {
@JoinColumn(name = "entity_id", updatable = false)
}, inverseJoinColumns = {
@JoinColumn(name = "method_id", updatable = false)
})
public Set<InvoiceDeliveryMethodDTO> getInvoiceDeliveryMethods() {
return this.invoiceDeliveryMethods;
}
public void setInvoiceDeliveryMethods(Set<InvoiceDeliveryMethodDTO> invoiceDeliveryMethods) {
this.invoiceDeliveryMethods = invoiceDeliveryMethods;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "entity_report_map",
joinColumns = {
@JoinColumn(name = "entity_id", updatable = false)
},
inverseJoinColumns = {
@JoinColumn(name = "report_id", updatable = false)
}
)
public Set<ReportDTO> getReports() {
return reports;
}
public void setReports(Set<ReportDTO> reports) {
this.reports = reports;
}
/*
* Conveniant methods to ease migration from entity beans
*/
@Transient
public Integer getCurrencyId() {
return currencyDTO.getId();
}
@Transient
public Integer getLanguageId() {
return language.getId();
}
@Version
@Column(name = "OPTLOCK")
public Integer getVersionNum() {
return versionNum;
}
public void setVersionNum(Integer versionNum) {
this.versionNum = versionNum;
}
@Override
public String toString() {
return " CompanyDTO: " + id;
}
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/nursingsummary/ConfigFlags.java | 2868 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
package ims.nursing.forms.nursingsummary;
import java.io.Serializable;
public final class ConfigFlags extends ims.framework.FormConfigFlags implements Serializable
{
private static final long serialVersionUID = 1L;
public final INVASIVE_DEVICE_REMOVAL_ROW_COLORClass INVASIVE_DEVICE_REMOVAL_ROW_COLOR;
public ConfigFlags(ims.framework.ConfigFlag configFlags)
{
super(configFlags);
INVASIVE_DEVICE_REMOVAL_ROW_COLOR = new INVASIVE_DEVICE_REMOVAL_ROW_COLORClass(configFlags);
}
public final class INVASIVE_DEVICE_REMOVAL_ROW_COLORClass implements Serializable
{
private static final long serialVersionUID = 1L;
private final ims.framework.ConfigFlag configFlags;
public INVASIVE_DEVICE_REMOVAL_ROW_COLORClass(ims.framework.ConfigFlag configFlags)
{
this.configFlags = configFlags;
}
public ims.framework.utils.Color getValue()
{
return (ims.framework.utils.Color)configFlags.get("INVASIVE_DEVICE_REMOVAL_ROW_COLOR");
}
}
}
| agpl-3.0 |
zheguang/voltdb | src/frontend/org/voltdb/utils/CLibrary.java | 2382 | /* This file is part of VoltDB.
* Copyright (C) 2008-2014 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.utils;
import org.voltcore.logging.VoltLogger;
import com.sun.jna.Native;
import sun.misc.SharedSecrets;
import java.io.FileDescriptor;
public class CLibrary {
private static final VoltLogger hostLog = new VoltLogger("HOST");
static {
try {
Native.register("c");
} catch (Exception e) {
hostLog.warn("Failed to load libc via JNA", e);
}
}
public static final class Rlimit extends com.sun.jna.Structure {
public long rlim_cur = 0;
public long rlim_max = 0;
}
public static final int RLIMIT_NOFILE_LINUX = 7;
public static final int RLIMIT_NOFILE_MAC_OS_X = 8;
public static native final int getrlimit(int resource, Rlimit rlimit);
/*
* Returns the limit on the number of open files or null
* on failure
*/
public static Integer getOpenFileLimit() {
try {
Rlimit rlimit = new Rlimit();
int retval =
getrlimit(
System.getProperty("os.name").equals("Linux") ? RLIMIT_NOFILE_LINUX : RLIMIT_NOFILE_MAC_OS_X,
rlimit);
if (retval != 0) {
return null;
} else if (rlimit.rlim_cur >= 1024) {
//Seems to be a sensible value that is the default or greater
return (int)rlimit.rlim_cur;
} else {
return null;
}
} catch (Exception e) {
hostLog.warn("Failed to retrieve open file limit via JNA", e);
}
return null;
}
public static native final int getpid();
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/MyOrderPasEventVoCollection.java | 8250 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.admin.pas.PAS Event business object (ID: 1014100003).
*/
public class MyOrderPasEventVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<MyOrderPasEventVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<MyOrderPasEventVo> col = new ArrayList<MyOrderPasEventVo>();
public String getBoClassName()
{
return "ims.core.admin.pas.domain.objects.PASEvent";
}
public boolean add(MyOrderPasEventVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, MyOrderPasEventVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(MyOrderPasEventVo instance)
{
return col.indexOf(instance);
}
public MyOrderPasEventVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, MyOrderPasEventVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(MyOrderPasEventVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(MyOrderPasEventVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
MyOrderPasEventVoCollection clone = new MyOrderPasEventVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((MyOrderPasEventVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public MyOrderPasEventVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public MyOrderPasEventVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public MyOrderPasEventVoCollection sort(SortOrder order)
{
return sort(new MyOrderPasEventVoComparator(order));
}
public MyOrderPasEventVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new MyOrderPasEventVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public MyOrderPasEventVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.admin.pas.vo.PASEventRefVoCollection toRefVoCollection()
{
ims.core.admin.pas.vo.PASEventRefVoCollection result = new ims.core.admin.pas.vo.PASEventRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public MyOrderPasEventVo[] toArray()
{
MyOrderPasEventVo[] arr = new MyOrderPasEventVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<MyOrderPasEventVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class MyOrderPasEventVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public MyOrderPasEventVoComparator()
{
this(SortOrder.ASCENDING);
}
public MyOrderPasEventVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public MyOrderPasEventVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
MyOrderPasEventVo voObj1 = (MyOrderPasEventVo)obj1;
MyOrderPasEventVo voObj2 = (MyOrderPasEventVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.ocrr.vo.beans.MyOrderPasEventVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.ocrr.vo.beans.MyOrderPasEventVoBean[] getBeanCollectionArray()
{
ims.ocrr.vo.beans.MyOrderPasEventVoBean[] result = new ims.ocrr.vo.beans.MyOrderPasEventVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
MyOrderPasEventVo vo = ((MyOrderPasEventVo)col.get(i));
result[i] = (ims.ocrr.vo.beans.MyOrderPasEventVoBean)vo.getBean();
}
return result;
}
public static MyOrderPasEventVoCollection buildFromBeanCollection(java.util.Collection beans)
{
MyOrderPasEventVoCollection coll = new MyOrderPasEventVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.ocrr.vo.beans.MyOrderPasEventVoBean)iter.next()).buildVo());
}
return coll;
}
public static MyOrderPasEventVoCollection buildFromBeanCollection(ims.ocrr.vo.beans.MyOrderPasEventVoBean[] beans)
{
MyOrderPasEventVoCollection coll = new MyOrderPasEventVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Clinical/src/ims/clinical/forms/familyhistory/GenForm.java | 61479 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.clinical.forms.familyhistory;
import ims.framework.*;
import ims.framework.controls.*;
import ims.framework.enumerations.*;
import ims.framework.utils.RuntimeAnchoring;
public class GenForm extends FormBridge
{
private static final long serialVersionUID = 1L;
public boolean canProvideData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).canProvideData();
}
public boolean hasData(IReportSeed[] reportSeeds)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields()).hasData();
}
public IReportField[] getData(IReportSeed[] reportSeeds)
{
return getData(reportSeeds, false);
}
public IReportField[] getData(IReportSeed[] reportSeeds, boolean excludeNulls)
{
return new ReportDataProvider(reportSeeds, this.getFormReportFields(), excludeNulls).getData();
}
public static class ctnFamilyHistoryContainer extends ContainerBridge
{
private static final long serialVersionUID = 1L;
public static class cbRelationshipComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.SupportNetworkRelationship value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.SupportNetworkRelationship value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.SupportNetworkRelationship value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.SupportNetworkRelationship value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.core.vo.lookups.SupportNetworkRelationship value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.SupportNetworkRelationship getValue()
{
return (ims.core.vo.lookups.SupportNetworkRelationship)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.SupportNetworkRelationship value)
{
super.control.setValue(value);
}
}
public static class cbLivingComboBox extends ComboBoxBridge
{
private static final long serialVersionUID = 1L;
public void newRow(ims.core.vo.lookups.YesNoUnknown value, String text)
{
super.control.newRow(value, text);
}
public void newRow(ims.core.vo.lookups.YesNoUnknown value, String text, ims.framework.utils.Image image)
{
super.control.newRow(value, text, image);
}
public void newRow(ims.core.vo.lookups.YesNoUnknown value, String text, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, textColor);
}
public void newRow(ims.core.vo.lookups.YesNoUnknown value, String text, ims.framework.utils.Image image, ims.framework.utils.Color textColor)
{
super.control.newRow(value, text, image, textColor);
}
public boolean removeRow(ims.core.vo.lookups.YesNoUnknown value)
{
return super.control.removeRow(value);
}
public ims.core.vo.lookups.YesNoUnknown getValue()
{
return (ims.core.vo.lookups.YesNoUnknown)super.control.getValue();
}
public void setValue(ims.core.vo.lookups.YesNoUnknown value)
{
super.control.setValue(value);
}
}
protected void setContext(Form form, ims.framework.interfaces.IAppForm appForm, Control control, FormLoader loader, Images form_images_local, ContextMenus contextMenus, Integer startControlID, ims.framework.utils.SizeInfo designSize, ims.framework.utils.SizeInfo runtimeSize, Integer startTabIndex, boolean skipContextValidation) throws Exception
{
if(form == null)
throw new RuntimeException("Invalid form");
if(appForm == null)
throw new RuntimeException("Invalid application form");
if(control == null); // this is to avoid eclipse warning only.
if(loader == null); // this is to avoid eclipse warning only.
if(form_images_local == null); // this is to avoid eclipse warning only.
if(contextMenus == null); // this is to avoid eclipse warning only.
if(startControlID == null)
throw new RuntimeException("Invalid startControlID");
if(designSize == null); // this is to avoid eclipse warning only.
if(runtimeSize == null); // this is to avoid eclipse warning only.
if(startTabIndex == null)
throw new RuntimeException("Invalid startTabIndex");
// Custom Controls
ims.framework.CustomComponent instance1 = factory.getEmptyCustomComponent();
RuntimeAnchoring anchoringHelper1 = new RuntimeAnchoring(designSize, runtimeSize, 424, 173, 368, 56, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT);
ims.framework.FormUiLogic m_customControlAuthoringInfoForm = loader.loadComponent(102228, appForm, startControlID * 10 + 1000, anchoringHelper1.getSize(), instance1, startTabIndex.intValue() + 1010, skipContextValidation);
//ims.framework.Control m_customControlAuthoringInfoControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1000), new Integer(424), new Integer(173), new Integer(368), new Integer(56), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, new Integer(startTabIndex.intValue() + 1010), m_customControlAuthoringInfoForm, instance1 } );
ims.framework.Control m_customControlAuthoringInfoControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1001), new Integer(anchoringHelper1.getX()), new Integer(anchoringHelper1.getY()), new Integer(anchoringHelper1.getWidth()), new Integer(anchoringHelper1.getHeight()), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, new Integer(startTabIndex.intValue() + 1010), m_customControlAuthoringInfoForm, instance1, Boolean.FALSE } );
super.addControl(m_customControlAuthoringInfoControl);
Menu[] menus1 = m_customControlAuthoringInfoForm.getForm().getRegisteredMenus();
for(int x = 0; x < menus1.length; x++)
{
form.registerMenu(menus1[x]);
}
ims.framework.CustomComponent instance2 = factory.getEmptyCustomComponent();
RuntimeAnchoring anchoringHelper2 = new RuntimeAnchoring(designSize, runtimeSize, 8, 14, 784, 64, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT);
ims.framework.FormUiLogic m_customControlCodingItemForm = loader.loadComponent(123133, appForm, startControlID * 10 + 2000, anchoringHelper2.getSize(), instance2, startTabIndex.intValue() + 2, skipContextValidation);
//ims.framework.Control m_customControlCodingItemControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1002), new Integer(8), new Integer(14), new Integer(784), new Integer(64), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, new Integer(startTabIndex.intValue() + 2), m_customControlCodingItemForm, instance2 } );
ims.framework.Control m_customControlCodingItemControl = factory.getControl(CustomComponent.class, new Object[] { control, new Integer(startControlID.intValue() + 1003), new Integer(anchoringHelper2.getX()), new Integer(anchoringHelper2.getY()), new Integer(anchoringHelper2.getWidth()), new Integer(anchoringHelper2.getHeight()), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, new Integer(startTabIndex.intValue() + 2), m_customControlCodingItemForm, instance2, Boolean.FALSE } );
super.addControl(m_customControlCodingItemControl);
Menu[] menus2 = m_customControlCodingItemForm.getForm().getRegisteredMenus();
for(int x = 0; x < menus2.length; x++)
{
form.registerMenu(menus2[x]);
}
// Label Controls
RuntimeAnchoring anchoringHelper3 = new RuntimeAnchoring(designSize, runtimeSize, 16, 105, 91, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1004), new Integer(anchoringHelper3.getX()), new Integer(anchoringHelper3.getY()), new Integer(anchoringHelper3.getWidth()), new Integer(anchoringHelper3.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Relative Name:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper4 = new RuntimeAnchoring(designSize, runtimeSize, 16, 81, 79, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1005), new Integer(anchoringHelper4.getX()), new Integer(anchoringHelper4.getY()), new Integer(anchoringHelper4.getWidth()), new Integer(anchoringHelper4.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Relationship:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper5 = new RuntimeAnchoring(designSize, runtimeSize, 16, 129, 41, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1006), new Integer(anchoringHelper5.getX()), new Integer(anchoringHelper5.getY()), new Integer(anchoringHelper5.getWidth()), new Integer(anchoringHelper5.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Notes:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper6 = new RuntimeAnchoring(designSize, runtimeSize, 432, 154, 82, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1007), new Integer(anchoringHelper6.getX()), new Integer(anchoringHelper6.getY()), new Integer(anchoringHelper6.getWidth()), new Integer(anchoringHelper6.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Age at Death:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper7 = new RuntimeAnchoring(designSize, runtimeSize, 432, 129, 43, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1008), new Integer(anchoringHelper7.getX()), new Integer(anchoringHelper7.getY()), new Integer(anchoringHelper7.getWidth()), new Integer(anchoringHelper7.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Living:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper8 = new RuntimeAnchoring(designSize, runtimeSize, 432, 106, 81, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1009), new Integer(anchoringHelper8.getX()), new Integer(anchoringHelper8.getY()), new Integer(anchoringHelper8.getWidth()), new Integer(anchoringHelper8.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Age at Onset:", new Integer(1), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper9 = new RuntimeAnchoring(designSize, runtimeSize, 432, 81, 81, 17, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1010), new Integer(anchoringHelper9.getX()), new Integer(anchoringHelper9.getY()), new Integer(anchoringHelper9.getWidth()), new Integer(anchoringHelper9.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Date of Birth:", new Integer(1), null, new Integer(0)}));
// TextBox Controls
RuntimeAnchoring anchoringHelper10 = new RuntimeAnchoring(designSize, runtimeSize, 120, 105, 224, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1011), new Integer(anchoringHelper10.getX()), new Integer(anchoringHelper10.getY()), new Integer(anchoringHelper10.getWidth()), new Integer(anchoringHelper10.getHeight()), new Integer(startTabIndex.intValue() + 1004), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT,Boolean.FALSE, new Integer(100), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
RuntimeAnchoring anchoringHelper11 = new RuntimeAnchoring(designSize, runtimeSize, 120, 129, 224, 80, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(TextBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1012), new Integer(anchoringHelper11.getX()), new Integer(anchoringHelper11.getY()), new Integer(anchoringHelper11.getWidth()), new Integer(anchoringHelper11.getHeight()), new Integer(startTabIndex.intValue() + 1005), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT,Boolean.TRUE, new Integer(500), Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, ims.framework.enumerations.CharacterCasing.NORMAL, ims.framework.enumerations.TextTrimming.NONE, "", ""}));
// Date Controls
RuntimeAnchoring anchoringHelper12 = new RuntimeAnchoring(designSize, runtimeSize, 562, 79, 184, 20, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(DateControl.class, new Object[] { control, new Integer(startControlID.intValue() + 1013), new Integer(anchoringHelper12.getX()), new Integer(anchoringHelper12.getY()), new Integer(anchoringHelper12.getWidth()), new Integer(anchoringHelper12.getHeight()), new Integer(startTabIndex.intValue() + 1006), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT,Boolean.TRUE, null, Boolean.FALSE, null, Boolean.FALSE, null}));
// ComboBox Controls
RuntimeAnchoring anchoringHelper13 = new RuntimeAnchoring(designSize, runtimeSize, 120, 81, 224, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
ComboBox m_cbRelationshipTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1014), new Integer(anchoringHelper13.getX()), new Integer(anchoringHelper13.getY()), new Integer(anchoringHelper13.getWidth()), new Integer(anchoringHelper13.getHeight()), new Integer(startTabIndex.intValue() + 1003), ControlState.DISABLED, ControlState.UNKNOWN,ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT ,Boolean.TRUE, Boolean.FALSE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.TRUE, new Integer(-1)});
addControl(m_cbRelationshipTemp);
cbRelationshipComboBox cbRelationship = (cbRelationshipComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cbRelationshipComboBox.class, m_cbRelationshipTemp);
super.addComboBox(cbRelationship);
RuntimeAnchoring anchoringHelper14 = new RuntimeAnchoring(designSize, runtimeSize, 562, 129, 214, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT);
ComboBox m_cbLivingTemp = (ComboBox)factory.getControl(ComboBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1015), new Integer(anchoringHelper14.getX()), new Integer(anchoringHelper14.getY()), new Integer(anchoringHelper14.getWidth()), new Integer(anchoringHelper14.getHeight()), new Integer(startTabIndex.intValue() + 1008), ControlState.DISABLED, ControlState.ENABLED,ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT ,Boolean.TRUE, Boolean.TRUE, SortOrder.NONE, Boolean.FALSE, new Integer(1), null, Boolean.FALSE, new Integer(-1)});
addControl(m_cbLivingTemp);
cbLivingComboBox cbLiving = (cbLivingComboBox)ComboBoxFlyweightFactory.getInstance().createComboBoxBridge(cbLivingComboBox.class, m_cbLivingTemp);
super.addComboBox(cbLiving);
// IntBox Controls
RuntimeAnchoring anchoringHelper15 = new RuntimeAnchoring(designSize, runtimeSize, 562, 152, 56, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(IntBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1016), new Integer(anchoringHelper15.getX()), new Integer(anchoringHelper15.getY()), new Integer(anchoringHelper15.getWidth()), new Integer(anchoringHelper15.getHeight()), new Integer(startTabIndex.intValue() + 1009), ControlState.DISABLED, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT,Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, new Integer(3)}));
RuntimeAnchoring anchoringHelper16 = new RuntimeAnchoring(designSize, runtimeSize, 562, 104, 56, 21, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(IntBox.class, new Object[] { control, new Integer(startControlID.intValue() + 1017), new Integer(anchoringHelper16.getX()), new Integer(anchoringHelper16.getY()), new Integer(anchoringHelper16.getWidth()), new Integer(anchoringHelper16.getHeight()), new Integer(startTabIndex.intValue() + 1007), ControlState.DISABLED, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT,Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null, null, Boolean.FALSE, new Integer(3)}));
}
protected void setCollapsed(boolean value)
{
super.container.setCollapsed(value);
}
//protected boolean isCollapsed()
//{
//return super.container.isCollapsed();
//}
protected void setCaption(String value)
{
super.container.setCaption(value);
}
public ims.core.forms.authoringinfo.IComponent customControlAuthoringInfo()
{
return (ims.core.forms.authoringinfo.IComponent)((ims.framework.cn.controls.CustomComponent)super.getControl(0)).getLogic();
}
public void setcustomControlAuthoringInfoValueChangedEvent(ims.framework.delegates.ValueChanged delegate)
{
((CustomComponent)super.getControl(0)).setValueChangedEvent(delegate);
}
public void setcustomControlAuthoringInfoVisible(boolean value)
{
((ims.framework.Control)super.getControl(0)).setVisible(value);
}
public boolean iscustomControlAuthoringInfoVisible()
{
return ((ims.framework.Control)super.getControl(0)).isVisible();
}
public void setcustomControlAuthoringInfoEnabled(boolean value)
{
((ims.framework.Control)super.getControl(0)).setEnabled(value);
}
public boolean iscustomControlAuthoringInfoEnabled()
{
return ((ims.framework.Control)super.getControl(0)).isEnabled();
}
public ims.clinical.forms.clinicalcoding.IComponent customControlCodingItem()
{
return (ims.clinical.forms.clinicalcoding.IComponent)((ims.framework.cn.controls.CustomComponent)super.getControl(1)).getLogic();
}
public void setcustomControlCodingItemValueChangedEvent(ims.framework.delegates.ValueChanged delegate)
{
((CustomComponent)super.getControl(1)).setValueChangedEvent(delegate);
}
public void setcustomControlCodingItemVisible(boolean value)
{
((ims.framework.Control)super.getControl(1)).setVisible(value);
}
public boolean iscustomControlCodingItemVisible()
{
return ((ims.framework.Control)super.getControl(1)).isVisible();
}
public void setcustomControlCodingItemEnabled(boolean value)
{
((ims.framework.Control)super.getControl(1)).setEnabled(value);
}
public boolean iscustomControlCodingItemEnabled()
{
return ((ims.framework.Control)super.getControl(1)).isEnabled();
}
public TextBox txtRelativeName()
{
return (TextBox)super.getControl(9);
}
public TextBox txtNotes()
{
return (TextBox)super.getControl(10);
}
public DateControl dateDOB()
{
return (DateControl)super.getControl(11);
}
public cbRelationshipComboBox cbRelationship()
{
return (cbRelationshipComboBox)super.getComboBox(0);
}
public cbLivingComboBox cbLiving()
{
return (cbLivingComboBox)super.getComboBox(1);
}
public IntBox intAgeDeath()
{
return (IntBox)super.getControl(14);
}
public IntBox intAgeOnset()
{
return (IntBox)super.getControl(15);
}
}
public static class grdListRow extends GridRowBridge
{
private static final long serialVersionUID = 1L;
protected grdListRow(GridRow row)
{
super(row);
}
public void showOpened(int column)
{
super.row.showOpened(column);
}
public void setcolRelativeNameReadOnly(boolean value)
{
super.row.setReadOnly(0, value);
}
public boolean iscolRelativeNameReadOnly()
{
return super.row.isReadOnly(0);
}
public void showcolRelativeNameOpened()
{
super.row.showOpened(0);
}
public void setTooltipForcolRelativeName(String value)
{
super.row.setTooltip(0, value);
}
public String getcolRelativeName()
{
return (String)super.row.get(0);
}
public void setcolRelativeName(String value)
{
super.row.set(0, value);
}
public void setCellcolRelativeNameTooltip(String value)
{
super.row.setTooltip(0, value);
}
public void setcolRelationshipReadOnly(boolean value)
{
super.row.setReadOnly(1, value);
}
public boolean iscolRelationshipReadOnly()
{
return super.row.isReadOnly(1);
}
public void showcolRelationshipOpened()
{
super.row.showOpened(1);
}
public void setTooltipForcolRelationship(String value)
{
super.row.setTooltip(1, value);
}
public ims.core.vo.lookups.SupportNetworkRelationship getcolRelationship()
{
return (ims.core.vo.lookups.SupportNetworkRelationship)super.row.get(1);
}
public void setcolRelationship(ims.core.vo.lookups.SupportNetworkRelationship value)
{
super.row.set(1, value, true);
}
public void setCellcolRelationshipTooltip(String value)
{
super.row.setTooltip(1, value);
}
public void setcolDiagnosisReadOnly(boolean value)
{
super.row.setReadOnly(2, value);
}
public boolean iscolDiagnosisReadOnly()
{
return super.row.isReadOnly(2);
}
public void showcolDiagnosisOpened()
{
super.row.showOpened(2);
}
public void setTooltipForcolDiagnosis(String value)
{
super.row.setTooltip(2, value);
}
public String getcolDiagnosis()
{
return (String)super.row.get(2);
}
public void setcolDiagnosis(String value)
{
super.row.set(2, value);
}
public void setCellcolDiagnosisTooltip(String value)
{
super.row.setTooltip(2, value);
}
public void setcolAgeOnsetReadOnly(boolean value)
{
super.row.setReadOnly(3, value);
}
public boolean iscolAgeOnsetReadOnly()
{
return super.row.isReadOnly(3);
}
public void showcolAgeOnsetOpened()
{
super.row.showOpened(3);
}
public void setTooltipForcolAgeOnset(String value)
{
super.row.setTooltip(3, value);
}
public Integer getcolAgeOnset()
{
return (Integer)super.row.get(3);
}
public void setcolAgeOnset(Integer value)
{
super.row.set(3, value);
}
public void setCellcolAgeOnsetTooltip(String value)
{
super.row.setTooltip(3, value);
}
public void setcolLivingReadOnly(boolean value)
{
super.row.setReadOnly(4, value);
}
public boolean iscolLivingReadOnly()
{
return super.row.isReadOnly(4);
}
public void showcolLivingOpened()
{
super.row.showOpened(4);
}
public void setTooltipForcolLiving(String value)
{
super.row.setTooltip(4, value);
}
public ims.core.vo.lookups.YesNoUnknown getcolLiving()
{
return (ims.core.vo.lookups.YesNoUnknown)super.row.get(4);
}
public void setcolLiving(ims.core.vo.lookups.YesNoUnknown value)
{
super.row.set(4, value, true);
}
public void setCellcolLivingTooltip(String value)
{
super.row.setTooltip(4, value);
}
public ims.vo.ValueObject getValue()
{
return (ims.vo.ValueObject)super.row.getValue();
}
public void setValue(ims.vo.ValueObject value)
{
super.row.setValue(value);
}
}
public static class grdListRowCollection extends GridRowCollectionBridge
{
private static final long serialVersionUID = 1L;
private grdListRowCollection(GridRowCollection collection)
{
super(collection);
}
public grdListRow get(int index)
{
return new grdListRow(super.collection.get(index));
}
public grdListRow newRow()
{
return new grdListRow(super.collection.newRow());
}
public grdListRow newRow(boolean autoSelect)
{
return new grdListRow(super.collection.newRow(autoSelect));
}
public grdListRow newRowAt(int index)
{
return new grdListRow(super.collection.newRowAt(index));
}
public grdListRow newRowAt(int index, boolean autoSelect)
{
return new grdListRow(super.collection.newRowAt(index, autoSelect));
}
}
public static class grdListGrid extends GridBridge
{
private static final long serialVersionUID = 1L;
private void addStringColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean bold, int sortOrder, int maxLength, boolean canGrow, ims.framework.enumerations.CharacterCasing casing)
{
super.grid.addStringColumn(caption, captionAlignment, alignment, width, readOnly, bold, sortOrder, maxLength, canGrow, casing);
}
private void addComboBoxColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, boolean autoPostBack, boolean bold, boolean canGrow, int maxDropDownItems)
{
super.grid.addComboBoxColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, autoPostBack, bold, canGrow, maxDropDownItems);
}
private void addIntColumn(String caption, int captionAlignment, int alignment, int width, boolean readOnly, boolean canBeEmpty, String validationString, boolean bold, int sortOrder, boolean canGrow)
{
super.grid.addIntColumn(caption, captionAlignment, alignment, width, readOnly, canBeEmpty, validationString, bold, sortOrder, canGrow);
}
public ims.vo.ValueObject[] getValues()
{
ims.vo.ValueObject[] listOfValues = new ims.vo.ValueObject[this.getRows().size()];
for(int x = 0; x < this.getRows().size(); x++)
{
listOfValues[x] = this.getRows().get(x).getValue();
}
return listOfValues;
}
public ims.vo.ValueObject getValue()
{
return (ims.vo.ValueObject)super.grid.getValue();
}
public void setValue(ims.vo.ValueObject value)
{
super.grid.setValue(value);
}
public grdListRow getSelectedRow()
{
return super.grid.getSelectedRow() == null ? null : new grdListRow(super.grid.getSelectedRow());
}
public int getSelectedRowIndex()
{
return super.grid.getSelectedRowIndex();
}
public grdListRowCollection getRows()
{
return new grdListRowCollection(super.grid.getRows());
}
public grdListRow getRowByValue(ims.vo.ValueObject value)
{
GridRow row = super.grid.getRowByValue(value);
return row == null?null:new grdListRow(row);
}
public void setcolRelativeNameHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(0, value);
}
public String getcolRelativeNameHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(0);
}
public void setcolRelationshipHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(1, value);
}
public String getcolRelationshipHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(1);
}
public GridComboBox colRelationshipComboBox()
{
return new GridComboBox(super.grid, 1);
}
public void setcolDiagnosisHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(2, value);
}
public String getcolDiagnosisHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(2);
}
public void setcolAgeOnsetHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(3, value);
}
public String getcolAgeOnsetHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(3);
}
public void setcolLivingHeaderTooltip(String value)
{
super.grid.setColumnHeaderTooltip(4, value);
}
public String getcolLivingHeaderTooltip()
{
return super.grid.getColumnHeaderTooltip(4);
}
public GridComboBox colLivingComboBox()
{
return new GridComboBox(super.grid, 4);
}
}
private void validateContext(ims.framework.Context context)
{
if(context == null)
return;
if(!context.isValidContextType(ims.core.vo.PatientShort.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.PatientShort' of the global context variable 'Core.PatientShort' is not supported.");
if(!context.isValidContextType(ims.core.vo.ClinicalContactShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.ClinicalContactShortVo' of the global context variable 'Core.CurrentClinicalContact' is not supported.");
if(!context.isValidContextType(ims.core.vo.EpisodeofCareShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.EpisodeofCareShortVo' of the global context variable 'Core.EpisodeofCareShort' is not supported.");
if(!context.isValidContextType(ims.core.vo.CareContextShortVo.class))
throw new ims.framework.exceptions.CodingRuntimeException("The type 'ims.core.vo.CareContextShortVo' of the global context variable 'Core.CurrentCareContext' is not supported.");
}
private void validateMandatoryContext(Context context)
{
if(new ims.framework.ContextVariable("Core.CurrentCareContext", "_cvp_Core.CurrentCareContext").getValueIsNull(context))
throw new ims.framework.exceptions.FormMandatoryContextMissingException("The required context data 'Core.CurrentCareContext' is not available.");
}
public boolean supportsRecordedInError()
{
return true;
}
public ims.vo.ValueObject getRecordedInErrorVo()
{
return this.getLocalContext().getSelectedRecord();
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context) throws Exception
{
setContext(loader, form, appForm, factory, context, Boolean.FALSE, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, Context context, Boolean skipContextValidation) throws Exception
{
setContext(loader, form, appForm, factory, context, skipContextValidation, new Integer(0), null, null, new Integer(0));
}
protected void setContext(FormLoader loader, Form form, ims.framework.interfaces.IAppForm appForm, UIFactory factory, ims.framework.Context context, Boolean skipContextValidation, Integer startControlID, ims.framework.utils.SizeInfo runtimeSize, ims.framework.Control control, Integer startTabIndex) throws Exception
{
if(loader == null); // this is to avoid eclipse warning only.
if(factory == null); // this is to avoid eclipse warning only.
if(runtimeSize == null); // this is to avoid eclipse warning only.
if(appForm == null)
throw new RuntimeException("Invalid application form");
if(startControlID == null)
throw new RuntimeException("Invalid startControlID");
if(control == null); // this is to avoid eclipse warning only.
if(startTabIndex == null)
throw new RuntimeException("Invalid startTabIndex");
this.context = context;
this.componentIdentifier = startControlID.toString();
this.formInfo = form.getFormInfo();
this.globalContext = new GlobalContext(context);
if(skipContextValidation == null || !skipContextValidation.booleanValue())
{
validateContext(context);
validateMandatoryContext(context);
}
super.setContext(form);
ims.framework.utils.SizeInfo designSize = new ims.framework.utils.SizeInfo(848, 632);
if(runtimeSize == null)
runtimeSize = designSize;
form.setWidth(runtimeSize.getWidth());
form.setHeight(runtimeSize.getHeight());
super.setFormReferences(FormReferencesFlyweightFactory.getInstance().create(Forms.class));
super.setImageReferences(ImageReferencesFlyweightFactory.getInstance().create(Images.class));
super.setGlobalContext(ContextBridgeFlyweightFactory.getInstance().create(GlobalContextBridge.class, context, false));
super.setLocalContext(new LocalContext(context, form.getFormInfo(), componentIdentifier));
// Context Menus
contextMenus = new ContextMenus();
contextMenus.contextMenuLIP = factory.createMenu(startControlID.intValue() + 1);
contextMenus.contextMenuLIPNewItem = factory.createMenuItem(startControlID.intValue() + 1, "New", true, false, new Integer(102179), true, false);
contextMenus.contextMenuLIP.add(contextMenus.contextMenuLIPNewItem);
contextMenus.contextMenuLIPUpdateItem = factory.createMenuItem(startControlID.intValue() + 2, "Edit", true, false, new Integer(102150), true, false);
contextMenus.contextMenuLIP.add(contextMenus.contextMenuLIPUpdateItem);
form.registerMenu(contextMenus.contextMenuLIP);
// Container Clasess
RuntimeAnchoring anchoringHelper17 = new RuntimeAnchoring(designSize, runtimeSize, 16, 312, 816, 272, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT);
Container m_ctnFamilyHistory = (Container)factory.getControl(Container.class, new Object[] { control, new Integer(startControlID.intValue() + 1018), new Integer(anchoringHelper17.getX()), new Integer(anchoringHelper17.getY()), new Integer(anchoringHelper17.getWidth()), new Integer(anchoringHelper17.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFTRIGHT, "Detail", new Boolean(true)});
addControl(m_ctnFamilyHistory);
ctnFamilyHistoryContainer ctnFamilyHistory = (ctnFamilyHistoryContainer)ContainerBridgeFlyweightFactory.getInstance().createContainerBridge(ctnFamilyHistoryContainer.class, m_ctnFamilyHistory, factory);
ims.framework.utils.SizeInfo m_ctnFamilyHistoryDesignSize = new ims.framework.utils.SizeInfo(816, 272);
ims.framework.utils.SizeInfo m_ctnFamilyHistoryRuntimeSize = new ims.framework.utils.SizeInfo(anchoringHelper17.getWidth(), anchoringHelper17.getHeight());
ctnFamilyHistory.setContext(form, appForm, m_ctnFamilyHistory, loader, this.getImages(), contextMenus, startControlID, m_ctnFamilyHistoryDesignSize, m_ctnFamilyHistoryRuntimeSize, startTabIndex, skipContextValidation);
super.addContainer(ctnFamilyHistory);
// Label Controls
RuntimeAnchoring anchoringHelper18 = new RuntimeAnchoring(designSize, runtimeSize, 280, 72, 0, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1019), new Integer(anchoringHelper18.getX()), new Integer(anchoringHelper18.getY()), new Integer(anchoringHelper18.getWidth()), new Integer(anchoringHelper18.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "", new Integer(0), null, new Integer(0)}));
RuntimeAnchoring anchoringHelper19 = new RuntimeAnchoring(designSize, runtimeSize, 496, 80, 0, 17, ims.framework.enumerations.ControlAnchoring.TOPLEFT);
super.addControl(factory.getControl(Label.class, new Object[] { control, new Integer(startControlID.intValue() + 1020), new Integer(anchoringHelper19.getX()), new Integer(anchoringHelper19.getY()), new Integer(anchoringHelper19.getWidth()), new Integer(anchoringHelper19.getHeight()), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.TOPLEFT, "", new Integer(0), null, new Integer(0)}));
// Button Controls
RuntimeAnchoring anchoringHelper20 = new RuntimeAnchoring(designSize, runtimeSize, 96, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1021), new Integer(anchoringHelper20.getX()), new Integer(anchoringHelper20.getY()), new Integer(anchoringHelper20.getWidth()), new Integer(anchoringHelper20.getHeight()), new Integer(startTabIndex.intValue() + 2013), ControlState.UNKNOWN, ControlState.UNKNOWN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "Edit", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper21 = new RuntimeAnchoring(designSize, runtimeSize, 16, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1022), new Integer(anchoringHelper21.getX()), new Integer(anchoringHelper21.getY()), new Integer(anchoringHelper21.getWidth()), new Integer(anchoringHelper21.getHeight()), new Integer(startTabIndex.intValue() + 2011), ControlState.ENABLED, ControlState.HIDDEN, ims.framework.enumerations.ControlAnchoring.BOTTOMLEFT, "New", Boolean.TRUE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper22 = new RuntimeAnchoring(designSize, runtimeSize, 672, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1023), new Integer(anchoringHelper22.getX()), new Integer(anchoringHelper22.getY()), new Integer(anchoringHelper22.getWidth()), new Integer(anchoringHelper22.getHeight()), new Integer(startTabIndex.intValue() + 2015), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Save", Boolean.FALSE, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
RuntimeAnchoring anchoringHelper23 = new RuntimeAnchoring(designSize, runtimeSize, 754, 592, 75, 23, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT);
super.addControl(factory.getControl(Button.class, new Object[] { control, new Integer(startControlID.intValue() + 1024), new Integer(anchoringHelper23.getX()), new Integer(anchoringHelper23.getY()), new Integer(anchoringHelper23.getWidth()), new Integer(anchoringHelper23.getHeight()), new Integer(startTabIndex.intValue() + 2017), ControlState.HIDDEN, ControlState.ENABLED, ims.framework.enumerations.ControlAnchoring.BOTTOMRIGHT, "Cancel", Boolean.FALSE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null, ims.framework.utils.Color.Default, ims.framework.utils.Color.Default }));
// Grid Controls
RuntimeAnchoring anchoringHelper24 = new RuntimeAnchoring(designSize, runtimeSize, 16, 16, 816, 288, ims.framework.enumerations.ControlAnchoring.ALL);
Grid m_grdListTemp = (Grid)factory.getControl(Grid.class, new Object[] { control, new Integer(startControlID.intValue() + 1025), new Integer(anchoringHelper24.getX()), new Integer(anchoringHelper24.getY()), new Integer(anchoringHelper24.getWidth()), new Integer(anchoringHelper24.getHeight()), new Integer(startTabIndex.intValue() + 1), ControlState.READONLY, ControlState.DISABLED, ims.framework.enumerations.ControlAnchoring.ALL,Boolean.TRUE, Boolean.FALSE, new Integer(24), Boolean.TRUE, contextMenus.contextMenuLIP, Boolean.FALSE, Boolean.FALSE, new Integer(0), null, Boolean.TRUE, Boolean.TRUE});
addControl(m_grdListTemp);
grdListGrid grdList = (grdListGrid)GridFlyweightFactory.getInstance().createGridBridge(grdListGrid.class, m_grdListTemp);
grdList.addStringColumn("Relative Name", 0, 0, 120, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL);
grdList.addComboBoxColumn("Relationship", 0, 0, 160, true, true, false, false, true, -1);
grdList.addStringColumn("Diagnosis", 0, 0, 340, true, false, 0, 0, true, ims.framework.enumerations.CharacterCasing.NORMAL);
grdList.addIntColumn("Age Onset", 0, 0, 80, true, true, null, false, 0, true);
grdList.addComboBoxColumn("Living", 0, 0, -1, true, true, false, false, true, -1);
super.addGrid(grdList);
}
public Forms getForms()
{
return (Forms)super.getFormReferences();
}
public Images getImages()
{
return (Images)super.getImageReferences();
}
public ctnFamilyHistoryContainer ctnFamilyHistory()
{
return (ctnFamilyHistoryContainer)super.getContainer(0);
}
public Button btnUpdate()
{
return (Button)super.getControl(3);
}
public Button btnNew()
{
return (Button)super.getControl(4);
}
public Button btnSave()
{
return (Button)super.getControl(5);
}
public Button btnCancel()
{
return (Button)super.getControl(6);
}
public grdListGrid grdList()
{
return (grdListGrid)super.getGrid(0);
}
public static class Forms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
private LocalFormName(int name)
{
super(name);
}
}
private Forms()
{
Core = new CoreForms();
}
public final class CoreForms implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreForms()
{
TaxonomySearch = new LocalFormName(104102);
}
public final FormName TaxonomySearch;
}
public CoreForms Core;
}
public static class Images implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private final class ImageHelper extends ims.framework.utils.ImagePath
{
private static final long serialVersionUID = 1L;
private ImageHelper(int id, String path, Integer width, Integer height)
{
super(id, path, width, height);
}
}
private Images()
{
Core = new CoreImages();
}
public final class CoreImages implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
private CoreImages()
{
Search = new ImageHelper(102120, "Images/Core/bin.gif", new Integer(15), new Integer(15));
}
public final ims.framework.utils.Image Search;
}
public final CoreImages Core;
}
public GlobalContext getGlobalContext()
{
return this.globalContext;
}
public static class GlobalContextBridge extends ContextBridge
{
private static final long serialVersionUID = 1L;
}
public LocalContext getLocalContext()
{
return (LocalContext)super.getLocalCtx();
}
public class LocalContext extends ContextBridge
{
private static final long serialVersionUID = 1L;
public LocalContext(Context context, ims.framework.FormInfo formInfo, String componentIdentifier)
{
super.setContext(context);
String prefix = formInfo.getLocalVariablesPrefix();
cxl_SelectedRecord = new ims.framework.ContextVariable("SelectedRecord", prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier + "");
cxl_CodingItemTextSubmitted = new ims.framework.ContextVariable("CodingItemTextSubmitted", prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__CodingItemTextSubmitted_" + componentIdentifier + "");
}
public boolean getSelectedRecordIsNotNull()
{
return !cxl_SelectedRecord.getValueIsNull(context);
}
public ims.clinical.vo.FamilyHistoryVo getSelectedRecord()
{
return (ims.clinical.vo.FamilyHistoryVo)cxl_SelectedRecord.getValue(context);
}
public void setSelectedRecord(ims.clinical.vo.FamilyHistoryVo value)
{
cxl_SelectedRecord.setValue(context, value);
}
private ims.framework.ContextVariable cxl_SelectedRecord = null;
public boolean getCodingItemTextSubmittedIsNotNull()
{
return !cxl_CodingItemTextSubmitted.getValueIsNull(context);
}
public String getCodingItemTextSubmitted()
{
return (String)cxl_CodingItemTextSubmitted.getValue(context);
}
public void setCodingItemTextSubmitted(String value)
{
cxl_CodingItemTextSubmitted.setValue(context, value);
}
private ims.framework.ContextVariable cxl_CodingItemTextSubmitted = null;
}
public final class ContextMenus implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public final class LIP implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
public static final int New = 1;
public static final int Update = 2;
}
public void disableAllLIPMenuItems()
{
this.contextMenuLIPNewItem.setEnabled(false);
this.contextMenuLIPUpdateItem.setEnabled(false);
}
public void hideAllLIPMenuItems()
{
this.contextMenuLIPNewItem.setVisible(false);
this.contextMenuLIPUpdateItem.setVisible(false);
}
private Menu contextMenuLIP;
public MenuItem getLIPNewItem()
{
return this.contextMenuLIPNewItem;
}
private MenuItem contextMenuLIPNewItem;
public MenuItem getLIPUpdateItem()
{
return this.contextMenuLIPUpdateItem;
}
private MenuItem contextMenuLIPUpdateItem;
}
private ContextMenus contextMenus;
public ContextMenus getContextMenus()
{
return this.contextMenus;
}
private IReportField[] getFormReportFields()
{
if(this.context == null)
return null;
if(this.reportFields == null)
this.reportFields = new ReportFields(this.context, this.formInfo, this.componentIdentifier).getReportFields();
return this.reportFields;
}
private class ReportFields
{
public ReportFields(Context context, ims.framework.FormInfo formInfo, String componentIdentifier)
{
this.context = context;
this.formInfo = formInfo;
this.componentIdentifier = componentIdentifier;
}
public IReportField[] getReportFields()
{
String prefix = formInfo.getLocalVariablesPrefix();
IReportField[] fields = new IReportField[85];
fields[0] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ID", "ID_Patient");
fields[1] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SEX", "Sex");
fields[2] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOB", "Dob");
fields[3] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-DOD", "Dod");
fields[4] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-RELIGION", "Religion");
fields[5] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISACTIVE", "IsActive");
fields[6] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ETHNICORIGIN", "EthnicOrigin");
fields[7] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-MARITALSTATUS", "MaritalStatus");
fields[8] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SCN", "SCN");
fields[9] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-SOURCEOFINFORMATION", "SourceOfInformation");
fields[10] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-TIMEOFDEATH", "TimeOfDeath");
fields[11] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-ISQUICKREGISTRATIONPATIENT", "IsQuickRegistrationPatient");
fields[12] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientShort", "BO-1001100000-CURRENTRESPONSIBLECONSULTANT", "CurrentResponsibleConsultant");
fields[13] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-ID", "ID_Patient");
fields[14] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-SEX", "Sex");
fields[15] = new ims.framework.ReportField(this.context, "_cvp_Core.PatientFilter", "BO-1001100000-DOB", "Dob");
fields[16] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ID", "ID_ClinicalContact");
fields[17] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-SPECIALTY", "Specialty");
fields[18] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CONTACTTYPE", "ContactType");
fields[19] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-STARTDATETIME", "StartDateTime");
fields[20] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ENDDATETIME", "EndDateTime");
fields[21] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-CARECONTEXT", "CareContext");
fields[22] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentClinicalContact", "BO-1004100003-ISCLINICALNOTECREATED", "IsClinicalNoteCreated");
fields[23] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ID", "ID_Hcp");
fields[24] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-HCPTYPE", "HcpType");
fields[25] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISACTIVE", "IsActive");
fields[26] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISHCPARESPONSIBLEHCP", "IsHCPaResponsibleHCP");
fields[27] = new ims.framework.ReportField(this.context, "_cvp_Core.RecordingHCP", "BO-1006100000-ISARESPONSIBLEEDCLINICIAN", "IsAResponsibleEDClinician");
fields[28] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ID", "ID_CareContext");
fields[29] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-CONTEXT", "Context");
fields[30] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ORDERINGHOSPITAL", "OrderingHospital");
fields[31] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ESTIMATEDDISCHARGEDATE", "EstimatedDischargeDate");
fields[32] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-STARTDATETIME", "StartDateTime");
fields[33] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-ENDDATETIME", "EndDateTime");
fields[34] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-LOCATIONTYPE", "LocationType");
fields[35] = new ims.framework.ReportField(this.context, "_cvp_Core.CurrentCareContext", "BO-1004100019-RESPONSIBLEHCP", "ResponsibleHCP");
fields[36] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ID", "ID_EpisodeOfCare");
fields[37] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-CARESPELL", "CareSpell");
fields[38] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-SPECIALTY", "Specialty");
fields[39] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-RELATIONSHIP", "Relationship");
fields[40] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-STARTDATE", "StartDate");
fields[41] = new ims.framework.ReportField(this.context, "_cvp_Core.EpisodeofCareShort", "BO-1004100018-ENDDATE", "EndDate");
fields[42] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[43] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALNOTE", "ClinicalNote");
fields[44] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTETYPE", "NoteType");
fields[45] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-DISCIPLINE", "Discipline");
fields[46] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CLINICALCONTACT", "ClinicalContact");
fields[47] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISDERIVEDNOTE", "IsDerivedNote");
fields[48] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEW", "ForReview");
fields[49] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[50] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-REVIEWINGDATETIME", "ReviewingDateTime");
fields[51] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISCORRECTED", "IsCorrected");
fields[52] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-ISTRANSCRIBED", "IsTranscribed");
fields[53] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-SOURCEOFNOTE", "SourceOfNote");
fields[54] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-RECORDINGDATETIME", "RecordingDateTime");
fields[55] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-INHOSPITALREPORT", "InHospitalReport");
fields[56] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-CARECONTEXT", "CareContext");
fields[57] = new ims.framework.ReportField(this.context, "_cvp_Clinical.CurrentClinicalNote", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[58] = new ims.framework.ReportField(this.context, "_cvp_STHK.AvailableBedsListFilter", "BO-1014100009-ID", "ID_BedSpaceState");
fields[59] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ID", "ID_PendingEmergencyAdmission");
fields[60] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingEmergencyAdmissionsFilter", "BO-1014100011-ADMISSIONSTATUS", "AdmissionStatus");
fields[61] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ID", "ID_InpatientEpisode");
fields[62] = new ims.framework.ReportField(this.context, "_cvp_STHK.PendingDischargesListFilter", "BO-1014100000-ESTDISCHARGEDATE", "EstDischargeDate");
fields[63] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-ID", "ID_ClinicalNotes");
fields[64] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEW", "ForReview");
fields[65] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-FORREVIEWDISCIPLINE", "ForReviewDiscipline");
fields[66] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-NOTECLASSIFICATION", "NoteClassification");
fields[67] = new ims.framework.ReportField(this.context, "_cvp_Clinical.ExtendedClinicalNotesListFilter", "BO-1011100000-CARECONTEXT", "CareContext");
fields[68] = new ims.framework.ReportField(this.context, "_cvp_Core.PasEvent", "BO-1014100003-ID", "ID_PASEvent");
fields[69] = new ims.framework.ReportField(this.context, "_cvp_Correspondence.CorrespondenceDetails", "BO-1052100001-ID", "ID_CorrespondenceDetails");
fields[70] = new ims.framework.ReportField(this.context, "_cvp_CareUk.CatsReferral", "BO-1004100035-ID", "ID_CatsReferral");
fields[71] = new ims.framework.ReportField(this.context, "_cv_Core.TaxonomyMap", "BO-1003100010-ID", "ID_TaxonomyMap");
fields[72] = new ims.framework.ReportField(this.context, "_cv_Core.TaxonomyMap", "BO-1003100010-TAXONOMYNAME", "TaxonomyName");
fields[73] = new ims.framework.ReportField(this.context, "_cv_Core.TaxonomyMap", "BO-1003100010-TAXONOMYCODE", "TaxonomyCode");
fields[74] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-ID", "ID_PatientFamilyHistory");
fields[75] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-RELATIONSHIP", "Relationship");
fields[76] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-RELATIVENAME", "RelativeName");
fields[77] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-RELATIVEDOB", "RelativeDOB");
fields[78] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-AGEATONSET", "AgeAtOnset");
fields[79] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-RELATIVELIVING", "RelativeLiving");
fields[80] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-AGEATDEATH", "AgeAtDeath");
fields[81] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-NOTES", "Notes");
fields[82] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-DIAGNOSISDESCRIPTION", "DiagnosisDescription");
fields[83] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-PATIENT", "Patient");
fields[84] = new ims.framework.ReportField(this.context, prefix + "_lv_Clinical.FamilyHistory.__internal_x_context__SelectedRecord_" + componentIdentifier, "BO-1003100056-CARECONTEXT", "CareContext");
return fields;
}
protected Context context = null;
protected ims.framework.FormInfo formInfo;
protected String componentIdentifier;
}
public String getUniqueIdentifier()
{
return null;
}
private Context context = null;
private ims.framework.FormInfo formInfo = null;
private String componentIdentifier;
private GlobalContext globalContext = null;
private IReportField[] reportFields = null;
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/SpecimenWorkListitemCustomVo.java | 28845 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.vo;
public class SpecimenWorkListitemCustomVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public SpecimenWorkListitemCustomVo()
{
}
public SpecimenWorkListitemCustomVo(ims.ocrr.vo.beans.SpecimenWorkListitemCustomVoBean bean)
{
this.worklistitemid = bean.getWorkListitemId();
this.instructionstocollector = bean.getInstructionsToCollector();
this.serviceid = bean.getServiceId();
this.servicename = bean.getServiceName();
this.investigation = bean.getInvestigation();
this.patientid = bean.getPatientId();
this.patientsurname = bean.getPatientSurname();
this.patientforename = bean.getPatientForename();
this.wardid = bean.getWardId();
this.ward = bean.getWard();
this.containerquantity = bean.getContainerQuantity();
this.adultcontainer = bean.getAdultContainer();
this.collectionstatus = bean.getCollectionStatus();
this.collector = bean.getCollector();
this.collectiondatetime = bean.getCollectionDateTime() == null ? null : bean.getCollectionDateTime().buildDateTime();
this.collectioncomments = bean.getCollectionComments();
this.collectingmos = bean.getCollectingMos();
this.specimencontainerid = bean.getSpecimenContainerId();
this.paediatriccontainer = bean.getPaediatricContainer();
this.paediatriccontainerid = bean.getPaediatricContainerId();
this.adultvolume = bean.getAdultVolume();
this.paediatricvolume = bean.getPaediatricVolume();
this.dftnooflabelsets = bean.getDftNoOfLabelSets();
this.containeradultvolume = bean.getContainerAdultVolume();
this.containerpaediatricvolume = bean.getContainerPaediatricVolume();
this.orderspecimenid = bean.getOrderSpecimenId();
this.placerordnum = bean.getPlacerOrdNum();
this.orderinvestigationid = bean.getOrderInvestigationId();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.beans.SpecimenWorkListitemCustomVoBean bean)
{
this.worklistitemid = bean.getWorkListitemId();
this.instructionstocollector = bean.getInstructionsToCollector();
this.serviceid = bean.getServiceId();
this.servicename = bean.getServiceName();
this.investigation = bean.getInvestigation();
this.patientid = bean.getPatientId();
this.patientsurname = bean.getPatientSurname();
this.patientforename = bean.getPatientForename();
this.wardid = bean.getWardId();
this.ward = bean.getWard();
this.containerquantity = bean.getContainerQuantity();
this.adultcontainer = bean.getAdultContainer();
this.collectionstatus = bean.getCollectionStatus();
this.collector = bean.getCollector();
this.collectiondatetime = bean.getCollectionDateTime() == null ? null : bean.getCollectionDateTime().buildDateTime();
this.collectioncomments = bean.getCollectionComments();
this.collectingmos = bean.getCollectingMos();
this.specimencontainerid = bean.getSpecimenContainerId();
this.paediatriccontainer = bean.getPaediatricContainer();
this.paediatriccontainerid = bean.getPaediatricContainerId();
this.adultvolume = bean.getAdultVolume();
this.paediatricvolume = bean.getPaediatricVolume();
this.dftnooflabelsets = bean.getDftNoOfLabelSets();
this.containeradultvolume = bean.getContainerAdultVolume();
this.containerpaediatricvolume = bean.getContainerPaediatricVolume();
this.orderspecimenid = bean.getOrderSpecimenId();
this.placerordnum = bean.getPlacerOrdNum();
this.orderinvestigationid = bean.getOrderInvestigationId();
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.ocrr.vo.beans.SpecimenWorkListitemCustomVoBean bean = null;
if(map != null)
bean = (ims.ocrr.vo.beans.SpecimenWorkListitemCustomVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.ocrr.vo.beans.SpecimenWorkListitemCustomVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public boolean getWorkListitemIdIsNotNull()
{
return this.worklistitemid != null;
}
public Integer getWorkListitemId()
{
return this.worklistitemid;
}
public void setWorkListitemId(Integer value)
{
this.isValidated = false;
this.worklistitemid = value;
}
public boolean getInstructionsToCollectorIsNotNull()
{
return this.instructionstocollector != null;
}
public String getInstructionsToCollector()
{
return this.instructionstocollector;
}
public static int getInstructionsToCollectorMaxLength()
{
return 255;
}
public void setInstructionsToCollector(String value)
{
this.isValidated = false;
this.instructionstocollector = value;
}
public boolean getServiceIdIsNotNull()
{
return this.serviceid != null;
}
public Integer getServiceId()
{
return this.serviceid;
}
public void setServiceId(Integer value)
{
this.isValidated = false;
this.serviceid = value;
}
public boolean getServiceNameIsNotNull()
{
return this.servicename != null;
}
public String getServiceName()
{
return this.servicename;
}
public static int getServiceNameMaxLength()
{
return 255;
}
public void setServiceName(String value)
{
this.isValidated = false;
this.servicename = value;
}
public boolean getInvestigationIsNotNull()
{
return this.investigation != null;
}
public String getInvestigation()
{
return this.investigation;
}
public static int getInvestigationMaxLength()
{
return 255;
}
public void setInvestigation(String value)
{
this.isValidated = false;
this.investigation = value;
}
public boolean getPatientIdIsNotNull()
{
return this.patientid != null;
}
public Integer getPatientId()
{
return this.patientid;
}
public void setPatientId(Integer value)
{
this.isValidated = false;
this.patientid = value;
}
public boolean getPatientSurnameIsNotNull()
{
return this.patientsurname != null;
}
public String getPatientSurname()
{
return this.patientsurname;
}
public static int getPatientSurnameMaxLength()
{
return 255;
}
public void setPatientSurname(String value)
{
this.isValidated = false;
this.patientsurname = value;
}
public boolean getPatientForenameIsNotNull()
{
return this.patientforename != null;
}
public String getPatientForename()
{
return this.patientforename;
}
public static int getPatientForenameMaxLength()
{
return 255;
}
public void setPatientForename(String value)
{
this.isValidated = false;
this.patientforename = value;
}
public boolean getWardIdIsNotNull()
{
return this.wardid != null;
}
public Integer getWardId()
{
return this.wardid;
}
public void setWardId(Integer value)
{
this.isValidated = false;
this.wardid = value;
}
public boolean getWardIsNotNull()
{
return this.ward != null;
}
public String getWard()
{
return this.ward;
}
public static int getWardMaxLength()
{
return 255;
}
public void setWard(String value)
{
this.isValidated = false;
this.ward = value;
}
public boolean getContainerQuantityIsNotNull()
{
return this.containerquantity != null;
}
public Integer getContainerQuantity()
{
return this.containerquantity;
}
public void setContainerQuantity(Integer value)
{
this.isValidated = false;
this.containerquantity = value;
}
public boolean getAdultContainerIsNotNull()
{
return this.adultcontainer != null;
}
public String getAdultContainer()
{
return this.adultcontainer;
}
public static int getAdultContainerMaxLength()
{
return 255;
}
public void setAdultContainer(String value)
{
this.isValidated = false;
this.adultcontainer = value;
}
public boolean getCollectionStatusIsNotNull()
{
return this.collectionstatus != null;
}
public Integer getCollectionStatus()
{
return this.collectionstatus;
}
public void setCollectionStatus(Integer value)
{
this.isValidated = false;
this.collectionstatus = value;
}
public boolean getCollectorIsNotNull()
{
return this.collector != null;
}
public String getCollector()
{
return this.collector;
}
public static int getCollectorMaxLength()
{
return 255;
}
public void setCollector(String value)
{
this.isValidated = false;
this.collector = value;
}
public boolean getCollectionDateTimeIsNotNull()
{
return this.collectiondatetime != null;
}
public ims.framework.utils.DateTime getCollectionDateTime()
{
return this.collectiondatetime;
}
public void setCollectionDateTime(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.collectiondatetime = value;
}
public boolean getCollectionCommentsIsNotNull()
{
return this.collectioncomments != null;
}
public String getCollectionComments()
{
return this.collectioncomments;
}
public static int getCollectionCommentsMaxLength()
{
return 255;
}
public void setCollectionComments(String value)
{
this.isValidated = false;
this.collectioncomments = value;
}
public boolean getCollectingMosIsNotNull()
{
return this.collectingmos != null;
}
public Integer getCollectingMos()
{
return this.collectingmos;
}
public void setCollectingMos(Integer value)
{
this.isValidated = false;
this.collectingmos = value;
}
public boolean getSpecimenContainerIdIsNotNull()
{
return this.specimencontainerid != null;
}
public Integer getSpecimenContainerId()
{
return this.specimencontainerid;
}
public void setSpecimenContainerId(Integer value)
{
this.isValidated = false;
this.specimencontainerid = value;
}
public boolean getPaediatricContainerIsNotNull()
{
return this.paediatriccontainer != null;
}
public String getPaediatricContainer()
{
return this.paediatriccontainer;
}
public static int getPaediatricContainerMaxLength()
{
return 255;
}
public void setPaediatricContainer(String value)
{
this.isValidated = false;
this.paediatriccontainer = value;
}
public boolean getPaediatricContainerIdIsNotNull()
{
return this.paediatriccontainerid != null;
}
public Integer getPaediatricContainerId()
{
return this.paediatriccontainerid;
}
public void setPaediatricContainerId(Integer value)
{
this.isValidated = false;
this.paediatriccontainerid = value;
}
public boolean getAdultVolumeIsNotNull()
{
return this.adultvolume != null;
}
public Float getAdultVolume()
{
return this.adultvolume;
}
public void setAdultVolume(Float value)
{
this.isValidated = false;
this.adultvolume = value;
}
public boolean getPaediatricVolumeIsNotNull()
{
return this.paediatricvolume != null;
}
public Float getPaediatricVolume()
{
return this.paediatricvolume;
}
public void setPaediatricVolume(Float value)
{
this.isValidated = false;
this.paediatricvolume = value;
}
public boolean getDftNoOfLabelSetsIsNotNull()
{
return this.dftnooflabelsets != null;
}
public Integer getDftNoOfLabelSets()
{
return this.dftnooflabelsets;
}
public void setDftNoOfLabelSets(Integer value)
{
this.isValidated = false;
this.dftnooflabelsets = value;
}
public boolean getContainerAdultVolumeIsNotNull()
{
return this.containeradultvolume != null;
}
public Float getContainerAdultVolume()
{
return this.containeradultvolume;
}
public void setContainerAdultVolume(Float value)
{
this.isValidated = false;
this.containeradultvolume = value;
}
public boolean getContainerPaediatricVolumeIsNotNull()
{
return this.containerpaediatricvolume != null;
}
public Float getContainerPaediatricVolume()
{
return this.containerpaediatricvolume;
}
public void setContainerPaediatricVolume(Float value)
{
this.isValidated = false;
this.containerpaediatricvolume = value;
}
public boolean getOrderSpecimenIdIsNotNull()
{
return this.orderspecimenid != null;
}
public Integer getOrderSpecimenId()
{
return this.orderspecimenid;
}
public void setOrderSpecimenId(Integer value)
{
this.isValidated = false;
this.orderspecimenid = value;
}
public boolean getPlacerOrdNumIsNotNull()
{
return this.placerordnum != null;
}
public String getPlacerOrdNum()
{
return this.placerordnum;
}
public static int getPlacerOrdNumMaxLength()
{
return 255;
}
public void setPlacerOrdNum(String value)
{
this.isValidated = false;
this.placerordnum = value;
}
public boolean getOrderInvestigationIdIsNotNull()
{
return this.orderinvestigationid != null;
}
public Integer getOrderInvestigationId()
{
return this.orderinvestigationid;
}
public void setOrderInvestigationId(Integer value)
{
this.isValidated = false;
this.orderinvestigationid = value;
}
public final String getIItemText()
{
return toString();
}
public final Integer getBoId()
{
return null;
}
public final String getBoClassName()
{
return null;
}
public boolean equals(Object obj)
{
if(obj == null)
return false;
if(!(obj instanceof SpecimenWorkListitemCustomVo))
return false;
SpecimenWorkListitemCustomVo compareObj = (SpecimenWorkListitemCustomVo)obj;
if(this.getWorkListitemId() == null && compareObj.getWorkListitemId() != null)
return false;
if(this.getWorkListitemId() != null && compareObj.getWorkListitemId() == null)
return false;
if(this.getWorkListitemId() != null && compareObj.getWorkListitemId() != null)
if(!this.getWorkListitemId().equals(compareObj.getWorkListitemId()))
return false;
if(this.getInstructionsToCollector() == null && compareObj.getInstructionsToCollector() != null)
return false;
if(this.getInstructionsToCollector() != null && compareObj.getInstructionsToCollector() == null)
return false;
if(this.getInstructionsToCollector() != null && compareObj.getInstructionsToCollector() != null)
if(!this.getInstructionsToCollector().equals(compareObj.getInstructionsToCollector()))
return false;
if(this.getServiceId() == null && compareObj.getServiceId() != null)
return false;
if(this.getServiceId() != null && compareObj.getServiceId() == null)
return false;
if(this.getServiceId() != null && compareObj.getServiceId() != null)
if(!this.getServiceId().equals(compareObj.getServiceId()))
return false;
if(this.getPatientId() == null && compareObj.getPatientId() != null)
return false;
if(this.getPatientId() != null && compareObj.getPatientId() == null)
return false;
if(this.getPatientId() != null && compareObj.getPatientId() != null)
if(!this.getPatientId().equals(compareObj.getPatientId()))
return false;
if(this.getWardId() == null && compareObj.getWardId() != null)
return false;
if(this.getWardId() != null && compareObj.getWardId() == null)
return false;
if(this.getWardId() != null && compareObj.getWardId() != null)
if(!this.getWardId().equals(compareObj.getWardId()))
return false;
if(this.getContainerQuantity() == null && compareObj.getContainerQuantity() != null)
return false;
if(this.getContainerQuantity() != null && compareObj.getContainerQuantity() == null)
return false;
if(this.getContainerQuantity() != null && compareObj.getContainerQuantity() != null)
if(!this.getContainerQuantity().equals(compareObj.getContainerQuantity()))
return false;
if(this.getCollectionStatus() == null && compareObj.getCollectionStatus() != null)
return false;
if(this.getCollectionStatus() != null && compareObj.getCollectionStatus() == null)
return false;
if(this.getCollectionStatus() != null && compareObj.getCollectionStatus() != null)
if(!this.getCollectionStatus().equals(compareObj.getCollectionStatus()))
return false;
if(this.getCollector() == null && compareObj.getCollector() != null)
return false;
if(this.getCollector() != null && compareObj.getCollector() == null)
return false;
if(this.getCollector() != null && compareObj.getCollector() != null)
if(!this.getCollector().equals(compareObj.getCollector()))
return false;
if(this.getCollectionDateTime() == null && compareObj.getCollectionDateTime() != null)
return false;
if(this.getCollectionDateTime() != null && compareObj.getCollectionDateTime() == null)
return false;
if(this.getCollectionDateTime() != null && compareObj.getCollectionDateTime() != null)
if(!this.getCollectionDateTime().equals(compareObj.getCollectionDateTime()))
return false;
if(this.getCollectionComments() == null && compareObj.getCollectionComments() != null)
return false;
if(this.getCollectionComments() != null && compareObj.getCollectionComments() == null)
return false;
if(this.getCollectionComments() != null && compareObj.getCollectionComments() != null)
if(!this.getCollectionComments().equals(compareObj.getCollectionComments()))
return false;
if(this.getCollectingMos() == null && compareObj.getCollectingMos() != null)
return false;
if(this.getCollectingMos() != null && compareObj.getCollectingMos() == null)
return false;
if(this.getCollectingMos() != null && compareObj.getCollectingMos() != null)
if(!this.getCollectingMos().equals(compareObj.getCollectingMos()))
return false;
if(this.getInvestigation() == null && compareObj.getInvestigation() != null)
return false;
if(this.getInvestigation() != null && compareObj.getInvestigation() == null)
return false;
if(this.getInvestigation() != null && compareObj.getInvestigation() != null)
if(!this.getInvestigation().equals(compareObj.getInvestigation()))
return false;
if(this.getSpecimenContainerId() == null && compareObj.getSpecimenContainerId() != null)
return false;
if(this.getSpecimenContainerId() != null && compareObj.getSpecimenContainerId() == null)
return false;
if(this.getSpecimenContainerId() != null && compareObj.getSpecimenContainerId() != null)
if(!this.getSpecimenContainerId().equals(compareObj.getSpecimenContainerId()))
return false;
if(this.getAdultContainer() == null && compareObj.getAdultContainer() != null)
return false;
if(this.getAdultContainer() != null && compareObj.getAdultContainer() == null)
return false;
if(this.getAdultContainer() != null && compareObj.getAdultContainer() != null)
if(!this.getAdultContainer().equals(compareObj.getAdultContainer()))
return false;
if(this.getPaediatricContainer() == null && compareObj.getPaediatricContainer() != null)
return false;
if(this.getPaediatricContainer() != null && compareObj.getPaediatricContainer() == null)
return false;
if(this.getPaediatricContainer() != null && compareObj.getPaediatricContainer() != null)
if(!this.getPaediatricContainer().equals(compareObj.getPaediatricContainer()))
return false;
if(this.getAdultVolume() == null && compareObj.getAdultVolume() != null)
return false;
if(this.getAdultVolume() != null && compareObj.getAdultVolume() == null)
return false;
if(this.getAdultVolume() != null && compareObj.getAdultVolume() != null)
if(!this.getAdultVolume().equals(compareObj.getAdultVolume()))
return false;
if(this.getPaediatricVolume() == null && compareObj.getPaediatricVolume() != null)
return false;
if(this.getPaediatricVolume() != null && compareObj.getPaediatricVolume() == null)
return false;
if(this.getPaediatricVolume() != null && compareObj.getPaediatricVolume() != null)
if(!this.getPaediatricVolume().equals(compareObj.getPaediatricVolume()))
return false;
if(this.getPaediatricContainerId() == null && compareObj.getPaediatricContainerId() != null)
return false;
if(this.getPaediatricContainerId() != null && compareObj.getPaediatricContainerId() == null)
return false;
if(this.getPaediatricContainerId() != null && compareObj.getPaediatricContainerId() != null)
return this.getPaediatricContainerId().equals(compareObj.getPaediatricContainerId());
return super.equals(obj);
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
SpecimenWorkListitemCustomVo clone = new SpecimenWorkListitemCustomVo();
clone.worklistitemid = this.worklistitemid;
clone.instructionstocollector = this.instructionstocollector;
clone.serviceid = this.serviceid;
clone.servicename = this.servicename;
clone.investigation = this.investigation;
clone.patientid = this.patientid;
clone.patientsurname = this.patientsurname;
clone.patientforename = this.patientforename;
clone.wardid = this.wardid;
clone.ward = this.ward;
clone.containerquantity = this.containerquantity;
clone.adultcontainer = this.adultcontainer;
clone.collectionstatus = this.collectionstatus;
clone.collector = this.collector;
if(this.collectiondatetime == null)
clone.collectiondatetime = null;
else
clone.collectiondatetime = (ims.framework.utils.DateTime)this.collectiondatetime.clone();
clone.collectioncomments = this.collectioncomments;
clone.collectingmos = this.collectingmos;
clone.specimencontainerid = this.specimencontainerid;
clone.paediatriccontainer = this.paediatriccontainer;
clone.paediatriccontainerid = this.paediatriccontainerid;
clone.adultvolume = this.adultvolume;
clone.paediatricvolume = this.paediatricvolume;
clone.dftnooflabelsets = this.dftnooflabelsets;
clone.containeradultvolume = this.containeradultvolume;
clone.containerpaediatricvolume = this.containerpaediatricvolume;
clone.orderspecimenid = this.orderspecimenid;
clone.placerordnum = this.placerordnum;
clone.orderinvestigationid = this.orderinvestigationid;
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(SpecimenWorkListitemCustomVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A SpecimenWorkListitemCustomVo object cannot be compared an Object of type " + obj.getClass().getName());
}
SpecimenWorkListitemCustomVo compareObj = (SpecimenWorkListitemCustomVo)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getWorkListitemId() == null && compareObj.getWorkListitemId() != null)
return -1;
if(this.getWorkListitemId() != null && compareObj.getWorkListitemId() == null)
return 1;
if(this.getWorkListitemId() != null && compareObj.getWorkListitemId() != null)
retVal = this.getWorkListitemId().compareTo(compareObj.getWorkListitemId());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.worklistitemid != null)
count++;
if(this.instructionstocollector != null)
count++;
if(this.serviceid != null)
count++;
if(this.servicename != null)
count++;
if(this.investigation != null)
count++;
if(this.patientid != null)
count++;
if(this.patientsurname != null)
count++;
if(this.patientforename != null)
count++;
if(this.wardid != null)
count++;
if(this.ward != null)
count++;
if(this.containerquantity != null)
count++;
if(this.adultcontainer != null)
count++;
if(this.collectionstatus != null)
count++;
if(this.collector != null)
count++;
if(this.collectiondatetime != null)
count++;
if(this.collectioncomments != null)
count++;
if(this.collectingmos != null)
count++;
if(this.specimencontainerid != null)
count++;
if(this.paediatriccontainer != null)
count++;
if(this.paediatriccontainerid != null)
count++;
if(this.adultvolume != null)
count++;
if(this.paediatricvolume != null)
count++;
if(this.dftnooflabelsets != null)
count++;
if(this.containeradultvolume != null)
count++;
if(this.containerpaediatricvolume != null)
count++;
if(this.orderspecimenid != null)
count++;
if(this.placerordnum != null)
count++;
if(this.orderinvestigationid != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 28;
}
protected Integer worklistitemid;
protected String instructionstocollector;
protected Integer serviceid;
protected String servicename;
protected String investigation;
protected Integer patientid;
protected String patientsurname;
protected String patientforename;
protected Integer wardid;
protected String ward;
protected Integer containerquantity;
protected String adultcontainer;
protected Integer collectionstatus;
protected String collector;
protected ims.framework.utils.DateTime collectiondatetime;
protected String collectioncomments;
protected Integer collectingmos;
protected Integer specimencontainerid;
protected String paediatriccontainer;
protected Integer paediatriccontainerid;
protected Float adultvolume;
protected Float paediatricvolume;
protected Integer dftnooflabelsets;
protected Float containeradultvolume;
protected Float containerpaediatricvolume;
protected Integer orderspecimenid;
protected String placerordnum;
protected Integer orderinvestigationid;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/beans/ChemoDosageDetailsVoBean.java | 4855 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo.beans;
public class ChemoDosageDetailsVoBean extends ims.vo.ValueObjectBean
{
public ChemoDosageDetailsVoBean()
{
}
public ChemoDosageDetailsVoBean(ims.oncology.vo.ChemoDosageDetailsVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.patientmedication = vo.getPatientMedication() == null ? null : (ims.core.vo.beans.PatientMedicationLiteVoBean)vo.getPatientMedication().getBean();
this.numberdoses = vo.getNumberDoses();
this.providerorganisation = vo.getProviderOrganisation() == null ? null : (ims.vo.LookupInstanceBean)vo.getProviderOrganisation().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.oncology.vo.ChemoDosageDetailsVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.patientmedication = vo.getPatientMedication() == null ? null : (ims.core.vo.beans.PatientMedicationLiteVoBean)vo.getPatientMedication().getBean(map);
this.numberdoses = vo.getNumberDoses();
this.providerorganisation = vo.getProviderOrganisation() == null ? null : (ims.vo.LookupInstanceBean)vo.getProviderOrganisation().getBean();
}
public ims.oncology.vo.ChemoDosageDetailsVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.oncology.vo.ChemoDosageDetailsVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.oncology.vo.ChemoDosageDetailsVo vo = null;
if(map != null)
vo = (ims.oncology.vo.ChemoDosageDetailsVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.oncology.vo.ChemoDosageDetailsVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.core.vo.beans.PatientMedicationLiteVoBean getPatientMedication()
{
return this.patientmedication;
}
public void setPatientMedication(ims.core.vo.beans.PatientMedicationLiteVoBean value)
{
this.patientmedication = value;
}
public Integer getNumberDoses()
{
return this.numberdoses;
}
public void setNumberDoses(Integer value)
{
this.numberdoses = value;
}
public ims.vo.LookupInstanceBean getProviderOrganisation()
{
return this.providerorganisation;
}
public void setProviderOrganisation(ims.vo.LookupInstanceBean value)
{
this.providerorganisation = value;
}
private Integer id;
private int version;
private ims.core.vo.beans.PatientMedicationLiteVoBean patientmedication;
private Integer numberdoses;
private ims.vo.LookupInstanceBean providerorganisation;
}
| agpl-3.0 |
medsob/Tanaguru | engine/tanaguru-i18n/src/main/java/org/tanaguru/i18n/entity/reference/LevelI18nImpl.java | 2434 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This file is part of Tanaguru.
*
* Tanaguru 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.i18n.entity.reference;
import java.io.Serializable;
import javax.persistence.*;
import org.tanaguru.entity.reference.Level;
import org.tanaguru.entity.reference.LevelImpl;
import org.tanaguru.i18n.entity.AbstractInternationalizedEntity;
import org.tanaguru.sdk.entity.i18n.Language;
/**
*
* @author jkowalczyk
*/
@Entity
@Table(name = "LEVEL_I18N")
public class LevelI18nImpl extends AbstractInternationalizedEntity<Level>
implements LevelI18n, Serializable {
private static final long serialVersionUID = 8315456347802456004L;
@Column(name = "Description")
private String description;
@Column(name = "Label")
private String label;
@ManyToOne
@JoinColumn(name = "Id_Level")
private LevelImpl target;
public LevelI18nImpl() {
super();
}
public LevelI18nImpl(Language language, Level target, String label,
String description) {
super(language, target);
this.label = label;
this.description = description;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getLabel() {
return label;
}
@Override
public Level getTarget() {
return target;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public void setLabel(String label) {
this.label = label;
}
@Override
public void setTarget(Level target) {
this.target = (LevelImpl) target;
}
} | agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/DomainObjects/src/ims/core/patient/domain/objects/MergedPatient.java | 28511 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 12/10/2015, 13:28
*
*/
package ims.core.patient.domain.objects;
/**
*
* @author Cristian Belciug
* Generated.
*/
public class MergedPatient extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1001100014;
private static final long serialVersionUID = 1001100014L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Patient Name */
private ims.core.generic.domain.objects.PersonName name;
/** Sex */
private ims.domain.lookups.LookupInstance sex;
/** Partial Date as not always fully known */
private Integer dob;
/** Date of Death */
private java.util.Date dod;
/** Patient Address */
private ims.core.generic.domain.objects.Address address;
/** Identifier's associated with Patient
* Collection of ims.core.patient.domain.objects.NonUniquePatientId.
*/
private java.util.List identifiers;
/** Patient's GP */
private ims.core.resource.people.domain.objects.Gp gp;
/** Surgery at which Patient Attends */
private ims.core.resource.place.domain.objects.LocSite gpSurgery;
/** Patient's Next of Kin */
private ims.core.patient.domain.objects.NextOfKin nok;
/** Ethnic Origin Lookup */
private ims.domain.lookups.LookupInstance ethnicOrigin;
/** Religion Lookup */
private ims.domain.lookups.LookupInstance religion;
/** Marital Status Lookup */
private ims.domain.lookups.LookupInstance maritalStatus;
/** Occupation Lookup */
private ims.domain.lookups.LookupInstance occupation;
/** Language Lookup */
private ims.domain.lookups.LookupInstance language;
/** Communication Channels
* Collection of ims.core.generic.domain.objects.CommunicationChannel.
*/
private java.util.List commChannels;
/** Patient Medical Insurance Details */
private ims.core.patient.domain.objects.NationalHealthCover insurance;
/** Collection of Patient Addresses
* Collection of ims.core.generic.domain.objects.Address.
*/
private java.util.List addresses;
/** DestiantionPatient */
private ims.core.patient.domain.objects.Patient destiantionPatient;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public MergedPatient (Integer id, int ver)
{
super(id, ver);
}
public MergedPatient ()
{
super();
}
public MergedPatient (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.core.patient.domain.objects.MergedPatient.class;
}
public ims.core.generic.domain.objects.PersonName getName() {
return name;
}
public void setName(ims.core.generic.domain.objects.PersonName name) {
this.name = name;
}
public ims.domain.lookups.LookupInstance getSex() {
return sex;
}
public void setSex(ims.domain.lookups.LookupInstance sex) {
this.sex = sex;
}
public Integer getDob() {
return dob;
}
public void setDob(Integer dob) {
this.dob = dob;
}
public java.util.Date getDod() {
return dod;
}
public void setDod(java.util.Date dod) {
this.dod = dod;
}
public ims.core.generic.domain.objects.Address getAddress() {
return address;
}
public void setAddress(ims.core.generic.domain.objects.Address address) {
this.address = address;
}
public java.util.List getIdentifiers() {
if ( null == identifiers ) {
identifiers = new java.util.ArrayList();
}
return identifiers;
}
public void setIdentifiers(java.util.List paramValue) {
this.identifiers = paramValue;
}
public ims.core.resource.people.domain.objects.Gp getGp() {
return gp;
}
public void setGp(ims.core.resource.people.domain.objects.Gp gp) {
this.gp = gp;
}
public ims.core.resource.place.domain.objects.LocSite getGpSurgery() {
return gpSurgery;
}
public void setGpSurgery(ims.core.resource.place.domain.objects.LocSite gpSurgery) {
this.gpSurgery = gpSurgery;
}
public ims.core.patient.domain.objects.NextOfKin getNok() {
return nok;
}
public void setNok(ims.core.patient.domain.objects.NextOfKin nok) {
this.nok = nok;
}
public ims.domain.lookups.LookupInstance getEthnicOrigin() {
return ethnicOrigin;
}
public void setEthnicOrigin(ims.domain.lookups.LookupInstance ethnicOrigin) {
this.ethnicOrigin = ethnicOrigin;
}
public ims.domain.lookups.LookupInstance getReligion() {
return religion;
}
public void setReligion(ims.domain.lookups.LookupInstance religion) {
this.religion = religion;
}
public ims.domain.lookups.LookupInstance getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(ims.domain.lookups.LookupInstance maritalStatus) {
this.maritalStatus = maritalStatus;
}
public ims.domain.lookups.LookupInstance getOccupation() {
return occupation;
}
public void setOccupation(ims.domain.lookups.LookupInstance occupation) {
this.occupation = occupation;
}
public ims.domain.lookups.LookupInstance getLanguage() {
return language;
}
public void setLanguage(ims.domain.lookups.LookupInstance language) {
this.language = language;
}
public java.util.List getCommChannels() {
if ( null == commChannels ) {
commChannels = new java.util.ArrayList();
}
return commChannels;
}
public void setCommChannels(java.util.List paramValue) {
this.commChannels = paramValue;
}
public ims.core.patient.domain.objects.NationalHealthCover getInsurance() {
return insurance;
}
public void setInsurance(ims.core.patient.domain.objects.NationalHealthCover insurance) {
this.insurance = insurance;
}
public java.util.List getAddresses() {
if ( null == addresses ) {
addresses = new java.util.ArrayList();
}
return addresses;
}
public void setAddresses(java.util.List paramValue) {
this.addresses = paramValue;
}
public ims.core.patient.domain.objects.Patient getDestiantionPatient() {
return destiantionPatient;
}
public void setDestiantionPatient(ims.core.patient.domain.objects.Patient destiantionPatient) {
this.destiantionPatient = destiantionPatient;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*name* :");
if (name != null)
{
auditStr.append(toShortClassName(name));
auditStr.append(name.toString());
}
auditStr.append("; ");
auditStr.append("\r\n*sex* :");
if (sex != null)
auditStr.append(sex.getText());
auditStr.append("; ");
auditStr.append("\r\n*dob* :");
auditStr.append(dob);
auditStr.append("; ");
auditStr.append("\r\n*dod* :");
auditStr.append(dod);
auditStr.append("; ");
auditStr.append("\r\n*address* :");
if (address != null)
{
auditStr.append(toShortClassName(address));
auditStr.append(address.toString());
}
auditStr.append("; ");
auditStr.append("\r\n*identifiers* :");
if (identifiers != null)
{
int i6=0;
for (i6=0; i6<identifiers.size(); i6++)
{
if (i6 > 0)
auditStr.append(",");
ims.core.patient.domain.objects.NonUniquePatientId obj = (ims.core.patient.domain.objects.NonUniquePatientId)identifiers.get(i6);
if (obj != null)
{
if (i6 == 0)
{
auditStr.append(toShortClassName(obj));
auditStr.append("[");
}
auditStr.append(obj.toString());
}
}
if (i6 > 0)
auditStr.append("] " + i6);
}
auditStr.append("; ");
auditStr.append("\r\n*gp* :");
if (gp != null)
{
auditStr.append(toShortClassName(gp));
auditStr.append(gp.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*gpSurgery* :");
if (gpSurgery != null)
{
auditStr.append(toShortClassName(gpSurgery));
auditStr.append(gpSurgery.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*nok* :");
if (nok != null)
{
auditStr.append(toShortClassName(nok));
auditStr.append(nok.getId());
}
auditStr.append("; ");
auditStr.append("\r\n*ethnicOrigin* :");
if (ethnicOrigin != null)
auditStr.append(ethnicOrigin.getText());
auditStr.append("; ");
auditStr.append("\r\n*religion* :");
if (religion != null)
auditStr.append(religion.getText());
auditStr.append("; ");
auditStr.append("\r\n*maritalStatus* :");
if (maritalStatus != null)
auditStr.append(maritalStatus.getText());
auditStr.append("; ");
auditStr.append("\r\n*occupation* :");
if (occupation != null)
auditStr.append(occupation.getText());
auditStr.append("; ");
auditStr.append("\r\n*language* :");
if (language != null)
auditStr.append(language.getText());
auditStr.append("; ");
auditStr.append("\r\n*commChannels* :");
if (commChannels != null)
{
int i15=0;
for (i15=0; i15<commChannels.size(); i15++)
{
if (i15 > 0)
auditStr.append(",");
ims.core.generic.domain.objects.CommunicationChannel obj = (ims.core.generic.domain.objects.CommunicationChannel)commChannels.get(i15);
if (obj != null)
{
if (i15 == 0)
{
auditStr.append(toShortClassName(obj));
auditStr.append("[");
}
auditStr.append(obj.toString());
}
}
if (i15 > 0)
auditStr.append("] " + i15);
}
auditStr.append("; ");
auditStr.append("\r\n*insurance* :");
if (insurance != null)
{
auditStr.append(toShortClassName(insurance));
auditStr.append(insurance.toString());
}
auditStr.append("; ");
auditStr.append("\r\n*addresses* :");
if (addresses != null)
{
int i17=0;
for (i17=0; i17<addresses.size(); i17++)
{
if (i17 > 0)
auditStr.append(",");
ims.core.generic.domain.objects.Address obj = (ims.core.generic.domain.objects.Address)addresses.get(i17);
if (obj != null)
{
if (i17 == 0)
{
auditStr.append(toShortClassName(obj));
auditStr.append("[");
}
auditStr.append(obj.toString());
}
}
if (i17 > 0)
auditStr.append("] " + i17);
}
auditStr.append("; ");
auditStr.append("\r\n*destiantionPatient* :");
if (destiantionPatient != null)
{
auditStr.append(toShortClassName(destiantionPatient));
auditStr.append(destiantionPatient.getId());
}
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "MergedPatient";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getName() != null)
{
sb.append("<name>");
sb.append(this.getName().toXMLString(domMap));
sb.append("</name>");
}
if (this.getSex() != null)
{
sb.append("<sex>");
sb.append(this.getSex().toXMLString());
sb.append("</sex>");
}
if (this.getDob() != null)
{
sb.append("<dob>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getDob().toString()));
sb.append("</dob>");
}
if (this.getDod() != null)
{
sb.append("<dod>");
sb.append(new ims.framework.utils.DateTime(this.getDod()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</dod>");
}
if (this.getAddress() != null)
{
sb.append("<address>");
sb.append(this.getAddress().toXMLString(domMap));
sb.append("</address>");
}
if (this.getIdentifiers() != null)
{
if (this.getIdentifiers().size() > 0 )
{
sb.append("<identifiers>");
sb.append(ims.domain.DomainObject.toXMLString(this.getIdentifiers(), domMap));
sb.append("</identifiers>");
}
}
if (this.getGp() != null)
{
sb.append("<gp>");
sb.append(this.getGp().toXMLString(domMap));
sb.append("</gp>");
}
if (this.getGpSurgery() != null)
{
sb.append("<gpSurgery>");
sb.append(this.getGpSurgery().toXMLString(domMap));
sb.append("</gpSurgery>");
}
if (this.getNok() != null)
{
sb.append("<nok>");
sb.append(this.getNok().toXMLString(domMap));
sb.append("</nok>");
}
if (this.getEthnicOrigin() != null)
{
sb.append("<ethnicOrigin>");
sb.append(this.getEthnicOrigin().toXMLString());
sb.append("</ethnicOrigin>");
}
if (this.getReligion() != null)
{
sb.append("<religion>");
sb.append(this.getReligion().toXMLString());
sb.append("</religion>");
}
if (this.getMaritalStatus() != null)
{
sb.append("<maritalStatus>");
sb.append(this.getMaritalStatus().toXMLString());
sb.append("</maritalStatus>");
}
if (this.getOccupation() != null)
{
sb.append("<occupation>");
sb.append(this.getOccupation().toXMLString());
sb.append("</occupation>");
}
if (this.getLanguage() != null)
{
sb.append("<language>");
sb.append(this.getLanguage().toXMLString());
sb.append("</language>");
}
if (this.getCommChannels() != null)
{
if (this.getCommChannels().size() > 0 )
{
sb.append("<commChannels>");
sb.append(ims.domain.DomainObject.toXMLString(this.getCommChannels(), domMap));
sb.append("</commChannels>");
}
}
if (this.getInsurance() != null)
{
sb.append("<insurance>");
sb.append(this.getInsurance().toXMLString(domMap));
sb.append("</insurance>");
}
if (this.getAddresses() != null)
{
if (this.getAddresses().size() > 0 )
{
sb.append("<addresses>");
sb.append(ims.domain.DomainObject.toXMLString(this.getAddresses(), domMap));
sb.append("</addresses>");
}
}
if (this.getDestiantionPatient() != null)
{
sb.append("<destiantionPatient>");
sb.append(this.getDestiantionPatient().toXMLString(domMap));
sb.append("</destiantionPatient>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
MergedPatient domainObject = getMergedPatientfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
MergedPatient domainObject = getMergedPatientfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static MergedPatient getMergedPatientfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getMergedPatientfromXML(doc.getRootElement(), factory, domMap);
}
public static MergedPatient getMergedPatientfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!MergedPatient.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!MergedPatient.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the MergedPatient class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (MergedPatient)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(MergedPatient.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
MergedPatient ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (MergedPatient)factory.getImportedDomainObject(MergedPatient.class, externalSource, extId);
if (ret == null)
{
ret = new MergedPatient();
}
String keyClassName = "MergedPatient";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (MergedPatient)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, MergedPatient obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("name");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setName(ims.core.generic.domain.objects.PersonName.getPersonNamefromXML(fldEl, factory, domMap));
}
fldEl = el.element("sex");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setSex(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("dob");
if(fldEl != null)
{
obj.setDob(new Integer(fldEl.getTextTrim()));
}
fldEl = el.element("dod");
if(fldEl != null)
{
obj.setDod(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("address");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setAddress(ims.core.generic.domain.objects.Address.getAddressfromXML(fldEl, factory, domMap));
}
fldEl = el.element("identifiers");
if(fldEl != null)
{
fldEl = fldEl.element("list");
obj.setIdentifiers(ims.core.patient.domain.objects.NonUniquePatientId.fromListXMLString(fldEl, factory, obj.getIdentifiers(), domMap));
}
fldEl = el.element("gp");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setGp(ims.core.resource.people.domain.objects.Gp.getGpfromXML(fldEl, factory, domMap));
}
fldEl = el.element("gpSurgery");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setGpSurgery(ims.core.resource.place.domain.objects.LocSite.getLocSitefromXML(fldEl, factory, domMap));
}
fldEl = el.element("nok");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setNok(ims.core.patient.domain.objects.NextOfKin.getNextOfKinfromXML(fldEl, factory, domMap));
}
fldEl = el.element("ethnicOrigin");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setEthnicOrigin(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("religion");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setReligion(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("maritalStatus");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setMaritalStatus(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("occupation");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setOccupation(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("language");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setLanguage(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("commChannels");
if(fldEl != null)
{
fldEl = fldEl.element("list");
obj.setCommChannels(ims.core.generic.domain.objects.CommunicationChannel.fromListXMLString(fldEl, factory, obj.getCommChannels(), domMap));
}
fldEl = el.element("insurance");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setInsurance(ims.core.patient.domain.objects.NationalHealthCover.getNationalHealthCoverfromXML(fldEl, factory, domMap));
}
fldEl = el.element("addresses");
if(fldEl != null)
{
fldEl = fldEl.element("list");
obj.setAddresses(ims.core.generic.domain.objects.Address.fromListXMLString(fldEl, factory, obj.getAddresses(), domMap));
}
fldEl = el.element("destiantionPatient");
if(fldEl != null)
{
fldEl = fldEl.element("class");
obj.setDestiantionPatient(ims.core.patient.domain.objects.Patient.getPatientfromXML(fldEl, factory, domMap));
}
}
public static String[] getCollectionFields()
{
return new String[]{
"identifiers"
, "commChannels"
, "addresses"
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String Name = "name";
public static final String Sex = "sex";
public static final String Dob = "dob";
public static final String Dod = "dod";
public static final String Address = "address";
public static final String Identifiers = "identifiers";
public static final String Gp = "gp";
public static final String GpSurgery = "gpSurgery";
public static final String Nok = "nok";
public static final String EthnicOrigin = "ethnicOrigin";
public static final String Religion = "religion";
public static final String MaritalStatus = "maritalStatus";
public static final String Occupation = "occupation";
public static final String Language = "language";
public static final String CommChannels = "commChannels";
public static final String Insurance = "insurance";
public static final String Addresses = "addresses";
public static final String DestiantionPatient = "destiantionPatient";
}
}
| agpl-3.0 |
erdincay/ejb | src/com/lp/server/anfrage/fastlanereader/AnfragepositionartHandler.java | 11940 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* 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: developers@heliumv.com
******************************************************************************/
package com.lp.server.anfrage.fastlanereader;
import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.lp.server.anfrage.fastlanereader.generated.FLRAnfragepositionart;
import com.lp.server.anfrage.service.AnfrageServiceFac;
import com.lp.server.util.fastlanereader.FLRSessionFactory;
import com.lp.server.util.fastlanereader.UseCaseHandler;
import com.lp.server.util.fastlanereader.service.query.FilterBlock;
import com.lp.server.util.fastlanereader.service.query.FilterKriterium;
import com.lp.server.util.fastlanereader.service.query.QueryParameters;
import com.lp.server.util.fastlanereader.service.query.QueryResult;
import com.lp.server.util.fastlanereader.service.query.SortierKriterium;
import com.lp.server.util.fastlanereader.service.query.TableInfo;
import com.lp.util.EJBExceptionLP;
/**
* <p>
* <I>FLR fuer ANF_ANFRAGEPOSITIONART.</I>
* </p>
*
* <p>
* Copyright Logistik Pur Software GmbH (c) 2004-2007
* </p>
*
* <p>
* Erstellungsdatum <I>12.09.05</I>
* </p>
*
* <p>
* </p>
*
* @author Uli Walch
* @version 1.0
*/
public class AnfragepositionartHandler extends UseCaseHandler {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String FLR_ANFRAGEPOSITIONART = "flranfragepositionart.";
public static final String FLR_ANFRAGEPOSITIONART_FROM_CLAUSE = " from FLRAnfragepositionart flranfragepositionart ";
/**
* gets the page of data for the specified row using the current
* queryParameters.
*
* @param rowIndex
* diese Zeile soll selektiert sein
* @return QueryResult das Ergebnis der Abfrage
* @throws EJBExceptionLP
* Ausnahme
* @see UseCaseHandler#getPageAt(java.lang.Integer)
*/
public QueryResult getPageAt(Integer rowIndex) throws EJBExceptionLP {
QueryResult result = null;
SessionFactory factory = FLRSessionFactory.getFactory();
Session session = null;
try {
int colCount = getTableInfo().getColumnClasses().length;
int pageSize = AnfragepositionartHandler.PAGE_SIZE;
int startIndex = Math.max(rowIndex.intValue() - (pageSize / 2), 0);
int endIndex = startIndex + pageSize - 1;
session = factory.openSession();
String queryString = this.getFromClause() + this.buildWhereClause()
+ this.buildOrderByClause();
// myLogger.info("HQL: " + queryString);
Query query = session.createQuery(queryString);
query.setFirstResult(startIndex);
query.setMaxResults(pageSize);
List<?> resultList = query.list();
Iterator<?> resultListIterator = resultList.iterator();
Object[][] rows = new Object[resultList.size()][colCount];
int row = 0;
int col = 0;
while (resultListIterator.hasNext()) {
FLRAnfragepositionart positionart = (FLRAnfragepositionart) resultListIterator
.next();
rows[row][col++] = positionart.getPositionsart_c_nr();
rows[row][col++] = getSystemMultilanguageFac()
.uebersetzePositionsartOptimal(
positionart.getPositionsart_c_nr(),
theClientDto.getLocUi(),
theClientDto.getLocMandant());
rows[row][col++] = positionart.getI_sort();
row++;
col = 0;
}
result = new QueryResult(rows, this.getRowCount(), startIndex,
endIndex, 0);
} catch (Exception e) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
} finally {
try {
session.close();
} catch (HibernateException he) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
}
}
return result;
}
/**
* gets the total number of rows represented by the current query.
*
* @return int die Anzehl der Zeilen im Ergebnis
* @see UseCaseHandler#getRowCountFromDataBase()
*/
protected long getRowCountFromDataBase() {
long rowCount = 0;
SessionFactory factory = FLRSessionFactory.getFactory();
Session session = null;
try {
session = factory.openSession();
String queryString = "select count(*) " + this.getFromClause()
+ this.buildWhereClause();
Query query = session.createQuery(queryString);
List<?> rowCountResult = query.list();
if (rowCountResult != null && rowCountResult.size() > 0) {
rowCount = ((Long) rowCountResult.get(0)).longValue();
}
} catch (Exception e) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException he) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER_HIBERNATE,
he);
}
}
}
return rowCount;
}
/**
* builds the where clause of the HQL (Hibernate Query Language) statement
* using the current query.
*
* @return the HQL where clause.
*/
private String buildWhereClause() {
StringBuffer where = new StringBuffer("");
if (this.getQuery() != null && this.getQuery().getFilterBlock() != null
&& this.getQuery().getFilterBlock().filterKrit != null) {
FilterBlock filterBlock = this.getQuery().getFilterBlock();
FilterKriterium[] filterKriterien = this.getQuery()
.getFilterBlock().filterKrit;
String booleanOperator = filterBlock.boolOperator;
boolean filterAdded = false;
for (int i = 0; i < filterKriterien.length; i++) {
if (filterKriterien[i].isKrit) {
if (filterAdded) {
where.append(" " + booleanOperator);
}
filterAdded = true;
where.append(" " + FLR_ANFRAGEPOSITIONART
+ filterKriterien[i].kritName);
where.append(" " + filterKriterien[i].operator);
where.append(" " + filterKriterien[i].value);
}
}
if (filterAdded) {
where.insert(0, " WHERE");
}
}
return where.toString();
}
/**
* builds the HQL (Hibernate Query Language) order by clause using the sort
* criterias contained in the current query.
*
* @return the HQL order by clause.
*/
private String buildOrderByClause() {
StringBuffer orderBy = new StringBuffer("");
if (this.getQuery() != null) {
SortierKriterium[] kriterien = this.getQuery().getSortKrit();
boolean sortAdded = false;
if (kriterien != null && kriterien.length > 0) {
for (int i = 0; i < kriterien.length; i++) {
if (kriterien[i].isKrit) {
if (sortAdded) {
orderBy.append(", ");
}
sortAdded = true;
orderBy.append(FLR_ANFRAGEPOSITIONART
+ kriterien[i].kritName);
orderBy.append(" ");
orderBy.append(kriterien[i].value);
}
}
} else {
// no sort criteria found, add default sort
if (sortAdded) {
orderBy.append(", ");
}
orderBy.append(FLR_ANFRAGEPOSITIONART).append("i_sort").append(
" ASC ");
sortAdded = true;
}
if (orderBy.indexOf(FLR_ANFRAGEPOSITIONART + "i_sort") < 0) {
// unique sort required because otherwise rowNumber of
// selectedId
// within sort() method may be different from the position of
// selectedId
// as returned in the page of getPageAt().
if (sortAdded) {
orderBy.append(", ");
}
orderBy.append(" ").append(FLR_ANFRAGEPOSITIONART).append(
"i_sort").append(" ");
sortAdded = true;
}
if (sortAdded) {
orderBy.insert(0, " ORDER BY ");
}
}
return orderBy.toString();
}
/**
* get the basic from clause for the HQL statement.
*
* @return the from clause.
*/
private String getFromClause() {
return FLR_ANFRAGEPOSITIONART_FROM_CLAUSE;
}
public TableInfo getTableInfo() {
if (super.getTableInfo() == null) {
setTableInfo(new TableInfo(new Class[] { String.class,
String.class, Integer.class
}, new String[] {
AnfrageServiceFac.FLR_ANFRAGEPOSITIONART_POSITIONSART_C_NR,
getTextRespectUISpr("lp.kennung",
theClientDto.getMandant(),
theClientDto.getLocUi()),
getTextRespectUISpr("lp.sort", theClientDto
.getMandant(),theClientDto
.getLocUi()) }, new int[] {
QueryParameters.FLR_BREITE_SHARE_WITH_REST,
QueryParameters.FLR_BREITE_SHARE_WITH_REST,
QueryParameters.FLR_BREITE_M }, new String[] {
AnfrageServiceFac.FLR_ANFRAGEPOSITIONART_POSITIONSART_C_NR,
AnfrageServiceFac.FLR_ANFRAGEPOSITIONART_POSITIONSART_C_NR,
"i_sort" }));
}
return super.getTableInfo();
}
/**
* sorts the data of the current query using the specified criterias and
* returns the page of data where the row of selectedId is contained.
*
* @param sortierKriterien
* nach diesen Kriterien wird das Ergebnis sortiert
* @param selectedId
* auf diesem Datensatz soll der Cursor stehen
* @return QueryResult das Ergebnis der Abfrage
* @throws EJBExceptionLP
* Ausnahme
* @see UseCaseHandler#sort(SortierKriterium[], Object)
*/
public QueryResult sort(SortierKriterium[] sortierKriterien,
Object selectedId) throws EJBExceptionLP {
this.getQuery().setSortKrit(sortierKriterien);
QueryResult result = null;
int rowNumber = 0;
if (selectedId != null) {
SessionFactory factory = FLRSessionFactory.getFactory();
Session session = null;
try {
session = factory.openSession();
String queryString = "select "
+ FLR_ANFRAGEPOSITIONART
+ AnfrageServiceFac.FLR_ANFRAGEPOSITIONART_POSITIONSART_C_NR
+ FLR_ANFRAGEPOSITIONART_FROM_CLAUSE
+ this.buildWhereClause() + this.buildOrderByClause();
Query query = session.createQuery(queryString);
ScrollableResults scrollableResult = query.scroll();
if (scrollableResult != null) {
scrollableResult.beforeFirst();
while (scrollableResult.next()) {
String c_nr = (String) scrollableResult.getString(0);
if (selectedId.equals(c_nr)) {
rowNumber = scrollableResult.getRowNumber();
break;
}
}
}
} catch (Exception e) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FLR, e);
} finally {
try {
session.close();
} catch (HibernateException he) {
throw new EJBExceptionLP(EJBExceptionLP.FEHLER, he);
}
}
}
if (rowNumber < 0 || rowNumber >= this.getRowCount()) {
rowNumber = 0;
}
result = this.getPageAt(new Integer(rowNumber));
result.setIndexOfSelectedRow(rowNumber);
return result;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Admin/src/ims/admin/domain/impl/ServiceStatsImpl.java | 3902 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Michael Noonan using IMS Development Environment (version 1.53 build 2620.27330)
// Copyright (C) 1995-2007 IMS MAXIMS plc. All rights reserved.
package ims.admin.domain.impl;
import java.util.ArrayList;
import java.util.List;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorComposite;
import com.jamonapi.MonitorFactory;
import ims.admin.domain.base.impl.BaseServiceStatsImpl;
import ims.framework.utils.DateTime;
import ims.admin.vo.ServiceMonitorVoCollection;
import ims.admin.vo.ServiceMonitorVo;
public class ServiceStatsImpl extends BaseServiceStatsImpl
{
private static final long serialVersionUID = 1L;
/**
* Resets all the Monitor counters
*/
public void resetMonitor()
{
MonitorFactory.getRootMonitor().reset();
}
/**
* Retrieves all the Service Monitor Values
*/
public ServiceMonitorVoCollection getServiceMonitors(String filter)
{
MonitorComposite rootMonitor = MonitorFactory.getRootMonitor();
Monitor[] allMonitors = rootMonitor.getMonitors();
ServiceMonitorVoCollection ret = new ServiceMonitorVoCollection();
Monitor currentMonitor = null;
String serviceName = null;
for (int i = 0; i < allMonitors.length; i++)
{
currentMonitor = allMonitors[i];
ServiceMonitorVo vo = new ServiceMonitorVo();
List list = new ArrayList();
currentMonitor.getMonKey().getRowData(list);
serviceName = list.get(0).toString();
if (filter == null || filter.equals("") || (serviceName.indexOf(filter) != -1))
{
vo.setServiceName(serviceName);
vo.setHits(new Integer((int) currentMonitor.getHits()));
vo.setAvg(new Integer((int) currentMonitor.getAvg()));
vo.setTotal(new Integer((int) currentMonitor.getTotal()));
vo.setStdDev(new Float((float) currentMonitor.getStdDev()));
vo.setLast(new Float((float) currentMonitor.getLastValue()));
vo.setMin(new Float((float) currentMonitor.getMin()));
vo.setMax(new Float((float) currentMonitor.getMax()));
vo.setActive(new Integer((int) currentMonitor.getActive()));
vo.setAvgActive(new Float((float) currentMonitor.getAvgActive()));
vo.setMaxActive(new Integer((int) currentMonitor.getMaxActive()));
vo.setFirstAccess(new DateTime(currentMonitor.getFirstAccess()));
vo.setLastAccess(new DateTime(currentMonitor.getLastAccess()));
ret.add(vo);
}
}
return ret;
}
}
| agpl-3.0 |
DemandCube/NeverwinterDP | registry/vm/src/main/java/com/neverwinterdp/vm/event/VMEvent.java | 710 | package com.neverwinterdp.vm.event;
import com.neverwinterdp.registry.event.NodeEvent;
import com.neverwinterdp.registry.event.Event;
public class VMEvent extends Event {
static public enum VMAttr { vmdescriptor, vmstatus, heartbeat, master_leader}
final static public String VM_STATUS = "vm-status" ;
final static public String VM_HEARTBEAT = "vm-heartbeat" ;
final static public String VM_MASTER_ELECTION = "vm-master-election" ;
public VMEvent(String name, NodeEvent event) {
super(name, event);
}
public void attr(VMAttr attr, Object value) {
attr(attr.toString(), value);
}
public <T> T attr(VMAttr attr) {
return (T) attr(attr.toString());
}
} | agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/lookups/PASSpecialtyCollection.java | 4802 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo.lookups;
import ims.framework.cn.data.TreeModel;
import ims.framework.cn.data.TreeNode;
import ims.vo.LookupInstanceCollection;
import ims.vo.LookupInstVo;
public class PASSpecialtyCollection extends LookupInstanceCollection implements ims.vo.ImsCloneable, TreeModel
{
private static final long serialVersionUID = 1L;
public void add(PASSpecialty value)
{
super.add(value);
}
public int indexOf(PASSpecialty instance)
{
return super.indexOf(instance);
}
public boolean contains(PASSpecialty instance)
{
return indexOf(instance) >= 0;
}
public PASSpecialty get(int index)
{
return (PASSpecialty)super.getIndex(index);
}
public void remove(PASSpecialty instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public Object clone()
{
PASSpecialtyCollection newCol = new PASSpecialtyCollection();
PASSpecialty item;
for (int i = 0; i < super.size(); i++)
{
item = this.get(i);
newCol.add(new PASSpecialty(item.getID(), item.getText(), item.isActive(), item.getParent(), item.getImage(), item.getColor(), item.getOrder()));
}
for (int i = 0; i < newCol.size(); i++)
{
item = newCol.get(i);
if (item.getParent() != null)
{
int parentIndex = this.indexOf(item.getParent());
if(parentIndex >= 0)
item.setParent(newCol.get(parentIndex));
else
item.setParent((PASSpecialty)item.getParent().clone());
}
}
return newCol;
}
public PASSpecialty getInstance(int instanceId)
{
return (PASSpecialty)super.getInstanceById(instanceId);
}
public TreeNode[] getRootNodes()
{
LookupInstVo[] roots = super.getRoots();
TreeNode[] nodes = new TreeNode[roots.length];
System.arraycopy(roots, 0, nodes, 0, roots.length);
return nodes;
}
public PASSpecialty[] toArray()
{
PASSpecialty[] arr = new PASSpecialty[this.size()];
super.toArray(arr);
return arr;
}
public static PASSpecialtyCollection buildFromBeanCollection(java.util.Collection beans)
{
PASSpecialtyCollection coll = new PASSpecialtyCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while(iter.hasNext())
{
coll.add(PASSpecialty.buildLookup((ims.vo.LookupInstanceBean)iter.next()));
}
return coll;
}
public static PASSpecialtyCollection buildFromBeanCollection(ims.vo.LookupInstanceBean[] beans)
{
PASSpecialtyCollection coll = new PASSpecialtyCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(PASSpecialty.buildLookup(beans[x]));
}
return coll;
}
}
| agpl-3.0 |
gortiz/mongowp | mongowp-core/src/main/java/com/torodb/mongowp/fields/BooleanField.java | 833 | /*
* Copyright 2014 8Kdata Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.torodb.mongowp.fields;
import com.torodb.mongowp.bson.BsonBoolean;
/**
*
*/
public class BooleanField extends BsonField<Boolean, BsonBoolean> {
public BooleanField(String fieldName) {
super(fieldName);
}
}
| agpl-3.0 |
medsob/Tanaguru | ws/tanaguru-ws/src/main/java/com/oceaneconsulting/tanaguru/ws/types/AuditLaunchResult.java | 650 | package com.oceaneconsulting.tanaguru.ws.types;
import java.io.Serializable;
/**
* Audit launching result.
*
* @author shamdi at oceaneconsulting dot com
*
*/
public class AuditLaunchResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = -790338109931724106L;
private Long idAudit;
private String message = "";
public Long getIdAudit() {
return idAudit;
}
public void setIdAudit(Long idAudit) {
this.idAudit = idAudit;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| agpl-3.0 |
aborg0/RapidMiner-Unuk | src/com/rapidminer/gui/renderer/visualization/LiftChartRenderer.java | 3187 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.renderer.visualization;
import java.awt.Component;
import com.rapidminer.gui.plotter.Plotter;
import com.rapidminer.gui.plotter.PlotterAdapter;
import com.rapidminer.gui.plotter.PlotterConfigurationModel;
import com.rapidminer.gui.plotter.charts.ParetoChartPlotter;
import com.rapidminer.gui.renderer.AbstractRenderer;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.visualization.LiftParetoChart;
import com.rapidminer.report.Reportable;
/**
* A renderer for the Lift Pareto chart.
*
* @author Ingo Mierswa
*/
public class LiftChartRenderer extends AbstractRenderer {
public String getName() {
return "Plot";
}
private Plotter createLiftChartPlotter(Object renderable) {
LiftParetoChart paretoChartInformation = (LiftParetoChart)renderable;
PlotterConfigurationModel settings = new PlotterConfigurationModel(PlotterConfigurationModel.PARETO_PLOT, paretoChartInformation.getLiftChartData());
Plotter plotter = settings.getPlotter();
settings.setParameterAsString(ParetoChartPlotter.PARAMETER_SUFFIX_AXIS + PlotterAdapter.transformParameterName(plotter.getAxisName(0)), settings.getDataTable().getColumnName(0));
settings.setParameterAsString(ParetoChartPlotter.PARAMETER_PLOT_COLUMN, settings.getDataTable().getColumnName(1));
settings.setParameterAsString(ParetoChartPlotter.PARAMETER_COUNT_VALUE, paretoChartInformation.getTargetValue());
settings.setParameterAsInt(ParetoChartPlotter.PARAMETER_SORTING_DIRECTION, ParetoChartPlotter.KEYS_DESCENDING);
settings.setParameterAsBoolean(ParetoChartPlotter.PARAMETER_SHOW_BAR_LABELS, paretoChartInformation.showBarLabels());
settings.setParameterAsBoolean(ParetoChartPlotter.PARAMETER_SHOW_CUMULATIVE_LABELS, paretoChartInformation.showCumulativeLabels());
settings.setParameterAsBoolean(ParetoChartPlotter.PARAMETER_ROTATE_LABELS, paretoChartInformation.rotateLabels());
return plotter;
}
public Reportable createReportable(Object renderable, IOContainer ioContainer, int width, int height) {
Plotter plotter = createLiftChartPlotter(renderable);
plotter.getRenderComponent().setSize(width, height);
return plotter;
}
public Component getVisualizationComponent(Object renderable, IOContainer ioContainer) {
return createLiftChartPlotter(renderable).getPlotter();
}
}
| agpl-3.0 |
accesstest3/cfunambol | common/server-framework/src/test/java/com/funambol/server/thread/ThreadToolsTest.java | 11129 | /*
* 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.server.thread;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import junit.framework.TestCase;
/**
* ThreadTools's test case
*/
public class ThreadToolsTest extends TestCase {
public ThreadToolsTest(String testName) {
super(testName);
}
// -------------------------------------------------------------- Test cases
/**
* Test of stopThreadById method, of class ThreadTools.
*/
public void testStopThreadById() {
String threadName = "stop-by-id";
Thread thread = new SimpleThread(threadName);
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.stopThreadById(id);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadById(id) != null );
assertFalse("Thread still running", threadFound);
}
/**
* Test of stopThreadByName method, of class ThreadTools.
*/
public void testStopThreadByName() {
String threadName = "stop-by-name";
Thread thread = new SimpleThread(threadName);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.stopThreadByName(threadName);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadByName(threadName) != null );
assertFalse("Thread still running", threadFound); }
/**
* Test of interruptThreadById method, of class ThreadTools.
*/
public void testInterruptThreadById_not_interruptable() {
String threadName = "interrupt-by-id-not-interruptable";
Thread thread = new SimpleThread(threadName, false);
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.interruptThreadById(id);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadById(id) != null );
assertTrue("Thread should be still alive", threadFound);
}
/**
* Test of interruptThreadById method, of class ThreadTools.
*/
public void testInterruptThreadById() {
String threadName = "interrupt-by-id";
Thread thread = new SimpleThread(threadName, true);
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.interruptThreadById(id);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadById(id) != null );
assertFalse("Thread still running", threadFound);
}
/**
* Test of interruptThreadByName method, of class ThreadTools.
*/
public void testInterruptThreadByName() {
String threadName = "interrupt-by-name";
Thread thread = new SimpleThread(threadName, true); // interruptable thread
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.interruptThreadByName(threadName);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadByName(threadName) != null );
assertFalse("Thread still running", threadFound);
}
/**
* Test of interruptThreadByName method, of class ThreadTools.
*/
public void testInterruptThreadByName_not_interruptable() {
String threadName = "interrupt-by-name-not-interruptable";
Thread thread = new SimpleThread(threadName, false); // not interruptable thread
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadTools.interruptThreadByName(threadName);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean threadFound = ( ThreadTools.getThreadByName(threadName) != null );
assertTrue("Thread should be still alive", threadFound);
}
/**
* Test of getThreadById method, of class ThreadTools.
*/
public void testGetThreadById() {
String threadName = "get-by-id";
Thread thread = new SimpleThread(threadName, false);
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
Thread th2 = ThreadTools.getThreadById(id);
assertEquals("Thread not found", thread, th2);
}
/**
* Test of getThreadIdByName method, of class ThreadTools.
*/
public void testGetThreadIdByName() {
String threadName = "get-id-by-name [dev-id] [username]";
Thread thread = new SimpleThread(threadName, false);
Long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
Long idTh = ThreadTools.getThreadIdByName("get-id-by-name [] s[]");
assertEquals("Wrong id", id, idTh);
threadName = "get-id-by-name-2";
thread = new SimpleThread(threadName, false);
id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
idTh = ThreadTools.getThreadIdByName(threadName);
assertEquals("Wrong id", id, idTh);
}
/**
* Test of getThreadByName method, of class ThreadTools.
*/
public void testGetThreadByName() {
String threadName = "get-by-name";
Thread thread = new SimpleThread(threadName, false);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
Thread th2 = ThreadTools.getThreadByName(threadName);
assertEquals("Thread not found", thread, th2);
String realThreadName = "get-by-name-2 [deviceid] [username]";
threadName = "get-by-name-2";
thread = new SimpleThread(realThreadName, false);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
th2 = ThreadTools.getThreadByName(threadName);
assertEquals("Thread not found", thread, th2);
}
/**
* Test of getStackTraceAsString method, of class ThreadTools.
*/
public void testGetStackTraceAsString_Thread() {
String threadName = "stack-trace";
Thread thread = new SimpleThread(threadName, true); // interruptable thread
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
String stack = ThreadTools.getStackTraceAsString(thread);
assertTrue("Missing thread id", stack.indexOf("(id=" + id + ")") != -1);
assertTrue("Wrong stack trace", stack.indexOf("at java.lang.Thread.sleep") != -1);
assertTrue("Wrong stack trace", stack.indexOf("at com.funambol.server.thread.ThreadToolsTest$SimpleThread.run(ThreadToolsTest.java") != -1);
}
/**
* Test of getStackTraceAsString method, of class ThreadTools.
*/
public void testGetStackTraceAsString_ThreadInfo() {
String threadName = "stack-trace-thread-info";
Thread thread = new SimpleThread(threadName, true); // interruptable thread
long id = thread.getId();
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
ThreadInfo threadInfo = ManagementFactory.getThreadMXBean()
.getThreadInfo(thread.getId(), Integer.MAX_VALUE);
String stack = ThreadTools.getStackTraceAsString(threadInfo);
assertTrue("Missing thread id", stack.indexOf("(id=" + id + ")") != -1);
assertTrue("Wrong stack trace", stack.indexOf("at java.lang.Thread.sleep") != -1);
assertTrue("Wrong stack trace", stack.indexOf("at com.funambol.server.thread.ThreadToolsTest$SimpleThread.run(ThreadToolsTest.java") != -1);
}
class SimpleThread extends Thread {
private boolean interruptable = false;
public SimpleThread(String name) {
super(name);
}
public SimpleThread(String name, boolean interruptable) {
super(name);
this.interruptable = interruptable;
}
@Override
public void run() {
System.out.println("Start: " + getName());
do {
try {
System.out.println("sleeping");
Thread.sleep(5 * 1000);
} catch (InterruptedException ex) {
System.out.println("Interrupt!");
}
} while (!interruptable);
}
}
}
| agpl-3.0 |
fqqb/yamcs | yamcs-core/src/main/java/org/yamcs/cfdp/CfdpTransactionId.java | 1091 | package org.yamcs.cfdp;
import java.util.Objects;
public class CfdpTransactionId {
private int sequenceNumber;
private long initiatorEntity;
public CfdpTransactionId(long entityId, long sequenceNumber) {
this.initiatorEntity = entityId;
this.sequenceNumber = (int)sequenceNumber;
}
public int getSequenceNumber() {
return sequenceNumber;
}
public long getInitiatorEntity() {
return initiatorEntity;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (getClass() != o.getClass()) {
return false;
}
CfdpTransactionId other = (CfdpTransactionId) o;
return sequenceNumber == other.sequenceNumber && initiatorEntity == other.initiatorEntity;
}
@Override
public int hashCode() {
return Objects.hash(sequenceNumber, initiatorEntity);
}
@Override
public String toString() {
return initiatorEntity+"_"+sequenceNumber;
}
}
| agpl-3.0 |
kerr-huang/openss7 | src/java/org/openss7/ss7/mtp/JainMtpStackImpl.java | 16612 | /*
@(#) src/java/org/openss7/ss7/mtp/JainMtpStackImpl.java <p>
Copyright © 2008-2015 Monavacon Limited <a href="http://www.monavacon.com/"><http://www.monavacon.com/></a>. <br>
Copyright © 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/"><http://www.openss7.com/></a>. <br>
Copyright © 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org"><bidulock@openss7.org></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/"><http://www.gnu.org/licenses/></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>
*/
package org.openss7.ss7.mtp;
import org.openss7.ss7.*;
/**
* This class defines the vendor-specific OpenSS7 MTP protocol stack.
* Each vendor's protocol stack will have an object that implements
* this interface to control the creation/deletion of proprietary
* MtpProviders and the implicit attaching and detaching of those
* MtpProviders to this JainMtpStack implementation. <p>
*
* It must be noted that under the <b>JAIN Naming Convention</b>, the
* <b>lower-level package structure</b> and <b>classname</b> of a
* proprietary implementation fo the
* <i>jain.protocol.ss7.mtp.JainMtpStack</i> interface <b>must</b> be
* <i>jain.protocol.ss7.mtp.JainMtpStackImpl</i>. <p>
*
* Under the JAIN naming convention, the <b>Upper-level package
* structure</b> (pathname) can be used to differentiate between
* proprietary implementations from different SS7 vendors. The
* pathname used by each SS7 Vendor <b>must be</b> the domain name
* assigned to the vendor in reverse order; e.g. The OpenSS7 Project's
* would be "org.openss7". <p>
*
* It follows that a proprietary implementation of a JainMtpStack will
* be located at: <br>
* <i><pathname><b>.</b>jain.protocol.ss7.tcap.JainMtpStackImpl</i>
* <br>
* <b>Where:</b> <br>
* <i>pathname</i> is the reverse domain name, e.g. "org.openss7" <br>
* The resulting Peer JAIN SS7 Object would be located at:
* <i><b>org.openss7</b>.jain.protocol.ss7.mtp.JainMtpStackImpl</i>
* <br>
* An application may create a JainMtpStackImpl by invoking the
* {@link jain.protocol.ss7.JainSs7Factory#createJainSS7Object} method.
* The <b>Pathname</b> of the vendor specific implementation of which
* you want to instantiate of which you want to instantiate can be set
* before calling this method or the default or current pathname may be
* used. <p>
*
* For applications that require some means to identify multiple stacks
* (with multiple SPCs) setStackName() can be used. An application can
* choose to supply any identifier to this method. <p>
*
* <b>Note</b> that a JainMtpStack represents a single SPC.
*
* @author Monavacon Limited
* @version 1.2.2
* @see JainMtpStack
* @see JainMtpProviderImpl
*/
public class JainMtpStackImpl implements Runnable, JainMtpStack {
/** Private network indicator parameter. */
private javax.jain.ss7.NetworkIndicator networkIndicator = null;
/** Private network indicator parameter setting. */
private boolean networkIndicatorIsSet = false;
/** Private signalling point code parameter. */
private javax.jain.ss7.SignalingPointCode signalingPointCode = new javax.jain.ss7.SignalingPointCode(0,0,0);
/** Private signalling point code parameter setting. */
private boolean signalingPointCodeIsSet = false;
/** Private stack specification parameter. */
private int stackSpecification = MtpConstants.MTP_PV_ITU_1993;
/** Private stack specification paramter setting. */
private boolean stackSpecificationIsSet = false;
/** Private stack name parameter. */
private java.lang.String stackName = "javax.jain.ss7.mtp.JainMtpProviderImpl";
/** Private stack name parameter setting. */
private boolean stackNameIsSet = false;
/** Private vendor name parameter. */
private java.lang.String vendorName = "org.openss7";
/** Private vendor name parameter setting. */
private boolean vendorNameIsSet = false;
/** Private provider list. */
private java.util.Vector providerList = new java.util.Vector();
/** Constructs a new JainMtpStackImpl instance. */
public JainMtpStackImpl() {
}
/** Creates a new Peer (vendor specific) JainMtpProvider whose
* reference is exposed by this JainMtpStackImpl.
* @return
* Peer Jain MTP Provider referenced by this JainMtpStackImpl.
* @exception javax.jain.PeerUnavailableException
* Thrown when the class is not found for a specific peer
* implementation.
* @exception javax.jain.ParameterNotSetException
* Thrown wen a mandatory stack parameter is not set.
*/
public JainMtpProvider createProvider()
throws javax.jain.PeerUnavailableException,
javax.jain.ParameterNotSetException {
if (networkIndicatorIsSet == false)
throw new javax.jain.ParameterNotSetException("Network Indicator: not set.");
if (signalingPointCodeIsSet == false)
throw new javax.jain.ParameterNotSetException("Signaling Point Code: not set.");
if (stackSpecificationIsSet == false)
throw new javax.jain.ParameterNotSetException("Stack Specification: not set.");
if (vendorNameIsSet == false)
throw new javax.jain.ParameterNotSetException("Vendor Name: not set.");
JainMtpProvider mtpProvider;
try {
Class providerObjectClass = Class.forName(getVendorName() + "." + getStackName());
java.lang.Object providerObject = providerObjectClass.newInstance();
mtpProvider = (JainMtpProvider) providerObject;
} catch (Exception e) {
throw new javax.jain.PeerUnavailableException("Peer unavailable.");
}
providerList.add(mtpProvider);
return mtpProvider;
}
/** Deletes a JainMtpProvider created by and attached to this stack.
* @param providerToBeDeleted
* Specifies the provider to be deleted.
* @exception javax.jain.DeleteProviderException
* Thrown when the provider to be deleted is not a provider created
* by this stack, or the provider is busy. */
public void deleteProvider(JainMtpProvider providerToBeDeleted)
throws javax.jain.DeleteProviderException {
int size = providerList.size();
providerList.remove(providerToBeDeleted);
if (size == providerList.size())
throw new javax.jain.DeleteProviderException();
mtpProvider.finalize();
}
/** Returns an array of JainMtpProviders for this stack.
* @return
* An array of JainMtpProvider objects created by and attached to
* this stack. */
public JainMtpProvider[] getProviderList() {
JainMtpProvider[] providerArray
= new JainMtpProvider[providerList.size()];
Iterator i = providerList.iterator();
for (int n = 0; i.hasNext(); n++)
providerArray[n] = i.next();
return providerArray;
}
/** Resturns the user's name for this stack.
* @return
* A string describing the stack name. */
public java.lang.String getStackName() {
return stackName;
}
/** Sets the name of the stack as a string.
* @param stackName
* The new Stack Name value. */
public void setStackName(java.lang.String stackName) {
this.stackName = stackName;
this.stackNameIsSet = true;
}
/** Returns the Vendor's name for this stack
* @return
* A string describing the Vendor's name. */
public java.lang.String getVendorName() {
return vendorName;
}
/** Sets the Vendors name for this stack, this name will be the
* Vendor's domain name inverted i.e, "org.openss7" similar to the
* path name of the JAIN Factory.
* @param vendorName
* The new Vendor's name. */
public void setVendorName(java.lang.String vendorName) {
this.vendorName = vendorName;
this.vendorNameIsSet = true;
}
/** Gets the stack Specification that this Stack is currently
* supporting. <p>
* <b>Note to developers</b>:- This should not be confused with the
* protocol version field supported by the ANSI 1996 Dialogue
* Portion.
* @return
* The current Protocol Version of this stack. This may be one of
* the following values: * <ul>
* <li>{@link MtpConstants#STACK_SPECIFICATION_ANSI_92 STACK_SPECIFICATION_ANSI_92}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ANSI_96 STACK_SPECIFICATION_ANSI_96}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ITU_93 STACK_SPECIFICATION_ITU_93}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ITU_97 STACK_SPECIFICATION_ITU_97} </ul>
* @see MtpConstants */
public int getStackSpecification() {
return stackSpecification;
}
/** Sets the Stack specification that this Stack is to support.
* Invoking this method should initially configure the stack to
* support the given specification if the specification supported
* has not already been set. In the event that this Stack is
* already supporting a specification other than the supplied
* specification, then the Stack will change the supported
* specification if possible, or throw an Exception if this is not
* possible. <p>
* <b>Note to developers</b>:- This should not be confused with the
* protocol version field supported by the ANSI 1996 Dialogue
* Portion.
* @param stackSpecification
* One of the following values: * <ul>
* <li>{@link MtpConstants#STACK_SPECIFICATION_ANSI_92 STACK_SPECIFICATION_ANSI_92}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ANSI_96 STACK_SPECIFICATION_ANSI_96}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ITU_93 STACK_SPECIFICATION_ITU_93}
* <li>{@link MtpConstants#STACK_SPECIFICATION_ITU_97 STACK_SPECIFICATION_ITU_97} </ul>
* @exception javax.jain.VersionNotSupportException
* Thrown when the supplied stack specification cannot be supported
* by this Stack, or if the Stack cannot change supported stack
* specifications because it is not in a idle state.
* @see MtpConstants */
public void setStackSpecification(int stackSpecification)
throws javax.jain.VersionNotSupportedException {
if (providerList.size() == 0) {
switch (stackSpecification) {
case MtpConstants.STACK_SPECIFICATION_ANSI_92:
case MtpConstants.STACK_SPECIFICATION_ANSI_96:
case MtpConstants.STACK_SPECIFICATION_ITU_93:
case MtpConstants.STACK_SPECIFICATION_ITU_97:
this.stackSpecification = stackSpecification;
this.stackSpecificationIsSet = true;
return;
}
throw new javax.jain.VersionNotSupportedException("Version " + stackSpecification + " out of range.");
}
throw new javax.jain.VersionNotSupportedException("Provider already created.");
}
/** Sets the signaling point code for the stack.
* Invoking this method should set the signalling point code
* associated with the stack. In the event that the stack is
* already supporting a signalling point code other than the
* supplied signalling point code, then the stack will change the
* supported signalling point code, if possible, or will throw an
* exception if not possible.
* @param signalingPointCode
* The signalling point code to set.
* @exception javax.jain.protocol.ss7.SS7InvalidParamException
* Thrown when the supplied signalling point code is invalid, or if
* the stack cannot change the signalling point code because it is
* not in the idle state. */
public void setSignalingPointCode(javax.jain.ss7.SignalingPointCode signalingPointCode)
throws javax.jain.protocol.ss7.SS7InvalidParamException {
if (providerList.size() == 0) {
this.signalingPointCode = signalingPointCode;
this.signalingPointCodeIsSet = (signalingPointCode != null);
return;
}
throw new javax.jain.protocol.ss7.SS7InvalidParamException("Provider already created.");
}
/** Gets the signaling point code associated with the stack.
* @return
* The signalling point code associated with the stack.
* @exception javax.jain.ParameterNotSetException
* Thrown when the signalling point code has not been set for the
* stack and there is no default value. */
public javax.jain.ss7.SignalingPointCode getSignalingPointCode()
throws javax.jain.ParameterNotSetException {
if (signalingPointCodeIsSet)
return signalingPointCode;
throw new javax.jain.ParameterNotSetException("Signaling Point Code: not set.");
}
/** Sets the network indicator for the stack.
* Invoking this method should set the network indicator associated
* with the stack. In the event that the stack is already
* supporting a network indicator other than the supplied network
* indicator, then the stack will change the supported network
* indicator, if possible, or will throw an exception if not
* possible.
* @param networkIndicator
* The network indicator to set.
* @exception javax.jain.protocol.ss7.SS7InvalidParamException
* Thrown when the supplied network indicator is invalid, or if the
* stack cannot change the network indicator because it is not in
* the idle state. */
public void setNetworkIndicator(javax.jain.ss7.NetworkIndicator networkIndicator)
throws javax.jain.protocol.ss7.SS7InvalidParamException {
if (provderList.size() == 0) {
this.networkIndicator = networkIndicator;
this.networkIndicatorIsSet = (networkIndicator != null);
return;
}
throw new javax.jain.protocol.ss7.SS7InvalidParamException("Provider already created.");
}
/** Gets the network indicator associated with the stack.
* @return
* The network indicator associated with the stack.
* @exception javax.jain.ParameterNotSetException
* Thrown when the network indicator has not been set for the stack
* and there is no default value. */
public javax.jain.ss7.NetworkIndicator getNetworkIndicator()
throws javax.jain.ParameterNotSetException {
if (networkIndicatorIsSet)
return networkIndicator;
throw new javax.jain.ParameterNotSetException("Network Indicator: not set.");
}
}
// vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
| agpl-3.0 |
google-code-export/fullmetalgalaxy | src/com/fullmetalgalaxy/model/persist/GameStatistics.java | 1490 | /* *********************************************************************
*
* This file is part of Full Metal Galaxy.
* http://www.fullmetalgalaxy.com
*
* Full Metal Galaxy 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.
*
* Full Metal Galaxy 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 Full Metal Galaxy.
* If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2010 to 2015 Vincent Legendre
*
* *********************************************************************/
package com.fullmetalgalaxy.model.persist;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author vincent legendre
*
* contain results of a finished game,
* don't contain statistics related to a specific player.
*/
public class GameStatistics implements Serializable, IsSerializable
{
static final long serialVersionUID = 1;
/**
* used for serialization policy
*/
protected GameStatistics() {}
public GameStatistics(Game p_game)
{
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/base/impl/BaseModifyMultipleSlotsDialogImpl.java | 2707 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.scheduling.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseModifyMultipleSlotsDialogImpl extends DomainImpl implements ims.scheduling.domain.ModifyMultipleSlotsDialog, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatesaveTheatreSession(ims.scheduling.vo.SessionTheatreVo voSession)
{
if(voSession == null)
throw new ims.domain.exceptions.DomainRuntimeException("The parameter 'voSession' of type 'ims.scheduling.vo.SessionTheatreVo' cannot be null.");
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/HcpLocationsServicesVo.java | 7524 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
/**
* Linked to core.resource.HcpLocationService business object (ID: 1005100000).
*/
public class HcpLocationsServicesVo extends ims.core.resource.vo.HcpLocationServiceRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public HcpLocationsServicesVo()
{
}
public HcpLocationsServicesVo(Integer id, int version)
{
super(id, version);
}
public HcpLocationsServicesVo(ims.core.vo.beans.HcpLocationsServicesVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.service = bean.getService() == null ? null : bean.getService().buildVo();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.beans.HcpLocationsServicesVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.service = bean.getService() == null ? null : bean.getService().buildVo(map);
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.core.vo.beans.HcpLocationsServicesVoBean bean = null;
if(map != null)
bean = (ims.core.vo.beans.HcpLocationsServicesVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.core.vo.beans.HcpLocationsServicesVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("SERVICE"))
return getService();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getServiceIsNotNull()
{
return this.service != null;
}
public ims.core.vo.ServiceVo getService()
{
return this.service;
}
public void setService(ims.core.vo.ServiceVo value)
{
this.isValidated = false;
this.service = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
if(this.service != null)
{
if(!this.service.isValidated())
{
this.isBusy = false;
return false;
}
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
if(this.service == null)
listOfErrors.add("Service is mandatory");
if(this.service != null)
{
String[] listOfOtherErrors = this.service.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
HcpLocationsServicesVo clone = new HcpLocationsServicesVo(this.id, this.version);
if(this.service == null)
clone.service = null;
else
clone.service = (ims.core.vo.ServiceVo)this.service.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(HcpLocationsServicesVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A HcpLocationsServicesVo object cannot be compared an Object of type " + obj.getClass().getName());
}
HcpLocationsServicesVo compareObj = (HcpLocationsServicesVo)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getID_HcpLocationService() == null && compareObj.getID_HcpLocationService() != null)
return -1;
if(this.getID_HcpLocationService() != null && compareObj.getID_HcpLocationService() == null)
return 1;
if(this.getID_HcpLocationService() != null && compareObj.getID_HcpLocationService() != null)
retVal = this.getID_HcpLocationService().compareTo(compareObj.getID_HcpLocationService());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.service != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 1;
}
protected ims.core.vo.ServiceVo service;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Pathways/src/ims/pathways/domain/impl/PatientJourneyBreachReasonImpl.java | 3775 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Cristian Belciug using IMS Development Environment (version 1.80 build 5308.16958)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
package ims.pathways.domain.impl;
import ims.domain.DomainFactory;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.exceptions.CodingRuntimeException;
import ims.pathways.domain.base.impl.BasePatientJourneyBreachReasonImpl;
import ims.pathways.domain.objects.PatientPathwayJourney;
import ims.pathways.vo.PatientJourneyWithBreachReasonVo;
import ims.pathways.vo.domain.PatientJourneyWithBreachReasonVoAssembler;
public class PatientJourneyBreachReasonImpl extends BasePatientJourneyBreachReasonImpl
{
private static final long serialVersionUID = 1L;
public PatientJourneyWithBreachReasonVo getPatientJourney(ims.pathways.vo.PatientPathwayJourneyRefVo patientJourney)
{
if(patientJourney == null || patientJourney.getID_PatientPathwayJourney() == null)
return null;
return PatientJourneyWithBreachReasonVoAssembler.create((PatientPathwayJourney) getDomainFactory().getDomainObject(PatientPathwayJourney.class, patientJourney.getID_PatientPathwayJourney()));
}
public PatientJourneyWithBreachReasonVo save(PatientJourneyWithBreachReasonVo patientJourney) throws StaleObjectException
{
if(patientJourney == null)
throw new CodingRuntimeException("Cannot save a null PatientPathwayJourney.");
if(!patientJourney.isValidated())
throw new CodingRuntimeException("PatientPathwayJourney is not validated.");
DomainFactory factory = getDomainFactory();
PatientPathwayJourney doPatientPathwayJourney = PatientJourneyWithBreachReasonVoAssembler.extractPatientPathwayJourney(factory, patientJourney);
factory.save(doPatientPathwayJourney);
return PatientJourneyWithBreachReasonVoAssembler.create(doPatientPathwayJourney);
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/OCRR/src/ims/ocrr/forms/newresultsmyresultstabcomponent/GlobalContext.java | 3365 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.forms.newresultsmyresultstabcomponent;
import java.io.Serializable;
public final class GlobalContext extends ims.framework.FormContext implements Serializable
{
private static final long serialVersionUID = 1L;
public GlobalContext(ims.framework.Context context)
{
super(context);
OCRR = new OCRRContext(context);
}
public final class OCRRContext implements Serializable
{
private static final long serialVersionUID = 1L;
private OCRRContext(ims.framework.Context context)
{
this.context = context;
}
public boolean getSelectedDisciplinesIsNotNull()
{
return !cx_OCRRSelectedDisciplines.getValueIsNull(context);
}
public ims.core.vo.ServiceLiteVoCollection getSelectedDisciplines()
{
return (ims.core.vo.ServiceLiteVoCollection)cx_OCRRSelectedDisciplines.getValue(context);
}
public void setSelectedDisciplines(ims.core.vo.ServiceLiteVoCollection value)
{
cx_OCRRSelectedDisciplines.setValue(context, value);
}
private ims.framework.ContextVariable cx_OCRRSelectedDisciplines = new ims.framework.ContextVariable("OCRR.SelectedDisciplines", "_cv_OCRR.SelectedDisciplines");
private ims.framework.Context context;
}
public OCRRContext OCRR;
}
| agpl-3.0 |
hyc/BerkeleyDB | examples/java/src/collections/ship/factory/SampleViews.java | 4191 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
package collections.ship.factory;
import com.sleepycat.collections.StoredSortedMap;
import com.sleepycat.collections.StoredSortedValueSet;
import com.sleepycat.collections.TupleSerialFactory;
/**
* SampleViews defines the data bindings and collection views for the sample
* database.
*
* @author Mark Hayes
*/
public class SampleViews {
private StoredSortedMap partMap;
private StoredSortedMap supplierMap;
private StoredSortedMap shipmentMap;
private StoredSortedMap shipmentByPartMap;
private StoredSortedMap shipmentBySupplierMap;
private StoredSortedMap supplierByCityMap;
/**
* Create the data bindings and collection views.
*/
public SampleViews(SampleDatabase db) {
// Use the TupleSerialFactory for a Serial/Tuple-based database
// where marshalling interfaces are used.
//
TupleSerialFactory factory = db.getFactory();
// Create map views for all stores and indices.
// StoredSortedMap is used since the stores and indices are ordered
// (they use the DB_BTREE access method).
//
partMap =
factory.newSortedMap(db.getPartDatabase(),
PartKey.class, Part.class, true);
supplierMap =
factory.newSortedMap(db.getSupplierDatabase(),
SupplierKey.class, Supplier.class, true);
shipmentMap =
factory.newSortedMap(db.getShipmentDatabase(),
ShipmentKey.class, Shipment.class, true);
shipmentByPartMap =
factory.newSortedMap(db.getShipmentByPartDatabase(),
PartKey.class, Shipment.class, true);
shipmentBySupplierMap =
factory.newSortedMap(db.getShipmentBySupplierDatabase(),
SupplierKey.class, Shipment.class, true);
supplierByCityMap =
factory.newSortedMap(db.getSupplierByCityDatabase(),
String.class, Supplier.class, true);
}
// The views returned below can be accessed using the java.util.Map or
// java.util.Set interfaces, or using the StoredMap and StoredValueSet
// classes, which provide additional methods. The entity sets could be
// obtained directly from the Map.values() method but convenience methods
// are provided here to return them in order to avoid down-casting
// elsewhere.
/**
* Return a map view of the part storage container.
*/
public StoredSortedMap getPartMap() {
return partMap;
}
/**
* Return a map view of the supplier storage container.
*/
public StoredSortedMap getSupplierMap() {
return supplierMap;
}
/**
* Return a map view of the shipment storage container.
*/
public StoredSortedMap getShipmentMap() {
return shipmentMap;
}
/**
* Return an entity set view of the part storage container.
*/
public StoredSortedValueSet getPartSet() {
return (StoredSortedValueSet) partMap.values();
}
/**
* Return an entity set view of the supplier storage container.
*/
public StoredSortedValueSet getSupplierSet() {
return (StoredSortedValueSet) supplierMap.values();
}
/**
* Return an entity set view of the shipment storage container.
*/
public StoredSortedValueSet getShipmentSet() {
return (StoredSortedValueSet) shipmentMap.values();
}
/**
* Return a map view of the shipment-by-part index.
*/
public StoredSortedMap getShipmentByPartMap() {
return shipmentByPartMap;
}
/**
* Return a map view of the shipment-by-supplier index.
*/
public StoredSortedMap getShipmentBySupplierMap() {
return shipmentBySupplierMap;
}
/**
* Return a map view of the supplier-by-city index.
*/
public StoredSortedMap getSupplierByCityMap() {
return supplierByCityMap;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/icp/vo/beans/InpatientEpisodeWithICPInfoVoBean.java | 5366 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.icp.vo.beans;
public class InpatientEpisodeWithICPInfoVoBean extends ims.vo.ValueObjectBean
{
public InpatientEpisodeWithICPInfoVoBean()
{
}
public InpatientEpisodeWithICPInfoVoBean(ims.icp.vo.InpatientEpisodeWithICPInfoVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.pasevent = vo.getPasEvent() == null ? null : (ims.core.vo.beans.PasEventShortVoBean)vo.getPasEvent().getBean();
this.admissiondatetime = vo.getAdmissionDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAdmissionDateTime().getBean();
this.icpinfo = vo.getICPInfo() == null ? null : (ims.icp.vo.beans.PatientICPLiteVoBean)vo.getICPInfo().getBean();
this.bednumber = vo.getBedNumber();
this.carecontext = vo.getCareContext() == null ? null : new ims.vo.RefVoBean(vo.getCareContext().getBoId(), vo.getCareContext().getBoVersion());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.icp.vo.InpatientEpisodeWithICPInfoVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.pasevent = vo.getPasEvent() == null ? null : (ims.core.vo.beans.PasEventShortVoBean)vo.getPasEvent().getBean(map);
this.admissiondatetime = vo.getAdmissionDateTime() == null ? null : (ims.framework.utils.beans.DateTimeBean)vo.getAdmissionDateTime().getBean();
this.icpinfo = vo.getICPInfo() == null ? null : (ims.icp.vo.beans.PatientICPLiteVoBean)vo.getICPInfo().getBean(map);
this.bednumber = vo.getBedNumber();
this.carecontext = vo.getCareContext() == null ? null : new ims.vo.RefVoBean(vo.getCareContext().getBoId(), vo.getCareContext().getBoVersion());
}
public ims.icp.vo.InpatientEpisodeWithICPInfoVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.icp.vo.InpatientEpisodeWithICPInfoVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.icp.vo.InpatientEpisodeWithICPInfoVo vo = null;
if(map != null)
vo = (ims.icp.vo.InpatientEpisodeWithICPInfoVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.icp.vo.InpatientEpisodeWithICPInfoVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.core.vo.beans.PasEventShortVoBean getPasEvent()
{
return this.pasevent;
}
public void setPasEvent(ims.core.vo.beans.PasEventShortVoBean value)
{
this.pasevent = value;
}
public ims.framework.utils.beans.DateTimeBean getAdmissionDateTime()
{
return this.admissiondatetime;
}
public void setAdmissionDateTime(ims.framework.utils.beans.DateTimeBean value)
{
this.admissiondatetime = value;
}
public ims.icp.vo.beans.PatientICPLiteVoBean getICPInfo()
{
return this.icpinfo;
}
public void setICPInfo(ims.icp.vo.beans.PatientICPLiteVoBean value)
{
this.icpinfo = value;
}
public String getBedNumber()
{
return this.bednumber;
}
public void setBedNumber(String value)
{
this.bednumber = value;
}
public ims.vo.RefVoBean getCareContext()
{
return this.carecontext;
}
public void setCareContext(ims.vo.RefVoBean value)
{
this.carecontext = value;
}
private Integer id;
private int version;
private ims.core.vo.beans.PasEventShortVoBean pasevent;
private ims.framework.utils.beans.DateTimeBean admissiondatetime;
private ims.icp.vo.beans.PatientICPLiteVoBean icpinfo;
private String bednumber;
private ims.vo.RefVoBean carecontext;
}
| agpl-3.0 |
auroreallibe/Silverpeas-Core | core-services/silverstatistics/src/test-awaiting/java/com/stratelia/silverpeas/silverstatistics/control/AccessStatsSilverStatisticsDAOTest.java | 5979 | /*
* Copyright (C) 2000 - 2016 Silverpeas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of the GPL, you may
* redistribute this Program in connection with Free/Libre Open Source Software ("FLOSS")
* applications as described in Silverpeas's FLOSS exception. You should have received a copy of the
* text describing the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/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 com.stratelia.silverpeas.silverstatistics.control;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.stratelia.silverpeas.silverstatistics.model.StatisticsConfig;
import com.stratelia.silverpeas.silverstatistics.util.StatType;
import com.mockrunner.jdbc.JDBCTestModule;
import com.mockrunner.jdbc.StatementResultSetHandler;
import com.mockrunner.mock.jdbc.JDBCMockObjectFactory;
import com.mockrunner.mock.jdbc.MockConnection;
import com.mockrunner.mock.jdbc.MockPreparedStatement;
import com.mockrunner.mock.jdbc.MockResultSet;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/**
* @author ehugonnet
*/
public class AccessStatsSilverStatisticsDAOTest {
private StatisticsConfig config;
private JDBCMockObjectFactory factory;
private JDBCTestModule module;
private static final StatType typeofStat = StatType.Access;
public AccessStatsSilverStatisticsDAOTest() {
}
@Before
public void initialiseConfig() throws Exception {
config = new StatisticsConfig();
config.init();
factory = new JDBCMockObjectFactory();
module = new JDBCTestModule(factory);
module.setExactMatch(true);
}
@Test
public void testInsertData() throws Exception {
MockConnection connexion = factory.getMockConnection();
List<String> data = Arrays.asList("2011-04-17", "1308", "kmelia", "WA3", "kmelia36", "262");
SilverStatisticsDAO.insertDataStats(connexion, typeofStat, data, config);
module.verifyAllStatementsClosed();
List<?> statements = module.getPreparedStatements();
assertNotNull(statements);
assertThat(statements, hasSize(1));
MockPreparedStatement pstmt = module.getPreparedStatement(0);
assertThat(pstmt.getSQL(), is(
"INSERT INTO SB_Stat_Access(dateStat,userId,peasType,spaceId,componentId,countAccess) VALUES(?,?,?,?,?,?)"));
Map parameters = pstmt.getParameterMap();
assertThat((String) parameters.get(1), is("2011-04-17"));
assertThat((Integer) parameters.get(2), is(1308));
assertThat((String) parameters.get(3), is("kmelia"));
assertThat((String) parameters.get(4), is("WA3"));
assertThat((String) parameters.get(5), is("kmelia36"));
assertThat((Long) parameters.get(6), is(262L));
}
@Test
public void testPutDataStatsWithExistingData() throws Exception {
MockConnection connexion = factory.getMockConnection();
StatementResultSetHandler statementHandler = connexion.getStatementResultSetHandler();
MockResultSet result = statementHandler.createResultSet();
result.addRow(new Long[]{10000L});
statementHandler.prepareGlobalResultSet(result);
List<String> data = Arrays.asList("2011-04-17", "1308", "kmelia", "WA3", "kmelia36", "262");
SilverStatisticsDAO.putDataStats(connexion, typeofStat, data, config);
module.verifyAllStatementsClosed();
List<?> statements = module.getPreparedStatements();
assertNotNull(statements);
assertThat(statements, hasSize(1));
MockPreparedStatement pstmt = module.getPreparedStatement(0);
assertThat(pstmt.getSQL(), is("UPDATE SB_Stat_Access SET countAccess=countAccess+? "
+ "WHERE dateStat='2011-04-17' AND userId=1308 AND peasType='kmelia' AND spaceId='WA3' "
+ "AND componentId='kmelia36'"));
Map parameters = pstmt.getParameterMap();
assertThat((Long) parameters.get(1), is(262L));
}
@Test
public void testPutDataStatsWithoutExistingData() throws Exception {
MockConnection connexion = factory.getMockConnection();
StatementResultSetHandler statementHandler = connexion.getStatementResultSetHandler();
MockResultSet emptyResult = statementHandler.createResultSet();
statementHandler.prepareGlobalResultSet(emptyResult);
List<String> data = Arrays.asList("2011-04-17", "1308", "kmelia", "WA3", "kmelia36", "262");
SilverStatisticsDAO.putDataStats(connexion, typeofStat, data, config);
module.verifyAllStatementsClosed();
List<?> statements = module.getPreparedStatements();
assertNotNull(statements);
assertThat(statements, hasSize(1));
MockPreparedStatement pstmt = module.getPreparedStatement(0);
assertThat(pstmt.getSQL(), is("INSERT INTO SB_Stat_Access(dateStat,userId,peasType,spaceId,"
+ "componentId,countAccess) VALUES(?,?,?,?,?,?)"));
Map parameters = pstmt.getParameterMap();
assertThat((String) parameters.get(1), is("2011-04-17"));
assertThat((Integer) parameters.get(2), is(1308));
assertThat((String) parameters.get(3), is("kmelia"));
assertThat((String) parameters.get(4), is("WA3"));
assertThat((String) parameters.get(5), is("kmelia36"));
assertThat((Long) parameters.get(6), is(262L));
}
}
| agpl-3.0 |
niuxuetao/paxml | PaxmlCore/src/main/java/org/paxml/core/Namespaces.java | 1225 | /**
* This file is part of PaxmlCore.
*
* PaxmlCore 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.
*
* PaxmlCore 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 PaxmlCore. If not, see <http://www.gnu.org/licenses/>.
*/
package org.paxml.core;
/**
* paxml namespace contants.
*
* @author Xuetao Niu
*
*/
public final class Namespaces {
/**
* The root namespace of paxml.
*/
public static final String ROOT = "";
/**
* The name space of data tag definition.
*/
public static final String DATA = "data";
/**
* The namespace of file invoker tag definition.
*/
public static final String FILE = "file";
/**
* The namespace of command invoker tag definition.
*/
public static final String COMMAND = "command";
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/DomainObjects/src/ims/icps/instantiation/domain/objects/PatientICPStageStatus.java | 13852 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 12/10/2015, 13:28
*
*/
package ims.icps.instantiation.domain.objects;
/**
*
* @author Neil McAnaspie
* Generated.
*/
public class PatientICPStageStatus extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1100100002;
private static final long serialVersionUID = 1100100002L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
/** Date of Status Change */
private java.util.Date statusDate;
/** ChangedBy */
private String changedBy;
/** Status */
private ims.domain.lookups.LookupInstance status;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public PatientICPStageStatus (Integer id, int ver)
{
super(id, ver);
}
public PatientICPStageStatus ()
{
super();
}
public PatientICPStageStatus (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
}
public Class getRealDomainClass()
{
return ims.icps.instantiation.domain.objects.PatientICPStageStatus.class;
}
public java.util.Date getStatusDate() {
return statusDate;
}
public void setStatusDate(java.util.Date statusDate) {
this.statusDate = statusDate;
}
public String getChangedBy() {
return changedBy;
}
public void setChangedBy(String changedBy) {
if ( null != changedBy && changedBy.length() > 125 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for changedBy. Tried to set value: "+
changedBy);
}
this.changedBy = changedBy;
}
public ims.domain.lookups.LookupInstance getStatus() {
return status;
}
public void setStatus(ims.domain.lookups.LookupInstance status) {
this.status = status;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*statusDate* :");
auditStr.append(statusDate);
auditStr.append("; ");
auditStr.append("\r\n*changedBy* :");
auditStr.append(changedBy);
auditStr.append("; ");
auditStr.append("\r\n*status* :");
if (status != null)
auditStr.append(status.getText());
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" id=\"" + this.getId() + "\"");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
String keyClassName = "PatientICPStageStatus";
String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName();
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId());
if (impObj == null)
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(this.getId());
impObj.setExternalSource(externalSource);
impObj.setDomainObject(this);
impObj.setLocalId(this.getId());
impObj.setClassName(keyClassName);
domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj);
}
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getStatusDate() != null)
{
sb.append("<statusDate>");
sb.append(new ims.framework.utils.DateTime(this.getStatusDate()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</statusDate>");
}
if (this.getChangedBy() != null)
{
sb.append("<changedBy>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getChangedBy().toString()));
sb.append("</changedBy>");
}
if (this.getStatus() != null)
{
sb.append("<status>");
sb.append(this.getStatus().toXMLString());
sb.append("</status>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
PatientICPStageStatus domainObject = getPatientICPStageStatusfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
PatientICPStageStatus domainObject = getPatientICPStageStatusfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static PatientICPStageStatus getPatientICPStageStatusfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getPatientICPStageStatusfromXML(doc.getRootElement(), factory, domMap);
}
public static PatientICPStageStatus getPatientICPStageStatusfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!PatientICPStageStatus.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!PatientICPStageStatus.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the PatientICPStageStatus class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (PatientICPStageStatus)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(PatientICPStageStatus.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
PatientICPStageStatus ret = null;
int extId = Integer.parseInt(el.attributeValue("id"));
String externalSource = el.attributeValue("source");
ret = (PatientICPStageStatus)factory.getImportedDomainObject(PatientICPStageStatus.class, externalSource, extId);
if (ret == null)
{
ret = new PatientICPStageStatus();
}
String keyClassName = "PatientICPStageStatus";
ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId);
if (impObj != null)
{
return (PatientICPStageStatus)impObj.getDomainObject();
}
else
{
impObj = new ims.configuration.ImportedObject();
impObj.setExternalId(extId);
impObj.setExternalSource(externalSource);
impObj.setDomainObject(ret);
domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj);
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, PatientICPStageStatus obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("statusDate");
if(fldEl != null)
{
obj.setStatusDate(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("changedBy");
if(fldEl != null)
{
obj.setChangedBy(new String(fldEl.getTextTrim()));
}
fldEl = el.element("status");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setStatus(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
public static class FieldNames
{
public static final String ID = "id";
public static final String StatusDate = "statusDate";
public static final String ChangedBy = "changedBy";
public static final String Status = "status";
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Rules/src/ims/rules/forms/rulespriorityeditor/IFormUILogicCode.java | 2254 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# 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/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.rules.forms.rulespriorityeditor;
public interface IFormUILogicCode extends ims.base.interfaces.IUILIPLogicCode
{
// No methods yet.
}
| agpl-3.0 |
BiosemanticsDotOrg/GeneDiseasePlosBio | java/Common/src/org/erasmusmc/collections/Cursor.java | 1012 | /*
* Concept profile generation tool suite
* Copyright (C) 2015 Biosemantics Group, Erasmus University Medical Center,
* Rotterdam, The Netherlands
*
* 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.erasmusmc.collections;
public interface Cursor<D> {
public boolean isValid();
public void next();
public void delete();
public D get();
public void put(D d);
}
| agpl-3.0 |
Qingbao/PasswdManagerAndroid | src/noconflict/org/bouncycastle/crypto/CryptoException.java | 507 | package noconflict.org.bouncycastle.crypto;
/**
* the foundation class for the hard exceptions thrown by the crypto packages.
*/
public class CryptoException
extends Exception
{
/**
* base constructor.
*/
public CryptoException()
{
}
/**
* create a CryptoException with the given message.
*
* @param message the message to be carried with the exception.
*/
public CryptoException(
String message)
{
super(message);
}
}
| lgpl-2.1 |
Qingbao/PasswdManagerAndroid | src/noconflict/org/bouncycastle/crypto/tls/Certificate.java | 3711 | package noconflict.org.bouncycastle.crypto.tls;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import noconflict.org.bouncycastle.asn1.ASN1Encodable;
import noconflict.org.bouncycastle.asn1.ASN1InputStream;
import noconflict.org.bouncycastle.asn1.DERObject;
import noconflict.org.bouncycastle.asn1.x509.X509CertificateStructure;
/**
* A representation for a certificate chain as used by a tls server.
*/
public class Certificate
{
public static final Certificate EMPTY_CHAIN = new Certificate(new X509CertificateStructure[0]);
/**
* The certificates.
*/
protected X509CertificateStructure[] certs;
/**
* Parse the ServerCertificate message.
*
* @param is The stream where to parse from.
* @return A Certificate object with the certs, the server has sended.
* @throws IOException If something goes wrong during parsing.
*/
protected static Certificate parse(InputStream is) throws IOException
{
X509CertificateStructure[] certs;
int left = TlsUtils.readUint24(is);
if (left == 0)
{
return EMPTY_CHAIN;
}
Vector tmp = new Vector();
while (left > 0)
{
int size = TlsUtils.readUint24(is);
left -= 3 + size;
byte[] buf = new byte[size];
TlsUtils.readFully(buf, is);
ByteArrayInputStream bis = new ByteArrayInputStream(buf);
ASN1InputStream ais = new ASN1InputStream(bis);
DERObject o = ais.readObject();
tmp.addElement(X509CertificateStructure.getInstance(o));
if (bis.available() > 0)
{
throw new IllegalArgumentException(
"Sorry, there is garbage data left after the certificate");
}
}
certs = new X509CertificateStructure[tmp.size()];
for (int i = 0; i < tmp.size(); i++)
{
certs[i] = (X509CertificateStructure)tmp.elementAt(i);
}
return new Certificate(certs);
}
/**
* Encodes version of the ClientCertificate message
*
* @param os stream to write the message to
* @throws IOException If something goes wrong
*/
protected void encode(OutputStream os) throws IOException
{
Vector encCerts = new Vector();
int totalSize = 0;
for (int i = 0; i < this.certs.length; ++i)
{
byte[] encCert = certs[i].getEncoded(ASN1Encodable.DER);
encCerts.addElement(encCert);
totalSize += encCert.length + 3;
}
TlsUtils.writeUint24(totalSize + 3, os);
TlsUtils.writeUint24(totalSize, os);
for (int i = 0; i < encCerts.size(); ++i)
{
byte[] encCert = (byte[])encCerts.elementAt(i);
TlsUtils.writeOpaque24(encCert, os);
}
}
/**
* Private constructor from a cert array.
*
* @param certs The certs the chain should contain.
*/
public Certificate(X509CertificateStructure[] certs)
{
if (certs == null)
{
throw new IllegalArgumentException("'certs' cannot be null");
}
this.certs = certs;
}
/**
* @return An array which contains the certs, this chain contains.
*/
public X509CertificateStructure[] getCerts()
{
X509CertificateStructure[] result = new X509CertificateStructure[certs.length];
System.arraycopy(certs, 0, result, 0, certs.length);
return result;
}
public boolean isEmpty()
{
return certs.length == 0;
}
}
| lgpl-2.1 |
markmc/rhevm-api | powershell/jaxrs/src/test/java/com/redhat/rhevm/api/powershell/resource/AbstractPowerShellStorageDomainContentsResourceTest.java | 4201 | /*
* Copyright © 2010 Red Hat, Inc.
*
* 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 com.redhat.rhevm.api.powershell.resource;
import java.util.concurrent.Executor;
import javax.ws.rs.core.UriInfo;
import com.redhat.rhevm.api.common.resource.UriInfoProvider;
import com.redhat.rhevm.api.model.BaseResource;
import com.redhat.rhevm.api.model.BaseResources;
import com.redhat.rhevm.api.powershell.util.PowerShellCmd;
import com.redhat.rhevm.api.powershell.util.PowerShellParser;
import com.redhat.rhevm.api.powershell.util.PowerShellPoolMap;
import org.junit.runner.RunWith;
import static org.easymock.classextension.EasyMock.expect;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.easymock.PowerMock.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest( { PowerShellCmd.class })
public abstract class AbstractPowerShellStorageDomainContentsResourceTest<C extends BaseResources,
R extends BaseResource,
A extends AbstractPowerShellStorageDomainContentsResource<R>>
extends AbstractPowerShellResourceTest<R, A> {
protected static final String[] NAMES = {"clontarf", "killester", "harmonstown", "raheny", "kilbarrack"};
protected static final String DATA_CENTER_NAME = "sutton";
protected static final String DATA_CENTER_ID = asId(DATA_CENTER_NAME);
protected static final String STORAGE_DOMAIN_NAME = "howth";
protected static final String STORAGE_DOMAIN_ID = asId(STORAGE_DOMAIN_NAME);
protected static final String STORAGE_DOMAIN_URI = BASE_PATH + SLASH + "datacenters" + SLASH + DATA_CENTER_ID + SLASH + "storagedomains" + SLASH + STORAGE_DOMAIN_ID;
protected static final String IMPORT_CLUSTER_ID = asId("seapoint");
protected static final String IMPORT_DEST_DOMAIN_ID = asId("blackrock");
protected A getResource(Executor executor,
PowerShellPoolMap poolMap,
PowerShellParser parser,
UriInfoProvider uriProvider) {
PowerShellAttachedStorageDomainsResource grandParent =
new PowerShellAttachedStorageDomainsResource(DATA_CENTER_ID, poolMap, parser);
PowerShellAttachedStorageDomainResource parent =
new PowerShellAttachedStorageDomainResource(grandParent,
STORAGE_DOMAIN_ID,
executor,
uriProvider,
poolMap,
parser);
return getResource(parent, poolMap, parser);
}
protected abstract A getResource(PowerShellAttachedStorageDomainResource parent,
PowerShellPoolMap poolMap,
PowerShellParser parser);
@Override
protected void setUriInfo(UriInfo uriInfo) {
super.setUriInfo(uriInfo);
resource.setUriInfo(uriInfo);
}
protected void setUpCmdExpectations(String command, String ret) {
mockStatic(PowerShellCmd.class);
expect(PowerShellCmd.runCommand(setUpPoolExpectations(), command)).andReturn(ret);
}
}
| lgpl-2.1 |
jbossws/jbossws-cxf | modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/benchmark/test/complex/types/RegistrationFault.java | 1651 |
package org.jboss.test.ws.jaxws.benchmark.test.complex.types;
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;
/**
* <p>Java class for RegistrationFault complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RegistrationFault">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="message" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RegistrationFault", namespace = "http://complex.jaxws.ws.test.jboss.org/", propOrder = {
"message"
})
@XmlSeeAlso({
AlreadyRegisteredFault.class,
ValidationFault.class
})
public class RegistrationFault {
@XmlElement(required = true, nillable = true)
protected String message;
/**
* Gets the value of the message property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMessage() {
return message;
}
/**
* Sets the value of the message property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessage(String value) {
this.message = value;
}
}
| lgpl-2.1 |
FreeScienceCommunity/PLPlot | examples/java/x24.java | 3918 | //--------------------------------------------------------------------------
// Unicode Pace Flag
//--------------------------------------------------------------------------
//
// Copyright (C) 2005 Rafael Laboissiere
// 2006 Andrew Ross
//
//
// This file is part of PLplot.
//
// PLplot is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library General Public License as published
// by the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// PLplot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public License
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// Packages needed (by Debian name):
//
// ttf-arphic-bkai00mp
// ttf-freefont
// ttf-indic-fonts
// ttf-unfonts
// ttf-bangla-fonts
//
// For the latest Ubuntu systems lohit_hi.ttf has been moved to the
// ttf-indic-fonts-core package instead of ttf-devanagari-fonts so you
// will have to use this package instead and update the font path.
//
package plplot.examples;
import plplot.core.*;
import static plplot.core.plplotjavacConstants.*;
class x24 {
PLStream pls = new PLStream();
int red[] = { 240, 204, 204, 204, 0, 39, 125 };
int green[] = { 240, 0, 125, 204, 204, 80, 0 };
int blue[] = { 240, 0, 0, 0, 0, 204, 125 };
double px[] = { 0.0, 0.0, 1.0, 1.0 };
double py[] = { 0.0, 0.25, 0.25, 0.0 };
double sx[] = {
0.16374,
0.15844,
0.15255,
0.17332,
0.50436,
0.51721,
0.49520,
0.48713,
0.83976,
0.81688,
0.82231,
0.82647
};
double sy[] = {
0.125,
0.375,
0.625,
0.875,
0.125,
0.375,
0.625,
0.875,
0.125,
0.375,
0.625,
0.875
};
// Taken from http://www.columbia.edu/~fdc/pace/
String peace[] = {
// Mandarin
"#<0x00>和平",
// Hindi
"#<0x20>शांति",
// English
"#<0x10>Peace",
// Hebrew
"#<0x10>שלום",
// Russian
"#<0x10>Мир",
// German
"#<0x10>Friede",
// Korean
"#<0x30>평화",
// French
"#<0x10>Paix",
// Spanish
"#<0x10>Paz",
// Arabic
"#<0x10>ﺳﻼم",
// Turkish
"#<0x10>Barış",
// Kurdish
"#<0x10>Hasîtî",
};
public x24( String[] args )
{
int i, j;
pls.parseopts( args, PL_PARSE_FULL | PL_PARSE_NOPROGRAM );
pls.init();
pls.adv( 0 );
pls.vpor( 0.0, 1.0, 0.0, 1.0 );
pls.wind( 0.0, 1.0, 0.0, 1.0 );
pls.col0( 0 );
pls.box( "", 1.0, 0, "", 1.0, 0 );
pls.scmap0n( 7 );
pls.scmap0( red, green, blue );
pls.schr( 0, 4.0 );
pls.font( 1 );
for ( i = 0; i < 4; i++ )
{
pls.col0( i + 1 );
pls.fill( px, py );
for ( j = 0; j < 4; j++ )
py [j] += 1.0 / 4.0;
}
pls.col0( 0 );
for ( i = 0; i < 12; i++ )
pls.ptex( sx [i], sy [i], 1.0, 0.0, 0.5, peace [i] );
pls.end();
}
public static void main( String[] args )
{
new x24( args );
}
}
//--------------------------------------------------------------------------
// End of x24.java
//--------------------------------------------------------------------------
| lgpl-2.1 |
liscju/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java | 14135 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import javax.xml.bind.DatatypeConverter;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closeables;
import com.google.common.io.Flushables;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* This class maintains a persistent(on file-system) store of the files
* that have checked ok(no validation events) and their associated
* timestamp. It is used to optimize Checkstyle between few launches.
* It is mostly useful for plugin and extensions of Checkstyle.
* It uses a property file
* for storage. A hashcode of the Configuration is stored in the
* cache file to ensure the cache is invalidated when the
* configuration has changed.
*
* @author Oliver Burn
* @author Andrei Selkin
*/
final class PropertyCacheFile {
/**
* The property key to use for storing the hashcode of the
* configuration. To avoid name clashes with the files that are
* checked the key is chosen in such a way that it cannot be a
* valid file name.
*/
public static final String CONFIG_HASH_KEY = "configuration*?";
/**
* The property prefix to use for storing the hashcode of an
* external resource. To avoid name clashes with the files that are
* checked the prefix is chosen in such a way that it cannot be a
* valid file name and makes it clear it is a resource.
*/
public static final String EXTERNAL_RESOURCE_KEY_PREFIX = "module-resource*?:";
/** The details on files. **/
private final Properties details = new Properties();
/** Configuration object. **/
private final Configuration config;
/** File name of cache. **/
private final String fileName;
/** Generated configuration hash. **/
private String configHash;
/**
* Creates a new {@code PropertyCacheFile} instance.
*
* @param config the current configuration, not null
* @param fileName the cache file
*/
PropertyCacheFile(Configuration config, String fileName) {
if (config == null) {
throw new IllegalArgumentException("config can not be null");
}
if (fileName == null) {
throw new IllegalArgumentException("fileName can not be null");
}
this.config = config;
this.fileName = fileName;
}
/**
* Load cached values from file.
* @throws IOException when there is a problems with file read
*/
public void load() throws IOException {
// get the current config so if the file isn't found
// the first time the hash will be added to output file
configHash = getHashCodeBasedOnObjectContent(config);
if (new File(fileName).exists()) {
FileInputStream inStream = null;
try {
inStream = new FileInputStream(fileName);
details.load(inStream);
final String cachedConfigHash = details.getProperty(CONFIG_HASH_KEY);
if (!configHash.equals(cachedConfigHash)) {
// Detected configuration change - clear cache
reset();
}
}
finally {
Closeables.closeQuietly(inStream);
}
}
else {
// put the hash in the file if the file is going to be created
reset();
}
}
/**
* Cleans up the object and updates the cache file.
* @throws IOException when there is a problems with file save
*/
public void persist() throws IOException {
final Path directory = Paths.get(fileName).getParent();
if (directory != null) {
Files.createDirectories(directory);
}
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName);
details.store(out, null);
}
finally {
flushAndCloseOutStream(out);
}
}
/**
* Resets the cache to be empty except for the configuration hash.
*/
public void reset() {
details.clear();
details.setProperty(CONFIG_HASH_KEY, configHash);
}
/**
* Flushes and closes output stream.
* @param stream the output stream
* @throws IOException when there is a problems with file flush and close
*/
private static void flushAndCloseOutStream(OutputStream stream) throws IOException {
if (stream != null) {
Flushables.flush(stream, false);
}
Closeables.close(stream, false);
}
/**
* Checks that file is in cache.
* @param uncheckedFileName the file to check
* @param timestamp the timestamp of the file to check
* @return whether the specified file has already been checked ok
*/
public boolean isInCache(String uncheckedFileName, long timestamp) {
final String lastChecked = details.getProperty(uncheckedFileName);
return Objects.equals(lastChecked, Long.toString(timestamp));
}
/**
* Records that a file checked ok.
* @param checkedFileName name of the file that checked ok
* @param timestamp the timestamp of the file
*/
public void put(String checkedFileName, long timestamp) {
details.setProperty(checkedFileName, Long.toString(timestamp));
}
/**
* Retrieves the hash of a specific file.
* @param name The name of the file to retrieve.
* @return The has of the file or {@code null}.
*/
public String get(String name) {
return details.getProperty(name);
}
/**
* Removed a specific file from the cache.
* @param checkedFileName The name of the file to remove.
*/
public void remove(String checkedFileName) {
details.remove(checkedFileName);
}
/**
* Calculates the hashcode for the serializable object based on its content.
* @param object serializable object.
* @return the hashcode for serializable object.
*/
private static String getHashCodeBasedOnObjectContent(Serializable object) {
try {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// in-memory serialization of Configuration
serialize(object, outputStream);
// Instead of hexEncoding outputStream.toByteArray() directly we
// use a message digest here to keep the length of the
// hashcode reasonable
final MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(outputStream.toByteArray());
return DatatypeConverter.printHexBinary(digest.digest());
}
catch (final IOException | NoSuchAlgorithmException ex) {
// rethrow as unchecked exception
throw new IllegalStateException("Unable to calculate hashcode.", ex);
}
}
/**
* Serializes object to output stream.
* @param object object to be erialized
* @param outputStream serialization stream
* @throws IOException if an error occurs
*/
private static void serialize(Serializable object,
OutputStream outputStream) throws IOException {
final ObjectOutputStream oos = new ObjectOutputStream(outputStream);
try {
oos.writeObject(object);
}
finally {
flushAndCloseOutStream(oos);
}
}
/**
* Puts external resources in cache.
* If at least one external resource changed, clears the cache.
* @param locations locations of external resources.
*/
public void putExternalResources(Set<String> locations) {
final Set<ExternalResource> resources = loadExternalResources(locations);
if (areExternalResourcesChanged(resources)) {
reset();
}
fillCacheWithExternalResources(resources);
}
/**
* Loads a set of {@link ExternalResource} based on their locations.
* @param resourceLocations locations of external configuration resources.
* @return a set of {@link ExternalResource}.
*/
private static Set<ExternalResource> loadExternalResources(Set<String> resourceLocations) {
final Set<ExternalResource> resources = new HashSet<>();
for (String location : resourceLocations) {
String contentHashSum = null;
try {
final byte[] content = loadExternalResource(location);
contentHashSum = getHashCodeBasedOnObjectContent(content);
}
catch (CheckstyleException ex) {
// if exception happened (configuration resource was not found, connection is not
// available, resource is broken, etc), we need to calculate hash sum based on
// exception object content in order to check whether problem is resolved later
// and/or the configuration is changed.
contentHashSum = getHashCodeBasedOnObjectContent(ex);
}
finally {
resources.add(new ExternalResource(EXTERNAL_RESOURCE_KEY_PREFIX + location,
contentHashSum));
}
}
return resources;
}
/**
* Loads the content of external resource.
* @param location external resource location.
* @return array of bytes which represents the content of external resource in binary form.
* @throws CheckstyleException if error while loading occurs.
*/
private static byte[] loadExternalResource(String location) throws CheckstyleException {
final byte[] content;
final URI uri = CommonUtils.getUriByFilename(location);
try {
content = ByteStreams.toByteArray(new BufferedInputStream(uri.toURL().openStream()));
}
catch (IOException ex) {
throw new CheckstyleException("Unable to load external resource file " + location, ex);
}
return content;
}
/**
* Checks whether the contents of external configuration resources were changed.
* @param resources a set of {@link ExternalResource}.
* @return true if the contents of external configuration resources were changed.
*/
private boolean areExternalResourcesChanged(Set<ExternalResource> resources) {
return resources.stream().anyMatch(resource -> {
boolean changed = false;
if (isResourceLocationInCache(resource.location)) {
final String contentHashSum = resource.contentHashSum;
final String cachedHashSum = details.getProperty(resource.location);
if (!cachedHashSum.equals(contentHashSum)) {
changed = true;
}
}
else {
changed = true;
}
return changed;
});
}
/**
* Fills cache with a set of {@link ExternalResource}.
* If external resource from the set is already in cache, it will be skipped.
* @param externalResources a set of {@link ExternalResource}.
*/
private void fillCacheWithExternalResources(Set<ExternalResource> externalResources) {
externalResources.stream()
.filter(resource -> !isResourceLocationInCache(resource.location))
.forEach(resource -> details.setProperty(resource.location, resource.contentHashSum));
}
/**
* Checks whether resource location is in cache.
* @param location resource location.
* @return true if resource location is in cache.
*/
private boolean isResourceLocationInCache(String location) {
final String cachedHashSum = details.getProperty(location);
return cachedHashSum != null;
}
/**
* Class which represents external resource.
* @author Andrei Selkin
*/
private static class ExternalResource {
/** Location of resource. */
private final String location;
/** Hash sum which is calculated based on resource content. */
private final String contentHashSum;
/**
* Creates an instance.
* @param location resource location.
* @param contentHashSum content hash sum.
*/
ExternalResource(String location, String contentHashSum) {
this.location = location;
this.contentHashSum = contentHashSum;
}
}
}
| lgpl-2.1 |
davipt/geoip-api-java | examples/NetSpeedCellLookup.java | 605 | import com.maxmind.geoip.*;
import java.io.IOException;
/* sample of how to use the GeoIP Java API with GeoIP Organization and ISP databases */
/* This example can also be used with the GeoIP Domain, NetSpeedCell and ASNum databases */
/* Usage: java NetSpeedCellLookup 64.4.4.4 */
class NetSpeedCellLookup {
public static void main(String[] args) {
try {
LookupService ns = new LookupService("/usr/local/share/GeoIP/GeoIPNetSpeedCell.dat");
System.out.println("XX: " + ns.getOrg(args[0]));
ns.close();
}
catch (IOException e) {
System.out.println("IO Exception");
}
}
}
| lgpl-2.1 |
git-moss/Push2Display | lib/batik-1.8/sources/org/apache/batik/util/SVGConstants.java | 41361 | /*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.batik.util;
/**
* Define SVG constants, such as tag names, attribute names and URI
*
* @author <a href="mailto:tkormann@apache.org">Thierry Kormann</a>
* @author <a href="mailto:vincent.hardy@eng.sun.com">Vincent Hardy</a>
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id: SVGConstants.java 662138 2008-06-01 03:26:00Z cam $
*/
public interface SVGConstants extends CSSConstants, XMLConstants {
/////////////////////////////////////////////////////////////////////////
// SVG general
/////////////////////////////////////////////////////////////////////////
String SVG_PUBLIC_ID =
"-//W3C//DTD SVG 1.0//EN";
String SVG_SYSTEM_ID =
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd";
String SVG_NAMESPACE_URI =
"http://www.w3.org/2000/svg";
String SVG_VERSION =
"1.0";
//////////////////////////////////////////////////////////////////////////
// Events type and attributes
//////////////////////////////////////////////////////////////////////////
/**
* The event type for MouseEvent.
*/
String SVG_MOUSEEVENTS_EVENT_TYPE = "MouseEvents";
/**
* The event type for UIEvent.
*/
String SVG_UIEVENTS_EVENT_TYPE = "UIEvents";
/**
* The event type for SVGEvent.
*/
String SVG_SVGEVENTS_EVENT_TYPE = "SVGEvents";
/**
* The event type for KeyEvent.
*/
String SVG_KEYEVENTS_EVENT_TYPE = "KeyEvents";
// ---------------------------------------------------------------------
/**
* The event type for 'keydown' KeyEvent.
*/
String SVG_KEYDOWN_EVENT_TYPE = "keydown";
/**
* The event type for 'keypress' KeyEvent.
*/
String SVG_KEYPRESS_EVENT_TYPE = "keypress";
/**
* The event type for 'keyup' KeyEvent.
*/
String SVG_KEYUP_EVENT_TYPE = "keyup";
/**
* The event type for 'click' MouseEvent.
*/
String SVG_CLICK_EVENT_TYPE = "click";
/**
* The event type for 'mouseup' MouseEvent.
*/
String SVG_MOUSEUP_EVENT_TYPE = "mouseup";
/**
* The event type for 'mousedown' MouseEvent.
*/
String SVG_MOUSEDOWN_EVENT_TYPE = "mousedown";
/**
* The event type for 'mousemove' MouseEvent.
*/
String SVG_MOUSEMOVE_EVENT_TYPE = "mousemove";
/**
* The event type for 'mouseout' MouseEvent.
*/
String SVG_MOUSEOUT_EVENT_TYPE = "mouseout";
/**
* The event type for 'mouseover' MouseEvent.
*/
String SVG_MOUSEOVER_EVENT_TYPE = "mouseover";
/**
* The event type for 'DOMFocusIn' UIEvent.
*/
String SVG_DOMFOCUSIN_EVENT_TYPE = "DOMFocusIn";
/**
* The event type for 'DOMFocusOut' UIEvent.
*/
String SVG_DOMFOCUSOUT_EVENT_TYPE = "DOMFocusOut";
/**
* The event type for 'DOMActivate' UIEvent.
*/
String SVG_DOMACTIVATE_EVENT_TYPE = "DOMActivate";
/**
* The event type for 'SVGLoad' SVGEvent.
*/
String SVG_SVGLOAD_EVENT_TYPE = "SVGLoad";
/**
* The event type for 'SVGUnload' SVGEvent.
*/
String SVG_SVGUNLOAD_EVENT_TYPE = "SVGUnload";
/**
* The event type for 'SVGAbort' SVGEvent.
*/
String SVG_SVGABORT_EVENT_TYPE = "SVGAbort";
/**
* The event type for 'SVGError' SVGEvent.
*/
String SVG_SVGERROR_EVENT_TYPE = "SVGError";
/**
* The event type for 'SVGResize' SVGEvent.
*/
String SVG_SVGRESIZE_EVENT_TYPE = "SVGResize";
/**
* The event type for 'SVGScroll' SVGEvent.
*/
String SVG_SVGSCROLL_EVENT_TYPE = "SVGScroll";
/**
* The event type for 'SVGZoom' SVGEvent.
*/
String SVG_SVGZOOM_EVENT_TYPE = "SVGZoom";
// ---------------------------------------------------------------------
/**
* The 'onkeyup' attribute name of type KeyEvents.
*/
String SVG_ONKEYUP_ATTRIBUTE = "onkeyup";
/**
* The 'onkeydown' attribute name of type KeyEvents.
*/
String SVG_ONKEYDOWN_ATTRIBUTE = "onkeydown";
/**
* The 'onkeypress' attribute name of type KeyEvents.
*/
String SVG_ONKEYPRESS_ATTRIBUTE = "onkeypress";
/**
* The 'onabort' attribute name of type SVGEvents.
*/
String SVG_ONABORT_ATTRIBUTE = "onabort";
/**
* The 'onabort' attribute name of type SVGEvents.
*/
String SVG_ONACTIVATE_ATTRIBUTE = "onactivate";
/**
* The 'onbegin' attribute name of type SVGEvents.
*/
String SVG_ONBEGIN_ATTRIBUTE = "onbegin";
/**
* The 'onclick' attribute name of type MouseEvents.
*/
String SVG_ONCLICK_ATTRIBUTE = "onclick";
/**
* The 'onend' attribute name of type SVGEvents.
*/
String SVG_ONEND_ATTRIBUTE = "onend";
/**
* The 'onerror' attribute name of type SVGEvents.
*/
String SVG_ONERROR_ATTRIBUTE = "onerror";
/**
* The 'onfocusin' attribute name of type UIEvents.
*/
String SVG_ONFOCUSIN_ATTRIBUTE = "onfocusin";
/**
* The 'onfocusout' attribute name of type UIEvents.
*/
String SVG_ONFOCUSOUT_ATTRIBUTE = "onfocusout";
/**
* The 'onload' attribute name of type SVGEvents.
*/
String SVG_ONLOAD_ATTRIBUTE = "onload";
/**
* The 'onmousedown' attribute name of type MouseEvents.
*/
String SVG_ONMOUSEDOWN_ATTRIBUTE = "onmousedown";
/**
* The 'onmousemove' attribute name of type MouseEvents.
*/
String SVG_ONMOUSEMOVE_ATTRIBUTE = "onmousemove";
/**
* The 'onmouseout' attribute name of type MouseEvents.
*/
String SVG_ONMOUSEOUT_ATTRIBUTE = "onmouseout";
/**
* The 'onmouseover' attribute name of type MouseEvents.
*/
String SVG_ONMOUSEOVER_ATTRIBUTE = "onmouseover";
/**
* The 'onmouseup' attribute name of type MouseEvents.
*/
String SVG_ONMOUSEUP_ATTRIBUTE = "onmouseup";
/**
* The 'onrepeat' attribute name of type SVGEvents.
*/
String SVG_ONREPEAT_ATTRIBUTE = "onrepeat";
/**
* The 'onresize' attribute name of type SVGEvents.
*/
String SVG_ONRESIZE_ATTRIBUTE = "onresize";
/**
* The 'onscroll' attribute name of type SVGEvents.
*/
String SVG_ONSCROLL_ATTRIBUTE = "onscroll";
/**
* The 'onunload' attribute name of type SVGEvents.
*/
String SVG_ONUNLOAD_ATTRIBUTE = "onunload";
/**
* The 'onzoom' attribute name of type SVGEvents.
*/
String SVG_ONZOOM_ATTRIBUTE = "onzoom";
/////////////////////////////////////////////////////////////////////////
// SVG features
/////////////////////////////////////////////////////////////////////////
// SVG 1.0 feature strings
String SVG_ORG_W3C_SVG_FEATURE = "org.w3c.svg";
String SVG_ORG_W3C_SVG_STATIC_FEATURE = "org.w3c.svg.static";
String SVG_ORG_W3C_SVG_ANIMATION_FEATURE = "org.w3c.svg.animation";
String SVG_ORG_W3C_SVG_DYNAMIC_FEATURE = "org.w3c.svg.dynamic";
String SVG_ORG_W3C_SVG_ALL_FEATURE = "org.w3c.svg.all";
String SVG_ORG_W3C_DOM_SVG_FEATURE = "org.w3c.dom.svg";
String SVG_ORG_W3C_DOM_SVG_STATIC_FEATURE = "org.w3c.dom.svg.static";
String SVG_ORG_W3C_DOM_SVG_ANIMATION_FEATURE = "org.w3c.dom.svg.animation";
String SVG_ORG_W3C_DOM_SVG_DYNAMIC_FEATURE = "org.w3c.dom.svg.dynamic";
String SVG_ORG_W3C_DOM_SVG_ALL_FEATURE = "org.w3c.dom.svg.all";
// SVG 1.1 feature strings
String SVG_SVG11_SVG_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVG";
String SVG_SVG11_SVG_DOM_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVGDOM";
String SVG_SVG11_SVG_STATIC_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVG-static";
String SVG_SVG11_SVG_DOM_STATIC_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVGDOM-static";
String SVG_SVG11_SVG_ANIMATION_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVG-animation";
String SVG_SVG11_SVG_DOM_ANIMATION_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVGDOM-animation";
String SVG_SVG11_SVG_DYNAMIC_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVG-dynamic";
String SVG_SVG11_SVG_DOM_DYNAMIC_FEATURE = "http://www.w3.org/TR/SVG11/feature#SVGDOM-dynamic";
String SVG_SVG11_CORE_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#CoreAttribute";
String SVG_SVG11_STRUCTURE_FEATURE = "http://www.w3.org/TR/SVG11/feature#Structure";
String SVG_SVG11_BASIC_STRUCTURE_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicStructure";
String SVG_SVG11_CONTAINER_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#ContainerAttribute";
String SVG_SVG11_CONDITIONAL_PROCESSING_FEATURE = "http://www.w3.org/TR/SVG11/feature#ConditionalProcessing";
String SVG_SVG11_IMAGE_FEATURE = "http://www.w3.org/TR/SVG11/feature#Image";
String SVG_SVG11_STYLE_FEATURE = "http://www.w3.org/TR/SVG11/feature#Style";
String SVG_SVG11_VIEWPORT_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#ViewportAttribute";
String SVG_SVG11_SHAPE_FEATURE = "http://www.w3.org/TR/SVG11/feature#Shape";
String SVG_SVG11_TEXT_FEATURE = "http://www.w3.org/TR/SVG11/feature#Text";
String SVG_SVG11_BASIC_TEXT_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicText";
String SVG_SVG11_PAINT_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#PaintAttribute";
String SVG_SVG11_BASIC_PAINT_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicPaintAttribute";
String SVG_SVG11_OPACITY_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#OpacityAttribute";
String SVG_SVG11_GRAPHICS_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#GraphicsAttribute";
String SVG_SVG11_BASIC_GRAPHICS_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicGraphicsAttribute";
String SVG_SVG11_MARKER_FEATURE = "http://www.w3.org/TR/SVG11/feature#Marker";
String SVG_SVG11_COLOR_PROFILE_FEATURE = "http://www.w3.org/TR/SVG11/feature#ColorProfile";
String SVG_SVG11_GRADIENT_FEATURE = "http://www.w3.org/TR/SVG11/feature#Gradient";
String SVG_SVG11_PATTERN_FEATURE = "http://www.w3.org/TR/SVG11/feature#Pattern";
String SVG_SVG11_CLIP_FEATURE = "http://www.w3.org/TR/SVG11/feature#Clip";
String SVG_SVG11_BASIC_CLIP_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicClip";
String SVG_SVG11_MASK_FEATURE = "http://www.w3.org/TR/SVG11/feature#Mask";
String SVG_SVG11_FILTER_FEATURE = "http://www.w3.org/TR/SVG11/feature#Filter";
String SVG_SVG11_BASIC_FILTER_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicFilter";
String SVG_SVG11_DOCUMENT_EVENTS_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute";
String SVG_SVG11_GRAPHICAL_EVENTS_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#GraphicalEventsAttribute";
String SVG_SVG11_ANIMATION_EVENTS_ATTRIBUTE_FEATURE = "http://www.w3.org/TR/SVG11/feature#AnimationEventsAttribute";
String SVG_SVG11_CURSOR_FEATURE = "http://www.w3.org/TR/SVG11/feature#Cursor";
String SVG_SVG11_HYPERLINKING_FEATURE = "http://www.w3.org/TR/SVG11/feature#Hyperlinking";
String SVG_SVG11_XLINK_FEATURE = "http://www.w3.org/TR/SVG11/feature#Xlink";
String SVG_SVG11_EXTERNAL_RESOURCES_REQUIRED_FEATURE = "http://www.w3.org/TR/SVG11/feature#ExternalResourcesRequired";
String SVG_SVG11_VIEW_FEATURE = "http://www.w3.org/TR/SVG11/feature#View";
String SVG_SVG11_SCRIPT_FEATURE = "http://www.w3.org/TR/SVG11/feature#Script";
String SVG_SVG11_ANIMATION_FEATURE = "http://www.w3.org/TR/SVG11/feature#Animation";
String SVG_SVG11_FONT_FEATURE = "http://www.w3.org/TR/SVG11/feature#Font";
String SVG_SVG11_BASIC_FONT_FEATURE = "http://www.w3.org/TR/SVG11/feature#BasicFont";
String SVG_SVG11_EXTENSIBILITY_FEATURE = "http://www.w3.org/TR/SVG11/feature#Extensibility";
// TODO SVG 1.2 feature strings
/////////////////////////////////////////////////////////////////////////
// SVG tags
/////////////////////////////////////////////////////////////////////////
String SVG_A_TAG = "a";
String SVG_ALT_GLYPH_TAG = "altGlyph";
String SVG_ALT_GLYPH_DEF_TAG = "altGlyphDef";
String SVG_ALT_GLYPH_ITEM_TAG = "altGlyphItem";
String SVG_ANIMATE_TAG = "animate";
String SVG_ANIMATE_COLOR_TAG = "animateColor";
String SVG_ANIMATE_MOTION_TAG = "animateMotion";
String SVG_ANIMATE_TRANSFORM_TAG = "animateTransform";
String SVG_CIRCLE_TAG = "circle";
String SVG_CLIP_PATH_TAG = "clipPath";
String SVG_COLOR_PROFILE_TAG = "color-profile";
String SVG_CURSOR_TAG = "cursor";
String SVG_DEFINITION_SRC_TAG = "definition-src";
String SVG_DEFS_TAG = "defs";
String SVG_DESC_TAG = "desc";
String SVG_ELLIPSE_TAG = "ellipse";
String SVG_FE_BLEND_TAG = "feBlend";
String SVG_FE_COLOR_MATRIX_TAG = "feColorMatrix";
String SVG_FE_COMPONENT_TRANSFER_TAG = "feComponentTransfer";
String SVG_FE_COMPOSITE_TAG = "feComposite";
String SVG_FE_CONVOLVE_MATRIX_TAG = "feConvolveMatrix";
String SVG_FE_DIFFUSE_LIGHTING_TAG = "feDiffuseLighting";
String SVG_FE_DISPLACEMENT_MAP_TAG = "feDisplacementMap";
String SVG_FE_DISTANT_LIGHT_TAG = "feDistantLight";
String SVG_FE_FLOOD_TAG = "feFlood";
String SVG_FE_FUNC_A_TAG = "feFuncA";
String SVG_FE_FUNC_B_TAG = "feFuncB";
String SVG_FE_FUNC_G_TAG = "feFuncG";
String SVG_FE_FUNC_R_TAG = "feFuncR";
String SVG_FE_GAUSSIAN_BLUR_TAG = "feGaussianBlur";
String SVG_FE_IMAGE_TAG = "feImage";
String SVG_FE_MERGE_NODE_TAG = "feMergeNode";
String SVG_FE_MERGE_TAG = "feMerge";
String SVG_FE_MORPHOLOGY_TAG = "feMorphology";
String SVG_FE_OFFSET_TAG = "feOffset";
String SVG_FE_POINT_LIGHT_TAG = "fePointLight";
String SVG_FE_SPECULAR_LIGHTING_TAG = "feSpecularLighting";
String SVG_FE_SPOT_LIGHT_TAG = "feSpotLight";
String SVG_FE_TILE_TAG = "feTile";
String SVG_FE_TURBULENCE_TAG = "feTurbulence";
String SVG_FILTER_TAG = "filter";
String SVG_FONT_TAG = "font";
String SVG_FONT_FACE_TAG = "font-face";
String SVG_FONT_FACE_FORMAT_TAG = "font-face-format";
String SVG_FONT_FACE_NAME_TAG = "font-face-name";
String SVG_FONT_FACE_SRC_TAG = "font-face-src";
String SVG_FONT_FACE_URI_TAG = "font-face-uri";
String SVG_FOREIGN_OBJECT_TAG = "foreignObject";
String SVG_G_TAG = "g";
String SVG_GLYPH_TAG = "glyph";
String SVG_GLYPH_REF_TAG = "glyphRef";
String SVG_HKERN_TAG = "hkern";
String SVG_IMAGE_TAG = "image";
String SVG_LINE_TAG = "line";
String SVG_LINEAR_GRADIENT_TAG = "linearGradient";
String SVG_MARKER_TAG = "marker";
String SVG_MASK_TAG = "mask";
String SVG_METADATA_TAG = "metadata";
String SVG_MISSING_GLYPH_TAG = "missing-glyph";
String SVG_MPATH_TAG = "mpath";
String SVG_PATH_TAG = "path";
String SVG_PATTERN_TAG = "pattern";
String SVG_POLYGON_TAG = "polygon";
String SVG_POLYLINE_TAG = "polyline";
String SVG_RADIAL_GRADIENT_TAG = "radialGradient";
String SVG_RECT_TAG = "rect";
String SVG_SET_TAG = "set";
String SVG_SCRIPT_TAG = "script";
String SVG_STOP_TAG = "stop";
String SVG_STYLE_TAG = "style";
String SVG_SVG_TAG = "svg";
String SVG_SWITCH_TAG = "switch";
String SVG_SYMBOL_TAG = "symbol";
String SVG_TEXT_PATH_TAG = "textPath";
String SVG_TEXT_TAG = "text";
String SVG_TITLE_TAG = "title";
String SVG_TREF_TAG = "tref";
String SVG_TSPAN_TAG = "tspan";
String SVG_USE_TAG = "use";
String SVG_VIEW_TAG = "view";
String SVG_VKERN_TAG = "vkern";
/////////////////////////////////////////////////////////////////////////
// SVG attributes
/////////////////////////////////////////////////////////////////////////
String SVG_ACCENT_HEIGHT_ATTRIBUTE = "accent-height";
String SVG_ACCUMULATE_ATTRIBUTE = "accumulate";
String SVG_ADDITIVE_ATTRIBUTE = "additive";
String SVG_AMPLITUDE_ATTRIBUTE = "amplitude";
String SVG_ARABIC_FORM_ATTRIBUTE = "arabic-form";
String SVG_ASCENT_ATTRIBUTE = "ascent";
String SVG_AZIMUTH_ATTRIBUTE = "azimuth";
String SVG_ALPHABETIC_ATTRIBUTE = "alphabetic";
String SVG_ATTRIBUTE_NAME_ATTRIBUTE = "attributeName";
String SVG_ATTRIBUTE_TYPE_ATTRIBUTE = "attributeType";
String SVG_BASE_FREQUENCY_ATTRIBUTE = "baseFrequency";
String SVG_BASE_PROFILE_ATTRIBUTE = "baseProfile";
String SVG_BEGIN_ATTRIBUTE = "begin";
String SVG_BBOX_ATTRIBUTE = "bbox";
String SVG_BIAS_ATTRIBUTE = "bias";
String SVG_BY_ATTRIBUTE = "by";
String SVG_CALC_MODE_ATTRIBUTE = "calcMode";
String SVG_CAP_HEIGHT_ATTRIBUTE = "cap-height";
String SVG_CLASS_ATTRIBUTE = "class";
String SVG_CLIP_PATH_ATTRIBUTE = CSS_CLIP_PATH_PROPERTY;
String SVG_CLIP_PATH_UNITS_ATTRIBUTE = "clipPathUnits";
String SVG_COLOR_INTERPOLATION_ATTRIBUTE = CSS_COLOR_INTERPOLATION_PROPERTY;
String SVG_COLOR_RENDERING_ATTRIBUTE = CSS_COLOR_RENDERING_PROPERTY;
String SVG_CONTENT_SCRIPT_TYPE_ATTRIBUTE = "contentScriptType";
String SVG_CONTENT_STYLE_TYPE_ATTRIBUTE = "contentStyleType";
String SVG_CX_ATTRIBUTE = "cx";
String SVG_CY_ATTRIBUTE = "cy";
String SVG_DESCENT_ATTRIBUTE = "descent";
String SVG_DIFFUSE_CONSTANT_ATTRIBUTE = "diffuseConstant";
String SVG_DIVISOR_ATTRIBUTE = "divisor";
String SVG_DUR_ATTRIBUTE = "dur";
String SVG_DX_ATTRIBUTE = "dx";
String SVG_DY_ATTRIBUTE = "dy";
String SVG_D_ATTRIBUTE = "d";
String SVG_EDGE_MODE_ATTRIBUTE = "edgeMode";
String SVG_ELEVATION_ATTRIBUTE = "elevation";
String SVG_ENABLE_BACKGROUND_ATTRIBUTE = CSS_ENABLE_BACKGROUND_PROPERTY;
String SVG_END_ATTRIBUTE = "end";
String SVG_EXPONENT_ATTRIBUTE = "exponent";
String SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE = "externalResourcesRequired";
String SVG_FILL_ATTRIBUTE = CSS_FILL_PROPERTY;
String SVG_FILL_OPACITY_ATTRIBUTE = CSS_FILL_OPACITY_PROPERTY;
String SVG_FILL_RULE_ATTRIBUTE = CSS_FILL_RULE_PROPERTY;
String SVG_FILTER_ATTRIBUTE = CSS_FILTER_PROPERTY;
String SVG_FILTER_RES_ATTRIBUTE = "filterRes";
String SVG_FILTER_UNITS_ATTRIBUTE = "filterUnits";
String SVG_FLOOD_COLOR_ATTRIBUTE = CSS_FLOOD_COLOR_PROPERTY;
String SVG_FLOOD_OPACITY_ATTRIBUTE = CSS_FLOOD_OPACITY_PROPERTY;
String SVG_FORMAT_ATTRIBUTE = "format";
String SVG_FONT_FAMILY_ATTRIBUTE = CSS_FONT_FAMILY_PROPERTY;
String SVG_FONT_SIZE_ATTRIBUTE = CSS_FONT_SIZE_PROPERTY;
String SVG_FONT_STRETCH_ATTRIBUTE = CSS_FONT_STRETCH_PROPERTY;
String SVG_FONT_STYLE_ATTRIBUTE = CSS_FONT_STYLE_PROPERTY;
String SVG_FONT_VARIANT_ATTRIBUTE = CSS_FONT_VARIANT_PROPERTY;
String SVG_FONT_WEIGHT_ATTRIBUTE = CSS_FONT_WEIGHT_PROPERTY;
String SVG_FROM_ATTRIBUTE = "from";
String SVG_FX_ATTRIBUTE = "fx";
String SVG_FY_ATTRIBUTE = "fy";
String SVG_G1_ATTRIBUTE = "g1";
String SVG_G2_ATTRIBUTE = "g2";
String SVG_GLYPH_NAME_ATTRIBUTE = "glyph-name";
String SVG_GLYPH_REF_ATTRIBUTE = "glyphRef";
String SVG_GRADIENT_TRANSFORM_ATTRIBUTE = "gradientTransform";
String SVG_GRADIENT_UNITS_ATTRIBUTE = "gradientUnits";
String SVG_HANGING_ATTRIBUTE = "hanging";
String SVG_HEIGHT_ATTRIBUTE = "height";
String SVG_HORIZ_ADV_X_ATTRIBUTE = "horiz-adv-x";
String SVG_HORIZ_ORIGIN_X_ATTRIBUTE = "horiz-origin-x";
String SVG_HORIZ_ORIGIN_Y_ATTRIBUTE = "horiz-origin-y";
String SVG_ID_ATTRIBUTE = XMLConstants.XML_ID_ATTRIBUTE;
String SVG_IDEOGRAPHIC_ATTRIBUTE = "ideographic";
String SVG_IMAGE_RENDERING_ATTRIBUTE = CSS_IMAGE_RENDERING_PROPERTY;
String SVG_IN2_ATTRIBUTE = "in2";
String SVG_INTERCEPT_ATTRIBUTE = "intercept";
String SVG_IN_ATTRIBUTE = "in";
String SVG_K_ATTRIBUTE = "k";
String SVG_K1_ATTRIBUTE = "k1";
String SVG_K2_ATTRIBUTE = "k2";
String SVG_K3_ATTRIBUTE = "k3";
String SVG_K4_ATTRIBUTE = "k4";
String SVG_KERNEL_MATRIX_ATTRIBUTE = "kernelMatrix";
String SVG_KERNEL_UNIT_LENGTH_ATTRIBUTE = "kernelUnitLength";
String SVG_KERNING_ATTRIBUTE = CSS_KERNING_PROPERTY;
String SVG_KEY_POINTS_ATTRIBUTE = "keyPoints";
String SVG_KEY_SPLINES_ATTRIBUTE = "keySplines";
String SVG_KEY_TIMES_ATTRIBUTE = "keyTimes";
String SVG_LANG_ATTRIBUTE = "lang";
String SVG_LENGTH_ADJUST_ATTRIBUTE = "lengthAdjust";
String SVG_LIGHTING_COLOR_ATTRIBUTE = "lighting-color";
String SVG_LIMITING_CONE_ANGLE_ATTRIBUTE = "limitingConeAngle";
String SVG_LOCAL_ATTRIBUTE = "local";
String SVG_MARKER_HEIGHT_ATTRIBUTE = "markerHeight";
String SVG_MARKER_UNITS_ATTRIBUTE = "markerUnits";
String SVG_MARKER_WIDTH_ATTRIBUTE = "markerWidth";
String SVG_MASK_ATTRIBUTE = CSS_MASK_PROPERTY;
String SVG_MASK_CONTENT_UNITS_ATTRIBUTE = "maskContentUnits";
String SVG_MASK_UNITS_ATTRIBUTE = "maskUnits";
String SVG_MATHEMATICAL_ATTRIBUTE = "mathematical";
String SVG_MAX_ATTRIBUTE = "max";
String SVG_MEDIA_ATTRIBUTE = "media";
String SVG_METHOD_ATTRIBUTE = "method";
String SVG_MIN_ATTRIBUTE = "min";
String SVG_MODE_ATTRIBUTE = "mode";
String SVG_NAME_ATTRIBUTE = "name";
String SVG_NUM_OCTAVES_ATTRIBUTE = "numOctaves";
String SVG_OFFSET_ATTRIBUTE = "offset";
String SVG_OPACITY_ATTRIBUTE = CSS_OPACITY_PROPERTY;
String SVG_OPERATOR_ATTRIBUTE = "operator";
String SVG_ORDER_ATTRIBUTE = "order";
String SVG_ORIENT_ATTRIBUTE = "orient";
String SVG_ORIENTATION_ATTRIBUTE = "orientation";
String SVG_ORIGIN_ATTRIBUTE = "origin";
String SVG_OVERLINE_POSITION_ATTRIBUTE = "overline-position";
String SVG_OVERLINE_THICKNESS_ATTRIBUTE = "overline-thickness";
String SVG_PANOSE_1_ATTRIBUTE = "panose-1";
String SVG_PATH_ATTRIBUTE = "path";
String SVG_PATH_LENGTH_ATTRIBUTE = "pathLength";
String SVG_PATTERN_CONTENT_UNITS_ATTRIBUTE = "patternContentUnits";
String SVG_PATTERN_TRANSFORM_ATTRIBUTE = "patternTransform";
String SVG_PATTERN_UNITS_ATTRIBUTE = "patternUnits";
String SVG_POINTS_ATTRIBUTE = "points";
String SVG_POINTS_AT_X_ATTRIBUTE = "pointsAtX";
String SVG_POINTS_AT_Y_ATTRIBUTE = "pointsAtY";
String SVG_POINTS_AT_Z_ATTRIBUTE = "pointsAtZ";
String SVG_PRESERVE_ALPHA_ATTRIBUTE = "preserveAlpha";
String SVG_PRESERVE_ASPECT_RATIO_ATTRIBUTE = "preserveAspectRatio";
String SVG_PRIMITIVE_UNITS_ATTRIBUTE = "primitiveUnits";
String SVG_RADIUS_ATTRIBUTE = "radius";
String SVG_REF_X_ATTRIBUTE = "refX";
String SVG_REF_Y_ATTRIBUTE = "refY";
String SVG_RENDERING_INTENT_ATTRIBUTE = "rendering-intent";
String SVG_REPEAT_COUNT_ATTRIBUTE = "repeatCount";
String SVG_REPEAT_DUR_ATTRIBUTE = "repeatDur";
String SVG_REQUIRED_FEATURES_ATTRIBUTE = "requiredFeatures";
String SVG_REQUIRED_EXTENSIONS_ATTRIBUTE = "requiredExtensions";
String SVG_RESULT_ATTRIBUTE = "result";
String SVG_RESTART_ATTRIBUTE = "restart";
String SVG_RX_ATTRIBUTE = "rx";
String SVG_RY_ATTRIBUTE = "ry";
String SVG_R_ATTRIBUTE = "r";
String SVG_ROTATE_ATTRIBUTE = "rotate";
String SVG_SCALE_ATTRIBUTE = "scale";
String SVG_SEED_ATTRIBUTE = "seed";
String SVG_SHAPE_RENDERING_ATTRIBUTE = CSS_SHAPE_RENDERING_PROPERTY;
String SVG_SLOPE_ATTRIBUTE = "slope";
String SVG_SNAPSHOT_TIME_ATTRIBUTE = "snapshotTime";
String SVG_SPACE_ATTRIBUTE = "space";
String SVG_SPACING_ATTRIBUTE = "spacing";
String SVG_SPECULAR_CONSTANT_ATTRIBUTE = "specularConstant";
String SVG_SPECULAR_EXPONENT_ATTRIBUTE = "specularExponent";
String SVG_SPREAD_METHOD_ATTRIBUTE = "spreadMethod";
String SVG_START_OFFSET_ATTRIBUTE = "startOffset";
String SVG_STD_DEVIATION_ATTRIBUTE = "stdDeviation";
String SVG_STEMH_ATTRIBUTE = "stemh";
String SVG_STEMV_ATTRIBUTE = "stemv";
String SVG_STITCH_TILES_ATTRIBUTE = "stitchTiles";
String SVG_STOP_COLOR_ATTRIBUTE = "stop-color";
String SVG_STOP_OPACITY_ATTRIBUTE = CSS_STOP_OPACITY_PROPERTY;
String SVG_STRIKETHROUGH_POSITION_ATTRIBUTE = "strikethrough-position";
String SVG_STRIKETHROUGH_THICKNESS_ATTRIBUTE = "strikethrough-thickness";
String SVG_STRING_ATTRIBUTE = "string";
String SVG_STROKE_ATTRIBUTE = CSS_STROKE_PROPERTY;
String SVG_STROKE_DASHARRAY_ATTRIBUTE = CSS_STROKE_DASHARRAY_PROPERTY;
String SVG_STROKE_DASHOFFSET_ATTRIBUTE = CSS_STROKE_DASHOFFSET_PROPERTY;
String SVG_STROKE_LINECAP_ATTRIBUTE = CSS_STROKE_LINECAP_PROPERTY;
String SVG_STROKE_LINEJOIN_ATTRIBUTE = CSS_STROKE_LINEJOIN_PROPERTY;
String SVG_STROKE_MITERLIMIT_ATTRIBUTE = CSS_STROKE_MITERLIMIT_PROPERTY;
String SVG_STROKE_OPACITY_ATTRIBUTE = CSS_STROKE_OPACITY_PROPERTY;
String SVG_STROKE_WIDTH_ATTRIBUTE = CSS_STROKE_WIDTH_PROPERTY;
String SVG_STYLE_ATTRIBUTE = "style";
String SVG_SURFACE_SCALE_ATTRIBUTE = "surfaceScale";
String SVG_SYSTEM_LANGUAGE_ATTRIBUTE = "systemLanguage";
String SVG_TABLE_VALUES_ATTRIBUTE = "tableValues";
String SVG_TARGET_ATTRIBUTE = "target";
String SVG_TARGET_X_ATTRIBUTE = "targetX";
String SVG_TARGET_Y_ATTRIBUTE = "targetY";
String SVG_TEXT_ANCHOR_ATTRIBUTE = CSS_TEXT_ANCHOR_PROPERTY;
String SVG_TEXT_LENGTH_ATTRIBUTE = "textLength";
String SVG_TEXT_RENDERING_ATTRIBUTE = CSS_TEXT_RENDERING_PROPERTY;
String SVG_TITLE_ATTRIBUTE = "title";
String SVG_TO_ATTRIBUTE = "to";
String SVG_TRANSFORM_ATTRIBUTE = "transform";
String SVG_TYPE_ATTRIBUTE = "type";
String SVG_U1_ATTRIBUTE = "u1";
String SVG_U2_ATTRIBUTE = "u2";
String SVG_UNDERLINE_POSITION_ATTRIBUTE = "underline-position";
String SVG_UNDERLINE_THICKNESS_ATTRIBUTE = "underline-thickness";
String SVG_UNICODE_ATTRIBUTE = "unicode";
String SVG_UNICODE_RANGE_ATTRIBUTE = "unicode-range";
String SVG_UNITS_PER_EM_ATTRIBUTE = "units-per-em";
String SVG_V_ALPHABETIC_ATTRIBUTE = "v-alphabetic";
String SVG_V_HANGING_ATTRIBUTE = "v-hanging";
String SVG_V_IDEOGRAPHIC_ATTRIBUTE = "v-ideographic";
String SVG_V_MATHEMATICAL_ATTRIBUTE = "v-mathematical";
String SVG_VALUES_ATTRIBUTE = "values";
String SVG_VERSION_ATTRIBUTE = "version";
String SVG_VERT_ADV_Y_ATTRIBUTE = "vert-adv-y";
String SVG_VERT_ORIGIN_X_ATTRIBUTE = "vert-origin-x";
String SVG_VERT_ORIGIN_Y_ATTRIBUTE = "vert-origin-y";
String SVG_VIEW_BOX_ATTRIBUTE = "viewBox";
String SVG_VIEW_TARGET_ATTRIBUTE = "viewTarget";
String SVG_WIDTH_ATTRIBUTE = "width";
String SVG_WIDTHS_ATTRIBUTE = "widths";
String SVG_X1_ATTRIBUTE = "x1";
String SVG_X2_ATTRIBUTE = "x2";
String SVG_X_ATTRIBUTE = "x";
String SVG_X_CHANNEL_SELECTOR_ATTRIBUTE = "xChannelSelector";
String SVG_X_HEIGHT_ATTRIBUTE = "xHeight";
String SVG_Y1_ATTRIBUTE = "y1";
String SVG_Y2_ATTRIBUTE = "y2";
String SVG_Y_ATTRIBUTE = "y";
String SVG_Y_CHANNEL_SELECTOR_ATTRIBUTE = "yChannelSelector";
String SVG_Z_ATTRIBUTE = "z";
String SVG_ZOOM_AND_PAN_ATTRIBUTE = "zoomAndPan";
/////////////////////////////////////////////////////////////////////////
// SVG attribute value
/////////////////////////////////////////////////////////////////////////
String SVG_100_VALUE = "100";
String SVG_200_VALUE = "200";
String SVG_300_VALUE = "300";
String SVG_400_VALUE = "400";
String SVG_500_VALUE = "500";
String SVG_600_VALUE = "600";
String SVG_700_VALUE = "700";
String SVG_800_VALUE = "800";
String SVG_900_VALUE = "900";
String SVG_ABSOLUTE_COLORIMETRIC_VALUE = "absolute-colorimetric";
String SVG_ALIGN_VALUE = "align";
String SVG_ALL_VALUE = "all";
String SVG_ARITHMETIC_VALUE = "arithmetic";
String SVG_ATOP_VALUE = "atop";
String SVG_AUTO_VALUE = "auto";
String SVG_A_VALUE = "A";
String SVG_BACKGROUND_ALPHA_VALUE = "BackgroundAlpha";
String SVG_BACKGROUND_IMAGE_VALUE = "BackgroundImage";
String SVG_BEVEL_VALUE = "bevel";
String SVG_BOLDER_VALUE = "bolder";
String SVG_BOLD_VALUE = "bold";
String SVG_BUTT_VALUE = "butt";
String SVG_B_VALUE = "B";
String SVG_COMPOSITE_VALUE = "composite";
String SVG_CRISP_EDGES_VALUE = "crispEdges";
String SVG_CROSSHAIR_VALUE = "crosshair";
String SVG_DARKEN_VALUE = "darken";
String SVG_DEFAULT_VALUE = "default";
String SVG_DIGIT_ONE_VALUE = "1";
String SVG_DILATE_VALUE = "dilate";
String SVG_DISABLE_VALUE = "disable";
String SVG_DISCRETE_VALUE = "discrete";
String SVG_DUPLICATE_VALUE = "duplicate";
String SVG_END_VALUE = "end";
String SVG_ERODE_VALUE = "erode";
String SVG_EVEN_ODD_VALUE = "evenodd";
String SVG_EXACT_VALUE = "exact";
String SVG_E_RESIZE_VALUE = "e-resize";
String SVG_FALSE_VALUE = "false";
String SVG_FILL_PAINT_VALUE = "FillPaint";
String SVG_FLOOD_VALUE = "flood";
String SVG_FRACTAL_NOISE_VALUE = "fractalNoise";
String SVG_GAMMA_VALUE = "gamma";
String SVG_GEOMETRIC_PRECISION_VALUE = "geometricPrecision";
String SVG_G_VALUE = "G";
String SVG_HELP_VALUE = "help";
String SVG_HUE_ROTATE_VALUE = "hueRotate";
String SVG_HUNDRED_PERCENT_VALUE = "100%";
String SVG_H_VALUE = "h";
String SVG_IDENTITY_VALUE = "identity";
String SVG_INITIAL_VALUE = "initial";
String SVG_IN_VALUE = "in";
String SVG_ISOLATED_VALUE = "isolated";
String SVG_ITALIC_VALUE = "italic";
String SVG_LIGHTEN_VALUE = "lighten";
String SVG_LIGHTER_VALUE = "lighter";
String SVG_LINEAR_RGB_VALUE = "linearRGB";
String SVG_LINEAR_VALUE = "linear";
String SVG_LUMINANCE_TO_ALPHA_VALUE = "luminanceToAlpha";
String SVG_MAGNIFY_VALUE = "magnify";
String SVG_MATRIX_VALUE = "matrix";
String SVG_MEDIAL_VALUE = "medial";
String SVG_MEET_VALUE = "meet";
String SVG_MIDDLE_VALUE = "middle";
String SVG_MITER_VALUE = "miter";
String SVG_MOVE_VALUE = "move";
String SVG_MULTIPLY_VALUE = "multiply";
String SVG_NEW_VALUE = "new";
String SVG_NE_RESIZE_VALUE = "ne-resize";
String SVG_NINETY_VALUE = "90";
String SVG_NONE_VALUE = "none";
String SVG_NON_ZERO_VALUE = "nonzero";
String SVG_NORMAL_VALUE = "normal";
String SVG_NO_STITCH_VALUE = "noStitch";
String SVG_NW_RESIZE_VALUE = "nw-resize";
String SVG_N_RESIZE_VALUE = "n-resize";
String SVG_OBJECT_BOUNDING_BOX_VALUE = "objectBoundingBox";
String SVG_OBLIQUE_VALUE = "oblique";
String SVG_ONE_VALUE = "1";
String SVG_OPAQUE_VALUE = "1";
String SVG_OPTIMIZE_LEGIBILITY_VALUE = "optimizeLegibility";
String SVG_OPTIMIZE_QUALITY_VALUE = "optimizeQuality";
String SVG_OPTIMIZE_SPEED_VALUE = "optimizeSpeed";
String SVG_OUT_VALUE = "out";
String SVG_OVER_VALUE = "over";
String SVG_PACED_VALUE = "paced";
String SVG_PAD_VALUE = "pad";
String SVG_PERCEPTUAL_VALUE = "perceptual";
String SVG_POINTER_VALUE = "pointer";
String SVG_PRESERVE_VALUE = "preserve";
String SVG_REFLECT_VALUE = "reflect";
String SVG_RELATIVE_COLORIMETRIC_VALUE = "relative-colorimetric";
String SVG_REPEAT_VALUE = "repeat";
String SVG_ROUND_VALUE = "round";
String SVG_R_VALUE = "R";
String SVG_SATURATE_VALUE = "saturate";
String SVG_SATURATION_VALUE = "saturation";
String SVG_SCREEN_VALUE = "screen";
String SVG_SE_RESIZE_VALUE = "se-resize";
String SVG_SLICE_VALUE = "slice";
String SVG_SOURCE_ALPHA_VALUE = "SourceAlpha";
String SVG_SOURCE_GRAPHIC_VALUE = "SourceGraphic";
String SVG_SPACING_AND_GLYPHS_VALUE = "spacingAndGlyphs";
String SVG_SPACING_VALUE = "spacing";
String SVG_SQUARE_VALUE = "square";
String SVG_SRGB_VALUE = "sRGB";
String SVG_START_VALUE = "start";
String SVG_STITCH_VALUE = "stitch";
String SVG_STRETCH_VALUE = "stretch";
String SVG_STROKE_PAINT_VALUE = "StrokePaint";
String SVG_STROKE_WIDTH_VALUE = "strokeWidth";
String SVG_SW_RESIZE_VALUE = "sw-resize";
String SVG_S_RESIZE_VALUE = "s-resize";
String SVG_TABLE_VALUE = "table";
String SVG_TERMINAL_VALUE = "terminal";
String SVG_TEXT_VALUE = "text";
String SVG_TRANSLATE_VALUE = "translate";
String SVG_TRUE_VALUE = "true";
String SVG_TURBULENCE_VALUE = "turbulence";
String SVG_USER_SPACE_ON_USE_VALUE = "userSpaceOnUse";
String SVG_V_VALUE = "v";
String SVG_WAIT_VALUE = "wait";
String SVG_WRAP_VALUE = "wrap";
String SVG_W_RESIZE_VALUE = "w-resize";
String SVG_XMAXYMAX_VALUE = "xMaxYMax";
String SVG_XMAXYMID_VALUE = "xMaxYMid";
String SVG_XMAXYMIN_VALUE = "xMaxYMin";
String SVG_XMIDYMAX_VALUE = "xMidYMax";
String SVG_XMIDYMID_VALUE = "xMidYMid";
String SVG_XMIDYMIN_VALUE = "xMidYMin";
String SVG_XMINYMAX_VALUE = "xMinYMax";
String SVG_XMINYMID_VALUE = "xMinYMid";
String SVG_XMINYMIN_VALUE = "xMinYMin";
String SVG_XOR_VALUE = "xor";
String SVG_ZERO_PERCENT_VALUE = "0%";
String SVG_ZERO_VALUE = "0";
///////////////////////////////////////////////////////////////////
// default values for attributes
///////////////////////////////////////////////////////////////////
String SVG_CIRCLE_CX_DEFAULT_VALUE = "0";
String SVG_CIRCLE_CY_DEFAULT_VALUE = "0";
String SVG_CLIP_PATH_CLIP_PATH_UNITS_DEFAULT_VALUE = SVG_USER_SPACE_ON_USE_VALUE;
String SVG_COMPONENT_TRANSFER_FUNCTION_AMPLITUDE_DEFAULT_VALUE = "1";
String SVG_COMPONENT_TRANSFER_FUNCTION_EXPONENT_DEFAULT_VALUE = "1";
String SVG_COMPONENT_TRANSFER_FUNCTION_INTERCEPT_DEFAULT_VALUE = "0";
String SVG_COMPONENT_TRANSFER_FUNCTION_OFFSET_DEFAULT_VALUE = "0";
String SVG_COMPONENT_TRANSFER_FUNCTION_SLOPE_DEFAULT_VALUE = "1";
String SVG_COMPONENT_TRANSFER_FUNCTION_TABLE_VALUES_DEFAULT_VALUE = "";
String SVG_CURSOR_X_DEFAULT_VALUE = "0";
String SVG_CURSOR_Y_DEFAULT_VALUE = "0";
String SVG_ELLIPSE_CX_DEFAULT_VALUE = "0";
String SVG_ELLIPSE_CY_DEFAULT_VALUE = "0";
String SVG_FE_COMPOSITE_K1_DEFAULT_VALUE = "0";
String SVG_FE_COMPOSITE_K2_DEFAULT_VALUE = "0";
String SVG_FE_COMPOSITE_K3_DEFAULT_VALUE = "0";
String SVG_FE_COMPOSITE_K4_DEFAULT_VALUE = "0";
String SVG_FE_COMPOSITE_OPERATOR_DEFAULT_VALUE = SVG_OVER_VALUE;
String SVG_FE_CONVOLVE_MATRIX_EDGE_MODE_DEFAULT_VALUE = SVG_DUPLICATE_VALUE;
String SVG_FE_DIFFUSE_LIGHTING_DIFFUSE_CONSTANT_DEFAULT_VALUE = "1";
String SVG_FE_DIFFUSE_LIGHTING_SURFACE_SCALE_DEFAULT_VALUE = "1";
String SVG_FE_DISPLACEMENT_MAP_SCALE_DEFAULT_VALUE = "0";
String SVG_FE_DISTANT_LIGHT_AZIMUTH_DEFAULT_VALUE = "0";
String SVG_FE_DISTANT_LIGHT_ELEVATION_DEFAULT_VALUE = "0";
String SVG_FE_POINT_LIGHT_X_DEFAULT_VALUE = "0";
String SVG_FE_POINT_LIGHT_Y_DEFAULT_VALUE = "0";
String SVG_FE_POINT_LIGHT_Z_DEFAULT_VALUE = "0";
String SVG_FE_SPECULAR_LIGHTING_SPECULAR_CONSTANT_DEFAULT_VALUE = "1";
String SVG_FE_SPECULAR_LIGHTING_SPECULAR_EXPONENT_DEFAULT_VALUE = "1";
String SVG_FE_SPECULAR_LIGHTING_SURFACE_SCALE_DEFAULT_VALUE = "1";
String SVG_FE_SPOT_LIGHT_LIMITING_CONE_ANGLE_DEFAULT_VALUE = "90";
String SVG_FE_SPOT_LIGHT_POINTS_AT_X_DEFAULT_VALUE = "0";
String SVG_FE_SPOT_LIGHT_POINTS_AT_Y_DEFAULT_VALUE = "0";
String SVG_FE_SPOT_LIGHT_POINTS_AT_Z_DEFAULT_VALUE = "0";
String SVG_FE_SPOT_LIGHT_SPECULAR_EXPONENT_DEFAULT_VALUE = "1";
String SVG_FE_SPOT_LIGHT_X_DEFAULT_VALUE = "0";
String SVG_FE_SPOT_LIGHT_Y_DEFAULT_VALUE = "0";
String SVG_FE_SPOT_LIGHT_Z_DEFAULT_VALUE = "0";
String SVG_FE_TURBULENCE_NUM_OCTAVES_DEFAULT_VALUE = "1";
String SVG_FE_TURBULENCE_SEED_DEFAULT_VALUE = "0";
String SVG_FILTER_FILTER_UNITS_DEFAULT_VALUE = SVG_USER_SPACE_ON_USE_VALUE;
String SVG_FILTER_HEIGHT_DEFAULT_VALUE = "120%";
String SVG_FILTER_PRIMITIVE_X_DEFAULT_VALUE = "0%";
String SVG_FILTER_PRIMITIVE_Y_DEFAULT_VALUE = "0%";
String SVG_FILTER_PRIMITIVE_WIDTH_DEFAULT_VALUE = "100%";
String SVG_FILTER_PRIMITIVE_HEIGHT_DEFAULT_VALUE = "100%";
String SVG_FILTER_PRIMITIVE_UNITS_DEFAULT_VALUE = SVG_USER_SPACE_ON_USE_VALUE;
String SVG_FILTER_WIDTH_DEFAULT_VALUE = "120%";
String SVG_FILTER_X_DEFAULT_VALUE = "-10%";
String SVG_FILTER_Y_DEFAULT_VALUE = "-10%";
String SVG_FONT_FACE_FONT_STRETCH_DEFAULT_VALUE = SVG_NORMAL_VALUE;
String SVG_FONT_FACE_FONT_STYLE_DEFAULT_VALUE = SVG_ALL_VALUE;
String SVG_FONT_FACE_FONT_VARIANT_DEFAULT_VALUE = SVG_NORMAL_VALUE;
String SVG_FONT_FACE_FONT_WEIGHT_DEFAULT_VALUE = SVG_ALL_VALUE;
String SVG_FONT_FACE_PANOSE_1_DEFAULT_VALUE = "0 0 0 0 0 0 0 0 0 0";
String SVG_FONT_FACE_SLOPE_DEFAULT_VALUE = "0";
String SVG_FONT_FACE_UNITS_PER_EM_DEFAULT_VALUE = "1000";
String SVG_FOREIGN_OBJECT_X_DEFAULT_VALUE = "0";
String SVG_FOREIGN_OBJECT_Y_DEFAULT_VALUE = "0";
String SVG_HORIZ_ORIGIN_X_DEFAULT_VALUE = "0";
String SVG_HORIZ_ORIGIN_Y_DEFAULT_VALUE = "0";
String SVG_KERN_K_DEFAULT_VALUE = "0";
String SVG_IMAGE_X_DEFAULT_VALUE = "0";
String SVG_IMAGE_Y_DEFAULT_VALUE = "0";
String SVG_LINE_X1_DEFAULT_VALUE = "0";
String SVG_LINE_X2_DEFAULT_VALUE = "0";
String SVG_LINE_Y1_DEFAULT_VALUE = "0";
String SVG_LINE_Y2_DEFAULT_VALUE = "0";
String SVG_LINEAR_GRADIENT_X1_DEFAULT_VALUE = "0%";
String SVG_LINEAR_GRADIENT_X2_DEFAULT_VALUE = "100%";
String SVG_LINEAR_GRADIENT_Y1_DEFAULT_VALUE = "0%";
String SVG_LINEAR_GRADIENT_Y2_DEFAULT_VALUE = "0%";
String SVG_MARKER_MARKER_HEIGHT_DEFAULT_VALUE = "3";
String SVG_MARKER_MARKER_UNITS_DEFAULT_VALUE = SVG_STROKE_WIDTH_VALUE;
String SVG_MARKER_MARKER_WIDTH_DEFAULT_VALUE = "3";
String SVG_MARKER_ORIENT_DEFAULT_VALUE = "0";
String SVG_MARKER_REF_X_DEFAULT_VALUE = "0";
String SVG_MARKER_REF_Y_DEFAULT_VALUE = "0";
String SVG_MASK_HEIGHT_DEFAULT_VALUE = "120%";
String SVG_MASK_MASK_UNITS_DEFAULT_VALUE = SVG_USER_SPACE_ON_USE_VALUE;
String SVG_MASK_WIDTH_DEFAULT_VALUE = "120%";
String SVG_MASK_X_DEFAULT_VALUE = "-10%";
String SVG_MASK_Y_DEFAULT_VALUE = "-10%";
String SVG_PATTERN_X_DEFAULT_VALUE = "0";
String SVG_PATTERN_Y_DEFAULT_VALUE = "0";
String SVG_PATTERN_WIDTH_DEFAULT_VALUE = "0";
String SVG_PATTERN_HEIGHT_DEFAULT_VALUE = "0";
String SVG_RADIAL_GRADIENT_CX_DEFAULT_VALUE = "50%";
String SVG_RADIAL_GRADIENT_CY_DEFAULT_VALUE = "50%";
String SVG_RADIAL_GRADIENT_R_DEFAULT_VALUE = "50%";
String SVG_RECT_X_DEFAULT_VALUE = "0";
String SVG_RECT_Y_DEFAULT_VALUE = "0";
String SVG_SCRIPT_TYPE_ECMASCRIPT = "text/ecmascript";
String SVG_SCRIPT_TYPE_APPLICATION_ECMASCRIPT = "application/ecmascript";
String SVG_SCRIPT_TYPE_JAVASCRIPT = "text/javascript";
String SVG_SCRIPT_TYPE_APPLICATION_JAVASCRIPT = "application/javascript";
String SVG_SCRIPT_TYPE_DEFAULT_VALUE = SVG_SCRIPT_TYPE_ECMASCRIPT;
String SVG_SCRIPT_TYPE_JAVA = "application/java-archive";
String SVG_SVG_X_DEFAULT_VALUE = "0";
String SVG_SVG_Y_DEFAULT_VALUE = "0";
String SVG_SVG_HEIGHT_DEFAULT_VALUE = "100%";
String SVG_SVG_WIDTH_DEFAULT_VALUE = "100%";
String SVG_TEXT_PATH_START_OFFSET_DEFAULT_VALUE = "0";
String SVG_USE_X_DEFAULT_VALUE = "0";
String SVG_USE_Y_DEFAULT_VALUE = "0";
String SVG_USE_WIDTH_DEFAULT_VALUE = "100%";
String SVG_USE_HEIGHT_DEFAULT_VALUE = "100%";
///////////////////////////////////////////////////////////////////
// various constants in SVG attributes
///////////////////////////////////////////////////////////////////
String TRANSFORM_TRANSLATE = "translate";
String TRANSFORM_ROTATE = "rotate";
String TRANSFORM_SCALE = "scale";
String TRANSFORM_SKEWX = "skewX";
String TRANSFORM_SKEWY = "skewY";
String TRANSFORM_MATRIX = "matrix";
String PATH_ARC = "A";
String PATH_CLOSE = "Z";
String PATH_CUBIC_TO = "C";
String PATH_MOVE = "M";
String PATH_LINE_TO = "L";
String PATH_VERTICAL_LINE_TO = "V";
String PATH_HORIZONTAL_LINE_TO = "H";
String PATH_QUAD_TO = "Q";
String PATH_SMOOTH_QUAD_TO = "T";
///////////////////////////////////////////////////////////////////
// event constants
///////////////////////////////////////////////////////////////////
String SVG_EVENT_CLICK = "click";
String SVG_EVENT_KEYDOWN = "keydown";
String SVG_EVENT_KEYPRESS = "keypress";
String SVG_EVENT_KEYUP = "keyup";
String SVG_EVENT_MOUSEDOWN = "mousedown";
String SVG_EVENT_MOUSEMOVE = "mousemove";
String SVG_EVENT_MOUSEOUT = "mouseout";
String SVG_EVENT_MOUSEOVER = "mouseover";
String SVG_EVENT_MOUSEUP = "mouseup";
}
| lgpl-3.0 |
unicesi/QD-SPL | Generation/co.shift.modeling.m2m.editor/src/domainmetamodelm2m/presentation/Domainmetamodelm2mEditor.java | 54218 | /**
*/
package domainmetamodelm2m.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.MarkerHelper;
import org.eclipse.emf.common.ui.ViewerPane;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import domainmetamodelm2m.provider.Domainmetamodelm2mItemProviderAdapterFactory;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
/**
* This is an example of a Domainmetamodelm2m model editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class Domainmetamodelm2mEditor
extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider, IGotoMarker {
/**
* This keeps track of the editing domain that is used to track all changes to the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComposedAdapterFactory adapterFactory;
/**
* This is the content outline page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge...
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>();
/**
* This is the viewer that shadows the selection in the content outline.
* The parent relation must be correctly defined for this to work.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This inverts the roll of parent and child in the content provider and show parents as a tree.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TreeViewer parentViewer;
/**
* This shows how a tree view works.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TreeViewer treeViewer;
/**
* This shows how a list view works.
* A list viewer doesn't support icons.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ListViewer listViewer;
/**
* This shows how a table view works.
* A table can be used as a list with icons.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TableViewer tableViewer;
/**
* This shows how a tree view with columns works.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected TreeViewer treeViewerWithColumns;
/**
* This keeps track of the active viewer pane, in the book.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ViewerPane currentViewerPane;
/**
* This keeps track of the active content viewer, which may be either one of the viewers in the pages or the content outline viewer.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are listening to this editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* The MarkerHelper is responsible for creating workspace resource markers presented
* in Eclipse's Problems View.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MarkerHelper markerHelper = new EditUIMarkerHelper();
/**
* This listens for when the outline becomes active
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IPartListener partListener =
new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline)p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(Domainmetamodelm2mEditor.this);
setCurrentViewer(contentOutlineViewer);
}
}
else if (p instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet)p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(Domainmetamodelm2mEditor.this);
handleActivate();
}
}
else if (p == Domainmetamodelm2mEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
// Ignore.
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded loaded.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EContentAdapter problemIndicationAdapter =
new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource)notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
}
else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
}
else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
resourceToDiagnosticMap.remove(target);
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
}
};
/**
* This listens for workspace changes.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IResourceChangeListener resourceChangeListener =
new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
try {
class ResourceDeltaVisitor implements IResourceDeltaVisitor {
protected ResourceSet resourceSet = editingDomain.getResourceSet();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
public boolean visit(IResourceDelta delta) {
if (delta.getResource().getType() == IResource.FILE) {
if (delta.getKind() == IResourceDelta.REMOVED ||
delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() != IResourceDelta.MARKERS) {
Resource resource = resourceSet.getResource(URI.createPlatformResourceURI(delta.getFullPath().toString(), true), false);
if (resource != null) {
if (delta.getKind() == IResourceDelta.REMOVED) {
removedResources.add(resource);
}
else if (!savedResources.remove(resource)) {
changedResources.add(resource);
}
}
}
return false;
}
return true;
}
public Collection<Resource> getChangedResources() {
return changedResources;
}
public Collection<Resource> getRemovedResources() {
return removedResources;
}
}
final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
if (!visitor.getRemovedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
removedResources.addAll(visitor.getRemovedResources());
if (!isDirty()) {
getSite().getPage().closeEditor(Domainmetamodelm2mEditor.this, false);
}
}
});
}
if (!visitor.getChangedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
changedResources.addAll(visitor.getChangedResources());
if (getSite().getPage().getActiveEditor() == Domainmetamodelm2mEditor.this) {
handleActivate();
}
}
});
}
}
catch (CoreException exception) {
DomainMetamodelM2MEditorPlugin.INSTANCE.log(exception);
}
}
};
/**
* Handles activation of the editor or it's associated views.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
//
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
//
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(Domainmetamodelm2mEditor.this, false);
}
else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
}
else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
}
catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the specified diagnostic.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic =
new BasicDiagnostic
(Diagnostic.OK,
"co.shift.modeling.m2m.editor",
0,
null,
new Object [] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
}
else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
problemEditorPart.setMarkerHelper(markerHelper);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
}
catch (PartInitException exception) {
DomainMetamodelM2MEditorPlugin.INSTANCE.log(exception);
}
}
if (markerHelper.hasMarkers(editingDomain.getResourceSet())) {
markerHelper.deleteMarkers(editingDomain.getResourceSet());
if (diagnostic.getSeverity() != Diagnostic.OK) {
try {
markerHelper.createMarkers(diagnostic);
}
catch (CoreException exception) {
DomainMetamodelM2MEditorPlugin.INSTANCE.log(exception);
}
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean handleDirtyConflict() {
return
MessageDialog.openQuestion
(getSite().getShell(),
getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Domainmetamodelm2mEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
//
adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new Domainmetamodelm2mItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
// Create the command stack that will notify this editor as commands are executed.
//
BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to be the selection of the viewer with focus.
//
commandStack.addCommandStackListener
(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec
(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
//
Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext(); ) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
}
else {
propertySheetPage.refresh();
}
}
}
});
}
});
// Create the editing domain with a special command stack.
//
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>());
}
/**
* This is here for the listener to be able to call it.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
//
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable =
new Runnable() {
public void run() {
// Try to select the items in the current content viewer of the editor.
//
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the {@link IEditingDomainProvider} interface.
* This is important for implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object [] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object [] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCurrentViewerPane(ViewerPane viewerPane) {
if (currentViewerPane != viewerPane) {
if (currentViewerPane != null) {
currentViewerPane.showFocus(false);
}
currentViewerPane = viewerPane;
}
setCurrentViewer(currentViewerPane.getViewer());
}
/**
* This makes sure that one content viewer, either for the current page or the outline view, if it has focus,
* is the current one.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
//
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
//
selectionChangedListener =
new ISelectionChangedListener() {
// This just notifies those things that are affected by the section.
//
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
//
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
//
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
//
currentViewer = viewer;
// Set the editors selection based on the current viewer's selection.
//
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider} interface.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well registering the menu for extension.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu= contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
}
/**
* This is the method called to load a resource into the editing domain's resource set based on the editor's input.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
try {
// Load the resource through the editing domain.
//
resource = editingDomain.getResourceSet().getResource(resourceURI, true);
}
catch (Exception e) {
exception = e;
resource = editingDomain.getResourceSet().getResource(resourceURI, false);
}
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
}
/**
* Returns a diagnostic describing the errors and warnings listed in the resource
* and the specified exception (if any).
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
if (!resource.getErrors().isEmpty() || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic =
new BasicDiagnostic
(Diagnostic.ERROR,
"co.shift.modeling.m2m.editor",
0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object [] { exception == null ? (Object)resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
}
else if (exception != null) {
return
new BasicDiagnostic
(Diagnostic.ERROR,
"co.shift.modeling.m2m.editor",
0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception });
}
else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* This is the method used by the framework to install your own controls.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void createPages() {
// Creates the model from the editor input
//
createModel();
// Only creates the other pages if there is something that can be edited
//
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
selectionViewer = (TreeViewer)viewerPane.getViewer();
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet());
selectionViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
viewerPane.setTitle(editingDomain.getResourceSet());
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
}
// Create a page for the parent tree view.
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
parentViewer = (TreeViewer)viewerPane.getViewer();
parentViewer.setAutoExpandLevel(30);
parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory));
parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(parentViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ParentPage_label"));
}
// This is the page for the list viewer
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new ListViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
listViewer = (ListViewer)viewerPane.getViewer();
listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(listViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ListPage_label"));
}
// This is the page for the tree viewer
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewer = (TreeViewer)viewerPane.getViewer();
treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory);
createContextMenuFor(treeViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreePage_label"));
}
// This is the page for the table viewer.
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TableViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
tableViewer = (TableViewer)viewerPane.getViewer();
Table table = tableViewer.getTable();
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn objectColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(3, 100, true));
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
TableColumn selfColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(2, 100, true));
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
tableViewer.setColumnProperties(new String [] {"a", "b"});
tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(tableViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TablePage_label"));
}
// This is the page for the table tree viewer.
//
{
ViewerPane viewerPane =
new ViewerPane(getSite().getPage(), Domainmetamodelm2mEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewerWithColumns = (TreeViewer)viewerPane.getViewer();
Tree tree = treeViewerWithColumns.getTree();
tree.setLayoutData(new FillLayout());
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
objectColumn.setWidth(250);
TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE);
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
selfColumn.setWidth(200);
treeViewerWithColumns.setColumnProperties(new String [] {"a", "b"});
treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(treeViewerWithColumns);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label"));
}
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
//
getContainer().addControlListener
(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part,
* this hides the single tab at the bottom.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder)getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part,
* this shows the tabs at the bottom.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder)getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
}
else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
}
else if (key.equals(IGotoMarker.class)) {
return this;
}
else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
//
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
//
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
//
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
//
contentOutlineViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
//
contentOutlinePage.addSelectionChangedListener
(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
//
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage =
new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
Domainmetamodelm2mEditor.this.setSelectionToViewer(selection);
Domainmetamodelm2mEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
propertySheetPages.add(propertySheetPage);
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other views.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection)selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
//
Object selectedElement = selectedElements.next();
// If it's the selection viewer, then we want it to select the same selection as this selection.
//
if (currentViewerPane.getViewer() == selectionViewer) {
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
//
selectionViewer.setSelection(new StructuredSelection(selectionList));
}
else {
// Set the input to the widget.
//
if (currentViewerPane.getViewer().getInput() != selectedElement) {
currentViewerPane.getViewer().setInput(selectedElement);
currentViewerPane.setTitle(selectedElement);
}
}
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command stack.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack)editingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running activity that modifies the workbench.
//
WorkspaceModifyOperation operation =
new WorkspaceModifyOperation() {
// This is the method that gets invoked when the operation runs.
//
@Override
public void execute(IProgressMonitor monitor) {
// Save the resources to the file system.
//
boolean first = true;
for (Resource resource : editingDomain.getResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource)) && !editingDomain.isReadOnly(resource)) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
}
catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
//
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
//
((BasicCommandStack)editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
}
catch (Exception exception) {
// Something went wrong that shouldn't.
//
DomainMetamodelM2MEditorPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the specified resource.
* The implementation uses the URI converter from the editor's resource set to try to open an input stream.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
}
catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void doSaveAs() {
SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell());
saveAsDialog.open();
IPath path = saveAsDialog.getResult();
if (path != null) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
if (file != null) {
doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file));
}
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor =
getActionBars().getStatusLineManager() != null ?
getActionBars().getStatusLineManager().getProgressMonitor() :
new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void gotoMarker(IMarker marker) {
List<?> targetObjects = markerHelper.getTargetObjects(editingDomain, marker);
if (!targetObjects.isEmpty()) {
setSelectionToViewer(targetObjects);
}
}
/**
* This is called during startup.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setFocus() {
if (currentViewerPane != null) {
currentViewerPane.setFocus();
}
else {
getControl(getActivePage()).setFocus();
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to return this editor's overall selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to set this editor's overall selection.
* Calling this result will notify the listeners.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer ?
contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection)selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
}
else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key) {
return DomainMetamodelM2MEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static String getString(String key, Object s1) {
return DomainMetamodelM2MEditorPlugin.INSTANCE.getString(key, new Object [] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help fill the context menus with contributions from the Edit menu.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener)getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EditingDomainActionBarContributor getActionBarContributor() {
return (EditingDomainActionBarContributor)getEditorSite().getActionBarContributor();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void dispose() {
updateProblemIndication = false;
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener);
getSite().getPage().removePartListener(partListener);
adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (PropertySheetPage propertySheetPage : propertySheetPages) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean showOutlineView() {
return true;
}
}
| lgpl-3.0 |