code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* This file is part of HortonMachine (http://www.hortonmachine.org)
* (C) HydroloGIS - www.hydrologis.com
*
* The HortonMachine 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.hortonmachine.dbs.log;
import java.util.Date;
import org.hortonmachine.dbs.utils.DbsUtilities;
/**
* A message to be used for logging.
*
* @author Andrea Antonello (www.hydrologis.com)
*
*/
public class Message {
public long id;
public long ts = 0;
/**
* One of {@link EMessageType}.
*/
public int type = EMessageType.INFO.getCode();
public String tag = "";
public String msg = "";
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Message [id=");
builder.append(id);
builder.append(", ts=");
builder.append(DbsUtilities.dbDateFormatter.format(new Date(ts)));
builder.append(", type=");
builder.append(EMessageType.fromCode(type).name());
builder.append(", tag=");
builder.append(tag);
builder.append(", msg=");
builder.append(msg);
builder.append("]");
return builder.toString();
}
}
| moovida/jgrasstools | dbs/src/main/java/org/hortonmachine/dbs/log/Message.java | Java | gpl-3.0 | 1,776 |
/*
* Copyright (C) 2015-2017 PÂRIS Quentin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.phoenicis.repository.repositoryTypes;
import org.junit.Test;
import org.phoenicis.repository.dto.CategoryDTO;
import org.phoenicis.repository.dto.RepositoryDTO;
import org.phoenicis.repository.dto.TypeDTO;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class BackgroundRepositoryTest {
private final ExecutorService mockExecutor = mock(ExecutorService.class);
private final Repository mockRepository = mock(Repository.class);
private final BackgroundRepository backgroundRepository = new BackgroundRepository(mockRepository, mockExecutor);
private RepositoryDTO mockResults = new RepositoryDTO.Builder().withTypes(Collections.singletonList(
new TypeDTO.Builder().withId("Type 1")
.withCategories(Arrays.asList(mock(CategoryDTO.class), mock(CategoryDTO.class))).build()))
.build();
@Test
public void testFetchInstallableApplications_taskIsPassed() {
doAnswer(invocation -> {
((Runnable) invocation.getArguments()[0]).run();
return null;
}).when(mockExecutor).submit(any(Runnable.class));
when(mockRepository.fetchInstallableApplications()).thenReturn(mockResults);
backgroundRepository.fetchInstallableApplications(categoryDTOs -> {
}, e -> {
});
verify(mockRepository).fetchInstallableApplications(any(), any());
}
} | Tutul-/POL-POM-5 | phoenicis-repository/src/test/java/org/phoenicis/repository/repositoryTypes/BackgroundRepositoryTest.java | Java | gpl-3.0 | 2,293 |
/*
* Component of GAE Project for TMSCA Contest Automation
* Copyright (C) 2013 Sushain Cherivirala
*
* 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 contestWebsite;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.Password;
import util.Retrieve;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
@SuppressWarnings("serial")
public class CreateAdmin extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity admin = new Entity("user");
admin.setProperty("user-id", "admin");
admin.setProperty("name", "Admin");
admin.setProperty("school", "Admin School");
try {
String salthash = Password.getSaltedHash("password");
admin.setProperty("hash", salthash.split("\\$")[1]);
admin.setProperty("salt", salthash.split("\\$")[0]);
}
catch (Exception e) {
e.printStackTrace();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
return;
}
datastore.put(admin);
Entity contestInfo = Retrieve.contestInfo();
contestInfo = contestInfo != null ? contestInfo : new Entity("contestInfo");
contestInfo.setProperty("testingMode", true);
datastore.put(contestInfo);
}
}
| curryninja123/contestManagement | src/contestWebsite/CreateAdmin.java | Java | gpl-3.0 | 2,143 |
package org.thoughtcrime.securesms.insights;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.RecyclerView;
import com.airbnb.lottie.LottieAnimationView;
import org.thoughtcrime.securesms.NewConversationActivity;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.ArcProgressBar;
import org.thoughtcrime.securesms.components.AvatarImageView;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.util.ThemeUtil;
import java.util.List;
public final class InsightsDashboardDialogFragment extends DialogFragment {
private TextView securePercentage;
private ArcProgressBar progress;
private View progressContainer;
private TextView tagline;
private TextView encryptedMessages;
private TextView title;
private TextView description;
private RecyclerView insecureRecipients;
private TextView locallyGenerated;
private AvatarImageView avatarImageView;
private InsightsInsecureRecipientsAdapter adapter;
private LottieAnimationView lottieAnimationView;
private AnimatorSet animatorSet;
private Button startAConversation;
private Toolbar toolbar;
private InsightsDashboardViewModel viewModel;
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
requireFragmentManager().beginTransaction()
.detach(this)
.attach(this)
.commit();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ThemeUtil.isDarkTheme(requireActivity())) {
setStyle(STYLE_NO_FRAME, R.style.TextSecure_DarkTheme);
} else {
setStyle(STYLE_NO_FRAME, R.style.TextSecure_LightTheme);
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.insights_dashboard, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
securePercentage = view.findViewById(R.id.insights_dashboard_percent_secure);
progress = view.findViewById(R.id.insights_dashboard_progress);
progressContainer = view.findViewById(R.id.insights_dashboard_percent_container);
encryptedMessages = view.findViewById(R.id.insights_dashboard_encrypted_messages);
tagline = view.findViewById(R.id.insights_dashboard_tagline);
title = view.findViewById(R.id.insights_dashboard_make_signal_secure);
description = view.findViewById(R.id.insights_dashboard_invite_your_contacts);
insecureRecipients = view.findViewById(R.id.insights_dashboard_recycler);
locallyGenerated = view.findViewById(R.id.insights_dashboard_this_stat_was_generated_locally);
avatarImageView = view.findViewById(R.id.insights_dashboard_avatar);
startAConversation = view.findViewById(R.id.insights_dashboard_start_a_conversation);
lottieAnimationView = view.findViewById(R.id.insights_dashboard_lottie_animation);
toolbar = view.findViewById(R.id.insights_dashboard_toolbar);
setupStartAConversation();
setDashboardDetailsAlpha(0f);
setNotEnoughDataAlpha(0f);
setupToolbar();
setupRecycler();
initializeViewModel();
}
private void setupStartAConversation() {
startAConversation.setOnClickListener(v -> startActivity(new Intent(requireActivity(), NewConversationActivity.class)));
}
private void setDashboardDetailsAlpha(float alpha) {
tagline.setAlpha(alpha);
title.setAlpha(alpha);
description.setAlpha(alpha);
insecureRecipients.setAlpha(alpha);
locallyGenerated.setAlpha(alpha);
encryptedMessages.setAlpha(alpha);
}
private void setupToolbar() {
toolbar.setNavigationOnClickListener(v -> dismiss());
}
private void setupRecycler() {
adapter = new InsightsInsecureRecipientsAdapter(this::handleInviteRecipient);
insecureRecipients.setAdapter(adapter);
}
private void initializeViewModel() {
final InsightsDashboardViewModel.Repository repository = new InsightsRepository(requireContext());
final InsightsDashboardViewModel.Factory factory = new InsightsDashboardViewModel.Factory(repository);
viewModel = ViewModelProviders.of(this, factory).get(InsightsDashboardViewModel.class);
viewModel.getState().observe(getViewLifecycleOwner(), state -> {
updateInsecurePercent(state.getData());
updateInsecureRecipients(state.getInsecureRecipients());
updateUserAvatar(state.getUserAvatar());
});
}
private void updateInsecurePercent(@Nullable InsightsData insightsData) {
if (insightsData == null) return;
if (insightsData.hasEnoughData()) {
setTitleAndDescriptionText(insightsData.getPercentInsecure());
animateProgress(insightsData.getPercentInsecure());
} else {
setNotEnoughDataText();
animateNotEnoughData();
}
}
private void animateProgress(int insecurePercent) {
startAConversation.setVisibility(View.GONE);
if (animatorSet == null) {
animatorSet = InsightsAnimatorSetFactory.create(insecurePercent,
this::setProgressPercentage,
this::setDashboardDetailsAlpha,
this::setPercentSecureScale,
insecurePercent == 0 ? this::setLottieProgress : null);
if (insecurePercent == 0) {
animatorSet.addListener(new ToolbarBackgroundColorAnimationListener());
}
animatorSet.start();
}
}
private void setProgressPercentage(float percent) {
securePercentage.setText(String.valueOf(Math.round(percent * 100)));
progress.setProgress(percent);
}
private void setPercentSecureScale(float scale) {
progressContainer.setScaleX(scale);
progressContainer.setScaleY(scale);
}
private void setLottieProgress(float progress) {
lottieAnimationView.setProgress(progress);
}
private void setTitleAndDescriptionText(int insecurePercent) {
startAConversation.setVisibility(View.GONE);
progressContainer.setVisibility(View.VISIBLE);
insecureRecipients.setVisibility(View.VISIBLE);
encryptedMessages.setText(R.string.InsightsDashboardFragment__encrypted_messages);
tagline.setText(getString(R.string.InsightsDashboardFragment__signal_protocol_automatically_protected, 100 - insecurePercent, InsightsConstants.PERIOD_IN_DAYS));
if (insecurePercent == 0) {
lottieAnimationView.setVisibility(View.VISIBLE);
title.setVisibility(View.GONE);
description.setVisibility(View.GONE);
} else {
lottieAnimationView.setVisibility(View.GONE);
title.setText(R.string.InsightsDashboardFragment__spread_the_word);
description.setText(R.string.InsightsDashboardFragment__invite_your_contacts);
title.setVisibility(View.VISIBLE);
description.setVisibility(View.VISIBLE);
}
}
private void setNotEnoughDataText() {
startAConversation.setVisibility(View.VISIBLE);
progressContainer.setVisibility(View.INVISIBLE);
insecureRecipients.setVisibility(View.GONE);
encryptedMessages.setText(R.string.InsightsDashboardFragment__not_enough_data);
tagline.setText(getString(R.string.InsightsDashboardFragment__your_insights_percentage_is_calculated_based_on, InsightsConstants.PERIOD_IN_DAYS));
}
private void animateNotEnoughData() {
if (animatorSet == null) {
animatorSet = InsightsAnimatorSetFactory.create(0, null, this::setNotEnoughDataAlpha, null, null);
animatorSet.start();
}
}
private void setNotEnoughDataAlpha(float alpha) {
encryptedMessages.setAlpha(alpha);
tagline.setAlpha(alpha);
startAConversation.setAlpha(alpha);
}
private void updateInsecureRecipients(@NonNull List<Recipient> recipients) {
adapter.updateData(recipients);
}
private void updateUserAvatar(@Nullable InsightsUserAvatar userAvatar) {
if (userAvatar == null) avatarImageView.setImageDrawable(null);
else userAvatar.load(avatarImageView);
}
private void handleInviteRecipient(final @NonNull Recipient recipient) {
new AlertDialog.Builder(requireContext())
.setTitle(getResources().getQuantityString(R.plurals.InviteActivity_send_sms_invites, 1, 1))
.setMessage(getString(R.string.InviteActivity_lets_switch_to_signal, getString(R.string.install_url)))
.setPositiveButton(R.string.InsightsDashboardFragment__send, (dialog, which) -> viewModel.sendSmsInvite(recipient))
.setNegativeButton(R.string.InsightsDashboardFragment__cancel, (dialog, which) -> dialog.dismiss())
.show();
}
@Override
public void onDestroyView() {
if (animatorSet != null) {
animatorSet.cancel();
animatorSet = null;
}
super.onDestroyView();
}
private final class ToolbarBackgroundColorAnimationListener implements Animator.AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
toolbar.setBackgroundResource(R.color.transparent);
}
@Override
public void onAnimationEnd(Animator animation) {
toolbar.setBackgroundColor(ThemeUtil.getThemedColor(requireContext(), android.R.attr.windowBackground));
}
@Override
public void onAnimationCancel(Animator animation) {
toolbar.setBackgroundColor(ThemeUtil.getThemedColor(requireContext(), android.R.attr.windowBackground));
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
}
| AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/insights/InsightsDashboardDialogFragment.java | Java | gpl-3.0 | 10,722 |
package org.openmastery.publisher.api;
import org.openmastery.publisher.api.activity.RandomNewEditorActivityBuilder;
import org.openmastery.publisher.api.batch.RandomNewBatchEventBuilder;
import org.openmastery.publisher.api.batch.RandomNewIFMBatchBuilder;
import org.openmastery.publisher.api.event.RandomEventBuilder;
import org.openmastery.publisher.api.ideaflow.RandomIdeaFlowBandBuilder;
import org.openmastery.publisher.api.task.RandomNewTaskBuilder;
public class RandomApiBuilderSupport {
public RandomNewTaskBuilder newTask() {
return new RandomNewTaskBuilder();
}
public RandomNewEditorActivityBuilder newEditorActivity() {
return new RandomNewEditorActivityBuilder();
}
public RandomNewBatchEventBuilder newBatchEvent() {
return new RandomNewBatchEventBuilder();
}
public RandomNewIFMBatchBuilder batch() {
return new RandomNewIFMBatchBuilder();
}
public RandomEventBuilder event() { return new RandomEventBuilder(); }
public RandomIdeaFlowBandBuilder ideaFlowBand() { return new RandomIdeaFlowBandBuilder(); }
}
| openmastery/ifm-publisher | src/mainTest/groovy/org/openmastery/publisher/api/RandomApiBuilderSupport.java | Java | gpl-3.0 | 1,050 |
/*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt 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.
*/
package org.fourthline.cling.support.model.dlna.message.header;
import org.fourthline.cling.model.message.header.InvalidHeaderException;
import org.fourthline.cling.support.model.dlna.types.BufferInfoType;
/**
* @author Mario Franco
*/
public class BufferInfoHeader extends DLNAHeader<BufferInfoType> {
public BufferInfoHeader() {
}
@Override
public void setString(String s) throws InvalidHeaderException {
if (s.length() != 0) {
try {
setValue(BufferInfoType.valueOf(s));
return;
} catch (Exception ex) {}
}
throw new InvalidHeaderException("Invalid BufferInfo header value: " + s);
}
@Override
public String getString() {
return getValue().getString();
}
}
| offbye/DroidDLNA | app/src/main/java/org/fourthline/cling/support/model/dlna/message/header/BufferInfoHeader.java | Java | gpl-3.0 | 1,395 |
package com.csy.rebate.domain.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class RebateDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private Integer userId;
private String userCode;
private String userName;
private Integer earningsFrom;
private Integer missionId;
private String missionName;
private Double amount;
private BigDecimal earnings;
private Byte status;
private String statusCn;
private Date createTm;
private String createDate;
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
private String creator;
private Date modifyTm;
private String modifior;
private Date settleTm;
private String settleMan;
private Byte type;
private String typeCn;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getEarningsFrom() {
return earningsFrom;
}
public void setEarningsFrom(Integer earningsFrom) {
this.earningsFrom = earningsFrom;
}
public String getStatusCn() {
return statusCn;
}
public void setStatusCn(String statusCn) {
this.statusCn = statusCn;
}
public Integer getMissionId() {
return missionId;
}
public void setMissionId(Integer missionId) {
this.missionId = missionId;
}
public String getMissionName() {
return missionName;
}
public void setMissionName(String missionName) {
this.missionName = missionName;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public BigDecimal getEarnings() {
return earnings;
}
public void setEarnings(BigDecimal earnings) {
this.earnings = earnings;
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
public Date getCreateTm() {
return createTm;
}
public void setCreateTm(Date createTm) {
this.createTm = createTm;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getModifyTm() {
return modifyTm;
}
public void setModifyTm(Date modifyTm) {
this.modifyTm = modifyTm;
}
public String getModifior() {
return modifior;
}
public void setModifior(String modifior) {
this.modifior = modifior;
}
public Date getSettleTm() {
return settleTm;
}
public void setSettleTm(Date settleTm) {
this.settleTm = settleTm;
}
public String getSettleMan() {
return settleMan;
}
public void setSettleMan(String settleMan) {
this.settleMan = settleMan;
}
public Byte getType() {
return type;
}
public void setType(Byte type) {
this.type = type;
}
public String getTypeCn() {
return typeCn;
}
public void setTypeCn(String typeCn) {
this.typeCn = typeCn;
}
}
| csycurry/cloud.group | cloud.group.websys/src/main/java/com/csy/rebate/domain/dto/RebateDTO.java | Java | gpl-3.0 | 3,347 |
/*
* Fenix Framework, a framework to develop Java Enterprise Applications.
*
* Copyright (C) 2013 Fenix Framework Team and/or its affiliates and other contributors as indicated by the @author tags.
*
* This file is part of the Fenix Framework. Read the file COPYRIGHT.TXT for more copyright and licensing information.
*/
package pt.ist.fenixframework.backend.jvstm.datagrid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pt.ist.fenixframework.FenixFramework;
import pt.ist.fenixframework.backend.jvstm.cluster.JvstmClusterBackEnd;
import pt.ist.fenixframework.backend.jvstm.pstm.OwnedVBox;
import pt.ist.fenixframework.backend.jvstm.pstm.StandaloneVBox;
import pt.ist.fenixframework.backend.jvstm.pstm.VBox;
import pt.ist.fenixframework.backend.jvstm.pstm.VBoxCache;
public class JvstmDataGridBackEnd extends JvstmClusterBackEnd {
private static final Logger logger = LoggerFactory.getLogger(JvstmDataGridBackEnd.class);
public static final String BACKEND_NAME = "jvstm-datagrid";
JvstmDataGridBackEnd() {
super(new DataGridRepository());
}
public static JvstmDataGridBackEnd getInstance() {
return (JvstmDataGridBackEnd) FenixFramework.getConfig().getBackEnd();
}
@Override
public String getName() {
return BACKEND_NAME;
}
@Override
public VBox lookupCachedVBox(String vboxId) {
VBox vbox = StandaloneVBox.lookupCachedVBox(vboxId);
if (vbox != null) {
return vbox;
}
// It may be an owned VBox
return OwnedVBox.lookupCachedVBox(vboxId);
}
public VBox vboxFromId(String vboxId) {
logger.debug("vboxFromId({})", vboxId);
VBox vbox = lookupCachedVBox(vboxId);
if (vbox == null) {
if (logger.isDebugEnabled()) {
logger.debug("VBox not found after lookup: {}", vboxId);
}
/* we assume that well-written programs write to data grid entries
before reading from them. As such, when a VBox is not cached, we
simply allocate it. This is especially relevant for StandaloneVBoxes
as OwnedVBoxes are correctly created before being accessed. */
// vbox = StandaloneVBox.makeNew(vboxId, true);
vbox = allocateVBox(vboxId);
}
return vbox;
}
private static VBox allocateVBox(String vboxId) {
// try an owned vbox first in case the id is valid.
VBox vbox = OwnedVBox.fromId(vboxId);
if (vbox == null) {
// make a standalone one
logger.debug("Allocating a StandaloneVBox for id {}", vboxId);
vbox = StandaloneVBox.makeNew(vboxId, true);
// cache vbox and return the canonical vbox
vbox = VBoxCache.getCache().cache((StandaloneVBox) vbox);
}
return vbox;
}
}
| jcarvalho/fenix-framework | backend/jvstm-datagrid/runtime/src/main/java/pt/ist/fenixframework/backend/jvstm/datagrid/JvstmDataGridBackEnd.java | Java | gpl-3.0 | 2,875 |
package pku.cbi.abcgrid.worker;
/**
* ######################################################
* # Ying Sun #
* # Center for Bioinformatics, Peking University. #
* # [email protected] #
* # Copyright 2006 #
* ######################################################
*/
import java.util.Map;
/**
* Result of a task MAY consist of some output files,
* and/or a standard output message and/or a standard error message.
*
*/
public final class Result
{
long job_id;
long task_id;
//fileName: fileData
Map<String,byte[]> output;
String command;
byte[] stdout;
byte[] stderr;
public Result(long jid,long tid,String[] cmd,
Map<String,byte[]> out,
byte[] sout,byte[] serr)
{
job_id = jid;
task_id = tid;
command = Util.join(cmd," ");
output = out;
stdout = sout;
stderr = serr;
}
public long getJobId()
{
return job_id;
}
public long getTaskId()
{
return task_id;
}
public Map<String,byte[]> getData()
{
return output;
}
public String getCommand()
{
return command;
}
public byte[] getStdout()
{
return stdout;
}
public byte[] getStderr()
{
return stderr;
}
}
| home9464/ABCGrid | worker/src/pku/cbi/abcgrid/worker/Result.java | Java | gpl-3.0 | 1,485 |
package ca.pfv.spmf.algorithms.frequentpatterns.upgrowth_ihup;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is an implementation of the UPGrowthPlus algorithm.<\br><\br>
*
* Copyright (c) 2015 Prashant Barhate <\br><\br>
*
* The UP-GrowthPlus algorithm was proposed in this paper: <\br><\br>
*
* V. S. Tseng, B.-E. Shie, C.-W. Wu, and P. S. Yu. Efficient algorithms for mining high
* utility itemsets from transactional databases.
* IEEE Transactions on Knowledge and Data Engineering, 2012, doi: 10.1109/TKDE.2012.59.<\br><\br>
*
* This file is part of the SPMF DATA MINING SOFTWARE *
* (http://www.philippe-fournier-viger.com/spmf). <\br><\br>
*
* SPMF 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. SPMF 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. <\br><\br>
*
* You should have received a copy of the GNU General Public License along with SPMF.
* If not, see <http://www.gnu.org/licenses/>. <\br><\br>
*
* @author Prashant Barhate
*/
public class AlgoUPGrowthPlus {
// variable for statistics
private double maxMemory = 0; // the maximum memory usage
private long startTimestamp = 0; // the time the algorithm started
private long endTimestamp = 0; // the time the algorithm terminated
private int huiCount = 0; // the number of HUIs generated
private int phuisCount; // the number of PHUIs generated
// map for minimum node utility during DLU(Decreasing Local Unpromizing
// items) strategy
private Map<Integer, Integer> mapMinimumItemUtility;
// writer to write the output file
private BufferedWriter writer = null;
// Structure to store the potential HUIs
private List<Itemset> phuis = new ArrayList<Itemset>();
// To activate debug mode
private final boolean DEBUG = false;
/**
* Method to run the algorithm
*
* @param input path to an input file
* @param output path for writing the output file
* @param minUtility the minimum utility threshold
* @throws IOException exception if error while reading or writing the file
*/
public void runAlgorithm(String input, String output, int minUtility)
throws IOException {
maxMemory = 0;
startTimestamp = System.currentTimeMillis();
writer = new BufferedWriter(new FileWriter(output));
// We create a map to store the TWU of each item
final Map<Integer, Integer> mapItemToTWU = new HashMap<Integer, Integer>();
// ******************************************
// First database scan to calculate the TWU of each item.
BufferedReader myInput = null;
String thisLine;
try {
// prepare the object for reading the file
myInput = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(input))));
// for each line (transaction) until the end of file
while ((thisLine = myInput.readLine()) != null) {
// if the line is a comment, is empty or is a kind of metadata
if (thisLine.isEmpty() == true || thisLine.charAt(0) == '#'
|| thisLine.charAt(0) == '%' || thisLine.charAt(0) == '@') {
continue;
}
// split the transaction according to the : separator
String split[] = thisLine.split(":");
// the first part is the list of items
String items[] = split[0].split(" ");
// the second part is the transaction utility
int transactionUtility = Integer.parseInt(split[1]);
// for each item, we add the transaction utility to its TWU
for (int i = 0; i < items.length; i++) {
// convert item to integer
Integer item = Integer.parseInt(items[i]);
// get the current TWU of that item
Integer twu = mapItemToTWU.get(item);
// add the utility of the item in the current transaction to its twu
twu = (twu == null) ? transactionUtility : twu + transactionUtility;
mapItemToTWU.put(item, twu);
}
}
} catch (Exception e) {
// catches exception if error while reading the input file
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
// ******************************************
// second database scan generate revised transaction and global UP-Tree
// and calculate the minimum utility of each item
// (required by the DLU(Decreasing Local Unpromizing items) strategy)
mapMinimumItemUtility = new HashMap<Integer, Integer>();
try {
UPTreePlus tree = new UPTreePlus();
// prepare the object for reading the file
myInput = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(input))));
// Transaction ID to track transactions
// for each line (transaction) until the end of file
while ((thisLine = myInput.readLine()) != null) {
// if the line is a comment, is empty or is a kind of metadata
if (thisLine.isEmpty() == true || thisLine.charAt(0) == '#'
|| thisLine.charAt(0) == '%' || thisLine.charAt(0) == '@') {
continue;
}
// split the line according to the separator
String split[] = thisLine.split(":");
// get the list of items
String items[] = split[0].split(" ");
// get the list of utility values corresponding to each item
// for that transaction
String utilityValues[] = split[2].split(" ");
int remainingUtility = 0;
// Create a list to store items
List<Item> revisedTransaction = new ArrayList<Item>();
// for each item
for (int i = 0; i < items.length; i++) {
// convert values to integers
int itm = Integer.parseInt(items[i]);
int utility = Integer.parseInt(utilityValues[i]);
if (mapItemToTWU.get(itm) >= minUtility) {
Item element = new Item(itm, utility);
// add it
revisedTransaction.add(element);
remainingUtility += utility;
// get the current Minimum Item Utility of that item
Integer minItemUtil = mapMinimumItemUtility.get(itm);
// Minimum Item Utility is utility of Transaction T if there
// does not exist Transaction T' such that utility(T')<
// utility(T)
if ((minItemUtil == null) || (minItemUtil >= utility)) {
mapMinimumItemUtility.put(itm, utility);
}
// prepare object for garbage collection
element = null;
}
}
// revised transaction in desceding order of TWU
Collections.sort(revisedTransaction, new Comparator<Item>() {
public int compare(Item o1, Item o2) {
return compareItemsDesc(o1.name, o2.name, mapItemToTWU);
}
});
// add transaction to the global UP-Tree
tree.addTransaction(revisedTransaction, remainingUtility);
}
// We create the header table for the global UP-Tree
tree.createHeaderList(mapItemToTWU);
// check the memory usage
checkMemory();
if(DEBUG) {
System.out.println("GLOBAL TREE" + "\nmapITEM-TWU : " +mapItemToTWU +
"\nmapITEM-MINUTIL : " +mapMinimumItemUtility + "\n" + tree.toString());
}
// Mine tree with UPGrowthPlus with 2 strategies DLU and DLN
upgrowthPlus(tree, minUtility, new int[0]);
// check the memory usage again and close the file.
checkMemory();
} catch (Exception e) {
// catches exception if error while reading the input file
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
// save the number of candidate found
phuisCount = phuis.size();
// ******************************************
// Third database scan to calculate the
// exact utility of each PHUIs and output those that are HUIS.
// First sort the PHUIs by size for optimization
Collections.sort(phuis, new Comparator<Itemset>() {
public int compare(Itemset arg0, Itemset arg1) {
return arg0.size() - arg1.size();
}}
);
try {
// prepare the object for reading the file
myInput = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(input))));
// for each line (transaction) until the end of file
while ((thisLine = myInput.readLine()) != null) {
// if the line is a comment, is empty or is a kind of metadata
if (thisLine.isEmpty() == true || thisLine.charAt(0) == '#'
|| thisLine.charAt(0) == '%' || thisLine.charAt(0) == '@') {
continue;
}
// split the line according to the separator
String split[] = thisLine.split(":");
// get the list of items
String items[] = split[0].split(" ");
// get the list of utility values corresponding to each item
// for that transaction
String utilityValues[] = split[2].split(" ");
// Create a list to store items
List<Item> revisedTransaction = new ArrayList<Item>();
// for each item
for (int i = 0; i < items.length; i++) {
// / convert values to integers
int item = Integer.parseInt(items[i]);
int utility = Integer.parseInt(utilityValues[i]);
Item element = new Item(item, utility);
if (mapItemToTWU.get(item) >= minUtility) {
revisedTransaction.add(element);
}
}
// sort the transaction by lexical order
// for faster comparison since PHUIs have been sorted
// by lexical order and this will make faster
// comparison
Collections.sort(revisedTransaction, new Comparator<Item>() {
public int compare(Item o1, Item o2) {
return o1.name - o2.name;
}});
// Compare each itemset with the transaction
for(Itemset itemset : phuis){
// OPTIMIZATION:
// if this itemset is larger than the current transaction
// it cannot be included in the transaction, so we stop
// and we don't need to consider the folowing itemsets
// either since they are ordered by increasing size.
if(itemset.size() > revisedTransaction.size()) {
break;
}
// Now check if itemset is included in the transaction
// and if yes, update its utility
updateExactUtility(revisedTransaction, itemset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// OUTPUT ALL HUIs
for(Itemset itemset : phuis) {
if(itemset.getExactUtility() >= minUtility) {
writeOut(itemset);
}
}
// check the memory usage again
checkMemory();
// record end time
endTimestamp = System.currentTimeMillis();
// Release some memory
phuis.clear();
mapMinimumItemUtility = null;
// CLOSE OUTPUT FILE
writer.close();
}
/**
* Compare two items according to the ascending order of TWU.
* @param item1 the first item
* @param item2 the second item
* @param mapItemEstimatedUtility the map indicating the TWU of each item
* @return -1 if item1 is smaller than 2. 1 if item 1 is greater than 2. Otherwise 0.
*/
private int compareItemsDesc(int item1, int item2, Map<Integer, Integer> mapItemEstimatedUtility) {
int compare = mapItemEstimatedUtility.get(item2) - mapItemEstimatedUtility.get(item1);
// if the same, use the lexical order otherwise use the TWU
return (compare == 0) ? item1 - item2 : compare;
}
/**
* Mine UP Tree recursively
*
* @param tree UPTree to mine
* @param minUtility minimum utility threshold
* @param prefix the prefix itemset
*/
private void upgrowthPlus(UPTreePlus tree, int minUtility, int[] prefix) throws IOException {
// For each item in the header table list of the tree in reverse order.
for (int i = tree.headerList.size() - 1; i >= 0; i--) {
// get the item
Integer item = tree.headerList.get(i);
// ===== CREATE THE LOCAL TREE =====
UPTreePlus localTree = createLocalTree(minUtility, tree, item);
// NEXT LINE IS FOR DEBUGING:
if(DEBUG) {
System.out.println("LOCAL TREE for projection by:" + ((prefix== null)?"": Arrays.toString(prefix)+ ",") + item +
"\n" + localTree.toString());
}
// ===== CALCULATE SUM OF ITEM NODE UTILITY =====
// take node from bottom of header table
UPNodePlus pathCPB = tree.mapItemNodes.get(item);
// take item
// int itemCPB = pathCPB.itemID;
int pathCPBUtility = 0;
while (pathCPB != null) {
// sum of items node utility
pathCPBUtility += pathCPB.nodeUtility;
pathCPB = pathCPB.nodeLink;
}
// if path utility of 'item' in header table is greater than
// minUtility
// then 'item' is a PHUI (Potential high utility itemset)
if (pathCPBUtility >= minUtility) {
// Create the itemset by appending the item to the current prefix
// This gives us a PHUI
int[] newPrefix = new int[prefix.length+1];
System.arraycopy(prefix, 0, newPrefix, 0, prefix.length);
newPrefix[prefix.length] = item;
// Save the PHUI
savePHUI(newPrefix);
// Make a recursive call to the UPGrowthPlus procedure to explore
// other itemsets that are extensions of the current PHUI
if(localTree.headerList.size() >0) {
upgrowthPlus(localTree, minUtility, newPrefix);
}
}
}
}
private UPTreePlus createLocalTree(int minUtility, UPTreePlus tree, Integer item) {
// === Construct conditional pattern base ===
// It is a subdatabase which consists of the set of prefix paths
List<List<UPNodePlus>> prefixPaths = new ArrayList<List<UPNodePlus>>();
UPNodePlus path = tree.mapItemNodes.get(item);
// map to store path utility of local items in CPB
final Map<Integer, Integer> itemPathUtility = new HashMap<Integer, Integer>();
while (path != null) {
// get the Node Utiliy of the item
int nodeutility = path.nodeUtility;
// if the path is not just the root node
if (path.parent.itemID != -1) {
// create the prefixpath
List<UPNodePlus> prefixPath = new ArrayList<UPNodePlus>();
// add this node.
prefixPath.add(path); // NOTE: we add it just to keep its // utility,
// actually it should not be part of the prefixPath
// Recursively add all the parents of this node.
UPNodePlus parentnode = path.parent;
while (parentnode.itemID != -1) {
prefixPath.add(parentnode);
// pu - path utility
Integer pu = itemPathUtility.get(parentnode.itemID);
pu = (pu == null) ? nodeutility : pu + nodeutility;
itemPathUtility.put(parentnode.itemID, pu);
parentnode = parentnode.parent;
}
// add the path to the list of prefixpaths
prefixPaths.add(prefixPath);
}
// We will look for the next prefixpath
path = path.nodeLink;
}
if(DEBUG) {
System.out.println("\n\n\nPREFIXPATHS:");
for (List<UPNodePlus> prefixPath : prefixPaths) {
for(UPNodePlus node : prefixPath) {
System.out.println(" " +node);
}
System.out.println(" --");
}
}
// Calculate the Utility of each item in the prefixpath
UPTreePlus localTree = new UPTreePlus();
Map<Integer,Integer> mapMiniNodeUtility = new HashMap<Integer,Integer>();
// ======= Calculate the minimum utility of each item =====
// for each prefixpath
for (List<UPNodePlus> prefixPath : prefixPaths) {
// for each node in the prefixpath, except the first one
for (int j = 1; j < prefixPath.size(); j++) {
UPNodePlus node = prefixPath.get(j);
// Here is DLU Strategy #################
// we check whether local item is promising or not
if (itemPathUtility.get(node.itemID) >= minUtility) {
Integer util = mapMiniNodeUtility.get(node.itemID);
if(util == null) {
mapMiniNodeUtility.put(node.itemID, node.minimalNodeUtility); // MOVED BY PHILIPPE
}else if(node.minimalNodeUtility < util) {
mapMiniNodeUtility.put(node.itemID, node.minimalNodeUtility);
}
}
}
}
// ====== End of minimum utility calculation =====
// for each prefixpath
for (List<UPNodePlus> prefixPath : prefixPaths) {
// the Utility of the prefixpath is the node utility of its
// first node.
int pathCount = prefixPath.get(0).count;
int pathUtility = prefixPath.get(0).nodeUtility;
List<Integer> localPath = new ArrayList<Integer>();
// for each node in the prefixpath,
// except the first one, we count the frequency
for (int j = 1; j < prefixPath.size(); j++) {
int itemValue = 0; // It store multiplication of minimum
// item utility and pathcount
// for each node in prefixpath
UPNodePlus node = prefixPath.get(j);
// Here is DLU Strategy #################
// we check whether local item is promising or not
if (itemPathUtility.get(node.itemID) >= minUtility) {
localPath.add(node.itemID);
} else { // If item is unpromising then we recalculate path
// utillity
// Here we requre to calculate path utility by
// subctracting minimal node utility of unpromising item
itemValue = node.minimalNodeUtility * pathCount;
}
pathUtility = pathUtility - itemValue;
}
if(DEBUG) {
System.out.println(" path utility after DGU,DGN,DLU: " + pathUtility);
}
// we reorganize local path in decending order of path utility
Collections.sort(localPath, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
// compare the TWU of the items
return compareItemsDesc(o1, o2, itemPathUtility);
}
});
// create tree for conditional pattern base
localTree.addLocalTransaction(localPath, pathUtility, mapMiniNodeUtility, pathCount);
}
// We create the local header table for the tree item - CPB
localTree.createHeaderList(itemPathUtility);
return localTree;
}
/**
* Save a PHUI in the list of PHUIs
* @param itemset the itemset
*/
private void savePHUI(int[] itemset) {
// Create an itemset object and store it in the list of pHUIS
Itemset itemsetObj = new Itemset(itemset);
// Sort the itemset by lexical order to faster calculate its
// exact utility later on.
Arrays.sort(itemset);
// add the itemset to the list of PHUIs
phuis.add(itemsetObj);
}
/**
* Update the exact utility of an itemset given a transaction
* It assumes that itemsets are sorted according to the lexical order.
* @param itemset1 the first itemset
* @param itemset2 the second itemset
* @return true if the first itemset contains the second itemset
*/
public void updateExactUtility(List<Item> transaction, Itemset itemset){
int utility = 0;
// for each item in the itemset
loop1: for(int i =0; i < itemset.size(); i++){
Integer itemI = itemset.get(i);
// for each item in the transaction
for(int j =0; j < transaction.size(); j++){
Item itemJ = transaction.get(j);
// if the current item in transaction is equal to the one in itemset
// search for the next one in itemset1
if(itemJ.name == itemI){
utility += transaction.get(j).utility;
continue loop1;
}
// if the current item in itemset1 is larger
// than the current item in itemset2, then
// stop because of the lexical order.
else if(itemJ.name > itemI){
return;
}
}
// means that an item was not found
return;
}
// if all items were found, increase utility.
itemset.increaseUtility(utility);
}
/**
* Write a HUI to the output file
* @param HUI
* @param utility
* @throws IOException
*/
private void writeOut(Itemset HUI) throws IOException {
huiCount++; // increase the number of high utility itemsets found
//Create a string buffer
StringBuilder buffer = new StringBuilder();
//Append each item
for (int i = 0; i < HUI.size(); i++) {
buffer.append(HUI.get(i));
buffer.append(' ');
}
buffer.append("#UTIL: ");
buffer.append(HUI.getExactUtility());
// write to file
writer.write(buffer.toString());
writer.newLine();
}
/**
* Method to check the memory usage and keep the maximum memory usage.
*/
private void checkMemory() {
// get the current memory usage
double currentMemory = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024d / 1024d;
// if higher than the maximum until now replace the maximum with the current memory usage
if (currentMemory > maxMemory) {
maxMemory = currentMemory;
}
}
/**
* Print statistics about the latest execution to System.out.
*/
public void printStats() {
System.out.println("============= UP-GROWTH+ ALGORITHM v96r17 - STATS =============");
System.out.println(" PHUIs (candidates) count: " + phuisCount);
System.out.println(" Total time ~ " + (endTimestamp - startTimestamp) + " ms");
System.out.println(" Memory ~ " + maxMemory + " MB");
System.out.println(" HUIs count : " + huiCount);
System.out.println("===================================================");
}
} | qualitified/qualitified-crm | qualitified-crm-core/src/main/java/ca/pfv/spmf/algorithms/frequentpatterns/upgrowth_ihup/AlgoUPGrowthPlus.java | Java | gpl-3.0 | 21,582 |
@javax.xml.bind.annotation.XmlSchema(namespace = "http://query.ws.draws.opap.gr/")
package gr.opap.draws.ws.query;
| kouzant/OpapDraws | src/main/java/gr/opap/draws/ws/query/package-info.java | Java | gpl-3.0 | 115 |
/*
* Copyright (C) 2013-2014, The Max Planck Institute for
* Psycholinguistics.
*
* 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, version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* A copy of the GNU General Public License is included in the file
* LICENSE. If that file is missing, see
* <http://www.gnu.org/licenses/>.
*/
package nl.mpi.mdmapper;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import javax.xml.namespace.NamespaceContext;
import javax.xml.XMLConstants;
/**
* An implementation of an XML namespace context.
*
* @author Lari Lampen (MPI-PL)
*/
public class NSContext implements NamespaceContext {
private static final Logger logger = Logger.getLogger(NSContext.class);
/**
* URIs indexed by prefix.
*/
private Map<String, String> pref2ns;
/**
* Prefixes indexed by URI. (Note that multiple prefixes can be bound to
* the same URI, but a prefix is only bound to a single URI at a time.
*/
private Map<String, List<String>> ns2pref;
/**
* Create a new namespace context (with no bindings).
*/
public NSContext() {
pref2ns = new HashMap<>();
ns2pref = new HashMap<>();
}
/**
* Add a new namespace binding.
*
* @param prefix namespace prefix
* @param ns namespace address
*/
public void add(String prefix, String ns) {
pref2ns.put(prefix, ns);
List<String> prefixes;
if (ns2pref.containsKey(ns)) {
prefixes = ns2pref.get(ns);
} else {
prefixes = new ArrayList<>();
ns2pref.put(ns, prefixes);
}
prefixes.add(prefix);
}
/**
* Look up namespace URI based on prefix. Some of the return
* values are fixed by the XML standard.
*/
@Override
public String getNamespaceURI(String prefix) {
if (prefix == null)
throw new IllegalArgumentException("Illegal check of null namespace prefix");
if (pref2ns.containsKey(prefix))
return pref2ns.get(prefix);
if (prefix.equals(XMLConstants.XML_NS_PREFIX))
return XMLConstants.XML_NS_URI;
if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE))
return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
return "";
}
/**
* Look up prefix based on namespace URI. Some of the return
* values are fixed by the XML standard.
*
* @param uri namespace URI
*/
@Override
public String getPrefix(String uri) {
if (uri == null)
throw new IllegalArgumentException("Illegal check of null namespace URI");
if (ns2pref.containsKey(uri))
return ns2pref.get(uri).get(0);
if (uri.equals(XMLConstants.XML_NS_URI))
return XMLConstants.XML_NS_PREFIX;
if (uri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))
return XMLConstants.XMLNS_ATTRIBUTE;
return null;
}
/**
* Get list of prefixes bound to a namespace URI. Some of the return values
* are fixed by the XML standard.
*
* @param uri namespace URI
*/
@Override
public Iterator getPrefixes(String uri) {
if (uri == null)
throw new IllegalArgumentException("Illegal check of null namespace URI");
if (ns2pref.containsKey(uri))
return ns2pref.get(uri).iterator();
if (uri.equals(XMLConstants.XML_NS_URI)) {
List<String> dummy = new ArrayList<>(1);
dummy.add(XMLConstants.XML_NS_PREFIX);
return dummy.iterator();
}
if (uri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
List<String> dummy = new ArrayList<>(1);
dummy.add(XMLConstants.XMLNS_ATTRIBUTE);
return dummy.iterator();
}
return Collections.emptyIterator();
}
}
| DASISH/md-mapper | src/main/java/nl/mpi/mdmapper/NSContext.java | Java | gpl-3.0 | 4,033 |
package main.java.views;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import main.java.models.BeatModel;
import main.java.models.BeatModelInterface;
import main.java.models.HeartAdapter;
import main.java.models.HeartModel;
import main.java.models.MP3Adapter;
import main.java.models.MP3Model;
import main.java.controllers.BeatController;
import main.java.controllers.ControllerInterface;
import main.java.controllers.HeartController;
import main.java.controllers.MP3Controller;
public class DJView implements ActionListener, BeatObserver, BPMObserver {
BeatModelInterface model;
ControllerInterface controller;
JFrame viewFrame;
JPanel viewPanel;
BeatBar beatBar;
JLabel bpmOutputLabel;
JFrame controlFrame;
JPanel controlPanel;
JLabel bpmLabel;
JTextField bpmTextField;
JButton setBPMButton;
JButton increaseBPMButton;
JButton decreaseBPMButton;
JMenuBar menuBar;
JMenu menu;
JMenu menuStrategy;
JMenuItem startMenuItem;
JMenuItem stopMenuItem;
JMenuItem djMenuItem;
JMenuItem heartMenuItem;
JMenuItem mp3MenuItem;
public DJView(ControllerInterface controller, BeatModelInterface model) {
this.controller = controller;
this.model = model;
model.registerObserver((BeatObserver)this);
model.registerObserver((BPMObserver)this);
}
public void createView() {
// Create all Swing components here
viewPanel = new JPanel(new GridLayout(1, 2));
viewFrame = new JFrame("View");
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
viewFrame.setSize(new Dimension(100, 80));
bpmOutputLabel = new JLabel("offline", SwingConstants.CENTER);
beatBar = new BeatBar();
beatBar.setValue(0);
JPanel bpmPanel = new JPanel(new GridLayout(2, 1));
bpmPanel.add(beatBar);
bpmPanel.add(bpmOutputLabel);
viewPanel.add(bpmPanel);
viewFrame.getContentPane().add(viewPanel, BorderLayout.CENTER);
viewFrame.pack();
viewFrame.setVisible(true);
}
public void createControls() {
// Create all Swing components here
JFrame.setDefaultLookAndFeelDecorated(true);
controlFrame = new JFrame("Control");
controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlFrame.setSize(new Dimension(100, 80));
controlPanel = new JPanel(new GridLayout(1, 2));
menuBar = new JMenuBar();
menu = new JMenu("DJ Control");
startMenuItem = new JMenuItem("Start");
menu.add(startMenuItem);
startMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
controller.start();
}
});
stopMenuItem = new JMenuItem("Stop");
menu.add(stopMenuItem);
stopMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
controller.stop();
}
});
JMenuItem exit = new JMenuItem("Quit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menu.add(exit);
menuBar.add(menu);
//Barra dropdown con selector de modelo
menuStrategy = new JMenu("Model");
djMenuItem = new JMenuItem("DJ Model");
menuStrategy.add(djMenuItem);
heartMenuItem = new JMenuItem("Heart Model");
menuStrategy.add(heartMenuItem);
mp3MenuItem = new JMenuItem("MP3 Model");
menuStrategy.add(mp3MenuItem);
djMenuItem.addActionListener(this);
heartMenuItem.addActionListener(this);
mp3MenuItem.addActionListener(this);
menuBar.add(menuStrategy);
controlFrame.setJMenuBar(menuBar);
bpmTextField = new JTextField(2);
bpmLabel = new JLabel("Enter BPM:", SwingConstants.RIGHT);
setBPMButton = new JButton("Set");
setBPMButton.setSize(new Dimension(10,40));
increaseBPMButton = new JButton(">>");
decreaseBPMButton = new JButton("<<");
setBPMButton.addActionListener(this);
increaseBPMButton.addActionListener(this);
decreaseBPMButton.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
buttonPanel.add(decreaseBPMButton);
buttonPanel.add(increaseBPMButton);
JPanel enterPanel = new JPanel(new GridLayout(1, 2));
enterPanel.add(bpmLabel);
enterPanel.add(bpmTextField);
JPanel insideControlPanel = new JPanel(new GridLayout(3, 1));
insideControlPanel.add(enterPanel);
insideControlPanel.add(setBPMButton);
insideControlPanel.add(buttonPanel);
controlPanel.add(insideControlPanel);
bpmLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
bpmOutputLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
controlFrame.getRootPane().setDefaultButton(setBPMButton);
controlFrame.getContentPane().add(controlPanel, BorderLayout.CENTER);
controlFrame.pack();
controlFrame.setVisible(true);
}
//Habilitadores y deshabilitadores de los botones en los dropdown menus
public void enableStopMenuItem() {stopMenuItem.setEnabled(true);}
public void disableStopMenuItem() {stopMenuItem.setEnabled(false);}
public void enableStartMenuItem() {startMenuItem.setEnabled(true);}
public void disableStartMenuItem() {startMenuItem.setEnabled(false);}
public void enableDJStartMenuItem(){djMenuItem.setEnabled(true);}
public void disableDJStartMenuItem(){djMenuItem.setEnabled(false);}
public void enableHeartStartMenuItem(){heartMenuItem.setEnabled(true);}
public void disableHeartStartMenuItem(){heartMenuItem.setEnabled(false);}
public void enableMP3StartMenuItem(){mp3MenuItem.setEnabled(true);}
public void disableMP3StartMenuItem(){mp3MenuItem.setEnabled(false);}
//ActionListener que delega al controlador las interacciones con los botones
public void actionPerformed(ActionEvent event) {
if (event.getSource() == setBPMButton) {
int bpm = Integer.parseInt(bpmTextField.getText());
controller.setBPM(bpm);
} else if (event.getSource() == increaseBPMButton) {
controller.increaseBPM();
} else if (event.getSource() == decreaseBPMButton) {
controller.decreaseBPM();
}
// Todos los botones para cambiar de modelo -> Patron Strategy
else{
//Si presiono heartMenuItem cambio al modelo heartmodel
if (event.getSource() == heartMenuItem) {
controller.stop(); //Paro el modelo anterior(Si estaba reproduciendo un mp3 detengo la reproduccion)
model.removeObserver((BPMObserver)this);
model.removeObserver((BeatObserver)this);
setModel(new HeartAdapter(HeartModel.getInstance()));
model.registerObserver((BPMObserver)this);
model.registerObserver((BeatObserver)this);
setController(new HeartController(HeartModel.getInstance(),this));
}
//Si presiono djMenuItem cambio al modelo beatmodel
if (event.getSource() == djMenuItem) {
controller.stop();
model.removeObserver((BPMObserver)this);
model.removeObserver((BeatObserver)this);
setModel(new BeatModel());
model.registerObserver((BPMObserver)this);
model.registerObserver((BeatObserver)this);
setController(new BeatController(model,this));
}
//Si presiono mp3MenuItem cambio al modelo propio
if (event.getSource() == mp3MenuItem) {
controller.stop();
model.removeObserver((BPMObserver)this);
model.removeObserver((BeatObserver)this);
MP3Model mp3model = MP3Model.getInstance();
setModel(new MP3Adapter(mp3model));
model.registerObserver((BPMObserver)this);
model.registerObserver((BeatObserver)this);
setController(new MP3Controller(mp3model,this));
}
//Al final siempre habilito los botones para cambiar de modelo
this.enableDJStartMenuItem();
this.enableHeartStartMenuItem();
this.enableMP3StartMenuItem();
}
}
//Actualiza BPM usando patron observer
public void updateBPM() {
if (model != null) {
int bpm = model.getBPM();
//Reviso que modelo se usa para ver que mostrar en la BeatBar
if (model instanceof MP3Adapter){
bpmOutputLabel.setText("Pista numero " + (bpm+1));
}
else{
if (bpm == 0) {
if (bpmOutputLabel != null) {
bpmOutputLabel.setText("offline");
}
} else {
if (bpmOutputLabel != null) {
if(model instanceof HeartAdapter)
bpmOutputLabel.setText("Numero de intentos: " + bpm);
else
bpmOutputLabel.setText("Current BPM: " + model.getBPM());
}
}
}
}
}
public void updateBeat() {
if (beatBar != null) {
beatBar.setValue(100);
}
}
//Setters de controlador y modelo para implementar patron Strategy
public void setController(ControllerInterface controller) {
this.controller = controller;
}
public void setModel(BeatModelInterface newModel){
this.model = newModel;
}
}
| ggonzalez94/Final_Gestion_Calidad_SW | src/main/java/views/DJView.java | Java | gpl-3.0 | 9,333 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2012. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.buttons;
import edu.wpi.first.wpilibj.command.Command;
/**
* This class provides an easy way to link commands to OI inputs.
*
* It is very easy to link a button to a command. For instance, you could
* link the trigger button of a joystick to a "score" command.
*
* This class represents a subclass of Trigger that is specifically aimed at
* buttons on an operator interface as a common use case of the more generalized
* Trigger objects. This is a simple wrapper around Trigger with the method names
* renamed to fit the Button object use.
*
* @author brad
*/
public abstract class Button extends Trigger {
/**
* Starts the given command whenever the button is newly pressed.
* @param command the command to start
*/
public void whenPressed(final Command command) {
whenActive(command);
}
/**
* Constantly starts the given command while the button is held.
*
* {@link Command#start()} will be called repeatedly while the button is held,
* and will be canceled when the button is released.
*
* @param command the command to start
*/
public void whileHeld(final Command command) {
whileActive(command);
}
/**
* Starts the command when the button is released
* @param command the command to start
*/
public void whenReleased(final Command command) {
whenInactive(command);
}
/**
* Toggles the command whenever the button is pressed (on then off then on)
* @param command the command to start
*/
public void toggleWhenPressed(final Command command) {
toggleWhenActive(command);
}
/**
* Cancel the command when the button is pressed
* @param command the command to start
*/
public void cancelWhenPressed(final Command command) {
cancelWhenActive(command);
}
}
| multiplemonomials/FRC-Test | src/edu/wpi/first/wpilibj/buttons/Button.java | Java | gpl-3.0 | 2,387 |
/**
* Copyright 2010 Roman Kisilenko
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.it_result.ca.scep;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.jscep.CertificateVerificationCallback;
/**
* @author roman
*
*/
public class CaFingerprintCallbackHandler implements CallbackHandler {
private Set<CertificateFingerprint> fingerprints = new HashSet<CertificateFingerprint>();
public CaFingerprintCallbackHandler(CertificateFingerprint fingerprint) {
this.fingerprints.add(fingerprint);
}
public CaFingerprintCallbackHandler(Set<CertificateFingerprint> fingerprints) {
this.fingerprints.addAll(fingerprints);
}
public void addFingerprint(CertificateFingerprint fingerprint) {
fingerprints.add(fingerprint);
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof CertificateVerificationCallback) {
final CertificateVerificationCallback callback = (CertificateVerificationCallback) callbacks[i];
callback.setVerified(false);
for (CertificateFingerprint fingerprint: fingerprints) {
try {
CertificateFingerprint actualFingerprint = CertificateFingerprint.calculate(callback.getCertificate());
if (fingerprint.equals(actualFingerprint)) {
callback.setVerified(true);
break;
}
} catch (Exception e) {
throw new IOException(e);
}
}
}
}
}
}
| RomanKisilenko/ca | src/main/java/me/it_result/ca/scep/CaFingerprintCallbackHandler.java | Java | gpl-3.0 | 2,317 |
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package rtg.api.util;
import javax.annotation.ParametersAreNonnullByDefault;
import mcp.MethodsReturnNonnullByDefault; | srs-bsns/Realistic-Terrain-Generation | src/main/java/rtg/api/util/package-info.java | Java | gpl-3.0 | 182 |
/*
* Copyright (c) 2006 - 2010 LinogistiX GmbH
*
* www.linogistix.com
*
* Project myWMS-LOS
*/
package de.linogistix.common.bobrowser.bo.editor;
import de.linogistix.common.services.J2EEServiceLocator;
import de.linogistix.common.services.J2EEServiceLocatorException;
import de.linogistix.common.util.ExceptionAnnotator;
import java.awt.Component;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.mywms.model.BasicEntity;
import org.openide.NotifyDescriptor;
import org.openide.explorer.propertysheet.PropertyEnv;
import org.openide.util.Lookup;
/**
*
* @author trautm
*/
public class BOEditorChooseFromService extends BOEditorChoose{
public static final String EDITOR_SERVICE_CLASS_KEY = "editorServiceClass";
public static final String EDITOR_SERVICE_METHOD_KEY = "editorServiceMethodname";
public static final String EDITOR_SERVICE_PARAM_KEY = "editorServiceParameters";
Method toInvoke;
Object[] params;
Object service;
@Override
public void attachEnv(PropertyEnv propertyEnv) {
super.attachEnv(propertyEnv);
Class c = (Class)propertyEnv.getFeatureDescriptor().getValue(EDITOR_SERVICE_CLASS_KEY);
String s = (String)propertyEnv.getFeatureDescriptor().getValue(EDITOR_SERVICE_METHOD_KEY);
Object[] p = (Object[])propertyEnv.getFeatureDescriptor().getValue(EDITOR_SERVICE_PARAM_KEY);
this.toInvoke = initInvokeMethod(c,s,p);
}
protected Method initInvokeMethod(Class c, String methodname, Object[] params){
try {
Class[] classes;
J2EEServiceLocator loc = Lookup.getDefault().lookup(J2EEServiceLocator.class);
this.service = loc.getStateless(c);
this.params = params;
if (params != null) {
classes = new Class[params.length];
int i = 0;
for (Object o : params) {
classes[i++] = o.getClass();
}
} else {
classes = new Class[0];
}
return this.service.getClass().getMethod(methodname, classes);
} catch (NoSuchMethodException ex) {
ExceptionAnnotator.annotate(ex);
} catch (SecurityException ex) {
ExceptionAnnotator.annotate(ex);
} catch (J2EEServiceLocatorException ex) {
ExceptionAnnotator.annotate(ex);
}
return null;
}
@Override
public Component getCustomEditor() {
NotifyDescriptor d;
try {
if (getTypeHint() == null) {
ExceptionAnnotator.annotate(new BOEditorTypeException());
} else {
return new BOEditorChooseFromServicePanel(this);
}
} catch (Throwable ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return null;
}
public List invokeService(){
List list;
try{
list = (List)toInvoke.invoke(service, params);
return list;
} catch (Throwable t){
ExceptionAnnotator.annotate(t);
return new ArrayList();
}
}
}
| tedvals/mywms | rich.client/los.clientsuite/LOS Common/src/de/linogistix/common/bobrowser/bo/editor/BOEditorChooseFromService.java | Java | gpl-3.0 | 3,387 |
package com.dotcms.content.elasticsearch.business;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterIndexHealth;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.close.CloseIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.admin.indices.optimize.OptimizeRequest;
import org.elasticsearch.action.admin.indices.optimize.OptimizeResponse;
import org.elasticsearch.action.admin.indices.settings.UpdateSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.UpdateSettingsRequestBuilder;
import org.elasticsearch.action.admin.indices.settings.UpdateSettingsResponse;
import org.elasticsearch.action.admin.indices.status.IndexStatus;
import org.elasticsearch.action.admin.indices.status.IndicesStatusRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData.State;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import com.dotcms.content.elasticsearch.util.ESClient;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.business.DotStateException;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.sitesearch.business.SiteSearchAPI;
import com.dotmarketing.util.Config;
import com.dotmarketing.util.ConfigUtils;
import com.dotmarketing.util.Logger;
import com.dotmarketing.util.UtilMethods;
public class ESIndexAPI {
private final String MAPPING_MARKER = "mapping=";
private final String JSON_RECORD_DELIMITER = "---+||+-+-";
private static final ESMappingAPIImpl mappingAPI = new ESMappingAPIImpl();
private ESClient esclient = new ESClient();
private ESContentletIndexAPI iapi = new ESContentletIndexAPI();
public enum Status { ACTIVE("active"), INACTIVE("inactive"), PROCESSING("processing");
private final String status;
Status(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
};
/**
* returns all indicies and status
* @return
*/
public Map<String,IndexStatus> getIndicesAndStatus() {
Client client=new ESClient().getClient();
return client.admin().indices().status(new IndicesStatusRequest()).actionGet().getIndices();
}
/**
* Writes an index to a backup file
* @param index
* @return
* @throws IOException
*/
public File backupIndex(String index) throws IOException {
return backupIndex(index, null);
}
/**
* writes an index to a backup file
* @param index
* @param toFile
* @return
* @throws IOException
*/
public File backupIndex(String index, File toFile) throws IOException {
boolean indexExists = indexExists(index);
if (!indexExists) {
throw new IOException("Index :" + index + " does not exist");
}
String date = new java.text.SimpleDateFormat("yyyy-MM-dd_hh-mm-ss").format(new Date());
if (toFile == null) {
toFile = new File(ConfigUtils.getBackupPath());
if(!toFile.exists()){
toFile.mkdirs();
}
toFile = new File(ConfigUtils.getBackupPath() + File.separator + index + "_" + date + ".json");
}
Client client = esclient.getClient();
BufferedWriter bw = null;
try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(toFile));
zipOut.setLevel(9);
zipOut.putNextEntry(new ZipEntry(toFile.getName()));
bw = new BufferedWriter(
new OutputStreamWriter(zipOut), 500000); // 500K buffer
final String type=index.startsWith("sitesearch_") ? SiteSearchAPI.ES_SITE_SEARCH_MAPPING : "content";
final String mapping = mappingAPI.getMapping(index, type);
bw.write(MAPPING_MARKER);
bw.write(mapping);
bw.newLine();
// setting up the search for all content
SearchResponse scrollResp = client.prepareSearch(index).setSearchType(SearchType.SCAN).setQuery(QueryBuilders.matchAllQuery())
.setSize(100).setScroll(TimeValue.timeValueMinutes(2)).execute().actionGet();
while (true) {
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(TimeValue.timeValueMinutes(2)).execute()
.actionGet();
boolean hitsRead = false;
for (SearchHit hit : scrollResp.getHits()) {
bw.write(hit.getId());
bw.write(JSON_RECORD_DELIMITER);
bw.write(hit.sourceAsString());
bw.newLine();
hitsRead = true;
}
if (!hitsRead) {
break;
}
}
return toFile;
} catch (Exception e) {
Logger.error(this.getClass(), "Can't export index",e);
throw new IOException(e.getMessage(),e);
} finally {
if (bw != null) {
bw.close();
}
}
}
public boolean optimize(List<String> indexNames) {
try {
IndicesAdminClient iac = new ESClient().getClient().admin().indices();
OptimizeRequest req = new OptimizeRequest(indexNames.toArray(new String[indexNames.size()]));
OptimizeResponse res = iac.optimize(req).get();
Logger.info(this.getClass(), "Optimizing " + indexNames + " :" + res.getSuccessfulShards() + "/" + res.getTotalShards()
+ " shards optimized");
return true;
} catch (Exception e) {
throw new ElasticSearchException(e.getMessage());
}
}
public boolean delete(String indexName) {
if(indexName==null) {
Logger.error(this.getClass(), "Failed to delete a null ES index");
return true;
}
try {
IndicesAdminClient iac = new ESClient().getClient().admin().indices();
DeleteIndexRequest req = new DeleteIndexRequest(indexName);
DeleteIndexResponse res = iac.delete(req).actionGet();
return res.acknowledged();
} catch (Exception e) {
throw new ElasticSearchException(e.getMessage());
}
}
/**
* Restores an index from a backup file
* @param backupFile
* @param index
* @throws IOException
*/
public void restoreIndex(File backupFile, String index) throws IOException {
BufferedReader br = null;
boolean indexExists = indexExists(index);
Client client = new ESClient().getClient();
try {
if (!indexExists) {
final IndicesAdminClient iac = new ESClient().getClient().admin().indices();
createIndex(index);
}
ZipInputStream zipIn=new ZipInputStream(new FileInputStream(backupFile));
zipIn.getNextEntry();
br = new BufferedReader(
new InputStreamReader(zipIn),500000);
// setting number_of_replicas=0 to improve the indexing while restoring
// also we restrict the index to the current server
moveIndexToLocalNode(index);
// wait a bit for the changes be made
Thread.sleep(1000L);
// setting up mapping
String mapping=br.readLine();
boolean mappingExists=mapping.startsWith(MAPPING_MARKER);
String type="content";
if(mappingExists) {
String patternStr = "^"+MAPPING_MARKER+"\\s*\\{\\s*\"(\\w+)\"";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(mapping);
boolean matchFound = matcher.find();
if (matchFound)
type = matcher.group(1);
}
// reading content
ArrayList<String> jsons = new ArrayList<String>();
// we recover the line that wasn't a mapping so it should be content
if(!mappingExists)
jsons.add(mapping);
for (int x = 0; x < 10000000; x++) {
for (int i = 0; i < 100; i++)
while (br.ready())
jsons.add(br.readLine());
if (jsons.size() > 0) {
try {
BulkRequestBuilder req = client.prepareBulk();
for (String raw : jsons) {
int delimidx=raw.indexOf(JSON_RECORD_DELIMITER);
if(delimidx>0) {
String id = raw.substring(0, delimidx);
String json = raw.substring(delimidx + JSON_RECORD_DELIMITER.length(), raw.length());
if (id != null)
req.add(new IndexRequest(index, type, id).source(json));
}
}
if(req.numberOfActions()>0) {
req.execute().actionGet();
//client.admin().indices().flush(new FlushRequest(index)).actionGet();
}
}
finally {
jsons.clear();
}
} else {
break;
}
}
} catch (Exception e) {
throw new IOException(e.getMessage(),e);
} finally {
if (br != null) {
br.close();
}
// back to the original configuration for number_of_replicas
// also let it go other servers
moveIndexBackToCluster(index);
ArrayList<String> list=new ArrayList<String>();
list.add(index);
iapi.optimize(list);
}
}
/**
* List of all indicies
* @return
*/
public Set<String> listIndices() {
Client client = esclient.getClient();
Map<String, IndexStatus> indices = client.admin().indices().status(new IndicesStatusRequest()).actionGet().getIndices();
return indices.keySet();
}
/**
*
* @param indexName
* @return
*/
public boolean indexExists(String indexName) {
return listIndices().contains(indexName.toLowerCase());
}
/**
* Creates an index with default settings
* @param indexName
* @throws DotStateException
* @throws IOException
*/
public void createIndex(String indexName) throws DotStateException, IOException{
createIndex(indexName, null, 0);
}
/**
* Creates an index with default settings. If shards<1 then shards will be default
* @param indexName
* @param shards
* @return
* @throws DotStateException
* @throws IOException
*/
public CreateIndexResponse createIndex(String indexName, int shards) throws DotStateException, IOException{
return createIndex(indexName, null, shards);
}
/**
* deletes and recreates an index
* @param indexName
* @throws DotStateException
* @throws IOException
* @throws DotDataException
*/
public void clearIndex(String indexName) throws DotStateException, IOException, DotDataException{
if(indexName == null || !indexExists(indexName)){
throw new DotStateException("Index" + indexName + " does not exist");
}
Map<String, ClusterIndexHealth> map = getClusterHealth();
ClusterIndexHealth cih = map.get(indexName);
int shards = cih.getNumberOfShards();
int replicas = cih.getNumberOfReplicas();
String alias=getIndexAlias(indexName);
iapi.delete(indexName);
if(UtilMethods.isSet(indexName) && indexName.indexOf("sitesearch") > -1) {
APILocator.getSiteSearchAPI().createSiteSearchIndex(indexName, alias, shards);
} else {
CreateIndexResponse res=createIndex(indexName, shards);
try {
int w=0;
while(!res.acknowledged() && ++w<100)
Thread.sleep(100);
}
catch(InterruptedException ex) {
Logger.warn(this, ex.getMessage(), ex);
}
}
if(UtilMethods.isSet(alias)) {
createAlias(indexName, alias);
}
if(replicas > 0){
APILocator.getESIndexAPI().updateReplicas(indexName, replicas);
}
}
/**
* unclusters an index, including changing the routing to all local
* @param index
* @throws IOException
*/
public void moveIndexToLocalNode(String index) throws IOException {
Client client=new ESClient().getClient();
String nodeName="dotCMS_" + Config.getStringProperty("DIST_INDEXATION_SERVER_ID");
UpdateSettingsResponse resp=client.admin().indices().updateSettings(
new UpdateSettingsRequest(index).settings(
jsonBuilder().startObject()
.startObject("index")
.field("number_of_replicas",0)
.field("routing.allocation.include._name",nodeName)
.endObject()
.endObject().string()
)).actionGet();
}
/**
* clusters an index, including changing the routing
* @param index
* @throws IOException
*/
public void moveIndexBackToCluster(String index) throws IOException {
Client client=new ESClient().getClient();
int nreplicas=Config.getIntProperty("es.index.number_of_replicas",0);
UpdateSettingsResponse resp=client.admin().indices().updateSettings(
new UpdateSettingsRequest(index).settings(
jsonBuilder().startObject()
.startObject("index")
.field("number_of_replicas",nreplicas)
.field("routing.allocation.include._name","*")
.endObject()
.endObject().string()
)).actionGet();
}
/**
* Creates a new index. If settings is null, the getDefaultIndexSettings() will be applied,
* if shards <1, then the default # of shards will be set
* @param indexName
* @param settings
* @param shards
* @return
* @throws ElasticSearchException
* @throws IOException
*/
public synchronized CreateIndexResponse createIndex(String indexName, String settings, int shards) throws ElasticSearchException, IOException {
IndicesAdminClient iac = new ESClient().getClient().admin().indices();
if(shards <1){
try{
shards = Integer.parseInt(System.getProperty("es.index.number_of_shards"));
}catch(Exception e){}
}
if(shards <1){
try{
shards = Config.getIntProperty("es.index.number_of_shards");
}catch(Exception e){}
}
if(shards <0){
shards=1;
}
//default settings, if null
if(settings ==null){
settings = getDefaultIndexSettings(shards);
}
Map map = new ObjectMapper().readValue(settings, LinkedHashMap.class);
map.put("number_of_shards", shards);
// create actual index
CreateIndexRequestBuilder cirb = iac.prepareCreate(indexName).setSettings(map);
return cirb.execute().actionGet();
}
public synchronized CreateIndexResponse createIndex(String indexName, String settings, int shards, String type, String mapping) throws ElasticSearchException, IOException {
IndicesAdminClient iac = new ESClient().getClient().admin().indices();
if(shards <1){
try{
shards = Integer.parseInt(System.getProperty("es.index.number_of_shards"));
}catch(Exception e){}
}
if(shards <1){
try{
shards = Config.getIntProperty("es.index.number_of_shards");
}catch(Exception e){}
}
if(shards <0){
shards=1;
}
//default settings, if null
if(settings ==null){
settings = getDefaultIndexSettings(shards);
}
// create actual index
iac.prepareCreate(indexName).setSettings(settings).addMapping(type, mapping).execute();
return null;
}
/**
* Returns the json (String) for
* the defualt ES index settings
* @param shards
* @return
* @throws IOException
*/
public String getDefaultIndexSettings(int shards) throws IOException{
return jsonBuilder().startObject()
.startObject("index")
.field("number_of_shards",shards+"")
.startObject("analysis")
.startObject("analyzer")
.startObject("default")
.field("type", "Whitespace")
.endObject()
.endObject()
.endObject()
.endObject()
.endObject().string();
}
/**
* returns cluster health
* @return
*/
public Map<String,ClusterIndexHealth> getClusterHealth() {
AdminClient client=new ESClient().getClient().admin();
ClusterHealthRequest req = new ClusterHealthRequest();
ActionFuture<ClusterHealthResponse> chr = client.cluster().health(req);
ClusterHealthResponse res = chr.actionGet();
Map<String,ClusterIndexHealth> map = res.getIndices();
return map;
}
/**
* This method will update the number of
* replicas on a given index
* @param indexName
* @param replicas
* @throws DotDataException
*/
public synchronized void updateReplicas (String indexName, int replicas) throws DotDataException {
Map<String,ClusterIndexHealth> idxs = getClusterHealth();
ClusterIndexHealth health = idxs.get( indexName);
if(health ==null){
return;
}
int curReplicas = health.getNumberOfReplicas();
if(curReplicas != replicas){
Map newSettings = new HashMap();
newSettings.put("index.number_of_replicas", replicas+"");
UpdateSettingsRequestBuilder usrb = new ESClient().getClient().admin().indices().prepareUpdateSettings(indexName);
usrb.setSettings(newSettings);
usrb.execute().actionGet();
}
}
public void putToIndex(String idx, String json, String id){
try{
Client client=new ESClient().getClient();
IndexResponse response = client.prepareIndex(idx, SiteSearchAPI.ES_SITE_SEARCH_MAPPING, id)
.setSource(json)
.execute()
.actionGet();
} catch (Exception e) {
Logger.error(ESIndexAPI.class, e.getMessage(), e);
}
}
public void createAlias(String indexName, String alias) {
try{
// checking for existing alias
if(getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()).get(alias)==null) {
Client client=new ESClient().getClient();
IndicesAliasesRequest req=new IndicesAliasesRequest();
req.addAlias(indexName, alias);
client.admin().indices().aliases(req).actionGet(30000L);
}
} catch (Exception e) {
Logger.error(ESIndexAPI.class, e.getMessage(), e);
throw new RuntimeException(e);
}
}
public Map<String,String> getIndexAlias(List<String> indexNames) {
return getIndexAlias(indexNames.toArray(new String[indexNames.size()]));
}
public Map<String,String> getIndexAlias(String[] indexNames) {
Map<String,String> alias=new HashMap<String,String>();
try{
Client client=new ESClient().getClient();
ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest()
.filterRoutingTable(true)
.filterNodes(true)
.filteredIndices(indexNames);
MetaData md=client.admin().cluster().state(clusterStateRequest)
.actionGet(30000).state().metaData();
for(IndexMetaData imd : md)
for(AliasMetaData amd : imd.aliases().values())
alias.put(imd.index(), amd.alias());
return alias;
} catch (Exception e) {
Logger.error(ESIndexAPI.class, e.getMessage(), e);
throw new RuntimeException(e);
}
}
public String getIndexAlias(String indexName) {
return getIndexAlias(new String[]{indexName}).get(indexName);
}
public Map<String,String> getAliasToIndexMap(List<String> indices) {
Map<String,String> map=getIndexAlias(indices);
Map<String,String> mapReverse=new HashMap<String,String>();
for (String idx : map.keySet())
mapReverse.put(map.get(idx), idx);
return mapReverse;
}
public void closeIndex(String indexName) {
Client client=new ESClient().getClient();
client.admin().indices().close(new CloseIndexRequest(indexName)).actionGet();
}
public void openIndex(String indexName) {
Client client=new ESClient().getClient();
client.admin().indices().open(new OpenIndexRequest(indexName)).actionGet();
}
public List<String> getClosedIndexes() {
Client client=new ESClient().getClient();
Map<String,IndexMetaData> indexState=client.admin().cluster().prepareState().execute().actionGet()
.getState().getMetaData().indices();
List<String> closeIdx=new ArrayList<String>();
for(String idx : indexState.keySet()) {
IndexMetaData idxM=indexState.get(idx);
if(idxM.getState().equals(State.CLOSE))
closeIdx.add(idx);
}
return closeIdx;
}
public Status getIndexStatus(String indexName) throws DotDataException {
List<String> currentIdx = iapi.getCurrentIndex();
List<String> newIdx =iapi.getNewIndex();
boolean active =currentIdx.contains(indexName);
boolean building =newIdx.contains(indexName);
if(active) return Status.ACTIVE;
else if(building) return Status.PROCESSING;
else return Status.INACTIVE;
}
}
| dotCMS/core-2.x | src/com/dotcms/content/elasticsearch/business/ESIndexAPI.java | Java | gpl-3.0 | 22,169 |
import java.math.BigInteger;
public class Example {
static {
System.loadLibrary("jeac");
}
public static void main(String argv[]) {
final byte[] EF_CARDACCESS = new BigInteger("318182300D060804007F00070202020201023012060A04007F000702020302020201020201413012060A04007F0007020204020202010202010D301C060904007F000702020302300C060704007F0007010202010D020141302B060804007F0007020206161F655041202D2042447220476D6248202D20546573746B617274652076322E3004491715411928800A01B421FA07000000000000000000000000000000000000201010291010", 16).toByteArray();
final byte[] PIN = "123456".getBytes();
eac.EAC_init();
SWIGTYPE_p_PACE_SEC secret = eac.PACE_SEC_new(PIN, s_type.PACE_PIN);
SWIGTYPE_p_BUF_MEM buf = eac.get_buf(EF_CARDACCESS);
eac.hexdump("EF.CardAccess", buf);
//System.out.println("Secret:");
//System.out.println(eac.PACE_SEC_print_private(secret, 4));
SWIGTYPE_p_EAC_CTX picc_ctx = eac.EAC_CTX_new();
SWIGTYPE_p_EAC_CTX pcd_ctx = eac.EAC_CTX_new();
eac.EAC_CTX_init_ef_cardaccess(EF_CARDACCESS, pcd_ctx);
eac.EAC_CTX_init_ef_cardaccess(EF_CARDACCESS, picc_ctx);
System.out.println("PACE step 1");
SWIGTYPE_p_BUF_MEM enc_nonce = eac.PACE_STEP1_enc_nonce(picc_ctx, secret);
System.out.println("PACE step 2");
eac.PACE_STEP2_dec_nonce(pcd_ctx, secret, enc_nonce);
System.out.println("PACE step 3A");
SWIGTYPE_p_BUF_MEM pcd_mapping_data = eac.PACE_STEP3A_generate_mapping_data(pcd_ctx);
SWIGTYPE_p_BUF_MEM picc_mapping_data = eac.PACE_STEP3A_generate_mapping_data(picc_ctx);
eac.PACE_STEP3A_map_generator(pcd_ctx, picc_mapping_data);
eac.PACE_STEP3A_map_generator(picc_ctx, pcd_mapping_data);
System.out.println("PACE step 3B");
SWIGTYPE_p_BUF_MEM pcd_ephemeral_pubkey = eac.PACE_STEP3B_generate_ephemeral_key(pcd_ctx);
SWIGTYPE_p_BUF_MEM picc_ephemeral_pubkey = eac.PACE_STEP3B_generate_ephemeral_key(picc_ctx);
eac.PACE_STEP3B_compute_shared_secret(pcd_ctx, picc_ephemeral_pubkey);
eac.PACE_STEP3B_compute_shared_secret(picc_ctx, pcd_ephemeral_pubkey);
System.out.println("PACE step 3C");
eac.PACE_STEP3C_derive_keys(pcd_ctx);
eac.PACE_STEP3C_derive_keys(picc_ctx);
System.out.println("PACE step 3D");
SWIGTYPE_p_BUF_MEM pcd_token = eac.PACE_STEP3D_compute_authentication_token(pcd_ctx, picc_ephemeral_pubkey);
SWIGTYPE_p_BUF_MEM picc_token = eac.PACE_STEP3D_compute_authentication_token(picc_ctx, pcd_ephemeral_pubkey);
eac.PACE_STEP3D_verify_authentication_token(pcd_ctx, picc_token);
int r = eac.PACE_STEP3D_verify_authentication_token(picc_ctx, pcd_token);
//System.out.println("PICC's EAC_CTX:");
//System.out.println(eac.EAC_CTX_print_private(picc_ctx, 4));
//System.out.println("PCD's EAC_CTX:");
//System.out.println(eac.EAC_CTX_print_private(pcd_ctx, 4));
eac.EAC_CTX_clear_free(pcd_ctx);
eac.EAC_CTX_clear_free(picc_ctx);
eac.PACE_SEC_clear_free(secret);
eac.EAC_cleanup();
if (r != 1)
System.out.println("Result was: " + r);
}
}
| d0/openpace | bindings/java/Example.java | Java | gpl-3.0 | 3,222 |
/**
* 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.hadoop.yarn.server.nodemanager.webapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.http.HtmlQuoting;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.webapp.Controller.RequestContext;
import com.google.inject.Injector;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
@Singleton
public class NMWebAppFilter extends GuiceContainer{
private Injector injector;
private Context nmContext;
private static final long serialVersionUID = 1L;
@Inject
public NMWebAppFilter(Injector injector, Context nmContext) {
super(injector);
this.injector = injector;
this.nmContext = nmContext;
}
@Override
public void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws IOException,
ServletException {
String redirectPath = containerLogPageRedirectPath(request);
if (redirectPath != null) {
String redirectMsg =
"Redirecting to log server" + " : " + redirectPath;
PrintWriter out = response.getWriter();
out.println(redirectMsg);
response.setHeader("Location", redirectPath);
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
return;
}
super.doFilter(request, response, chain);
}
private String containerLogPageRedirectPath(HttpServletRequest request) {
String uri = HtmlQuoting.quoteHtmlChars(request.getRequestURI());
String redirectPath = null;
if (!uri.contains("/ws/v1/node") && uri.contains("/containerlogs")) {
String[] parts = uri.split("/");
String containerIdStr = parts[3];
String appOwner = parts[4];
if (containerIdStr != null && !containerIdStr.isEmpty()) {
ContainerId containerId = null;
try {
containerId = ContainerId.fromString(containerIdStr);
} catch (IllegalArgumentException ex) {
return redirectPath;
}
ApplicationId appId =
containerId.getApplicationAttemptId().getApplicationId();
Application app = nmContext.getApplications().get(appId);
Configuration nmConf = nmContext.getLocalDirsHandler().getConfig();
if (app == null
&& nmConf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED,
YarnConfiguration.DEFAULT_LOG_AGGREGATION_ENABLED)) {
String logServerUrl =
nmConf.get(YarnConfiguration.YARN_LOG_SERVER_URL);
if (logServerUrl != null && !logServerUrl.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append(logServerUrl);
sb.append("/");
sb.append(nmContext.getNodeId().toString());
sb.append("/");
sb.append(containerIdStr);
sb.append("/");
sb.append(containerIdStr);
sb.append("/");
sb.append(appOwner);
redirectPath =
WebAppUtils.appendQueryParams(request, sb.toString());
} else {
injector.getInstance(RequestContext.class).set(
ContainerLogsPage.REDIRECT_URL, "false");
}
}
}
}
return redirectPath;
}
}
| jaypatil/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/NMWebAppFilter.java | Java | gpl-3.0 | 4,608 |
/*
* pnlString.java
*
* Created on Aug 23, 2009, 11:56:59 PM
*/
package pspconstructor.Properties;
/**
*
* @author Carlo
*/
public class pnlString extends javax.swing.JPanel {
/** Creates new form pnlString */
public pnlString() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lblArg = new javax.swing.JLabel();
txtStringArg = new javax.swing.JTextField();
lblArg.setText("Argument:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblArg)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
.addComponent(txtStringArg, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtStringArg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblArg))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JLabel lblArg;
public javax.swing.JTextField txtStringArg;
// End of variables declaration//GEN-END:variables
}
| CarloBarraco/PSPConstructor | src/pspconstructor/Properties/pnlString.java | Java | gpl-3.0 | 2,117 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package byui.cit260.starWars.view;
/**
*
* @author Bryce Blauser
*/
public class EnterWaypointView extends View {
public EnterWaypointView() {
super ("-------------------------------------------"
+ "\n| Enter Waypoint |"
+ "\n-------------------------------------------"
+ "\n Supply Ship (3P)"
+ "\n-------------------------------------------\n");
}
@Override
public boolean doAction(String value) {
value = value.toUpperCase(); // converto to upper
switch (value) {
case "3P": // Move to Supply Ship
this.moveToSupplyShip();
break;
default:
System.out.println("\n*** Invalid selection *** Try again");
}
return false;
}
private void moveToSupplyShip() {
SupplyShipView supplyView = new SupplyShipView();
supplyView.display();
}
}
| bblauser/star-wars | src/byui/cit260/starWars/view/EnterWaypointView.java | Java | gpl-3.0 | 1,209 |
/***********************************************************************
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 ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. García ([email protected])
A. Fernández ([email protected])
J. Luengo ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
**********************************************************************/
/**
* <p>
* @author Written by Albert Orriols (La Salle, Ramón Llull University - Barcelona) 28/03/2004
* @author Modified by Xavi Solé (La Salle, Ramón Llull University - Barcelona) 03/12/2008
* @version 1.1
* @since JDK1.2
* </p>
*/
package keel.Algorithms.Genetic_Rule_Learning.XCS;
import keel.Algorithms.Genetic_Rule_Learning.XCS.KeelParser.Config;
import java.util.*;
import java.lang.*;
import java.io.*;
public class TernaryRep implements Attribute{
/**
* <p>
* It contains a char value, that represents the value of the alelle.
* </p>
* <p>
*/
///////////////////////////////////////
// attributes
/**
* <p>
* Represents the value that takes this allele of the classifier.
* </p>
*/
private char pos;
///////////////////////////////////////
// associations
/**
* <p>
* A reference to a ternary mutation operator
* </p>
*/
private TernaryMutation ternaryMutation;
///////////////////////////////////////
// operations
/**
* <p>
* It is the default constructor of the class.
* value.
* </p>
*/
public TernaryRep() {
if (Config.typeOfMutation.toLowerCase().equals("niched")){
ternaryMutation = new TNichedMutation();
}
else{
ternaryMutation = new TFreeMutation();
}
} // end TernaryRep
/**
* <p>
* It's the constructor of the class value from the environmental value.
* </p>
* @param env is the environmental value for this attribute.
*/
public TernaryRep(double env) {
//Initialitation of the char value.
if (Config.rand() < Config.pDontCare)
pos = Config.dontCareSymbol;
else{
if (env == -1.)
pos = Config.charVector[(int)(Config.rand()*(double)Config.charVector.length)];
else
pos = (char)env;
}
// A new mutate object is declared
if (Config.typeOfMutation.toLowerCase().equals("niched")) ternaryMutation = new TNichedMutation();
else ternaryMutation = new TFreeMutation();
} // end TernaryRep
/**
* <p>
* It is the constructor of the class. It initializes the char
* according to the char value given as a parameter.
* </p>
* @param value is the value that takes the allele.
*/
public TernaryRep(char value) {
pos = value;
if (Config.typeOfMutation.toLowerCase().equals("niched")){
ternaryMutation = new TNichedMutation();
}
else{
ternaryMutation = new TFreeMutation();
}
} // end TernaryRep
/**
* <p>
* It is the constructor of the class. It creates a copy
* of the TernaryRep given as a parameter.
* </p>
* @param tr is the ternary representation that has to be cloned.
*/
public TernaryRep(Attribute tr) {
pos = ((TernaryRep)tr).pos;
if (Config.typeOfMutation.toLowerCase().equals("niched")){
ternaryMutation = new TNichedMutation();
}
else{
ternaryMutation = new TFreeMutation();
}
} // end TernaryRep
/**
* <p>
* Sets the value of the allele.
* </p>
* <p>
* @param value contains the value that has to be set.
* </p>
* <p>
* @param value2 is needed to implement the Attribute interface. In this case is not
* used.
* </p>
*/
public void setAllele(double value, double value2) {
if ((char)value == (char) -1. )
pos = Config.dontCareSymbol;
else
pos = (char)value;
} // end setAllele
/**
* <p>
* Sets the value of the allele.
* </p>
* <p>
* @param tr contains the value that has to be set.
* </p>
*
*/
public void setAllele(Attribute tr) {
pos = ((TernaryRep)tr).pos;
} // end setAllele
/**
* <p>
* Returns the value of the alelle
* </p>
* <p>
*
* @return a double with the value of the allele.
* </p>
*/
public double getAllele() {
return (double)pos;
} // end getAllele
public Attribute getAttributeAllele(){
return this;
}
/**
* <p>
* It returns the generality of the allele.
* </p>
*
* <p>
* @return a double with the generality of this allele.
* </p>
*/
public double getGenerality() {
if (pos == Config.dontCareSymbol) return 1.;
else return 0.;
} // end getGenerality
/**
* <p>
* Changes the allele if it is a don't care symbol and the random number generated is less than Pspecify.
* </p>
* <p>
* @param env is the environment.
* </p>
*/
public void makeSpecify (double env){
if (pos == Config.dontCareSymbol){
if (Config.rand() <= Config.Pspecify ){
if ((char)env == (char)-1.)
pos = Config.charVector[(int)(Config.rand() * (double)Config.charVector.length)];
else
pos = (char)env;
}
}
}
/**
* <p>
* Mutates the character.
* </p>
*
* <p>
* @param currentState is needed to implement the Attribute interface
* </p>
*/
public void mutate(double currentState) {
pos = ternaryMutation.mutate(pos, (char)currentState);
} // end mute
/**
* <p>
* Returns true if the allele matches with the environment.
* </p>
* <p>
* @param env is the value of the environment.
* </p>
* <p>
* @return a boolean indicating if the allele matches with the environmental value.
* </p>
*/
public boolean match (double env){
if (pos == (char)env || pos == Config.dontCareSymbol || (char)env == (char)(-1)) return true;
return false;
} // end match
/**
* <p>
* Returns true if the allele is subsumed by the ternary representation given as a parameter.
* </p>
* @param tr is the ternary representation of a classifier.
* @return a boolean indicating if the allele of the classifier is subsumed
*/
public boolean subsumes(Attribute tr){
if (pos == ((TernaryRep)tr).pos || pos == Config.dontCareSymbol) return true;
return false;
} // end subusmes
/**
* <p>
* Returns true if the allele is equal to the allele given as a parameter.
* </p>
* <p>
* @param tr is the ternary representation of a classifier.
* </p>
* <p>
* @return a boolean indicating if the two alleles are equal.
* </p>
*/
public boolean equals (Attribute tr){
return pos == ((TernaryRep)tr).pos;
} // end equals
/**
* <p>
* Returns if the character of the representation
* is a don't care symbol
* </p>
* <p>
* @return a double: 1 if the character is a don't care simbol
* and 0 otherwise
* </p>
*/
public double isDontCareSymbol(){
if (pos == Config.dontCareSymbol) {
return 1.;
}
return 0.;
} // end isDontCareSymbol
/**
* <p>
* Indicates if the classifier is more general than
* the classifier passed as a parameter.
* </p>
* <p>
* @param t is the ternary representation of the more
* specific classifier.
* </p>
* <p>
* @return a boolean indicating if it's more general.
* </p>
*/
public boolean isMoreGeneral(Attribute t){
if (pos == ((TernaryRep)t).pos || pos == Config.dontCareSymbol) return true;
return false;
}
/**
* <p>
* Prints the allele.
* </p>
*/
public void print(){
System.out.print (pos);
}
/**
* <p>
* Prints the allele.
* </p>
* <p>
* @param out is the PrintWriter where the allele has to be printed
* </p>
*/
public void print(PrintWriter out){
out.print (pos);
}
// THE NEXT FUNCTIONS ARE NOT IMPLEMENTED
public double getUpperAllele(){
return (double)pos;
}
public double getLowerAllele(){
return (double)pos;
}
public void verifyInterval(){}
public void printNotNorm(PrintWriter fout, Vector conv){}
public void printNotNorm(PrintWriter fout, int lo){}
public void printNotNorm(PrintWriter fout, double lo, double up){}
//public void crossAllele(Attribute at1, Attribute at2){}
//public double setAllele(int i, double lowerValue, double UpperValue){return 0.0;}
} // end TernaryRep
| TheMurderer/keel | src/keel/Algorithms/Genetic_Rule_Learning/XCS/TernaryRep.java | Java | gpl-3.0 | 9,444 |
/*
* 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/>.
*/
/*
* MultiScheme.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.meta;
import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.RandomizableMultipleClassifiersCombiner;
import weka.classifiers.RandomizableMultipleFilteredClassifiersCombiner;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
<!-- globalinfo-start -->
* Class for selecting a classifier from among several using cross validation on the training data or the performance on the training data. Performance is measured based on percent correct (classification) or mean-squared error (regression).
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -X <number of folds>
* Use cross validation for model selection using the
* given number of folds. (default 0, is to
* use training error)</pre>
*
* <pre> -S <num>
* Random number seed.
* (default 1)</pre>
*
* <pre> -B <classifier specification>
* Full class name of classifier to include, followed
* by scheme options. May be specified multiple times.
* (default: "weka.classifiers.rules.ZeroR")</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @author Len Trigg ([email protected])
* @version $Revision: 8034 $
*/
public class MultiScheme
extends RandomizableMultipleFilteredClassifiersCombiner {
/** for serialization */
private static final long serialVersionUID = 3987322782203939531L;
/** The classifier that had the best performance on training data. */
protected FilteredClassifier m_Classifier;
/** The index into the vector for the selected scheme */
protected int m_ClassifierIndex;
/**
* Number of folds to use for cross validation (0 means use training
* error for selection)
*/
protected int m_NumXValFolds;
/**
* Returns a string describing classifier
* @return a description suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Class for selecting a classifier from among several using cross "
+ "validation on the training data or the performance on the "
+ "training data. Performance is measured based on percent correct "
+ "(classification) or mean-squared error (regression).";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(1);
newVector.addElement(new Option(
"\tUse cross validation for model selection using the\n"
+ "\tgiven number of folds. (default 0, is to\n"
+ "\tuse training error)",
"X", 1, "-X <number of folds>"));
Enumeration enu = super.listOptions();
while (enu.hasMoreElements()) {
newVector.addElement(enu.nextElement());
}
return newVector.elements();
}
/**
* Parses a given list of options. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -X <number of folds>
* Use cross validation for model selection using the
* given number of folds. (default 0, is to
* use training error)</pre>
*
* <pre> -S <num>
* Random number seed.
* (default 1)</pre>
*
* <pre> -B <classifier specification>
* Full class name of classifier to include, followed
* by scheme options. May be specified multiple times.
* (default: "weka.classifiers.rules.ZeroR")</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</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 numFoldsString = Utils.getOption('X', options);
if (numFoldsString.length() != 0) {
setNumFolds(Integer.parseInt(numFoldsString));
} else {
setNumFolds(0);
}
super.setOptions(options);
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] superOptions = super.getOptions();
String [] options = new String [superOptions.length + 2];
int current = 0;
options[current++] = "-X"; options[current++] = "" + getNumFolds();
System.arraycopy(superOptions, 0, options, current,
superOptions.length);
return options;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String classifiersTipText() {
return "The classifiers to be chosen from.";
}
/**
* Sets the list of possible classifers to choose from.
*
* @param classifiers an array of classifiers with all options set.
*/
public void setClassifiers(FilteredClassifier [] classifiers) {
m_Classifiers = classifiers;
}
/**
* Gets the list of possible classifers to choose from.
*
* @return the array of Classifiers
*/
public FilteredClassifier [] getClassifiers() {
return m_Classifiers;
}
/**
* Gets a single classifier from the set of available classifiers.
*
* @param index the index of the classifier wanted
* @return the Classifier
*/
public FilteredClassifier getClassifier(int index) {
return m_Classifiers[index];
}
/**
* Gets the classifier specification string, which contains the class name of
* the classifier and any options to the classifier
*
* @param index the index of the classifier string to retrieve, starting from
* 0.
* @return the classifier string, or the empty string if no classifier
* has been assigned (or the index given is out of range).
*/
protected String getClassifierSpec(int index) {
if (m_Classifiers.length < index) {
return "";
}
FilteredClassifier c = getClassifier(index);
if (c instanceof OptionHandler) {
return c.getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler)c).getOptions());
}
return c.getClass().getName();
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String seedTipText() {
return "The seed used for randomizing the data " +
"for cross-validation.";
}
/**
* Sets the seed for random number generation.
*
* @param seed the random number seed
*/
public void setSeed(int seed) {
m_Seed = seed;;
}
/**
* Gets the random number seed.
*
* @return the random number seed
*/
public int getSeed() {
return m_Seed;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String numFoldsTipText() {
return "The number of folds used for cross-validation (if 0, " +
"performance on training data will be used).";
}
/**
* Gets the number of folds for cross-validation. A number less
* than 2 specifies using training error rather than cross-validation.
*
* @return the number of folds for cross-validation
*/
public int getNumFolds() {
return m_NumXValFolds;
}
/**
* Sets the number of folds for cross-validation. A number less
* than 2 specifies using training error rather than cross-validation.
*
* @param numFolds the number of folds for cross-validation
*/
public void setNumFolds(int numFolds) {
m_NumXValFolds = numFolds;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String debugTipText() {
return "Whether debug information is output to console.";
}
/**
* Set debugging mode
*
* @param debug true if debug output should be printed
*/
public void setDebug(boolean debug) {
m_Debug = debug;
}
/**
* Get whether debugging is turned on
*
* @return true if debugging output is on
*/
public boolean getDebug() {
return m_Debug;
}
/**
* Get the index of the classifier that was determined as best during
* cross-validation.
*
* @return the index in the classifier array
*/
public int getBestClassifierIndex() {
return m_ClassifierIndex;
}
/**
* Buildclassifier selects a classifier from the set of classifiers
* by minimising error on the training data.
*
* @param data the training data to be used for generating the
* boosted classifier.
* @throws Exception if the classifier could not be built successfully
*/
public void buildClassifier(Instances data) throws Exception {
if (m_Classifiers.length == 0) {
throw new Exception("No base classifiers have been set!");
}
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
Instances newData = new Instances(data);
newData.deleteWithMissingClass();
Random random = new Random(m_Seed);
newData.randomize(random);
if (newData.classAttribute().isNominal() && (m_NumXValFolds > 1)) {
newData.stratify(m_NumXValFolds);
}
Instances train = newData; // train on all data by default
Instances test = newData; // test on training data by default
FilteredClassifier bestClassifier = null;
int bestIndex = -1;
double bestPerformance = Double.NaN;
int numClassifiers = m_Classifiers.length;
for (int i = 0; i < numClassifiers; i++) {
FilteredClassifier currentClassifier = getClassifier(i);
Evaluation evaluation;
if (m_NumXValFolds > 1) {
evaluation = new Evaluation(newData);
for (int j = 0; j < m_NumXValFolds; j++) {
// We want to randomize the data the same way for every
// learning scheme.
train = newData.trainCV(m_NumXValFolds, j, new Random (1));
test = newData.testCV(m_NumXValFolds, j);
currentClassifier.buildClassifier(train);
evaluation.setPriors(train);
evaluation.evaluateModel(currentClassifier, test);
}
} else {
currentClassifier.buildClassifier(train);
evaluation = new Evaluation(train);
evaluation.evaluateModel(currentClassifier, test);
}
double error = evaluation.errorRate();
if (m_Debug) {
System.err.println("Error rate: " + Utils.doubleToString(error, 6, 4)
+ " for classifier "
+ currentClassifier.getClass().getName());
}
if ((i == 0) || (error < bestPerformance)) {
bestClassifier = currentClassifier;
bestPerformance = error;
bestIndex = i;
}
}
m_ClassifierIndex = bestIndex;
if (m_NumXValFolds > 1) {
bestClassifier.buildClassifier(newData);
}
m_Classifier = bestClassifier;
}
/**
* Returns class probabilities.
*
* @param instance the instance to be classified
* @return the distribution for the instance
* @throws Exception if instance could not be classified
* successfully
*/
public double[] distributionForInstance(Instance instance) throws Exception {
return m_Classifier.distributionForInstance(instance);
}
/**
* Output a representation of this classifier
* @return a string representation of the classifier
*/
public String toString() {
if (m_Classifier == null) {
return "MultiScheme: No model built yet.";
}
String result = "MultiScheme selection using";
if (m_NumXValFolds > 1) {
result += " cross validation error";
} else {
result += " error on training data";
}
result += " from the following:\n";
for (int i = 0; i < m_Classifiers.length; i++) {
result += '\t' + getClassifierSpec(i) + '\n';
}
result += "Selected scheme: "
+ getClassifierSpec(m_ClassifierIndex)
+ "\n\n"
+ m_Classifier.toString();
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 8034 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain the following arguments:
* -t training file [-T test file] [-c class index]
*/
public static void main(String [] argv) {
runClassifier(new MultiScheme(), argv);
}
}
| dsibournemouth/autoweka | weka-3.7.7/src/main/java/weka/classifiers/meta/MultiScheme.java | Java | gpl-3.0 | 13,589 |
package j2me.util;
import java.util.*;
import j2me.lang.*;
public
class StringParser implements Enumeration {
private int currentPosition;
private int newPosition;
private int maxPosition;
private String str;
private String delimiters;
private boolean retDelims;
private boolean delimsChanged;
private int maxDelimCodePoint;
private boolean hasSurrogates = false;
private int[] delimiterCodePoints;
public StringParser(String str, String delim, boolean returnDelims) {
currentPosition = 0;
newPosition = -1;
delimsChanged = false;
this.str = str;
maxPosition = str.length();
delimiters = delim;
retDelims = returnDelims;
makePoint();
}
public StringParser(String str, String delim) {
this(str, delim, false);
}
public StringParser(String str) {
this(str, " \t\n\r\f", false);
}
private int skipDelimiters(int startPos) {
if (delimiters == null)
throw new NullPointerException();
int position = startPos;
while (!retDelims && position < maxPosition) {
if (!hasSurrogates) {
char c = str.charAt(position);
if ((c > maxDelimCodePoint) || (delimiters.indexOf(c) < 0))
break;
position++;
} else {
int c = StringMe.codePointAt(str, position);
if ((c > maxDelimCodePoint) || !isDelimiter(c)) {
break;
}
position += CharacterMe.charCount(c);
}
}
return position;
}
private int parseTokens(int startPos) {
int position = startPos;
while (position < maxPosition) {
if (!hasSurrogates) {
char c = str.charAt(position);
if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0))
break;
position++;
} else {
int c = StringMe.codePointAt(str,position);
if ((c <= maxDelimCodePoint) && isDelimiter(c))
break;
position += CharacterMe.charCount(c);
}
}
if (retDelims && (startPos == position)) {
if (!hasSurrogates) {
char c = str.charAt(position);
if ((c <= maxDelimCodePoint) && (delimiters.indexOf(c) >= 0))
position++;
} else {
int c = StringMe.codePointAt(str,position);
if ((c <= maxDelimCodePoint) && isDelimiter(c))
position += CharacterMe.charCount(c);
}
}
return position;
}
private boolean isDelimiter(int codePoint) {
for (int i = 0; i < delimiterCodePoints.length; i++) {
if (delimiterCodePoints[i] == codePoint) {
return true;
}
}
return false;
}
public boolean hasMoreTokens() {
newPosition = skipDelimiters(currentPosition);
return (newPosition < maxPosition);
}
public String nextToken() {
currentPosition = (newPosition >= 0 && !delimsChanged) ?
newPosition : skipDelimiters(currentPosition);
/* Reset these anyway */
delimsChanged = false;
newPosition = -1;
if (currentPosition > maxPosition)
throw new NoSuchElementException();
if (currentPosition == maxPosition)
return "";
int start = currentPosition;
currentPosition = parseTokens(currentPosition);
return str.substring(start, currentPosition);
}
public String nextToken(String delim) {
delimiters = delim;
/* delimiter string specified, so set the appropriate flag. */
delimsChanged = true;
makePoint();
return nextToken();
}
public boolean hasMoreElements() {
return hasMoreTokens();
}
public Object nextElement() {
return nextToken();
}
public int countTokens() {
int count = 0;
int currpos = currentPosition;
while (currpos < maxPosition) {
currpos = skipDelimiters(currpos);
//if (currpos >= maxPosition)
// break;
currpos = parseTokens(currpos);
count++;
}
return count;
}
private void makePoint() {
if (delimiters == null) {
maxDelimCodePoint = 0;
return;
}
int m = 0;
int c;
int count = 0;
for (int i = 0; i < delimiters.length(); i += CharacterMe.charCount(c)) {
c = delimiters.charAt(i);
if (c >= CharacterMe.MIN_HIGH_SURROGATE && c <= CharacterMe.MAX_LOW_SURROGATE) {
c = StringMe.codePointAt(delimiters,i);
hasSurrogates = true;
}
if (m < c)
m = c;
count++;
}
maxDelimCodePoint = m;
if (hasSurrogates) {
delimiterCodePoints = new int[count];
for (int i = 0, j = 0; i < count; i++, j += CharacterMe.charCount(c)) {
c = StringMe.codePointAt(delimiters,j);
delimiterCodePoints[i] = c;
}
}
}
}
| chip/rhodes | platform/shared/rubyJVM/src/j2me/util/StringParser.java | Java | gpl-3.0 | 5,364 |
package net.gazeplay.games.horses;
import net.gazeplay.GameCategories;
import net.gazeplay.GameSpec;
import net.gazeplay.GameSpecSource;
import net.gazeplay.GameSummary;
public class HorsesGameSpecSource implements GameSpecSource {
@Override
public GameSpec getGameSpec() {
return new GameSpec(
GameSummary.builder().nameCode("Horses").gameThumbnail("data/Thumbnails/horses.png").category(GameCategories.Category.ACTION_REACTION).build(),
new HorsesGameVariantGenerator(), new HorsesGameLauncher());
}
}
| schwabdidier/GazePlay | gazeplay-games/src/main/java/net/gazeplay/games/horses/HorsesGameSpecSource.java | Java | gpl-3.0 | 550 |
package org.bukkit.plugin;
import org.bukkit.Bukkit;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.bukkit.event.server.ServiceUnregisterEvent;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A simple services manager.
*/
public class SimpleServicesManager implements ServicesManager {
/**
* Map of providers.
*/
private final Map<Class<?>, List<RegisteredServiceProvider<?>>> providers = new HashMap<Class<?>, List<RegisteredServiceProvider<?>>>();
/**
* Register a provider of a service.
*
* @param <T> Provider
* @param service service class
* @param provider provider to register
* @param plugin plugin with the provider
* @param priority priority of the provider
*/
public <T> void register(Class<T> service, T provider, Plugin plugin, ServicePriority priority) {
RegisteredServiceProvider<T> registeredProvider = null;
synchronized (providers) {
List<RegisteredServiceProvider<?>> registered = providers.get(service);
if (registered == null) {
registered = new ArrayList<RegisteredServiceProvider<?>>();
providers.put(service, registered);
}
registeredProvider = new RegisteredServiceProvider<T>(service, provider, priority, plugin);
// Insert the provider into the collection, much more efficient big O than sort
int position = Collections.binarySearch(registered, registeredProvider);
if (position < 0) {
registered.add(-(position + 1), registeredProvider);
} else {
registered.add(position, registeredProvider);
}
}
Bukkit.getServer().getPluginManager().callEvent(new ServiceRegisterEvent(registeredProvider));
}
/**
* Unregister all the providers registered by a particular plugin.
*
* @param plugin The plugin
*/
public void unregisterAll(Plugin plugin) {
ArrayList<ServiceUnregisterEvent> unregisteredEvents = new ArrayList<ServiceUnregisterEvent>();
synchronized (providers) {
Iterator<Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>>> it = providers.entrySet().iterator();
try {
while (it.hasNext()) {
Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>> entry = it.next();
Iterator<RegisteredServiceProvider<?>> it2 = entry.getValue().iterator();
try {
// Removed entries that are from this plugin
while (it2.hasNext()) {
RegisteredServiceProvider<?> registered = it2.next();
Plugin oPlugin = registered.getPlugin();
if (oPlugin != null ? oPlugin.equals(plugin) : plugin == null) {
it2.remove();
unregisteredEvents.add(new ServiceUnregisterEvent(registered));
}
}
} catch (NoSuchElementException e) { // Why does Java suck
}
// Get rid of the empty list
if (entry.getValue().size() == 0) {
it.remove();
}
}
} catch (NoSuchElementException e) {}
}
for (ServiceUnregisterEvent event : unregisteredEvents) {
Bukkit.getServer().getPluginManager().callEvent(event);
}
}
/**
* Unregister a particular provider for a particular service.
*
* @param service The service interface
* @param provider The service provider implementation
*/
public void unregister(Class<?> service, Object provider) {
ArrayList<ServiceUnregisterEvent> unregisteredEvents = new ArrayList<ServiceUnregisterEvent>();
synchronized (providers) {
Iterator<Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>>> it = providers.entrySet().iterator();
try {
while (it.hasNext()) {
Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>> entry = it.next();
// We want a particular service
if (entry.getKey() != service) {
continue;
}
Iterator<RegisteredServiceProvider<?>> it2 = entry.getValue().iterator();
try {
// Removed entries that are from this plugin
while (it2.hasNext()) {
RegisteredServiceProvider<?> registered = it2.next();
if (registered.getProvider() == provider) {
it2.remove();
unregisteredEvents.add(new ServiceUnregisterEvent(registered));
}
}
} catch (NoSuchElementException e) { // Why does Java suck
}
// Get rid of the empty list
if (entry.getValue().size() == 0) {
it.remove();
}
}
} catch (NoSuchElementException e) {}
}
for (ServiceUnregisterEvent event : unregisteredEvents) {
Bukkit.getServer().getPluginManager().callEvent(event);
}
}
/**
* Unregister a particular provider.
*
* @param provider The service provider implementation
*/
public void unregister(Object provider) {
ArrayList<ServiceUnregisterEvent> unregisteredEvents = new ArrayList<ServiceUnregisterEvent>();
synchronized (providers) {
Iterator<Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>>> it = providers.entrySet().iterator();
try {
while (it.hasNext()) {
Map.Entry<Class<?>, List<RegisteredServiceProvider<?>>> entry = it.next();
Iterator<RegisteredServiceProvider<?>> it2 = entry.getValue().iterator();
try {
// Removed entries that are from this plugin
while (it2.hasNext()) {
RegisteredServiceProvider<?> registered = it2.next();
if (registered.getProvider().equals(provider)) {
it2.remove();
unregisteredEvents.add(new ServiceUnregisterEvent(registered));
}
}
} catch (NoSuchElementException e) { // Why does Java suck
}
// Get rid of the empty list
if (entry.getValue().size() == 0) {
it.remove();
}
}
} catch (NoSuchElementException e) {}
}
for (ServiceUnregisterEvent event : unregisteredEvents) {
Bukkit.getServer().getPluginManager().callEvent(event);
}
}
/**
* Queries for a provider. This may return if no provider has been
* registered for a service. The highest priority provider is returned.
*
* @param <T> The service interface
* @param service The service interface
* @return provider or null
*/
public <T> T load(Class<T> service) {
synchronized (providers) {
List<RegisteredServiceProvider<?>> registered = providers.get(service);
if (registered == null) {
return null;
}
// This should not be null!
return service.cast(registered.get(0).getProvider());
}
}
/**
* Queries for a provider registration. This may return if no provider
* has been registered for a service.
*
* @param <T> The service interface
* @param service The service interface
* @return provider registration or null
*/
@SuppressWarnings("unchecked")
public <T> RegisteredServiceProvider<T> getRegistration(Class<T> service) {
synchronized (providers) {
List<RegisteredServiceProvider<?>> registered = providers.get(service);
if (registered == null) {
return null;
}
// This should not be null!
return (RegisteredServiceProvider<T>) registered.get(0);
}
}
/**
* Get registrations of providers for a plugin.
*
* @param plugin The plugin
* @return provider registration or null
*/
public List<RegisteredServiceProvider<?>> getRegistrations(Plugin plugin) {
ImmutableList.Builder<RegisteredServiceProvider<?>> ret = ImmutableList.<RegisteredServiceProvider<?>>builder();
synchronized (providers) {
for (List<RegisteredServiceProvider<?>> registered : providers.values()) {
for (RegisteredServiceProvider<?> provider : registered) {
if (provider.getPlugin().equals(plugin)) {
ret.add(provider);
}
}
}
}
return ret.build();
}
/**
* Get registrations of providers for a service. The returned list is
* an unmodifiable copy.
*
* @param <T> The service interface
* @param service The service interface
* @return a copy of the list of registrations
*/
@SuppressWarnings("unchecked")
public <T> List<RegisteredServiceProvider<T>> getRegistrations(Class<T> service) {
ImmutableList.Builder<RegisteredServiceProvider<T>> ret;
synchronized (providers) {
List<RegisteredServiceProvider<?>> registered = providers.get(service);
if (registered == null) {
return ImmutableList.<RegisteredServiceProvider<T>>of();
}
ret = ImmutableList.<RegisteredServiceProvider<T>>builder();
for (RegisteredServiceProvider<?> provider : registered) {
ret.add((RegisteredServiceProvider<T>) provider);
}
}
return ret.build();
}
/**
* Get a list of known services. A service is known if it has registered
* providers for it.
*
* @return a copy of the set of known services
*/
public Set<Class<?>> getKnownServices() {
synchronized (providers) {
return ImmutableSet.<Class<?>>copyOf(providers.keySet());
}
}
/**
* Returns whether a provider has been registered for a service.
*
* @param <T> service
* @param service service to check
* @return true if and only if there are registered providers
*/
public <T> boolean isProvidedFor(Class<T> service) {
synchronized (providers) {
return providers.containsKey(service);
}
}
} | Scrik/Cauldron-1 | eclipse/cauldron/src/main/java/org/bukkit/plugin/SimpleServicesManager.java | Java | gpl-3.0 | 11,250 |
/**
* 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.hadoop.mapred;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.hadoop.mapreduce.Cluster;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobPriority;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.TaskReport;
import org.apache.hadoop.mapreduce.TaskType;
import org.junit.Assert;
import org.junit.Test;
@SuppressWarnings("deprecation")
public class JobClientUnitTest {
public class TestJobClient extends JobClient {
TestJobClient(JobConf jobConf) throws IOException {
super(jobConf);
}
void setCluster(Cluster cluster) {
this.cluster = cluster;
}
}
public class TestJobClientGetJob extends TestJobClient {
int lastGetJobRetriesCounter = 0;
int getJobRetriesCounter = 0;
int getJobRetries = 0;
RunningJob runningJob;
TestJobClientGetJob(JobConf jobConf) throws IOException {
super(jobConf);
}
public int getLastGetJobRetriesCounter() {
return lastGetJobRetriesCounter;
}
public void setGetJobRetries(int getJobRetries) {
this.getJobRetries = getJobRetries;
}
public void setRunningJob(RunningJob runningJob) {
this.runningJob = runningJob;
}
protected RunningJob getJobInner(final JobID jobid) throws IOException {
if (getJobRetriesCounter >= getJobRetries) {
lastGetJobRetriesCounter = getJobRetriesCounter;
getJobRetriesCounter = 0;
return runningJob;
}
getJobRetriesCounter++;
return null;
}
}
@Test
public void testMapTaskReportsWithNullJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
Cluster mockCluster = mock(Cluster.class);
client.setCluster(mockCluster);
JobID id = new JobID("test",0);
when(mockCluster.getJob(id)).thenReturn(null);
TaskReport[] result = client.getMapTaskReports(id);
assertEquals(0, result.length);
verify(mockCluster).getJob(id);
}
@Test
public void testReduceTaskReportsWithNullJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
Cluster mockCluster = mock(Cluster.class);
client.setCluster(mockCluster);
JobID id = new JobID("test",0);
when(mockCluster.getJob(id)).thenReturn(null);
TaskReport[] result = client.getReduceTaskReports(id);
assertEquals(0, result.length);
verify(mockCluster).getJob(id);
}
@Test
public void testSetupTaskReportsWithNullJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
Cluster mockCluster = mock(Cluster.class);
client.setCluster(mockCluster);
JobID id = new JobID("test",0);
when(mockCluster.getJob(id)).thenReturn(null);
TaskReport[] result = client.getSetupTaskReports(id);
assertEquals(0, result.length);
verify(mockCluster).getJob(id);
}
@Test
public void testCleanupTaskReportsWithNullJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
Cluster mockCluster = mock(Cluster.class);
client.setCluster(mockCluster);
JobID id = new JobID("test",0);
when(mockCluster.getJob(id)).thenReturn(null);
TaskReport[] result = client.getCleanupTaskReports(id);
assertEquals(0, result.length);
verify(mockCluster).getJob(id);
}
@Test
public void testShowJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
long startTime = System.currentTimeMillis();
JobID jobID = new JobID(String.valueOf(startTime), 12345);
JobStatus mockJobStatus = mock(JobStatus.class);
when(mockJobStatus.getJobID()).thenReturn(jobID);
when(mockJobStatus.getJobName()).thenReturn(jobID.toString());
when(mockJobStatus.getState()).thenReturn(JobStatus.State.RUNNING);
when(mockJobStatus.getStartTime()).thenReturn(startTime);
when(mockJobStatus.getUsername()).thenReturn("mockuser");
when(mockJobStatus.getQueue()).thenReturn("mockqueue");
when(mockJobStatus.getPriority()).thenReturn(JobPriority.NORMAL);
when(mockJobStatus.getNumUsedSlots()).thenReturn(1);
when(mockJobStatus.getNumReservedSlots()).thenReturn(1);
when(mockJobStatus.getUsedMem()).thenReturn(1024L);
when(mockJobStatus.getReservedMem()).thenReturn(512L);
when(mockJobStatus.getNeededMem()).thenReturn(2048L);
when(mockJobStatus.getSchedulingInfo()).thenReturn("NA");
Job mockJob = mock(Job.class);
when(mockJob.getTaskReports(isA(TaskType.class))).thenReturn(
new TaskReport[5]);
Cluster mockCluster = mock(Cluster.class);
when(mockCluster.getJob(jobID)).thenReturn(mockJob);
client.setCluster(mockCluster);
ByteArrayOutputStream out = new ByteArrayOutputStream();
client.displayJobList(new JobStatus[] {mockJobStatus}, new PrintWriter(out));
String commandLineOutput = out.toString();
System.out.println(commandLineOutput);
Assert.assertTrue(commandLineOutput.contains("Total jobs:1"));
verify(mockJobStatus, atLeastOnce()).getJobID();
verify(mockJobStatus).getState();
verify(mockJobStatus).getStartTime();
verify(mockJobStatus).getUsername();
verify(mockJobStatus).getQueue();
verify(mockJobStatus).getPriority();
verify(mockJobStatus).getNumUsedSlots();
verify(mockJobStatus).getNumReservedSlots();
verify(mockJobStatus).getUsedMem();
verify(mockJobStatus).getReservedMem();
verify(mockJobStatus).getNeededMem();
verify(mockJobStatus).getSchedulingInfo();
// This call should not go to each AM.
verify(mockCluster, never()).getJob(jobID);
verify(mockJob, never()).getTaskReports(isA(TaskType.class));
}
@Test
public void testGetJobWithUnknownJob() throws Exception {
TestJobClient client = new TestJobClient(new JobConf());
Cluster mockCluster = mock(Cluster.class);
client.setCluster(mockCluster);
JobID id = new JobID("unknown",0);
when(mockCluster.getJob(id)).thenReturn(null);
assertNull(client.getJob(id));
}
@Test
public void testGetJobRetry() throws Exception {
//To prevent the test from running for a very long time, lower the retry
JobConf conf = new JobConf();
conf.setInt(MRJobConfig.MR_CLIENT_JOB_MAX_RETRIES, 2);
TestJobClientGetJob client = new TestJobClientGetJob(conf);
JobID id = new JobID("ajob", 1);
RunningJob rj = mock(RunningJob.class);
client.setRunningJob(rj);
//no retry
assertNotNull(client.getJob(id));
assertEquals(client.getLastGetJobRetriesCounter(), 0);
//2 retries
client.setGetJobRetries(2);
assertNotNull(client.getJob(id));
assertEquals(client.getLastGetJobRetriesCounter(), 2);
//beyond yarn.app.mapreduce.client.job.max-retries, will get null
client.setGetJobRetries(3);
assertNull(client.getJob(id));
}
@Test
public void testGetJobRetryDefault() throws Exception {
//To prevent the test from running for a very long time, lower the retry
JobConf conf = new JobConf();
TestJobClientGetJob client = new TestJobClientGetJob(conf);
JobID id = new JobID("ajob", 1);
RunningJob rj = mock(RunningJob.class);
client.setRunningJob(rj);
//3 retries (default)
client.setGetJobRetries(MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES);
assertNotNull(client.getJob(id));
assertEquals(client.getLastGetJobRetriesCounter(),
MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES);
//beyond yarn.app.mapreduce.client.job.max-retries, will get null
client.setGetJobRetries(MRJobConfig.DEFAULT_MR_CLIENT_JOB_MAX_RETRIES + 1);
assertNull(client.getJob(id));
}
}
| jaypatil/hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/JobClientUnitTest.java | Java | gpl-3.0 | 8,988 |
/*
* DynamicJava - Copyright (C) 1999 Dyade
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: The above copyright notice and this
* permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL DYADE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of Dyade shall not be used in advertising or
* otherwise to promote the sale, use or other dealings in this Software without prior written
* authorization from Dyade.
*/
package koala.dynamicjava.tree;
/**
* This class represents the character literal nodes of the syntax tree
*
* @author Stephane Hillion
* @version 1.0 - 1999/04/24
*/
public class CharacterLiteral extends Literal {
/**
* Initializes a literal
*
* @param rep the representation of the literal
* @param val the value of this literal
*/
public CharacterLiteral(final String rep) {
this(rep, null, 0, 0, 0, 0);
}
/**
* Initializes a literal
*
* @param rep the representation of the literal
* @param val the value of this literal
* @param fn the filename
* @param bl the begin line
* @param bc the begin column
* @param el the end line
* @param ec the end column
*/
public CharacterLiteral(final String rep, final String fn, final int bl, final int bc, final int el, final int ec) {
super(rep, new Character(decodeCharacter(rep)), char.class, fn, bl, bc, el, ec);
}
/**
* Decodes the representation of a Java literal character. The input is not checked since this
* method always called on a string produced by the parser.
*
* @param rep the representation of the character
* @return the character represented by the given string
*/
private static char decodeCharacter(final String rep) {
if (rep.length() == 3) {
return rep.charAt(1);
}
char c;
// Assume that charAt(1) == '\\' and length > 3
switch (c = rep.charAt(2)) {
case 'n':
return '\n';
case 't':
return '\t';
case 'b':
return '\b';
case 'r':
return '\r';
case 'f':
return '\f';
default:
if (Character.isDigit(c)) {
int v = 0;
for (int i = 2; i < rep.length() - 1; i++) {
v = v * 7 + Integer.parseInt("" + rep.charAt(i));
}
return (char) v;
} else {
return c;
}
}
}
}
| mbshopM/openconcerto | OpenConcerto/src/koala/dynamicjava/tree/CharacterLiteral.java | Java | gpl-3.0 | 3,495 |
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.oaipmh.responses;
import java.util.ArrayList;
import java.util.List;
import org.fao.oaipmh.OaiPmh;
import org.fao.oaipmh.util.ISODate;
import org.fao.oaipmh.util.Lib;
import org.jdom.Element;
//=============================================================================
public class Header {
private String identifier;
private ISODate dateStamp;
private boolean deleted;
private List<String> sets = new ArrayList<String>();
/**
* Default constructor.
* Builds a Header.
*/
public Header() {}
//---------------------------------------------------------------------------
public Header(Element header)
{
build(header);
}
//---------------------------------------------------------------------------
//---
//--- API methods
//---
//---------------------------------------------------------------------------
public String getIdentifier() { return identifier; }
public ISODate getDateStamp() { return dateStamp; }
public boolean isDeleted() { return deleted; }
//---------------------------------------------------------------------------
public List<String> getSets() {
return sets;
}
//---------------------------------------------------------------------------
public void setIdentifier(String identifier)
{
this.identifier = identifier;
}
//---------------------------------------------------------------------------
public void setDateStamp(ISODate dateStamp)
{
this.dateStamp = dateStamp;
}
//---------------------------------------------------------------------------
public void clearSets()
{
sets.clear();
}
//---------------------------------------------------------------------------
public void addSet(String set)
{
sets.add(set);
}
//---------------------------------------------------------------------------
public void setDeleted(boolean yesno)
{
deleted = yesno;
}
//---------------------------------------------------------------------------
public Element toXml()
{
Element header = new Element("header", OaiPmh.Namespaces.OAI_PMH);
Lib.add(header, "identifier", identifier);
Lib.add(header, "datestamp", dateStamp +"Z");
for (String set : sets)
Lib.add(header, "setSpec", set);
if (deleted)
header.setAttribute("status", "deleted");
return header;
}
//---------------------------------------------------------------------------
//---
//--- Private methods
//---
//---------------------------------------------------------------------------
private void build(Element header)
{
Element ident = header.getChild("identifier", OaiPmh.Namespaces.OAI_PMH);
Element date = header.getChild("datestamp", OaiPmh.Namespaces.OAI_PMH);
String status = header.getAttributeValue("status");
//--- store identifier & dateStamp
identifier = ident.getText();
dateStamp = new ISODate(date.getText());
deleted = (status != null);
//--- add set information
for (Object o : header.getChildren("setSpec", OaiPmh.Namespaces.OAI_PMH))
{
Element set = (Element) o;
sets.add(set.getText());
}
}
}
//=============================================================================
| OpenWIS/openwis | openwis-metadataportal/oaipmh/src/main/java/org/fao/oaipmh/responses/Header.java | Java | gpl-3.0 | 4,428 |
/*
* jFCPlib - ARK.java - Copyright © 2008 David Roden
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.pterodactylus.fcp;
/**
* Container for ARKs (address resolution keys).
*
* @author David ‘Bombe’ Roden <[email protected]>
*/
public class ARK {
/** The public URI of the ARK. */
private final String publicURI;
/** The private URI of the ARK. */
private final String privateURI;
/** The number of the ARK. */
private final int number;
/**
* Creates a new ARK with the given URI and number.
*
* @param publicURI
* The public URI of the ARK
* @param number
* The number of the ARK
*/
public ARK(String publicURI, String number) {
this(publicURI, null, number);
}
/**
* Creates a new ARK with the given URIs and number.
*
* @param publicURI
* The public URI of the ARK
* @param privateURI
* The private URI of the ARK
* @param number
* The number of the ARK
*/
public ARK(String publicURI, String privateURI, String number) {
if ((publicURI == null) || (number == null)) {
throw new NullPointerException(((publicURI == null) ? "publicURI" : "number") + " must not be null");
}
this.publicURI = publicURI;
this.privateURI = privateURI;
try {
this.number = Integer.valueOf(number);
} catch (NumberFormatException nfe1) {
throw new IllegalArgumentException("number must be numeric", nfe1);
}
}
/**
* Returns the public URI of the ARK.
*
* @return The public URI of the ARK
*/
public String getPublicURI() {
return publicURI;
}
/**
* Returns the private URI of the ARK.
*
* @return The private URI of the ARK
*/
public String getPrivateURI() {
return privateURI;
}
/**
* Returns the number of the ARK.
*
* @return The number of the ARK
*/
public int getNumber() {
return number;
}
}
| louboco/Icicle | app/src/main/java/net/pterodactylus/fcp/ARK.java | Java | gpl-3.0 | 2,561 |
package cn.nukkit.inventory;
public interface InventoryNetworkId {
public final static int WINDOW_INVENTORY = -1;
public final static int WINDOW_CONTAINER = 0;
public final static int WINDOW_WORKBENCH = 1;
public final static int WINDOW_FURNACE = 2;
public final static int WINDOW_ENCHANTMENT = 3;
public final static int WINDOW_BREWING_STAND = 4;
public final static int WINDOW_ANVIL = 5;
public final static int WINDOW_DISPENSER = 6;
public final static int WINDOW_DROPPER = 7;
public final static int WINDOW_HOPPER = 8;
public final static int WINDOW_CAULDRON = 9;
public final static int WINDOW_MINECART_CHEST = 10;
public final static int WINDOW_MINECART_HOPPER = 11;
public final static int WINDOW_HORSE = 12;
public final static int WINDOW_BEACON = 13;
public final static int WINDOW_STRUCTURE_EDITOR = 14;
public final static int WINDOW_TRADING = 15;
public final static int WINDOW_COMMAND_BLOCK = 16;
} | JupiterDevelopmentTeam/JupiterDevelopmentTeam | src/main/java/cn/nukkit/inventory/InventoryNetworkId.java | Java | gpl-3.0 | 985 |
package com.forgeessentials.core.misc;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerStopEvent;
import com.forgeessentials.util.events.ServerEventHandler;
import com.forgeessentials.util.output.LoggingHandler;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class TaskRegistry extends ServerEventHandler
{
public static class RunLaterTimerTask extends TimerTask
{
private boolean taskRunning = false;
private Runnable task;
public RunLaterTimerTask(Runnable task)
{
this.task = task;
}
@Override
public void run()
{
if (taskRunning)
return;
taskRunning = true;
TaskRegistry.runLater(() ->
{
try
{
task.run();
}
finally
{
taskRunning = false;
}
});
}
}
public static interface TickTask
{
public boolean tick();
public boolean editsBlocks();
}
private static TaskRegistry instance;
public static int MAX_BLOCK_TASKS = 6;
protected static ConcurrentLinkedQueue<TickTask> tickTasks = new ConcurrentLinkedQueue<>();
protected static ConcurrentLinkedQueue<Runnable> runLater = new ConcurrentLinkedQueue<>();
protected static Timer timer = new Timer();
protected static Map<Runnable, TimerTask> runnableTasks = new WeakHashMap<>();
/* ------------------------------------------------------------ */
public TaskRegistry()
{
super();
instance = this;
}
public static TaskRegistry getInstance()
{
return instance;
}
@SubscribeEvent
public void onServerStop(FEModuleServerStopEvent event)
{
tickTasks.clear();
runnableTasks.clear();
timer.cancel();
timer = new Timer(true);
}
/* ------------------------------------------------------------ */
public static void schedule(TickTask task)
{
tickTasks.add(task);
}
public static void remove(TickTask task)
{
tickTasks.remove(task);
}
public static void runLater(Runnable task)
{
runLater.add(task);
}
@SubscribeEvent
public void onTick(TickEvent.ServerTickEvent event)
{
for (Runnable task : runLater)
task.run();
runLater.clear();
int blockTaskCount = 0;
for (Iterator<TickTask> iterator = tickTasks.iterator(); iterator.hasNext(); )
{
TickTask task = iterator.next();
if (task.editsBlocks())
{
if (blockTaskCount >= MAX_BLOCK_TASKS)
continue;
blockTaskCount++;
}
if (task.tick())
iterator.remove();
}
}
/* ------------------------------------------------------------ */
/* Timers */
public static void schedule(TimerTask task, long delay)
{
try
{
timer.schedule(task, delay);
}
catch (IllegalStateException e)
{
LoggingHandler.felog.warn("Could not schedule timer");
e.printStackTrace();
}
}
public static void scheduleRepeated(TimerTask task, long delay, long interval)
{
try
{
timer.scheduleAtFixedRate(task, delay, interval);
}
catch (IllegalStateException e)
{
LoggingHandler.felog.warn("Exception scheduling timer");
e.printStackTrace();
}
}
public static void scheduleRepeated(TimerTask task, long interval)
{
scheduleRepeated(task, interval, interval);
}
public static void remove(TimerTask task)
{
task.cancel();
timer.purge();
}
/* ------------------------------------------------------------ */
/* Runnable compatibility */
protected static TimerTask getTimerTask(final Runnable task, final boolean repeated)
{
TimerTask timerTask = runnableTasks.get(task);
if (timerTask == null)
{
timerTask = new TimerTask()
{
@Override
public void run()
{
task.run();
if (!repeated)
runnableTasks.remove(task);
}
};
runnableTasks.put(task, timerTask);
}
return timerTask;
}
public static void schedule(Runnable task, long delay)
{
schedule(getTimerTask(task, false), delay);
}
public static void scheduleRepeated(Runnable task, long interval)
{
scheduleRepeated(task, interval, interval);
}
public static void scheduleRepeated(Runnable task, long delay, long interval)
{
scheduleRepeated(getTimerTask(task, true), delay, interval);
}
public static void remove(Runnable task)
{
TimerTask timerTask = runnableTasks.remove(task);
if (timerTask != null)
remove(timerTask);
}
/* ------------------------------------------------------------ */
public static long getMilliseconds(int h, int m, int s, int ms)
{
return ((h * 60 + m) * 60 + s) * 1000 + ms;
}
}
| ForgeEssentials/ForgeEssentials | src/main/java/com/forgeessentials/core/misc/TaskRegistry.java | Java | gpl-3.0 | 5,652 |
/*
###############################################################################
# #
# Copyright (C) 2011-2016 OpenMEAP, Inc. #
# Credits to Jonathan Schang & Rob Thacher #
# #
# Released under the LGPLv3 #
# #
# OpenMEAP 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. #
# #
# OpenMEAP 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 OpenMEAP. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
*/
package com.openmeap.samples.banking.web.model;
import javax.xml.bind.*;
import org.junit.*;
public class BankingServiceTest {
@Test public void testGetInstance() {
BankingService instance = BankingService.getInstance();
Assert.assertTrue(instance!=null);
Assert.assertTrue(instance==BankingService.getInstance());
}
@Test public void testGetAccounts() {
BankingService instance = BankingService.getInstance();
LoginResult res = instance.login("Jon Doe", "password");
Assert.assertTrue(res!=null);
Assert.assertTrue(res.getAccounts()!=null && res.getAccounts().getAccount().size()==2 );
Account checking = res.getAccounts().getAccount().get(0);
Account savings = res.getAccounts().getAccount().get(1);
Assert.assertTrue(checking.getPosted().equals(checking.getAvailable()));
Assert.assertTrue(savings.getPosted().equals(savings.getAvailable()));
res = instance.login("Not Existing", "password");
Assert.assertTrue(res==null);
}
/*@Test public void test() throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance("com.openmeap.samples.banking.web.model");
Marshaller m = jaxbContext.createMarshaller();
Result result = new Result();
result.setLoginResult(BankingService.getInstance().login("Jon Doe","password"));
m.marshal(result, System.out);
}*/
}
| thacher/OpenMEAP | samples/banking/banking-web/test/com/openmeap/samples/banking/web/model/BankingServiceTest.java | Java | gpl-3.0 | 3,074 |
/*
* Copyright (C) 2010-2021 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr 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.
*
* Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.core.function;
import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.structr.common.error.ArgumentCountException;
import org.structr.common.error.ArgumentNullException;
import org.structr.common.error.FrameworkException;
import org.structr.schema.action.ActionContext;
import org.w3c.dom.Document;
public class XPathFunction extends AdvancedScriptingFunction {
public static final String ERROR_MESSAGE_XPATH = "Usage: ${xpath(xmlDocument, expression, returnType)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\" [, \"STRING\"])}";
@Override
public String getName() {
return "xpath";
}
@Override
public String getSignature() {
return "document, xpath [, returnType ]";
}
@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
try {
assertArrayHasMinLengthAndAllElementsNotNull(sources, 2);
if (sources[0] instanceof Document) {
try {
final XPath xpath = XPathFactory.newInstance().newXPath();
QName returnType = XPathConstants.STRING;
if (sources.length == 3 && sources[2] instanceof String) {
returnType = new QName("http://www.w3.org/1999/XSL/Transform", (String) sources[2]);
}
return xpath.evaluate(sources[1].toString(), sources[0], returnType);
} catch (XPathExpressionException ioex) {
logException(caller, ioex, sources);
return null;
}
}
} catch (ArgumentNullException pe) {
// silently ignore null arguments
} catch (ArgumentCountException pe) {
logParameterError(caller, sources, pe.getMessage(), ctx.isJavaScriptContext());
return usage(ctx.isJavaScriptContext());
}
return null;
}
@Override
public String usage(boolean inJavaScriptContext) {
return ERROR_MESSAGE_XPATH;
}
@Override
public String shortDescription() {
return "Returns the value of the given XPath expression from the given XML DOM. The optional third parameter defines the return type, possible values are: NUMBER, STRING, BOOLEAN, NODESET, NODE, default is STRING.";
}
}
| ckramp/structr | structr-core/src/main/java/org/structr/core/function/XPathFunction.java | Java | gpl-3.0 | 2,966 |
// .//GEN-BEGIN:1_be
/******************************************************
* Code Generated From JAFFA Framework Default Pattern
*
* The JAFFA Project can be found at http://jaffa.sourceforge.net
* and is available under the Lesser GNU Public License
******************************************************/
package org.jaffa.applications.test.modules.time.domain;
import org.jaffa.metadata.*;
import java.util.*;
// .//GEN-END:1_be
// Add additional imports//GEN-FIRST:imports
// .//GEN-LAST:imports
// .//GEN-BEGIN:2_be
/** This class has the meta information for the TaskCode persistent class.
*/
public class TaskCodeMeta {
// domain-object class name
private static String m_name = "org.jaffa.applications.test.modules.time.domain.TaskCode";
// token to be used for getting the label for the domain-object
private static String m_labelToken = "[label.Jaffa.Time.TaskCode]";
// Field constants
/** A constant to identity the Task field.*/
public static final String TASK = "Task";
/** A constant to identity the Activity field.*/
public static final String ACTIVITY = "Activity";
/** A constant to identity the Description field.*/
public static final String DESCRIPTION = "Description";
// Meta Data Definitions
/** A constant which holds the meta information for the Task field.*/
public static final FieldMetaData META_TASK = new StringFieldMetaData(TASK, "[label.Jaffa.Admin.Time.TaskCode.Task]", Boolean.TRUE, null, new Integer(50), FieldMetaData.MIXED_CASE);
/** A constant which holds the meta information for the Activity field.*/
public static final FieldMetaData META_ACTIVITY = new StringFieldMetaData(ACTIVITY, "[label.Jaffa.Admin.Time.ActivityCode.Activity]", Boolean.TRUE, null, new Integer(50), FieldMetaData.MIXED_CASE);
/** A constant which holds the meta information for the Description field.*/
public static final FieldMetaData META_DESCRIPTION = new StringFieldMetaData(DESCRIPTION, "[label.Jaffa.Admin.Time.TaskCode.Description]", Boolean.TRUE, null, new Integer(50), FieldMetaData.MIXED_CASE);
// Map of FieldConstants + MetaDataDefinitions
private static Map m_fieldMap = new HashMap();
static {
m_fieldMap.put(TASK, META_TASK);
m_fieldMap.put(ACTIVITY, META_ACTIVITY);
m_fieldMap.put(DESCRIPTION, META_DESCRIPTION);
}
// List of MetaDataDefinitions for key fields
private static List m_keyFields = new LinkedList();
static {
m_keyFields.add(META_TASK);
}
// List of MetaDataDefinitions for mandatory fields
private static List m_mandatoryFields = new LinkedList();
static {
m_mandatoryFields.add(META_TASK);
m_mandatoryFields.add(META_ACTIVITY);
m_mandatoryFields.add(META_DESCRIPTION);
}
/** Returns the name of the persistent class.
* @return the name of the persistent class.
*/
public static String getName() {
return m_name;
}
/** Getter for property labelToken.
* @return Value of property labelToken.
*/
public static String getLabelToken() {
return m_labelToken;
}
/** This returns an array of all the fields of the persistent class.
* @return an array of all the fields of the persistent class.
*/
public static String[] getAttributes() {
return DomainMetaDataHelper.getAttributes(m_fieldMap);
}
/** This returns an array of meta information for all the fields of the persistent class.
* @return an array of meta information for all the fields of the persistent class.
*/
public static FieldMetaData[] getFieldMetaData() {
return DomainMetaDataHelper.getFieldMetaData(m_fieldMap);
}
/** This returns meta information for the input field.
* @param fieldName the field name.
* @return meta information for the input field.
*/
public static FieldMetaData getFieldMetaData(String fieldName) {
return DomainMetaDataHelper.getFieldMetaData(m_fieldMap, fieldName);
}
/** This returns an array of meta information for all the key fields of the persistent class.
* @return an array of meta information for all the key fields of the persistent class.
*/
public static FieldMetaData[] getKeyFields() {
return (FieldMetaData[]) m_keyFields.toArray(new FieldMetaData[0]);
}
/** This returns an array of meta information for all the mandatory fields of the persistent class.
* @return an array of meta information for all the mandatory fields of the persistent class.
*/
public static FieldMetaData[] getMandatoryFields() {
return (FieldMetaData[]) m_mandatoryFields.toArray(new FieldMetaData[0]);
}
// .//GEN-END:2_be
// All the custom code goes here//GEN-FIRST:custom
// .//GEN-LAST:custom
}
| snavaneethan1/jaffa-framework | jaffa-core/source/httpunittest/java/org/jaffa/applications/test/modules/time/domain/TaskCodeMeta.java | Java | gpl-3.0 | 4,914 |
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile 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.
*
* TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.ui;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import com.dalthed.tucan.R;
import com.dalthed.tucan.TuCanMobileActivity;
import com.dalthed.tucan.TucanMobile;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.Connection.CookieManager;
import com.dalthed.tucan.Connection.RequestObject;
import com.dalthed.tucan.Connection.SimpleSecureBrowser;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import com.dalthed.tucan.scraper.BasicScraper;
import com.dalthed.tucan.scraper.EventsScraper;
import com.dalthed.tucan.util.ConfigurationChangeStorage;
/**
* Displays the Events Menu
*
* @author Daniel Thiem
*
*/
public class Events extends SimpleWebListActivity {
private CookieManager localCookieManager;
private static final String LOG_TAG = "TuCanMobile";
private String URLStringtoCall;
/**
* Modus der Seite:<br>
* 0: Startseite<br>
* 1: Veranstaltungen<br>
* 2: Anmeldung zu Veranstaltungen<br>
* 10: Module
*/
private int mode = 0;
private EventsScraper scrape;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Standart procedure: Loading URL from Intent
super.onCreate(savedInstanceState, true, 2);
setContentView(R.layout.events);
String CookieHTTPString = getIntent().getExtras().getString("Cookie");
URLStringtoCall = getIntent().getExtras().getString("URL");
URL URLtoCall;
try {
URLtoCall = new URL(URLStringtoCall);
localCookieManager = new CookieManager();
localCookieManager.generateManagerfromHTTPString(URLtoCall.getHost(), CookieHTTPString);
callResultBrowser = new SimpleSecureBrowser(this);
RequestObject thisRequest = new RequestObject(URLStringtoCall, localCookieManager,
RequestObject.METHOD_GET, "");
callResultBrowser.execute(thisRequest);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, e.getMessage());
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.events);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// When Item is clicked, a new Request will start
SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser(this);
RequestObject thisRequest;
if (scrape != null) {
if (mode == 0 && scrape.eventLinks != null) {
// Modus overview
switch (position) {
case 0:
// Klick auf Module
mode = 10;
thisRequest = new RequestObject(TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST
+ scrape.eventLinks.get(0), scrape.getCookieManager(),
RequestObject.METHOD_GET, "");
callOverviewBrowser.execute(thisRequest);
break;
case 1:
// Klick auf Veranstaltungen
mode = 1;
thisRequest = new RequestObject(TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST
+ scrape.eventLinks.get(1), scrape.getCookieManager(),
RequestObject.METHOD_GET, "");
callOverviewBrowser.execute(thisRequest);
break;
case 2:
// Klick auf Anmeldung
mode = 2;
thisRequest = new RequestObject(TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST
+ scrape.eventLinks.get(2), scrape.getCookieManager(),
RequestObject.METHOD_GET, "");
callOverviewBrowser.execute(thisRequest);
break;
}
} else if (mode == 1 && scrape.eventLink != null) {
Intent StartSingleEventIntent = new Intent(Events.this, FragmentSingleEvent.class);
StartSingleEventIntent.putExtra(TucanMobile.EXTRA_URL, TucanMobile.TUCAN_PROT
+ TucanMobile.TUCAN_HOST + scrape.eventLink.get(position));
StartSingleEventIntent.putExtra(TucanMobile.EXTRA_COOKIE, scrape.getCookieManager()
.getCookieHTTPString(TucanMobile.TUCAN_HOST));
// StartSingleEventIntent.putExtra("UserName", UserName);
startActivity(StartSingleEventIntent);
} else if (mode == 2 && scrape.applyLink != null) {
if (position < scrape.applyLink.size()) {
thisRequest = new RequestObject(TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST
+ scrape.applyLink.get(position), scrape.getCookieManager(),
RequestObject.METHOD_GET, "");
callOverviewBrowser.execute(thisRequest);
}
} else if (mode == 10 && scrape.eventLink != null) {
Intent StartModuleIntent = new Intent(Events.this, Module.class);
StartModuleIntent.putExtra(TucanMobile.EXTRA_URL, TucanMobile.TUCAN_PROT
+ TucanMobile.TUCAN_HOST + scrape.eventLink.get(position));
StartModuleIntent.putExtra(TucanMobile.EXTRA_COOKIE,
localCookieManager.getCookieHTTPString(TucanMobile.TUCAN_HOST));
startActivity(StartModuleIntent);
}
}
}
public void onPostExecute(AnswerObject result) {
// Start Tracing zur geschwindigkeitsberschleunigung
// HTML Parsen
if (scrape == null) {
scrape = new EventsScraper(this, result);
} else {
scrape.setNewAnswer(result);
}
try {
setListAdapter(scrape.scrapeAdapter(mode));
} catch (LostSessionException e) {
Intent BackToLoginIntent = new Intent(this, TuCanMobileActivity.class);
BackToLoginIntent.putExtra("lostSession", true);
startActivity(BackToLoginIntent);
} catch (TucanDownException e) {
TucanMobile.alertOnTucanDown(this, e.getMessage());
}
// Stop tracing
setFastSwitchSubtites();
setSpinner();
}
/**
*
*/
private void setSpinner() {
if (mode != 0 && mode != 2) {
Spinner semesterSpinner = (Spinner) findViewById(R.id.exam_semester_spinner);
semesterSpinner.setVisibility(View.VISIBLE);
semesterSpinner.setAdapter(scrape.spinnerAdapter());
semesterSpinner.setSelection(scrape.SemesterOptionSelected);
semesterSpinner.setOnItemSelectedListener(new OnItemSelectedListener());
}
}
/**
*
*/
private void setFastSwitchSubtites() {
if (mode == 0) {
fsh.setSubtitle(getResources().getText(R.string.events_subtitle));
} else if (mode == 1) {
fsh.setSubtitle(getResources().getText(R.string.events_subtitle_events));
} else if (mode == 2) {
fsh.setSubtitle(getResources().getText(R.string.events_subtitle_register));
} else if (mode == 10) {
fsh.setSubtitle(getResources().getText(R.string.events_subtitle_modules));
}
}
public class OnItemSelectedListener implements
android.widget.AdapterView.OnItemSelectedListener {
int hitcount = 0;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (hitcount == 0) {
} else {
if (mode == 10) {
RequestObject thisRequest = new RequestObject(TucanMobile.TUCAN_PROT
+ TucanMobile.TUCAN_HOST + scrape.eventLinks.get(0) + "-N"
+ scrape.SemesterOptionValue.get(position), localCookieManager,
RequestObject.METHOD_GET, "");
SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser(Events.this);
callOverviewBrowser.execute(thisRequest);
} else if (mode == 1) {
RequestObject thisRequest = new RequestObject(TucanMobile.TUCAN_PROT
+ TucanMobile.TUCAN_HOST + scrape.eventLinks.get(1) + "-N"
+ scrape.SemesterOptionValue.get(position), localCookieManager,
RequestObject.METHOD_GET, "");
SimpleSecureBrowser callOverviewBrowser = new SimpleSecureBrowser(Events.this);
callOverviewBrowser.execute(thisRequest);
}
}
hitcount++;
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && mode != 0) {
@SuppressWarnings("unchecked")
ArrayList<String> eventNameBuffer = (ArrayList<String>) scrape.eventNames.clone();
ArrayAdapter<String> ListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, eventNameBuffer);
// Log.i(LOG_TAG,"Exam Names hat: "+examNames.size()+" Elemente");
setListAdapter(ListAdapter);
mode = 0;
Spinner semesterSpinner = (Spinner) findViewById(R.id.exam_semester_spinner);
semesterSpinner.setVisibility(View.GONE);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public ConfigurationChangeStorage saveConfiguration() {
ConfigurationChangeStorage cStore = new ConfigurationChangeStorage();
cStore.adapters.add(getListAdapter());
cStore.addScraper(scrape);
cStore.mode = mode;
return cStore;
}
@Override
public void retainConfiguration(ConfigurationChangeStorage conf) {
setListAdapter(conf.adapters.get(0));
BasicScraper retainedScraper = conf.getScraper(0, this);
if (retainedScraper instanceof EventsScraper) {
scrape = (EventsScraper) retainedScraper;
}
mode = conf.mode;
setSpinner();
setFastSwitchSubtites();
}
}
| pradeepb6/TuCanMobile | app/src/main/java/com/dalthed/tucan/ui/Events.java | Java | gpl-3.0 | 9,807 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
package org.opensplice.dds.core.event;
import org.omg.dds.core.ServiceEnvironment;
import org.omg.dds.core.event.LivelinessLostEvent;
import org.omg.dds.core.status.LivelinessLostStatus;
import org.omg.dds.pub.DataWriter;
import org.opensplice.dds.core.OsplServiceEnvironment;
public class LivelinessLostEventImpl<TYPE> extends LivelinessLostEvent<TYPE> {
private static final long serialVersionUID = -2199224454283393818L;
private final transient OsplServiceEnvironment environment;
private final LivelinessLostStatus status;
public LivelinessLostEventImpl(OsplServiceEnvironment environment,
DataWriter<TYPE> source, LivelinessLostStatus status) {
super(source);
this.environment = environment;
this.status = status;
}
@Override
public ServiceEnvironment getEnvironment() {
return this.environment;
}
@Override
public LivelinessLostStatus getStatus() {
return this.status;
}
@Override
public LivelinessLostEvent<TYPE> clone() {
return new LivelinessLostEventImpl<TYPE>(this.environment,
this.getSource(), this.status);
}
@SuppressWarnings("unchecked")
@Override
public DataWriter<TYPE> getSource() {
return (DataWriter<TYPE>) this.source;
}
}
| PrismTech/opensplice | src/api/dcps/java5/common/java/code/org/opensplice/dds/core/event/LivelinessLostEventImpl.java | Java | gpl-3.0 | 2,108 |
package com.eveningoutpost.dexdrip.ui.activities;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.databinding.Observable;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.eveningoutpost.dexdrip.BR;
import com.eveningoutpost.dexdrip.MegaStatus;
import com.eveningoutpost.dexdrip.Models.JoH;
import com.eveningoutpost.dexdrip.Models.UserError;
import com.eveningoutpost.dexdrip.R;
import com.eveningoutpost.dexdrip.UtilityModels.Inevitable;
import com.eveningoutpost.dexdrip.UtilityModels.PersistentStore;
import com.eveningoutpost.dexdrip.UtilityModels.Pref;
import com.eveningoutpost.dexdrip.databinding.ActivityThinJamBinding;
import com.eveningoutpost.dexdrip.ui.dialog.GenericConfirmDialog;
import com.eveningoutpost.dexdrip.ui.dialog.QuickSettingsDialogs;
import com.eveningoutpost.dexdrip.utils.AndroidBarcode;
import com.eveningoutpost.dexdrip.utils.LocationHelper;
import com.eveningoutpost.dexdrip.utils.Preferences;
import com.eveningoutpost.dexdrip.utils.bt.BtCallBack2;
import com.eveningoutpost.dexdrip.utils.bt.ScanMeister;
import com.eveningoutpost.dexdrip.watch.thinjam.BlueJay;
import com.eveningoutpost.dexdrip.watch.thinjam.BlueJayEntry;
import com.eveningoutpost.dexdrip.watch.thinjam.BlueJayService;
import com.eveningoutpost.dexdrip.xdrip;
import com.google.zxing.integration.android.IntentIntegrator;
import com.polidea.rxandroidble2.scan.ScanFilter;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.val;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import static com.eveningoutpost.dexdrip.watch.thinjam.Const.THINJAM_HUNT_MASK_STRING;
import static com.eveningoutpost.dexdrip.watch.thinjam.Const.THINJAM_HUNT_SERVICE_STRING;
// jamorham
public class ThinJamActivity extends AppCompatActivity implements BtCallBack2, ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = "ThinJamActivity";
private static final String THINJAM_ACTIVITY_COMMAND = "THINJAM_ACTIVITY_COMMAND";
private static final String REFRESH_FROM_STORED_MAC = "REFRESH_FROM_STORED_MAC";
private static final String INSTALL_CORE = "INSTALL_CORE";
private static final String UPDATE_CORE = "UPDATE_CORE";
private static final String UPDATE_MAIN = "UPDATE_MAIN";
private static final String REQUEST_QR = "REQUEST_QR";
private static final String SCAN_QR = "SCAN_QR";
@Getter
private static final boolean D = false;
private ActivityThinJamBinding binding;
private final ScanMeister scanMeister = new ScanMeister();
private final ScanFilter customFilter = new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString(THINJAM_HUNT_SERVICE_STRING), ParcelUuid.fromString(THINJAM_HUNT_MASK_STRING)).build();
private final ScanFilter nullFilter = new ScanFilter.Builder().build();
private BlueJayService thinJam;
private boolean mBound = false;
private volatile Bundle savedExtras = null;
private final Observable.OnPropertyChangedCallback changeRelayAdapter = new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
binding.getVm().textWindow.set(((ObservableField<String>) sender).get());
}
};
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
final BlueJayService.LocalBinder binder = (BlueJayService.LocalBinder) service;
thinJam = binder.getService();
thinJam.stringObservableField.removeOnPropertyChangedCallback(changeRelayAdapter);
thinJam.stringObservableField.addOnPropertyChangedCallback(changeRelayAdapter); // TODO can this leak? Better way to use same observable field?
mBound = true;
UserError.Log.d(TAG, "Connected to service");
processIncomingBundle(savedExtras);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityThinJamBinding.inflate(getLayoutInflater());
binding.setVm(new ViewModel(this));
setContentView(binding.getRoot());
JoH.fixActionBar(this);
scanMeister.setFilter(customFilter);
scanMeister.allowWide().unlimitedMatches();
scanMeister.addCallBack2(this, TAG);
((TextView) findViewById(R.id.tjLogText)).setMovementMethod(new ScrollingMovementMethod());
// handle incoming extras - TODO do we need to wait for service connect?
final Bundle bundle = getIntent().getExtras();
processIncomingBundle(bundle);
LocationHelper.requestLocationForBluetooth(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_thinjam, menu);
return true;
}
public void blueJayPowerStandby(MenuItem x) {
GenericConfirmDialog.show(this, "Confirm Standby",
"Are you sure you want to put the watch in to Standby mode?\n\nLong Press Watch Button to wake it again.",
() -> {
// call standby
thinJam.standby();
});
}
@Override
protected void onStart() {
super.onStart();
bindService();
}
private void bindService() {
final Intent intent = new Intent(this, BlueJayService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
thinJam.stringObservableField.removeOnPropertyChangedCallback(changeRelayAdapter);
unbindService(connection);
mBound = false;
super.onStop();
}
@Override
public void onNewIntent(Intent intent) {
Bundle bundle = intent.getExtras();
processIncomingBundle(bundle);
}
/* @Override
protected void onDestroy() {
thinJam.shutdown();
super.onDestroy();
}
*/
@Override
public void btCallback2(String mac, String status, String name, Bundle bundle) {
UserError.Log.d(TAG, "BT scan: " + mac + " " + status + " " + name);
if (status.equals("SCAN_FOUND")) {
binding.getVm().addToList(mac, name);
}
}
// View model item
public class TjItem {
public String name;
public String mac;
public int resource;
public ViewModel model;
public void onClick(View v) {
UserError.Log.d(TAG, "Clicked: " + mac);
binding.getVm().stopScan();
binding.getVm().items.clear();
binding.getVm().changeConnectedDevice(this);
}
TjItem(final String mac, final String name) {
this.mac = mac;
this.name = name;
}
}
// bound view model
@RequiredArgsConstructor
public class ViewModel {
Activity activity;
public final ObservableField<String> connectedDevice = new ObservableField<>();
public final ObservableField<String> status = new ObservableField<>();
public final ObservableField<String> textWindow = new ObservableField<>();
public final ObservableField<Integer> progressBar = new ObservableField<>();
public final ObservableList<TjItem> items = new ObservableArrayList<>();
public final ItemBinding<TjItem> itemBinding = ItemBinding.of(BR.item, R.layout.thinjam_scan_item);
private String mac = null;
ViewModel(Activity activity) {
this.activity = activity;
loadLastConnectedDevice();
}
public boolean showBack() {
return true;
}
public boolean showScanList() {
return items.size() > 0;
}
public void goBack(View v) {
stopScan();
items.clear();
}
public boolean doAction(final String action) {
switch (action) {
case "updateconfig":
JoH.static_toast_long("Refreshing watch config");
validateTxId();
break;
case "asktxid":
// for debug only
setTx();
break;
case "showqrcode":
JoH.static_toast_long("Showing QR code on watch");
thinJam.showQrCode();
break;
case "easyauth":
JoH.static_toast_long("Doing non-QR code Easy Auth");
thinJam.easyAuth();
break;
case "reboot":
JoH.static_toast_long("Rebooting");
thinJam.reboot();
break;
case "factoryreset":
JoH.static_toast_long("Factory Resetting");
thinJam.factoryReset();
break;
case "launchstatus":
xdrip.getAppContext().startActivity(JoH.getStartActivityIntent(MegaStatus.class).setAction("BlueJay").addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
break;
case "launchhelp":
xdrip.getAppContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://bluejay.website/quickhelp")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
break;
case "launchsettings":
xdrip.getAppContext().startActivity(JoH.getStartActivityIntent(Preferences.class).setAction("bluejay_preference_screen").addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
break;
default:
JoH.static_toast_long("Unknown action: "+action);
break;
}
return true;
}
public boolean scan(boolean legacy) {
UserError.Log.d(TAG, "Start scan");
if (JoH.ratelimit("bj-scan-startb",5)) {
if (legacy) {
scanMeister.setFilter(nullFilter).scan();
} else {
scanMeister.setFilter(customFilter).scan();
}
}
return false;
}
public void getStatus() {
thinJam.getStatus();
}
// boolean for long click
public boolean unitTesting(final String test) {
// call external test suite
if (test.startsWith("confirm")) {
val subtest = test.substring(7,test.length());
GenericConfirmDialog.show(this.activity, "Confirm:", "Please confirm when ready for: " + subtest, () -> {
thinJam.setProgressIndicator(progressBar);
thinJam.getDebug().processTestSuite(subtest);
});
} else {
thinJam.setProgressIndicator(progressBar);
thinJam.getDebug().processTestSuite(test);
}
return true;
}
final String TJ_UI_TX_ID = "Last-tj-txid";
// TODO remove?
void setTx() {
QuickSettingsDialogs.textSettingDialog(activity, TJ_UI_TX_ID, "Transmitter ID", "Enter TXID", InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD, new Runnable() {
@Override
public void run() {
validateTxId(); // also sets settings
}
});
}
private void validateTxId() {
Pref.setString(TJ_UI_TX_ID,Pref.getString("dex_txid","")); // for now just override but internal pref is probably not needed
String txid = Pref.getString(TJ_UI_TX_ID, "").trim().toUpperCase();
if (txid.length() > 6) {
txid = "";
}
thinJam.setSettings(txid);
thinJam.setTime();
}
// long click needs boolean
public boolean doOtaC(View v) {
thinJam.setProgressIndicator(progressBar);
JoH.static_toast_long("Doing OTA CORE");
Inevitable.task("do-ota-tj", 500, () -> thinJam.doOtaCore());
return false;
}
// long click needs boolean
public void doOtaM(View v) {
thinJam.setProgressIndicator(progressBar);
// JoH.static_toast_long("Doing OTA CORE");
Inevitable.task("do-ota-tj", 500, () -> thinJam.doOtaMain());
}
// long click needs boolean
public boolean doIdentityc(View v) {
identify();
return false;
}
public void stopScan() {
UserError.Log.d(TAG, "Stop scan");
scanMeister.stop();
}
public void addToList(final String mac, final String name) {
if (mac == null) return;
synchronized (items) {
if (!macInList(mac)) {
items.add(new TjItem(mac, name));
UserError.Log.d(TAG, "Added item " + mac + " " + name + " total:" + items.size());
}
}
}
public boolean macInList(final String mac) {
if (mac == null) return false;
for (TjItem item : items) {
if (item.mac.equals(mac)) return true;
}
return false;
}
public void changeConnectedDevice(final TjItem item) {
connectedDevice.set(item.mac + " " + item.name);
setMac(item.mac);
saveConnectedDevice();
BlueJayEntry.setEnabled();
thinJam.emptyQueue();
thinJam.stringObservableField.set("");
thinJam.notificationString.setLength(0);
refreshFromStoredMac();
}
private static final String PREF_CONNECTED_DEVICE_INFO = "TJ_CONNECTED_DEVICE_INFO";
private void saveConnectedDevice() {
PersistentStore.setString(PREF_CONNECTED_DEVICE_INFO, connectedDevice.get());
}
private void loadLastConnectedDevice() {
connectedDevice.set(PersistentStore.getString(PREF_CONNECTED_DEVICE_INFO));
try {
String[] split = connectedDevice.get().split(" ");
if (split[0].length() == 17)
setMac(split[0]);
} catch (Exception e) {
//
}
UserError.Log.d(TAG, "Mac loaded in as: " + mac);
}
private void setMac(final String mac) {
if (mac == null) return;
this.mac = mac;
thinJam.setMac(mac);
}
private void identify() {
thinJam.identify();
}
} // end view model class
public static void refreshFromStoredMac() {
startWithCommand(REFRESH_FROM_STORED_MAC);
}
public static void installCorePrompt() {
startWithCommand(INSTALL_CORE);
}
public static void updateCorePrompt() {
startWithCommand(UPDATE_CORE);
}
public static void updateMainPrompt() {
startWithCommand(UPDATE_MAIN);
}
public static void requestQrCode() { startWithCommand(REQUEST_QR);}
public static void launchQRScan() {
startWithCommand(SCAN_QR);
}
private static void startWithCommand(final String command) {
xdrip.getAppContext().startActivity(new Intent(xdrip.getAppContext(), ThinJamActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(THINJAM_ACTIVITY_COMMAND, command));
}
private void processIncomingBundle(final Bundle bundle) {
if (bundle != null) {
Log.d(TAG, "Processing incoming bundle");
if (!mBound) {
// save to process when service connects
savedExtras = bundle;
return;
} else {
savedExtras = null; // clear if might have been set
}
final String command = bundle.getString(THINJAM_ACTIVITY_COMMAND);
if (command != null) {
switch (command) {
case REFRESH_FROM_STORED_MAC:
binding.getVm().connectedDevice.set(BlueJay.getMac());
binding.getVm().setMac(BlueJay.getMac()); // TODO this doesn't handle name
binding.getVm().identify(); // re(do) identification.
break;
case INSTALL_CORE:
promptForCoreUpdate(false);
break;
case UPDATE_CORE:
promptForCoreUpdate(true);
break;
case UPDATE_MAIN:
promptForMainUpdate();
break;
case REQUEST_QR:
binding.getVm().doAction("showqrcode");
break;
case SCAN_QR:
new AndroidBarcode(this).scan();
break;
}
}
}
}
private void promptForCoreUpdate(boolean alreadyInstalled) {
GenericConfirmDialog.show(this, alreadyInstalled ? "Update Core?" : "Install Core?",
"Install xDrip core module?\n\nMake sure device is charging or this can break it!",
() -> {
binding.getVm().doOtaC(null);
});
}
private void promptForMainUpdate() {
GenericConfirmDialog.show(this, "Update Firmware?",
"Update BlueJay firmware?\n\nMake sure device is charging or this can break it!",
() -> {
binding.getVm().doOtaM(null);
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(android.Manifest.permission.ACCESS_FINE_LOCATION)) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
refreshFromStoredMac();
}
}
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
val scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult == null || scanResult.getContents() == null) {
return;
}
if (scanResult.getFormatName().equals("QR_CODE")) {
try {
BlueJay.processQRCode(scanResult.getRawBytes());
} catch (Exception e) {
// meh
}
}
}
}
| jamorham/xDrip-plus | app/src/main/java/com/eveningoutpost/dexdrip/ui/activities/ThinJamActivity.java | Java | gpl-3.0 | 19,937 |
package org.ovirt.engine.api.restapi.resource;
import static org.easymock.EasyMock.expect;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import org.ovirt.engine.api.model.Host;
import org.ovirt.engine.api.model.StorageConnection;
import org.ovirt.engine.core.common.action.AttachDetachStorageConnectionParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.queries.StorageServerConnectionQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class BackendStorageDomainServerConnectionsResourceTest extends AbstractBackendCollectionResourceTest<StorageConnection, StorageServerConnections, BackendStorageDomainServerConnectionsResource> {
protected static final org.ovirt.engine.core.common.businessentities.StorageType STORAGE_TYPES_MAPPED[] = {
org.ovirt.engine.core.common.businessentities.StorageType.NFS,
org.ovirt.engine.core.common.businessentities.StorageType.LOCALFS,
org.ovirt.engine.core.common.businessentities.StorageType.POSIXFS,
org.ovirt.engine.core.common.businessentities.StorageType.ISCSI };
public BackendStorageDomainServerConnectionsResourceTest() {
super(new BackendStorageDomainServerConnectionsResource(GUIDS[3]), null, "");
}
@Test
@Ignore
@Override
public void testQuery() throws Exception {
}
@Test
public void testAttachSuccess() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpActionExpectations(VdcActionType.AttachStorageConnectionToStorageDomain,
AttachDetachStorageConnectionParameters.class,
new String[] { },
new Object[] { },
true,
true);
StorageConnection connection = new StorageConnection();
connection.setId(GUIDS[3].toString());
Response response = collection.add(connection);
assertEquals(200, response.getStatus());
}
@Test
public void testAttachFailure() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpActionExpectations(VdcActionType.AttachStorageConnectionToStorageDomain,
AttachDetachStorageConnectionParameters.class,
new String[] { },
new Object[] { },
false,
false);
StorageConnection connection = new StorageConnection();
connection.setId(GUIDS[3].toString());
try {
Response response = collection.add(connection);
} catch (WebApplicationException wae) {
assertNotNull(wae.getResponse());
assertEquals(400, wae.getResponse().getStatus());
}
}
@Test
public void testDetachSuccess() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpGetEntityExpectations();
setUpActionExpectations(VdcActionType.DetachStorageConnectionFromStorageDomain,
AttachDetachStorageConnectionParameters.class,
new String[] {},
new Object[] {},
true,
true);
Response response = collection.remove(GUIDS[3].toString());
assertEquals(200, response.getStatus());
}
@Test
public void testDetachFailure() throws Exception {
setUriInfo(setUpBasicUriExpectations());
setUpGetEntityExpectations();
setUpActionExpectations(VdcActionType.DetachStorageConnectionFromStorageDomain,
AttachDetachStorageConnectionParameters.class,
new String[] {},
new Object[] {},
false,
false);
try {
Response response = collection.remove(GUIDS[3].toString());
} catch (WebApplicationException wae) {
assertNotNull(wae.getResponse());
assertEquals(400, wae.getResponse().getStatus());
}
}
@Override
protected List<StorageConnection> getCollection() {
return collection.list().getStorageConnections();
}
@Override
protected void setUpQueryExpectations(String query, Object failure) throws Exception {
assertEquals("", query);
setUpEntityQueryExpectations(VdcQueryType.GetStorageServerConnectionsForDomain,
VdcQueryParametersBase.class,
new String[] {},
new Object[] {},
setUpStorageConnections(),
failure);
control.replay();
}
protected List<StorageServerConnections> setUpStorageConnections() {
List<StorageServerConnections> storageConnections = new ArrayList<>();
storageConnections.add(getEntity(3));
return storageConnections;
}
@Override
protected void verifyCollection(List<StorageConnection> collection) throws Exception {
assertNotNull(collection);
assertEquals(1, collection.size());
}
@Override
protected StorageServerConnections getEntity(int index) {
return setUpEntityExpectations(control.createMock(StorageServerConnections.class), index);
}
static StorageServerConnections setUpEntityExpectations(StorageServerConnections entity, int index) {
expect(entity.getid()).andReturn(GUIDS[index].toString()).anyTimes();
expect(entity.getstorage_type()).andReturn(STORAGE_TYPES_MAPPED[index]).anyTimes();
expect(entity.getconnection()).andReturn("1.1.1.255").anyTimes();
if (STORAGE_TYPES_MAPPED[index].equals(StorageType.ISCSI)) {
expect(entity.getport()).andReturn("3260").anyTimes();
}
return entity;
}
StorageConnection getModel(int index) {
StorageConnection model = new StorageConnection();
model.setType(STORAGE_TYPES_MAPPED[index].toString());
if ( index == 0 || index == 3 ) {
model.setAddress("1.1.1.1");
}
Host host = new Host();
host.setId(GUIDS[1].toString());
model.setHost(host);
if (index == 0 || index == 1) {
model.setPath("/data1");
}
return model;
}
private void setUpGetEntityExpectations() throws Exception {
setUpEntityQueryExpectations(VdcQueryType.GetStorageServerConnectionById,
StorageServerConnectionQueryParametersBase.class,
new String[] { "ServerConnectionId" },
new Object[] { GUIDS[3].toString() },
getEntity(3));
}
}
| jtux270/translate | ovirt/backend/manager/modules/restapi/jaxrs/src/test/java/org/ovirt/engine/api/restapi/resource/BackendStorageDomainServerConnectionsResourceTest.java | Java | gpl-3.0 | 6,846 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
*
* The contents of this file are subject to the terms of the GNU General Public License Version 3
* only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
* copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each file.
*/
package org.openconcerto.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* Permet de lire un fichier zip.
*
* @author ILM Informatique
* @see org.openconcerto.utils.Zip
*/
public class Unzip extends ZipFile {
public static void toDir(File zip, File dir) throws IOException {
Unzip unz = new Unzip(zip);
unz.unzip(dir);
unz.close();
}
/**
* Ouvre un fichier zip en lecture.
* <p>
* Note : ne pas oublier de fermer.
* </p>
*
* @param f the ZIP file to be opened for reading
* @exception ZipException if a ZIP error has occurred
* @exception IOException if an I/O error has occurred
* @see ZipFile#close()
*/
public Unzip(File f) throws ZipException, IOException {
super(f);
}
// *** Lecture
/**
* Décompresse le zip dans un dossier. Si destDir n'existe pas le crée.
*
* @param destDir ou mettre le résultat.
* @throws ZipException si erreur lors de la décompression.
* @throws IOException si erreur de lecture, ou de création de la destination.
*/
public void unzip(File destDir) throws ZipException, IOException {
if (destDir == null)
destDir = new File("");
destDir.mkdirs();
final Enumeration en = this.entries();
while (en.hasMoreElements()) {
ZipEntry target = (ZipEntry) en.nextElement();
unzip(destDir, target);
}
}
public void unzip(File destDir, String entryName) throws ZipException, IOException {
unzipEntry(this, this.getEntry(entryName), destDir);
}
public void unzip(File destDir, ZipEntry entry) throws ZipException, IOException {
unzipEntry(this, entry, destDir);
}
static private void unzipEntry(ZipFile zf, ZipEntry target, File to) throws ZipException, IOException {
File file = new File(to, target.getName());
if (target.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream is = zf.getInputStream(target);
BufferedInputStream bis = new BufferedInputStream(is);
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int c;
while ((c = bis.read()) != -1) {
bos.write((byte) c);
}
bos.close();
fos.close();
}
}
/**
* Renvoie un flux sans dézipper le fichier.
*
* @param entryName le nom de l'entrée voulue.
* @return le flux correspondant, ou <code>null</code> si non existant.
* @throws IOException si erreur lecture.
* @see ZipFile#close()
*/
public InputStream getInputStream(String entryName) throws IOException {
final ZipEntry entry = this.getEntry(entryName);
if (entry == null)
// l'entrée n'existe pas
return null;
else
return this.getInputStream(entry);
}
}
| mbshopM/openconcerto | OpenConcerto/src/org/openconcerto/utils/Unzip.java | Java | gpl-3.0 | 4,050 |
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.context.hierarchies.standard;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Sam Brannen
* @since 3.2.2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
//
@ContextConfiguration(name = "parent", classes = ClassHierarchyWithMergedConfigLevelOneTests.AppConfig.class),//
@ContextConfiguration(name = "child", classes = ClassHierarchyWithMergedConfigLevelOneTests.UserConfig.class) //
})
public class ClassHierarchyWithMergedConfigLevelOneTests {
@Configuration
static class AppConfig {
@Bean
public String parent() {
return "parent";
}
}
@Configuration
static class UserConfig {
@Autowired
private AppConfig appConfig;
@Bean
public String user() {
return appConfig.parent() + " + user";
}
@Bean
public String beanFromUserConfig() {
return "from UserConfig";
}
}
@Autowired
protected String parent;
@Autowired
protected String user;
@Autowired(required = false)
@Qualifier("beanFromUserConfig")
protected String beanFromUserConfig;
@Autowired
protected ApplicationContext context;
@Test
public void loadContextHierarchy() {
assertNotNull("child ApplicationContext", context);
assertNotNull("parent ApplicationContext", context.getParent());
assertNull("grandparent ApplicationContext", context.getParent().getParent());
assertEquals("parent", parent);
assertEquals("parent + user", user);
assertEquals("from UserConfig", beanFromUserConfig);
}
}
| kingtang/spring-learn | spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java | Java | gpl-3.0 | 2,639 |
package org.oreon.core.vk.device;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public class VkDeviceBundle {
private PhysicalDevice physicalDevice;
private LogicalDevice logicalDevice;
}
| oreonengine/oreon-engine | oreonengine/oe-vk-api/src/main/java/org/oreon/core/vk/device/VkDeviceBundle.java | Java | gpl-3.0 | 243 |
package com.github.mrsdogood.neural;
import org.ejml.data.RowD1Matrix64F;
public class Utils {
public static class SigNaNException extends RuntimeException{};
/** the sigmoid function **/
public static final double sig(double x) {
if(Double.isNaN(x)){
System.err.println("sig not a number.");
throw new SigNaNException();
}
double ret = 1.0/(1.0+Math.exp(-x));
if(Double.isNaN(ret)){
System.err.println("sig returning not a number.");
throw new SigNaNException();
}
return ret;
}
public static final void sig(RowD1Matrix64F in, RowD1Matrix64F out) {
assert(in.getNumRows()==out.getNumRows());
assert(in.getNumCols()==out.getNumCols());
int size = in.getNumRows()*out.getNumCols();
for(int i = 0; i < size; i++){
out.set(i, sig(in.get(i)));
}
}
/** the derivative of the sigmoid function **/
public static final double dsig(double x) {
if(Double.isNaN(x)){
System.err.println("dsig not a number.");
throw new SigNaNException();
}
double sig = sig(x);
double ret = sig*(1-sig);
if(Double.isNaN(ret)){
System.err.println("dsig returning not a number from:"+x);
throw new SigNaNException();
}
return ret;
}
public static final void dsig(RowD1Matrix64F in, RowD1Matrix64F out) {
assert(in.getNumRows()==out.getNumRows());
assert(in.getNumCols()==out.getNumCols());
int size = in.getNumElements();
for(int i = 0; i < size; i++){
out.set(i, dsig(in.get(i)));
}
}
}
| MrsDogood/HessianFree | src/main/java/com/github/mrsdogood/neural/Utils.java | Java | gpl-3.0 | 1,713 |
/*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com
* @author Matthew Lohbihler
*
* 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/>.
*
* When signing a commercial license with Serotonin Software Technologies Inc.,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*/
package com.serotonin.bacnet4j;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.serotonin.bacnet4j.type.constructed.Address;
import com.serotonin.bacnet4j.type.constructed.ServicesSupported;
import com.serotonin.bacnet4j.type.enumerated.ObjectType;
import com.serotonin.bacnet4j.type.enumerated.Segmentation;
import com.serotonin.bacnet4j.type.primitive.ObjectIdentifier;
import com.serotonin.bacnet4j.type.primitive.OctetString;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
public class RemoteDevice implements Serializable {
private static final long serialVersionUID = 6338537708566242078L;
private final int instanceNumber;
private final Address address;
private final OctetString linkService;
private int maxAPDULengthAccepted;
private Segmentation segmentationSupported;
private int vendorId;
private String vendorName;
private String name;
private String modelName;
private String firmwareRevision;
private String applicationSoftwareVersion;
private UnsignedInteger protocolVersion;
private UnsignedInteger protocolRevision;
private ServicesSupported servicesSupported;
private final Map<ObjectIdentifier, RemoteObject> objects = new HashMap<ObjectIdentifier, RemoteObject>();
private Object userData;
private int maxReadMultipleReferences = -1;
public RemoteDevice(int instanceNumber, Address address, OctetString linkService) {
this.instanceNumber = instanceNumber;
this.address = address;
this.linkService = linkService;
}
public ObjectIdentifier getObjectIdentifier() {
return new ObjectIdentifier(ObjectType.device, instanceNumber);
}
@Override
public String toString() {
return "RemoteDevice(instanceNumber=" + instanceNumber + ", address=" + address + ", linkServiceAddress="
+ linkService + ")";
}
public String toExtendedString() {
return "RemoteDevice(instanceNumber=" + instanceNumber +
", address=" + address + ", linkServiceAddress=" + linkService +
", maxAPDULengthAccepted=" + maxAPDULengthAccepted +
", segmentationSupported=" + segmentationSupported +
", vendorId=" + vendorId + ", vendorName=" + vendorName +
", name=" + name + ", firmwareRevision=" + firmwareRevision +
", applicationSoftwareVersion=" + applicationSoftwareVersion +
", servicesSupported=" + servicesSupported + ", objects=" + objects + ")";
}
public void setObject(RemoteObject o) {
objects.put(o.getObjectIdentifier(), o);
}
public RemoteObject getObject(ObjectIdentifier oid) {
return objects.get(oid);
}
public List<RemoteObject> getObjects() {
return new ArrayList<RemoteObject>(objects.values());
}
public void clearObjects() {
objects.clear();
}
public Address getAddress() {
return address;
}
public OctetString getLinkService() {
return linkService;
}
public int getMaxAPDULengthAccepted() {
return maxAPDULengthAccepted;
}
public void setMaxAPDULengthAccepted(int maxAPDULengthAccepted) {
this.maxAPDULengthAccepted = maxAPDULengthAccepted;
}
public Segmentation getSegmentationSupported() {
return segmentationSupported;
}
public void setSegmentationSupported(Segmentation segmentationSupported) {
this.segmentationSupported = segmentationSupported;
}
public int getVendorId() {
return vendorId;
}
public void setVendorId(int vendorId) {
this.vendorId = vendorId;
}
public String getVendorName() {
return vendorName;
}
public void setVendorName(String vendorName) {
this.vendorName = vendorName;
}
public String getFirmwareRevision() {
return firmwareRevision;
}
public void setFirmwareRevision(String firmwareRevision) {
this.firmwareRevision = firmwareRevision;
}
public String getApplicationSoftwareVersion() {
return applicationSoftwareVersion;
}
public void setApplicationSoftwareVersion(String applicationSoftwareVersion) {
this.applicationSoftwareVersion = applicationSoftwareVersion;
}
public int getInstanceNumber() {
return instanceNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public UnsignedInteger getProtocolVersion() {
return protocolVersion;
}
public void setProtocolVersion(UnsignedInteger protocolVersion) {
this.protocolVersion = protocolVersion;
}
public UnsignedInteger getProtocolRevision() {
return protocolRevision;
}
public void setProtocolRevision(UnsignedInteger protocolRevision) {
this.protocolRevision = protocolRevision;
}
public ServicesSupported getServicesSupported() {
return servicesSupported;
}
public void setServicesSupported(ServicesSupported servicesSupported) {
this.servicesSupported = servicesSupported;
}
public Object getUserData() {
return userData;
}
public void setUserData(Object userData) {
this.userData = userData;
}
public int getMaxReadMultipleReferences() {
if (maxReadMultipleReferences == -1)
maxReadMultipleReferences = segmentationSupported.hasTransmitSegmentation() ? 200 : 20;
return maxReadMultipleReferences;
}
public void reduceMaxReadMultipleReferences() {
if (maxReadMultipleReferences > 1)
maxReadMultipleReferences = (int) (maxReadMultipleReferences * 0.75);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + instanceNumber;
result = prime * result + ((linkService == null) ? 0 : linkService.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final RemoteDevice other = (RemoteDevice) obj;
if (address == null) {
if (other.address != null)
return false;
}
else if (!address.equals(other.address))
return false;
if (instanceNumber != other.instanceNumber)
return false;
if (linkService == null) {
if (other.linkService != null)
return false;
}
else if (!linkService.equals(other.linkService))
return false;
return true;
}
}
| empeeoh/BACnet4J | src/com/serotonin/bacnet4j/RemoteDevice.java | Java | gpl-3.0 | 8,394 |
/*********************************************************************************************
*
* 'AbstractDisplayOutput.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and simulation
* platform. (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package msi.gama.outputs;
import msi.gama.common.interfaces.IGamaView;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.descriptions.IDescription;
/**
* The Class AbstractDisplayOutput.
*
* @author drogoul
*/
public abstract class AbstractDisplayOutput extends AbstractOutput implements IDisplayOutput {
final boolean virtual;
public AbstractDisplayOutput(final IDescription desc) {
super(desc);
virtual = IKeyword.TRUE.equals(getLiteral(IKeyword.VIRTUAL, null));
}
protected boolean disposed = false;
protected boolean synchro = false;
protected boolean inInitPhase = true;
protected IGamaView view;
final Runnable opener = () -> {
view = getScope().getGui().showView(getScope(), getViewId(), isUnique() ? null : getName(), 1); // IWorkbenchPage.VIEW_ACTIVATE
if (view == null) { return; }
view.addOutput(AbstractDisplayOutput.this);
};
@Override
public boolean isVirtual() {
return virtual;
}
@Override
public void open() {
super.open();
GAMA.getGui().run(getScope(), opener);
}
@Override
public boolean init(final IScope scope) throws GamaRuntimeException {
super.init(scope);
return true;
}
@Override
public void dispose() {
if (disposed) { return; }
disposed = true;
if (view != null) {
view.removeOutput(this);
view = null;
}
if (getScope() != null) {
GAMA.releaseScope(getScope());
}
}
@Override
public void update() throws GamaRuntimeException {
if (view != null) {
view.update(this);
}
}
@Override
public boolean isUnique() {
return false;
}
@Override
public boolean isSynchronized() {
return synchro;
}
@Override
public void setSynchronized(final boolean sync) {
synchro = sync;
if (view != null)
view.updateToolbarState();
}
@Override
public void setPaused(final boolean pause) {
super.setPaused(pause);
if (view != null)
view.updateToolbarState();
}
@Override
public abstract String getViewId();
@Override
public String getId() {
final String cName = ((AbstractOutput) this).getDescription().getModelDescription().getAlias();
if (cName != null && !cName.equals("") && !getName().contains("#")) { return isUnique() ? getViewId()
: getViewId() + getName() + "#" + cName; }
return isUnique() ? getViewId() : getViewId() + getName();
}
@Override
public boolean isInInitPhase() {
return inInitPhase;
}
@Override
public void setInInitPhase(final boolean state) {
inInitPhase = state;
}
}
| hqnghi88/gamaClone | msi.gama.core/src/msi/gama/outputs/AbstractDisplayOutput.java | Java | gpl-3.0 | 3,182 |
package org.overture.codegen.tests.other;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.overture.ast.definitions.PDefinition;
import org.overture.ast.definitions.SClassDefinition;
import org.overture.ast.lex.Dialect;
import org.overture.ast.node.INode;
import org.overture.ast.statements.AIdentifierStateDesignator;
import org.overture.codegen.analysis.vdm.IdStateDesignatorDefCollector;
import org.overture.codegen.analysis.vdm.Renaming;
import org.overture.codegen.analysis.vdm.VarRenamer;
import org.overture.codegen.logging.Logger;
import org.overture.codegen.tests.util.TestUtils;
import org.overture.codegen.utils.GeneralUtils;
import org.overture.config.Release;
import org.overture.config.Settings;
import org.overture.interpreter.util.InterpreterUtil;
import org.overture.interpreter.values.Value;
import org.overture.parser.messages.VDMWarning;
import org.overture.typechecker.assistant.TypeCheckerAssistantFactory;
import org.overture.typechecker.util.TypeCheckerUtil;
import org.overture.typechecker.util.TypeCheckerUtil.TypeCheckResult;
@RunWith(Parameterized.class)
public class VarShadowingTest
{
public static final String EVAL_ENTRY_POINT = "Entry`Run()";
private File inputFile;
private static final TypeCheckerAssistantFactory af = new TypeCheckerAssistantFactory();
public static final String ROOT = "src" + File.separatorChar + "test"
+ File.separatorChar + "resources" + File.separatorChar
+ "var_shadowing_specs";
public VarShadowingTest(File inputFile)
{
this.inputFile = inputFile;
}
@Before
public void init() throws Exception
{
Settings.dialect = Dialect.VDM_PP;
Settings.release = Release.VDM_10;
Logger.getLog().setSilent(true);
}
@Parameters(name = "{index} : {0}")
public static Collection<Object[]> testData()
{
return TestUtils.collectFiles(ROOT);
}
@Test
public void test() throws Exception
{
try
{
TypeCheckResult<List<SClassDefinition>> originalSpecTcResult = TypeCheckerUtil.typeCheckPp(inputFile);
Map<AIdentifierStateDesignator, PDefinition> idDefs = IdStateDesignatorDefCollector.getIdDefs(originalSpecTcResult.result, af);
Assert.assertTrue(inputFile.getName() + " has type errors", originalSpecTcResult.errors.isEmpty());
Value orgSpecResult = evalSpec(originalSpecTcResult.result);
List<Renaming> renamings = new LinkedList<Renaming>(new VarRenamer().computeRenamings(originalSpecTcResult.result, af, idDefs));
// It is very important that renamings are performed from the bottom, right to left, in order
// not to mess up the location of the names!!
Collections.sort(renamings);
StringBuilder sb = GeneralUtils.readLines(inputFile, "\n");
// Perform the renaming in a string buffer
rename(renamings, sb);
// Type check the renamed specification
TypeCheckResult<List<SClassDefinition>> renamed = TypeCheckerUtil.typeCheckPp(sb.toString());
// The renamed specification must contain no type errors and no warnings about hidden variables
Assert.assertTrue("Renamed specification contains errors", renamed.errors.isEmpty());
Assert.assertTrue("Found hidden variable warnings in renamed specification", filter(renamed.warnings).isEmpty());
Value renamedSpecResult = evalSpec(renamed.result);
// The two specifications must evaluate to the same result
Assert.assertTrue("Expected same value to be produced "
+ "for the original specification and the specification with "
+ "renamed variables. Got values "
+ orgSpecResult
+ " and "
+ renamedSpecResult
+ " from the original and "
+ "the renamed specification, respectively", orgSpecResult.equals(renamedSpecResult));
} catch (Exception e)
{
e.printStackTrace();
Assert.fail("Test: " + inputFile.getName() + " did not parse!");
}
}
private void rename(List<Renaming> renamings, StringBuilder sb)
{
for (Renaming r : renamings)
{
int startOffset = r.getLoc().getStartOffset() - 1;
int endOffset = startOffset + r.getNewName().length() - 2;
sb.replace(startOffset, endOffset, r.getNewName());
}
}
private Value evalSpec(List<SClassDefinition> classes) throws Exception
{
return InterpreterUtil.interpret(new LinkedList<INode>(classes), EVAL_ENTRY_POINT, Settings.dialect);
}
private List<VDMWarning> filter(List<VDMWarning> warnings)
{
List<VDMWarning> filtered = new LinkedList<VDMWarning>();
for (VDMWarning w : warnings)
{
if (w.number == 5007 || w.number == 5008)
{
filtered.add(w);
}
}
return filtered;
}
}
| LasseBP/overture | core/codegen/javagen/src/test/java/org/overture/codegen/tests/other/VarShadowingTest.java | Java | gpl-3.0 | 4,858 |
/*
* Copyright (C) 2017 Chan Chung Kwong <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.fooledit.editor.text.parser;
import java.io.*;
import java.nio.file.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.tool.*;
/**
*
* @author Chan Chung Kwong <[email protected]>
*/
public class AntlrParser{
public static void main(String[] args) throws IOException{
parse("/home/kwong/projects/grammars-v4/java8/examples/helloworld.java","/home/kwong/projects/grammars-v4/java8/Java8.g4","compilationUnit");
}
public static ParseTree parse(String fileName,String combinedGrammarFileName,String startRule)throws IOException{
final Grammar g=Grammar.load(combinedGrammarFileName);
LexerInterpreter lexEngine=g.createLexerInterpreter(CharStreams.fromPath(Paths.get(fileName)));
CommonTokenStream tokens=new CommonTokenStream(lexEngine);
ParserInterpreter parser=g.createParserInterpreter(tokens);
ParseTree t=parser.parse(g.getRule(startRule).index);
System.out.println("parse tree: "+t.toStringTree(parser));
return t;
}
}
| chungkwong/jtk | editor.text/src/main/java/cc/fooledit/editor/text/parser/AntlrParser.java | Java | gpl-3.0 | 1,710 |
/*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.dataio.geotiff.internal;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.dataio.dimap.DimapHeaderWriter;
import org.esa.snap.dataio.geotiff.Utils;
import org.esa.snap.framework.datamodel.Band;
import org.esa.snap.framework.datamodel.ColorPaletteDef;
import org.esa.snap.framework.datamodel.ImageInfo;
import org.esa.snap.framework.datamodel.Product;
import org.esa.snap.framework.datamodel.ProductData;
import org.esa.snap.util.Guardian;
import org.esa.snap.util.ProductUtils;
import org.esa.snap.util.geotiff.GeoTIFFMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.Color;
import java.awt.image.DataBuffer;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A TIFF IFD implementation for the GeoTIFF format.
*
* @author Marco Peters
* @author Sabine Embacher
* @author Norman Fomferra
* @version $Revision: 2932 $ $Date: 2008-08-28 16:43:48 +0200 (Do, 28 Aug 2008) $
*/
public class TiffIFD {
private static final long MAX_FILE_SIZE = 4294967296L;
private static final int TIFF_COLORMAP_SIZE = 256;
private static final int BYTES_FOR_NEXT_IFD_OFFSET = 4;
private static final int BYTES_FOR_NUMBER_OF_ENTRIES = 2;
private final TiffDirectoryEntrySet entrySet;
private int maxElemSizeBandDataType;
public TiffIFD(final Product product) {
entrySet = new TiffDirectoryEntrySet();
initEntrys(product);
}
public void write(final ImageOutputStream ios, final long ifdOffset, final long nextIfdOffset) throws IOException {
Guardian.assertGreaterThan("ifdOffset", ifdOffset, -1);
computeOffsets(ifdOffset);
ios.seek(ifdOffset);
final TiffDirectoryEntry[] entries = entrySet.getEntries();
new TiffShort(entries.length).write(ios);
long entryPosition = ios.getStreamPosition();
for (TiffDirectoryEntry entry : entries) {
ios.seek(entryPosition);
entry.write(ios);
entryPosition += TiffDirectoryEntry.BYTES_PER_ENTRY;
}
writeNextIfdOffset(ios, ifdOffset, nextIfdOffset);
}
private void writeNextIfdOffset(final ImageOutputStream ios, final long ifdOffset, final long nextIfdOffset) throws IOException {
ios.seek(getPosForNextIfdOffset(ifdOffset));
new TiffLong(nextIfdOffset).write(ios);
}
private long getPosForNextIfdOffset(final long ifdOffset) {
return ifdOffset + getRequiredIfdSize() - 4;
}
public TiffDirectoryEntry getEntry(final TiffShort tag) {
return entrySet.getEntry(tag);
}
public long getRequiredIfdSize() {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
return BYTES_FOR_NUMBER_OF_ENTRIES + entries.length * TiffDirectoryEntry.BYTES_PER_ENTRY + BYTES_FOR_NEXT_IFD_OFFSET;
}
public long getRequiredReferencedValuesSize() {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
long size = 0;
for (final TiffDirectoryEntry entry : entries) {
if (entry.mustValuesBeReferenced()) {
size += entry.getValuesSizeInBytes();
}
}
return size;
}
public long getRequiredSizeForStrips() {
final TiffLong[] counts = (TiffLong[]) getEntry(TiffTag.STRIP_BYTE_COUNTS).getValues();
long size = 0;
for (TiffLong count : counts) {
size += count.getValue();
}
return size;
}
public long getRequiredEntireSize() {
return getRequiredIfdSize() + getRequiredReferencedValuesSize() + getRequiredSizeForStrips();
}
private void computeOffsets(final long ifdOffset) {
final TiffDirectoryEntry[] entries = entrySet.getEntries();
long valuesOffset = computeStartOffsetForValues(entries.length, ifdOffset);
for (final TiffDirectoryEntry entry : entries) {
if (entry.mustValuesBeReferenced()) {
entry.setValuesOffset(valuesOffset);
valuesOffset += entry.getValuesSizeInBytes();
}
}
moveStripsTo(valuesOffset);
}
private void moveStripsTo(final long stripsStart) {
final TiffLong[] values = (TiffLong[]) getEntry(TiffTag.STRIP_OFFSETS).getValues();
for (int i = 0; i < values.length; i++) {
final long oldValue = values[i].getValue();
final long newValue = oldValue + stripsStart;
values[i] = new TiffLong(newValue);
}
}
private long computeStartOffsetForValues(final int numEntries, final long ifdOffset) {
final short bytesPerEntry = TiffDirectoryEntry.BYTES_PER_ENTRY;
final int bytesForEntries = numEntries * bytesPerEntry;
return ifdOffset + BYTES_FOR_NUMBER_OF_ENTRIES + bytesForEntries + BYTES_FOR_NEXT_IFD_OFFSET;
}
private void setEntry(final TiffDirectoryEntry entry) {
entrySet.set(entry);
}
public int getBandDataType() {
return maxElemSizeBandDataType;
}
private void initEntrys(final Product product) {
maxElemSizeBandDataType = getMaxElemSizeBandDataType(product.getBands());
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_WIDTH, new TiffLong(width)));
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_LENGTH, new TiffLong(height)));
setEntry(new TiffDirectoryEntry(TiffTag.BITS_PER_SAMPLE, calculateBitsPerSample(product)));
setEntry(new TiffDirectoryEntry(TiffTag.COMPRESSION, new TiffShort(1)));
setEntry(new TiffDirectoryEntry(TiffTag.IMAGE_DESCRIPTION, new TiffAscii(product.getName())));
setEntry(new TiffDirectoryEntry(TiffTag.SAMPLES_PER_PIXEL, new TiffShort(getNumBands(product))));
setEntry(new TiffDirectoryEntry(TiffTag.STRIP_OFFSETS, calculateStripOffsets()));
setEntry(new TiffDirectoryEntry(TiffTag.ROWS_PER_STRIP, new TiffLong(height)));
setEntry(new TiffDirectoryEntry(TiffTag.STRIP_BYTE_COUNTS, calculateStripByteCounts()));
setEntry(new TiffDirectoryEntry(TiffTag.X_RESOLUTION, new TiffRational(1, 1)));
setEntry(new TiffDirectoryEntry(TiffTag.Y_RESOLUTION, new TiffRational(1, 1)));
setEntry(new TiffDirectoryEntry(TiffTag.RESOLUTION_UNIT, new TiffShort(1)));
setEntry(new TiffDirectoryEntry(TiffTag.PLANAR_CONFIGURATION, TiffCode.PLANAR_CONFIG_PLANAR));
setEntry(new TiffDirectoryEntry(TiffTag.SAMPLE_FORMAT, calculateSampleFormat(product)));
setEntry(new TiffDirectoryEntry(TiffTag.BEAM_METADATA, getBeamMetadata(product)));
TiffShort[] colorMap = null;
if (isValidColorMapProduct(product)) {
colorMap = createColorMap(product);
}
if (colorMap != null) {
setEntry(new TiffDirectoryEntry(TiffTag.PHOTOMETRIC_INTERPRETATION, TiffCode.PHOTOMETRIC_RGB_PALETTE));
setEntry(new TiffDirectoryEntry(TiffTag.COLOR_MAP, colorMap));
} else {
setEntry(new TiffDirectoryEntry(TiffTag.PHOTOMETRIC_INTERPRETATION, TiffCode.PHOTOMETRIC_BLACK_IS_ZERO));
}
addGeoTiffTags(product);
}
private static int getNumBands(Product product) {
final Band[] bands = product.getBands();
final List<Band> bandList = new ArrayList<Band>(bands.length);
for (Band band : bands) {
if (Utils.shouldWriteNode(band)) {
bandList.add(band);
}
}
return bandList.size();
}
private TiffShort[] createColorMap(Product product) {
final ImageInfo imageInfo = product.getBandAt(0).getImageInfo(null, ProgressMonitor.NULL);
final ColorPaletteDef paletteDef = imageInfo.getColorPaletteDef();
final TiffShort[] redColor = new TiffShort[TIFF_COLORMAP_SIZE];
Arrays.fill(redColor, new TiffShort(0));
final TiffShort[] greenColor = new TiffShort[TIFF_COLORMAP_SIZE];
Arrays.fill(greenColor, new TiffShort(0));
final TiffShort[] blueColor = new TiffShort[TIFF_COLORMAP_SIZE];
Arrays.fill(blueColor, new TiffShort(0));
final float factor = 65535.0f / 255.0f;
for (ColorPaletteDef.Point point : paletteDef.getPoints()) {
final Color color = point.getColor();
final int red = (int) (color.getRed() * factor);
final int green = (int) (color.getGreen() * factor);
final int blue = (int) (color.getBlue() * factor);
int mapIndex = (int) Math.floor(point.getSample());
redColor[mapIndex] = new TiffShort(red);
greenColor[mapIndex] = new TiffShort(green);
blueColor[mapIndex] = new TiffShort(blue);
}
final TiffShort[] colorMap = new TiffShort[TIFF_COLORMAP_SIZE * 3];
System.arraycopy(redColor, 0, colorMap, 0, redColor.length);
System.arraycopy(greenColor, 0, colorMap, TIFF_COLORMAP_SIZE, greenColor.length);
System.arraycopy(blueColor, 0, colorMap, TIFF_COLORMAP_SIZE * 2, blueColor.length);
return colorMap;
}
private static boolean isValidColorMapProduct(Product product) {
return getNumBands(product) == 1 && product.getBandAt(0).getIndexCoding() != null &&
product.getBandAt(0).getDataType() == ProductData.TYPE_UINT8;
}
static TiffAscii getBeamMetadata(final Product product) {
final StringWriter stringWriter = new StringWriter();
final DimapHeaderWriter writer = new DimapHeaderWriter(product, stringWriter, "");
writer.writeHeader();
writer.close();
return new TiffAscii(stringWriter.getBuffer().toString());
}
private void addGeoTiffTags(final Product product) {
final GeoTIFFMetadata geoTIFFMetadata = ProductUtils.createGeoTIFFMetadata(product);
if (geoTIFFMetadata == null) {
return;
}
// for debug purpose
// geoTIFFMetadata.dump();
final int numEntries = geoTIFFMetadata.getNumGeoKeyEntries();
final TiffShort[] directoryTagValues = new TiffShort[numEntries * 4];
final ArrayList<TiffDouble> doubleValues = new ArrayList<TiffDouble>();
final ArrayList<String> asciiValues = new ArrayList<String>();
for (int i = 0; i < numEntries; i++) {
final GeoTIFFMetadata.KeyEntry entry = geoTIFFMetadata.getGeoKeyEntryAt(i);
final int[] data = entry.getData();
for (int j = 0; j < data.length; j++) {
directoryTagValues[i * 4 + j] = new TiffShort(data[j]);
}
if (data[1] == TiffTag.GeoDoubleParamsTag.getValue()) {
directoryTagValues[i * 4 + 3] = new TiffShort(doubleValues.size());
final double[] geoDoubleParams = geoTIFFMetadata.getGeoDoubleParams(data[0]);
for (double geoDoubleParam : geoDoubleParams) {
doubleValues.add(new TiffDouble(geoDoubleParam));
}
}
if (data[1] == TiffTag.GeoAsciiParamsTag.getValue()) {
int sizeInBytes = 0;
for (String asciiValue : asciiValues) {
sizeInBytes += asciiValue.length() + 1;
}
directoryTagValues[i * 4 + 3] = new TiffShort(sizeInBytes);
asciiValues.add(geoTIFFMetadata.getGeoAsciiParam(data[0]));
}
}
setEntry(new TiffDirectoryEntry(TiffTag.GeoKeyDirectoryTag, directoryTagValues));
if (!doubleValues.isEmpty()) {
final TiffDouble[] tiffDoubles = doubleValues.toArray(new TiffDouble[doubleValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoDoubleParamsTag, tiffDoubles));
}
if (!asciiValues.isEmpty()) {
final String[] tiffAsciies = asciiValues.toArray(new String[asciiValues.size()]);
setEntry(new TiffDirectoryEntry(TiffTag.GeoAsciiParamsTag, new GeoTiffAscii(tiffAsciies)));
}
double[] modelTransformation = geoTIFFMetadata.getModelTransformation();
if (!isZeroArray(modelTransformation)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelTransformationTag, toTiffDoubles(modelTransformation)));
} else {
double[] modelPixelScale = geoTIFFMetadata.getModelPixelScale();
if (!isZeroArray(modelPixelScale)) {
setEntry(new TiffDirectoryEntry(TiffTag.ModelPixelScaleTag, toTiffDoubles(modelPixelScale)));
}
final int numModelTiePoints = geoTIFFMetadata.getNumModelTiePoints();
if (numModelTiePoints > 0) {
final TiffDouble[] tiePoints = new TiffDouble[numModelTiePoints * 6];
for (int i = 0; i < numModelTiePoints; i++) {
final GeoTIFFMetadata.TiePoint modelTiePoint = geoTIFFMetadata.getModelTiePointAt(i);
final double[] data = modelTiePoint.getData();
for (int j = 0; j < data.length; j++) {
tiePoints[i * 6 + j] = new TiffDouble(data[j]);
}
}
setEntry(new TiffDirectoryEntry(TiffTag.ModelTiepointTag, tiePoints));
}
}
}
private static TiffDouble[] toTiffDoubles(double[] a) {
final TiffDouble[] td = new TiffDouble[a.length];
for (int i = 0; i < a.length; i++) {
td[i] = new TiffDouble(a[i]);
}
return td;
}
private static boolean isZeroArray(double[] a) {
for (double v : a) {
if (v != 0.0) {
return false;
}
}
return true;
}
static int getMaxElemSizeBandDataType(final Band[] bands) {
int maxSignedIntType = -1;
int maxUnsignedIntType = -1;
int maxFloatType = -1;
for (Band band : bands) {
int dt = band.getDataType();
if (ProductData.isIntType(dt)) {
if (ProductData.isUIntType(dt)) {
maxUnsignedIntType = Math.max(maxUnsignedIntType, dt);
} else {
maxSignedIntType = Math.max(maxSignedIntType, dt);
}
}
if (ProductData.isFloatingPointType(dt)) {
maxFloatType = Math.max(maxFloatType, dt);
}
}
if (maxFloatType != -1) {
return ProductData.TYPE_FLOAT32;
}
if (maxUnsignedIntType != -1) {
if (maxSignedIntType == -1) {
return maxUnsignedIntType;
}
if (ProductData.getElemSize(maxUnsignedIntType) >= ProductData.getElemSize(maxSignedIntType)) {
int returnType = maxUnsignedIntType - 10 + 1;
if (returnType > 12) {
return ProductData.TYPE_FLOAT32;
} else {
return returnType;
}
}
}
if (maxSignedIntType != -1) {
return maxSignedIntType;
}
return DataBuffer.TYPE_UNDEFINED;
}
private TiffShort[] calculateSampleFormat(final Product product) {
int dataType = getBandDataType();
TiffShort sampleFormat;
if (ProductData.isUIntType(dataType)) {
sampleFormat = TiffCode.SAMPLE_FORMAT_UINT;
} else if (ProductData.isIntType(dataType)) {
sampleFormat = TiffCode.SAMPLE_FORMAT_INT;
} else {
sampleFormat = TiffCode.SAMPLE_FORMAT_FLOAT;
}
final TiffShort[] tiffValues = new TiffShort[getNumBands(product)];
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = sampleFormat;
}
return tiffValues;
}
private TiffLong[] calculateStripByteCounts() {
TiffValue[] bitsPerSample = getBitsPerSampleValues();
final TiffLong[] tiffValues = new TiffLong[bitsPerSample.length];
for (int i = 0; i < tiffValues.length; i++) {
long byteCount = getByteCount(bitsPerSample, i);
tiffValues[i] = new TiffLong(byteCount);
}
return tiffValues;
}
private TiffLong[] calculateStripOffsets() {
TiffValue[] bitsPerSample = getBitsPerSampleValues();
final TiffLong[] tiffValues = new TiffLong[bitsPerSample.length];
long offset = 0;
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = new TiffLong(offset);
long byteCount = getByteCount(bitsPerSample, i);
offset += byteCount;
if (offset > MAX_FILE_SIZE) {
String msg = String.format("File size too big. TIFF file size is limited to [%d] bytes!", MAX_FILE_SIZE);
throw new IllegalStateException(msg);
}
}
return tiffValues;
}
private long getByteCount(TiffValue[] bitsPerSample, int i) {
long bytesPerSample = ((TiffShort) bitsPerSample[i]).getValue() / 8;
return getWidth() * getHeight() * bytesPerSample;
}
private TiffShort[] calculateBitsPerSample(final Product product) {
int dataType = getBandDataType();
int elemSize = ProductData.getElemSize(dataType);
final TiffShort[] tiffValues = new TiffShort[getNumBands(product)];
for (int i = 0; i < tiffValues.length; i++) {
tiffValues[i] = new TiffShort(8 * elemSize);
}
return tiffValues;
}
private TiffValue[] getBitsPerSampleValues() {
return getEntry(TiffTag.BITS_PER_SAMPLE).getValues();
}
private long getHeight() {
return ((TiffLong) getEntry(TiffTag.IMAGE_LENGTH).getValues()[0]).getValue();
}
private long getWidth() {
return ((TiffLong) getEntry(TiffTag.IMAGE_WIDTH).getValues()[0]).getValue();
}
}
| arraydev/snap-engine | snap-geotiff/src/main/java/org/esa/snap/dataio/geotiff/internal/TiffIFD.java | Java | gpl-3.0 | 18,601 |
/*
* Syncany, www.syncany.org
* Copyright (C) 2011-2016 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.cli;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
import org.syncany.cli.util.CliTableUtil;
import org.syncany.operations.OperationResult;
import org.syncany.operations.daemon.messages.ConnectToHostExternalEvent;
import org.syncany.operations.daemon.messages.PluginInstallExternalEvent;
import org.syncany.operations.plugin.ExtendedPluginInfo;
import org.syncany.operations.plugin.PluginInfo;
import org.syncany.operations.plugin.PluginOperation;
import org.syncany.operations.plugin.PluginOperationAction;
import org.syncany.operations.plugin.PluginOperationOptions;
import org.syncany.operations.plugin.PluginOperationOptions.PluginListMode;
import org.syncany.operations.plugin.PluginOperationResult;
import org.syncany.operations.plugin.PluginOperationResult.PluginResultCode;
import org.syncany.util.StringUtil;
import com.google.common.collect.Iterables;
import com.google.common.eventbus.Subscribe;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
public class PluginCommand extends Command {
private boolean minimalOutput = false;
@Override
public CommandScope getRequiredCommandScope() {
return CommandScope.ANY;
}
@Override
public boolean canExecuteInDaemonScope() {
return false; // TODO [low] Doesn't have an impact if command scope is ANY
}
@Override
public int execute(String[] operationArgs) throws Exception {
PluginOperationOptions operationOptions = parseOptions(operationArgs);
PluginOperationResult operationResult = new PluginOperation(config, operationOptions).execute();
printResults(operationResult);
return 0;
}
@Override
public PluginOperationOptions parseOptions(String[] operationArgs) throws Exception {
PluginOperationOptions operationOptions = new PluginOperationOptions();
OptionParser parser = new OptionParser();
OptionSpec<Void> optionLocal = parser.acceptsAll(asList("L", "local-only"));
OptionSpec<Void> optionRemote = parser.acceptsAll(asList("R", "remote-only"));
OptionSpec<Void> optionSnapshots = parser.acceptsAll(asList("s", "snapshot", "snapshots"));
OptionSpec<Void> optionMinimalOutput = parser.acceptsAll(asList("m", "minimal-output"));
OptionSpec<String> optionApiEndpoint = parser.acceptsAll(asList("a", "api-endpoint")).withRequiredArg();
OptionSet options = parser.parse(operationArgs);
// Files
List<?> nonOptionArgs = options.nonOptionArguments();
if (nonOptionArgs.size() == 0) {
throw new Exception("Invalid syntax, please specify an action (list, install, remove, update).");
}
// <action>
String actionStr = nonOptionArgs.get(0).toString();
PluginOperationAction action = parsePluginAction(actionStr);
operationOptions.setAction(action);
// --minimal-output
minimalOutput = options.has(optionMinimalOutput);
// --snapshots
operationOptions.setSnapshots(options.has(optionSnapshots));
// --api-endpoint
if (options.has(optionApiEndpoint)) {
operationOptions.setApiEndpoint(options.valueOf(optionApiEndpoint));
}
// install|remove <plugin-id>
if (action == PluginOperationAction.INSTALL || action == PluginOperationAction.REMOVE) {
if (nonOptionArgs.size() != 2) {
throw new Exception("Invalid syntax, please specify a plugin ID.");
}
// <plugin-id>
String pluginId = nonOptionArgs.get(1).toString();
operationOptions.setPluginId(pluginId);
}
// --local-only, --remote-only
else if (action == PluginOperationAction.LIST) {
if (options.has(optionLocal)) {
operationOptions.setListMode(PluginListMode.LOCAL);
}
else if (options.has(optionRemote)) {
operationOptions.setListMode(PluginListMode.REMOTE);
}
else {
operationOptions.setListMode(PluginListMode.ALL);
}
// <plugin-id> (optional in 'list' or 'update')
if (nonOptionArgs.size() == 2) {
String pluginId = nonOptionArgs.get(1).toString();
operationOptions.setPluginId(pluginId);
}
}
else if (action == PluginOperationAction.UPDATE && nonOptionArgs.size() == 2) {
String pluginId = nonOptionArgs.get(1).toString();
operationOptions.setPluginId(pluginId);
}
return operationOptions;
}
private PluginOperationAction parsePluginAction(String actionStr) throws Exception {
try {
return PluginOperationAction.valueOf(actionStr.toUpperCase());
}
catch (Exception e) {
throw new Exception("Invalid syntax, unknown action '" + actionStr + "'");
}
}
@Override
public void printResults(OperationResult operationResult) {
PluginOperationResult concreteOperationResult = (PluginOperationResult) operationResult;
switch (concreteOperationResult.getAction()) {
case LIST:
printResultList(concreteOperationResult);
return;
case INSTALL:
printResultInstall(concreteOperationResult);
return;
case REMOVE:
printResultRemove(concreteOperationResult);
return;
case UPDATE:
printResultUpdate(concreteOperationResult);
return;
default:
out.println("Unknown action: " + concreteOperationResult.getAction());
}
}
private void printResultList(PluginOperationResult operationResult) {
if (operationResult.getResultCode() == PluginResultCode.OK) {
List<String[]> tableValues = new ArrayList<String[]>();
tableValues.add(new String[]{"Id", "Name", "Local Version", "Type", "Remote Version", "Updatable", "Provided By"});
int outdatedCount = 0;
int updatableCount = 0;
int thirdPartyCount = 0;
for (ExtendedPluginInfo extPluginInfo : operationResult.getPluginList()) {
PluginInfo pluginInfo = (extPluginInfo.isInstalled()) ? extPluginInfo.getLocalPluginInfo() : extPluginInfo.getRemotePluginInfo();
String localVersionStr = (extPluginInfo.isInstalled()) ? extPluginInfo.getLocalPluginInfo().getPluginVersion() : "";
String installedStr = extPluginInfo.isInstalled() ? (extPluginInfo.canUninstall() ? "User" : "Global") : "";
String remoteVersionStr = (extPluginInfo.isRemoteAvailable()) ? extPluginInfo.getRemotePluginInfo().getPluginVersion() : "";
String thirdPartyStr = (pluginInfo.isPluginThirdParty()) ? "Third Party" : "Syncany Team";
String updatableStr = "";
if (extPluginInfo.isInstalled() && extPluginInfo.isOutdated()) {
if (extPluginInfo.canUninstall()) {
updatableStr = "Auto";
updatableCount++;
}
else {
updatableStr = "Manual";
}
outdatedCount++;
}
if (pluginInfo.isPluginThirdParty()) {
thirdPartyCount++;
}
tableValues.add(new String[]{pluginInfo.getPluginId(), pluginInfo.getPluginName(), localVersionStr, installedStr, remoteVersionStr, updatableStr, thirdPartyStr});
}
CliTableUtil.printTable(out, tableValues, "No plugins found.");
if (outdatedCount > 0) {
String isAre = (outdatedCount == 1) ? "is" : "are";
String pluginPlugins = (outdatedCount == 1) ? "plugin" : "plugins";
out.printf("\nUpdates:\nThere %s %d outdated %s, %d of them %s automatically updatable.\n", isAre, outdatedCount, pluginPlugins, updatableCount, isAre);
}
if (thirdPartyCount > 0) {
String pluginPlugins = (thirdPartyCount == 1) ? "plugin" : "plugins";
out.printf("\nThird party plugins:\nPlease note that the Syncany Team does not review or maintain the third-party %s\nlisted above. Please report issues to the corresponding plugin site.\n", pluginPlugins);
}
}
else {
out.printf("Listing plugins failed. No connection? Try -d to get more details.\n");
out.println();
}
}
private void printResultInstall(PluginOperationResult operationResult) {
// Print minimal result
if (minimalOutput) {
if (operationResult.getResultCode() == PluginResultCode.OK) {
out.println("OK");
}
else {
out.println("NOK");
}
}
// Print regular result
else {
if (operationResult.getResultCode() == PluginResultCode.OK) {
out.printf("Plugin successfully installed from %s\n", operationResult.getSourcePluginPath());
out.printf("Install location: %s\n", operationResult.getTargetPluginPath());
out.println();
printPluginDetails(operationResult.getAffectedPluginInfo());
printPluginConflictWarning(operationResult);
}
else {
out.println("Plugin installation failed. Try -d to get more details.");
out.println();
}
}
}
private void printResultUpdate(final PluginOperationResult operationResult) {
// Print regular result
if (operationResult.getResultCode() == PluginResultCode.OK) {
if (operationResult.getUpdatedPluginIds().size() == 0) {
out.println("All plugins are up to date.");
}
else {
Iterables.removeAll(operationResult.getUpdatedPluginIds(), operationResult.getErroneousPluginIds());
Iterables.removeAll(operationResult.getUpdatedPluginIds(), operationResult.getDelayedPluginIds());
if (operationResult.getDelayedPluginIds().size() > 0) {
out.printf("Plugins to be updated: %s\n", StringUtil.join(operationResult.getDelayedPluginIds(), ", "));
}
if (operationResult.getUpdatedPluginIds().size() > 0) {
out.printf("Plugins successfully updated: %s\n", StringUtil.join(operationResult.getUpdatedPluginIds(), ", "));
}
if (operationResult.getErroneousPluginIds().size() > 0) {
out.printf("Failed to update %s. Try -d to get more details\n", StringUtil.join(operationResult.getErroneousPluginIds(), ", "));
}
out.println();
}
}
else {
out.println("Plugin update failed. Try -d to get more details.");
out.println();
}
}
private void printPluginConflictWarning(PluginOperationResult operationResult) {
List<String> conflictingPluginIds = operationResult.getConflictingPluginIds();
if (conflictingPluginIds != null && conflictingPluginIds.size() > 0) {
out.println("---------------------------------------------------------------------------");
out.printf(" WARNING: The installed plugin '%s' conflicts with other installed:\n", operationResult.getAffectedPluginInfo().getPluginId());
out.printf(" plugin(s): %s\n", StringUtil.join(conflictingPluginIds, ", "));
out.println();
out.println(" If you'd like to use these plugins in the daemon, it is VERY likely");
out.println(" that parts of the application WILL CRASH. Data corruption might occur!");
out.println();
out.println(" Using the plugins outside of the daemon (sy <command> ...) might also");
out.println(" be an issue. Details about this in issue #154.");
out.println("---------------------------------------------------------------------------");
out.println();
}
}
private void printResultRemove(PluginOperationResult operationResult) {
// Print minimal result
if (minimalOutput) {
if (operationResult.getResultCode() == PluginResultCode.OK) {
out.println("OK");
}
else {
out.println("NOK");
}
}
// Print regular result
else {
if (operationResult.getResultCode() == PluginResultCode.OK) {
out.printf("Plugin successfully removed.\n");
out.printf("Original local was %s\n", operationResult.getSourcePluginPath());
out.println();
}
else {
out.println("Plugin removal failed.");
out.println();
out.println("Note: Plugins shipped with the application or additional packages");
out.println(" cannot be removed. These plugin are marked 'Global' in the list.");
out.println();
}
}
}
private void printPluginDetails(PluginInfo pluginInfo) {
out.println("Plugin details:");
out.println("- ID: " + pluginInfo.getPluginId());
out.println("- Name: " + pluginInfo.getPluginName());
out.println("- Version: " + pluginInfo.getPluginVersion());
out.println();
}
@Subscribe
public void onConnectToHostEventReceived(ConnectToHostExternalEvent event) {
if (!minimalOutput) {
out.printr("Connecting to " + event.getHost() + " ...");
}
}
@Subscribe
public void onPluginInstallEventReceived(PluginInstallExternalEvent event) {
if (!minimalOutput) {
out.printr("Installing plugin from " + event.getSource() + " ...");
}
}
}
| syncany/syncany-plugin-sftp | core/syncany-cli/src/main/java/org/syncany/cli/PluginCommand.java | Java | gpl-3.0 | 12,796 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.cts.verifier.sensors.helpers;
import com.android.cts.verifier.R;
import com.android.cts.verifier.sensors.base.BaseSensorTestActivity;
import com.android.cts.verifier.sensors.base.ISensorTestStateContainer;
/**
* A helper class for {@link SensorFeaturesDeactivator}. It abstracts the responsibility of handling
* device settings that affect sensors.
*
* This class is meant to be used only by {@link SensorFeaturesDeactivator}.
* To keep things simple, this class synchronizes access to its internal state on public methods.
* This approach is fine, because there is no need for concurrent access.
*/
abstract class SensorSettingContainer {
private static final int DEFAULT_SETTING_VALUE = -1;
private final String mAction;
private final int mSettingNameResId;
private boolean mInitialized;
private boolean mSettingAvailable;
private boolean mCapturedModeOn;
public SensorSettingContainer(String action, int settingNameResId) {
mAction = action;
mSettingNameResId = settingNameResId;
}
public synchronized void captureInitialState() {
if (mInitialized) {
return;
}
mSettingAvailable = getSettingMode(DEFAULT_SETTING_VALUE) != DEFAULT_SETTING_VALUE;
mCapturedModeOn = getCurrentSettingMode();
mInitialized = true;
}
public synchronized void requestToSetMode(
ISensorTestStateContainer stateContainer,
boolean modeOn) throws InterruptedException {
if (!isSettingAvailable()) {
return;
}
trySetMode(stateContainer, modeOn);
if (getCurrentSettingMode() != modeOn) {
String message = stateContainer.getString(
R.string.snsr_setting_mode_not_set,
getSettingName(stateContainer),
modeOn);
throw new IllegalStateException(message);
}
}
public synchronized void requestToResetMode(ISensorTestStateContainer stateContainer)
throws InterruptedException {
if (!isSettingAvailable()) {
return;
}
trySetMode(stateContainer, mCapturedModeOn);
}
private void trySetMode(ISensorTestStateContainer stateContainer, boolean modeOn)
throws InterruptedException {
BaseSensorTestActivity.SensorTestLogger logger = stateContainer.getTestLogger();
String settingName = getSettingName(stateContainer);
if (getCurrentSettingMode() == modeOn) {
logger.logMessage(R.string.snsr_setting_mode_set, settingName, modeOn);
return;
}
logger.logInstructions(R.string.snsr_setting_mode_request, settingName, modeOn);
logger.logInstructions(R.string.snsr_on_complete_return);
stateContainer.waitForUserToContinue();
stateContainer.executeActivity(mAction);
}
private boolean getCurrentSettingMode() {
return getSettingMode(DEFAULT_SETTING_VALUE) != 0;
}
private String getSettingName(ISensorTestStateContainer stateContainer) {
return stateContainer.getString(mSettingNameResId);
}
private boolean isSettingAvailable() {
if (!mInitialized) {
throw new IllegalStateException(
"Object must be initialized first by invoking #captureInitialState.");
}
return mSettingAvailable;
}
protected abstract int getSettingMode(int defaultValue);
}
| s20121035/rk3288_android5.1_repo | cts/apps/CtsVerifier/src/com/android/cts/verifier/sensors/helpers/SensorSettingContainer.java | Java | gpl-3.0 | 4,097 |
package twitter4j.api;
import twitter4j.Activity;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.TwitterException;
public interface UndocumentedActivityResources extends UndocumentedResources {
public ResponseList<Activity> getActivitiesAboutMe() throws TwitterException;
public ResponseList<Activity> getActivitiesAboutMe(Paging paging) throws TwitterException;
public ResponseList<Activity> getActivitiesByFriends() throws TwitterException;
public ResponseList<Activity> getActivitiesByFriends(Paging paging) throws TwitterException;
}
| 0359xiaodong/twidere | src/twitter4j/api/UndocumentedActivityResources.java | Java | gpl-3.0 | 573 |
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.widget;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
public class ResizablePathDrawable extends ShapeDrawable {
// An attribute mirroring the super class' value. getAlpha() is only
// available in API 19+ so to use that alpha value, we have to mirror it.
private int alpha = 255;
private final ColorStateList colorStateList;
private int currentColor;
public ResizablePathDrawable(NonScaledPathShape shape, int color) {
this(shape, ColorStateList.valueOf(color));
}
public ResizablePathDrawable(NonScaledPathShape shape, ColorStateList colorStateList) {
super(shape);
this.colorStateList = colorStateList;
updateColor(getState());
}
private boolean updateColor(int[] stateSet) {
int newColor = colorStateList.getColorForState(stateSet, Color.WHITE);
if (newColor != currentColor) {
currentColor = newColor;
alpha = Color.alpha(currentColor);
invalidateSelf();
return true;
}
return false;
}
public Path getPath() {
final NonScaledPathShape shape = (NonScaledPathShape) getShape();
return shape.path;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
paint.setColor(currentColor);
// setAlpha overrides the alpha value in set color. Since we just set the color,
// the alpha value is reset: override the alpha value with the old value. We don't
// set alpha if the color is transparent.
//
// Note: We *should* be able to call Shape.setAlpha, rather than Paint.setAlpha, but
// then the opacity doesn't change - dunno why but probably not worth the time.
if (currentColor != Color.TRANSPARENT) {
paint.setAlpha(alpha);
}
super.onDraw(shape, canvas, paint);
}
@Override
public void setAlpha(final int alpha) {
super.setAlpha(alpha);
this.alpha = alpha;
}
@Override
protected boolean onStateChange(int[] stateSet) {
return updateColor(stateSet);
}
/**
* Path-based shape implementation that re-creates the path
* when it gets resized as opposed to PathShape's scaling
* behaviour.
*/
public static class NonScaledPathShape extends Shape {
private Path path;
public NonScaledPathShape() {
path = new Path();
}
@Override
public void draw(Canvas canvas, Paint paint) {
// No point in drawing the shape if it's not
// going to be visible.
if (paint.getColor() == Color.TRANSPARENT) {
return;
}
canvas.drawPath(path, paint);
}
protected Path getPath() {
return path;
}
@Override
public NonScaledPathShape clone() throws CloneNotSupportedException {
final NonScaledPathShape clonedShape = (NonScaledPathShape) super.clone();
clonedShape.path = new Path(path);
return clonedShape;
}
}
}
| jrconlin/mc_backup | base/widget/ResizablePathDrawable.java | Java | mpl-2.0 | 3,714 |
package org.jcodec.common.model;
/**
* This class is part of JCodec ( www.jcodec.org )
* This software is distributed under FreeBSD License
*
* @author The JCodec project
*
*/
public class Picture8Bit {
private int width;
private int height;
private byte[] y;
private byte[] cb;
private byte[] cr;
public Picture8Bit(int width, int height, byte[] y, byte[] cb, byte[] cr) {
this.width = width;
this.height = height;
this.y = y;
this.cb = cb;
this.cr = cr;
}
public static Picture8Bit create422(int width, int height) {
return new Picture8Bit(width, height, new byte[width * height], new byte[(width * height) >> 1],
new byte[(width * height) >> 1]);
}
public static Picture8Bit create420(int width, int height) {
return new Picture8Bit(width, height, new byte[width * height], new byte[(width * height) >> 2],
new byte[(width * height) >> 2]);
}
public Picture8Bit(Picture8Bit other) {
this(other.width, other.height, other.y, other.cb, other.cr);
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public byte[] getY() {
return y;
}
public byte[] getCb() {
return cb;
}
public byte[] getCr() {
return cr;
}
} | OpenSpaceDev/OpenSpaceDVR | src/org/jcodec/common/model/Picture8Bit.java | Java | mpl-2.0 | 1,387 |
/*
* SimplePanelWithProgress.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.core.client.widget;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
public class SimplePanelWithProgress extends SimplePanel
implements ProvidesResize,
RequiresResize
{
public SimplePanelWithProgress()
{
loadProgressPanel_ = new ProgressPanel();
}
public SimplePanelWithProgress(Widget progressImage)
{
loadProgressPanel_ = new ProgressPanel(progressImage);
}
public SimplePanelWithProgress(Widget progressImage, int verticalOffset)
{
loadProgressPanel_ = new ProgressPanel(progressImage, verticalOffset);
}
@Override
public void setWidget(Widget widget)
{
if (isProgressShowing())
loadProgressPanel_.endProgressOperation();
super.setWidget(widget);
}
public void showProgress(int delayMs)
{
showProgress(delayMs, null);
}
public void showProgress(int delayMs, String message)
{
if (!isProgressShowing())
{
setWidget(loadProgressPanel_);
loadProgressPanel_.beginProgressOperation(delayMs, message);
}
}
public boolean isProgressShowing()
{
return loadProgressPanel_.equals(getWidget());
}
public void onResize()
{
if (getWidget() instanceof RequiresResize)
((RequiresResize)getWidget()).onResize();
}
private ProgressPanel loadProgressPanel_ = new ProgressPanel();
}
| JanMarvin/rstudio | src/gwt/src/org/rstudio/core/client/widget/SimplePanelWithProgress.java | Java | agpl-3.0 | 2,226 |
/*******************************************************************************
* 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 [email protected]).
*
* 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: [email protected]
******************************************************************************/
package com.lp.client.personal;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.EventObject;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.border.Border;
import com.lp.client.frame.ExceptionLP;
import com.lp.client.frame.HelperClient;
import com.lp.client.frame.component.DialogQuery;
import com.lp.client.frame.component.ISourceEvent;
import com.lp.client.frame.component.InternalFrame;
import com.lp.client.frame.component.ItemChangedEvent;
import com.lp.client.frame.component.PanelBasis;
import com.lp.client.frame.component.PanelQueryFLR;
import com.lp.client.frame.component.WrapperButton;
import com.lp.client.frame.component.WrapperCheckBox;
import com.lp.client.frame.component.WrapperComboBox;
import com.lp.client.frame.component.WrapperDateField;
import com.lp.client.frame.component.WrapperEditorField;
import com.lp.client.frame.component.WrapperEditorFieldKommentar;
import com.lp.client.frame.component.WrapperEmailField;
import com.lp.client.frame.component.WrapperLabel;
import com.lp.client.frame.component.WrapperPasswordField;
import com.lp.client.frame.component.WrapperTelefonField;
import com.lp.client.frame.component.WrapperTextField;
import com.lp.client.frame.delegate.DelegateFactory;
import com.lp.client.frame.dialog.DialogFactory;
import com.lp.client.partner.PartnerFilterFactory;
import com.lp.client.pc.LPMain;
import com.lp.client.system.SystemFilterFactory;
import com.lp.server.benutzer.service.BenutzerFac;
import com.lp.server.partner.service.PartnerDto;
import com.lp.server.partner.service.PartnerFac;
import com.lp.server.personal.service.BerufDto;
import com.lp.server.personal.service.KollektivDto;
import com.lp.server.personal.service.LohngruppeDto;
import com.lp.server.personal.service.PendlerpauschaleDto;
import com.lp.server.personal.service.PersonalDto;
import com.lp.server.personal.service.PersonalFac;
import com.lp.server.personal.service.ReligionDto;
import com.lp.server.system.service.LandDto;
import com.lp.server.system.service.LandplzortDto;
import com.lp.server.system.service.SystemFac;
import com.lp.server.util.fastlanereader.service.query.QueryParameters;
//@SuppressWarnings("static-access")
public class PanelPersonaldaten extends PanelBasis {
/**
*
*/
private static final long serialVersionUID = 1L;
PersonalDto personalDto = null;
private InternalFramePersonal internalFramePersonal = null;
private GridBagLayout gridBagLayoutAll = null;
private JPanel jpaWorkingOn = new JPanel();
private JPanel jpaButtonAction = null;
private Border border = null;
private GridBagLayout gridBagLayoutWorkingPanel = null;
private WrapperLabel wlaGeburtsdatum = new WrapperLabel();
private WrapperDateField wdfGeburtsdatum = new WrapperDateField();
private WrapperButton wbuGeburtsort = new WrapperButton();
private WrapperTextField wtfGeburtsort = new WrapperTextField();
private WrapperLabel wlaSozialversicherungsnummer = new WrapperLabel();
private WrapperTextField wtfsozialversicherungsnummer = new WrapperTextField();
private WrapperButton wbuSozialversicherer = new WrapperButton();
private WrapperButton wbuKollektiv = new WrapperButton();
private WrapperTextField wtfKollektiv = new WrapperTextField();
private WrapperTextField wtfSozialversicherer = new WrapperTextField();
private WrapperButton wbuBeruf = new WrapperButton();
private WrapperTextField wtfBeruf = new WrapperTextField();
private WrapperButton wbuLohngruppe = new WrapperButton();
private WrapperTextField wtfLohngruppe = new WrapperTextField();
private WrapperCheckBox wcbKeineAnzeigeInAnwesenheitsliste = new WrapperCheckBox();
private WrapperCheckBox wcbBekommtUeberstundenausbezahlt = new WrapperCheckBox();
private WrapperCheckBox wcbAnwesenheitslisteTermial = new WrapperCheckBox();
private WrapperCheckBox wcbAnwesenheitslisteAlleTermial = new WrapperCheckBox();
private WrapperEditorField wefSignatur = null;
private WrapperLabel wlaSignatur = new WrapperLabel();
private WrapperTextField wtfPendlerpauschale = new WrapperTextField();
private WrapperButton wbuPendlerpauschale = new WrapperButton();
private WrapperComboBox wcbFamilienstand = new WrapperComboBox();
private WrapperLabel wlaFamilienstand = new WrapperLabel();
private WrapperTextField wtfStaatsangehoerigkeit = new WrapperTextField();
private WrapperButton wbuStaatsangehoerigkeit = new WrapperButton();
private WrapperTextField wtfReligion = new WrapperTextField();
private WrapperButton wbuReligion = new WrapperButton();
private WrapperTextField wtfFirmenzugehoerigkeit = new WrapperTextField();
private WrapperButton wbuFirmenzugehoerigkeit = new WrapperButton();
private WrapperCheckBox wcbTelefonzeitStarten = null;
private WrapperLabel wlaDurchwahl = null;
private WrapperTextField wtfDurchwahl = null;
private WrapperLabel wlaEmail = null;
private WrapperEmailField wtfEmail = null;
private WrapperLabel wlaFaxdurchwahl = null;
private WrapperTextField wtfFaxdurchwahl = null;
private WrapperLabel wlaHandy = null;
private WrapperTelefonField wtfHandy = null;
private WrapperLabel wlaDirektfax = null;
private WrapperTextField wtfDirektfax = null;
private WrapperTextField wtfUnterschriftsfunktion = new WrapperTextField();
private WrapperTextField wtfUnterschriftstext = new WrapperTextField();
private WrapperLabel wlaUnterschriftsfunktion = new WrapperLabel();
private WrapperLabel wlaUnterschriftstext = new WrapperLabel();
private PanelQueryFLR panelQueryFLRGeburtsort = null;
private PanelQueryFLR panelQueryFLRSozialversicherer = null;
private PanelQueryFLR panelQueryFLRStaatsangehoerigkeit = null;
private PanelQueryFLR panelQueryFLRReligion = null;
private PanelQueryFLR panelQueryFLRKollektiv = null;
private PanelQueryFLR panelQueryFLRBeruf = null;
private PanelQueryFLR panelQueryFLRPendlerpauschale = null;
private PanelQueryFLR panelQueryFLRLohngrupe = null;
private PanelQueryFLR panelQueryFLRfirmenzugehoerigkeit = null;
private WrapperLabel wlaImapBenutzer = new WrapperLabel();
private WrapperTextField wtfImapBenutzer = new WrapperTextField();
private WrapperLabel wlaImapKennwort = new WrapperLabel();
private WrapperPasswordField wtfImapKennwort = new WrapperPasswordField();
private WrapperLabel wlaImapInboxFolder = new WrapperLabel() ;
private WrapperTextField wtfImapInboxFolder = new WrapperTextField() ;
static final public String ACTION_SPECIAL_GEBURTSORT_FROM_LISTE = "action_geburtsort_from_liste";
static final public String ACTION_SPECIAL_SOZIALVERISCHERER_FROM_LISTE = "action_sozialversicherer_from_liste";
static final public String ACTION_SPECIAL_STAATSANGEHOERIGKEIT_FROM_LISTE = "action_staatsangehoerigkeit_from_liste";
static final public String ACTION_SPECIAL_RELIGION_FROM_LISTE = "action_religion_from_liste";
static final public String ACTION_SPECIAL_KOLLEKTIV_FROM_LISTE = "action_kollektiv_from_liste";
static final public String ACTION_SPECIAL_BERUF_FROM_LISTE = "action_beruf_from_liste";
static final public String ACTION_SPECIAL_PENDLERPAUSCHALE_FROM_LISTE = "action_pendlerpauschale_from_liste";
static final public String ACTION_SPECIAL_LOHNGRUPPE_FROM_LISTE = "action_lohngruppe_from_liste";
static final public String ACTION_SPECIAL_FIRMENZUGEHOERIGKEIT_FROM_LISTE = "action_firmenzugehoerigkeit_from_liste";
public PanelPersonaldaten(InternalFrame internalFrame, String add2TitleI,
Object pk) throws Throwable {
super(internalFrame, add2TitleI, pk);
internalFramePersonal = (InternalFramePersonal) internalFrame;
jbInit();
setDefaults();
initComponents();
enableAllComponents(this, false);
}
protected String getLockMeWer() throws Exception {
return HelperClient.LOCKME_PERSONAL;
}
protected JComponent getFirstFocusableComponent() throws Exception {
return wdfGeburtsdatum;
}
public void eventYouAreSelected(boolean bNeedNoYouAreSelectedI)
throws Throwable {
leereAlleFelder(this);
super.eventYouAreSelected(false);
personalDto = DelegateFactory
.getInstance()
.getPersonalDelegate()
.personalFindByPrimaryKey(
((InternalFramePersonal) getInternalFrame())
.getPersonalDto().getIId());
dto2Components();
}
private void jbInit() throws Throwable {
setBorder(border);
// das Aussenpanel hat immer das Gridbaglayout.
gridBagLayoutAll = new GridBagLayout();
this.setLayout(gridBagLayoutAll);
getInternalFrame().addItemChangedListener(this);
// Actionpanel von Oberklasse holen und anhaengen.
jpaButtonAction = getToolsPanel();
this.setActionMap(null);
jpaWorkingOn = new JPanel();
gridBagLayoutWorkingPanel = new GridBagLayout();
jpaWorkingOn.setLayout(gridBagLayoutWorkingPanel);
wlaGeburtsdatum.setText(LPMain.getTextRespectUISPr(
"pers.personalangehoerige.geburtsdatum"));
wbuGeburtsort.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.geburtsort")
+ "...");
wlaSignatur.setText(LPMain.getTextRespectUISPr(
"pers.signatur"));
wefSignatur = new WrapperEditorFieldKommentar(getInternalFrame(),
LPMain.getTextRespectUISPr("pers.signatur"));
wefSignatur.getLpEditor().getTextBlockAttributes(-1).capacity = SystemFac.MAX_LAENGE_EDITORTEXT_WENN_NTEXT;
wbuGeburtsort
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_GEBURTSORT_FROM_LISTE);
wbuGeburtsort.addActionListener(this);
wtfGeburtsort.setActivatable(false);
wtfGeburtsort.setText("");
wtfGeburtsort.setColumnsMax(200);
wlaSozialversicherungsnummer.setText(LPMain.getTextRespectUISPr(
"pers.personalangehoerige.sozialversicherungsnummer"));
wtfsozialversicherungsnummer.setText("");
wtfsozialversicherungsnummer
.setColumnsMax(PersonalFac.MAX_PERSONAL_SOZIALVERSNR);
wbuSozialversicherer.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.sozialversicherer")
+ "...");
wbuSozialversicherer
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_SOZIALVERISCHERER_FROM_LISTE);
wbuSozialversicherer.addActionListener(this);
wbuKollektiv.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.kollektiv")
+ "...");
wbuKollektiv
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_KOLLEKTIV_FROM_LISTE);
wbuKollektiv.addActionListener(this);
wtfKollektiv.setActivatable(false);
wtfKollektiv.setText("");
wtfKollektiv.setColumnsMax(80);
wtfSozialversicherer.setActivatable(false);
wtfSozialversicherer.setColumnsMax(200);
wbuBeruf.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.beruf")
+ "...");
wbuBeruf.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_BERUF_FROM_LISTE);
wbuBeruf.addActionListener(this);
wtfBeruf.setActivatable(false);
wtfBeruf.setText("");
wtfBeruf.setColumnsMax(80);
wbuLohngruppe.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.lohngruppe")
+ "...");
wbuLohngruppe
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_LOHNGRUPPE_FROM_LISTE);
wbuLohngruppe.addActionListener(this);
wtfLohngruppe.setActivatable(false);
wtfLohngruppe.setText("");
wtfLohngruppe.setColumnsMax(80);
wcbKeineAnzeigeInAnwesenheitsliste.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.keineanzeigeinanwesenheitsliste"));
wcbBekommtUeberstundenausbezahlt.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.keineueberstundenauszahlung"));
wcbAnwesenheitslisteTermial.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.anwesenheitslisteterminal"));
wcbAnwesenheitslisteAlleTermial.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.anwesenheitslistealleterminal"));
wtfPendlerpauschale.setSelectionStart(17);
wtfPendlerpauschale.setActivatable(false);
wtfPendlerpauschale.setText("");
wtfPendlerpauschale.setColumnsMax(80);
wbuPendlerpauschale.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.pendlerpauschale")
+ "...");
wbuPendlerpauschale
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_PENDLERPAUSCHALE_FROM_LISTE);
wbuPendlerpauschale.addActionListener(this);
wlaFamilienstand.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.familienstand"));
wtfStaatsangehoerigkeit.setActivatable(false);
wtfStaatsangehoerigkeit.setText("");
wtfStaatsangehoerigkeit.setColumnsMax(80);
wbuStaatsangehoerigkeit.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.staatsangehoerigkeit") + "...");
wbuStaatsangehoerigkeit
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_STAATSANGEHOERIGKEIT_FROM_LISTE);
wbuStaatsangehoerigkeit.addActionListener(this);
wtfReligion.setActivatable(false);
wtfReligion.setText("");
wtfReligion.setColumnsMax(80);
wbuReligion.setText(LPMain.getTextRespectUISPr(
"lp.religion")
+ "...");
wbuReligion
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_RELIGION_FROM_LISTE);
wbuReligion.addActionListener(this);
wtfFirmenzugehoerigkeit.setActivatable(false);
wtfFirmenzugehoerigkeit.setText("");
wtfFirmenzugehoerigkeit.setColumnsMax(200);
wcbFamilienstand.setMandatoryField(false);
wbuFirmenzugehoerigkeit.setText(LPMain.getTextRespectUISPr(
"pers.personaldaten.firmenzugehoerigkeit")
+ "...");
wbuFirmenzugehoerigkeit
.setActionCommand(PanelPersonaldaten.ACTION_SPECIAL_FIRMENZUGEHOERIGKEIT_FROM_LISTE);
wbuFirmenzugehoerigkeit.addActionListener(this);
wlaUnterschriftsfunktion.setText(LPMain.getTextRespectUISPr(
"benutzer.unterschriftsfunktion"));
wlaUnterschriftstext.setText(LPMain.getTextRespectUISPr(
"benutzer.unterschriftstext"));
wtfImapBenutzer.setColumnsMax(80);
wtfUnterschriftsfunktion
.setColumnsMax(BenutzerFac.MAX_BENUTZERMANDANTSYSTEMROLLE_C_UNTERSCHRIFTSFUNKTION);
wtfUnterschriftstext
.setColumnsMax(BenutzerFac.MAX_BENUTZERMANDANTSYSTEMROLLE_C_UNTERSCHRIFTSTEXT);
wlaDurchwahl = new WrapperLabel();
wlaDurchwahl.setText(LPMain.getTextRespectUISPr(
"label.absenderdaten") + ": "+ LPMain.getTextRespectUISPr(
"lp.durchwahl"));
wtfDurchwahl = new WrapperTextField(PartnerFac.MAX_KOMMART_INHALT);
wlaEmail = new WrapperLabel();
wlaEmail.setText(LPMain.getTextRespectUISPr("lp.email"));
wtfEmail = new WrapperEmailField();
wlaFaxdurchwahl = new WrapperLabel();
wlaFaxdurchwahl = new WrapperLabel(LPMain
.getTextRespectUISPr("lp.faxdurchwahl"));
wtfFaxdurchwahl = new WrapperTextField(PartnerFac.MAX_KOMMART_INHALT);
wlaHandy = new WrapperLabel();
wlaHandy = new WrapperLabel(LPMain.getTextRespectUISPr(
"lp.handy"));
wtfHandy = new WrapperTelefonField(PartnerFac.MAX_KOMMART_INHALT);
wlaDirektfax = new WrapperLabel();
wlaDirektfax = new WrapperLabel(LPMain
.getTextRespectUISPr("lp.direktfax"));
wtfDirektfax = new WrapperTextField(PartnerFac.MAX_KOMMART_INHALT);
wcbTelefonzeitStarten = new WrapperCheckBox(
LPMain.getTextRespectUISPr("pers.telefonzeitstarten") );
wlaImapBenutzer.setText(LPMain.getTextRespectUISPr(
"pers.imapuser"));
wlaImapKennwort.setText(LPMain.getTextRespectUISPr(
"pers.imapkennwort"));
wlaImapInboxFolder.setText(LPMain.getTextRespectUISPr("pers.imapinboxfolder")) ;
wtfImapInboxFolder.setColumnsMax(80) ;
this.add(jpaButtonAction, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0,
0, 0, 0), 0, 0));
this.add(jpaWorkingOn, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0,
GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(-9, 0, 9, 0), 0, 0));
this.add(getPanelStatusbar(), new GridBagConstraints(0, 2, 1, 1, 1.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
iZeile = 0;
jpaWorkingOn.add(wlaFamilienstand, new GridBagConstraints(0, iZeile, 1,
1, 0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 150, 0));
jpaWorkingOn.add(wcbFamilienstand, new GridBagConstraints(1, iZeile, 1,
1, 2, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wlaGeburtsdatum, new GridBagConstraints(2, iZeile, 1,
1, 0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 150, 0));
jpaWorkingOn.add(wdfGeburtsdatum, new GridBagConstraints(3, iZeile, 2,
1, 2, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wbuGeburtsort, new GridBagConstraints(0, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfGeburtsort, new GridBagConstraints(1, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wlaSozialversicherungsnummer, new GridBagConstraints(
0, iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfsozialversicherungsnummer, new GridBagConstraints(
1, iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wbuSozialversicherer, new GridBagConstraints(2,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfSozialversicherer, new GridBagConstraints(3,
iZeile, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wbuStaatsangehoerigkeit, new GridBagConstraints(0,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfStaatsangehoerigkeit, new GridBagConstraints(1,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wbuReligion, new GridBagConstraints(2, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfReligion, new GridBagConstraints(3, iZeile, 2, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wbuKollektiv, new GridBagConstraints(0, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfKollektiv, new GridBagConstraints(1, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wbuBeruf, new GridBagConstraints(2, iZeile, 1, 1, 0.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfBeruf, new GridBagConstraints(3, iZeile, 2, 1, 0.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wbuPendlerpauschale, new GridBagConstraints(0, iZeile,
1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfPendlerpauschale, new GridBagConstraints(1, iZeile,
1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wbuLohngruppe, new GridBagConstraints(2, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 0, 2), 0, 0));
jpaWorkingOn.add(wtfLohngruppe, new GridBagConstraints(3, iZeile, 2, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wtfFirmenzugehoerigkeit, new GridBagConstraints(1,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wbuFirmenzugehoerigkeit, new GridBagConstraints(0,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
iZeile++;
jpaWorkingOn.add(wlaUnterschriftsfunktion, new GridBagConstraints(0,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfUnterschriftsfunktion, new GridBagConstraints(1,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wlaUnterschriftstext, new GridBagConstraints(2,
iZeile, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfUnterschriftstext, new GridBagConstraints(3,
iZeile, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wcbKeineAnzeigeInAnwesenheitsliste,
new GridBagConstraints(0, iZeile, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2),
0, 0));
jpaWorkingOn.add(wlaImapBenutzer, new GridBagConstraints(2, iZeile, 1,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfImapBenutzer, new GridBagConstraints(3, iZeile, 2,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wcbBekommtUeberstundenausbezahlt,
new GridBagConstraints(0, iZeile, 2, 1, 0.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2),
0, 0));
jpaWorkingOn.add(wlaImapKennwort, new GridBagConstraints(2, iZeile, 1,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfImapKennwort, new GridBagConstraints(3, iZeile, 2,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
++iZeile ;
jpaWorkingOn.add(wcbTelefonzeitStarten, new GridBagConstraints(0, iZeile,
2, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wlaImapInboxFolder, new GridBagConstraints(2, iZeile, 1,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfImapInboxFolder, new GridBagConstraints(3, iZeile, 2,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wcbAnwesenheitslisteTermial, new GridBagConstraints(0,
iZeile, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wcbAnwesenheitslisteAlleTermial,
new GridBagConstraints(2, iZeile, 3, 1, 0.0, 0.0,
GridBagConstraints.CENTER,
GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2),
0, 0));
// Zeile
// iZeile++;
// jpaWorkingOn.add(wcbTelefonzeitStarten, new GridBagConstraints(0, iZeile, 2,
// 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
// new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wlaDurchwahl, new GridBagConstraints(0, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfDurchwahl, new GridBagConstraints(1, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wlaEmail, new GridBagConstraints(2, iZeile, 1, 1, 0.0,
0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfEmail, new GridBagConstraints(3, iZeile, 2, 1, 1.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
// Zeile
iZeile++;
jpaWorkingOn.add(wlaFaxdurchwahl, new GridBagConstraints(0, iZeile, 1,
1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfFaxdurchwahl, new GridBagConstraints(1, iZeile, 1,
1, 0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wlaHandy, new GridBagConstraints(2, iZeile, 1, 1, 0.0,
0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfHandy, new GridBagConstraints(3, iZeile, 2, 1, 0.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
// Zeile
iZeile++;
jpaWorkingOn.add(wlaDirektfax, new GridBagConstraints(0, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wtfDirektfax, new GridBagConstraints(1, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
iZeile++;
jpaWorkingOn.add(wlaSignatur, new GridBagConstraints(0, iZeile, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 0));
jpaWorkingOn.add(wefSignatur, new GridBagConstraints(1, iZeile, 4, 1,
0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(2, 2, 2, 2), 0, 35));
String[] aWhichButtonIUse = { ACTION_UPDATE, ACTION_SAVE,
ACTION_DISCARD, };
enableToolsPanelButtons(aWhichButtonIUse);
}
protected void setDefaults() throws Throwable {
wcbFamilienstand.setMap(DelegateFactory.getInstance()
.getPersonalDelegate().getAllSprFamilienstaende());
}
protected void eventActionSpecial(ActionEvent e) throws Throwable {
if (e.getActionCommand().equals(
ACTION_SPECIAL_SOZIALVERISCHERER_FROM_LISTE)) {
dialogQuerySozialversichererFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_GEBURTSORT_FROM_LISTE)) {
dialogQueryGeburtsortFromListe(e);
} else if (e.getActionCommand().equals(ACTION_SPECIAL_BERUF_FROM_LISTE)) {
dialogQueryBerufFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_FIRMENZUGEHOERIGKEIT_FROM_LISTE)) {
dialogQueryFirmenzugehoerigkeitFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_KOLLEKTIV_FROM_LISTE)) {
dialogQueryKollektivFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_LOHNGRUPPE_FROM_LISTE)) {
dialogQueryLohngruppeFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_PENDLERPAUSCHALE_FROM_LISTE)) {
dialogQueryPendlerpauschaleFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_RELIGION_FROM_LISTE)) {
dialogQueryRelgionFromListe(e);
} else if (e.getActionCommand().equals(
ACTION_SPECIAL_STAATSANGEHOERIGKEIT_FROM_LISTE)) {
dialogQueryStaatsangehoerigkeitFromListe(e);
}
}
protected void dto2Components() throws ExceptionLP, Throwable {
if (personalDto.getBerufDto() != null) {
wtfBeruf.setText(personalDto.getBerufDto().getCBez());
}
if (personalDto.getKollektivDto() != null) {
wtfKollektiv.setText(personalDto.getKollektivDto().getCBez());
}
if (personalDto.getPendlerpauschaleDto() != null) {
wtfPendlerpauschale.setText(personalDto.getPendlerpauschaleDto()
.getCBez());
}
if (personalDto.getReligionDto() != null) {
wtfReligion.setText(personalDto.getReligionDto().getCNr());
}
if (personalDto.getLandplzortDto_Geburtsort() != null) {
wtfGeburtsort.setText(personalDto.getLandplzortDto_Geburtsort()
.formatLandPlzOrt());
}
if (personalDto.getLohngruppeIId() != null) {
wtfLohngruppe.setText(personalDto.getLohngruppeDto().getCBez());
}
if (personalDto.getPartnerDto_Sozialversicherer() != null) {
wtfSozialversicherer.setText(personalDto
.getPartnerDto_Sozialversicherer().formatTitelAnrede());
} else {
wtfSozialversicherer.setText(null);
}
if (personalDto.getPartnerDto_Firma() != null) {
wtfFirmenzugehoerigkeit.setText(personalDto.getPartnerDto_Firma()
.formatTitelAnrede());
} else {
wtfFirmenzugehoerigkeit.setText(null);
}
wtfsozialversicherungsnummer.setText(personalDto.getCSozialversnr());
if (personalDto.getLandDto() != null) {
wtfStaatsangehoerigkeit.setText(personalDto.getLandDto().getCLkz());
} else {
wtfStaatsangehoerigkeit.setText(null);
}
wcbFamilienstand
.setKeyOfSelectedItem(personalDto.getFamilienstandCNr());
wcbBekommtUeberstundenausbezahlt.setShort(personalDto
.getBUeberstundenausbezahlt());
if (personalDto.getBAnwesenheitsliste().intValue() == 0) {
wcbKeineAnzeigeInAnwesenheitsliste.setShort(new Short((short) 1));
} else {
wcbKeineAnzeigeInAnwesenheitsliste.setShort(new Short((short) 0));
}
wcbTelefonzeitStarten.setShort(personalDto
.getBTelefonzeitstarten());
wcbAnwesenheitslisteTermial.setShort(personalDto
.getBAnwesenheitTerminal());
wcbAnwesenheitslisteAlleTermial.setShort(personalDto
.getBAnwesenheitalleterminal());
wdfGeburtsdatum.setTimestamp(personalDto.getTGeburtsdatum());
wtfUnterschriftsfunktion.setText(personalDto
.getCUnterschriftsfunktion());
wtfUnterschriftstext.setText(personalDto.getCUnterschriftstext());
wtfImapBenutzer.setText(personalDto.getCImapbenutzer());
wtfImapKennwort.setText("**********");
wtfDirektfax.setText(personalDto.getCDirektfax());
wtfEmail.setEmail(personalDto.getCEmail(), null);
wtfFaxdurchwahl.setText(personalDto.getCFax());
if (personalDto.getCHandy() != null) {
wtfHandy.setPartnerKommunikationDto(personalDto.getPartnerDto(),
personalDto.getCHandy());
} else {
wtfHandy.setPartnerKommunikationDto(null, null);
}
wtfDurchwahl.setText(personalDto.getCTelefon());
wefSignatur.setText(DelegateFactory
.getInstance()
.getPersonalDelegate()
.getSignatur(personalDto.getIId(),
LPMain.getTheClient().getLocUiAsString()));
if(personalDto.getCImapInboxFolder() != null) {
wtfImapInboxFolder.setText(personalDto.getCImapInboxFolder()) ;
} else {
wtfImapInboxFolder.setText("") ;
}
this.setStatusbarPersonalIIdAendern(personalDto.getPersonalIIdAendern());
this.setStatusbarPersonalIIdAnlegen(personalDto.getPersonalIIdAnlegen());
this.setStatusbarTAnlegen(personalDto.getTAnlegen());
this.setStatusbarTAendern(personalDto.getTAendern());
}
void dialogQuerySozialversichererFromListe(ActionEvent e) throws Throwable {
panelQueryFLRSozialversicherer = PartnerFilterFactory.getInstance()
.createPanelFLRPartner(getInternalFrame(),
personalDto.getPartnerIIdSozialversicherer(), true);
new DialogQuery(panelQueryFLRSozialversicherer);
}
void dialogQueryFirmenzugehoerigkeitFromListe(ActionEvent e)
throws Throwable {
panelQueryFLRfirmenzugehoerigkeit = PartnerFilterFactory.getInstance()
.createPanelFLRPartner(getInternalFrame(),
personalDto.getPartnerIIdFirma(), true);
new DialogQuery(panelQueryFLRfirmenzugehoerigkeit);
}
void dialogQueryGeburtsortFromListe(ActionEvent e) throws Throwable {
panelQueryFLRGeburtsort = SystemFilterFactory.getInstance()
.createPanelFLRLandplzort(getInternalFrame(),
personalDto.getLandplzortIIdGeburt(), true);
new DialogQuery(panelQueryFLRGeburtsort);
}
void dialogQueryRelgionFromListe(ActionEvent e) throws Throwable {
panelQueryFLRReligion = PersonalFilterFactory.getInstance()
.createPanelFLRReligion(getInternalFrame(),
personalDto.getReligionIId());
new DialogQuery(panelQueryFLRReligion);
}
void dialogQueryBerufFromListe(ActionEvent e) throws Throwable {
String[] aWhichButtonIUse = { PanelBasis.ACTION_REFRESH,
PanelBasis.ACTION_LEEREN };
panelQueryFLRBeruf = new PanelQueryFLR(null, null,
QueryParameters.UC_ID_BERUF, aWhichButtonIUse,
internalFramePersonal, LPMain
.getTextRespectUISPr("title.berufauswahlliste"));
panelQueryFLRBeruf.befuellePanelFilterkriterienDirekt(
SystemFilterFactory.getInstance().createFKDBezeichnung(), null);
panelQueryFLRBeruf.setSelectedId(personalDto.getBerufIId());
new DialogQuery(panelQueryFLRBeruf);
}
void dialogQueryLohngruppeFromListe(ActionEvent e) throws Throwable {
String[] aWhichButtonIUse = { PanelBasis.ACTION_REFRESH,
PanelBasis.ACTION_LEEREN };
panelQueryFLRLohngrupe = new PanelQueryFLR(null, null,
QueryParameters.UC_ID_LOHNGRUPPE, aWhichButtonIUse,
internalFramePersonal, LPMain
.getTextRespectUISPr("title.lohngruppeauswahlliste"));
panelQueryFLRLohngrupe.befuellePanelFilterkriterienDirekt(
SystemFilterFactory.getInstance().createFKDBezeichnung(), null);
panelQueryFLRLohngrupe.setSelectedId(personalDto.getLohngruppeIId());
new DialogQuery(panelQueryFLRLohngrupe);
}
void dialogQueryKollektivFromListe(ActionEvent e) throws Throwable {
String[] aWhichButtonIUse = { PanelBasis.ACTION_REFRESH,
PanelBasis.ACTION_LEEREN };
panelQueryFLRKollektiv = new PanelQueryFLR(null, null,
QueryParameters.UC_ID_KOLLEKTIV, aWhichButtonIUse,
internalFramePersonal, LPMain.getTextRespectUISPr(
"title.kollektivauswahlliste"));
panelQueryFLRKollektiv.befuellePanelFilterkriterienDirekt(
SystemFilterFactory.getInstance().createFKDBezeichnung(), null);
panelQueryFLRKollektiv.setSelectedId(personalDto.getKollektivIId());
new DialogQuery(panelQueryFLRKollektiv);
}
void dialogQueryPendlerpauschaleFromListe(ActionEvent e) throws Throwable {
String[] aWhichButtonIUse = { PanelBasis.ACTION_REFRESH,
PanelBasis.ACTION_LEEREN };
panelQueryFLRPendlerpauschale = new PanelQueryFLR(null, null,
QueryParameters.UC_ID_PENDLERPAUSCHALE, aWhichButtonIUse,
internalFramePersonal, LPMain.getTextRespectUISPr(
"title.pendlerpauschaleauswahlliste"));
panelQueryFLRPendlerpauschale.befuellePanelFilterkriterienDirekt(
SystemFilterFactory.getInstance().createFKDBezeichnung(), null);
panelQueryFLRPendlerpauschale.setSelectedId(personalDto
.getKollektivIId());
new DialogQuery(panelQueryFLRPendlerpauschale);
}
void dialogQueryStaatsangehoerigkeitFromListe(ActionEvent e)
throws Throwable {
String[] aWhichButtonIUse = { PanelBasis.ACTION_REFRESH,
PanelBasis.ACTION_LEEREN };
panelQueryFLRStaatsangehoerigkeit = new PanelQueryFLR(null, null,
QueryParameters.UC_ID_LAND, aWhichButtonIUse,
internalFramePersonal, LPMain
.getTextRespectUISPr("title.landauswahlliste"));
panelQueryFLRStaatsangehoerigkeit.setSelectedId(personalDto
.getLandIIdStaatsangehoerigkeit());
new DialogQuery(panelQueryFLRStaatsangehoerigkeit);
}
protected void components2Dto() throws Throwable {
personalDto.setCSozialversnr(wtfsozialversicherungsnummer.getText());
personalDto.setFamilienstandCNr((String) wcbFamilienstand
.getKeyOfSelectedItem());
personalDto.setBUeberstundenausbezahlt(wcbBekommtUeberstundenausbezahlt
.getShort());
personalDto.setCUnterschriftsfunktion(wtfUnterschriftsfunktion
.getText());
personalDto.setCUnterschriftstext(wtfUnterschriftstext.getText());
personalDto.setCImapbenutzer(wtfImapBenutzer.getText());
if (!new String(wtfImapKennwort.getPassword()).equals("**********")) {
personalDto.setCImapkennwort(new String(wtfImapKennwort
.getPassword()));
}
if (wcbKeineAnzeigeInAnwesenheitsliste.getShort().intValue() == 0) {
personalDto.setBAnwesenheitsliste(new Short((short) 1));
} else {
personalDto.setBAnwesenheitsliste(new Short((short) 0));
}
personalDto.setBAnwesenheitTerminal(wcbAnwesenheitslisteTermial
.getShort());
personalDto.setBAnwesenheitalleterminal(wcbAnwesenheitslisteAlleTermial
.getShort());
personalDto.setTGeburtsdatum(wdfGeburtsdatum.getTimestamp());
personalDto.setBTelefonzeitstarten(wcbTelefonzeitStarten
.getShort());
// Kommunikationsdaten
personalDto.setCDirektfax(wtfDirektfax.getText());
personalDto.setCTelefon(wtfDurchwahl.getText());
personalDto.setCEmail(wtfEmail.getText());
personalDto.setCFax(wtfFaxdurchwahl.getText());
personalDto.setCHandy(wtfHandy.getText());
personalDto.setCImapInboxFolder(wtfImapInboxFolder.getText());
}
protected void eventItemchanged(EventObject eI) throws Throwable {
ItemChangedEvent e = (ItemChangedEvent) eI;
if (e.getID() == ItemChangedEvent.GOTO_DETAIL_PANEL) {
if (e.getSource() == panelQueryFLRBeruf) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
BerufDto berufDto = DelegateFactory.getInstance()
.getPersonalDelegate()
.berufFindByPrimaryKey((Integer) key);
wtfBeruf.setText(berufDto.getCBez());
personalDto.setBerufIId(berufDto.getIId());
} else if (e.getSource() == panelQueryFLRfirmenzugehoerigkeit) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
PartnerDto partnerTempDto = DelegateFactory.getInstance()
.getPartnerDelegate()
.partnerFindByPrimaryKey((Integer) key);
if (partnerTempDto.getIId().equals(
internalFramePersonal.getPersonalDto().getPartnerDto()
.getIId())) {
DialogFactory
.showModalDialog(
LPMain.getTextRespectUISPr(
"lp.error"),
LPMain.getTextRespectUISPr(
"pers.error.kannnichtselbstzugeordnetwerden"));
} else {
wtfFirmenzugehoerigkeit.setText(partnerTempDto
.formatAnrede());
personalDto.setPartnerIIdFirma(partnerTempDto.getIId());
}
} else if (e.getSource() == panelQueryFLRGeburtsort) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
LandplzortDto landplzortDto = DelegateFactory.getInstance()
.getSystemDelegate()
.landplzortFindByPrimaryKey((Integer) key);
wtfGeburtsort.setText(landplzortDto.formatLandPlzOrt());
personalDto.setLandplzortIIdGeburt(landplzortDto.getIId());
} else if (e.getSource() == panelQueryFLRKollektiv) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
KollektivDto kollektivDto = DelegateFactory.getInstance()
.getPersonalDelegate()
.kollektivFindByPrimaryKey((Integer) key);
wtfKollektiv.setText(kollektivDto.getCBez());
personalDto.setKollektivIId(kollektivDto.getIId());
} else if (e.getSource() == panelQueryFLRLohngrupe) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
LohngruppeDto lohngruppeDto = DelegateFactory.getInstance()
.getPersonalDelegate()
.lohngruppeFindByPrimaryKey((Integer) key);
wtfLohngruppe.setText(lohngruppeDto.getCBez());
personalDto.setLohngruppeIId(lohngruppeDto.getIId());
} else if (e.getSource() == panelQueryFLRPendlerpauschale) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
PendlerpauschaleDto pendlerpauschaleDto = DelegateFactory
.getInstance().getPersonalDelegate()
.pendlerpauschaleFindByPrimaryKey((Integer) key);
wtfPendlerpauschale.setText(pendlerpauschaleDto.getCBez());
personalDto
.setPendlerpauschaleIId(pendlerpauschaleDto.getIId());
} else if (e.getSource() == panelQueryFLRReligion) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
ReligionDto religionDto = DelegateFactory.getInstance()
.getPersonalDelegate()
.religionFindByPrimaryKey((Integer) key);
wtfReligion.setText(religionDto.getCNr());
personalDto.setReligionIId(religionDto.getIId());
} else if (e.getSource() == panelQueryFLRSozialversicherer) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
PartnerDto partnerDto = DelegateFactory.getInstance()
.getPartnerDelegate()
.partnerFindByPrimaryKey((Integer) key);
wtfSozialversicherer.setText(partnerDto.formatAnrede());
personalDto.setPartnerIIdSozialversicherer(partnerDto.getIId());
} else if (e.getSource() == panelQueryFLRStaatsangehoerigkeit) {
Object key = ((ISourceEvent) e.getSource()).getIdSelected();
LandDto landDto = DelegateFactory.getInstance()
.getSystemDelegate()
.landFindByPrimaryKey((Integer) key);
wtfStaatsangehoerigkeit.setText(landDto.getCLkz());
personalDto.setLandIIdStaatsangehoerigkeit(landDto.getIID());
}
} else if (e.getID() == ItemChangedEvent.ACTION_LEEREN) {
if (e.getSource() == panelQueryFLRBeruf) {
wtfBeruf.setText(null);
personalDto.setBerufDto(null);
personalDto.setBerufIId(null);
} else if (e.getSource() == panelQueryFLRfirmenzugehoerigkeit) {
wtfFirmenzugehoerigkeit.setText(null);
personalDto.setPartnerIIdFirma(null);
personalDto.setPartnerDto_Firma(null);
} else if (e.getSource() == panelQueryFLRGeburtsort) {
wtfGeburtsort.setText(null);
personalDto.setLandplzortDto_Geburtsort(null);
personalDto.setLandplzortIIdGeburt(null);
} else if (e.getSource() == panelQueryFLRKollektiv) {
wtfKollektiv.setText(null);
personalDto.setKollektivDto(null);
personalDto.setKollektivIId(null);
} else if (e.getSource() == panelQueryFLRLohngrupe) {
wtfLohngruppe.setText(null);
personalDto.setLohngruppeDto(null);
personalDto.setLohngruppeIId(null);
} else if (e.getSource() == panelQueryFLRPendlerpauschale) {
wtfPendlerpauschale.setText(null);
personalDto.setPendlerpauschaleDto(null);
personalDto.setPendlerpauschaleIId(null);
} else if (e.getSource() == panelQueryFLRReligion) {
wtfReligion.setText(null);
personalDto.setReligionDto(null);
personalDto.setReligionIId(null);
} else if (e.getSource() == panelQueryFLRSozialversicherer) {
wtfSozialversicherer.setText(null);
personalDto.setPartnerDto_Sozialversicherer(null);
personalDto.setPartnerIIdSozialversicherer(null);
} else if (e.getSource() == panelQueryFLRStaatsangehoerigkeit) {
wtfStaatsangehoerigkeit.setText(null);
personalDto.setLandDto(null);
personalDto.setLandIIdStaatsangehoerigkeit(null);
}
}
}
public void eventActionSave(ActionEvent e, boolean bNeedNoSaveI)
throws Throwable {
if (super.allMandatoryFieldsSetDlg()) {
components2Dto();
DelegateFactory.getInstance().getPersonalDelegate()
.updatePersonal(personalDto);
DelegateFactory
.getInstance()
.getPersonalDelegate()
.updateSignatur(personalDto.getIId(), wefSignatur.getText());
}
super.eventActionSave(e, true);
}
}
| erdincay/lpclientpc | src/com/lp/client/personal/PanelPersonaldaten.java | Java | agpl-3.0 | 44,159 |
//#############################################################################
//# #
//# 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 Marius Mihalec using IMS Development Environment (version 1.62 build 3110.16630)
// Copyright (C) 1995-2008 IMS MAXIMS plc. All rights reserved.
package ims.core.forms.bayfloorplandesigner;
import ims.core.vo.FloorLayoutVo;
import ims.core.vo.lookups.PreActiveActiveInactiveStatus;
import ims.domain.exceptions.StaleObjectException;
import ims.framework.enumerations.FormMode;
import ims.framework.exceptions.PresentationLogicException;
public class Logic extends BaseLogic
{
private static final long serialVersionUID = 1L;
@Override
protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
initialize();
open();
}
@Override
protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException
{
if(save())
{
form.setMode(FormMode.VIEW);
}
}
@Override
protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException
{
if(form.getLocalContext().getCurrentRecord() == null)
{
returnToList();
}
else
{
open();
form.setMode(FormMode.VIEW);
}
}
@Override
protected void onBtnEditClick() throws PresentationLogicException
{
open();
form.setMode(FormMode.EDIT);
}
@Override
protected void onLnkReturnClick() throws PresentationLogicException
{
returnToList();
}
private void initialize()
{
if(form.getGlobalContext().Core.FloorLayout.getReadOnly() != null && form.getGlobalContext().Core.FloorLayout.getReadOnly().booleanValue())
{
form.setMode(FormMode.VIEW);
}
else
{
form.setMode(FormMode.EDIT);
form.txtName().setFocus();
if(form.getGlobalContext().Core.FloorLayout.getSelection() == null)
{
form.cmbStatus().setValue(PreActiveActiveInactiveStatus.PREACTIVE);
}
}
}
private void open()
{
if(form.getGlobalContext().Core.FloorLayout.getSelection() != null)
{
populateScreenFromData(domain.get(form.getGlobalContext().Core.FloorLayout.getSelection()));
}
}
private FloorLayoutVo populateDataFromScreen(FloorLayoutVo value)
{
if(value == null)
value = new FloorLayoutVo();
value.setName(form.txtName().getValue());
value.setStatus(form.cmbStatus().getValue());
value.setVml(form.layoutDesigner().getPlan());
return value;
}
private void populateScreenFromData(FloorLayoutVo value)
{
form.getLocalContext().setCurrentRecord(value);
form.layoutDesigner().clearAreas();
form.layoutDesigner().setPlan("");
if(value != null)
{
form.txtName().setValue(value.getName());
form.cmbStatus().setValue(value.getStatus());
form.layoutDesigner().setPlan(value.getVml());
}
}
private boolean save()
{
FloorLayoutVo value = populateDataFromScreen(form.getLocalContext().getCurrentRecord());
String[] errors = value.validate();
if(errors != null && errors.length > 0)
{
engine.showErrors(errors);
return false;
}
try
{
value = domain.save(value);
}
catch (StaleObjectException e)
{
engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue());
open();
return false;
}
form.getLocalContext().setCurrentRecord(value);
form.getGlobalContext().Core.FloorLayout.setSelection(value);
return true;
}
private void returnToList()
{
engine.open(form.getForms().Core.FloorLayoutList);
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/bayfloorplandesigner/Logic.java | Java | agpl-3.0 | 5,379 |
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2013 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.iso.packager;
import org.jpos.iso.*;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
import org.jpos.util.SimpleLogSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @author [email protected]
* @version $Id$
* @see ISOPackager
* @see ISOBasePackager
* @see ISOComponent
*/
public class VISA1Packager
extends SimpleLogSource implements ISOPackager, VISA1ResponseFilter
{
public static final byte[] FS = { (byte)'\034' };
int[] sequence;
int respField;
String badResultCode;
String okPattern;
VISA1ResponseFilter filter;
/**
* @param sequence array of fields that go to VISA1 request
* @param respField where to put response
* @param badResultCode (i.e. "05")
* @param okPattern (i.e. "AUT. ")
*/
public VISA1Packager
(int[] sequence, int respField, String badResultCode, String okPattern)
{
super();
this.sequence = sequence;
this.respField = respField;
this.badResultCode = badResultCode;
this.okPattern = okPattern;
setVISA1ResponseFilter (this);
}
public void setVISA1ResponseFilter (VISA1ResponseFilter filter) {
this.filter = filter;
}
protected int handleSpecialField35 (ISOMsg m, List l)
throws ISOException
{
int len = 0;
byte[] entryMode = new byte[1];
if (m.hasField (35)) {
entryMode[0] = (byte) '\001';
byte[] value = m.getString(35).getBytes();
l.add (entryMode);
l.add (value);
l.add (FS);
len += value.length+2;
} else if (m.hasField (2) && m.hasField (14)) {
entryMode[0] = (byte) '\000';
String simulatedTrack2 = m.getString(2) + "=" + m.getString(14);
l.add (entryMode);
l.add (simulatedTrack2.getBytes());
l.add (FS);
len += simulatedTrack2.length()+2;
}
return len;
}
public byte[] pack (ISOComponent c) throws ISOException
{
LogEvent evt = new LogEvent (this, "pack");
try {
if (!(c instanceof ISOMsg))
throw new ISOException
("Can't call VISA1 packager on non ISOMsg");
ISOMsg m = (ISOMsg) c;
int len = 0;
List<byte[]> l = new ArrayList();
for (int i=0; i<sequence.length; i++) {
int fld = sequence[i];
if (fld == 35)
len += handleSpecialField35 (m, l);
else if (m.hasField(fld)) {
byte[] value;
if (fld == 4) {
long amt = Long.valueOf(m.getString(4));
value = ISOUtil.formatAmount (amt,12).trim().getBytes();
}
else
value = m.getString(fld).getBytes();
l.add(value);
len += value.length;
if (i < (sequence.length-1)) {
l.add(FS);
len++;
}
}
}
int k = 0;
byte[] d = new byte[len];
for (byte[] b :l) {
System.arraycopy(b, 0, d, k, b.length);
k += b.length;
}
if (logger != null) // save a few CPU cycle if no logger available
evt.addMessage (ISOUtil.dumpString (d));
return d;
} catch (ISOException e) {
evt.addMessage (e);
throw e;
} finally {
Logger.log(evt);
}
}
public String guessAutNumber (String s) {
StringBuilder buf = new StringBuilder();
for (int i=0; i<s.length(); i++)
if (Character.isDigit(s.charAt(i)))
buf.append (s.charAt(i));
if (buf.length() == 0)
return null;
while (buf.length() > 6)
buf.deleteCharAt(0);
while (buf.length() < 6)
buf.insert(0, "0");
return buf.toString();
}
public int unpack (ISOComponent m, byte[] b) throws ISOException
{
String response = new String (b);
m.set (new ISOField (respField, response));
m.set (new ISOField (39, badResultCode));
if (response.startsWith (okPattern)) {
String autNumber = filter.guessAutNumber (response);
if (autNumber != null) {
m.set (new ISOField (39, "00"));
m.set (new ISOField (38, autNumber));
}
}
return b.length;
}
public void unpack (ISOComponent m, InputStream in) throws ISOException {
throw new ISOException ("not implemented");
}
public String getFieldDescription(ISOComponent m, int fldNumber)
{
return "VISA 1 fld "+fldNumber;
}
public String getDescription () {
return getClass().getName();
}
public ISOMsg createISOMsg() {
return new ISOMsg();
}
}
| napramirez/jPOS | jpos/src/main/java/org/jpos/iso/packager/VISA1Packager.java | Java | agpl-3.0 | 5,890 |
//#############################################################################
//# #
//# 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:25
*
*/
package ims.hl7.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Michael Noonan
*/
public class MOSMessageQueueVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.hl7.vo.MOSMessageQueueVo copy(ims.hl7.vo.MOSMessageQueueVo valueObjectDest, ims.hl7.vo.MOSMessageQueueVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_MOSMessageQueue(valueObjectSrc.getID_MOSMessageQueue());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// ProviderSystem
valueObjectDest.setProviderSystem(valueObjectSrc.getProviderSystem());
// wasProcessed
valueObjectDest.setWasProcessed(valueObjectSrc.getWasProcessed());
// wasDiscarded
valueObjectDest.setWasDiscarded(valueObjectSrc.getWasDiscarded());
// msgText
valueObjectDest.setMsgText(valueObjectSrc.getMsgText());
// ackText
valueObjectDest.setAckText(valueObjectSrc.getAckText());
// failureMsg
valueObjectDest.setFailureMsg(valueObjectSrc.getFailureMsg());
// messageStatus
valueObjectDest.setMessageStatus(valueObjectSrc.getMessageStatus());
// msgType
valueObjectDest.setMsgType(valueObjectSrc.getMsgType());
// queueType
valueObjectDest.setQueueType(valueObjectSrc.getQueueType());
// MOS
valueObjectDest.setMOS(valueObjectSrc.getMOS());
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 #createMOSMessageQueueVoCollectionFromMOSMessageQueue(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.hl7adtout.domain.objects.MOSMessageQueue objects.
*/
public static ims.hl7.vo.MOSMessageQueueVoCollection createMOSMessageQueueVoCollectionFromMOSMessageQueue(java.util.Set domainObjectSet)
{
return createMOSMessageQueueVoCollectionFromMOSMessageQueue(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.hl7adtout.domain.objects.MOSMessageQueue objects.
*/
public static ims.hl7.vo.MOSMessageQueueVoCollection createMOSMessageQueueVoCollectionFromMOSMessageQueue(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.hl7.vo.MOSMessageQueueVoCollection voList = new ims.hl7.vo.MOSMessageQueueVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.hl7adtout.domain.objects.MOSMessageQueue domainObject = (ims.hl7adtout.domain.objects.MOSMessageQueue) iterator.next();
ims.hl7.vo.MOSMessageQueueVo 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.hl7adtout.domain.objects.MOSMessageQueue objects.
*/
public static ims.hl7.vo.MOSMessageQueueVoCollection createMOSMessageQueueVoCollectionFromMOSMessageQueue(java.util.List domainObjectList)
{
return createMOSMessageQueueVoCollectionFromMOSMessageQueue(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.hl7adtout.domain.objects.MOSMessageQueue objects.
*/
public static ims.hl7.vo.MOSMessageQueueVoCollection createMOSMessageQueueVoCollectionFromMOSMessageQueue(DomainObjectMap map, java.util.List domainObjectList)
{
ims.hl7.vo.MOSMessageQueueVoCollection voList = new ims.hl7.vo.MOSMessageQueueVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.hl7adtout.domain.objects.MOSMessageQueue domainObject = (ims.hl7adtout.domain.objects.MOSMessageQueue) domainObjectList.get(i);
ims.hl7.vo.MOSMessageQueueVo 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.hl7adtout.domain.objects.MOSMessageQueue 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 extractMOSMessageQueueSet(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVoCollection voCollection)
{
return extractMOSMessageQueueSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractMOSMessageQueueSet(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVoCollection 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.hl7.vo.MOSMessageQueueVo vo = voCollection.get(i);
ims.hl7adtout.domain.objects.MOSMessageQueue domainObject = MOSMessageQueueVoAssembler.extractMOSMessageQueue(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.hl7adtout.domain.objects.MOSMessageQueue 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 extractMOSMessageQueueList(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVoCollection voCollection)
{
return extractMOSMessageQueueList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractMOSMessageQueueList(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVoCollection 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.hl7.vo.MOSMessageQueueVo vo = voCollection.get(i);
ims.hl7adtout.domain.objects.MOSMessageQueue domainObject = MOSMessageQueueVoAssembler.extractMOSMessageQueue(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.hl7adtout.domain.objects.MOSMessageQueue object.
* @param domainObject ims.hl7adtout.domain.objects.MOSMessageQueue
*/
public static ims.hl7.vo.MOSMessageQueueVo create(ims.hl7adtout.domain.objects.MOSMessageQueue domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.hl7adtout.domain.objects.MOSMessageQueue object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.hl7.vo.MOSMessageQueueVo create(DomainObjectMap map, ims.hl7adtout.domain.objects.MOSMessageQueue domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.hl7.vo.MOSMessageQueueVo valueObject = (ims.hl7.vo.MOSMessageQueueVo) map.getValueObject(domainObject, ims.hl7.vo.MOSMessageQueueVo.class);
if ( null == valueObject )
{
valueObject = new ims.hl7.vo.MOSMessageQueueVo(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.hl7adtout.domain.objects.MOSMessageQueue
*/
public static ims.hl7.vo.MOSMessageQueueVo insert(ims.hl7.vo.MOSMessageQueueVo valueObject, ims.hl7adtout.domain.objects.MOSMessageQueue 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.hl7adtout.domain.objects.MOSMessageQueue
*/
public static ims.hl7.vo.MOSMessageQueueVo insert(DomainObjectMap map, ims.hl7.vo.MOSMessageQueueVo valueObject, ims.hl7adtout.domain.objects.MOSMessageQueue domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_MOSMessageQueue(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;
// ProviderSystem
valueObject.setProviderSystem(ims.ocrr.vo.domain.ProviderSystemVoAssembler.create(map, domainObject.getProviderSystem()) );
// wasProcessed
valueObject.setWasProcessed( domainObject.isWasProcessed() );
// wasDiscarded
valueObject.setWasDiscarded( domainObject.isWasDiscarded() );
// msgText
valueObject.setMsgText(domainObject.getMsgText());
// ackText
valueObject.setAckText(domainObject.getAckText());
// failureMsg
valueObject.setFailureMsg(domainObject.getFailureMsg());
// messageStatus
ims.domain.lookups.LookupInstance instance7 = domainObject.getMessageStatus();
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.ocrr.vo.lookups.OrderMessageStatus voLookup7 = new ims.ocrr.vo.lookups.OrderMessageStatus(instance7.getId(),instance7.getText(), instance7.isActive(), null, img, color);
ims.ocrr.vo.lookups.OrderMessageStatus 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.ocrr.vo.lookups.OrderMessageStatus(parent7.getId(),parent7.getText(), parent7.isActive(), null, img, color));
parentVoLookup7 = parentVoLookup7.getParent();
parent7 = parent7.getParent();
}
valueObject.setMessageStatus(voLookup7);
}
// msgType
ims.domain.lookups.LookupInstance instance8 = domainObject.getMsgType();
if ( null != instance8 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath());
}
color = instance8.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.MsgEventType voLookup8 = new ims.core.vo.lookups.MsgEventType(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color);
ims.core.vo.lookups.MsgEventType parentVoLookup8 = voLookup8;
ims.domain.lookups.LookupInstance parent8 = instance8.getParent();
while (parent8 != null)
{
if (parent8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent8.getColor();
if (color != null)
color.getValue();
parentVoLookup8.setParent(new ims.core.vo.lookups.MsgEventType(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color));
parentVoLookup8 = parentVoLookup8.getParent();
parent8 = parent8.getParent();
}
valueObject.setMsgType(voLookup8);
}
// queueType
ims.domain.lookups.LookupInstance instance9 = domainObject.getQueueType();
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.QueueType voLookup9 = new ims.core.vo.lookups.QueueType(instance9.getId(),instance9.getText(), instance9.isActive(), null, img, color);
ims.core.vo.lookups.QueueType 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.QueueType(parent9.getId(),parent9.getText(), parent9.isActive(), null, img, color));
parentVoLookup9 = parentVoLookup9.getParent();
parent9 = parent9.getParent();
}
valueObject.setQueueType(voLookup9);
}
// MOS
if (domainObject.getMOS() != null)
{
if(domainObject.getMOS() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getMOS();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setMOS(new ims.core.resource.people.vo.MemberOfStaffRefVo(id, -1));
}
else
{
valueObject.setMOS(new ims.core.resource.people.vo.MemberOfStaffRefVo(domainObject.getMOS().getId(), domainObject.getMOS().getVersion()));
}
}
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.hl7adtout.domain.objects.MOSMessageQueue extractMOSMessageQueue(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVo valueObject)
{
return extractMOSMessageQueue(domainFactory, valueObject, new HashMap());
}
public static ims.hl7adtout.domain.objects.MOSMessageQueue extractMOSMessageQueue(ims.domain.ILightweightDomainFactory domainFactory, ims.hl7.vo.MOSMessageQueueVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_MOSMessageQueue();
ims.hl7adtout.domain.objects.MOSMessageQueue domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.hl7adtout.domain.objects.MOSMessageQueue)domMap.get(valueObject);
}
// ims.hl7.vo.MOSMessageQueueVo ID_MOSMessageQueue field is unknown
domainObject = new ims.hl7adtout.domain.objects.MOSMessageQueue();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_MOSMessageQueue());
if (domMap.get(key) != null)
{
return (ims.hl7adtout.domain.objects.MOSMessageQueue)domMap.get(key);
}
domainObject = (ims.hl7adtout.domain.objects.MOSMessageQueue) domainFactory.getDomainObject(ims.hl7adtout.domain.objects.MOSMessageQueue.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_MOSMessageQueue());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.admin.domain.objects.ProviderSystem value1 = null;
if ( null != valueObject.getProviderSystem() )
{
if (valueObject.getProviderSystem().getBoId() == null)
{
if (domMap.get(valueObject.getProviderSystem()) != null)
{
value1 = (ims.core.admin.domain.objects.ProviderSystem)domMap.get(valueObject.getProviderSystem());
}
}
else
{
value1 = (ims.core.admin.domain.objects.ProviderSystem)domainFactory.getDomainObject(ims.core.admin.domain.objects.ProviderSystem.class, valueObject.getProviderSystem().getBoId());
}
}
domainObject.setProviderSystem(value1);
domainObject.setWasProcessed(valueObject.getWasProcessed());
domainObject.setWasDiscarded(valueObject.getWasDiscarded());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getMsgText() != null && valueObject.getMsgText().equals(""))
{
valueObject.setMsgText(null);
}
domainObject.setMsgText(valueObject.getMsgText());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getAckText() != null && valueObject.getAckText().equals(""))
{
valueObject.setAckText(null);
}
domainObject.setAckText(valueObject.getAckText());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getFailureMsg() != null && valueObject.getFailureMsg().equals(""))
{
valueObject.setFailureMsg(null);
}
domainObject.setFailureMsg(valueObject.getFailureMsg());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value7 = null;
if ( null != valueObject.getMessageStatus() )
{
value7 =
domainFactory.getLookupInstance(valueObject.getMessageStatus().getID());
}
domainObject.setMessageStatus(value7);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value8 = null;
if ( null != valueObject.getMsgType() )
{
value8 =
domainFactory.getLookupInstance(valueObject.getMsgType().getID());
}
domainObject.setMsgType(value8);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value9 = null;
if ( null != valueObject.getQueueType() )
{
value9 =
domainFactory.getLookupInstance(valueObject.getQueueType().getID());
}
domainObject.setQueueType(value9);
ims.core.resource.people.domain.objects.MemberOfStaff value10 = null;
if ( null != valueObject.getMOS() )
{
if (valueObject.getMOS().getBoId() == null)
{
if (domMap.get(valueObject.getMOS()) != null)
{
value10 = (ims.core.resource.people.domain.objects.MemberOfStaff)domMap.get(valueObject.getMOS());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value10 = domainObject.getMOS();
}
else
{
value10 = (ims.core.resource.people.domain.objects.MemberOfStaff)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.MemberOfStaff.class, valueObject.getMOS().getBoId());
}
}
domainObject.setMOS(value10);
return domainObject;
}
}
| IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/hl7/vo/domain/MOSMessageQueueVoAssembler.java | Java | agpl-3.0 | 25,755 |
/*
* 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 java.nio;
/** A buffer of chars.
* <p>
* A char buffer can be created in either one of the following ways:
* </p>
* <ul>
* <li>{@link #allocate(int) Allocate} a new char array and create a buffer based on it;</li>
* <li>{@link #wrap(char[]) Wrap} an existing char array to create a new buffer;</li>
* <li>{@link #wrap(CharSequence) Wrap} an existing char sequence to create a new buffer;</li>
* <li>Use {@link java.nio.ByteBuffer#asCharBuffer() ByteBuffer.asCharBuffer} to create a char buffer based on a byte buffer.</li>
* </ul>
*
* @since Android 1.0 */
public abstract class CharBuffer extends Buffer implements Comparable<CharBuffer>, CharSequence, Appendable {// , Readable {
/** Constructs a {@code CharBuffer} with given capacity.
*
* @param capacity the capacity of the buffer.
* @since Android 1.0 */
CharBuffer (int capacity) {
super(capacity);
}
/** Writes the given char to the current position and increases the position by 1.
*
* @param c the char to write.
* @return this buffer.
* @exception BufferOverflowException if position is equal or greater than limit.
* @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
* @since Android 1.0 */
public abstract CharBuffer put (char c);
/** Writes chars from the given char array to the current position and increases the position by the number of chars written.
* <p>
* Calling this method has the same effect as {@code put(src, 0, src.length)}.
* </p>
*
* @param src the source char array.
* @return this buffer.
* @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}.
* @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
* @since Android 1.0 */
public final CharBuffer put (char[] src) {
return put(src, 0, src.length);
}
/** Writes chars from the given char array, starting from the specified offset, to the current position and increases the
* position by the number of chars written.
*
* @param src the source char array.
* @param off the offset of char array, must not be negative and not greater than {@code src.length}.
* @param len the number of chars to write, must be no less than zero and no greater than {@code src.length - off}.
* @return this buffer.
* @exception BufferOverflowException if {@code remaining()} is less than {@code len}.
* @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid.
* @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer.
* @since Android 1.0 */
public CharBuffer put (char[] src, int off, int len) {
int length = src.length;
if ((off < 0) || (len < 0) || (long)off + (long)len > length) {
throw new IndexOutOfBoundsException();
}
if (len > remaining()) {
throw new BufferOverflowException();
}
for (int i = off; i < off + len; i++) {
put(src[i]);
}
return this;
}
}
| ianopolous/Peergos | src/peergos/gwt/emu/java/nio/CharBuffer.java | Java | agpl-3.0 | 3,800 |
/*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.desktop.components;
import com.jfoenix.controls.JFXRadioButton;
import javafx.scene.control.Skin;
import static bisq.desktop.components.TooltipUtil.showTooltipIfTruncated;
public class AutoTooltipRadioButton extends JFXRadioButton {
public AutoTooltipRadioButton() {
super();
}
public AutoTooltipRadioButton(String text) {
super(text);
}
@Override
protected Skin<?> createDefaultSkin() {
return new AutoTooltipRadioButtonSkin(this);
}
private class AutoTooltipRadioButtonSkin extends JFXRadioButtonSkinBisqStyle {
public AutoTooltipRadioButtonSkin(JFXRadioButton radioButton) {
super(radioButton);
}
@Override
protected void layoutChildren(double x, double y, double w, double h) {
super.layoutChildren(x, y, w, h);
showTooltipIfTruncated(this, getSkinnable());
}
}
}
| bitsquare/bitsquare | desktop/src/main/java/bisq/desktop/components/AutoTooltipRadioButton.java | Java | agpl-3.0 | 1,608 |
//#############################################################################
//# #
//# 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.careuk.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.clinical.ReferralLetterDetails business object (ID: 1003100093).
*/
public class ReferralLetterForSessionManagementVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<ReferralLetterForSessionManagementVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<ReferralLetterForSessionManagementVo> col = new ArrayList<ReferralLetterForSessionManagementVo>();
public String getBoClassName()
{
return "ims.core.clinical.domain.objects.ReferralLetterDetails";
}
public boolean add(ReferralLetterForSessionManagementVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, ReferralLetterForSessionManagementVo 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(ReferralLetterForSessionManagementVo instance)
{
return col.indexOf(instance);
}
public ReferralLetterForSessionManagementVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, ReferralLetterForSessionManagementVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(ReferralLetterForSessionManagementVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(ReferralLetterForSessionManagementVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
ReferralLetterForSessionManagementVoCollection clone = new ReferralLetterForSessionManagementVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((ReferralLetterForSessionManagementVo)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 ReferralLetterForSessionManagementVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public ReferralLetterForSessionManagementVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public ReferralLetterForSessionManagementVoCollection sort(SortOrder order)
{
return sort(new ReferralLetterForSessionManagementVoComparator(order));
}
public ReferralLetterForSessionManagementVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new ReferralLetterForSessionManagementVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public ReferralLetterForSessionManagementVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.clinical.vo.ReferralLetterDetailsRefVoCollection toRefVoCollection()
{
ims.core.clinical.vo.ReferralLetterDetailsRefVoCollection result = new ims.core.clinical.vo.ReferralLetterDetailsRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public ReferralLetterForSessionManagementVo[] toArray()
{
ReferralLetterForSessionManagementVo[] arr = new ReferralLetterForSessionManagementVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<ReferralLetterForSessionManagementVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class ReferralLetterForSessionManagementVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public ReferralLetterForSessionManagementVoComparator()
{
this(SortOrder.ASCENDING);
}
public ReferralLetterForSessionManagementVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public ReferralLetterForSessionManagementVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
ReferralLetterForSessionManagementVo voObj1 = (ReferralLetterForSessionManagementVo)obj1;
ReferralLetterForSessionManagementVo voObj2 = (ReferralLetterForSessionManagementVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean[] getBeanCollectionArray()
{
ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean[] result = new ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
ReferralLetterForSessionManagementVo vo = ((ReferralLetterForSessionManagementVo)col.get(i));
result[i] = (ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean)vo.getBean();
}
return result;
}
public static ReferralLetterForSessionManagementVoCollection buildFromBeanCollection(java.util.Collection beans)
{
ReferralLetterForSessionManagementVoCollection coll = new ReferralLetterForSessionManagementVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean)iter.next()).buildVo());
}
return coll;
}
public static ReferralLetterForSessionManagementVoCollection buildFromBeanCollection(ims.careuk.vo.beans.ReferralLetterForSessionManagementVoBean[] beans)
{
ReferralLetterForSessionManagementVoCollection coll = new ReferralLetterForSessionManagementVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/careuk/vo/ReferralLetterForSessionManagementVoCollection.java | Java | agpl-3.0 | 9,237 |
//#############################################################################
//# #
//# 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 Rory Fitzpatrick using IMS Development Environment (version 1.70 build 3467.22451)
// Copyright (C) 1995-2009 IMS MAXIMS. All rights reserved.
package ims.clinical.forms.inpatientlistwithicpactions;
import java.io.Serializable;
public final class AccessLogic extends BaseAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public boolean isAccessible()
{
if(!super.isAccessible())
return false;
// TODO: Add your conditions here.
return true;
}
public boolean isReadOnly()
{
if(super.isReadOnly())
return true;
// TODO: Add your conditions here.
return false;
}
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/Clinical/src/ims/clinical/forms/inpatientlistwithicpactions/AccessLogic.java | Java | agpl-3.0 | 2,155 |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.fielddata.plain;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.util.BigDoubleArrayList;
import org.elasticsearch.index.fielddata.*;
import org.elasticsearch.index.fielddata.ordinals.Ordinals;
/**
*/
public abstract class DoubleArrayAtomicFieldData extends AtomicNumericFieldData {
public static DoubleArrayAtomicFieldData empty(int numDocs) {
return new Empty(numDocs);
}
private final int numDocs;
protected long size = -1;
public DoubleArrayAtomicFieldData(int numDocs) {
super(true);
this.numDocs = numDocs;
}
@Override
public void close() {
}
@Override
public int getNumDocs() {
return numDocs;
}
static class Empty extends DoubleArrayAtomicFieldData {
Empty(int numDocs) {
super(numDocs);
}
@Override
public LongValues getLongValues() {
return LongValues.EMPTY;
}
@Override
public DoubleValues getDoubleValues() {
return DoubleValues.EMPTY;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return 0;
}
@Override
public long getMemorySizeInBytes() {
return 0;
}
@Override
public BytesValues getBytesValues() {
return BytesValues.EMPTY;
}
@Override
public ScriptDocValues getScriptValues() {
return ScriptDocValues.EMPTY;
}
}
public static class WithOrdinals extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final Ordinals ordinals;
public WithOrdinals(BigDoubleArrayList values, int numDocs, Ordinals ordinals) {
super(numDocs);
this.values = values;
this.ordinals = ordinals;
}
@Override
public boolean isMultiValued() {
return ordinals.isMultiValued();
}
@Override
public boolean isValuesOrdered() {
return true;
}
@Override
public long getNumberUniqueValues() {
return ordinals.getNumOrds();
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_INT/*size*/ + RamUsageEstimator.NUM_BYTES_INT/*numDocs*/ + values.sizeInBytes() + ordinals.getMemorySizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, ordinals.ordinals());
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, ordinals.ordinals());
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues.WithOrdinals {
private final BigDoubleArrayList values;
LongValues(BigDoubleArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public final long getValueByOrd(long ord) {
return (long) values.get(ord);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.WithOrdinals {
private final BigDoubleArrayList values;
DoubleValues(BigDoubleArrayList values, Ordinals.Docs ordinals) {
super(ordinals);
this.values = values;
}
@Override
public double getValueByOrd(long ord) {
return values.get(ord);
}
}
}
/**
* A single valued case, where not all values are "set", so we have a FixedBitSet that
* indicates which values have an actual value.
*/
public static class SingleFixedSet extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final FixedBitSet set;
private final long numOrds;
public SingleFixedSet(BigDoubleArrayList values, int numDocs, FixedBitSet set, long numOrds) {
super(numDocs);
this.values = values;
this.set = set;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes() + RamUsageEstimator.sizeOf(set.getBits());
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values, set);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values, set);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues {
private final BigDoubleArrayList values;
private final FixedBitSet set;
LongValues(BigDoubleArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public boolean hasValue(int docId) {
return set.get(docId);
}
@Override
public long getValue(int docId) {
return (long) values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues {
private final BigDoubleArrayList values;
private final FixedBitSet set;
DoubleValues(BigDoubleArrayList values, FixedBitSet set) {
super(false);
this.values = values;
this.set = set;
}
@Override
public boolean hasValue(int docId) {
return set.get(docId);
}
@Override
public double getValue(int docId) {
return values.get(docId);
}
}
}
/**
* Assumes all the values are "set", and docId is used as the index to the value array.
*/
public static class Single extends DoubleArrayAtomicFieldData {
private final BigDoubleArrayList values;
private final long numOrds;
/**
* Note, here, we assume that there is no offset by 1 from docId, so position 0
* is the value for docId 0.
*/
public Single(BigDoubleArrayList values, int numDocs, long numOrds) {
super(numDocs);
this.values = values;
this.numOrds = numOrds;
}
@Override
public boolean isMultiValued() {
return false;
}
@Override
public boolean isValuesOrdered() {
return false;
}
@Override
public long getNumberUniqueValues() {
return numOrds;
}
@Override
public long getMemorySizeInBytes() {
if (size == -1) {
size = RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + values.sizeInBytes();
}
return size;
}
@Override
public LongValues getLongValues() {
return new LongValues(values);
}
@Override
public DoubleValues getDoubleValues() {
return new DoubleValues(values);
}
static class LongValues extends org.elasticsearch.index.fielddata.LongValues.Dense {
private final BigDoubleArrayList values;
LongValues(BigDoubleArrayList values) {
super(false);
this.values = values;
}
@Override
public long getValue(int docId) {
return (long) values.get(docId);
}
}
static class DoubleValues extends org.elasticsearch.index.fielddata.DoubleValues.Dense {
private final BigDoubleArrayList values;
DoubleValues(BigDoubleArrayList values) {
super(false);
this.values = values;
}
@Override
public double getValue(int docId) {
return values.get(docId);
}
}
}
}
| exercitussolus/yolo | src/main/java/org/elasticsearch/index/fielddata/plain/DoubleArrayAtomicFieldData.java | Java | agpl-3.0 | 9,736 |
/*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla 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 Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
package org.openlmis.report.model.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GeographicZoneJsonDto {
private int id;
private int zoned;
private int geojsonid;
private String geometry;
}
| kelvinmbwilo/vims | modules/report/src/main/java/org/openlmis/report/model/dto/GeographicZoneJsonDto.java | Java | agpl-3.0 | 1,235 |
//#############################################################################
//# #
//# 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.admin.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.PDSBackOfficeItem business object (ID: 1004100073).
*/
public class PDSBackOfficeItemRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<PDSBackOfficeItemRefVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<PDSBackOfficeItemRefVo> col = new ArrayList<PDSBackOfficeItemRefVo>();
public final String getBoClassName()
{
return "ims.core.admin.domain.objects.PDSBackOfficeItem";
}
public ims.domain.IDomainGetter[] getIDomainGetterItems()
{
ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()];
col.toArray(result);
return result;
}
public boolean add(PDSBackOfficeItemRefVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, PDSBackOfficeItemRefVo 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(PDSBackOfficeItemRefVo instance)
{
return col.indexOf(instance);
}
public PDSBackOfficeItemRefVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, PDSBackOfficeItemRefVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(PDSBackOfficeItemRefVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(PDSBackOfficeItemRefVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
PDSBackOfficeItemRefVoCollection clone = new PDSBackOfficeItemRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((PDSBackOfficeItemRefVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
return true;
}
public String[] validate()
{
return null;
}
public PDSBackOfficeItemRefVo[] toArray()
{
PDSBackOfficeItemRefVo[] arr = new PDSBackOfficeItemRefVo[col.size()];
col.toArray(arr);
return arr;
}
public PDSBackOfficeItemRefVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public PDSBackOfficeItemRefVoCollection sort(SortOrder order)
{
return sort(new PDSBackOfficeItemRefVoComparator(order));
}
@SuppressWarnings("unchecked")
public PDSBackOfficeItemRefVoCollection sort(Comparator comparator)
{
Collections.sort(this.col, comparator);
return this;
}
public Iterator<PDSBackOfficeItemRefVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class PDSBackOfficeItemRefVoComparator implements Comparator
{
private int direction = 1;
public PDSBackOfficeItemRefVoComparator()
{
this(SortOrder.ASCENDING);
}
public PDSBackOfficeItemRefVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
this.direction = -1;
}
}
public int compare(Object obj1, Object obj2)
{
PDSBackOfficeItemRefVo voObj1 = (PDSBackOfficeItemRefVo)obj1;
PDSBackOfficeItemRefVo voObj2 = (PDSBackOfficeItemRefVo)obj2;
return direction*(voObj1.compareTo(voObj2));
}
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/admin/vo/PDSBackOfficeItemRefVoCollection.java | Java | agpl-3.0 | 5,948 |
//#############################################################################
//# #
//# 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.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BasePatientMergeManagerImpl extends DomainImpl implements ims.core.domain.PatientMergeManager, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatelistOutstandingRequests(ims.framework.utils.Date dateFrom, ims.framework.utils.Date dateTo, ims.core.resource.people.vo.MemberOfStaffRefVo requestedBy, ims.core.vo.PatientId sourcePat, ims.core.vo.PatientId destPat)
{
}
@SuppressWarnings("unused")
public void validatelistHistoryRequests(ims.framework.utils.Date dteFrom, ims.framework.utils.Date dteTo, ims.core.resource.people.vo.MemberOfStaffRefVo requestedBy, ims.core.vo.PatientId sourcePatient, ims.core.vo.PatientId destinationPatient)
{
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/domain/base/impl/BasePatientMergeManagerImpl.java | Java | agpl-3.0 | 2,946 |
/*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.viewer;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.util.LinkedList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.rapidminer.gui.processeditor.results.ResultDisplayTools;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.performance.PerformanceCriterion;
import com.rapidminer.operator.performance.PerformanceVector;
/**
* Can be used to display the criteria of a {@link PerformanceVector}.
*
* @author Ingo Mierswa
*/
public class PerformanceVectorViewer extends JPanel {
private static final long serialVersionUID = -5848837142789453985L;
public PerformanceVectorViewer(final PerformanceVector performanceVector, final IOContainer container) {
setLayout(new BorderLayout());
// all criteria
final CardLayout cardLayout = new CardLayout();
final JPanel mainPanel = new JPanel(cardLayout);
add(mainPanel, BorderLayout.CENTER);
List<String> criteriaNameList = new LinkedList<String>();
for (int i = 0; i < performanceVector.getSize(); i++) {
PerformanceCriterion criterion = performanceVector.getCriterion(i);
criteriaNameList.add(criterion.getName());
Component component = ResultDisplayTools.createVisualizationComponent(criterion, container, "Performance Criterion");
JScrollPane criterionPane = new ExtendedJScrollPane(component);
criterionPane.setBorder(null);
mainPanel.add(criterionPane, criterion.getName());
}
String[] criteriaNames = new String[criteriaNameList.size()];
criteriaNameList.toArray(criteriaNames);
final JList criteriaList = new JList(criteriaNames) {
private static final long serialVersionUID = 3031125186920370793L;
@Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.width = Math.max(150, dim.width);
return dim;
}
};
// selection list
criteriaList.setBorder(BorderFactory.createTitledBorder("Criterion Selector"));
criteriaList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
criteriaList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selected = (String)criteriaList.getSelectedValue();
cardLayout.show(mainPanel, selected);
}
});
JScrollPane listScrollPane = new ExtendedJScrollPane(criteriaList);
listScrollPane.setBorder(null);
add(listScrollPane, BorderLayout.WEST);
// select first criterion
criteriaList.setSelectedIndices(new int[] { 0 });
}
}
| rapidminer/rapidminer-5 | src/com/rapidminer/gui/viewer/PerformanceVectorViewer.java | Java | agpl-3.0 | 3,703 |
//#############################################################################
//# #
//# 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.forms.casenotearchiveordestroy;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void bindcmbTypeArchLookup();
abstract protected void defaultcmbTypeArchLookupValue();
abstract protected void bindcmbStatusArchLookup();
abstract protected void defaultcmbStatusArchLookupValue();
abstract protected void bindcmbTypeDestrLookup();
abstract protected void defaultcmbTypeDestrLookupValue();
abstract protected void bindcmbStatusDestrLookup();
abstract protected void defaultcmbStatusDestrLookupValue();
abstract protected void bindcmbScannedTypeLookup();
abstract protected void defaultcmbScannedTypeLookupValue();
abstract protected void bindcmbScannedStatusLookup();
abstract protected void defaultcmbScannedStatusLookupValue();
abstract protected void onFormModeChanged();
abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void oncmbTypeArchValueSet(Object value);
abstract protected void oncmbStatusArchValueSet(Object value);
abstract protected void oncmbTypeDestrValueSet(Object value);
abstract protected void oncmbStatusDestrValueSet(Object value);
abstract protected void oncmbScannedTypeValueSet(Object value);
abstract protected void oncmbScannedStatusValueSet(Object value);
abstract protected void onBtnActionClick() throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormModeChangedEvent(new FormModeChanged()
{
private static final long serialVersionUID = 1L;
public void handle()
{
onFormModeChanged();
}
});
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
bindLookups();
onFormOpen(args);
}
});
this.form.btnCancel().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnCancelClick();
}
});
this.form.lyrArchDestr().tabPageArchive().cmbTypeArch().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbTypeArchValueSet(value);
}
});
this.form.lyrArchDestr().tabPageArchive().cmbStatusArch().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbStatusArchValueSet(value);
}
});
this.form.lyrArchDestr().tabPageDestroy().cmbTypeDestr().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbTypeDestrValueSet(value);
}
});
this.form.lyrArchDestr().tabPageDestroy().cmbStatusDestr().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbStatusDestrValueSet(value);
}
});
this.form.lyrArchDestr().tabPageScan().cmbScannedType().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbScannedTypeValueSet(value);
}
});
this.form.lyrArchDestr().tabPageScan().cmbScannedStatus().setValueSetEvent(new ComboBoxValueSet()
{
private static final long serialVersionUID = 1L;
public void handle(Object value)
{
oncmbScannedStatusValueSet(value);
}
});
this.form.btnAction().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnActionClick();
}
});
}
protected void bindLookups()
{
bindcmbTypeArchLookup();
bindcmbStatusArchLookup();
bindcmbTypeDestrLookup();
bindcmbStatusDestrLookup();
bindcmbScannedTypeLookup();
bindcmbScannedStatusLookup();
}
protected void rebindAllLookups()
{
bindcmbTypeArchLookup();
bindcmbStatusArchLookup();
bindcmbTypeDestrLookup();
bindcmbStatusDestrLookup();
bindcmbScannedTypeLookup();
bindcmbScannedStatusLookup();
}
protected void defaultAllLookupValues()
{
defaultcmbTypeArchLookupValue();
defaultcmbStatusArchLookupValue();
defaultcmbTypeDestrLookupValue();
defaultcmbStatusDestrLookupValue();
defaultcmbScannedTypeLookupValue();
defaultcmbScannedStatusLookupValue();
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/casenotearchiveordestroy/Handlers.java | Java | agpl-3.0 | 7,165 |
//#############################################################################
//# #
//# 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.beans;
public class OrderSetShortVoBean extends ims.vo.ValueObjectBean
{
public OrderSetShortVoBean()
{
}
public OrderSetShortVoBean(ims.ocrr.vo.OrderSetShortVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.name = vo.getName();
this.description = vo.getDescription();
this.activestatus = vo.getActiveStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getActiveStatus().getBean();
this.color = vo.getColor() == null ? null : (ims.framework.utils.beans.ColorBean)vo.getColor().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.OrderSetShortVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.name = vo.getName();
this.description = vo.getDescription();
this.activestatus = vo.getActiveStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getActiveStatus().getBean();
this.color = vo.getColor() == null ? null : (ims.framework.utils.beans.ColorBean)vo.getColor().getBean();
}
public ims.ocrr.vo.OrderSetShortVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.ocrr.vo.OrderSetShortVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.ocrr.vo.OrderSetShortVo vo = null;
if(map != null)
vo = (ims.ocrr.vo.OrderSetShortVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.ocrr.vo.OrderSetShortVo();
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 String getName()
{
return this.name;
}
public void setName(String value)
{
this.name = value;
}
public String getDescription()
{
return this.description;
}
public void setDescription(String value)
{
this.description = value;
}
public ims.vo.LookupInstanceBean getActiveStatus()
{
return this.activestatus;
}
public void setActiveStatus(ims.vo.LookupInstanceBean value)
{
this.activestatus = value;
}
public ims.framework.utils.beans.ColorBean getColor()
{
return this.color;
}
public void setColor(ims.framework.utils.beans.ColorBean value)
{
this.color = value;
}
private Integer id;
private int version;
private String name;
private String description;
private ims.vo.LookupInstanceBean activestatus;
private ims.framework.utils.beans.ColorBean color;
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/beans/OrderSetShortVoBean.java | Java | agpl-3.0 | 4,699 |
/*
* 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.operator.preprocessing.filter;
import java.util.List;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.ProcessSetupError.Severity;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.annotation.ResourceConsumptionEstimator;
import com.rapidminer.operator.ports.metadata.AttributeMetaData;
import com.rapidminer.operator.ports.metadata.AttributeSetPrecondition;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.MetaData;
import com.rapidminer.operator.ports.metadata.SimpleMetaDataError;
import com.rapidminer.operator.preprocessing.AbstractDataProcessing;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeAttribute;
import com.rapidminer.parameter.ParameterTypeList;
import com.rapidminer.parameter.ParameterTypeStringCategory;
import com.rapidminer.parameter.UndefinedParameterError;
import com.rapidminer.tools.OperatorResourceConsumptionHandler;
/**
* <p>
* This operator can be used to change the attribute type of an attribute of the input example set.
* If you want to change the attribute name you should use the {@link ChangeAttributeName} operator.
* </p>
*
* <p>
* The target type indicates if the attribute is a regular attribute (used by learning operators) or a
* special attribute (e.g. a label or id attribute). The following target
* attribute types are possible:
* </p>
* <ul>
* <li>regular: only regular attributes are used as input variables for learning tasks</li>
* <li>id: the id attribute for the example set</li>
* <li>label: target attribute for learning</li>
* <li>prediction: predicted attribute, i.e. the predictions of a learning scheme</li>
* <li>cluster: indicates the membership to a cluster</li>
* <li>weight: indicates the weight of the example</li>
* <li>batch: indicates the membership to an example batch</li>
* </ul>
* <p>
* Users can also define own attribute types by simply using the desired name.
* </p>
*
* @author Ingo Mierswa
*/
public class ChangeAttributeRole extends AbstractDataProcessing {
/** The parameter name for "The name of the attribute of which the type should be changed." */
public static final String PARAMETER_NAME = "attribute_name";
/** The parameter name for "The target type of the attribute (only changed if parameter change_attribute_type is true)." */
public static final String PARAMETER_TARGET_ROLE = "target_role";
public static final String PARAMETER_CHANGE_ATTRIBUTES = "set_additional_roles";
private static final String REGULAR_NAME = "regular";
private static final String[] TARGET_ROLES = new String[] { REGULAR_NAME, Attributes.ID_NAME, Attributes.LABEL_NAME, Attributes.PREDICTION_NAME, Attributes.CLUSTER_NAME, Attributes.WEIGHT_NAME, Attributes.BATCH_NAME };
public ChangeAttributeRole(OperatorDescription description) {
super(description);
getExampleSetInputPort().addPrecondition(new AttributeSetPrecondition(getExampleSetInputPort(), AttributeSetPrecondition.getAttributesByParameter(this, PARAMETER_NAME)));
getExampleSetInputPort().addPrecondition(new AttributeSetPrecondition(getExampleSetInputPort(), AttributeSetPrecondition.getAttributesByParameterListEntry(this, PARAMETER_CHANGE_ATTRIBUTES, 0)));
}
@Override
protected MetaData modifyMetaData(ExampleSetMetaData metaData) {
try {
String targetRole = null;
if (isParameterSet(PARAMETER_TARGET_ROLE))
targetRole = getParameterAsString(PARAMETER_TARGET_ROLE);
if (isParameterSet(PARAMETER_NAME)) {
String name = getParameter(PARAMETER_NAME);
setRoleMetaData(metaData, name, targetRole);
}
// now proceed with list
if (isParameterSet(PARAMETER_CHANGE_ATTRIBUTES)) {
List<String[]> list = getParameterList(PARAMETER_CHANGE_ATTRIBUTES);
for (String[] pairs: list) {
setRoleMetaData(metaData, pairs[0], pairs[1]);
}
}
} catch (UndefinedParameterError e) {
}
return metaData;
}
private void setRoleMetaData(ExampleSetMetaData metaData, String name, String targetRole) {
AttributeMetaData amd = metaData.getAttributeByName(name);
if (amd != null) {
if (targetRole != null) {
if (REGULAR_NAME.equals(targetRole)) {
amd.setRegular();
} else {
AttributeMetaData oldRole = metaData.getAttributeByRole(targetRole);
if (oldRole != null && oldRole != amd) {
getInputPort().addError(new SimpleMetaDataError(Severity.WARNING, getInputPort(), "already_contains_role", targetRole));
metaData.removeAttribute(oldRole);
}
amd.setRole(targetRole);
}
}
}
}
@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
String name = getParameterAsString(PARAMETER_NAME);
String newRole = getParameterAsString(PARAMETER_TARGET_ROLE);
setRole(exampleSet, name, newRole);
// now do the list
if (isParameterSet(PARAMETER_CHANGE_ATTRIBUTES)) {
List<String[]> list = getParameterList(PARAMETER_CHANGE_ATTRIBUTES);
for (String[] pairs: list) {
setRole(exampleSet, pairs[0], pairs[1]);
}
}
return exampleSet;
}
private void setRole(ExampleSet exampleSet, String name, String newRole) throws UserError {
Attribute attribute = exampleSet.getAttributes().get(name);
if (attribute == null) {
if (!name.isEmpty()) {
throw new UserError(this, 160, name);
} else {
throw new UserError(this, 111, name);
}
}
exampleSet.getAttributes().remove(attribute);
if ((newRole == null) || (newRole.trim().length() == 0))
throw new UserError(this, 205, PARAMETER_TARGET_ROLE);
if (newRole.equals(REGULAR_NAME)) {
exampleSet.getAttributes().addRegular(attribute);
} else {
exampleSet.getAttributes().setSpecialAttribute(attribute, newRole);
}
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeAttribute(PARAMETER_NAME, "The name of the attribute whose role should be changed.", getExampleSetInputPort(), false, false));
ParameterType type = new ParameterTypeStringCategory(PARAMETER_TARGET_ROLE, "The target role of the attribute (only changed if parameter change_attribute_type is true).", TARGET_ROLES, TARGET_ROLES[0]);
type.setExpert(false);
types.add(type);
types.add(new ParameterTypeList(PARAMETER_CHANGE_ATTRIBUTES, "This parameter defines additional attribute role combinations.",
new ParameterTypeAttribute(PARAMETER_NAME, "The name of the attribute whose role should be changed.", getExampleSetInputPort(), false, false),
new ParameterTypeStringCategory(PARAMETER_TARGET_ROLE, "The target role of the attribute (only changed if parameter change_attribute_type is true).", TARGET_ROLES, TARGET_ROLES[0]),
false));
return types;
}
@Override
public boolean writesIntoExistingData() {
return false;
}
@Override
public ResourceConsumptionEstimator getResourceConsumptionEstimator() {
return OperatorResourceConsumptionHandler.getResourceConsumptionEstimator(getInputPort(), ChangeAttributeRole.class, null);
}
}
| aborg0/RapidMiner-Unuk | src/com/rapidminer/operator/preprocessing/filter/ChangeAttributeRole.java | Java | agpl-3.0 | 8,197 |
//#############################################################################
//# #
//# 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.coe.assessment.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to coe.assessment.Personal Hygiene Feet business object (ID: 1012100036).
*/
public class PersonalHygieneFeetRefVoCollection extends ims.vo.ValueObjectCollection implements ims.domain.IDomainCollectionGetter, ims.vo.ImsCloneable, Iterable<PersonalHygieneFeetRefVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<PersonalHygieneFeetRefVo> col = new ArrayList<PersonalHygieneFeetRefVo>();
public final String getBoClassName()
{
return "ims.coe.assessment.domain.objects.PersonalHygieneFeet";
}
public ims.domain.IDomainGetter[] getIDomainGetterItems()
{
ims.domain.IDomainGetter[] result = new ims.domain.IDomainGetter[col.size()];
col.toArray(result);
return result;
}
public boolean add(PersonalHygieneFeetRefVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, PersonalHygieneFeetRefVo 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(PersonalHygieneFeetRefVo instance)
{
return col.indexOf(instance);
}
public PersonalHygieneFeetRefVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, PersonalHygieneFeetRefVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(PersonalHygieneFeetRefVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(PersonalHygieneFeetRefVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
PersonalHygieneFeetRefVoCollection clone = new PersonalHygieneFeetRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((PersonalHygieneFeetRefVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
return true;
}
public String[] validate()
{
return null;
}
public PersonalHygieneFeetRefVo[] toArray()
{
PersonalHygieneFeetRefVo[] arr = new PersonalHygieneFeetRefVo[col.size()];
col.toArray(arr);
return arr;
}
public PersonalHygieneFeetRefVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public PersonalHygieneFeetRefVoCollection sort(SortOrder order)
{
return sort(new PersonalHygieneFeetRefVoComparator(order));
}
@SuppressWarnings("unchecked")
public PersonalHygieneFeetRefVoCollection sort(Comparator comparator)
{
Collections.sort(this.col, comparator);
return this;
}
public Iterator<PersonalHygieneFeetRefVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class PersonalHygieneFeetRefVoComparator implements Comparator
{
private int direction = 1;
public PersonalHygieneFeetRefVoComparator()
{
this(SortOrder.ASCENDING);
}
public PersonalHygieneFeetRefVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
this.direction = -1;
}
}
public int compare(Object obj1, Object obj2)
{
PersonalHygieneFeetRefVo voObj1 = (PersonalHygieneFeetRefVo)obj1;
PersonalHygieneFeetRefVo voObj2 = (PersonalHygieneFeetRefVo)obj2;
return direction*(voObj1.compareTo(voObj2));
}
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/coe/assessment/vo/PersonalHygieneFeetRefVoCollection.java | Java | agpl-3.0 | 6,024 |
//#############################################################################
//# #
//# 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.careuk.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to CAREUK.WorkAllocation business object (ID: 1096100033).
*/
public class WorkAllocationVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<WorkAllocationVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<WorkAllocationVo> col = new ArrayList<WorkAllocationVo>();
public String getBoClassName()
{
return "ims.careuk.domain.objects.WorkAllocation";
}
public boolean add(WorkAllocationVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, WorkAllocationVo 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(WorkAllocationVo instance)
{
return col.indexOf(instance);
}
public WorkAllocationVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, WorkAllocationVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(WorkAllocationVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(WorkAllocationVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
WorkAllocationVoCollection clone = new WorkAllocationVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((WorkAllocationVo)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 WorkAllocationVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public WorkAllocationVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public WorkAllocationVoCollection sort(SortOrder order)
{
return sort(new WorkAllocationVoComparator(order));
}
public WorkAllocationVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new WorkAllocationVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public WorkAllocationVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.careuk.vo.WorkAllocationRefVoCollection toRefVoCollection()
{
ims.careuk.vo.WorkAllocationRefVoCollection result = new ims.careuk.vo.WorkAllocationRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public WorkAllocationVo[] toArray()
{
WorkAllocationVo[] arr = new WorkAllocationVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<WorkAllocationVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class WorkAllocationVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public WorkAllocationVoComparator()
{
this(SortOrder.ASCENDING);
}
public WorkAllocationVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public WorkAllocationVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
WorkAllocationVo voObj1 = (WorkAllocationVo)obj1;
WorkAllocationVo voObj2 = (WorkAllocationVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.careuk.vo.beans.WorkAllocationVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.careuk.vo.beans.WorkAllocationVoBean[] getBeanCollectionArray()
{
ims.careuk.vo.beans.WorkAllocationVoBean[] result = new ims.careuk.vo.beans.WorkAllocationVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
WorkAllocationVo vo = ((WorkAllocationVo)col.get(i));
result[i] = (ims.careuk.vo.beans.WorkAllocationVoBean)vo.getBean();
}
return result;
}
public static WorkAllocationVoCollection buildFromBeanCollection(java.util.Collection beans)
{
WorkAllocationVoCollection coll = new WorkAllocationVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.careuk.vo.beans.WorkAllocationVoBean)iter.next()).buildVo());
}
return coll;
}
public static WorkAllocationVoCollection buildFromBeanCollection(ims.careuk.vo.beans.WorkAllocationVoBean[] beans)
{
WorkAllocationVoCollection coll = new WorkAllocationVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/careuk/vo/WorkAllocationVoCollection.java | Java | agpl-3.0 | 8,207 |
//#############################################################################
//# #
//# 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 Florin Blindu using IMS Development Environment (version 1.80 build 4785.23502)
// Copyright (C) 1995-2013 IMS MAXIMS. All rights reserved.
package ims.core.domain.impl;
import ims.admin.domain.HcpAdmin;
import ims.admin.domain.impl.HcpAdminImpl;
import ims.core.domain.base.impl.BaseAuthoringInfoSingleLineImpl;
import ims.core.vo.HcpFilter;
import ims.core.vo.HcpLiteVoCollection;
import ims.core.vo.lookups.HcpDisType;
import ims.domain.DomainFactory;
import ims.domain.exceptions.DomainRuntimeException;
import java.util.ArrayList;
import java.util.List;
public class AuthoringInfoSingleLineImpl extends BaseAuthoringInfoSingleLineImpl
{
private static final long serialVersionUID = 1L;
public HcpLiteVoCollection listHcpLiteByNameAndDisciplineType(String hcpName, HcpDisType hcpDisciplineType)
{
//WDEV-8356
if (hcpName == null || hcpName.length() == 0)
throw new DomainRuntimeException("Name not supplied");
HcpAdmin hcpImpl = (HcpAdmin) getDomainImpl(HcpAdminImpl.class);
return hcpImpl.listHcpLiteByNameAndDisciplineType(hcpName, hcpDisciplineType);
/*
HcpFilter filter = new HcpFilter();
filter.setQueryName(new PersonName());
filter.getQueryName().setSurname(hcpName);
if(hcpDisciplineType != null)
filter.setHcpType(hcpDisciplineType);
List l = this.listHCPList(filter);
return HcpLiteVoAssembler.createHcpLiteVoCollectionFromHcp(l);*/
}
private List listHCPList(HcpFilter filter)
{
DomainFactory factory = getDomainFactory();
String hql;
ArrayList<String> markers = new ArrayList<String>();
ArrayList<Object> values = new ArrayList<Object>();
if (filter == null)
filter = new HcpFilter();
hql = " from Hcp h ";
StringBuffer condStr = new StringBuffer();
String andStr = " ";
if (filter.getQueryName() != null)
{
if (filter.getQueryName().getSurname() != null && filter.getQueryName().getSurname().length() > 0)
{
condStr.append(" h.mos.name.upperSurname like :hcpSname");
markers.add("hcpSname");
values.add(filter.getQueryName().getSurname().toUpperCase() + "%");
andStr = " and ";
}
if (filter.getQueryName().getForename() != null && filter.getQueryName().getForename().length() > 0)
{
condStr.append(andStr + " h.mos.name.upperForename like :hcpFname");
markers.add("hcpFname");
values.add(filter.getQueryName().getForename().toUpperCase() + "%");
andStr = " and ";
}
}
if (filter.getHcpType() != null)
{
//If the hcpType = HcpDisType.OTHER we must allow for that field being null or it's parent == OTHER
if (filter.getHcpType().equals(HcpDisType.OTHER))
{
condStr.append(andStr + " ( h.hcpType is null or h.hcpType.parent.id = :hcpType) ");
}
else
{
condStr.append(andStr + " h.hcpType = :hcpType");
}
markers.add("hcpType");
values.add(getDomLookup(filter.getHcpType()));
andStr = " and ";
}
condStr.append(andStr + "h.isActive = :isActive");
markers.add("isActive");
values.add(Boolean.TRUE);
andStr = " and ";
if (andStr.equals(" and "))
{
hql += " where ";
}
hql += condStr.toString();
return factory.find(hql, markers, values);
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/domain/impl/AuthoringInfoSingleLineImpl.java | Java | agpl-3.0 | 5,161 |
//#############################################################################
//# #
//# 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.icp.vo;
/**
* Linked to ICPs.Instantiation.PatientICP business object (ID: 1100100000).
*/
public class PatientICPVo extends ims.icps.instantiation.vo.PatientICPRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public PatientICPVo()
{
}
public PatientICPVo(Integer id, int version)
{
super(id, version);
}
public PatientICPVo(ims.icp.vo.beans.PatientICPVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion());
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion());
this.pasevent = bean.getPasEvent() == null ? null : new ims.core.admin.pas.vo.PASEventRefVo(new Integer(bean.getPasEvent().getId()), bean.getPasEvent().getVersion());
this.icp = bean.getICP() == null ? null : bean.getICP().buildVo();
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo();
this.stages = ims.icp.vo.PatientICPStageVoCollection.buildFromBeanCollection(bean.getStages());
this.hasoutstandingadminactions = bean.getHasOutstandingAdminActions();
this.hasoutstandingnursingactions = bean.getHasOutstandingNursingActions();
this.hasoutstandingphysioactions = bean.getHasOutstandingPhysioActions();
this.hasoutstandingclinicalactions = bean.getHasOutstandingClinicalActions();
if(bean.getAppointments() != null)
{
this.appointments = new ims.scheduling.vo.Booking_AppointmentRefVoCollection();
for(int appointments_i = 0; appointments_i < bean.getAppointments().length; appointments_i++)
{
this.appointments.add(new ims.scheduling.vo.Booking_AppointmentRefVo(new Integer(bean.getAppointments()[appointments_i].getId()), bean.getAppointments()[appointments_i].getVersion()));
}
}
if(bean.getCriticalEvents() != null)
{
this.criticalevents = new ims.icps.instantiation.vo.PatientCriticalEventsRefVoCollection();
for(int criticalevents_i = 0; criticalevents_i < bean.getCriticalEvents().length; criticalevents_i++)
{
this.criticalevents.add(new ims.icps.instantiation.vo.PatientCriticalEventsRefVo(new Integer(bean.getCriticalEvents()[criticalevents_i].getId()), bean.getCriticalEvents()[criticalevents_i].getVersion()));
}
}
this.starteddatetime = bean.getStartedDateTime() == null ? null : bean.getStartedDateTime().buildDateTime();
this.completeddatetime = bean.getCompletedDateTime() == null ? null : bean.getCompletedDateTime().buildDateTime();
if(bean.getEvaluationNotes() != null)
{
this.evaluationnotes = new ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVoCollection();
for(int evaluationnotes_i = 0; evaluationnotes_i < bean.getEvaluationNotes().length; evaluationnotes_i++)
{
this.evaluationnotes.add(new ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVo(new Integer(bean.getEvaluationNotes()[evaluationnotes_i].getId()), bean.getEvaluationNotes()[evaluationnotes_i].getVersion()));
}
}
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.icp.vo.beans.PatientICPVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.patient = bean.getPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPatient().getId()), bean.getPatient().getVersion());
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion());
this.pasevent = bean.getPasEvent() == null ? null : new ims.core.admin.pas.vo.PASEventRefVo(new Integer(bean.getPasEvent().getId()), bean.getPasEvent().getVersion());
this.icp = bean.getICP() == null ? null : bean.getICP().buildVo(map);
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo(map);
this.stages = ims.icp.vo.PatientICPStageVoCollection.buildFromBeanCollection(bean.getStages());
this.hasoutstandingadminactions = bean.getHasOutstandingAdminActions();
this.hasoutstandingnursingactions = bean.getHasOutstandingNursingActions();
this.hasoutstandingphysioactions = bean.getHasOutstandingPhysioActions();
this.hasoutstandingclinicalactions = bean.getHasOutstandingClinicalActions();
if(bean.getAppointments() != null)
{
this.appointments = new ims.scheduling.vo.Booking_AppointmentRefVoCollection();
for(int appointments_i = 0; appointments_i < bean.getAppointments().length; appointments_i++)
{
this.appointments.add(new ims.scheduling.vo.Booking_AppointmentRefVo(new Integer(bean.getAppointments()[appointments_i].getId()), bean.getAppointments()[appointments_i].getVersion()));
}
}
if(bean.getCriticalEvents() != null)
{
this.criticalevents = new ims.icps.instantiation.vo.PatientCriticalEventsRefVoCollection();
for(int criticalevents_i = 0; criticalevents_i < bean.getCriticalEvents().length; criticalevents_i++)
{
this.criticalevents.add(new ims.icps.instantiation.vo.PatientCriticalEventsRefVo(new Integer(bean.getCriticalEvents()[criticalevents_i].getId()), bean.getCriticalEvents()[criticalevents_i].getVersion()));
}
}
this.starteddatetime = bean.getStartedDateTime() == null ? null : bean.getStartedDateTime().buildDateTime();
this.completeddatetime = bean.getCompletedDateTime() == null ? null : bean.getCompletedDateTime().buildDateTime();
if(bean.getEvaluationNotes() != null)
{
this.evaluationnotes = new ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVoCollection();
for(int evaluationnotes_i = 0; evaluationnotes_i < bean.getEvaluationNotes().length; evaluationnotes_i++)
{
this.evaluationnotes.add(new ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVo(new Integer(bean.getEvaluationNotes()[evaluationnotes_i].getId()), bean.getEvaluationNotes()[evaluationnotes_i].getVersion()));
}
}
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.icp.vo.beans.PatientICPVoBean bean = null;
if(map != null)
bean = (ims.icp.vo.beans.PatientICPVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.icp.vo.beans.PatientICPVoBean();
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("PATIENT"))
return getPatient();
if(fieldName.equals("CARECONTEXT"))
return getCareContext();
if(fieldName.equals("CLINICALCONTACT"))
return getClinicalContact();
if(fieldName.equals("PASEVENT"))
return getPasEvent();
if(fieldName.equals("ICP"))
return getICP();
if(fieldName.equals("AUTHORINGINFORMATION"))
return getAuthoringInformation();
if(fieldName.equals("STAGES"))
return getStages();
if(fieldName.equals("HASOUTSTANDINGADMINACTIONS"))
return getHasOutstandingAdminActions();
if(fieldName.equals("HASOUTSTANDINGNURSINGACTIONS"))
return getHasOutstandingNursingActions();
if(fieldName.equals("HASOUTSTANDINGPHYSIOACTIONS"))
return getHasOutstandingPhysioActions();
if(fieldName.equals("HASOUTSTANDINGCLINICALACTIONS"))
return getHasOutstandingClinicalActions();
if(fieldName.equals("APPOINTMENTS"))
return getAppointments();
if(fieldName.equals("CRITICALEVENTS"))
return getCriticalEvents();
if(fieldName.equals("STARTEDDATETIME"))
return getStartedDateTime();
if(fieldName.equals("COMPLETEDDATETIME"))
return getCompletedDateTime();
if(fieldName.equals("EVALUATIONNOTES"))
return getEvaluationNotes();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getPatientIsNotNull()
{
return this.patient != null;
}
public ims.core.patient.vo.PatientRefVo getPatient()
{
return this.patient;
}
public void setPatient(ims.core.patient.vo.PatientRefVo value)
{
this.isValidated = false;
this.patient = value;
}
public boolean getCareContextIsNotNull()
{
return this.carecontext != null;
}
public ims.core.admin.vo.CareContextRefVo getCareContext()
{
return this.carecontext;
}
public void setCareContext(ims.core.admin.vo.CareContextRefVo value)
{
this.isValidated = false;
this.carecontext = value;
}
public boolean getClinicalContactIsNotNull()
{
return this.clinicalcontact != null;
}
public ims.core.admin.vo.ClinicalContactRefVo getClinicalContact()
{
return this.clinicalcontact;
}
public void setClinicalContact(ims.core.admin.vo.ClinicalContactRefVo value)
{
this.isValidated = false;
this.clinicalcontact = value;
}
public boolean getPasEventIsNotNull()
{
return this.pasevent != null;
}
public ims.core.admin.pas.vo.PASEventRefVo getPasEvent()
{
return this.pasevent;
}
public void setPasEvent(ims.core.admin.pas.vo.PASEventRefVo value)
{
this.isValidated = false;
this.pasevent = value;
}
public boolean getICPIsNotNull()
{
return this.icp != null;
}
public ims.icp.vo.ICPLiteVo getICP()
{
return this.icp;
}
public void setICP(ims.icp.vo.ICPLiteVo value)
{
this.isValidated = false;
this.icp = value;
}
public boolean getAuthoringInformationIsNotNull()
{
return this.authoringinformation != null;
}
public ims.core.vo.AuthoringInformationVo getAuthoringInformation()
{
return this.authoringinformation;
}
public void setAuthoringInformation(ims.core.vo.AuthoringInformationVo value)
{
this.isValidated = false;
this.authoringinformation = value;
}
public boolean getStagesIsNotNull()
{
return this.stages != null;
}
public ims.icp.vo.PatientICPStageVoCollection getStages()
{
return this.stages;
}
public void setStages(ims.icp.vo.PatientICPStageVoCollection value)
{
this.isValidated = false;
this.stages = value;
}
public boolean getHasOutstandingAdminActionsIsNotNull()
{
return this.hasoutstandingadminactions != null;
}
public Boolean getHasOutstandingAdminActions()
{
return this.hasoutstandingadminactions;
}
public void setHasOutstandingAdminActions(Boolean value)
{
this.isValidated = false;
this.hasoutstandingadminactions = value;
}
public boolean getHasOutstandingNursingActionsIsNotNull()
{
return this.hasoutstandingnursingactions != null;
}
public Boolean getHasOutstandingNursingActions()
{
return this.hasoutstandingnursingactions;
}
public void setHasOutstandingNursingActions(Boolean value)
{
this.isValidated = false;
this.hasoutstandingnursingactions = value;
}
public boolean getHasOutstandingPhysioActionsIsNotNull()
{
return this.hasoutstandingphysioactions != null;
}
public Boolean getHasOutstandingPhysioActions()
{
return this.hasoutstandingphysioactions;
}
public void setHasOutstandingPhysioActions(Boolean value)
{
this.isValidated = false;
this.hasoutstandingphysioactions = value;
}
public boolean getHasOutstandingClinicalActionsIsNotNull()
{
return this.hasoutstandingclinicalactions != null;
}
public Boolean getHasOutstandingClinicalActions()
{
return this.hasoutstandingclinicalactions;
}
public void setHasOutstandingClinicalActions(Boolean value)
{
this.isValidated = false;
this.hasoutstandingclinicalactions = value;
}
public boolean getAppointmentsIsNotNull()
{
return this.appointments != null;
}
public ims.scheduling.vo.Booking_AppointmentRefVoCollection getAppointments()
{
return this.appointments;
}
public void setAppointments(ims.scheduling.vo.Booking_AppointmentRefVoCollection value)
{
this.isValidated = false;
this.appointments = value;
}
public boolean getCriticalEventsIsNotNull()
{
return this.criticalevents != null;
}
public ims.icps.instantiation.vo.PatientCriticalEventsRefVoCollection getCriticalEvents()
{
return this.criticalevents;
}
public void setCriticalEvents(ims.icps.instantiation.vo.PatientCriticalEventsRefVoCollection value)
{
this.isValidated = false;
this.criticalevents = value;
}
public boolean getStartedDateTimeIsNotNull()
{
return this.starteddatetime != null;
}
public ims.framework.utils.DateTime getStartedDateTime()
{
return this.starteddatetime;
}
public void setStartedDateTime(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.starteddatetime = value;
}
public boolean getCompletedDateTimeIsNotNull()
{
return this.completeddatetime != null;
}
public ims.framework.utils.DateTime getCompletedDateTime()
{
return this.completeddatetime;
}
public void setCompletedDateTime(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.completeddatetime = value;
}
public boolean getEvaluationNotesIsNotNull()
{
return this.evaluationnotes != null;
}
public ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVoCollection getEvaluationNotes()
{
return this.evaluationnotes;
}
public void setEvaluationNotes(ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVoCollection value)
{
this.isValidated = false;
this.evaluationnotes = value;
}
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]);
}
}
if(this.patient == null)
listOfErrors.add("Patient is mandatory");
if(this.carecontext == null)
listOfErrors.add("CareContext is mandatory");
if(this.icp == null)
listOfErrors.add("ICP is mandatory");
if(this.authoringinformation == null)
listOfErrors.add("AuthoringInformation is mandatory");
if(this.stages == null || this.stages.size() == 0)
listOfErrors.add("Stages are mandatory");
if(this.hasoutstandingadminactions == null)
listOfErrors.add("hasOutstandingAdminActions is mandatory");
if(this.hasoutstandingnursingactions == null)
listOfErrors.add("hasOutstandingNursingActions is mandatory");
if(this.hasoutstandingphysioactions == null)
listOfErrors.add("hasOutstandingPhysioActions is mandatory");
if(this.hasoutstandingclinicalactions == null)
listOfErrors.add("hasOutstandingClinicalActions is mandatory");
if(this.starteddatetime == null)
listOfErrors.add("StartedDateTime is mandatory");
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;
PatientICPVo clone = new PatientICPVo(this.id, this.version);
clone.patient = this.patient;
clone.carecontext = this.carecontext;
clone.clinicalcontact = this.clinicalcontact;
clone.pasevent = this.pasevent;
if(this.icp == null)
clone.icp = null;
else
clone.icp = (ims.icp.vo.ICPLiteVo)this.icp.clone();
if(this.authoringinformation == null)
clone.authoringinformation = null;
else
clone.authoringinformation = (ims.core.vo.AuthoringInformationVo)this.authoringinformation.clone();
if(this.stages == null)
clone.stages = null;
else
clone.stages = (ims.icp.vo.PatientICPStageVoCollection)this.stages.clone();
clone.hasoutstandingadminactions = this.hasoutstandingadminactions;
clone.hasoutstandingnursingactions = this.hasoutstandingnursingactions;
clone.hasoutstandingphysioactions = this.hasoutstandingphysioactions;
clone.hasoutstandingclinicalactions = this.hasoutstandingclinicalactions;
clone.appointments = this.appointments;
clone.criticalevents = this.criticalevents;
if(this.starteddatetime == null)
clone.starteddatetime = null;
else
clone.starteddatetime = (ims.framework.utils.DateTime)this.starteddatetime.clone();
if(this.completeddatetime == null)
clone.completeddatetime = null;
else
clone.completeddatetime = (ims.framework.utils.DateTime)this.completeddatetime.clone();
clone.evaluationnotes = this.evaluationnotes;
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 (!(PatientICPVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A PatientICPVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((PatientICPVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((PatientICPVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.patient != null)
count++;
if(this.carecontext != null)
count++;
if(this.clinicalcontact != null)
count++;
if(this.pasevent != null)
count++;
if(this.icp != null)
count++;
if(this.authoringinformation != null)
count++;
if(this.stages != null)
count++;
if(this.hasoutstandingadminactions != null)
count++;
if(this.hasoutstandingnursingactions != null)
count++;
if(this.hasoutstandingphysioactions != null)
count++;
if(this.hasoutstandingclinicalactions != null)
count++;
if(this.appointments != null)
count++;
if(this.criticalevents != null)
count++;
if(this.starteddatetime != null)
count++;
if(this.completeddatetime != null)
count++;
if(this.evaluationnotes != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 16;
}
protected ims.core.patient.vo.PatientRefVo patient;
protected ims.core.admin.vo.CareContextRefVo carecontext;
protected ims.core.admin.vo.ClinicalContactRefVo clinicalcontact;
protected ims.core.admin.pas.vo.PASEventRefVo pasevent;
protected ims.icp.vo.ICPLiteVo icp;
protected ims.core.vo.AuthoringInformationVo authoringinformation;
protected ims.icp.vo.PatientICPStageVoCollection stages;
protected Boolean hasoutstandingadminactions;
protected Boolean hasoutstandingnursingactions;
protected Boolean hasoutstandingphysioactions;
protected Boolean hasoutstandingclinicalactions;
protected ims.scheduling.vo.Booking_AppointmentRefVoCollection appointments;
protected ims.icps.instantiation.vo.PatientCriticalEventsRefVoCollection criticalevents;
protected ims.framework.utils.DateTime starteddatetime;
protected ims.framework.utils.DateTime completeddatetime;
protected ims.icps.instantiation.vo.PatientICPEvaluationNoteRefVoCollection evaluationnotes;
private boolean isValidated = false;
private boolean isBusy = false;
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/icp/vo/PatientICPVo.java | Java | agpl-3.0 | 22,583 |
//#############################################################################
//# #
//# 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.forms.alertcomment;
import java.io.Serializable;
import ims.framework.Context;
import ims.framework.FormName;
import ims.framework.FormAccessLogic;
public class BaseAccessLogic extends FormAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public final void setContext(Context context, FormName formName)
{
form = new CurrentForm(new GlobalContext(context), new CurrentForms());
engine = new CurrentEngine(formName);
}
public boolean isAccessible()
{
return true;
}
public boolean isReadOnly()
{
return false;
}
public CurrentEngine engine;
public CurrentForm form;
public final static class CurrentForm implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentForm(GlobalContext globalcontext, CurrentForms forms)
{
this.globalcontext = globalcontext;
this.forms = forms;
}
public final GlobalContext getGlobalContext()
{
return globalcontext;
}
public final CurrentForms getForms()
{
return forms;
}
private GlobalContext globalcontext;
private CurrentForms forms;
}
public final static class CurrentEngine implements Serializable
{
private static final long serialVersionUID = 1L;
CurrentEngine(FormName formName)
{
this.formName = formName;
}
public final FormName getFormName()
{
return formName;
}
private FormName formName;
}
public static final class CurrentForms implements Serializable
{
private static final long serialVersionUID = 1L;
protected final class LocalFormName extends FormName
{
private static final long serialVersionUID = 1L;
protected LocalFormName(int value)
{
super(value);
}
}
private CurrentForms()
{
}
}
}
| FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/alertcomment/BaseAccessLogic.java | Java | agpl-3.0 | 3,929 |
package org.ethereum.samples;
import org.ethereum.config.CommonConfig;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.datasource.Source;
import org.ethereum.db.IndexedBlockStore;
import java.util.List;
/**
* Created by Anton Nashatyrev on 21.07.2016.
*/
public class CheckFork {
public static void main(String[] args) throws Exception {
SystemProperties.getDefault().overrideParams("database.dir", "");
Source<byte[], byte[]> index = CommonConfig.getDefault().cachedDbSource("index");
Source<byte[], byte[]> blockDS = CommonConfig.getDefault().cachedDbSource("block");
IndexedBlockStore indexedBlockStore = new IndexedBlockStore();
indexedBlockStore.init(index, blockDS);
for (int i = 1_919_990; i < 1_921_000; i++) {
Block chainBlock = indexedBlockStore.getChainBlockByNumber(i);
List<Block> blocks = indexedBlockStore.getBlocksByNumber(i);
String s = chainBlock.getShortDescr() + " (";
for (Block block : blocks) {
if (!block.isEqual(chainBlock)) {
s += block.getShortDescr() + " ";
}
}
System.out.println(s);
}
}
}
| dbenrosen/EtherPay | ethereumj-core/src/main/java/org/ethereum/samples/CheckFork.java | Java | agpl-3.0 | 1,263 |
/*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software GmbH & Co. KG, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* 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 org.opencms.workplace.explorer.menu;
import org.opencms.file.CmsObject;
import org.opencms.main.OpenCms;
import org.opencms.workplace.explorer.CmsResourceUtil;
/**
* Defines a menu item rule that sets the visibility to inactive if the current resource is unlocked and the auto lock
* feature is disabled.<p>
*
* @since 6.5.6
*/
public class CmsMirPrSameUnlockedInactiveNoAl extends A_CmsMenuItemRule {
/**
* @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#getVisibility(org.opencms.file.CmsObject, CmsResourceUtil[])
*/
@Override
public CmsMenuItemVisibilityMode getVisibility(CmsObject cms, CmsResourceUtil[] resourceUtil) {
return CmsMenuItemVisibilityMode.VISIBILITY_INACTIVE.addMessageKey(
Messages.GUI_CONTEXTMENU_TITLE_INACTIVE_NOTLOCKED_0);
}
/**
* @see org.opencms.workplace.explorer.menu.I_CmsMenuItemRule#matches(org.opencms.file.CmsObject, CmsResourceUtil[])
*/
public boolean matches(CmsObject cms, CmsResourceUtil[] resourceUtil) {
if (resourceUtil[0].isInsideProject()) {
if (resourceUtil[0].getLock().isNullLock()) {
return !OpenCms.getWorkplaceManager().autoLockResources();
}
}
// resource is not in current project
return false;
}
}
| ggiudetti/opencms-core | src/org/opencms/workplace/explorer/menu/CmsMirPrSameUnlockedInactiveNoAl.java | Java | lgpl-2.1 | 2,455 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.persister.internal;
import java.util.Map;
import org.hibernate.boot.registry.StandardServiceInitiator;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.persister.spi.PersisterFactory;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;
/**
* @author Steve Ebersole
*/
public class PersisterFactoryInitiator implements StandardServiceInitiator<PersisterFactory> {
public static final PersisterFactoryInitiator INSTANCE = new PersisterFactoryInitiator();
public static final String IMPL_NAME = "hibernate.persister.factory";
@Override
public Class<PersisterFactory> getServiceInitiated() {
return PersisterFactory.class;
}
@Override
@SuppressWarnings( {"unchecked"})
public PersisterFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
final Object customImpl = configurationValues.get( IMPL_NAME );
if ( customImpl == null ) {
return new PersisterFactoryImpl();
}
if ( PersisterFactory.class.isInstance( customImpl ) ) {
return (PersisterFactory) customImpl;
}
final Class<? extends PersisterFactory> customImplClass = Class.class.isInstance( customImpl )
? ( Class<? extends PersisterFactory> ) customImpl
: locate( registry, customImpl.toString() );
try {
return customImplClass.newInstance();
}
catch (Exception e) {
throw new ServiceException( "Could not initialize custom PersisterFactory impl [" + customImplClass.getName() + "]", e );
}
}
private Class<? extends PersisterFactory> locate(ServiceRegistryImplementor registry, String className) {
return registry.getService( ClassLoaderService.class ).classForName( className );
}
}
| 1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/persister/internal/PersisterFactoryInitiator.java | Java | lgpl-2.1 | 2,001 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.gateway;
import java.util.Map;
public interface GatewayEngine {
public static final int LOGLEVEL_INFO = 0;
public static final int LOGLEVEL_DEBUG = 1;
public static final int LOGLEVEL_WARN = 2;
public static final int LOGLEVEL_ERROR = 3;
public static final int LOGLEVEL_FATAL = 4;
public static final int LOGLEVEL_TRACE = 5;
/**
* invoke given method on cfc listener
*
* @param gateway
* @param method method to invoke
* @param data arguments
* @return returns if invocation was successfull
*/
public boolean invokeListener(Gateway gateway, String method, Map<?, ?> data);
/**
* logs message with defined logger for gateways
*
* @param gateway
* @param level
* @param message
*/
public void log(Gateway gateway, int level, String message);
} | lucee/Lucee_old | loader/src/main/java/lucee/runtime/gateway/GatewayEngine.java | Java | lgpl-2.1 | 1,567 |
/*
* Forge Mod Loader
* Copyright (c) 2012-2013 cpw.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v2.1
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* cpw - implementation
*/
package cpw.mods.fml.common;
import java.util.Set;
import cpw.mods.fml.common.versioning.ArtifactVersion;
public class MissingModsException extends RuntimeException
{
private static final long serialVersionUID = 1L;
public Set<ArtifactVersion> missingMods;
public MissingModsException(Set<ArtifactVersion> missingMods)
{
this.missingMods = missingMods;
}
}
| ninjacha/Food_Overhaul | build/unpacked/src/main/java/cpw/mods/fml/common/MissingModsException.java | Java | lgpl-2.1 | 758 |
/*
* Copyright (C) 2007 ETH Zurich
*
* This file is part of Fosstrak (www.fosstrak.org).
*
* Fosstrak is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* Fosstrak 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 Fosstrak; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.fosstrak.reader.rprm.core.mgmt.alarm;
import org.fosstrak.reader.rprm.core.AntennaReadPoint;
import org.fosstrak.reader.rprm.core.ReaderDevice;
/**
* <code>FailedEraseAlarm</code> extends the <code>Alarm</code> class. Its
* receipt signals a tag erase or tag block erase failure. The abstract model's
* <code>AntennaReadPoint.failedEraseAlarmControl</code> data element controls
* the triggering of alarms of this type.
*/
public class FailedEraseAlarm extends Alarm {
/**
* The name of the read point (an <code>AntennaReadPoint</code>) over
* which the erase failure occurred.
*/
private String readPointName;
/**
* The value of <code>AntennaReadPoint.failedEraseCount</code> element
* after the erase failure occurred.
*/
private int failedEraseCount;
/**
* The value of the <code>AntennaReadPoint.noiseLevel</code> element when
* the erase failure occurred.
*/
private int noiseLevel;
/**
* Constructor.
*
* @param name
* The name of the alarm identifying the type of alarm, e.g.,
* "FailedEraseAlarm"
* @param alarmLevel
* The severity level of the alarm
* @param readerDevice
* The reader device
* @param readPoint
* The <code>AntennaReadPoint</code> over which the erase
* failure occured
*/
public FailedEraseAlarm(String name, AlarmLevel alarmLevel,
ReaderDevice readerDevice, AntennaReadPoint readPoint) {
super(name, alarmLevel, readerDevice);
readPointName = readPoint.getName();
failedEraseCount = readPoint.getFailedEraseCount();
noiseLevel = readPoint.getNoiseLevel();
}
/**
* Returns the name of the read point (an <code>AntennaReadPoint</code>)
* over which the erase failure occurred.
*
* @return The name of the <code>ReadPoint</code>
*/
public String getReadPointName() {
return readPointName;
}
/**
* Returns the value of <code>AntennaReadPoint.failedEraseCount</code>
* element after the erase failure occurred.
*
* @return The <code>failedEraseCount</code> for the
* <code>ReadPoint</code>
*/
public int getFailedEraseCount() {
return failedEraseCount;
}
/**
* Returns the value of the <code>AntennaReadPoint.noiseLevel</code>
* element when the erase failure occurred.
*
* @return The <code>noiseLevel</code> for the <code>ReadPoint</code>
*/
public int getNoiseLevel() {
return noiseLevel;
}
}
| tavlima/fosstrak-reader | reader-rprm-core/src/main/java/org/fosstrak/reader/rprm/core/mgmt/alarm/FailedEraseAlarm.java | Java | lgpl-2.1 | 3,308 |
/*
* Created on 13-dic-2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.herac.tuxguitar.player.base;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.herac.tuxguitar.song.managers.TGSongManager;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGChannel;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGMeasure;
import org.herac.tuxguitar.song.models.TGMeasureHeader;
import org.herac.tuxguitar.song.models.TGNote;
import org.herac.tuxguitar.song.models.TGSong;
import org.herac.tuxguitar.song.models.TGString;
import org.herac.tuxguitar.song.models.TGStroke;
import org.herac.tuxguitar.song.models.TGTempo;
import org.herac.tuxguitar.song.models.TGTrack;
import org.herac.tuxguitar.song.models.TGVelocities;
import org.herac.tuxguitar.song.models.TGVoice;
import org.herac.tuxguitar.song.models.effects.TGEffectBend;
import org.herac.tuxguitar.song.models.effects.TGEffectHarmonic;
import org.herac.tuxguitar.song.models.effects.TGEffectTremoloBar;
/**
* @author julian
*
* TODO To change the template for this generated type comment go to Window - Preferences - Java - Code Style - Code Templates
*/
public class MidiSequenceParser {
private static final int DEFAULT_METRONOME_KEY = 37;
private static final int DEFAULT_DURATION_PM = 60;
private static final int DEFAULT_DURATION_DEAD = 30;
private static final int DEFAULT_BEND = 64;
private static final float DEFAULT_BEND_SEMI_TONE = 2.75f;
/**
* flag para agregar los controles por defecto,
* no se recomienda usar este flag si el reproductor asigna estos controles en tiempo real.
*/
public static final int ADD_DEFAULT_CONTROLS = 0x01;
/**
* flag para agregar los valores del mixer (volumen, balance, instrumento),
* no se recomienda usar este flag si el reproductor asigna estos valores en tiempo real.
*/
public static final int ADD_MIXER_MESSAGES = 0x02;
/**
* flag para agregar la pista del metronomo,
* en casos como la exportacion de midi, este flag no sera necesario
*/
public static final int ADD_METRONOME = 0x04;
/**
* tuxguitar usa como primer tick el valor de la constante Duration.QUARTER_TIME
* asignando este flag, es posible crear el primer tick en cero.
*/
public static final int ADD_FIRST_TICK_MOVE = 0x08;
public static final int DEFAULT_PLAY_FLAGS = (ADD_METRONOME);
public static final int DEFAULT_EXPORT_FLAGS = (ADD_FIRST_TICK_MOVE | ADD_DEFAULT_CONTROLS | ADD_MIXER_MESSAGES);
/**
* Song Manager
*/
private TGSong song;
/**
* Song Manager
*/
private TGSongManager songManager;
/**
* flags
*/
private int flags;
/**
* Index of info track
*/
private int infoTrack;
/**
* Index of metronome track
*/
private int metronomeTrack;
private int metronomeChannelId;
private int firstTickMove;
private int tempoPercent;
private int transpose;
private int sHeader;
private int eHeader;
public MidiSequenceParser(TGSong song, TGSongManager songManager, int flags) {
this.song = song;
this.songManager = songManager;
this.flags = flags;
this.tempoPercent = 100;
this.transpose = 0;
this.sHeader = -1;
this.eHeader = -1;
this.firstTickMove = (int)(((flags & ADD_FIRST_TICK_MOVE) != 0)?(-TGDuration.QUARTER_TIME):0);
}
public int getInfoTrack(){
return this.infoTrack;
}
public int getMetronomeTrack(){
return this.metronomeTrack;
}
private long getTick(long tick){
return (tick + this.firstTickMove);
}
public void setSHeader(int header) {
this.sHeader = header;
}
public void setEHeader(int header) {
this.eHeader = header;
}
public void setMetronomeChannelId(int metronomeChannelId) {
this.metronomeChannelId = metronomeChannelId;
}
public void setTempoPercent(int tempoPercent) {
this.tempoPercent = tempoPercent;
}
public void setTranspose(int transpose) {
this.transpose = transpose;
}
private int fix( int value ){
return ( value >= 0 ? value <= 127 ? value : 127 : 0 );
}
/**
* Crea la cancion
*/
public void parse(MidiSequenceHandler sequence) {
this.infoTrack = 0;
this.metronomeTrack = (sequence.getTracks() - 1);
MidiSequenceHelper helper = new MidiSequenceHelper(sequence);
MidiRepeatController controller = new MidiRepeatController(this.song,this.sHeader,this.eHeader);
while(!controller.finished()){
int index = controller.getIndex();
long move = controller.getRepeatMove();
controller.process();
if(controller.shouldPlay()){
helper.addMeasureHelper( new MidiMeasureHelper(index,move) );
}
}
this.addDefaultMessages(helper, this.song);
for (int i = 0; i < this.song.countTracks(); i++) {
TGTrack songTrack = this.song.getTrack(i);
createTrack(helper, songTrack);
}
sequence.notifyFinish();
}
/**
* Crea las pistas de la cancion
*/
private void createTrack(MidiSequenceHelper sh, TGTrack track) {
TGChannel tgChannel = this.songManager.getChannel(this.song, track.getChannelId() );
if( tgChannel != null ){
TGMeasure previous = null;
this.addBend(sh,track.getNumber(),TGDuration.QUARTER_TIME,DEFAULT_BEND, tgChannel.getChannelId(), -1, false);
this.makeChannel(sh, tgChannel, track.getNumber());
int mCount = sh.getMeasureHelpers().size();
for( int mIndex = 0 ; mIndex < mCount ; mIndex++ ){
MidiMeasureHelper mh = sh.getMeasureHelper( mIndex );
TGMeasure measure = track.getMeasure(mh.getIndex());
if(track.getNumber() == 1){
addTimeSignature(sh,measure, previous, mh.getMove());
addTempo(sh,measure, previous, mh.getMove());
addMetronome(sh,measure.getHeader(), mh.getMove() );
}
//agrego los pulsos
makeBeats( sh, tgChannel, track, measure, mIndex, mh.getMove() );
previous = measure;
}
}
}
private void makeBeats(MidiSequenceHelper sh, TGChannel channel, TGTrack track, TGMeasure measure, int mIndex, long startMove) {
int[] stroke = new int[track.stringCount()];
TGBeat previous = null;
for (int bIndex = 0; bIndex < measure.countBeats(); bIndex++) {
TGBeat beat = measure.getBeat(bIndex);
makeNotes( sh, channel, track, beat, measure.getTempo(), mIndex, bIndex, startMove, getStroke(beat, previous, stroke) );
previous = beat;
}
}
/**
* Crea las notas del compas
*/
private void makeNotes( MidiSequenceHelper sh, TGChannel tgChannel, TGTrack track, TGBeat beat, TGTempo tempo, int mIndex,int bIndex, long startMove, int[] stroke) {
for( int vIndex = 0; vIndex < beat.countVoices(); vIndex ++ ){
TGVoice voice = beat.getVoice(vIndex);
MidiTickHelper th = checkTripletFeel(voice,bIndex);
for (int noteIdx = 0; noteIdx < voice.countNotes(); noteIdx++) {
TGNote note = voice.getNote(noteIdx);
if (!note.isTiedNote()) {
int key = (this.transpose + track.getOffset() + note.getValue() + ((TGString)track.getStrings().get(note.getString() - 1)).getValue());
long start = applyStrokeStart(note, (th.getStart() + startMove) , stroke);
long duration = applyStrokeDuration(note, getRealNoteDuration(sh, track, note, tempo, th.getDuration(), mIndex,bIndex), stroke);
int velocity = getRealVelocity(sh, note, track, tgChannel, mIndex, bIndex);
int channel = tgChannel.getChannelId();
int midiVoice = note.getString();
boolean bendMode = false;
boolean percussionChannel = tgChannel.isPercussionChannel();
//---Fade In---
if(note.getEffect().isFadeIn()){
makeFadeIn(sh,track.getNumber(), start, duration, tgChannel.getVolume(), channel);
}
//---Grace---
if(note.getEffect().isGrace() && !percussionChannel ){
bendMode = true;
int graceKey = track.getOffset() + note.getEffect().getGrace().getFret() + ((TGString)track.getStrings().get(note.getString() - 1)).getValue();
int graceLength = note.getEffect().getGrace().getDurationTime();
int graceVelocity = note.getEffect().getGrace().getDynamic();
long graceDuration = ((note.getEffect().getGrace().isDead())?applyStaticDuration(tempo, DEFAULT_DURATION_DEAD, graceLength):graceLength);
if(note.getEffect().getGrace().isOnBeat() || (start - graceLength) < TGDuration.QUARTER_TIME){
start += graceLength;
duration -= graceLength;
}
makeNote(sh,track.getNumber(), graceKey,start - graceLength,graceDuration,graceVelocity,channel,midiVoice, bendMode);
}
//---Trill---
if(note.getEffect().isTrill() && !percussionChannel ){
int trillKey = track.getOffset() + note.getEffect().getTrill().getFret() + ((TGString)track.getStrings().get(note.getString() - 1)).getValue();
long trillLength = note.getEffect().getTrill().getDuration().getTime();
boolean realKey = true;
long tick = start;
while(true){
if(tick + 10 >= (start + duration)){
break ;
}else if( (tick + trillLength) >= (start + duration)){
trillLength = (((start + duration) - tick) - 1);
}
makeNote(sh,track.getNumber(),((realKey)?key:trillKey),tick,trillLength,velocity,channel,midiVoice,bendMode);
realKey = (!realKey);
tick += trillLength;
}
continue;
}
//---Tremolo Picking---
if(note.getEffect().isTremoloPicking()){
long tpLength = note.getEffect().getTremoloPicking().getDuration().getTime();
long tick = start;
while(true){
if(tick + 10 >= (start + duration)){
break ;
}else if( (tick + tpLength) >= (start + duration)){
tpLength = (((start + duration) - tick) - 1);
}
makeNote(sh,track.getNumber(),key,tick,tpLength,velocity,channel,midiVoice,bendMode);
tick += tpLength;
}
continue;
}
//---Bend---
if( note.getEffect().isBend() && !percussionChannel ){
bendMode = true;
makeBend(sh,track.getNumber(),start,duration,note.getEffect().getBend(),channel,midiVoice,bendMode);
}
//---TremoloBar---
else if( note.getEffect().isTremoloBar() && !percussionChannel ){
bendMode = true;
makeTremoloBar(sh,track.getNumber(),start,duration,note.getEffect().getTremoloBar(),channel,midiVoice,bendMode);
}
//---Slide---
else if( note.getEffect().isSlide() && !percussionChannel){
bendMode = true;
makeSlide(sh, note, track, mIndex, bIndex, startMove, channel,midiVoice,bendMode);
}
//---Vibrato---
else if( note.getEffect().isVibrato() && !percussionChannel){
bendMode = true;
makeVibrato(sh,track.getNumber(),start,duration,channel,midiVoice,bendMode);
}
//---Harmonic---
if( note.getEffect().isHarmonic() && !percussionChannel){
int orig = key;
//Natural
if(note.getEffect().getHarmonic().isNatural()){
for(int i = 0;i < TGEffectHarmonic.NATURAL_FREQUENCIES.length;i ++){
if((note.getValue() % 12) == (TGEffectHarmonic.NATURAL_FREQUENCIES[i][0] % 12) ){
key = ((orig + TGEffectHarmonic.NATURAL_FREQUENCIES[i][1]) - note.getValue());
break;
}
}
}
//Artifical/Tapped/Pinch/Semi
else{
if( note.getEffect().getHarmonic().isSemi() && !percussionChannel ){
makeNote(sh,track.getNumber(),Math.min(127,orig), start, duration,Math.max(TGVelocities.MIN_VELOCITY,velocity - (TGVelocities.VELOCITY_INCREMENT * 3)),channel,midiVoice,bendMode);
}
key = (orig + TGEffectHarmonic.NATURAL_FREQUENCIES[note.getEffect().getHarmonic().getData()][1]);
}
if( (key - 12) > 0 ){
int hVelocity = Math.max(TGVelocities.MIN_VELOCITY,velocity - (TGVelocities.VELOCITY_INCREMENT * 4));
makeNote(sh,track.getNumber(),(key - 12), start, duration,hVelocity,channel,midiVoice,bendMode);
}
}
//---Normal Note---
makeNote(sh,track.getNumber(), Math.min(127,key), start, duration, velocity,channel,midiVoice,bendMode);
}
}
}
}
/**
* Crea una nota en la posicion start
*/
private void makeNote(MidiSequenceHelper sh,int track, int key, long start, long duration, int velocity, int channel, int midiVoice, boolean bendMode) {
sh.getSequence().addNoteOn(getTick(start),track,channel,fix(key),fix(velocity), midiVoice, bendMode);
if( duration > 0 ){
sh.getSequence().addNoteOff(getTick(start + duration),track,channel,fix(key),fix(velocity), midiVoice, bendMode);
}
}
private void makeChannel(MidiSequenceHelper sh,TGChannel channel,int track) {
if((this.flags & ADD_MIXER_MESSAGES) != 0){
int channelId = channel.getChannelId();
long tick = getTick(TGDuration.QUARTER_TIME);
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.VOLUME,fix(channel.getVolume()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.BALANCE,fix(channel.getBalance()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.CHORUS,fix(channel.getChorus()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.REVERB,fix(channel.getReverb()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.PHASER,fix(channel.getPhaser()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.TREMOLO,fix(channel.getTremolo()));
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.EXPRESSION, 127);
if(!channel.isPercussionChannel()){
sh.getSequence().addControlChange(tick,track,channelId,MidiControllers.BANK_SELECT, fix(channel.getBank()));
}
sh.getSequence().addProgramChange(tick,track,channelId,fix(channel.getProgram()));
}
}
/**
* Agrega un Time Signature si es distinto al anterior
*/
private void addTimeSignature(MidiSequenceHelper sh,TGMeasure currMeasure, TGMeasure prevMeasure,long startMove){
boolean addTimeSignature = false;
if (prevMeasure == null) {
addTimeSignature = true;
} else {
int currNumerator = currMeasure.getTimeSignature().getNumerator();
int currValue = currMeasure.getTimeSignature().getDenominator().getValue();
int prevNumerator = prevMeasure.getTimeSignature().getNumerator();
int prevValue = prevMeasure.getTimeSignature().getDenominator().getValue();
if (currNumerator != prevNumerator || currValue != prevValue) {
addTimeSignature = true;
}
}
if (addTimeSignature) {
sh.getSequence().addTimeSignature(getTick(currMeasure.getStart() + startMove), getInfoTrack(), currMeasure.getTimeSignature());
}
}
/**
* Agrega un Tempo si es distinto al anterior
*/
private void addTempo(MidiSequenceHelper sh,TGMeasure currMeasure, TGMeasure prevMeasure,long startMove){
boolean addTempo = false;
if (prevMeasure == null) {
addTempo = true;
} else {
if (currMeasure.getTempo().getInUSQ() != prevMeasure.getTempo().getInUSQ()) {
addTempo = true;
}
}
if (addTempo) {
int usq = (int)(currMeasure.getTempo().getInUSQ() * 100.00 / this.tempoPercent );
sh.getSequence().addTempoInUSQ(getTick(currMeasure.getStart() + startMove), getInfoTrack(), usq);
}
}
/**
* Retorna la Duracion real de una nota, verificando si tiene otras ligadas
*/
private long getRealNoteDuration(MidiSequenceHelper sh, TGTrack track, TGNote note, TGTempo tempo, long duration,int mIndex, int bIndex) {
boolean letRing = (note.getEffect().isLetRing());
boolean letRingBeatChanged = false;
long lastEnd = (note.getVoice().getBeat().getStart() + note.getVoice().getDuration().getTime() + sh.getMeasureHelper(mIndex).getMove());
long realDuration = duration;
int nextBIndex = (bIndex + 1);
int mCount = sh.getMeasureHelpers().size();
for (int m = mIndex; m < mCount; m++) {
MidiMeasureHelper mh = sh.getMeasureHelper( m );
TGMeasure measure = track.getMeasure( mh.getIndex() );
int beatCount = measure.countBeats();
for (int b = nextBIndex; b < beatCount; b++) {
TGBeat beat = measure.getBeat(b);
TGVoice voice = beat.getVoice(note.getVoice().getIndex());
if(!voice.isEmpty()){
if(voice.isRestVoice()){
return applyDurationEffects(note, tempo, realDuration);
}
int noteCount = voice.countNotes();
for (int n = 0; n < noteCount; n++) {
TGNote nextNote = voice.getNote( n );
if (!nextNote.equals(note) || mIndex != m ) {
if (nextNote.getString() == note.getString()) {
if (nextNote.isTiedNote()) {
realDuration += (mh.getMove() + beat.getStart() - lastEnd) + (nextNote.getVoice().getDuration().getTime());
lastEnd = (mh.getMove() + beat.getStart() + voice.getDuration().getTime());
letRing = (nextNote.getEffect().isLetRing());
letRingBeatChanged = true;
} else {
return applyDurationEffects(note, tempo, realDuration);
}
}
}
}
if(letRing && !letRingBeatChanged){
realDuration += ( voice.getDuration().getTime() );
}
letRingBeatChanged = false;
}
}
nextBIndex = 0;
}
return applyDurationEffects(note, tempo, realDuration);
}
private long applyDurationEffects(TGNote note, TGTempo tempo, long duration){
//dead note
if(note.getEffect().isDeadNote()){
return applyStaticDuration(tempo, DEFAULT_DURATION_DEAD, duration);
}
//palm mute
if(note.getEffect().isPalmMute()){
return applyStaticDuration(tempo, DEFAULT_DURATION_PM, duration);
}
//staccato
if(note.getEffect().isStaccato()){
return (long)(duration * 50.00 / 100.00);
}
return duration;
}
private long applyStaticDuration(TGTempo tempo, long duration, long maximum ){
long value = ( tempo.getValue() * duration / 60 );
return (value < maximum ? value : maximum );
}
private int getRealVelocity(MidiSequenceHelper sh, TGNote note, TGTrack tgTrack, TGChannel tgChannel, int mIndex,int bIndex){
int velocity = note.getVelocity();
//Check for Hammer effect
if(!tgChannel.isPercussionChannel()){
MidiNoteHelper previousNote = getPreviousNote(sh, note,tgTrack,mIndex,bIndex,false);
if(previousNote != null && previousNote.getNote().getEffect().isHammer()){
velocity = Math.max(TGVelocities.MIN_VELOCITY,(velocity - 25));
}
}
//Check for GhostNote effect
if(note.getEffect().isGhostNote()){
velocity = Math.max(TGVelocities.MIN_VELOCITY,(velocity - TGVelocities.VELOCITY_INCREMENT));
}else if(note.getEffect().isAccentuatedNote()){
velocity = Math.max(TGVelocities.MIN_VELOCITY,(velocity + TGVelocities.VELOCITY_INCREMENT));
}else if(note.getEffect().isHeavyAccentuatedNote()){
velocity = Math.max(TGVelocities.MIN_VELOCITY,(velocity + (TGVelocities.VELOCITY_INCREMENT * 2)));
}
return ((velocity > 127)?127:velocity);
}
public void addMetronome(MidiSequenceHelper sh,TGMeasureHeader header, long startMove){
if( (this.flags & ADD_METRONOME) != 0) {
if( this.metronomeChannelId >= 0 ){
long start = (startMove + header.getStart());
long length = header.getTimeSignature().getDenominator().getTime();
for(int i = 1; i <= header.getTimeSignature().getNumerator();i ++){
makeNote(sh,getMetronomeTrack(),DEFAULT_METRONOME_KEY,start,length,TGVelocities.DEFAULT,this.metronomeChannelId,-1,false);
start += length;
}
}
}
}
public void addDefaultMessages(MidiSequenceHelper sh, TGSong tgSong) {
if( (this.flags & ADD_DEFAULT_CONTROLS) != 0) {
Iterator it = tgSong.getChannels();
while ( it.hasNext() ){
int channelId = ((TGChannel) it.next()).getChannelId();
sh.getSequence().addControlChange(getTick(TGDuration.QUARTER_TIME),getInfoTrack(),channelId,MidiControllers.RPN_MSB,0);
sh.getSequence().addControlChange(getTick(TGDuration.QUARTER_TIME),getInfoTrack(),channelId,MidiControllers.RPN_LSB,0);
sh.getSequence().addControlChange(getTick(TGDuration.QUARTER_TIME),getInfoTrack(),channelId,MidiControllers.DATA_ENTRY_MSB,12);
sh.getSequence().addControlChange(getTick(TGDuration.QUARTER_TIME),getInfoTrack(),channelId,MidiControllers.DATA_ENTRY_LSB, 0);
}
}
}
private void addBend(MidiSequenceHelper sh,int track, long tick,int bend, int channel, int midiVoice, boolean bendMode) {
sh.getSequence().addPitchBend(getTick(tick),track,channel,fix(bend), midiVoice, bendMode);
}
public void makeVibrato(MidiSequenceHelper sh,int track,long start, long duration,int channel, int midiVoice, boolean bendMode){
long nextStart = start;
long end = nextStart + duration;
while(nextStart < end){
nextStart = ((nextStart + 160 > end)?end:nextStart + 160);
addBend(sh, track, nextStart, DEFAULT_BEND, channel, midiVoice, bendMode);
nextStart = ((nextStart + 160 > end)?end:nextStart + 160);
addBend(sh, track, nextStart, DEFAULT_BEND + (int)(DEFAULT_BEND_SEMI_TONE / 2.0f), channel, midiVoice, bendMode);
}
addBend(sh, track, nextStart, DEFAULT_BEND, channel, midiVoice, bendMode);
}
public void makeBend(MidiSequenceHelper sh,int track,long start, long duration, TGEffectBend bend, int channel, int midiVoice, boolean bendMode){
List points = bend.getPoints();
for(int i=0;i<points.size();i++){
TGEffectBend.BendPoint point = (TGEffectBend.BendPoint)points.get(i);
long bendStart = start + point.getTime(duration);
int value = DEFAULT_BEND + (int)(point.getValue() * DEFAULT_BEND_SEMI_TONE / TGEffectBend.SEMITONE_LENGTH);
value = ((value <= 127)?value:127);
value = ((value >= 0)?value:0);
addBend(sh, track, bendStart, value, channel, midiVoice, bendMode);
if(points.size() > i + 1){
TGEffectBend.BendPoint nextPoint = (TGEffectBend.BendPoint)points.get(i + 1);
int nextValue = DEFAULT_BEND + (int)(nextPoint.getValue() * DEFAULT_BEND_SEMI_TONE / TGEffectBend.SEMITONE_LENGTH);
long nextBendStart = start + nextPoint.getTime(duration);
if(nextValue != value){
double width = ( (nextBendStart - bendStart) / Math.abs( (nextValue - value) ) );
//ascendente
if(value < nextValue){
while(value < nextValue){
value ++;
bendStart +=width;
addBend(sh, track, bendStart,((value <= 127) ? value : 127), channel, midiVoice, bendMode);
}
//descendente
}else if(value > nextValue){
while(value > nextValue){
value --;
bendStart +=width;
addBend(sh, track, bendStart,((value >= 0) ? value : 0), channel, midiVoice, bendMode);
}
}
}
}
}
addBend(sh, track, start + duration, DEFAULT_BEND, channel, midiVoice, bendMode);
}
public void makeTremoloBar(MidiSequenceHelper sh,int track,long start, long duration, TGEffectTremoloBar effect, int channel, int midiVoice, boolean bendMode){
List points = effect.getPoints();
for(int i=0;i<points.size();i++){
TGEffectTremoloBar.TremoloBarPoint point = (TGEffectTremoloBar.TremoloBarPoint)points.get(i);
long pointStart = start + point.getTime(duration);
int value = DEFAULT_BEND + (int)(point.getValue() * (DEFAULT_BEND_SEMI_TONE * 2) );
value = ((value <= 127)?value:127);
value = ((value >= 0)?value:0);
addBend(sh, track, pointStart, value, channel, midiVoice, bendMode);
if(points.size() > i + 1){
TGEffectTremoloBar.TremoloBarPoint nextPoint = (TGEffectTremoloBar.TremoloBarPoint)points.get(i + 1);
int nextValue = DEFAULT_BEND + (int)(nextPoint.getValue() * (DEFAULT_BEND_SEMI_TONE * 2));
long nextPointStart = start + nextPoint.getTime(duration);
if(nextValue != value){
double width = ( (nextPointStart - pointStart) / Math.abs( (nextValue - value) ) );
//ascendente
if(value < nextValue){
while(value < nextValue){
value ++;
pointStart +=width;
addBend(sh, track, pointStart,((value <= 127) ? value : 127), channel, midiVoice, bendMode);
}
//descendente
}else if(value > nextValue){
while(value > nextValue){
value --;
pointStart += width;
addBend(sh, track, pointStart,((value >= 0) ? value : 0), channel, midiVoice, bendMode);
}
}
}
}
}
addBend(sh, track, start + duration, DEFAULT_BEND, channel, midiVoice, bendMode);
}
private void makeSlide(MidiSequenceHelper sh, TGNote note,TGTrack track, int mIndex, int bIndex, long startMove,int channel,int midiVoice,boolean bendMode){
MidiNoteHelper nextNote = this.getNextNote(sh, note, track, mIndex, bIndex, true);
if( nextNote != null ){
int value1 = note.getValue();
int value2 = nextNote.getNote().getValue();
long tick1 = note.getVoice().getBeat().getStart() + startMove;
long tick2 = nextNote.getNote().getVoice().getBeat().getStart() + nextNote.getMeasure().getMove();
// Make the Slide
this.makeSlide(sh, track.getNumber(), tick1, value1, tick2, value2, channel, midiVoice, bendMode);
// Normalize the Bend
this.addBend(sh,track.getNumber(), tick2 ,DEFAULT_BEND, channel, midiVoice, bendMode);
}
}
public void makeSlide(MidiSequenceHelper sh,int track,long tick1,int value1,long tick2,int value2,int channel, int midiVoice, boolean bendMode){
long distance = (value2 - value1);
long length = (tick2 - tick1);
int points = (int)(length / (TGDuration.QUARTER_TIME / 8));
for(int i = 1;i <= points; i ++){
float tone = ((((length / points) * (float)i) * distance) / length);
int bend = (DEFAULT_BEND + (int)(tone * (DEFAULT_BEND_SEMI_TONE * 2)));
addBend(sh, track, tick1 + ( (length / points) * i), bend, channel, midiVoice, bendMode);
}
}
private void makeFadeIn(MidiSequenceHelper sh,int track,long start,long duration,int volume3,int channel){
int expression = 31;
int expressionIncrement = 1;
long tick = start;
long tickIncrement = (duration / ((127 - expression) / expressionIncrement));
while( tick < (start + duration) && expression < 127 ) {
sh.getSequence().addControlChange(getTick(tick),track,channel,MidiControllers.EXPRESSION, fix(expression));
tick += tickIncrement;
expression += expressionIncrement;
}
sh.getSequence().addControlChange(getTick((start + duration)),track,channel, MidiControllers.EXPRESSION, 127);
}
private int[] getStroke(TGBeat beat, TGBeat previous, int[] stroke){
int direction = beat.getStroke().getDirection();
if( previous == null || !(direction == TGStroke.STROKE_NONE && previous.getStroke().getDirection() == TGStroke.STROKE_NONE)){
if( direction == TGStroke.STROKE_NONE ){
for( int i = 0 ; i < stroke.length ; i ++ ){
stroke[ i ] = 0;
}
}else{
int stringUseds = 0;
int stringCount = 0;
for( int vIndex = 0; vIndex < beat.countVoices(); vIndex ++ ){
TGVoice voice = beat.getVoice(vIndex);
for (int nIndex = 0; nIndex < voice.countNotes(); nIndex++) {
TGNote note = voice.getNote(nIndex);
if( !note.isTiedNote() ){
stringUseds |= 0x01 << ( note.getString() - 1 );
stringCount ++;
}
}
}
if( stringCount > 0 ){
int strokeMove = 0;
int strokeIncrement = beat.getStroke().getIncrementTime(beat);
for( int i = 0 ; i < stroke.length ; i ++ ){
int index = ( direction == TGStroke.STROKE_DOWN ? (stroke.length - 1) - i : i );
if( (stringUseds & ( 0x01 << index ) ) != 0 ){
stroke[ index ] = strokeMove;
strokeMove += strokeIncrement;
}
}
}
}
}
return stroke;
}
private long applyStrokeStart( TGNote note, long start , int[] stroke){
return (start + stroke[ note.getString() - 1 ]);
}
private long applyStrokeDuration( TGNote note, long duration , int[] stroke){
return (duration > stroke[note.getString() - 1] ? (duration - stroke[ note.getString() - 1 ]) : duration );
}
private MidiTickHelper checkTripletFeel(TGVoice voice,int bIndex){
long bStart = voice.getBeat().getStart();
long bDuration = voice.getDuration().getTime();
if(voice.getBeat().getMeasure().getTripletFeel() == TGMeasureHeader.TRIPLET_FEEL_EIGHTH){
if(voice.getDuration().isEqual(newDuration(TGDuration.EIGHTH))){
//first time
if( (bStart % TGDuration.QUARTER_TIME) == 0){
TGVoice v = getNextBeat(voice,bIndex);
if(v == null || ( v.getBeat().getStart() > (bStart + voice.getDuration().getTime()) || v.getDuration().isEqual(newDuration(TGDuration.EIGHTH))) ){
TGDuration duration = newDuration(TGDuration.EIGHTH);
duration.getDivision().setEnters(3);
duration.getDivision().setTimes(2);
bDuration = (duration.getTime() * 2);
}
}
//second time
else if( (bStart % (TGDuration.QUARTER_TIME / 2)) == 0){
TGVoice v = getPreviousBeat(voice,bIndex);
if(v == null || ( v.getBeat().getStart() < (bStart - voice.getDuration().getTime()) || v.getDuration().isEqual(newDuration(TGDuration.EIGHTH)) )){
TGDuration duration = newDuration(TGDuration.EIGHTH);
duration.getDivision().setEnters(3);
duration.getDivision().setTimes(2);
bStart = ( (bStart - voice.getDuration().getTime()) + (duration.getTime() * 2));
bDuration = duration.getTime();
}
}
}
}else if(voice.getBeat().getMeasure().getTripletFeel() == TGMeasureHeader.TRIPLET_FEEL_SIXTEENTH){
if(voice.getDuration().isEqual(newDuration(TGDuration.SIXTEENTH))){
//first time
if( (bStart % (TGDuration.QUARTER_TIME / 2)) == 0){
TGVoice v = getNextBeat(voice,bIndex);
if(v == null || ( v.getBeat().getStart() > (bStart + voice.getDuration().getTime()) || v.getDuration().isEqual(newDuration(TGDuration.SIXTEENTH))) ){
TGDuration duration = newDuration(TGDuration.SIXTEENTH);
duration.getDivision().setEnters(3);
duration.getDivision().setTimes(2);
bDuration = (duration.getTime() * 2);
}
}
//second time
else if( (bStart % (TGDuration.QUARTER_TIME / 4)) == 0){
TGVoice v = getPreviousBeat(voice,bIndex);
if(v == null || ( v.getBeat().getStart() < (bStart - voice.getDuration().getTime()) || v.getDuration().isEqual(newDuration(TGDuration.SIXTEENTH)) )){
TGDuration duration = newDuration(TGDuration.SIXTEENTH);
duration.getDivision().setEnters(3);
duration.getDivision().setTimes(2);
bStart = ( (bStart - voice.getDuration().getTime()) + (duration.getTime() * 2));
bDuration = duration.getTime();
}
}
}
}
return new MidiTickHelper(bStart, bDuration);
}
private TGDuration newDuration(int value){
TGDuration duration = this.songManager.getFactory().newDuration();
duration.setValue(value);
return duration;
}
private TGVoice getPreviousBeat(TGVoice beat,int bIndex){
TGVoice previous = null;
for (int b = bIndex - 1; b >= 0; b--) {
TGBeat current = beat.getBeat().getMeasure().getBeat( b );
if(current.getStart() < beat.getBeat().getStart() && !current.getVoice(beat.getIndex()).isEmpty()){
if(previous == null || current.getStart() > previous.getBeat().getStart()){
previous = current.getVoice(beat.getIndex());
}
}
}
return previous;
}
private TGVoice getNextBeat(TGVoice beat,int bIndex){
TGVoice next = null;
for (int b = bIndex + 1; b < beat.getBeat().getMeasure().countBeats(); b++) {
TGBeat current = beat.getBeat().getMeasure().getBeat( b );
if(current.getStart() > beat.getBeat().getStart() && !current.getVoice(beat.getIndex()).isEmpty()){
if(next == null || current.getStart() < next.getBeat().getStart()){
next = current.getVoice(beat.getIndex());
}
}
}
return next;
}
private MidiNoteHelper getNextNote(MidiSequenceHelper sh, TGNote note,TGTrack track, int mIndex, int bIndex, boolean breakAtRest){
int nextBIndex = (bIndex + 1);
int measureCount = sh.getMeasureHelpers().size();
for (int m = mIndex; m < measureCount; m++) {
MidiMeasureHelper mh = sh.getMeasureHelper( m );
TGMeasure measure = track.getMeasure( mh.getIndex() );
int beatCount = measure.countBeats();
for (int b = nextBIndex; b < beatCount; b++) {
TGBeat beat = measure.getBeat( b );
TGVoice voice = beat.getVoice( note.getVoice().getIndex() );
if( !voice.isEmpty() ){
int noteCount = voice.countNotes();
for (int n = 0; n < noteCount; n++) {
TGNote nextNote = voice.getNote( n );
if(nextNote.getString() == note.getString()){
return new MidiNoteHelper(mh,nextNote);
}
}
if( breakAtRest ){
return null;
}
}
}
nextBIndex = 0;
}
return null;
}
private MidiNoteHelper getPreviousNote(MidiSequenceHelper pHelper, TGNote note,TGTrack track, int mIndex, int bIndex, boolean breakAtRest){
int nextBIndex = bIndex;
for (int m = mIndex; m >= 0; m--) {
MidiMeasureHelper mh = pHelper.getMeasureHelper( m );
TGMeasure measure = track.getMeasure( mh.getIndex() );
if( this.sHeader == -1 || this.sHeader <= measure.getNumber() ){
nextBIndex = (nextBIndex < 0 ? measure.countBeats() : nextBIndex);
for (int b = (nextBIndex - 1); b >= 0; b--) {
TGBeat beat = measure.getBeat( b );
TGVoice voice = beat.getVoice( note.getVoice().getIndex() );
if( !voice.isEmpty() ){
int noteCount = voice.countNotes();
for (int n = 0; n < noteCount; n ++) {
TGNote current = voice.getNote( n );
if(current.getString() == note.getString()){
return new MidiNoteHelper(mh,current);
}
}
if( breakAtRest ){
return null;
}
}
}
}
nextBIndex = -1;
}
return null;
}
private class MidiTickHelper{
private long start;
private long duration;
public MidiTickHelper(long start,long duration){
this.start = start;
this.duration = duration;
}
public long getDuration() {
return this.duration;
}
public long getStart() {
return this.start;
}
}
private class MidiNoteHelper {
private MidiMeasureHelper measure;
private TGNote note;
public MidiNoteHelper(MidiMeasureHelper measure, TGNote note){
this.measure = measure;
this.note = note;
}
public MidiMeasureHelper getMeasure() {
return this.measure;
}
public TGNote getNote() {
return this.note;
}
}
private class MidiMeasureHelper {
private int index;
private long move;
public MidiMeasureHelper(int index,long move){
this.index = index;
this.move = move;
}
public int getIndex() {
return this.index;
}
public long getMove() {
return this.move;
}
}
private class MidiSequenceHelper {
private List measureHeaderHelpers;
private MidiSequenceHandler sequence;
public MidiSequenceHelper(MidiSequenceHandler sequence){
this.sequence = sequence;
this.measureHeaderHelpers = new ArrayList();
}
public MidiSequenceHandler getSequence(){
return this.sequence;
}
public void addMeasureHelper( MidiMeasureHelper helper ){
this.measureHeaderHelpers.add( helper );
}
public List getMeasureHelpers(){
return this.measureHeaderHelpers;
}
public MidiMeasureHelper getMeasureHelper( int index ){
return (MidiMeasureHelper)this.measureHeaderHelpers.get( index );
}
}
} | m-wichmann/tg2ly | src/org/herac/tuxguitar/player/base/MidiSequenceParser.java | Java | lgpl-2.1 | 34,940 |
/*******************************************************************************
* Copyright (c) 2001-2005 Sasa Markovic and Ciaran Treanor.
* Copyright (c) 2011 The OpenNMS Group, Inc.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*******************************************************************************/
package org.jrobin.graph;
import java.awt.*;
class Rule extends PlotElement {
final LegendText legend;
final float width;
Rule(Paint color, LegendText legend, float width) {
super(color);
this.legend = legend;
this.width = width;
}
}
| roskens/jrobin | src/main/java/org/jrobin/graph/Rule.java | Java | lgpl-2.1 | 1,261 |
/*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003-2005, University of Maryland
*
* 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 edu.umd.cs.findbugs.detect;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.ListIterator;
import java.util.Set;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.LineNumber;
import org.apache.bcel.classfile.LineNumberTable;
import org.apache.bcel.classfile.Utility;
import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.Token;
import edu.umd.cs.findbugs.Tokenizer;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.Hierarchy;
import edu.umd.cs.findbugs.ba.SourceFile;
import edu.umd.cs.findbugs.ba.SourceFinder;
import edu.umd.cs.findbugs.charsets.UTF8;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
public class DroppedException extends PreorderVisitor implements Detector {
private static final boolean DEBUG = SystemProperties.getBoolean("de.debug");
private static final boolean LOOK_IN_SOURCE_TO_FIND_COMMENTED_CATCH_BLOCKS = SystemProperties
.getBoolean("findbugs.de.comment");
Set<String> causes = new HashSet<>();
Set<String> checkedCauses = new HashSet<>();
private final BugReporter bugReporter;
private final BugAccumulator bugAccumulator;
private ClassContext classContext;
public DroppedException(BugReporter bugReporter) {
this.bugReporter = bugReporter;
this.bugAccumulator = new BugAccumulator(bugReporter);
if (DEBUG) {
System.out.println("Dropped Exception debugging turned on");
}
}
@Override
public void visitClassContext(ClassContext classContext) {
this.classContext = classContext;
classContext.getJavaClass().accept(this);
bugAccumulator.reportAccumulatedBugs();
}
@Override
public void report() {
}
boolean isChecked(String c) {
if (!causes.add(c)) {
return checkedCauses.contains(c);
}
try {
if (Hierarchy.isSubtype(c, "java.lang.Exception") && !Hierarchy.isSubtype(c, "java.lang.RuntimeException")) {
checkedCauses.add(c);
return true;
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
return false;
}
private int getUnsignedShort(byte[] a, int i) {
return asUnsignedByte(a[i]) << 8 | asUnsignedByte(a[i + 1]);
}
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "UC_USELESS_CONDITION", justification = "To be fixed in SpotBugs 4.0.0, see https://github.com/spotbugs/spotbugs/issues/84")
@Override
public void visit(Code obj) {
CodeException[] exp = obj.getExceptionTable();
LineNumberTable lineNumbers = obj.getLineNumberTable();
if (exp == null) {
return;
}
byte[] code = obj.getCode();
for (CodeException aExp : exp) {
int handled = aExp.getHandlerPC();
int start = aExp.getStartPC();
int end = aExp.getEndPC();
int cause = aExp.getCatchType();
boolean exitInTryBlock = false;
if (DEBUG) {
System.out.println("start = " + start + ", end = " + end + ", codeLength = " + code.length + ", handled = "
+ handled);
}
for (int j = start; j <= end && j < code.length;) {
int opcode = asUnsignedByte(code[j]);
if (Const.getNoOfOperands(opcode) < 0) {
exitInTryBlock = true;
break;
}
j += 1 + Const.getNoOfOperands(opcode);
if (opcode >= Const.IRETURN && opcode <= Const.RETURN || opcode >= Const.IFEQ && opcode <= Const.GOTO && (opcode != Const.GOTO || j < end)) {
exitInTryBlock = true;
if (DEBUG) {
System.out.println("\texit: " + opcode + " in " + getFullyQualifiedMethodName());
}
break;
}
}
if (exitInTryBlock) {
if (DEBUG) {
System.out.println("Exit in try block");
}
continue;
}
if (handled < 5) {
continue;
}
@DottedClassName String causeName;
if (cause == 0) {
causeName = "java.lang.Throwable";
} else {
causeName = Utility.compactClassName(getConstantPool().getConstantString(cause, Const.CONSTANT_Class), false);
if (!isChecked(causeName)) {
continue;
}
}
int jumpAtEnd = 0;
if (end < code.length && asUnsignedByte(code[end]) == Const.GOTO) {
jumpAtEnd = getUnsignedShort(code, end + 1);
if (jumpAtEnd < handled) {
jumpAtEnd = 0;
}
}
int opcode = asUnsignedByte(code[handled]);
int afterHandler = 0;
if (DEBUG) {
System.out.println("DE:\topcode is " + Const.getOpcodeName(opcode) + ", " + asUnsignedByte(code[handled + 1]));
}
boolean drops = false;
boolean startsWithASTORE03 = opcode >= Const.ASTORE_0 && opcode <= Const.ASTORE_3;
if (startsWithASTORE03 && asUnsignedByte(code[handled + 1]) == Const.RETURN) {
if (DEBUG) {
System.out.println("Drop 1");
}
drops = true;
afterHandler = handled + 1;
}
if (handled + 2 < code.length && opcode == Const.ASTORE && asUnsignedByte(code[handled + 2]) == Const.RETURN) {
drops = true;
afterHandler = handled + 2;
if (DEBUG) {
System.out.println("Drop 2");
}
}
if (handled + 3 < code.length && !exitInTryBlock) {
if (DEBUG) {
System.out.println("DE: checking for jumps");
}
if (startsWithASTORE03 && asUnsignedByte(code[handled - 3]) == Const.GOTO) {
int offsetBefore = getUnsignedShort(code, handled - 2);
if (DEBUG) {
System.out.println("offset before = " + offsetBefore);
}
if (offsetBefore == 4) {
drops = true;
afterHandler = handled + 1;
if (DEBUG) {
System.out.println("Drop 3");
}
}
}
if (opcode == Const.ASTORE && asUnsignedByte(code[handled - 3]) == Const.GOTO) {
int offsetBefore = getUnsignedShort(code, handled - 2);
if (offsetBefore == 5) {
drops = true;
afterHandler = handled + 2;
if (DEBUG) {
System.out.println("Drop 4");
}
}
}
if (startsWithASTORE03 && asUnsignedByte(code[handled + 1]) == Const.GOTO && asUnsignedByte(code[handled - 3]) == Const.GOTO) {
int offsetBefore = getUnsignedShort(code, handled - 2);
int offsetAfter = getUnsignedShort(code, handled + 2);
if (offsetAfter > 0 && offsetAfter + 4 == offsetBefore) {
drops = true;
afterHandler = handled + 4;
if (DEBUG) {
System.out.println("Drop 5");
}
}
}
if (opcode == Const.ASTORE && asUnsignedByte(code[handled + 2]) == Const.GOTO && asUnsignedByte(code[handled - 3]) == Const.GOTO) {
int offsetBefore = getUnsignedShort(code, handled - 2);
int offsetAfter = getUnsignedShort(code, handled + 3);
if (offsetAfter > 0 && offsetAfter + 5 == offsetBefore) {
drops = true;
afterHandler = handled + 5;
if (DEBUG) {
System.out.println("Drop 6");
}
}
}
}
boolean multiLineHandler = false;
if (DEBUG) {
System.out.println("afterHandler = " + afterHandler + ", handled = " + handled);
}
if (afterHandler > handled && lineNumbers != null) {
int startHandlerLinenumber = lineNumbers.getSourceLine(handled);
int endHandlerLinenumber = getNextExecutableLineNumber(lineNumbers, afterHandler) - 1;
if (DEBUG) {
System.out.println("Handler in lines " + startHandlerLinenumber + "-" + endHandlerLinenumber);
}
if (endHandlerLinenumber > startHandlerLinenumber) {
multiLineHandler = true;
if (DEBUG) {
System.out.println("Multiline handler");
}
}
}
if (end - start >= 4 && drops && !"java.lang.InterruptedException".equals(causeName)
&& !"java.lang.CloneNotSupportedException".equals(causeName)) {
int priority = NORMAL_PRIORITY;
if (exitInTryBlock) {
priority++;
}
if (end - start == 4) {
priority++;
}
SourceLineAnnotation srcLine = SourceLineAnnotation.fromVisitedInstruction(this.classContext, this, handled);
if (srcLine != null && LOOK_IN_SOURCE_TO_FIND_COMMENTED_CATCH_BLOCKS) {
if (catchBlockHasComment(srcLine)) {
return;
} else {
priority++;
}
} else {
// can't look at source
if (lineNumbers == null || multiLineHandler) {
priority += 2;
}
}
if ("java.lang.Error".equals(causeName) || "java.lang.Exception".equals(causeName) || "java.lang.Throwable".equals(causeName)
|| "java.lang.RuntimeException".equals(causeName)) {
priority--;
if (end - start > 30) {
priority--;
}
}
int register = -1;
if (startsWithASTORE03) {
register = opcode - Const.ASTORE_0;
} else if (opcode == Const.ASTORE) {
register = asUnsignedByte(code[handled + 1]);
}
if (register >= 0) {
LocalVariableAnnotation lva = LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(), register, handled+2, handled+1);
String name = lva.getName();
if (DEBUG) {
System.out.println("Name: " + name);
}
if (name.startsWith("ignore") || name.startsWith("cant")) {
continue;
}
}
if (DEBUG) {
System.out.println("Priority is " + priority);
}
if (priority > LOW_PRIORITY) {
return;
}
if (priority < HIGH_PRIORITY) {
priority = HIGH_PRIORITY;
}
if (DEBUG) {
System.out.println("reporting warning");
}
BugInstance bugInstance = new BugInstance(this, exitInTryBlock ? "DE_MIGHT_DROP" : "DE_MIGHT_IGNORE", priority)
.addClassAndMethod(this);
bugInstance.addClass(causeName).describe("CLASS_EXCEPTION");
bugInstance.addSourceLine(srcLine);
bugAccumulator.accumulateBug(bugInstance, srcLine);
}
}
}
private int getNextExecutableLineNumber(LineNumberTable linenumbers, int PC) {
LineNumber[] entries = linenumbers.getLineNumberTable();
int beforePC = 0;
int i = 0;
for (; i < entries.length && entries[i].getStartPC() < PC; i++) {
int line = entries[i].getLineNumber();
if (line > beforePC) {
beforePC = line;
}
}
if (i < entries.length) {
int secondChoice = entries[i].getLineNumber();
for (; i < entries.length; i++) {
int line = entries[i].getLineNumber();
if (line > beforePC) {
return line;
}
}
return secondChoice;
} else {
return entries[entries.length - 1].getLineNumber();
}
}
private static final int START = 0;
private static final int CATCH = 1;
private static final int OPEN_PAREN = 2;
private static final int CLOSE_PAREN = 3;
private static final int OPEN_BRACE = 4;
/**
* Maximum number of lines we look backwards to find the "catch" keyword.
* Looking backwards is necessary when the indentation style puts the open
* brace on a different line from the catch clause.
*/
private static final int NUM_CONTEXT_LINES = 3;
/**
* The number of lines that we'll scan to look at the source for a catch
* block.
*/
private static final int MAX_LINES = 7;
/**
* Analyze a class's source code to see if there is a comment (or other
* text) in a catch block we have marked as dropping an exception.
*
* @return true if there is a comment in the catch block, false if not (or
* if we can't tell)
*/
private boolean catchBlockHasComment(SourceLineAnnotation srcLine) {
if (!LOOK_IN_SOURCE_TO_FIND_COMMENTED_CATCH_BLOCKS) {
return false;
}
SourceFinder sourceFinder = AnalysisContext.currentAnalysisContext().getSourceFinder();
try {
SourceFile sourceFile = sourceFinder.findSourceFile(srcLine.getPackageName(), srcLine.getSourceFile());
int startLine = srcLine.getStartLine();
int scanStartLine = startLine - NUM_CONTEXT_LINES;
if (scanStartLine < 1) {
scanStartLine = 1;
}
int offset = sourceFile.getLineOffset(scanStartLine - 1);
if (offset < 0)
{
return false; // Source file has changed?
}
Tokenizer tokenizer = new Tokenizer(UTF8.reader(sourceFile.getInputStreamFromOffset(offset)));
// Read the tokens into an ArrayList,
// keeping track of where the catch block is reported
// to start
ArrayList<Token> tokenList = new ArrayList<>(40);
int eolOfCatchBlockStart = -1;
for (int line = scanStartLine; line < scanStartLine + MAX_LINES;) {
Token token = tokenizer.next();
int kind = token.getKind();
if (kind == Token.EOF) {
break;
}
if (kind == Token.EOL) {
if (line == startLine) {
eolOfCatchBlockStart = tokenList.size();
}
++line;
}
tokenList.add(token);
}
if (eolOfCatchBlockStart < 0)
{
return false; // Couldn't scan line reported as start of catch
// block
}
// Starting at the end of the line reported as the start of the
// catch block,
// scan backwards for the token "catch".
ListIterator<Token> iter = tokenList.listIterator(eolOfCatchBlockStart);
boolean foundCatch = false;
while (iter.hasPrevious()) {
Token token = iter.previous();
if (token.getKind() == Token.WORD && "catch".equals(token.getLexeme())) {
foundCatch = true;
break;
}
}
if (!foundCatch)
{
return false; // Couldn't find "catch" keyword
}
// Scan forward from the "catch" keyword to see what text
// is in the handler block. If the block is non-empty,
// then we suppress the warning (on the theory that the
// programmer has indicated that there is a good reason
// that the exception is ignored).
boolean done = false;
int numLines = 0;
int state = START;
int level = 0;
do {
if (!iter.hasNext()) {
break;
}
Token token = iter.next();
int type = token.getKind();
String value = token.getLexeme();
switch (type) {
case Token.EOL:
if (DEBUG) {
System.out.println("Saw token: [EOL]");
}
++numLines;
if (numLines >= MAX_LINES) {
done = true;
}
break;
default:
if (DEBUG) {
System.out.println("Got token: " + value);
}
switch (state) {
case START:
if ("catch".equals(value)) {
state = CATCH;
}
break;
case CATCH:
if ("(".equals(value)) {
state = OPEN_PAREN;
}
break;
case OPEN_PAREN:
if (")".equals(value)) {
if (level == 0) {
state = CLOSE_PAREN;
} else {
--level;
}
} else if ("(".equals(value)) {
++level;
}
break;
case CLOSE_PAREN:
if ("{".equals(value)) {
state = OPEN_BRACE;
}
break;
case OPEN_BRACE:
boolean closeBrace = "}".equals(value);
if (DEBUG && !closeBrace) {
System.out.println("Found a comment in catch block: " + value);
}
return !closeBrace;
}
break;
}
} while (!done);
} catch (IOException e) {
// Ignored; we'll just assume there is no comment
}
return false;
}
}
| sewe/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/detect/DroppedException.java | Java | lgpl-2.1 | 20,678 |
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.lenskit.util.table;
import org.apache.commons.lang3.builder.Builder;
import org.lenskit.util.table.writer.AbstractTableWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Builder to construct tables.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class TableBuilder extends AbstractTableWriter implements Builder<Table> {
private final TableLayout layout;
private final List<Row> rows;
/**
* Construct a new builder using a particular layout.
*
* @param layout The table layout.
*/
public TableBuilder(TableLayout layout) {
this.layout = layout;
rows = new ArrayList<Row>();
}
public TableBuilder(List<String> columns) {
TableLayoutBuilder bld = new TableLayoutBuilder();
for (String col: columns) {
bld.addColumn(col);
}
layout = bld.build();
rows = new ArrayList<Row>();
}
@Override
public TableLayout getLayout() {
return layout;
}
@Override
public void close() {}
@Override
public void writeRow(List<?> row) {
addRow(row);
}
/**
* Add a row to the table.
*
* @param row The row to add.
* @throws IllegalArgumentException if the row has the wrong length.
* @since 1.1
*/
public synchronized void addRow(List<?> row) {
addRow(row.toArray());
}
/**
* Add a row to the table.
*
* @param row The row to add.
* @throws IllegalArgumentException if the row has the wrong length.
* @since 1.1
*/
public synchronized void addRow(Object... row) {
checkRowWidth(row.length);
rows.add(new RowImpl(layout, row));
}
@Override
public Table build() {
return new TableImpl(layout, rows);
}
}
| amaliujia/lenskit | lenskit-eval/src/main/java/org/lenskit/util/table/TableBuilder.java | Java | lgpl-2.1 | 2,907 |
/**
* JRadius - A RADIUS Server Java Adapter
* Copyright (C) 2004-2006 PicoPoint, B.V.
*
* 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 net.jradius.packet.attribute.value;
import java.net.InetAddress;
/**
* The IPv6 attribute value
*
* @author David Bird
*/
public class IPv6AddrValue extends IPAddrValue
{
private static final long serialVersionUID = 0L;
public IPv6AddrValue() { }
public IPv6AddrValue(InetAddress i)
{
super(i);
}
public int getLength()
{
return 16;
}
}
| Chandrashar/jradius | core/src/main/java/net/jradius/packet/attribute/value/IPv6AddrValue.java | Java | lgpl-2.1 | 1,239 |
/*
* Copyright (c) 2007 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.core.database;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.row.ValueMetaInterface;
/**
* Contains MySQL specific information through static final members
*
* @author Matt
* @since 11-mrt-2005
*/
public class MySQLDatabaseMeta extends BaseDatabaseMeta implements DatabaseInterface
{
public int[] getAccessTypeList()
{
return new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC, DatabaseMeta.TYPE_ACCESS_JNDI };
}
public int getDefaultDatabasePort()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_NATIVE) return 3306;
return -1;
}
public String getLimitClause(int nrRows)
{
return " LIMIT "+nrRows;
}
/**
* Returns the minimal SQL to launch in order to determine the layout of the resultset for a given database table
* @param tableName The name of the table to determine the layout for
* @return The SQL to launch.
*/
public String getSQLQueryFields(String tableName)
{
return "SELECT * FROM "+tableName+" LIMIT 0"; //$NON-NLS-1$ //$NON-NLS-2$
}
public String getSQLTableExists(String tablename)
{
return getSQLQueryFields(tablename);
}
public String getSQLColumnExists(String columnname, String tablename)
{
return getSQLQueryColumnFields(columnname, tablename);
}
public String getSQLQueryColumnFields(String columnname, String tableName)
{
return "SELECT " + columnname + " FROM "+tableName +" LIMIT 0"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* @see org.pentaho.di.core.database.DatabaseInterface#getNotFoundTK(boolean)
*/
public int getNotFoundTK(boolean use_autoinc)
{
if ( supportsAutoInc() && use_autoinc)
{
return 1;
}
return super.getNotFoundTK(use_autoinc);
}
public String getDriverClass()
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "sun.jdbc.odbc.JdbcOdbcDriver";
}
else
{
return "org.gjt.mm.mysql.Driver";
}
}
public String getURL(String hostname, String port, String databaseName)
{
if (getAccessType()==DatabaseMeta.TYPE_ACCESS_ODBC)
{
return "jdbc:odbc:"+databaseName;
}
else
{
if (Const.isEmpty(port))
{
return "jdbc:mysql://"+hostname+"/"+databaseName;
}
else
{
return "jdbc:mysql://"+hostname+":"+port+"/"+databaseName;
}
}
}
/**
* @return The extra option separator in database URL for this platform (usually this is semicolon ; )
*/
public String getExtraOptionSeparator()
{
return "&";
}
/**
* @return This indicator separates the normal URL from the options
*/
public String getExtraOptionIndicator()
{
return "?";
}
/**
* @return true if the database supports transactions.
*/
public boolean supportsTransactions()
{
return false;
}
/**
* @return true if the database supports bitmap indexes
*/
public boolean supportsBitmapIndex()
{
return false;
}
/**
* @return true if the database supports views
*/
public boolean supportsViews()
{
return true;
}
/**
* @return true if the database supports synonyms
*/
public boolean supportsSynonyms()
{
return false;
}
/**
* Generates the SQL statement to add a column to the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to add a column to the specified table
*/
public String getAddColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" ADD "+getFieldDefinition(v, tk, pk, use_autoinc, true, false);
}
/**
* Generates the SQL statement to modify a column in the specified table
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param use_autoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to modify a column in the specified table
*/
public String getModifyColumnStatement(String tablename, ValueMetaInterface v, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
return "ALTER TABLE "+tablename+" MODIFY "+getFieldDefinition(v, tk, pk, use_autoinc, true, false);
}
public String getFieldDefinition(ValueMetaInterface v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr)
{
String retval="";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
if (add_fieldname) retval+=fieldname+" ";
int type = v.getType();
switch(type)
{
case ValueMetaInterface.TYPE_DATE : retval+="DATETIME"; break;
case ValueMetaInterface.TYPE_BOOLEAN :
if (supportsBooleanDataType()) {
retval+="BOOLEAN";
} else {
retval+="CHAR(1)";
}
break;
case ValueMetaInterface.TYPE_NUMBER :
case ValueMetaInterface.TYPE_INTEGER :
case ValueMetaInterface.TYPE_BIGNUMBER :
if (fieldname.equalsIgnoreCase(tk) || // Technical key
fieldname.equalsIgnoreCase(pk) // Primary key
)
{
if (use_autoinc)
{
retval+="BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY";
}
else
{
retval+="BIGINT NOT NULL PRIMARY KEY";
}
}
else
{
// Integer values...
if (precision==0)
{
if (length>9)
{
if (length<19) {
// can hold signed values between -9223372036854775808 and 9223372036854775807
// 18 significant digits
retval+="BIGINT";
}
else {
retval+="DECIMAL("+length+")";
}
}
else
{
retval+="INT";
}
}
// Floating point values...
else
{
if (length>15)
{
retval+="DECIMAL("+length;
if (precision>0) retval+=", "+precision;
retval+=")";
}
else
{
// A double-precision floating-point number is accurate to approximately 15 decimal places.
// http://mysql.mirrors-r-us.net/doc/refman/5.1/en/numeric-type-overview.html
retval+="DOUBLE";
}
}
}
break;
case ValueMetaInterface.TYPE_STRING:
if (length>0)
{
if (length==1) retval+="CHAR(1)";
else if (length< 256) retval+="VARCHAR("+length+")";
else if (length< 65536) retval+="TEXT";
else if (length<16777216) retval+="MEDIUMTEXT";
else retval+="LONGTEXT";
}
else
{
retval+="TINYTEXT";
}
break;
case ValueMetaInterface.TYPE_BINARY:
retval+="LONGBLOB";
break;
default:
retval+=" UNKNOWN";
break;
}
if (add_cr) retval+=Const.CR;
return retval;
}
/* (non-Javadoc)
* @see org.pentaho.di.core.database.DatabaseInterface#getReservedWords()
*/
public String[] getReservedWords()
{
return new String[]
{
"ADD", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT",
"BINARY", "BLOB", "BOTH", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER",
"CHECK", "COLLATE", "COLUMN", "CONDITION", "CONNECTION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT_DATE",
"CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC",
"DECIMAL", "DECLARE", "DEFAULT", "DELAYED", "DELETE", "DESC", "DESCRIBE", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV",
"DOUBLE", "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "ENCLOSED", "ESCAPED", "EXISTS", "EXIT", "EXPLAIN",
"FALSE", "FETCH", "FLOAT", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GOTO", "GRANT", "GROUP",
"HAVING", "HIGH_PRIORITY", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER",
"INOUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERVAL", "INTO", "IS", "ITERATE", "JOIN", "KEY",
"KEYS", "KILL", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCATE",
"LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MATCH", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT",
"MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NOT", "NO_WRITE_TO_BINLOG", "NULL", "NUMERIC", "ON", "OPTIMIZE",
"OPTION", "OPTIONALLY", "OR", "ORDER", "OUT", "OUTER", "OUTFILE", "POSITION", "PRECISION", "PRIMARY", "PROCEDURE", "PURGE",
"READ", "READS", "REAL", "REFERENCES", "REGEXP", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESTRICT", "RETURN",
"REVOKE", "RIGHT", "RLIKE", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET", "SHOW",
"SMALLINT", "SONAME", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT",
"SSL", "STARTING", "STRAIGHT_JOIN", "TABLE", "TERMINATED", "THEN", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING",
"TRIGGER", "TRUE", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING",
"UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "WHEN", "WHERE", "WHILE",
"WITH", "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL"
};
}
/* (non-Javadoc)
* @see org.pentaho.di.core.database.DatabaseInterface#getStartQuote()
*/
public String getStartQuote()
{
return "`";
}
/**
* Simply add an underscore in the case of MySQL!
* @see org.pentaho.di.core.database.DatabaseInterface#getEndQuote()
*/
public String getEndQuote()
{
return "`";
}
/**
* @param tableNames The names of the tables to lock
* @return The SQL command to lock database tables for write purposes.
*/
public String getSQLLockTables(String tableNames[])
{
String sql="LOCK TABLES ";
for (int i=0;i<tableNames.length;i++)
{
if (i>0) sql+=", ";
sql+=tableNames[i]+" WRITE";
}
sql+=";"+Const.CR;
return sql;
}
/**
* @param tableName The name of the table to unlock
* @return The SQL command to unlock a database table.
*/
public String getSQLUnlockTables(String tableName[])
{
return "UNLOCK TABLES"; // This unlocks all tables
}
public boolean needsToLockAllTables() {
return true;
}
/**
* @return extra help text on the supported options on the selected database platform.
*/
public String getExtraOptionsHelpText()
{
return "http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html";
}
public String[] getUsedLibraries()
{
return new String[] { "mysql-connector-java-3.1.14-bin.jar" };
}
/**
* @param tableName
* @return true if the specified table is a system table
*/
public boolean isSystemTable(String tableName) {
if ( tableName.startsWith("sys")) return true;
if ( tableName.equals("dtproperties")) return true;
return false;
}
/**
* Get the SQL to insert a new empty unknown record in a dimension.
* @param schemaTable the schema-table name to insert into
* @param keyField The key field
* @param versionField the version field
* @return the SQL to insert the unknown record into the SCD.
*/
public String getSQLInsertAutoIncUnknownDimensionRow(String schemaTable, String keyField, String versionField) {
return "insert into "+schemaTable+"("+keyField+", "+versionField+") values (1, 1)";
}
/**
* @param string
* @return A string that is properly quoted for use in a SQL statement (insert, update, delete, etc)
*/
public String quoteSQLString(String string) {
string = string.replaceAll("'", "\\\\'");
string = string.replaceAll("\\n", "\\\\n");
string = string.replaceAll("\\r", "\\\\r");
return "'"+string+"'";
}
/**
* @return true if the database is a MySQL variant, like MySQL 5.1, InfiniDB, InfoBright, and so on.
*/
public boolean isMySQLVariant() {
return true;
}
}
| juanmjacobs/kettle | src-db/org/pentaho/di/core/database/MySQLDatabaseMeta.java | Java | lgpl-2.1 | 13,674 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.dmr.ValueExpression;
import org.junit.Test;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class ExpressionResolverUnitTestCase {
@Test(expected = OperationFailedException.class)
public void testDefaultExpressionResolverWithNoResolutions() throws OperationFailedException {
ModelNode unresolved = createModelNode();
ExpressionResolver.TEST_RESOLVER.resolveExpressions(unresolved);
fail("Did not fail with OFE: " + unresolved);
}
@Test
public void testDefaultExpressionResolverWithRecursiveSystemPropertyResolutions() throws OperationFailedException {
System.setProperty("test.prop.expr", "EXPR");
System.setProperty("test.prop.b", "B");
System.setProperty("test.prop.c", "C");
System.setProperty("test.prop.two", "TWO");
System.setProperty("test.prop.three", "THREE");
// recursive example
System.setProperty("test.prop.prop", "${test.prop.prop.intermediate}");
System.setProperty("test.prop.prop.intermediate", "PROP");
// recursive example with a property expression as the default
System.setProperty("test.prop.expr", "${NOTHERE:${ISHERE}}");
System.setProperty("ISHERE", "EXPR");
//PROP
try {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(createModelNode());
checkResolved(node);
} finally {
System.clearProperty("test.prop.expr");
System.clearProperty("test.prop.b");
System.clearProperty("test.prop.c");
System.clearProperty("test.prop.two");
System.clearProperty("test.prop.three");
System.clearProperty("test.prop.prop");
}
}
@Test
public void testDefaultExpressionResolverWithSystemPropertyResolutions() throws OperationFailedException {
System.setProperty("test.prop.expr", "EXPR");
System.setProperty("test.prop.b", "B");
System.setProperty("test.prop.c", "C");
System.setProperty("test.prop.two", "TWO");
System.setProperty("test.prop.three", "THREE");
System.setProperty("test.prop.prop", "PROP");
try {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(createModelNode());
checkResolved(node);
} finally {
System.clearProperty("test.prop.expr");
System.clearProperty("test.prop.b");
System.clearProperty("test.prop.c");
System.clearProperty("test.prop.two");
System.clearProperty("test.prop.three");
System.clearProperty("test.prop.prop");
}
}
@Test
public void testPluggableExpressionResolverRecursive() throws OperationFailedException {
ModelNode node = new ExpressionResolverImpl() {
@Override
protected void resolvePluggableExpression(ModelNode node, OperationContext context) {
String s = node.asString();
if (s.equals("${test.prop.expr}")) {
node.set("${test.prop.expr.inner}");
} else if (s.equals("${test.prop.expr.inner}")) {
node.set("EXPR");
} else if (s.equals("${test.prop.b}")) {
node.set("B");
} else if (s.equals("${test.prop.c}")) {
node.set("C");
} else if (s.equals("${test.prop.two}")) {
node.set("TWO");
} else if (s.equals("${test.prop.three}")) {
node.set("THREE");
} else if (s.equals("${test.prop.prop}")) {
node.set("PROP");
}
}
}.resolveExpressions(createModelNode());
checkResolved(node);
}
@Test
public void testPluggableExpressionResolver() throws OperationFailedException {
ModelNode node = new ExpressionResolverImpl() {
@Override
protected void resolvePluggableExpression(ModelNode node, OperationContext context) {
String s = node.asString();
if (s.equals("${test.prop.expr}")) {
node.set("EXPR");
} else if (s.equals("${test.prop.b}")) {
node.set("B");
} else if (s.equals("${test.prop.c}")) {
node.set("C");
} else if (s.equals("${test.prop.two}")) {
node.set("TWO");
} else if (s.equals("${test.prop.three}")) {
node.set("THREE");
} else if (s.equals("${test.prop.prop}")) {
node.set("PROP");
}
}
}.resolveExpressions(createModelNode());
checkResolved(node);
}
@Test(expected = OperationFailedException.class)
public void testPluggableExpressionResolverNotResolved() throws OperationFailedException {
ModelNode unresolved = createModelNode();
new ExpressionResolverImpl() {
@Override
protected void resolvePluggableExpression(ModelNode node, OperationContext context) {
}
}.resolveExpressions(unresolved);
fail("Did not fail with OFE: " + unresolved);
}
@Test
public void testPluggableExpressionResolverSomeResolvedAndSomeByDefault() throws OperationFailedException {
System.setProperty("test.prop.c", "C");
System.setProperty("test.prop.three", "THREE");
System.setProperty("test.prop.prop", "PROP");
try {
ModelNode node = new ExpressionResolverImpl() {
@Override
protected void resolvePluggableExpression(ModelNode node, OperationContext context) {
String s = node.asString();
if (s.equals("${test.prop.expr}")) {
node.set("EXPR");
} else if (s.equals("${test.prop.b}")) {
node.set("B");
} else if (s.equals("${test.prop.two}")) {
node.set("TWO");
}
}
}.resolveExpressions(createModelNode());
checkResolved(node);
} finally {
System.clearProperty("test.prop.c");
System.clearProperty("test.prop.three");
System.clearProperty("test.prop.prop");
}
}
@Test
public void testSimpleLenientResolver() {
ModelNode input = createModelNode();
input.get("defaulted").set(new ValueExpression("${test.default:default}"));
ModelNode node = new ModelNode();
try {
node = ExpressionResolver.SIMPLE_LENIENT.resolveExpressions(input);
} catch (OperationFailedException ofe) {
fail("Should not have thrown OFE: " + ofe.toString());
}
assertEquals(7, node.keys().size());
assertEquals(1, node.get("int").asInt());
assertEquals(new ValueExpression("${test.prop.expr}"), node.get("expr").asExpression());
assertEquals(3, node.get("map").keys().size());
assertEquals("a", node.get("map", "plain").asString());
assertEquals(new ValueExpression("${test.prop.b}"), node.get("map", "prop.b").asExpression());
assertEquals(new ValueExpression("${test.prop.c}"), node.get("map", "prop.c").asExpression());
assertEquals(3, node.get("list").asList().size());
assertEquals("one", node.get("list").asList().get(0).asString());
assertEquals(new ValueExpression("${test.prop.two}"), node.get("list").asList().get(1).asExpression());
assertEquals(new ValueExpression("${test.prop.three}"), node.get("list").asList().get(2).asExpression());
assertEquals("plain", node.get("plainprop").asProperty().getValue().asString());
assertEquals(new ValueExpression("${test.prop.prop}"), node.get("prop").asProperty().getValue().asExpression());
assertEquals("default", node.get("defaulted").asString());
}
@Test
public void testPluggableExpressionResolverNestedExpression() throws OperationFailedException {
System.setProperty("test.prop.nested", "expr");
try {
ModelNode node = new ExpressionResolverImpl() {
@Override
protected void resolvePluggableExpression(ModelNode node, OperationContext context) {
String s = node.asString();
if (s.equals("${test.prop.expr}")) {
node.set("EXPR");
}
}
}.resolveExpressions(new ModelNode(new ValueExpression("${test.prop.${test.prop.nested}}")));
assertEquals("EXPR", node.asString());
} finally {
System.clearProperty("test.prop.nested");
}
}
@Test
public void testNestedExpressions() throws OperationFailedException {
System.setProperty("foo", "FOO");
System.setProperty("bar", "BAR");
System.setProperty("baz", "BAZ");
System.setProperty("FOO", "oof");
System.setProperty("BAR", "rab");
System.setProperty("BAZ", "zab");
System.setProperty("foo.BAZ.BAR", "FOO.baz.bar");
System.setProperty("foo.BAZBAR", "FOO.bazbar");
System.setProperty("bazBAR", "BAZbar");
System.setProperty("fooBAZbar", "FOObazBAR");
try {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo:${bar}}"));
assertEquals("FOO", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${${bar}}"));
assertEquals("rab", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo.${baz}.${bar}}"));
assertEquals("FOO.baz.bar", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo.${baz}${bar}}"));
assertEquals("FOO.bazbar", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("a${foo${baz${bar}}}b"));
assertEquals("aFOObazBARb", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("a${foo${baz${bar}}}"));
assertEquals("aFOObazBAR", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo${baz${bar}}}b"));
assertEquals("FOObazBARb", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("a${foo}.b.${bar}c"));
assertEquals("aFOO.b.BARc", node.asString());
System.clearProperty("foo");
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo:${bar}}"));
assertEquals("BAR", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo:${bar}.{}.$$}"));
assertEquals("BAR.{}.$$", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$$${bar}"));
assertEquals("$BAR", node.asString());
} finally {
System.clearProperty("foo");
System.clearProperty("bar");
System.clearProperty("baz");
System.clearProperty("FOO");
System.clearProperty("BAR");
System.clearProperty("BAZ");
System.clearProperty("foo.BAZ.BAR");
System.clearProperty("foo.BAZBAR");
System.clearProperty("bazBAR");
System.clearProperty("fooBAZbar");
}
}
@Test
public void testDollarEscaping() throws OperationFailedException {
System.setProperty("$$", "FOO");
try {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$$"));
assertEquals("$", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$$$"));
assertEquals("$$", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$$$$"));
assertEquals("$$", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${$$$$:$$}"));
assertEquals("$$", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${$$:$$}"));
assertEquals("FOO", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${foo:$${bar}}"));
assertEquals("${bar}", node.asString());
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$${bar}"));
assertEquals("${bar}", node.asString());
} finally {
System.clearProperty("$$");
}
}
@Test
public void testFileSeparator() throws OperationFailedException {
assertEquals(File.separator, ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${/}")).asString());
assertEquals(File.separator + "a", ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${/}a")).asString());
assertEquals("a" + File.separator, ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("a${/}")).asString());
}
@Test
public void testPathSeparator() {
assertEquals(File.pathSeparator, new ValueExpression("${:}").resolveString());
assertEquals(File.pathSeparator + "a", new ValueExpression("${:}a").resolveString());
assertEquals("a" + File.pathSeparator, new ValueExpression("a${:}").resolveString());
}
@Test
public void testNonExpression() throws OperationFailedException {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("abc"));
assertEquals("abc", node.asString());
assertEquals(ModelType.STRING, node.getType());
}
@Test
public void testBlankExpression() throws OperationFailedException {
ModelNode node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression(""));
assertEquals("", node.asString());
assertEquals(ModelType.STRING, node.getType());
}
/**
* Test that a incomplete expression to a system property reference throws an ISE
*/
@Test(expected = OperationFailedException.class)
public void testIncompleteReference() throws OperationFailedException {
System.setProperty("test.property1", "test.property1.value");
try {
ModelNode resolved = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${test.property1"));
fail("Did not fail with OFE: " + resolved);
} finally {
System.clearProperty("test.property1");
}
}
/**
* Test that an incomplete expression is ignored if escaped
*/
@Test
public void testEscapedIncompleteReference() throws OperationFailedException {
assertEquals("${test.property1", ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("$${test.property1")).asString());
}
/**
* Test that a incomplete expression to a system property reference throws an ISE
*/
@Test(expected = OperationFailedException.class)
public void testIncompleteReferenceFollowingSuccessfulResolve() throws OperationFailedException {
System.setProperty("test.property1", "test.property1.value");
try {
ModelNode resolved = ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${test.property1} ${test.property1"));
fail("Did not fail with OFE: "+ resolved);
} finally {
System.clearProperty("test.property1");
}
}
/**
* Test an expression that contains more than one system property name to
* see that the second property value is used when the first property
* is not defined.
*/
@Test
public void testSystemPropertyRefs() throws OperationFailedException {
System.setProperty("test.property2", "test.property2.value");
try {
assertEquals("test.property2.value", ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${test.property1,test.property2}")).asString());
} finally {
System.clearProperty("test.property2");
}
assertEquals("default", ExpressionResolver.TEST_RESOLVER.resolveExpressions(expression("${test.property1,test.property2:default}")).asString());
}
@Test
public void testExpressionWithDollarEndingDefaultValue() throws OperationFailedException {
try {
ModelNode node = new ModelNode();
node.get("expr").set(new ValueExpression("${test.property.dollar.default:default$}-test"));
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(node);
assertEquals("default$-test", node.get("expr").asString());
node = new ModelNode();
node.get("expr").set(new ValueExpression("${test.property.dollar.default:default$test}-test"));
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(node);
assertEquals(1, node.keys().size());
assertEquals("default$test-test", node.get("expr").asString());
System.setProperty("test.property.dollar.default", "system-prop-value");
node = new ModelNode();
node.get("expr").set(new ValueExpression("${test.property.dollar.default:default$}-test"));
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(node);
assertEquals(1, node.keys().size());
assertEquals("system-prop-value-test", node.get("expr").asString());
node = new ModelNode();
node.get("expr").set(new ValueExpression("${test.property.dollar.default:default$test}-test"));
node = ExpressionResolver.TEST_RESOLVER.resolveExpressions(node);
assertEquals(1, node.keys().size());
assertEquals("system-prop-value-test", node.get("expr").asString());
} finally {
System.clearProperty("test.property.dollar.default");
}
}
private ModelNode expression(String str) {
return new ModelNode(new ValueExpression(str));
}
private void checkResolved(ModelNode node) {
assertEquals(6, node.keys().size());
assertEquals(1, node.get("int").asInt());
assertEquals("EXPR", node.get("expr").asString());
assertEquals(3, node.get("map").keys().size());
assertEquals("a", node.get("map", "plain").asString());
assertEquals("B", node.get("map", "prop.b").asString());
assertEquals("C", node.get("map", "prop.c").asString());
assertEquals(3, node.get("list").asList().size());
assertEquals("one", node.get("list").asList().get(0).asString());
assertEquals("TWO", node.get("list").asList().get(1).asString());
assertEquals("THREE", node.get("list").asList().get(2).asString());
assertEquals("plain", node.get("plainprop").asProperty().getValue().asString());
assertEquals("PROP", node.get("prop").asProperty().getValue().asString());
}
private ModelNode createModelNode() {
ModelNode node = new ModelNode();
node.get("int").set(1);
node.get("expr").set(new ValueExpression("${test.prop.expr}"));
node.get("map", "plain").set("a");
node.get("map", "prop.b").set(new ValueExpression("${test.prop.b}"));
node.get("map", "prop.c").set(new ValueExpression("${test.prop.c}"));
node.get("list").add("one");
node.get("list").add(new ValueExpression("${test.prop.two}"));
node.get("list").add(new ValueExpression("${test.prop.three}"));
node.get("plainprop").set("plain", "plain");
node.get("prop").set("test", new ValueExpression("${test.prop.prop}"));
return node;
}
}
| luck3y/wildfly-core | controller/src/test/java/org/jboss/as/controller/ExpressionResolverUnitTestCase.java | Java | lgpl-2.1 | 21,247 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.db.migrations.v45;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbTester;
import org.sonar.server.db.DbClient;
import org.sonar.server.db.migrations.MigrationStep;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import static org.assertj.core.api.Assertions.assertThat;
public class DeleteMeasuresOnDeletedProfilesMigrationTest {
@Rule
public DbTester db = DbTester.createForSchema(System2.INSTANCE, DeleteMeasuresOnDeletedProfilesMigrationTest.class, "schema.sql");
MigrationStep migration;
@Before
public void setUp() {
DbClient dbClient = new DbClient(db.database(), db.myBatis());
migration = new DeleteMeasuresOnDeletedProfilesMigrationStep(dbClient);
}
@Test
public void delete_measures_with_no_json_data() throws Exception {
db.prepareDbUnit(getClass(), "before.xml");
migration.execute();
Connection connection = db.openConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select id from project_measures");
try {
assertThat(rs.next()).isTrue();
assertThat(rs.getInt(1)).isEqualTo(2);
assertThat(rs.next()).isFalse();
} finally {
rs.close();
stmt.close();
connection.close();
}
}
}
| ayondeep/sonarqube | server/sonar-server/src/test/java/org/sonar/server/db/migrations/v45/DeleteMeasuresOnDeletedProfilesMigrationTest.java | Java | lgpl-3.0 | 2,262 |
package org.molgenis.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Can be used by legacy classes to get a reference to the application context
*
* @author erwin
*/
// Intended static write from instance
@SuppressWarnings("squid:S2696")
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext ctx = null;
public static ApplicationContext getApplicationContext() {
return ctx;
}
@Override
public void setApplicationContext(ApplicationContext ctx) {
ApplicationContextProvider.ctx = ctx;
}
}
| bartcharbon/molgenis | molgenis-util/src/main/java/org/molgenis/util/ApplicationContextProvider.java | Java | lgpl-3.0 | 653 |
/**
*/
package fr.inria.lang.vM;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Integer Attr Def Complement</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link fr.inria.lang.vM.IntegerAttrDefComplement#getMin <em>Min</em>}</li>
* <li>{@link fr.inria.lang.vM.IntegerAttrDefComplement#getMax <em>Max</em>}</li>
* <li>{@link fr.inria.lang.vM.IntegerAttrDefComplement#getDelta <em>Delta</em>}</li>
* </ul>
* </p>
*
* @see fr.inria.lang.vM.VMPackage#getIntegerAttrDefComplement()
* @model
* @generated
*/
public interface IntegerAttrDefComplement extends EObject
{
/**
* Returns the value of the '<em><b>Min</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Min</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Min</em>' attribute.
* @see #setMin(String)
* @see fr.inria.lang.vM.VMPackage#getIntegerAttrDefComplement_Min()
* @model
* @generated
*/
String getMin();
/**
* Sets the value of the '{@link fr.inria.lang.vM.IntegerAttrDefComplement#getMin <em>Min</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Min</em>' attribute.
* @see #getMin()
* @generated
*/
void setMin(String value);
/**
* Returns the value of the '<em><b>Max</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Max</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Max</em>' attribute.
* @see #setMax(String)
* @see fr.inria.lang.vM.VMPackage#getIntegerAttrDefComplement_Max()
* @model
* @generated
*/
String getMax();
/**
* Sets the value of the '{@link fr.inria.lang.vM.IntegerAttrDefComplement#getMax <em>Max</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Max</em>' attribute.
* @see #getMax()
* @generated
*/
void setMax(String value);
/**
* Returns the value of the '<em><b>Delta</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Delta</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Delta</em>' containment reference.
* @see #setDelta(IntegerDeltaDef)
* @see fr.inria.lang.vM.VMPackage#getIntegerAttrDefComplement_Delta()
* @model containment="true"
* @generated
*/
IntegerDeltaDef getDelta();
/**
* Sets the value of the '{@link fr.inria.lang.vM.IntegerAttrDefComplement#getDelta <em>Delta</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Delta</em>' containment reference.
* @see #getDelta()
* @generated
*/
void setDelta(IntegerDeltaDef value);
} // IntegerAttrDefComplement
| ViViD-DiverSE/VM-Source | fr.inria.lang.vm/src-gen/fr/inria/lang/vM/IntegerAttrDefComplement.java | Java | lgpl-3.0 | 3,212 |
/*
* This file is part of the 3D City Database Importer/Exporter.
* Copyright (c) 2007 - 2013
* Institute for Geodesy and Geoinformation Science
* Technische Universitaet Berlin, Germany
* http://www.gis.tu-berlin.de/
*
* The 3D City Database Importer/Exporter program is free software:
* you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free
* Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*
* The development of the 3D City Database Importer/Exporter has
* been financially supported by the following cooperation partners:
*
* Business Location Center, Berlin <http://www.businesslocationcenter.de/>
* virtualcitySYSTEMS GmbH, Berlin <http://www.virtualcitysystems.de/>
* Berlin Senate of Business, Technology and Women <http://www.berlin.de/sen/wtf/>
*/
package de.tub.citydb.config.project.filter;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
@XmlType(name="BoundingBoxModeType")
@XmlEnum
public enum FilterBoundingBoxMode {
@XmlEnumValue("contain")
CONTAIN("contain"),
@XmlEnumValue("overlap")
OVERLAP("overlap");
private final String value;
FilterBoundingBoxMode(String v) {
value = v;
}
public String value() {
return value;
}
public static FilterBoundingBoxMode fromValue(String v) {
for (FilterBoundingBoxMode c: FilterBoundingBoxMode.values()) {
if (c.value.equals(v)) {
return c;
}
}
return CONTAIN;
}
}
| 3dcitydb/importer-exporter-postgis | src/de/tub/citydb/config/project/filter/FilterBoundingBoxMode.java | Java | lgpl-3.0 | 2,147 |
package mod.chiselsandbits.helpers;
import mod.chiselsandbits.api.APIExceptions.CannotBeChiseled;
import mod.chiselsandbits.chiseledblock.data.VoxelBlob;
import mod.chiselsandbits.core.ChiselsAndBits;
import mod.chiselsandbits.core.api.BitAccess;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class VoxelRegionSrc implements IVoxelSrc
{
final BlockPos min;
final BlockPos max;
final BlockPos actingCenter;
final int wrapZ;
final int wrapY;
final int wrapX;
final VoxelBlob blobs[];
private VoxelRegionSrc(
final World src,
final BlockPos min,
final BlockPos max,
final BlockPos actingCenter )
{
this.min = min;
this.max = max;
this.actingCenter = actingCenter.subtract( min );
wrapX = max.getX() - min.getX() + 1;
wrapY = max.getY() - min.getY() + 1;
wrapZ = max.getZ() - min.getZ() + 1;
blobs = new VoxelBlob[wrapX * wrapY * wrapZ];
for ( int x = min.getX(); x <= max.getX(); ++x )
{
for ( int y = min.getY(); y <= max.getY(); ++y )
{
for ( int z = min.getZ(); z <= max.getZ(); ++z )
{
final int idx = x - min.getX() + ( y - min.getY() ) * wrapX + ( z - min.getZ() ) * wrapX * wrapY;
try
{
final BitAccess access = (BitAccess) ChiselsAndBits.getApi().getBitAccess( src, new BlockPos( x, y, z ) );
blobs[idx] = access.getNativeBlob();
}
catch ( final CannotBeChiseled e )
{
blobs[idx] = new VoxelBlob();
}
}
}
}
}
public VoxelRegionSrc(
final World theWorld,
final BlockPos blockPos,
final int range )
{
this( theWorld, blockPos.add( -range, -range, -range ), blockPos.add( range, range, range ), blockPos );
}
@Override
public int getSafe(
int x,
int y,
int z )
{
x += actingCenter.getX() * VoxelBlob.dim;
y += actingCenter.getY() * VoxelBlob.dim;
z += actingCenter.getZ() * VoxelBlob.dim;
final int bitPosX = x & 0xf;
final int bitPosY = y & 0xf;
final int bitPosZ = z & 0xf;
final int blkPosX = x >> 4;
final int blkPosY = y >> 4;
final int blkPosZ = z >> 4;
final int idx = blkPosX + blkPosY * wrapX + blkPosZ * wrapX * wrapY;
if ( blkPosX < 0 || blkPosY < 0 || blkPosZ < 0 || blkPosX >= wrapX || blkPosY >= wrapY || blkPosZ >= wrapZ )
{
return 0;
}
return blobs[idx].get( bitPosX, bitPosY, bitPosZ );
}
public VoxelBlob getBlobAt(
final BlockPos blockPos )
{
final int blkPosX = blockPos.getX() - min.getX();
final int blkPosY = blockPos.getY() - min.getY();
final int blkPosZ = blockPos.getZ() - min.getZ();
final int idx = blkPosX + blkPosY * wrapX + blkPosZ * wrapX * wrapY;
if ( blkPosX < 0 || blkPosY < 0 || blkPosZ < 0 || blkPosX >= wrapX || blkPosY >= wrapY || blkPosZ >= wrapZ )
{
return new VoxelBlob();
}
return blobs[idx];
}
}
| AlgorithmX2/Chisels-and-Bits | src/main/java/mod/chiselsandbits/helpers/VoxelRegionSrc.java | Java | lgpl-3.0 | 2,799 |
package edu.brown.cs.h2r.burlapcraft.helper;
public class HelperGeometry {
public static class Pose {
private final double x;
private final double y;
private final double z;
private final double qx;
private final double qy;
private final double qz;
private final double qw;
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public static Pose fromXyz(double x, double y, double z) {
return new Pose(x, y, z, 0, 0, 0, 0);
}
public Pose(double _x, double _y, double _z, double _qx, double _qy, double _qz, double _qw) {
x = _x;
y = _y;
z = _z;
qx = _qx;
qy = _qy;
qz = _qz;
qw = _qw;
}
public Pose add(Pose p2) {
return Pose.fromXyz(this.x + p2.x, this.y + p2.y, this.z + p2.z);
}
public double distance(Pose p2) {
return HelperGeometry.distance(x, y, z, p2.x, p2.y, p2.z);
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append(String.valueOf(x));
result.append(",");
result.append(String.valueOf(y));
result.append(",");
result.append(String.valueOf(z));
return result.toString();
}
}
public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.pow(Math.pow((x2 - x1), 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2), 0.5);
}
}
| h2r/burlapcraft | src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperGeometry.java | Java | lgpl-3.0 | 1,399 |
/*******************************************************************************
* ===========================================================
* Ankush : Big Data Cluster Management Solution
* ===========================================================
*
* (C) Copyright 2014, by Impetus Technologies
*
* This is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL v3) as
* published by the Free Software Foundation;
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.28 at 12:38:28 PM IST
//
package com.impetus.ankush.agent.action.impl;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}property" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"property"
})
@XmlRootElement(name = "configuration")
public class Configuration {
/** The property. */
@XmlElement(required = true)
protected List<Property> property;
/**
* Gets the value of the property property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the property property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProperty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
*
* @return the property
* {@link Property }
*/
public List<Property> getProperty() {
if (property == null) {
property = new ArrayList<Property>();
}
return this.property;
}
}
| impetus-opensource/ankush | agent/src/main/java/com/impetus/ankush/agent/action/impl/Configuration.java | Java | lgpl-3.0 | 3,311 |
/*
* Copyright 2005 Joe Walker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.directwebremoting.extend;
import java.lang.reflect.Method;
/**
* Call is a POJO to encapsulate the information required to make a single java
* call, including the result of the call (either returned data or exception).
* Either the Method and Parameters should be filled in to allow a call to be
* made or, the exception should be filled in indicating that things have gone
* wrong already.
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class Call
{
/**
* @return the exception
*/
public Throwable getException()
{
return exception;
}
/**
* @param exception the exception to set
*/
public void setException(Throwable exception)
{
this.exception = exception;
}
/**
* @return the method
*/
public Method getMethod()
{
return method;
}
/**
* @param method the method to set
*/
public void setMethod(Method method)
{
this.method = method;
}
/**
* @return the parameters
*/
public Object[] getParameters()
{
return parameters;
}
/**
* @param parameters the parameters to set
*/
public void setParameters(Object[] parameters)
{
this.parameters = parameters;
}
/**
* @param callId The callId to set.
*/
public void setCallId(String callId)
{
this.callId = callId;
}
/**
* @return Returns the callId.
*/
public String getCallId()
{
return callId;
}
/**
* @param scriptName The scriptName to set.
*/
public void setScriptName(String scriptName)
{
this.scriptName = scriptName;
}
/**
* @return Returns the scriptName.
*/
public String getScriptName()
{
return scriptName;
}
/**
* @param methodName The methodName to set.
*/
public void setMethodName(String methodName)
{
this.methodName = methodName;
}
/**
* @return Returns the methodName.
*/
public String getMethodName()
{
return methodName;
}
private String callId = null;
private String scriptName = null;
private String methodName = null;
private Method method = null;
private Object[] parameters = null;
private Throwable exception = null;
}
| simeshev/parabuild-ci | 3rdparty/dwr-2.0.1/src/java/org/directwebremoting/extend/Call.java | Java | lgpl-3.0 | 2,972 |
/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
package gate.creole.annic.apache.lucene.analysis.standard;
/**
* Describes the input token stream.
*/
public class Token {
/**
* An integer that describes the kind of this token. This numbering
* system is determined by JavaCCParser, and a table of these numbers is
* stored in the file ...Constants.java.
*/
public int kind;
/**
* beginLine and beginColumn describe the position of the first character
* of this token; endLine and endColumn describe the position of the
* last character of this token.
*/
public int beginLine, beginColumn, endLine, endColumn;
/**
* The string image of the token.
*/
public String image;
/**
* A reference to the next regular (non-special) token from the input
* stream. If this is the last token from the input stream, or if the
* token manager has not read tokens beyond this one, this field is
* set to null. This is true only if this token is also a regular
* token. Otherwise, see below for a description of the contents of
* this field.
*/
public Token next;
/**
* This field is used to access special tokens that occur prior to this
* token, but after the immediately preceding regular (non-special) token.
* If there are no such special tokens, this field is set to null.
* When there are more than one such special token, this field refers
* to the last of these special tokens, which in turn refers to the next
* previous special token through its specialToken field, and so on
* until the first special token (whose specialToken field is null).
* The next fields of special tokens refer to other special tokens that
* immediately follow it (without an intervening regular token). If there
* is no such token, this field is null.
*/
public Token specialToken;
/**
* Returns the image.
*/
@Override
public String toString()
{
return image;
}
/**
* Returns a new Token object, by default. However, if you want, you
* can create and return subclass objects based on the value of ofKind.
* Simply add the cases to the switch for all those special cases.
* For example, if you have a subclass of Token called IDToken that
* you want to create if ofKind is ID, simlpy add something like :
*
* case MyParserConstants.ID : return new IDToken();
*
* to the following switch statement. Then you can cast matchedToken
* variable to the appropriate type and use it in your lexical actions.
*/
public static final Token newToken(int ofKind)
{
switch(ofKind)
{
default : return new Token();
}
}
}
| GateNLP/gate-core | src/main/java/gate/creole/annic/apache/lucene/analysis/standard/Token.java | Java | lgpl-3.0 | 2,708 |
// Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Tools;
/**
* Run-Length Metrics.
* @author Diego Catalano
*/
public final class RunLengthFeatures {
/**
* Don't let anyone instantiate this class.
*/
private RunLengthFeatures(){};
/**
* This metric increases when short runs dominate, for example, in fine-grained textures.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double ShortRunEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 0; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] / (j * j);
}
}
return r / numberPrimitives;
}
/**
* This metric increases when long runs dominate, for example, in textures with large homogeneous areas or coarse textures.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double LongRunEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 0; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] * j * j;
}
}
return r / numberPrimitives;
}
/**
* Emphasis is orthogonal to SRE, and the metric increases when the texture is dominated by many runs of low gray value.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double LowGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 0; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] / (i * i);
}
}
return r / numberPrimitives;
}
/**
* Emphasis is orthogonal to LRE, and the metric increases when the texture is dominated by many runs of high gray value.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double HighGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 0; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] * i * i;
}
}
return r / numberPrimitives;
}
/**
* This is a diagonal metric that combines SRE and LGRE. The metric increases when the texture is dominated by many short runs of low gray value.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double ShortRunLowGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] / ((i * i) * (j * j));
}
}
return r / numberPrimitives;
}
/**
* This metric is orthogonal to SRLGE and LRHGE and increases when the texture is dominated by short runs with high intensity levels.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double ShortRunHighGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += (runMatrix[i][j] * i * i) / (j * j);
}
}
return r / numberPrimitives;
}
/**
* Complementary to SRHGE, it increases when the texture is dominated by long runs that have low gray levels.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double LongRunLowGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] * j * j / (i * i);
}
}
return r / numberPrimitives;
}
/**
* This is the complementary metric to SRLGE and increases with a combination of long, high-gray value runs.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double LongRunHighGrayLevelEmphasis(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 1; i < runMatrix.length; i++) {
for (int j = 1; j < runMatrix[0].length; j++) {
r += runMatrix[i][j] * j * j * i * i;
}
}
return r / numberPrimitives;
}
/**
* This metric increases when gray-level outliers dominate the histogram.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double GrayLevelNonUniformity(double[][] runMatrix, int numberPrimitives){
double r = 0;
double sumJ = 0;
for (int i = 1; i < runMatrix.length; i++) {
r += sumJ * sumJ;
for (int j = 1; j < runMatrix[0].length; j++) {
sumJ += runMatrix[i][j];
}
}
return r / numberPrimitives;
}
/**
* This metric increases when few run-length outliers dominate the histogram.
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double RunLengthNonUniformity(double[][] runMatrix, int numberPrimitives){
double r = 0;
double sumI = 0;
for (int j = 1; j < runMatrix[0].length; j++) {
r += sumI * sumI;
for (int i = 1; i < runMatrix.length; i++) {
sumI += runMatrix[i][j];
}
}
return r / numberPrimitives;
}
/**
*
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double GrayLevelDistribution(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int i = 0; i < runMatrix.length; i++) {
for (int j = 0; j < runMatrix[0].length; j++) {
r += Math.pow(runMatrix[i][j] * j * j, 2);
}
}
return r / numberPrimitives;
}
/**
*
* @param runMatrix Run length matrix.
* @param numberPrimitives Number of primitives.
* @return
*/
public static double RunLenghtDistribution(double[][] runMatrix, int numberPrimitives){
double r = 0;
for (int j = 0; j < runMatrix[0].length; j++) {
for (int i = 0; i < runMatrix.length; i++) {
r += Math.pow(runMatrix[i][j] * i * i, 2);
}
}
return r / numberPrimitives;
}
/**
* This metric provides information on the overall homogeneity of the histogram and is maximal when all runs are of unity length irrespective of the gray level.
* @param runMatrix Run length matrix.
* @param numberPossiblePrimitives Number of primitives.
* @return
*/
public static double RunPercentage(double[][] runMatrix, int numberPossiblePrimitives){
double r = 0;
for (int i = 0; i < runMatrix.length; i++) {
for (int j = 0; j < runMatrix[0].length; j++) {
r += runMatrix[i][j];
}
}
return r / numberPossiblePrimitives;
}
} | cswaroop/Catalano-Framework | Catalano.Image/src/Catalano/Imaging/Tools/RunLengthFeatures.java | Java | lgpl-3.0 | 9,068 |
package org.perfectable.visuable.visual;
public final class StringIdentifier implements Visual.Identifier {
private static final long serialVersionUID = -3837459117766391558L;
public static final String PREFIX = "vx-";
private final String code;
public static StringIdentifier of(String code) {
return new StringIdentifier(code);
}
private StringIdentifier(String code) {
this.code = code;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof StringIdentifier)) {
return false;
}
StringIdentifier other = (StringIdentifier) obj;
return this.code.equals(other.code);
}
@Override
public int hashCode() {
return this.code.hashCode();
}
@Override
public String toString() {
return this.code;
}
}
| nivertius/perfectable | visuable/src/main/java/org/perfectable/visuable/visual/StringIdentifier.java | Java | lgpl-3.0 | 794 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.