repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/jndi/src/test/java/org/apache/harmony/jndi/tests/javax/naming/NotContextExceptionTest.java
4414
/* * 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.harmony.jndi.tests.javax.naming; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.naming.CompositeName; import javax.naming.InvalidNameException; import javax.naming.NotContextException; import junit.framework.TestCase; public class NotContextExceptionTest extends TestCase { /** * Test serialize NotContextException: write a NotContextException object * into a byte array, and read from it. the two object should be equals. */ public void testSerializable_Simple() throws ClassNotFoundException, IOException, InvalidNameException { NotContextException exception = new NotContextException( "Test exception Serializable: NotContextException"); exception.setRemainingName(new CompositeName( "www.apache.org/foundation")); exception.setResolvedName(new CompositeName( "http://www.apache.org/index.html")); exception.setResolvedObj("This is a string object."); exception.setRootCause(new NullPointerException("null pointer")); // write to byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(exception); byte[] buffer = baos.toByteArray(); oos.close(); baos.close(); // read from byte array ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); NotContextException exception2 = (NotContextException) ois.readObject(); ois.close(); bais.close(); assertEquals(exception.getExplanation(), exception2.getExplanation()); assertEquals(exception.getResolvedObj(), exception2.getResolvedObj()); assertEquals(exception.getRemainingName(), exception2 .getRemainingName()); assertEquals(exception.getResolvedName(), exception2.getResolvedName()); assertEquals(exception.getRootCause().getMessage(), exception2 .getRootCause().getMessage()); assertEquals(exception.getRootCause().getClass(), exception2 .getRootCause().getClass()); } /** * Test InvalidNameException serialization compatibility */ public void testSerializable_compatibility() throws InvalidNameException, ClassNotFoundException, IOException { ObjectInputStream ois = new ObjectInputStream(getClass() .getClassLoader().getResourceAsStream( "/serialization/javax/naming/NotContextException.ser")); NotContextException exception2 = (NotContextException) ois.readObject(); ois.close(); NotContextException exception = new NotContextException( "Test exception Serializable: NotContextException"); exception.setRemainingName(new CompositeName( "www.apache.org/foundation")); exception.setResolvedName(new CompositeName( "http://www.apache.org/index.html")); exception.setResolvedObj("This is a string object."); exception.setRootCause(new NullPointerException("null pointer")); assertEquals(exception.getExplanation(), exception2.getExplanation()); assertEquals(exception.getResolvedObj(), exception2.getResolvedObj()); assertEquals(exception.getRemainingName(), exception2 .getRemainingName()); assertEquals(exception.getResolvedName(), exception2.getResolvedName()); assertEquals(exception.getRootCause().getMessage(), exception2 .getRootCause().getMessage()); assertEquals(exception.getRootCause().getClass(), exception2 .getRootCause().getClass()); } }
gpl-2.0
skymania/OpenRate
src/main/java/OpenRate/record/flexRecord/RecordBlockDef.java
4229
/* ==================================================================== * Limited Evaluation License: * * This software is open source, but licensed. The license with this package * is an evaluation license, which may not be used for productive systems. If * you want a full license, please contact us. * * The exclusive owner of this work is the OpenRate project. * This work, including all associated documents and components * is Copyright of the OpenRate project 2006-2015. * * The following restrictions apply unless they are expressly relaxed in a * contractual agreement between the license holder or one of its officially * assigned agents and you or your organisation: * * 1) This work may not be disclosed, either in full or in part, in any form * electronic or physical, to any third party. This includes both in the * form of source code and compiled modules. * 2) This work contains trade secrets in the form of architecture, algorithms * methods and technologies. These trade secrets may not be disclosed to * third parties in any form, either directly or in summary or paraphrased * form, nor may these trade secrets be used to construct products of a * similar or competing nature either by you or third parties. * 3) This work may not be included in full or in part in any application. * 4) You may not remove or alter any proprietary legends or notices contained * in or on this work. * 5) This software may not be reverse-engineered or otherwise decompiled, if * you received this work in a compiled form. * 6) This work is licensed, not sold. Possession of this software does not * imply or grant any right to you. * 7) You agree to disclose any changes to this work to the copyright holder * and that the copyright holder may include any such changes at its own * discretion into the work * 8) You agree not to derive other works from the trade secrets in this work, * and that any such derivation may make you liable to pay damages to the * copyright holder * 9) You agree to use this software exclusively for evaluation purposes, and * that you shall not use this software to derive commercial profit or * support your business or personal activities. * * This software is provided "as is" and any expressed or impled warranties, * including, but not limited to, the impled warranties of merchantability * and fitness for a particular purpose are disclaimed. In no event shall * The OpenRate Project or its officially assigned agents be liable to any * direct, indirect, incidental, special, exemplary, or consequential damages * (including but not limited to, procurement of substitute goods or services; * Loss of use, data, or profits; or any business interruption) however caused * and on theory of liability, whether in contract, strict liability, or tort * (including negligence or otherwise) arising in any way out of the use of * this software, even if advised of the possibility of such damage. * This software contains portions by The Apache Software Foundation, Robert * Half International. * ==================================================================== */ package OpenRate.record.flexRecord; import java.util.ArrayList; import java.util.HashMap; /** * This class defines the structures and mappings that allow us to construct * record definitions on the fly * * @author TGDSPIA1 */ public class RecordBlockDef { int NumberOfFields = 0; String[] FieldNames; int[] FieldTypes; // the field separator for this block String Separator = null; // This is the name of the block String BlockName; // The mapping information that we will do when creating a new block of // this type. This is an ArrayList so that we hold all of the fields that are // to be mapped in a list. ArrayList<MapElement> Mapping; // The ChildTemplates hashmap contains the definitions of the child blocks HashMap<String, RecordBlockDef> ChildTemplates; // This is the index to allow us to find the field names quickly. This takes // the full path name and returns the block reference and the field info // (Offset, type) HashMap<String, Integer> FieldNameIndex; }
gpl-2.0
marek-g/libvlc-signio
vlc-android/src/org/videolan/vlc/gui/browser/NetworkBrowserFragment.java
6093
/* * ************************************************************************* * NetworkBrowserFragment.java * ************************************************************************** * Copyright © 2015 VLC authors and VideoLAN * Author: Geoffrey Métais * * 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.videolan.vlc.gui.browser; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.View; import org.videolan.vlc.media.MediaDatabase; import org.videolan.vlc.media.MediaWrapper; import org.videolan.vlc.R; import org.videolan.vlc.util.AndroidDevices; import java.util.ArrayList; public class NetworkBrowserFragment extends BaseBrowserFragment { public NetworkBrowserFragment() { ROOT = "smb"; mHandler = new BrowserFragmentHandler(this); mAdapter = new NetworkBrowserAdapter(this); } @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); if (mMrl == null) mMrl = ROOT; mRoot = ROOT.equals(mMrl); } public void onStart(){ super.onStart(); //Handle network connection state IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); getActivity().registerReceiver(networkReceiver, filter); } @Override protected Fragment createFragment() { return new NetworkBrowserFragment(); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(networkReceiver); } @Override protected void update() { if (!AndroidDevices.hasLANConnection()) updateEmptyView(); else super.update(); } protected void updateDisplay() { if (mRoot) updateFavorites(); mAdapter.notifyDataSetChanged(); parseSubDirectories(); } @Override protected void browseRoot() { ArrayList<MediaWrapper> favs = MediaDatabase.getInstance().getAllNetworkFav(); if (!favs.isEmpty()) { mFavorites = favs.size(); for (MediaWrapper fav : favs) { mAdapter.addItem(fav, false, true); } mAdapter.addItem("Network favorites", false, true); } mMediaBrowser.discoverNetworkShares(); } @Override protected String getCategoryTitle() { return getString(R.string.network_browsing); } private void updateFavorites(){ ArrayList<MediaWrapper> favs = MediaDatabase.getInstance().getAllNetworkFav(); int newSize = favs.size(), totalSize = mAdapter.getItemCount(); if (newSize == 0 && mFavorites == 0) return; for (int i = 1 ; i <= mFavorites ; ++i){ //remove former favorites mAdapter.removeItem(totalSize-i, mReadyToDisplay); } if (newSize == 0) mAdapter.removeItem(totalSize-mFavorites-1, mReadyToDisplay); //also remove separator if no more fav else { if (mFavorites == 0) mAdapter.addItem("Network favorites", false, false); //add header if needed for (MediaWrapper fav : favs) mAdapter.addItem(fav, false, false); //add new favorites } mFavorites = newSize; //update count } public void toggleFavorite() { MediaDatabase db = MediaDatabase.getInstance(); if (db.networkFavExists(mCurrentMedia.getUri())) db.deleteNetworkFav(mCurrentMedia.getUri()); else db.addNetworkFavItem(mCurrentMedia.getUri(), mCurrentMedia.getTitle()); getActivity().supportInvalidateOptionsMenu(); } /** * Update views visibility and emptiness info */ protected void updateEmptyView() { if (AndroidDevices.hasLANConnection()) { if (mAdapter.isEmpty()) { mEmptyView.setText(mRoot ? R.string.network_shares_discovery : R.string.network_empty); mEmptyView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); mSwipeRefreshLayout.setEnabled(false); } else { if (mEmptyView.getVisibility() == View.VISIBLE) { mEmptyView.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE); mSwipeRefreshLayout.setEnabled(true); } } } else { if (mEmptyView.getVisibility() == View.GONE) { mEmptyView.setText(R.string.network_connection_needed); mEmptyView.setVisibility(View.VISIBLE); mRecyclerView.setVisibility(View.GONE); mSwipeRefreshLayout.setEnabled(false); } } } private final BroadcastReceiver networkReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (mReadyToDisplay && ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) { update(); } } }; }
gpl-2.0
du-lab/mzmine2
src/main/java/net/sf/mzmine/modules/rawdatamethods/exportscans/ExportScansFromRawFilesModule.java
2761
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.modules.rawdatamethods.exportscans; import java.util.Collection; import javax.annotation.Nonnull; import org.apache.commons.lang3.ArrayUtils; import net.sf.mzmine.datamodel.MZmineProject; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import net.sf.mzmine.modules.MZmineModuleCategory; import net.sf.mzmine.modules.MZmineProcessingModule; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.parameters.parametertypes.selectors.ScanSelection; import net.sf.mzmine.taskcontrol.Task; import net.sf.mzmine.util.ExitCode; /** * Exports scans around a center time */ public class ExportScansFromRawFilesModule implements MZmineProcessingModule { private static final String MODULE_NAME = "Export scans into one file"; private static final String MODULE_DESCRIPTION = "Export scans or mass lists into one file "; @Override public @Nonnull String getName() { return MODULE_NAME; } @Override public @Nonnull String getDescription() { return MODULE_DESCRIPTION; } @Override @Nonnull public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection<Task> tasks) { ScanSelection select = parameters.getParameter(ExportScansFromRawFilesParameters.scanSelect).getValue(); Scan[] scans = new Scan[0]; for (RawDataFile raw : parameters.getParameter(ExportScansFromRawFilesParameters.dataFiles) .getValue().getMatchingRawDataFiles()) { scans = ArrayUtils.addAll(scans, select.getMatchingScans(raw)); } ExportScansTask task = new ExportScansTask(scans, parameters); tasks.add(task); return ExitCode.OK; } @Override public @Nonnull MZmineModuleCategory getModuleCategory() { return MZmineModuleCategory.RAWDATA; } @Override public @Nonnull Class<? extends ParameterSet> getParameterSetClass() { return ExportScansFromRawFilesParameters.class; } }
gpl-2.0
rfdrake/opennms
opennms-webapp/src/main/java/org/opennms/web/notification/NotificationModel.java
17508
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.notification; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.opennms.core.resource.Vault; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.opennms.core.utils.DBUtils; public class NotificationModel extends Object { private static final Logger LOG = LoggerFactory.getLogger(NotificationModel.class); private static final String USERID = "userID"; private static final String NOTICE_TIME = "notifytime"; private static final String TXT_MESG = "textMsg"; private static final String NUM_MESG = "numericMsg"; private static final String NOTIFY = "notifyID"; private static final String TIME = "pageTime"; private static final String REPLYTIME = "respondTime"; private static final String ANS_BY = "answeredBy"; private static final String CONTACT = "contactInfo"; private static final String NODE = "nodeID"; private static final String INTERFACE = "interfaceID"; private static final String SERVICE = "serviceID"; private static final String MEDIA = "media"; private static final String EVENTID = "eventid"; private static final String SELECT = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS"; private static final String NOTICE_ID = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS where NOTIFYID = ?"; private static final String SENT_TO = "SELECT userid, notifytime, media, contactinfo FROM usersnotified WHERE notifyid=?"; private static final String INSERT_NOTIFY = "INSERT INTO NOTIFICATIONS (notifyid, textmsg, numericmsg, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid) VALUES (NEXTVAL('notifyNxtId'), ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static final String OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE respondTime is NULL"; private static final String OUTSTANDING_COUNT = "SELECT COUNT(notifyid) AS TOTAL FROM NOTIFICATIONS WHERE respondTime is NULL"; private static final String USER_OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)"; private static final String USER_OUTSTANDING_COUNT = "SELECT COUNT(notifyid) AS TOTAL FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)"; /** * <p>getNoticeInfo</p> * * @param id a int. * @return a {@link org.opennms.web.notification.Notification} object. * @throws java.sql.SQLException if any. */ public Notification getNoticeInfo(int id) throws SQLException { Notification nbean = null; PreparedStatement pstmt = null; ResultSet rs = null; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { pstmt = conn.prepareStatement(NOTICE_ID); d.watch(pstmt); pstmt.setInt(1, id); rs = pstmt.executeQuery(); d.watch(rs); Notification[] n = rs2NotifyBean(conn, rs); if (n.length > 0) { nbean = n[0]; } else { nbean = new Notification(); } rs.close(); pstmt.close(); // create the list of users the page was sent to final PreparedStatement sentTo = conn.prepareStatement(SENT_TO); d.watch(sentTo); sentTo.setInt(1, id); final ResultSet sentToResults = sentTo.executeQuery(); d.watch(sentToResults); final List<NoticeSentTo> sentToList = new ArrayList<NoticeSentTo>(); while (sentToResults.next()) { NoticeSentTo newSentTo = new NoticeSentTo(); newSentTo.setUserId(sentToResults.getString(USERID)); Timestamp ts = sentToResults.getTimestamp(NOTICE_TIME); if (ts != null) { newSentTo.setTime(ts.getTime()); } else { newSentTo.setTime(0); } newSentTo.setMedia(sentToResults.getString(MEDIA)); newSentTo.setContactInfo(sentToResults.getString(CONTACT)); sentToList.add(newSentTo); } nbean.m_sentTo = sentToList; } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return nbean; } /** * <p>allNotifications</p> * * @return an array of {@link org.opennms.web.notification.Notification} objects. * @throws java.sql.SQLException if any. */ public Notification[] allNotifications() throws SQLException { return this.allNotifications(null); } /** * Return all notifications, both outstanding and acknowledged. * * @param order a {@link java.lang.String} object. * @return an array of {@link org.opennms.web.notification.Notification} objects. * @throws java.sql.SQLException if any. */ public Notification[] allNotifications(String order) throws SQLException { Notification[] notices = null; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final Statement stmt = conn.createStatement(); d.watch(stmt); // oh man this is lame, but it'll be a DAO soon right? right? :P String query = SELECT; if (order != null) { if (order.equalsIgnoreCase("asc")) { query += " ORDER BY pagetime ASC"; } else if (order.equalsIgnoreCase("desc")) { query += " ORDER BY pagetime DESC"; } } query += ";"; final ResultSet rs = stmt.executeQuery(query); d.watch(rs); notices = rs2NotifyBean(conn, rs); } catch (SQLException e) { LOG.error("allNotifications: Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return (notices); } private String getServiceName(Connection conn, Integer id) { if (id == null) { return null; } String serviceName = null; PreparedStatement ps = null; ResultSet rs = null; final DBUtils d = new DBUtils(getClass()); try { ps = conn.prepareStatement("SELECT servicename from service where serviceid = ?"); d.watch(ps); ps.setInt(1, id); rs = ps.executeQuery(); d.watch(rs); if (rs.next()) { serviceName = rs.getString("servicename"); } } catch (SQLException e) { LOG.warn("unable to get service name for service ID '{}'", id, e); } finally { d.cleanUp(); } return serviceName; } /** * Returns the data from the result set as an array of * Notification objects. The ResultSet must be positioned before * the first result before calling this method (this is the case right * after calling java.sql.Connection#createStatement and friends or * after calling java.sql.ResultSet#beforeFirst). * * @param conn a {@link java.sql.Connection} object. * @param rs a {@link java.sql.ResultSet} object. * @return an array of {@link org.opennms.web.notification.Notification} objects. * @throws java.sql.SQLException if any. */ protected Notification[] rs2NotifyBean(Connection conn, ResultSet rs) throws SQLException { Notification[] notices = null; Vector<Notification> vector = new Vector<Notification>(); try { while (rs.next()) { Notification nbean = new Notification(); nbean.m_timeReply = 0; nbean.m_txtMsg = rs.getString(TXT_MESG); nbean.m_numMsg = rs.getString(NUM_MESG); nbean.m_notifyID = rs.getInt(NOTIFY); if (rs.getTimestamp(TIME) != null) { nbean.m_timeSent = rs.getTimestamp(TIME).getTime(); } if (rs.getTimestamp(REPLYTIME) != null) { nbean.m_timeReply = rs.getTimestamp(REPLYTIME).getTime(); } nbean.m_responder = rs.getString(ANS_BY); nbean.m_nodeID = rs.getInt(NODE); nbean.m_interfaceID = rs.getString(INTERFACE); nbean.m_serviceId = rs.getInt(SERVICE); nbean.m_eventId = rs.getInt(EVENTID); nbean.m_serviceName = getServiceName(conn, nbean.m_serviceId); vector.addElement(nbean); } } catch (SQLException e) { LOG.error("Error occurred in rs2NotifyBean: {}", e, e); throw e; } notices = new Notification[vector.size()]; for (int i = 0; i < notices.length; i++) { notices[i] = vector.elementAt(i); } return notices; } /** * This method returns the count of all outstanding notices. * * @return an array of {@link org.opennms.web.notification.Notification} objects. * @throws java.sql.SQLException if any. */ public Notification[] getOutstandingNotices() throws SQLException { Notification[] notices = null; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final Statement stmt = conn.createStatement(); d.watch(stmt); final ResultSet rs = stmt.executeQuery(OUTSTANDING); d.watch(rs); notices = rs2NotifyBean(conn, rs); } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return notices; } /** * This method returns notices not yet acknowledged. * * @return a int. * @throws java.sql.SQLException if any. */ public int getOutstandingNoticeCount() throws SQLException { int count = 0; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final Statement stmt = conn.createStatement(); d.watch(stmt); final ResultSet rs = stmt.executeQuery(OUTSTANDING_COUNT); d.watch(rs); if (rs.next()) { count = rs.getInt("TOTAL"); } } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return count; } /** * This method returns notices not yet acknowledged. * * @param username a {@link java.lang.String} object. * @return a int. * @throws java.sql.SQLException if any. */ public int getOutstandingNoticeCount(String username) throws SQLException { if (username == null) { throw new IllegalArgumentException("Cannot take null parameters."); } int count = 0; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final PreparedStatement pstmt = conn.prepareStatement(USER_OUTSTANDING_COUNT); d.watch(pstmt); pstmt.setString(1, username); final ResultSet rs = pstmt.executeQuery(); d.watch(rs); if (rs.next()) { count = rs.getInt("TOTAL"); } } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return (count); } /** * This method returns notices not yet acknowledged. * * @param name a {@link java.lang.String} object. * @return an array of {@link org.opennms.web.notification.Notification} objects. * @throws java.sql.SQLException if any. */ public Notification[] getOutstandingNotices(String name) throws SQLException { Notification[] notices = null; final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final PreparedStatement pstmt = conn.prepareStatement(USER_OUTSTANDING); d.watch(pstmt); pstmt.setString(1, name); final ResultSet rs = pstmt.executeQuery(); d.watch(rs); notices = rs2NotifyBean(conn, rs); } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } return (notices); } /** * This method updates the table when the user acknowledges the pager * information. * * @param name a {@link java.lang.String} object. * @param noticeId a int. * @throws java.sql.SQLException if any. */ public void acknowledged(String name, int noticeId) throws SQLException { if (name == null) { throw new IllegalArgumentException("Cannot take null parameters."); } final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final PreparedStatement pstmt = conn.prepareStatement("UPDATE notifications SET respondtime = ? , answeredby = ? WHERE notifyid= ?"); d.watch(pstmt); pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); pstmt.setString(2, name); pstmt.setInt(3, noticeId); pstmt.execute(); } catch (SQLException e) { LOG.error("Problem acknowledging notification {} as answered by '{}': {}", noticeId, name, e, e); throw e; } finally { d.cleanUp(); } } /** * This method helps insert into the database. * * @param nbean a {@link org.opennms.web.notification.Notification} object. * @throws java.sql.SQLException if any. */ public void insert(Notification nbean) throws SQLException { if (nbean == null || nbean.m_txtMsg == null) { throw new IllegalArgumentException("Cannot take null parameters."); } final Connection conn = Vault.getDbConnection(); final DBUtils d = new DBUtils(getClass(), conn); try { final PreparedStatement pstmt = conn.prepareStatement(INSERT_NOTIFY); d.watch(pstmt); pstmt.setString(1, nbean.m_txtMsg); pstmt.setString(2, nbean.m_numMsg); pstmt.setLong(3, nbean.m_timeSent); pstmt.setLong(4, nbean.m_timeReply); pstmt.setString(5, nbean.m_responder); pstmt.setInt(6, nbean.m_nodeID); pstmt.setString(7, nbean.m_interfaceID); pstmt.setInt(8, nbean.m_serviceId); pstmt.setInt(9, nbean.m_eventId); pstmt.execute(); } catch (SQLException e) { LOG.error("Problem getting data from the notifications table: {}", e, e); throw e; } finally { d.cleanUp(); } } }
gpl-2.0
CancerCollaboratory/dockstore
dockstore-webservice/src/main/java/io/logstash/appender/LogstashAppenderFactory.java
3238
/* * Copyright 2017 OICR * * 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 io.logstash.appender; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.Appender; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import io.dropwizard.logging.AbstractAppenderFactory; import io.dropwizard.logging.async.AsyncAppenderFactory; import io.dropwizard.logging.filter.LevelFilterFactory; import io.dropwizard.logging.layout.LayoutFactory; import java.net.InetSocketAddress; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import net.logstash.logback.appender.LogstashTcpSocketAppender; import net.logstash.logback.encoder.LogstashEncoder; /** * Custom log appender that pushes the logs to logstash. * Specify the host and optional port in the application configuration file. */ @JsonTypeName("logstash") public class LogstashAppenderFactory extends AbstractAppenderFactory { private static final int MAX_PORT = 65535; private static final int MIN_PORT = 1; @NotNull protected String host; @Min(MIN_PORT) @Max(MAX_PORT) protected int port; @Min(MIN_PORT) @Max(MAX_PORT) public LogstashAppenderFactory() { this.port = LogstashTcpSocketAppender.DEFAULT_PORT; } @JsonProperty public String getHost() { return host; } @JsonProperty public void setHost(String host) { this.host = host; } @JsonProperty public int getPort() { return port; } @JsonProperty public void setPort(int port) { this.port = port; } @Override public Appender build(LoggerContext context, String s, LayoutFactory layoutFactory, LevelFilterFactory levelFilterFactory, AsyncAppenderFactory asyncAppenderFactory) { final LogstashTcpSocketAppender appender = new LogstashTcpSocketAppender(); final LogstashEncoder encoder = new LogstashEncoder(); encoder.setIncludeContext(true); // Mapped Diagnostic Context encoder.setIncludeMdc(true); encoder.setIncludeCallerData(false); appender.setContext(context); appender.addDestinations(new InetSocketAddress(host, port)); appender.setIncludeCallerData(false); appender.setQueueSize(LogstashTcpSocketAppender.DEFAULT_QUEUE_SIZE); appender.addFilter(levelFilterFactory.build(Level.ALL)); appender.setEncoder(encoder); encoder.start(); appender.start(); return wrapAsync(appender, asyncAppenderFactory); } }
gpl-2.0
MICSTI/my-mobile-music
src/at/micsti/mymusic/ChartArtistAdapter.java
1719
package at.micsti.mymusic; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ChartArtistAdapter extends ArrayAdapter<ChartArtist> { public ChartArtistAdapter(Context context, ArrayList<ChartArtist> artists) { super(context, R.layout.item_chart_artist, artists); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position ChartArtist chartArtist = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_chart_artist, parent, false); } // Lookup view for data population TextView artistRank = (TextView) convertView.findViewById(R.id.artistRank); TextView artistDiff = (TextView) convertView.findViewById(R.id.artistDiff); TextView artistName = (TextView) convertView.findViewById(R.id.artistName); TextView artistPlayCount = (TextView) convertView.findViewById(R.id.artistPlayCount); // Populate the data into the template view using the data object artistRank.setText(String.valueOf(chartArtist.getRank())); artistDiff.setText(String.valueOf(chartArtist.getRankDiff())); artistName.setText(chartArtist.getArtistName()); artistPlayCount.setText(String.valueOf(chartArtist.getPlayedCount())); // Return the completed view to render on screen return convertView; } }
gpl-2.0
tauprojects/mpp
src/main/java/org/deuce/transform/asm/ClassByteCode.java
457
package org.deuce.transform.asm; /** * A structure to hold a tuple of class and its bytecode. * @author guy * @since 1.1 */ public class ClassByteCode{ final private String className; final private byte[] bytecode; public ClassByteCode(String className, byte[] bytecode){ this.className = className; this.bytecode = bytecode; } public String getClassName() { return className; } public byte[] getBytecode() { return bytecode; } }
gpl-2.0
Myrninvollo/Server
src/net/minecraft/item/ItemBlock.java
4231
package net.minecraft.item; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.world.World; public class ItemBlock extends Item { protected final Block field_150939_a; private static final String __OBFID = "CL_00001772"; public ItemBlock(Block p_i45328_1_) { this.field_150939_a = p_i45328_1_; } /** * Sets the unlocalized name of this item to the string passed as the parameter, prefixed by "item." */ public ItemBlock setUnlocalizedName(String p_77655_1_) { super.setUnlocalizedName(p_77655_1_); return this; } /** * Callback for item usage. If the item does something special on right clicking, he will have one of those. Return * True if something happen and false if it don't. This is for ITEMS, not BLOCKS */ public boolean onItemUse(ItemStack p_77648_1_, EntityPlayer p_77648_2_, World p_77648_3_, int p_77648_4_, int p_77648_5_, int p_77648_6_, int p_77648_7_, float p_77648_8_, float p_77648_9_, float p_77648_10_) { Block var11 = p_77648_3_.getBlock(p_77648_4_, p_77648_5_, p_77648_6_); if (var11 == Blocks.snow_layer && (p_77648_3_.getBlockMetadata(p_77648_4_, p_77648_5_, p_77648_6_) & 7) < 1) { p_77648_7_ = 1; } else if (var11 != Blocks.vine && var11 != Blocks.tallgrass && var11 != Blocks.deadbush) { if (p_77648_7_ == 0) { --p_77648_5_; } if (p_77648_7_ == 1) { ++p_77648_5_; } if (p_77648_7_ == 2) { --p_77648_6_; } if (p_77648_7_ == 3) { ++p_77648_6_; } if (p_77648_7_ == 4) { --p_77648_4_; } if (p_77648_7_ == 5) { ++p_77648_4_; } } if (p_77648_1_.stackSize == 0) { return false; } else if (!p_77648_2_.canPlayerEdit(p_77648_4_, p_77648_5_, p_77648_6_, p_77648_7_, p_77648_1_)) { return false; } else if (p_77648_5_ == 255 && this.field_150939_a.getMaterial().isSolid()) { return false; } else if (p_77648_3_.func_147472_a(this.field_150939_a, p_77648_4_, p_77648_5_, p_77648_6_, false, p_77648_7_, p_77648_2_, p_77648_1_)) { int var12 = this.getMetadata(p_77648_1_.getItemDamage()); int var13 = this.field_150939_a.onBlockPlaced(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, p_77648_7_, p_77648_8_, p_77648_9_, p_77648_10_, var12); if (p_77648_3_.setBlock(p_77648_4_, p_77648_5_, p_77648_6_, this.field_150939_a, var13, 3)) { if (p_77648_3_.getBlock(p_77648_4_, p_77648_5_, p_77648_6_) == this.field_150939_a) { this.field_150939_a.onBlockPlacedBy(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, p_77648_2_, p_77648_1_); this.field_150939_a.onPostBlockPlaced(p_77648_3_, p_77648_4_, p_77648_5_, p_77648_6_, var13); } p_77648_3_.playSoundEffect((double)((float)p_77648_4_ + 0.5F), (double)((float)p_77648_5_ + 0.5F), (double)((float)p_77648_6_ + 0.5F), this.field_150939_a.stepSound.func_150496_b(), (this.field_150939_a.stepSound.getVolume() + 1.0F) / 2.0F, this.field_150939_a.stepSound.getFrequency() * 0.8F); --p_77648_1_.stackSize; } return true; } else { return false; } } /** * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have * different names based on their damage or NBT. */ public String getUnlocalizedName(ItemStack p_77667_1_) { return this.field_150939_a.getUnlocalizedName(); } /** * Returns the unlocalized name of this item. */ public String getUnlocalizedName() { return this.field_150939_a.getUnlocalizedName(); } }
gpl-2.0
dschultzca/RomRaider
src/main/java/com/romraider/logger/ecu/comms/io/protocol/LoggerProtocolDS2.java
2226
/* * RomRaider Open-Source Tuning, Logging and Reflashing * Copyright (C) 2006-2020 RomRaider.com * * 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 com.romraider.logger.ecu.comms.io.protocol; import java.util.Collection; import com.romraider.logger.ecu.comms.manager.PollingState; import com.romraider.logger.ecu.comms.query.EcuQuery; import com.romraider.logger.ecu.definition.Module; public interface LoggerProtocolDS2 extends LoggerProtocol { byte[] constructReadProcedureRequest(Module module, Collection<EcuQuery> queries); byte[] constructReadAddressResponse( Collection<EcuQuery> queries, int requestSize); byte[] constructReadGroupRequest( Module module, String group); byte[] constructReadGroupResponse( Collection<EcuQuery> queries, int requestSize); byte[] constructReadMemoryRequest( Module module, Collection<EcuQuery> queryList); byte[] constructReadMemoryRange(Module module, Collection<EcuQuery> queries, int length); public byte[] constructReadMemoryRangeResponse(int requestSize, int length); void processReadAddressResponse(Collection<EcuQuery> queries, byte[] response, PollingState pollState); void processReadMemoryRangeResponse(Collection<EcuQuery> queries, byte[] response); byte[] constructSetAddressRequest( Module module, Collection<EcuQuery> queryList); byte[] constructSetAddressResponse(int length); void validateSetAddressResponse(byte[] response); }
gpl-2.0
AcademicTorrents/AcademicTorrents-Downloader
vuze/com/aelitis/azureus/core/speedmanager/impl/v2/PingSpaceMon.java
7240
package com.aelitis.azureus.core.speedmanager.impl.v2; import org.gudy.azureus2.core3.util.SystemTime; import com.aelitis.azureus.core.speedmanager.SpeedManagerLimitEstimate; import com.aelitis.azureus.core.speedmanager.SpeedManagerPingMapper; import com.aelitis.azureus.core.speedmanager.SpeedManager; import com.aelitis.azureus.core.speedmanager.impl.SpeedManagerAlgorithmProviderAdapter; import java.util.List; import java.util.ArrayList; /** * Created on Jul 16, 2007 * Created by Alan Snyder * Copyright (C) 2007 Aelitis, All Rights Reserved. * <p/> * 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. * <p/> * AELITIS, SAS au capital de 63.529,40 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. */ public class PingSpaceMon { private static final long INTERVAL = 1000 * 60 * 15L; long nextCheck = System.currentTimeMillis() + INTERVAL; TransferMode mode; List listeners = new ArrayList();//List<PSMonitorListener> public void addListener(PSMonitorListener listener){ //don't register the same listener twice. for(int i=0; i<listeners.size(); i++){ PSMonitorListener t = (PSMonitorListener) listeners.get(i); if( t==listener ){ SpeedManagerLogger.trace("Not logging same listener twice. listener="+listener.toString()); return; } } listeners.add( listener ); } public boolean removeListener(PSMonitorListener listener){ return listeners.remove(listener); } boolean checkForLowerLimits(){ long curr = SystemTime.getCurrentTime(); if( curr > nextCheck ){ SpeedManagerLogger.trace("PingSpaceMon checking for lower limits."); for(int i=0; i<listeners.size(); i++ ){ PSMonitorListener l =(PSMonitorListener) listeners.get(i); if(l!=null){ l.notifyUpload( getUploadEstCapacity() ); }else{ SpeedManagerLogger.trace("listener index _"+i+"_ was null."); } } resetTimer(); return true; } return false; } /** * * @param tMode - * @return - true if is has a new mode, and the clock starts over. */ boolean updateStatus(TransferMode tMode){ if(mode==null){ mode=tMode; return true; } if( mode.getMode() != tMode.getMode() ){ mode = tMode; resetTimer(); return true; } return checkForLowerLimits(); }//updateStatus void resetTimer(){ long curr = SystemTime.getCurrentTime(); nextCheck = curr + INTERVAL; SpeedManagerLogger.trace("Monitor resetting time. Next check in interval."); } /** * Get the current estimated upload limit from the ping mapper. * @param - true if the long-term persistent result should be used. * @return - SpeedManagerLimitEstimate. */ public static SpeedManagerLimitEstimate getUploadLimit(boolean persistent){ try{ SMInstance pm = SMInstance.getInstance(); SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter(); SpeedManagerPingMapper persistentMap = adapter.getPingMapper(); SpeedManagerLimitEstimate upEst = persistentMap.getEstimatedUploadLimit(true); return upEst; }catch(Throwable t){ //log this event and SpeedManagerLogger.log( t.toString() ); t.printStackTrace(); //something to return 1 and -1.0f results. return new DefaultLimitEstimate(); } }//getUploadLimit public static SpeedManagerLimitEstimate getUploadEstCapacity() { try{ SMInstance pm = SMInstance.getInstance(); SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter(); SpeedManager sm = adapter.getSpeedManager(); SpeedManagerLimitEstimate upEstCapacity = sm.getEstimatedUploadCapacityBytesPerSec(); return upEstCapacity; }catch(Throwable t){ //log this event and SpeedManagerLogger.log( t.toString() ); t.printStackTrace(); //something to return 1 and -1.0f results. return new DefaultLimitEstimate(); } } /** * Get the current estimated download limit from the ping mapper. * @return - SpeedManagerLimitEstimate */ public static SpeedManagerLimitEstimate getDownloadLimit(){ try{ SMInstance pm = SMInstance.getInstance(); SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter(); SpeedManagerPingMapper persistentMap = adapter.getPingMapper(); SpeedManagerLimitEstimate downEst = persistentMap.getEstimatedDownloadLimit(true); return downEst; }catch(Throwable t){ //log this event and SpeedManagerLogger.log( t.toString() ); t.printStackTrace(); //something to return 0 and -1.0f results. return new DefaultLimitEstimate(); } }//getDownloadLimit /** * Get the estimated download capacity from the SpeedManager. * @return - SpeedManagerLimitEstimate */ public static SpeedManagerLimitEstimate getDownloadEstCapacity() { try{ SMInstance pm = SMInstance.getInstance(); SpeedManagerAlgorithmProviderAdapter adapter = pm.getAdapter(); SpeedManager sm = adapter.getSpeedManager(); SpeedManagerLimitEstimate downEstCapacity = sm.getEstimatedDownloadCapacityBytesPerSec(); return downEstCapacity; }catch(Throwable t){ //log this event and SpeedManagerLogger.log( t.toString() ); t.printStackTrace(); //something to return 0 and -1.0f results. return new DefaultLimitEstimate(); } } static class DefaultLimitEstimate implements SpeedManagerLimitEstimate { public int getBytesPerSec() { return 1; } public float getEstimateType() { return -1.0f; } public float getMetricRating() { return -1.0f; } public int[][] getSegments() { return new int[0][]; } public long getWhen(){ return(0);} public String getString() { return "default"; } }//class }
gpl-2.0
hbbpb/stanford-corenlp-gv
src/edu/stanford/nlp/ling/tokensregex/Env.java
14483
package edu.stanford.nlp.ling.tokensregex; import edu.stanford.nlp.ling.tokensregex.types.Expressions; import edu.stanford.nlp.ling.tokensregex.types.Tags; import edu.stanford.nlp.pipeline.CoreMapAggregator; import edu.stanford.nlp.pipeline.CoreMapAttributeAggregator; import java.util.function.Function; import edu.stanford.nlp.process.CoreLabelTokenFactory; import edu.stanford.nlp.util.Pair; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Holds environment variables to be used for compiling string into a pattern. * Use {@link EnvLookup} to perform actual lookup (it will provide reasonable defaults) * * <p> * Some of the types of variables to bind are: * <ul> * <li><code>SequencePattern</code> (compiled pattern)</li> * <li><code>PatternExpr</code> (sequence pattern expression - precompiled)</li> * <li><code>NodePattern</code> (pattern for matching one element)</li> * <li><code>Class</code> (binding of CoreMap attribute to java Class)</li> * </ul> * </p> */ public class Env { /** * Parser that converts a string into a SequencePattern. * @see edu.stanford.nlp.ling.tokensregex.parser.TokenSequenceParser */ SequencePattern.Parser parser; /** * Mapping of variable names to their values */ Map<String, Object> variables = new HashMap<>();//Generics.newHashMap(); /** * Mapping of per thread temporary variables to their values */ ThreadLocal<Map<String,Object>> threadLocalVariables = new ThreadLocal<>(); /** * Mapping of variables that can be expanded in a regular expression for strings, * to their regular expressions. * The variable name must start with "$" and include only the alphanumeric characters * (it should follow the pattern <code>$[A-Za-z0-9_]+</code>). * Each variable is mapped to a pair, consisting of the <code>Pattern</code> representing * the name of the variable to be replaced, and a <code>String</code> representing the * regular expression (escaped) that is used to replace the name of the variable. */ Map<String, Pair<Pattern,String>> stringRegexVariables = new HashMap<>();//Generics.newHashMap(); /** * Default parameters (used when reading in rules for {@link SequenceMatchRules}. */ public Map<String, Object> defaults = new HashMap<>();//Generics.newHashMap(); /** * Default flags to use for string regular expressions match * @see java.util.regex.Pattern#compile(String,int) */ public int defaultStringPatternFlags = 0; /** * Default flags to use for string literal match * @see NodePattern#CASE_INSENSITIVE */ public int defaultStringMatchFlags = 0; public Class sequenceMatchResultExtractor; public Class stringMatchResultExtractor; /** * Annotation key to use to getting tokens (default is CoreAnnotations.TokensAnnotation.class) */ public Class defaultTokensAnnotationKey; /** * Annotation key to use to getting text (default is CoreAnnotations.TextAnnotation.class) */ public Class defaultTextAnnotationKey; /** * List of keys indicating the per-token annotations (default is null). * If specified, each token will be annotated with the extracted results from the * {@link #defaultResultsAnnotationExtractor}. * If null, then individual tokens that are matched are not annotated. */ public List<Class> defaultTokensResultAnnotationKey; /** * List of keys indicating what fields should be annotated for the aggregated CoreMap. * If specified, the aggregated CoreMap is annotated with the extracted results from the * {@link #defaultResultsAnnotationExtractor}. * If null, then the aggregated CoreMap is not annotated. */ public List<Class> defaultResultAnnotationKey; /** * Annotation key to use during composite phase for storing matched sequences and to match against. */ public Class defaultNestedResultsAnnotationKey; /** * How should the tokens be aggregated when collapsing a sequence of tokens into one CoreMap */ public Map<Class, CoreMapAttributeAggregator> defaultTokensAggregators; private CoreMapAggregator defaultTokensAggregator; /** * Whether we should merge and output CoreLabels or not */ public boolean aggregateToTokens; /** * How annotations are extracted from the MatchedExpression. * If the result type is a List and more than one annotation key is specified, * then the result is paired with the annotation key. * Example: If annotation key is [ner,normalized] and result is [CITY,San Francisco] * then the final CoreMap will have ner=CITY, normalized=San Francisco. * Otherwise, the result is treated as one object (all keys will be assigned that value). */ Function<MatchedExpression,?> defaultResultsAnnotationExtractor; /** * Interface for performing custom binding of values to the environment */ public interface Binder { void init(String prefix, Properties props); void bind(Env env); } public Env(SequencePattern.Parser p) { this.parser = p; } public void initDefaultBindings() { bind("FALSE", Expressions.FALSE); bind("TRUE", Expressions.TRUE); bind("NIL", Expressions.NIL); bind("ENV", this); bind("tags", Tags.TagsAnnotation.class); } public Map<String, Object> getDefaults() { return defaults; } public void setDefaults(Map<String, Object> defaults) { this.defaults = defaults; } public Map<Class, CoreMapAttributeAggregator> getDefaultTokensAggregators() { return defaultTokensAggregators; } public void setDefaultTokensAggregators(Map<Class, CoreMapAttributeAggregator> defaultTokensAggregators) { this.defaultTokensAggregators = defaultTokensAggregators; } public CoreMapAggregator getDefaultTokensAggregator() { if (defaultTokensAggregator == null && (defaultTokensAggregators != null || aggregateToTokens)) { CoreLabelTokenFactory tokenFactory = (aggregateToTokens)? new CoreLabelTokenFactory():null; Map<Class, CoreMapAttributeAggregator> aggregators = defaultTokensAggregators; if (aggregators == null) { aggregators = CoreMapAttributeAggregator.DEFAULT_NUMERIC_TOKENS_AGGREGATORS; } defaultTokensAggregator = CoreMapAggregator.getAggregator(aggregators, null, tokenFactory); } return defaultTokensAggregator; } public Class getDefaultTextAnnotationKey() { return defaultTextAnnotationKey; } public void setDefaultTextAnnotationKey(Class defaultTextAnnotationKey) { this.defaultTextAnnotationKey = defaultTextAnnotationKey; } public Class getDefaultTokensAnnotationKey() { return defaultTokensAnnotationKey; } public void setDefaultTokensAnnotationKey(Class defaultTokensAnnotationKey) { this.defaultTokensAnnotationKey = defaultTokensAnnotationKey; } public List<Class> getDefaultTokensResultAnnotationKey() { return defaultTokensResultAnnotationKey; } public void setDefaultTokensResultAnnotationKey(Class... defaultTokensResultAnnotationKey) { this.defaultTokensResultAnnotationKey = Arrays.asList(defaultTokensResultAnnotationKey); } public void setDefaultTokensResultAnnotationKey(List<Class> defaultTokensResultAnnotationKey) { this.defaultTokensResultAnnotationKey = defaultTokensResultAnnotationKey; } public List<Class> getDefaultResultAnnotationKey() { return defaultResultAnnotationKey; } public void setDefaultResultAnnotationKey(Class... defaultResultAnnotationKey) { this.defaultResultAnnotationKey = Arrays.asList(defaultResultAnnotationKey); } public void setDefaultResultAnnotationKey(List<Class> defaultResultAnnotationKey) { this.defaultResultAnnotationKey = defaultResultAnnotationKey; } public Class getDefaultNestedResultsAnnotationKey() { return defaultNestedResultsAnnotationKey; } public void setDefaultNestedResultsAnnotationKey(Class defaultNestedResultsAnnotationKey) { this.defaultNestedResultsAnnotationKey = defaultNestedResultsAnnotationKey; } public Function<MatchedExpression, ?> getDefaultResultsAnnotationExtractor() { return defaultResultsAnnotationExtractor; } public void setDefaultResultsAnnotationExtractor(Function<MatchedExpression, ?> defaultResultsAnnotationExtractor) { this.defaultResultsAnnotationExtractor = defaultResultsAnnotationExtractor; } public Class getSequenceMatchResultExtractor() { return sequenceMatchResultExtractor; } public void setSequenceMatchResultExtractor(Class sequenceMatchResultExtractor) { this.sequenceMatchResultExtractor = sequenceMatchResultExtractor; } public Class getStringMatchResultExtractor() { return stringMatchResultExtractor; } public void setStringMatchResultExtractor(Class stringMatchResultExtractor) { this.stringMatchResultExtractor = stringMatchResultExtractor; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public void clearVariables() { this.variables.clear(); } public int getDefaultStringPatternFlags() { return defaultStringPatternFlags; } public void setDefaultStringPatternFlags(int defaultStringPatternFlags) { this.defaultStringPatternFlags = defaultStringPatternFlags; } public int getDefaultStringMatchFlags() { return defaultStringMatchFlags; } public void setDefaultStringMatchFlags(int defaultStringMatchFlags) { this.defaultStringMatchFlags = defaultStringMatchFlags; } private static final Pattern STRING_REGEX_VAR_NAME_PATTERN = Pattern.compile("\\$[A-Za-z0-9_]+"); public void bindStringRegex(String var, String regex) { // Enforce requirements on variable names ($alphanumeric_) if (!STRING_REGEX_VAR_NAME_PATTERN.matcher(var).matches()) { throw new IllegalArgumentException("StringRegex binding error: Invalid variable name " + var); } Pattern varPattern = Pattern.compile(Pattern.quote(var)); String replace = Matcher.quoteReplacement(regex); stringRegexVariables.put(var, new Pair<>(varPattern, replace)); } public String expandStringRegex(String regex) { // Replace all variables in regex String expanded = regex; for (Map.Entry<String, Pair<Pattern, String>> stringPairEntry : stringRegexVariables.entrySet()) { Pair<Pattern,String> p = stringPairEntry.getValue(); expanded = p.first().matcher(expanded).replaceAll(p.second()); } return expanded; } public Pattern getStringPattern(String regex) { String expanded = expandStringRegex(regex); return Pattern.compile(expanded, defaultStringPatternFlags); } public void bind(String name, Object obj) { if (obj != null) { variables.put(name, obj); } else { variables.remove(name); } } public void bind(String name, SequencePattern pattern) { bind(name, pattern.getPatternExpr()); } public void unbind(String name) { bind(name, null); } public NodePattern getNodePattern(String name) { Object obj = variables.get(name); if (obj != null) { if (obj instanceof SequencePattern) { SequencePattern seqPattern = (SequencePattern) obj; if (seqPattern.getPatternExpr() instanceof SequencePattern.NodePatternExpr) { return ((SequencePattern.NodePatternExpr) seqPattern.getPatternExpr()).nodePattern; } else { throw new Error("Invalid node pattern class: " + seqPattern.getPatternExpr().getClass() + " for variable " + name); } } else if (obj instanceof SequencePattern.NodePatternExpr) { SequencePattern.NodePatternExpr pe = (SequencePattern.NodePatternExpr) obj; return pe.nodePattern; } else if (obj instanceof NodePattern) { return (NodePattern) obj; } else if (obj instanceof String) { try { SequencePattern.NodePatternExpr pe = (SequencePattern.NodePatternExpr) parser.parseNode(this, (String) obj); return pe.nodePattern; } catch (Exception pex) { throw new RuntimeException("Error parsing " + obj + " to node pattern", pex); } } else { throw new Error("Invalid node pattern variable class: " + obj.getClass() + " for variable " + name); } } return null; } public SequencePattern.PatternExpr getSequencePatternExpr(String name, boolean copy) { Object obj = variables.get(name); if (obj != null) { if (obj instanceof SequencePattern) { SequencePattern seqPattern = (SequencePattern) obj; return seqPattern.getPatternExpr(); } else if (obj instanceof SequencePattern.PatternExpr) { SequencePattern.PatternExpr pe = (SequencePattern.PatternExpr) obj; return (copy)? pe.copy():pe; } else if (obj instanceof NodePattern) { return new SequencePattern.NodePatternExpr( (NodePattern) obj); } else if (obj instanceof String) { try { return parser.parseSequence(this, (String) obj); } catch (Exception pex) { throw new RuntimeException("Error parsing " + obj + " to sequence pattern", pex); } } else { throw new Error("Invalid sequence pattern variable class: " + obj.getClass()); } } return null; } public Object get(String name) { return variables.get(name); } // Functions for storing temporary thread specific variables // that are used when running tokensregex public void push(String name, Object value) { Map<String,Object> vars = threadLocalVariables.get(); if (vars == null) { threadLocalVariables.set(vars = new HashMap<>()); //Generics.newHashMap()); } Stack<Object> stack = (Stack<Object>) vars.get(name); if (stack == null) { vars.put(name, stack = new Stack<>()); } stack.push(value); } public Object pop(String name) { Map<String,Object> vars = threadLocalVariables.get(); if (vars == null) return null; Stack<Object> stack = (Stack<Object>) vars.get(name); if (stack == null || stack.isEmpty()) { return null; } else { return stack.pop(); } } public Object peek(String name) { Map<String,Object> vars = threadLocalVariables.get(); if (vars == null) return null; Stack<Object> stack = (Stack<Object>) vars.get(name); if (stack == null || stack.isEmpty()) { return null; } else { return stack.peek(); } } }
gpl-2.0
netroby/jdk9-shenandoah-hotspot
test/sanity/WhiteBox.java
2149
/* * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test WhiteBox * @bug 8011675 * @summary verify that whitebox can be used even if not all functions are declared in java-part * @author igor.ignatyev@oracle.com * @library /testlibrary * @compile WhiteBox.java * @run main ClassFileInstaller sun.hotspot.WhiteBox * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI sun.hotspot.WhiteBox * @clean sun.hotspot.WhiteBox */ package sun.hotspot; public class WhiteBox { private static native void registerNatives(); static { registerNatives(); } public native int notExistedMethod(); public native int getHeapOopSize(); public static void main(String[] args) { WhiteBox wb = new WhiteBox(); if (wb.getHeapOopSize() < 0) { throw new Error("wb.getHeapOopSize() < 0"); } boolean catched = false; try { wb.notExistedMethod(); } catch (UnsatisfiedLinkError e) { catched = true; } if (!catched) { throw new Error("wb.notExistedMethod() was invoked"); } } }
gpl-2.0
infinity0/proxy-doclet
src.orig/openjdk-6-src-b16-24_apr_2009/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java
5757
/* * Copyright 1997-2004 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.doclets.formats.html; import com.sun.javadoc.*; import com.sun.tools.doclets.internal.toolkit.util.*; import java.io.*; /** * This abstract class exists to provide functionality needed in the * the formatting of member information. Since AbstractSubWriter and its * subclasses control this, they would be the logical place to put this. * However, because each member type has its own subclass, subclassing * can not be used effectively to change formatting. The concrete * class subclass of this class can be subclassed to change formatting. * * @see AbstractMemberWriter * @see ClassWriterImpl * * @author Robert Field * @author Atul M Dambalkar */ public abstract class SubWriterHolderWriter extends HtmlDocletWriter { public SubWriterHolderWriter(ConfigurationImpl configuration, String filename) throws IOException { super(configuration, filename); } public SubWriterHolderWriter(ConfigurationImpl configuration, String path, String filename, String relpath) throws IOException { super(configuration, path, filename, relpath); } public void printTypeSummaryHeader() { tdIndex(); font("-1"); code(); } public void printTypeSummaryFooter() { codeEnd(); fontEnd(); tdEnd(); } public void printSummaryHeader(AbstractMemberWriter mw, ClassDoc cd) { mw.printSummaryAnchor(cd); tableIndexSummary(); tableHeaderStart("#CCCCFF"); mw.printSummaryLabel(cd); tableHeaderEnd(); } public void printTableHeadingBackground(String str) { tableIndexDetail(); tableHeaderStart("#CCCCFF", 1); bold(str); tableHeaderEnd(); tableEnd(); } public void printInheritedSummaryHeader(AbstractMemberWriter mw, ClassDoc cd) { mw.printInheritedSummaryAnchor(cd); tableIndexSummary(); tableInheritedHeaderStart("#EEEEFF"); mw.printInheritedSummaryLabel(cd); tableInheritedHeaderEnd(); trBgcolorStyle("white", "TableRowColor"); summaryRow(0); code(); } public void printSummaryFooter(AbstractMemberWriter mw, ClassDoc cd) { tableEnd(); space(); } public void printInheritedSummaryFooter(AbstractMemberWriter mw, ClassDoc cd) { codeEnd(); summaryRowEnd(); trEnd(); tableEnd(); space(); } protected void printIndexComment(Doc member) { printIndexComment(member, member.firstSentenceTags()); } protected void printIndexComment(Doc member, Tag[] firstSentenceTags) { Tag[] deprs = member.tags("deprecated"); if (Util.isDeprecated((ProgramElementDoc) member)) { boldText("doclet.Deprecated"); space(); if (deprs.length > 0) { printInlineDeprecatedComment(member, deprs[0]); } return; } else { ClassDoc cd = ((ProgramElementDoc)member).containingClass(); if (cd != null && Util.isDeprecated(cd)) { boldText("doclet.Deprecated"); space(); } } printSummaryComment(member, firstSentenceTags); } public void printSummaryLinkType(AbstractMemberWriter mw, ProgramElementDoc member) { trBgcolorStyle("white", "TableRowColor"); mw.printSummaryType(member); summaryRow(0); code(); } public void printSummaryLinkComment(AbstractMemberWriter mw, ProgramElementDoc member) { printSummaryLinkComment(mw, member, member.firstSentenceTags()); } public void printSummaryLinkComment(AbstractMemberWriter mw, ProgramElementDoc member, Tag[] firstSentenceTags) { codeEnd(); println(); br(); printNbsps(); printIndexComment(member, firstSentenceTags); summaryRowEnd(); trEnd(); } public void printInheritedSummaryMember(AbstractMemberWriter mw, ClassDoc cd, ProgramElementDoc member, boolean isFirst) { if (! isFirst) { mw.print(", "); } mw.writeInheritedSummaryLink(cd, member); } public void printMemberHeader() { hr(); } public void printMemberFooter() { } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/beans/src/test/support/java/org/apache/harmony/beans/tests/support/mock/MockNullSubClass.java
943
/* * 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.harmony.beans.tests.support.mock; public class MockNullSubClass extends MockNullSuperClass{ }
gpl-2.0
xiupitter/XiuConnectionManager
src/java/org/jivesoftware/multiplexer/ServerPacketReader.java
4394
/** * $RCSfile$ * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.multiplexer; import org.dom4j.Element; import org.dom4j.io.XMPPPacketReader; import org.jivesoftware.multiplexer.net.SocketConnection; import org.jivesoftware.util.JiveGlobals; import org.jivesoftware.util.Log; import java.io.IOException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Reads and processes stanzas sent from the server. Each connection to the server will * have an instance of this class. Read packets will be processed using a thread pool. * By default, the thread pool will have 5 processing threads. Configure the property * <tt>xmpp.manager.incoming.threads</tt> to change the number of processing threads * per connection to the server. * * @author Gaston Dombiak */ class ServerPacketReader implements SocketStatistic { private boolean open = true; private XMPPPacketReader reader = null; /** * Pool of threads that will process incoming stanzas from the server. */ private ThreadPoolExecutor threadPool; /** * Actual object responsible for handling incoming traffic. */ private ServerPacketHandler packetsHandler; public ServerPacketReader(XMPPPacketReader reader, SocketConnection connection, String address) { this.reader = reader; packetsHandler = new ServerPacketHandler(connection, address); init(); } private void init() { // Create a pool of threads that will process incoming packets. int maxThreads = JiveGlobals.getIntProperty("xmpp.manager.incoming.threads", 5); if (maxThreads < 1) { // Ensure that the max number of threads in the pool is at least 1 maxThreads = 1; } threadPool = new ThreadPoolExecutor(maxThreads, maxThreads, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy()); // Create a thread that will read and store DOM Elements. Thread thread = new Thread("Server Packet Reader") { public void run() { while (open) { Element doc; try { doc = reader.parseDocument().getRootElement(); if (doc == null) { // Stop reading the stream since the remote server has sent an end of // stream element and probably closed the connection. shutdown(); } else { // Queue task that process incoming stanzas threadPool.execute(new ProcessStanzaTask(packetsHandler, doc)); } } catch (IOException e) { Log.debug("Finishing Incoming Server Stanzas Reader.", e); shutdown(); } catch (Exception e) { Log.error("Finishing Incoming Server Stanzas Reader.", e); shutdown(); } } } }; thread.setDaemon(true); thread.start(); } public long getLastActive() { return reader.getLastActive(); } public void shutdown() { open = false; threadPool.shutdown(); } /** * Task that processes incoming stanzas from the server. */ private class ProcessStanzaTask implements Runnable { /** * Incoming stanza to process. */ private Element stanza; /** * Actual object responsible for handling incoming traffic. */ private ServerPacketHandler handler; public ProcessStanzaTask(ServerPacketHandler handler, Element stanza) { this.handler = handler; this.stanza = stanza; } public void run() { handler.handle(stanza); } } }
gpl-2.0
scoophealth/oscar
src/main/java/oscar/oscarMessenger/pageUtil/MsgViewPDFAction.java
2991
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarMessenger.pageUtil; import java.io.IOException; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.oscarehr.managers.SecurityInfoManager; import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; import oscar.util.Doc2PDF; public class MsgViewPDFAction extends Action { private SecurityInfoManager securityInfoManager = SpringUtils.getBean(SecurityInfoManager.class); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MsgViewPDFForm frm = (MsgViewPDFForm) form; if(!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_msg", "r", null)) { throw new SecurityException("missing required security object (_msg)"); } try { String pdfAttachment = ( String) request.getSession().getAttribute("PDFAttachment"); String id = frm.getFile_id(); int fileID = Integer.parseInt(id ); if ( pdfAttachment != null && pdfAttachment.length() != 0) { Vector attVector = Doc2PDF.getXMLTagValue(pdfAttachment, "CONTENT" ); String pdfFile = ( String) attVector.elementAt(fileID); Doc2PDF.PrintPDFFromBin ( response, pdfFile ); } } catch(Exception e) { MiscUtils.getLogger().error("Error", e); return ( mapping.findForward("success")); } return ( mapping.findForward("success")); } }
gpl-2.0
teamfx/openjfx-9-dev-rt
modules/javafx.web/src/ios/java/javafx/scene/web/WebView.java
38327
/* * Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.web; import javafx.css.CssMetaData; import javafx.css.StyleableBooleanProperty; import javafx.css.StyleableDoubleProperty; import javafx.css.StyleableObjectProperty; import javafx.css.StyleableProperty; import javafx.css.converter.BooleanConverter; import javafx.css.converter.EnumConverter; import javafx.css.converter.SizeConverter; import com.sun.javafx.geom.BaseBounds; import com.sun.javafx.geom.PickRay; import com.sun.javafx.geom.transform.Affine3D; import com.sun.javafx.geom.transform.BaseTransform; import com.sun.javafx.scene.DirtyBits; import com.sun.javafx.scene.NodeHelper; import com.sun.javafx.scene.input.PickResultChooser; import com.sun.java.scene.web.WebViewHelper; import com.sun.javafx.scene.SceneHelper; import com.sun.javafx.sg.prism.NGNode; import com.sun.javafx.tk.TKPulseListener; import com.sun.javafx.tk.Toolkit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javafx.beans.property.*; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.css.Styleable; import javafx.geometry.Bounds; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.text.FontSmoothingType; /** * {@code WebView} is a {@link javafx.scene.Node} that manages a * {@link WebEngine} and displays its content. The associated {@code WebEngine} * is created automatically at construction time and cannot be changed * afterwards. {@code WebView} handles mouse and some keyboard events, and * manages scrolling automatically, so there's no need to put it into a * {@code ScrollPane}. * * <p>{@code WebView} objects must be created and accessed solely from the * FX thread. * @since JavaFX 2.0 */ final public class WebView extends Parent { static { WebViewHelper.setWebViewAccessor(new WebViewHelper.WebViewAccessor() { @Override public NGNode doCreatePeer(Node node) { return ((WebView) node).doCreatePeer(); } @Override public void doUpdatePeer(Node node) { ((WebView) node).doUpdatePeer(); } @Override public void doTransformsChanged(Node node) { ((WebView) node).doTransformsChanged(); } @Override public BaseBounds doComputeGeomBounds(Node node, BaseBounds bounds, BaseTransform tx) { return ((WebView) node).doComputeGeomBounds(bounds, tx); } @Override public boolean doComputeContains(Node node, double localX, double localY) { return ((WebView) node).doComputeContains(localX, localY); } @Override public void doPickNodeLocal(Node node, PickRay localPickRay, PickResultChooser result) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } private static final boolean DEFAULT_CONTEXT_MENU_ENABLED = true; private static final FontSmoothingType DEFAULT_FONT_SMOOTHING_TYPE = FontSmoothingType.LCD; private static final double DEFAULT_ZOOM = 1.0; private static final double DEFAULT_FONT_SCALE = 1.0; private static final double DEFAULT_MIN_WIDTH = 0; private static final double DEFAULT_MIN_HEIGHT = 0; private static final double DEFAULT_PREF_WIDTH = 800; private static final double DEFAULT_PREF_HEIGHT = 600; private static final double DEFAULT_MAX_WIDTH = Double.MAX_VALUE; private static final double DEFAULT_MAX_HEIGHT = Double.MAX_VALUE; private final WebEngine engine; // pointer to native WebViewImpl private final long handle; /** * The stage pulse listener registered with the toolkit. * This field guarantees that the listener will exist throughout * the whole lifetime of the WebView node. This field is necessary * because the toolkit references its stage pulse listeners weakly. */ private final TKPulseListener stagePulseListener; /** * Returns the {@code WebEngine} object. */ public final WebEngine getEngine() { return engine; } private final ReadOnlyDoubleWrapper width = new ReadOnlyDoubleWrapper(this, "width"); /** * Returns width of this {@code WebView}. */ public final double getWidth() { return width.get(); } /** * Width of this {@code WebView}. */ public ReadOnlyDoubleProperty widthProperty() { return width.getReadOnlyProperty(); } private final ReadOnlyDoubleWrapper height = new ReadOnlyDoubleWrapper(this, "height"); /** * Returns height of this {@code WebView}. */ public final double getHeight() { return height.get(); } /** * Height of this {@code WebView}. */ public ReadOnlyDoubleProperty heightProperty() { return height.getReadOnlyProperty(); } /** * Zoom factor applied to the whole page contents. * * @defaultValue 1.0 */ private DoubleProperty zoom; /** * Sets current zoom factor applied to the whole page contents. * @param value zoom factor to be set * @see #zoomProperty() * @see #getZoom() * @since JavaFX 8.0 */ public final void setZoom(double value) { WebEngine.checkThread(); zoomProperty().set(value); } /** * Returns current zoom factor applied to the whole page contents. * @return current zoom factor * @see #zoomProperty() * @see #setZoom(double value) * @since JavaFX 8.0 */ public final double getZoom() { return (this.zoom != null) ? this.zoom.get() : DEFAULT_ZOOM; } /** * Returns zoom property object. * @return zoom property object * @see #getZoom() * @see #setZoom(double value) * @since JavaFX 8.0 */ public final DoubleProperty zoomProperty() { if (zoom == null) { zoom = new StyleableDoubleProperty(DEFAULT_ZOOM) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.ZOOM; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "zoom"; } }; } return zoom; } /** * Specifies scale factor applied to font. This setting affects * text content but not images and fixed size elements. * * @defaultValue 1.0 */ private DoubleProperty fontScale; public final void setFontScale(double value) { WebEngine.checkThread(); fontScaleProperty().set(value); } public final double getFontScale() { return (this.fontScale != null) ? this.fontScale.get() : DEFAULT_FONT_SCALE; } public DoubleProperty fontScaleProperty() { if (fontScale == null) { fontScale = new StyleableDoubleProperty(DEFAULT_FONT_SCALE) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.FONT_SCALE; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "fontScale"; } }; } return fontScale; } /** * Creates a {@code WebView} object. */ public WebView() { long[] nativeHandle = new long[1]; _initWebView(nativeHandle); getStyleClass().add("web-view"); handle = nativeHandle[0]; engine = new WebEngine(); engine.setView(this); stagePulseListener = () -> { handleStagePulse(); }; focusedProperty().addListener((ov, t, t1) -> { }); Toolkit.getToolkit().addStageTkPulseListener(stagePulseListener); final ChangeListener<Bounds> chListener = new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) { NodeHelper.transformsChanged(WebView.this); } }; parentProperty().addListener(new ChangeListener<Parent>(){ @Override public void changed(ObservableValue<? extends Parent> observable, Parent oldValue, Parent newValue) { if (oldValue != null && newValue == null) { // webview has been removed from scene _removeWebView(handle); } if (oldValue != null) { do { oldValue.boundsInParentProperty().removeListener(chListener); oldValue = oldValue.getParent(); } while (oldValue != null); } if (newValue != null) { do { final Node n = newValue; newValue.boundsInParentProperty().addListener(chListener); newValue = newValue.getParent(); } while (newValue != null); } } }); layoutBoundsProperty().addListener(new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> observable, Bounds oldValue, Bounds newValue) { Affine3D trans = calculateNodeToSceneTransform(WebView.this); _setTransform(handle, trans.getMxx(), trans.getMxy(), trans.getMxz(), trans.getMxt(), trans.getMyx(), trans.getMyy(), trans.getMyz(), trans.getMyt(), trans.getMzx(), trans.getMzy(), trans.getMzz(), trans.getMzt()); } }); impl_treeVisibleProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { _setVisible(handle, newValue); } }); } // Resizing support. Allows arbitrary growing and shrinking. // Designed after javafx.scene.control.Control @Override public boolean isResizable() { return true; } @Override public void resize(double width, double height) { this.width.set(width); this.height.set(height); NodeHelper.markDirty(this, DirtyBits.NODE_GEOMETRY); NodeHelper.geomChanged(this); _setWidth(handle, width); _setHeight(handle, height); } /** * Called during layout to determine the minimum width for this node. * * @return the minimum width that this node should be resized to during layout */ @Override public final double minWidth(double height) { return getMinWidth(); } /** * Called during layout to determine the minimum height for this node. * * @return the minimum height that this node should be resized to during layout */ @Override public final double minHeight(double width) { return getMinHeight(); } /** * Called during layout to determine the preferred width for this node. * * @return the preferred width that this node should be resized to during layout */ @Override public final double prefWidth(double height) { return getPrefWidth(); } /** * Called during layout to determine the preferred height for this node. * * @return the preferred height that this node should be resized to during layout */ @Override public final double prefHeight(double width) { return getPrefHeight(); } /** * Called during layout to determine the maximum width for this node. * * @return the maximum width that this node should be resized to during layout */ @Override public final double maxWidth(double height) { return getMaxWidth(); } /** * Called during layout to determine the maximum height for this node. * * @return the maximum height that this node should be resized to during layout */ @Override public final double maxHeight(double width) { return getMaxHeight(); } /** * Minimum width property. */ public DoubleProperty minWidthProperty() { if (minWidth == null) { minWidth = new StyleableDoubleProperty(DEFAULT_MIN_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MIN_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "minWidth"; } }; } return minWidth; } private DoubleProperty minWidth; /** * Sets minimum width. */ public final void setMinWidth(double value) { minWidthProperty().set(value); _setWidth(handle, value); } /** * Returns minimum width. */ public final double getMinWidth() { return (this.minWidth != null) ? this.minWidth.get() : DEFAULT_MIN_WIDTH; } /** * Minimum height property. */ public DoubleProperty minHeightProperty() { if (minHeight == null) { minHeight = new StyleableDoubleProperty(DEFAULT_MIN_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MIN_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "minHeight"; } }; } return minHeight; } private DoubleProperty minHeight; /** * Sets minimum height. */ public final void setMinHeight(double value) { minHeightProperty().set(value); _setHeight(handle, value); } /** * Sets minimum height. */ public final double getMinHeight() { return (this.minHeight != null) ? this.minHeight.get() : DEFAULT_MIN_HEIGHT; } /** * Convenience method for setting minimum width and height. */ public void setMinSize(double minWidth, double minHeight) { setMinWidth(minWidth); setMinHeight(minHeight); _setWidth(handle, minWidth); _setHeight(handle, minHeight); } /** * Preferred width property. */ public DoubleProperty prefWidthProperty() { if (prefWidth == null) { prefWidth = new StyleableDoubleProperty(DEFAULT_PREF_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.PREF_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "prefWidth"; } }; } return prefWidth; } private DoubleProperty prefWidth; /** * Sets preferred width. */ public final void setPrefWidth(double value) { prefWidthProperty().set(value); _setWidth(handle, value); } /** * Returns preferred width. */ public final double getPrefWidth() { return (this.prefWidth != null) ? this.prefWidth.get() : DEFAULT_PREF_WIDTH; } /** * Preferred height property. */ public DoubleProperty prefHeightProperty() { if (prefHeight == null) { prefHeight = new StyleableDoubleProperty(DEFAULT_PREF_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.PREF_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "prefHeight"; } }; } return prefHeight; } private DoubleProperty prefHeight; /** * Sets preferred height. */ public final void setPrefHeight(double value) { prefHeightProperty().set(value); _setHeight(handle, value); } /** * Returns preferred height. */ public final double getPrefHeight() { return (this.prefHeight != null) ? this.prefHeight.get() : DEFAULT_PREF_HEIGHT; } /** * Convenience method for setting preferred width and height. */ public void setPrefSize(double prefWidth, double prefHeight) { setPrefWidth(prefWidth); setPrefHeight(prefHeight); _setWidth(handle, prefWidth); _setHeight(handle, prefHeight); } /** * Maximum width property. */ public DoubleProperty maxWidthProperty() { if (maxWidth == null) { maxWidth = new StyleableDoubleProperty(DEFAULT_MAX_WIDTH) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MAX_WIDTH; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "maxWidth"; } }; } return maxWidth; } private DoubleProperty maxWidth; /** * Sets maximum width. */ public final void setMaxWidth(double value) { maxWidthProperty().set(value); _setWidth(handle, value); } /** * Returns maximum width. */ public final double getMaxWidth() { return (this.maxWidth != null) ? this.maxWidth.get() : DEFAULT_MAX_WIDTH; } /** * Maximum height property. */ public DoubleProperty maxHeightProperty() { if (maxHeight == null) { maxHeight = new StyleableDoubleProperty(DEFAULT_MAX_HEIGHT) { @Override public void invalidated() { if (getParent() != null) { getParent().requestLayout(); } } @Override public CssMetaData<WebView, Number> getCssMetaData() { return StyleableProperties.MAX_HEIGHT; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "maxHeight"; } }; } return maxHeight; } private DoubleProperty maxHeight; /** * Sets maximum height. */ public final void setMaxHeight(double value) { maxHeightProperty().set(value); _setHeight(handle, value); } /** * Returns maximum height. */ public final double getMaxHeight() { return (this.maxHeight != null) ? this.maxHeight.get() : DEFAULT_MAX_HEIGHT; } /** * Convenience method for setting maximum width and height. */ public void setMaxSize(double maxWidth, double maxHeight) { setMaxWidth(maxWidth); setMaxHeight(maxHeight); _setWidth(handle, maxWidth); _setHeight(handle, maxHeight); } /** * Specifies a requested font smoothing type : gray or LCD. * * The width of the bounding box is defined by the widest row. * * Note: LCD mode doesn't apply in numerous cases, such as various * compositing modes, where effects are applied and very large glyphs. * * @defaultValue FontSmoothingType.LCD * @since JavaFX 2.2 */ private ObjectProperty<FontSmoothingType> fontSmoothingType; public final void setFontSmoothingType(FontSmoothingType value) { fontSmoothingTypeProperty().set(value); } public final FontSmoothingType getFontSmoothingType() { return (this.fontSmoothingType != null) ? this.fontSmoothingType.get() : DEFAULT_FONT_SMOOTHING_TYPE; } public final ObjectProperty<FontSmoothingType> fontSmoothingTypeProperty() { if (this.fontSmoothingType == null) { this.fontSmoothingType = new StyleableObjectProperty<FontSmoothingType>(DEFAULT_FONT_SMOOTHING_TYPE) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, FontSmoothingType> getCssMetaData() { return StyleableProperties.FONT_SMOOTHING_TYPE; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "fontSmoothingType"; } }; } return this.fontSmoothingType; } /** * Specifies whether context menu is enabled. * * @defaultValue true * @since JavaFX 2.2 */ private BooleanProperty contextMenuEnabled; public final void setContextMenuEnabled(boolean value) { contextMenuEnabledProperty().set(value); } public final boolean isContextMenuEnabled() { return contextMenuEnabled == null ? DEFAULT_CONTEXT_MENU_ENABLED : contextMenuEnabled.get(); } public final BooleanProperty contextMenuEnabledProperty() { if (contextMenuEnabled == null) { contextMenuEnabled = new StyleableBooleanProperty(DEFAULT_CONTEXT_MENU_ENABLED) { @Override public void invalidated() { Toolkit.getToolkit().checkFxUserThread(); } @Override public CssMetaData<WebView, Boolean> getCssMetaData() { return StyleableProperties.CONTEXT_MENU_ENABLED; } @Override public Object getBean() { return WebView.this; } @Override public String getName() { return "contextMenuEnabled"; } }; } return contextMenuEnabled; } /** * Super-lazy instantiation pattern from Bill Pugh. */ private static final class StyleableProperties { private static final CssMetaData<WebView, Boolean> CONTEXT_MENU_ENABLED = new CssMetaData<WebView, Boolean>( "-fx-context-menu-enabled", BooleanConverter.getInstance(), DEFAULT_CONTEXT_MENU_ENABLED) { @Override public boolean isSettable(WebView view) { return view.contextMenuEnabled == null || !view.contextMenuEnabled.isBound(); } @Override public StyleableProperty<Boolean> getStyleableProperty(WebView view) { return (StyleableProperty<Boolean>)view.contextMenuEnabledProperty(); } }; private static final CssMetaData<WebView, FontSmoothingType> FONT_SMOOTHING_TYPE = new CssMetaData<WebView, FontSmoothingType>( "-fx-font-smoothing-type", new EnumConverter<FontSmoothingType>(FontSmoothingType.class), DEFAULT_FONT_SMOOTHING_TYPE) { @Override public boolean isSettable(WebView view) { return view.fontSmoothingType == null || !view.fontSmoothingType.isBound(); } @Override public StyleableProperty<FontSmoothingType> getStyleableProperty(WebView view) { return (StyleableProperty<FontSmoothingType>)view.fontSmoothingTypeProperty(); } }; private static final CssMetaData<WebView, Number> ZOOM = new CssMetaData<WebView, Number>( "-fx-zoom", SizeConverter.getInstance(), DEFAULT_ZOOM) { @Override public boolean isSettable(WebView view) { return view.zoom == null || !view.zoom.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.zoomProperty(); } }; private static final CssMetaData<WebView, Number> FONT_SCALE = new CssMetaData<WebView, Number>( "-fx-font-scale", SizeConverter.getInstance(), DEFAULT_FONT_SCALE) { @Override public boolean isSettable(WebView view) { return view.fontScale == null || !view.fontScale.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.fontScaleProperty(); } }; private static final CssMetaData<WebView, Number> MIN_WIDTH = new CssMetaData<WebView, Number>( "-fx-min-width", SizeConverter.getInstance(), DEFAULT_MIN_WIDTH) { @Override public boolean isSettable(WebView view) { return view.minWidth == null || !view.minWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.minWidthProperty(); } }; private static final CssMetaData<WebView, Number> MIN_HEIGHT = new CssMetaData<WebView, Number>( "-fx-min-height", SizeConverter.getInstance(), DEFAULT_MIN_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.minHeight == null || !view.minHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.minHeightProperty(); } }; private static final CssMetaData<WebView, Number> MAX_WIDTH = new CssMetaData<WebView, Number>( "-fx-max-width", SizeConverter.getInstance(), DEFAULT_MAX_WIDTH) { @Override public boolean isSettable(WebView view) { return view.maxWidth == null || !view.maxWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.maxWidthProperty(); } }; private static final CssMetaData<WebView, Number> MAX_HEIGHT = new CssMetaData<WebView, Number>( "-fx-max-height", SizeConverter.getInstance(), DEFAULT_MAX_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.maxHeight == null || !view.maxHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.maxHeightProperty(); } }; private static final CssMetaData<WebView, Number> PREF_WIDTH = new CssMetaData<WebView, Number>( "-fx-pref-width", SizeConverter.getInstance(), DEFAULT_PREF_WIDTH) { @Override public boolean isSettable(WebView view) { return view.prefWidth == null || !view.prefWidth.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.prefWidthProperty(); } }; private static final CssMetaData<WebView, Number> PREF_HEIGHT = new CssMetaData<WebView, Number>( "-fx-pref-height", SizeConverter.getInstance(), DEFAULT_PREF_HEIGHT) { @Override public boolean isSettable(WebView view) { return view.prefHeight == null || !view.prefHeight.isBound(); } @Override public StyleableProperty<Number> getStyleableProperty(WebView view) { return (StyleableProperty<Number>)view.prefHeightProperty(); } }; private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES; static { List<CssMetaData<? extends Styleable, ?>> styleables = new ArrayList<CssMetaData<? extends Styleable, ?>>(Parent.getClassCssMetaData()); styleables.add(CONTEXT_MENU_ENABLED); styleables.add(FONT_SMOOTHING_TYPE); styleables.add(ZOOM); styleables.add(FONT_SCALE); styleables.add(MIN_WIDTH); styleables.add(PREF_WIDTH); styleables.add(MAX_WIDTH); styleables.add(MIN_HEIGHT); styleables.add(PREF_HEIGHT); styleables.add(MAX_HEIGHT); STYLEABLES = Collections.unmodifiableList(styleables); } } /** * @return The CssMetaData associated with this class, which may include the * CssMetaData of its superclasses. * @since JavaFX 8.0 */ public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() { return StyleableProperties.STYLEABLES; } /** * {@inheritDoc} * @since JavaFX 8.0 */ @Override public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() { return getClassCssMetaData(); } // event handling private void handleStagePulse() { // The stage pulse occurs before the scene pulse. // Here the page content is updated before CSS/Layout/Sync pass // is initiated by the scene pulse. The update may // change the WebView children and, if so, the children should be // processed right away during the scene pulse. // The WebView node does not render its pending render queues // while it is invisible. Therefore, we should not schedule new // render queues while the WebView is invisible to prevent // the list of render queues from growing infinitely. // Also, if and when the WebView becomes invisible, the currently // pending render queues, if any, become obsolete and should be // discarded. boolean reallyVisible = impl_isTreeVisible() && getScene() != null && getScene().getWindow() != null && getScene().getWindow().isShowing(); if (reallyVisible) { if (NodeHelper.isDirty(this, DirtyBits.WEBVIEW_VIEW)) { SceneHelper.setAllowPGAccess(true); //getPGWebView().update(); // creates new render queues SceneHelper.setAllowPGAccess(false); } } else { _setVisible(handle, false); } } @Override protected ObservableList<Node> getChildren() { return super.getChildren(); } // Node stuff /* * Note: This method MUST only be called via its accessor method. */ private NGNode doCreatePeer() { // return new NGWebView(); return null; // iOS doesn't need this method. } /* * Note: This method MUST only be called via its accessor method. */ private BaseBounds doComputeGeomBounds(BaseBounds bounds, BaseTransform tx) { bounds.deriveWithNewBounds(0, 0, 0, (float) getWidth(), (float)getHeight(), 0); tx.transform(bounds, bounds); return bounds; } /* * Note: This method MUST only be called via its accessor method. */ private boolean doComputeContains(double localX, double localY) { // Note: Local bounds contain test is already done by the caller. (Node.contains()). return true; } /* * Note: This method MUST only be called via its accessor method. */ private void doUpdatePeer() { //PGWebView peer = getPGWebView(); if (NodeHelper.isDirty(this, DirtyBits.NODE_GEOMETRY)) { //peer.resize((float)getWidth(), (float)getHeight()); } if (NodeHelper.isDirty(this, DirtyBits.WEBVIEW_VIEW)) { //peer.requestRender(); } } private static Affine3D calculateNodeToSceneTransform(Node node) { final Affine3D transform = new Affine3D(); do { transform.preConcatenate(NodeHelper.getLeafTransform(node)); node = node.getParent(); } while (node != null); return transform; } /* * Note: This method MUST only be called via its accessor method. */ private void doTransformsChanged() { Affine3D trans = calculateNodeToSceneTransform(this); _setTransform(handle, trans.getMxx(), trans.getMxy(), trans.getMxz(), trans.getMxt(), trans.getMyx(), trans.getMyy(), trans.getMyz(), trans.getMyt(), trans.getMzx(), trans.getMzy(), trans.getMzz(), trans.getMzt()); } long getNativeHandle() { return handle; } // native callbacks private void notifyLoadStarted() { engine.notifyLoadStarted(); } private void notifyLoadFinished(String loc, String content) { engine.notifyLoadFinished(loc, content); } private void notifyLoadFailed() { engine.notifyLoadFailed(); } private void notifyJavaCall(String arg) { engine.notifyJavaCall(arg); } /* Inits native WebView and returns its pointer in the given array */ private native void _initWebView(long[] nativeHandle); /* Sets width of the native WebView */ private native void _setWidth(long handle, double w); /* Sets height of the native WebView */ private native void _setHeight(long handle, double h); /* Sets visibility of the native WebView */ private native void _setVisible(long handle, boolean v); /* Removes the native WebView from scene */ private native void _removeWebView(long handle); /* Applies transform on the native WebView */ private native void _setTransform(long handle, double mxx, double mxy, double mxz, double mxt, double myx, double myy, double myz, double myt, double mzx, double mzy, double mzz, double mzt); }
gpl-2.0
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/swing/src/main/java/common/javax/swing/AbstractButton.java
32559
/* * 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 javax.swing; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.ItemSelectable; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.Serializable; import javax.accessibility.AccessibleAction; import javax.accessibility.AccessibleExtendedComponent; import javax.accessibility.AccessibleIcon; import javax.accessibility.AccessibleKeyBinding; import javax.accessibility.AccessibleRelationSet; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; import javax.accessibility.AccessibleText; import javax.accessibility.AccessibleValue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.ButtonUI; import javax.swing.plaf.InsetsUIResource; import javax.swing.plaf.UIResource; import javax.swing.text.AttributeSet; import org.apache.harmony.x.swing.ButtonCommons; import org.apache.harmony.x.swing.StringConstants; import org.apache.harmony.x.swing.Utilities; import org.apache.harmony.x.swing.internal.nls.Messages; /** * <p> * <i>AbstractButton</i> * </p> * <h3>Implementation Notes:</h3> * <ul> * <li>The <code>serialVersionUID</code> fields are explicitly declared as a performance * optimization, not as a guarantee of serialization compatibility.</li> * </ul> */ public abstract class AbstractButton extends JComponent implements ItemSelectable, SwingConstants { protected abstract class AccessibleAbstractButton extends AccessibleJComponent implements AccessibleAction, AccessibleValue, AccessibleText, AccessibleExtendedComponent, Serializable { @Override public AccessibleKeyBinding getAccessibleKeyBinding() { return null; } public int getAccessibleActionCount() { return 1; } @Override public String getToolTipText() { return AbstractButton.this.getToolTipText(); } @Override public AccessibleValue getAccessibleValue() { return this; } @Override public AccessibleText getAccessibleText() { return null; } @Override public String getAccessibleName() { return (super.getAccessibleName() != null) ? super.getAccessibleName() : getText(); } @Override public AccessibleRelationSet getAccessibleRelationSet() { return super.getAccessibleRelationSet(); } @Override public String getTitledBorderText() { return super.getTitledBorderText(); } @Override public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet set = super.getAccessibleStateSet(); if (isSelected()) { set.add(AccessibleState.CHECKED); } return set; } @Override public AccessibleIcon[] getAccessibleIcon() { if (icon != null && icon instanceof ImageIcon) { return new AccessibleIcon[] { (AccessibleIcon) ((ImageIcon) icon) .getAccessibleContext() }; } return null; } @Override public AccessibleAction getAccessibleAction() { return this; } public boolean doAccessibleAction(int index) { if (0 <= index && index < getAccessibleActionCount()) { return true; } return false; } public String getAccessibleActionDescription(int index) { if (0 <= index && index < getAccessibleActionCount()) { return "click"; } return null; } public Number getCurrentAccessibleValue() { return (AbstractButton.this.isSelected()) ? new Integer(1) : new Integer(0); } public Number getMaximumAccessibleValue() { return new Integer(1); } public Number getMinimumAccessibleValue() { return new Integer(0); } public boolean setCurrentAccessibleValue(Number value) { boolean valueSet = (value.intValue() == 0) ? false : true; if (valueSet != isSelected()) { setSelected(valueSet); if (valueSet) { firePropertyChange("AccessibleState", null, AccessibleState.SELECTED); firePropertyChange("AccessibleValue", new Integer(0), new Integer(1)); } else { firePropertyChange("AccessibleState", AccessibleState.SELECTED, null); firePropertyChange("AccessibleValue", new Integer(1), new Integer(0)); } } return true; } public int getCaretPosition() { return -1; } public int getCharCount() { String text = AbstractButton.this.getText(); return (text != null) ? text.length() : 0; } public int getSelectionEnd() { return -1; } public int getSelectionStart() { return -1; } public int getIndexAtPoint(Point point) { return -1; } public Rectangle getCharacterBounds(int arg0) { return null; } public String getSelectedText() { return null; } public String getAfterIndex(int part, int index) { return null; } public String getAtIndex(int part, int index) { return null; } public String getBeforeIndex(int part, int index) { return null; } public AttributeSet getCharacterAttribute(int index) { return null; } }; protected class ButtonChangeListener implements ChangeListener, Serializable { private static final long serialVersionUID = 1L; private ButtonChangeListener() { } public void stateChanged(ChangeEvent event) { int mn = model.getMnemonic(); updateMnemonic(mn, Utilities.keyCodeToKeyChar(mn)); fireStateChanged(); } }; private final class ActionAndModelListener implements ItemListener, ActionListener, PropertyChangeListener, Serializable { private static final long serialVersionUID = 1L; public void itemStateChanged(ItemEvent event) { fireItemStateChanged(event); } public void actionPerformed(ActionEvent event) { fireActionPerformed(event); } public void propertyChange(PropertyChangeEvent event) { configurePropertyFromAction((Action) event.getSource(), event.getPropertyName()); } }; public static final String MODEL_CHANGED_PROPERTY = "model"; public static final String TEXT_CHANGED_PROPERTY = "text"; public static final String MNEMONIC_CHANGED_PROPERTY = "mnemonic"; public static final String MARGIN_CHANGED_PROPERTY = "margin"; public static final String VERTICAL_ALIGNMENT_CHANGED_PROPERTY = "verticalAlignment"; public static final String HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY = "horizontalAlignment"; public static final String VERTICAL_TEXT_POSITION_CHANGED_PROPERTY = "verticalTextPosition"; public static final String HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY = "horizontalTextPosition"; public static final String BORDER_PAINTED_CHANGED_PROPERTY = "borderPainted"; public static final String FOCUS_PAINTED_CHANGED_PROPERTY = "focusPainted"; public static final String ROLLOVER_ENABLED_CHANGED_PROPERTY = "rolloverEnabled"; public static final String CONTENT_AREA_FILLED_CHANGED_PROPERTY = "contentAreaFilled"; public static final String ICON_CHANGED_PROPERTY = "icon"; public static final String PRESSED_ICON_CHANGED_PROPERTY = "pressedIcon"; public static final String SELECTED_ICON_CHANGED_PROPERTY = "selectedIcon"; public static final String ROLLOVER_ICON_CHANGED_PROPERTY = "rolloverIcon"; public static final String ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY = "rolloverSelectedIcon"; public static final String DISABLED_ICON_CHANGED_PROPERTY = "disabledIcon"; public static final String DISABLED_SELECTED_ICON_CHANGED_PROPERTY = "disabledSelectedIcon"; private static final Object ALL_ACTION_PROPERTIES = new Object() { // $NON-LOCK-1$ @Override public boolean equals(Object o) { return true; } }; private static final Action CLEAR_ACTION_PROPERTIES = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { } @Override public void putValue(String name, Object value) { } @Override public void setEnabled(boolean enabled) { } }; protected transient ChangeEvent changeEvent = new ChangeEvent(this); protected ButtonModel model; protected ChangeListener changeListener = createChangeListener(); protected ActionListener actionListener = createActionListener(); protected ItemListener itemListener = createItemListener(); private PropertyChangeListener actionPropertyChangeListener; private ActionAndModelListener handler; private String text = ""; private Insets margin; private Action action; private Icon icon; private Icon pressedIcon; private Icon disabledIcon; private Icon defaultDisabledIcon; private Icon selectedIcon; private Icon disabledSelectedIcon; private Icon defaultDisabledSelectedIcon; private Icon rolloverIcon; private Icon rolloverSelectedIcon; private boolean borderPainted = true; private boolean focusPainted = true; private boolean rolloverEnabled; private boolean contentAreaFilled = true; private int verticalAlignment = SwingConstants.CENTER; private int horizontalAlignment = SwingConstants.CENTER; private int verticalTextPosition = SwingConstants.CENTER; private int horizontalTextPosition = SwingConstants.TRAILING; private int iconTextGap = 4; private int mnemonic; private int mnemonicIndex = -1; private long multiClickThreshhold; private InsetsUIResource defaultMargin; protected void init(String text, Icon icon) { if (text != null) { setText(text); } if (icon != null) { setIcon(icon); } updateUI(); } protected PropertyChangeListener createActionPropertyChangeListener(Action action) { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } public void setUI(ButtonUI ui) { super.setUI(ui); } public ButtonUI getUI() { return (ButtonUI) ui; } public void removeChangeListener(ChangeListener listener) { listenerList.remove(ChangeListener.class, listener); } public void addChangeListener(ChangeListener listener) { listenerList.add(ChangeListener.class, listener); } public ChangeListener[] getChangeListeners() { return listenerList.getListeners(ChangeListener.class); } protected ChangeListener createChangeListener() { return new ButtonChangeListener(); } public void setSelectedIcon(Icon selectedIcon) { Icon oldValue = this.selectedIcon; this.selectedIcon = selectedIcon; resetDefaultDisabledIcons(); firePropertyChange(SELECTED_ICON_CHANGED_PROPERTY, oldValue, selectedIcon); } public void setRolloverSelectedIcon(Icon rolloverSelectedIcon) { if (this.rolloverSelectedIcon != rolloverSelectedIcon) { Icon oldValue = this.rolloverSelectedIcon; this.rolloverSelectedIcon = rolloverSelectedIcon; firePropertyChange(ROLLOVER_SELECTED_ICON_CHANGED_PROPERTY, oldValue, rolloverSelectedIcon); setRolloverEnabled(true); } } public void setRolloverIcon(Icon rolloverIcon) { if (this.rolloverIcon != rolloverIcon) { Icon oldValue = this.rolloverIcon; this.rolloverIcon = rolloverIcon; firePropertyChange(ROLLOVER_ICON_CHANGED_PROPERTY, oldValue, rolloverIcon); setRolloverEnabled(true); } } public void setPressedIcon(Icon pressedIcon) { Icon oldValue = this.pressedIcon; this.pressedIcon = pressedIcon; firePropertyChange(PRESSED_ICON_CHANGED_PROPERTY, oldValue, pressedIcon); } private void resetDefaultDisabledIcons() { defaultDisabledIcon = null; defaultDisabledSelectedIcon = null; } public void setIcon(Icon icon) { Icon oldValue = this.icon; this.icon = icon; resetDefaultDisabledIcons(); firePropertyChange(ICON_CHANGED_PROPERTY, oldValue, icon); } public void setDisabledSelectedIcon(Icon disabledSelectedIcon) { Icon oldValue = this.disabledSelectedIcon; this.disabledSelectedIcon = disabledSelectedIcon; resetDefaultDisabledIcons(); firePropertyChange(DISABLED_SELECTED_ICON_CHANGED_PROPERTY, oldValue, disabledSelectedIcon); } public void setDisabledIcon(Icon disabledIcon) { Icon oldValue = this.disabledIcon; this.disabledIcon = disabledIcon; resetDefaultDisabledIcons(); firePropertyChange(DISABLED_ICON_CHANGED_PROPERTY, oldValue, disabledIcon); } public Icon getSelectedIcon() { return selectedIcon; } public Icon getRolloverSelectedIcon() { return rolloverSelectedIcon; } public Icon getRolloverIcon() { return rolloverIcon; } public Icon getPressedIcon() { return pressedIcon; } public Icon getIcon() { return icon; } private Icon createDefaultDisabledSelectedIcon() { if (defaultDisabledSelectedIcon != null) { return defaultDisabledSelectedIcon; } if (selectedIcon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) selectedIcon).getImage())); } else if (disabledIcon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) disabledIcon).getImage())); } else if (icon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) icon).getImage())); } return defaultDisabledIcon; } public Icon getDisabledSelectedIcon() { return (disabledSelectedIcon != null) ? disabledSelectedIcon : createDefaultDisabledSelectedIcon(); } private Icon createDefaultDisabledIcon() { if (defaultDisabledIcon != null) { return defaultDisabledIcon; } if (icon instanceof ImageIcon) { defaultDisabledIcon = new ImageIcon(GrayFilter .createDisabledImage(((ImageIcon) icon).getImage())); } return defaultDisabledIcon; } public Icon getDisabledIcon() { return (disabledIcon != null) ? disabledIcon : createDefaultDisabledIcon(); } public void setModel(ButtonModel m) { if (model != m) { ButtonModel oldValue = model; if (model != null) { model.removeActionListener(actionListener); model.removeItemListener(itemListener); model.removeChangeListener(changeListener); } model = m; if (model != null) { model.addChangeListener(changeListener); model.addItemListener(itemListener); model.addActionListener(actionListener); int mn = model.getMnemonic(); updateMnemonic(mn, Utilities.keyCodeToKeyChar(mn)); } firePropertyChange(MODEL_CHANGED_PROPERTY, oldValue, model); } } public ButtonModel getModel() { return model; } public void setAction(Action action) { if (this.action == action && action != null) { return; } Action oldValue = this.action; if (oldValue != null) { if (hasListener(Action.class, oldValue)) { removeActionListener(oldValue); } if (actionPropertyChangeListener != null) { oldValue.removePropertyChangeListener(actionPropertyChangeListener); } } this.action = action; if (action != null) { if (!hasListener(ActionListener.class, action)) { listenerList.add(Action.class, action); addActionListener(action); } actionPropertyChangeListener = createActionPropertyChangeListener(action); action.addPropertyChangeListener(actionPropertyChangeListener); } firePropertyChange(StringConstants.ACTION_PROPERTY_CHANGED, oldValue, action); configurePropertiesFromAction(action); } void configurePropertyFromAction(Action action, Object propertyName) { if (propertyName == null) { return; } if (propertyName.equals(Action.MNEMONIC_KEY)) { Object actionMnemonic = action.getValue(Action.MNEMONIC_KEY); setMnemonic((actionMnemonic != null) ? ((Integer) actionMnemonic).intValue() : 0); } if (propertyName.equals(Action.SHORT_DESCRIPTION)) { setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION)); } if (propertyName.equals(Action.SMALL_ICON)) { setIcon((Icon) action.getValue(Action.SMALL_ICON)); } if (propertyName.equals(StringConstants.ENABLED_PROPERTY_CHANGED)) { setEnabled(action.isEnabled()); } if (propertyName.equals(Action.NAME)) { setText((String) action.getValue(Action.NAME)); } if (propertyName.equals(Action.ACTION_COMMAND_KEY)) { setActionCommand((String) action.getValue(Action.ACTION_COMMAND_KEY)); } } protected void configurePropertiesFromAction(Action action) { final Action a = (action != null) ? action : CLEAR_ACTION_PROPERTIES; configurePropertyFromAction(a, getActionPropertiesFilter()); } public Action getAction() { return action; } public void setText(String text) { if (text != this.text) { String oldValue = this.text; this.text = text; firePropertyChange(TEXT_CHANGED_PROPERTY, oldValue, text); updateDisplayedMnemonicsIndex(Utilities.keyCodeToKeyChar(mnemonic)); } } @Deprecated public void setLabel(String label) { setText(label); } public void setActionCommand(String command) { model.setActionCommand(command); } protected int checkVerticalKey(int key, String exceptionText) { return Utilities.checkVerticalKey(key, exceptionText); } protected int checkHorizontalKey(int key, String exceptionText) { return Utilities.checkHorizontalKey(key, exceptionText); } public String getText() { return text; } @Deprecated public String getLabel() { return getText(); } public String getActionCommand() { String command = model.getActionCommand(); return (command != null) ? command : getText(); } public Object[] getSelectedObjects() { return model.isSelected() ? new Object[] { getText() } : null; } public void removeItemListener(ItemListener listener) { listenerList.remove(ItemListener.class, listener); } public void addItemListener(ItemListener listener) { listenerList.add(ItemListener.class, listener); } public ItemListener[] getItemListeners() { return listenerList.getListeners(ItemListener.class); } protected ItemListener createItemListener() { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } protected void fireItemStateChanged(ItemEvent event) { ItemListener[] listeners = getItemListeners(); if (listeners.length > 0) { ItemEvent itemEvent = new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED, this, event .getStateChange()); for (int i = 0; i < listeners.length; i++) { listeners[i].itemStateChanged(itemEvent); } } } public void removeActionListener(ActionListener listener) { listenerList.remove(ActionListener.class, listener); } public void addActionListener(ActionListener listener) { listenerList.add(ActionListener.class, listener); } public ActionListener[] getActionListeners() { return listenerList.getListeners(ActionListener.class); } protected ActionListener createActionListener() { return (handler != null) ? handler : (handler = new ActionAndModelListener()); } protected void fireActionPerformed(ActionEvent event) { ActionListener[] listeners = getActionListeners(); if (listeners.length > 0) { String command = (event.getActionCommand() != null) ? event.getActionCommand() : getText(); ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, command, event.getModifiers()); for (int i = 0; i < listeners.length; i++) { listeners[i].actionPerformed(actionEvent); } } } public void setMargin(Insets margin) { /* default values are obtained from UI (Harmony-4655) */ if (margin instanceof InsetsUIResource) { defaultMargin = (InsetsUIResource) margin; } else if (margin == null) { /* * According to spec if margin == null default value sets * (Harmony-4655) */ margin = defaultMargin; } Insets oldValue = this.margin; this.margin = margin; firePropertyChange(MARGIN_CHANGED_PROPERTY, oldValue, margin); } public Insets getMargin() { return margin; } @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) { Icon curIcon = ButtonCommons.getCurrentIcon(this); if ((curIcon == null) || !(curIcon instanceof ImageIcon) || (((ImageIcon) curIcon).getImage() != img)) { return false; } return super.imageUpdate(img, infoflags, x, y, w, h); } @Override protected void paintBorder(Graphics g) { if (isBorderPainted()) { super.paintBorder(g); } } public void doClick(int pressTime) { final ButtonModel model = getModel(); model.setArmed(true); model.setPressed(true); if (pressTime > 0) { paintImmediately(0, 0, getWidth(), getHeight()); try { Thread.sleep(pressTime); } catch (InterruptedException e) { } } model.setPressed(false); model.setArmed(false); } /** * The click delay is based on 1.5 release behavior which can be revealed using the * following code: * * <pre> * AbstractButton ab = new AbstractButton() { * }; * long startTime = System.currentTimeMillis(); * ab.setModel(new DefaultButtonModel()); * for (int i = 0; i &lt; 100; i++) { * ab.doClick(); * } * long stopTime = System.currentTimeMillis(); * System.err.println(&quot;doClick takes &quot; + (stopTime - startTime) / 100); * </pre> */ public void doClick() { doClick(70); } public void setSelected(boolean selected) { model.setSelected(selected); } public void setRolloverEnabled(boolean rollover) { boolean oldValue = rolloverEnabled; rolloverEnabled = rollover; firePropertyChange(ROLLOVER_ENABLED_CHANGED_PROPERTY, oldValue, rolloverEnabled); } public void setFocusPainted(boolean painted) { boolean oldValue = focusPainted; focusPainted = painted; firePropertyChange(FOCUS_PAINTED_CHANGED_PROPERTY, oldValue, painted); } @Override public void setEnabled(boolean enabled) { model.setEnabled(enabled); super.setEnabled(enabled); } public void setContentAreaFilled(boolean filled) { boolean oldValue = contentAreaFilled; contentAreaFilled = filled; firePropertyChange(CONTENT_AREA_FILLED_CHANGED_PROPERTY, oldValue, contentAreaFilled); } public void setBorderPainted(boolean painted) { boolean oldValue = borderPainted; borderPainted = painted; firePropertyChange(BORDER_PAINTED_CHANGED_PROPERTY, oldValue, borderPainted); } public void setMultiClickThreshhold(long threshold) { if (threshold < 0) { throw new IllegalArgumentException(Messages.getString("swing.05")); //$NON-NLS-1$ } multiClickThreshhold = threshold; } public void setVerticalTextPosition(int pos) { int oldValue = verticalTextPosition; verticalTextPosition = checkVerticalKey(pos, VERTICAL_TEXT_POSITION_CHANGED_PROPERTY); firePropertyChange(VERTICAL_TEXT_POSITION_CHANGED_PROPERTY, oldValue, verticalTextPosition); } public void setVerticalAlignment(int alignment) { int oldValue = verticalAlignment; verticalAlignment = checkVerticalKey(alignment, VERTICAL_ALIGNMENT_CHANGED_PROPERTY); firePropertyChange(VERTICAL_ALIGNMENT_CHANGED_PROPERTY, oldValue, verticalAlignment); } public void setMnemonic(char keyChar) { setMnemonic(Utilities.keyCharToKeyCode(keyChar), keyChar); } public void setMnemonic(int mnemonicCode) { setMnemonic(mnemonicCode, Utilities.keyCodeToKeyChar(mnemonicCode)); } private void setMnemonic(int keyCode, char keyChar) { model.setMnemonic(keyCode); } private void updateMnemonic(int keyCode, char keyChar) { int oldKeyCode = mnemonic; if (oldKeyCode == keyCode) { return; } mnemonic = keyCode; firePropertyChange(MNEMONIC_CHANGED_PROPERTY, oldKeyCode, keyCode); updateDisplayedMnemonicsIndex(keyChar); } private void updateDisplayedMnemonicsIndex(char keyChar) { setDisplayedMnemonicIndex(Utilities.getDisplayedMnemonicIndex(text, keyChar)); } public int getMnemonic() { return mnemonic; } public void setDisplayedMnemonicIndex(int index) throws IllegalArgumentException { if (index < -1 || index >= 0 && (text == null || index >= text.length())) { throw new IllegalArgumentException(Messages.getString("swing.10",index)); //$NON-NLS-1$ } int oldValue = mnemonicIndex; mnemonicIndex = index; firePropertyChange(StringConstants.MNEMONIC_INDEX_PROPERTY_CHANGED, oldValue, index); } public int getDisplayedMnemonicIndex() { return mnemonicIndex; } public void setIconTextGap(int gap) { LookAndFeel.markPropertyNotInstallable(this, StringConstants.ICON_TEXT_GAP_PROPERTY_CHANGED); int oldValue = iconTextGap; iconTextGap = gap; firePropertyChange(StringConstants.ICON_TEXT_GAP_PROPERTY_CHANGED, oldValue, iconTextGap); } public void setHorizontalTextPosition(int pos) { int oldValue = horizontalTextPosition; horizontalTextPosition = checkHorizontalKey(pos, HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY); firePropertyChange(HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY, oldValue, horizontalTextPosition); } public void setHorizontalAlignment(int alignment) { int oldValue = horizontalAlignment; horizontalAlignment = checkHorizontalKey(alignment, HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY); firePropertyChange(HORIZONTAL_ALIGNMENT_CHANGED_PROPERTY, oldValue, horizontalAlignment); } public boolean isSelected() { return model.isSelected(); } public boolean isRolloverEnabled() { return rolloverEnabled; } public boolean isFocusPainted() { return focusPainted; } public boolean isContentAreaFilled() { return contentAreaFilled; } public boolean isBorderPainted() { return borderPainted; } protected void fireStateChanged() { ChangeListener[] listeners = getChangeListeners(); for (int i = 0; i < listeners.length; i++) { listeners[i].stateChanged(changeEvent); } } public long getMultiClickThreshhold() { return multiClickThreshhold; } public int getVerticalTextPosition() { return verticalTextPosition; } public int getVerticalAlignment() { return verticalAlignment; } public int getIconTextGap() { return iconTextGap; } public int getHorizontalTextPosition() { return horizontalTextPosition; } public int getHorizontalAlignment() { return horizontalAlignment; } Object getActionPropertiesFilter() { return ALL_ACTION_PROPERTIES; } boolean processMnemonics(KeyEvent event) { final KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(event); if (keyStroke.isOnKeyRelease() || getMnemonic() == 0) { return false; } if (isMnemonicKeyStroke(keyStroke)) { Action action = getActionMap().get(StringConstants.MNEMONIC_ACTION); if (action != null) { SwingUtilities.notifyAction(action, keyStroke, event, this, event .getModifiersEx()); return true; } } return false; } boolean isMnemonicKeyStroke(KeyStroke keyStroke) { return keyStroke.getKeyCode() == getMnemonic() && (keyStroke.getModifiers() & InputEvent.ALT_DOWN_MASK) != 0; } }
gpl-2.0
ael-code/preston
src/org/simpleframework/transport/trace/Agent.java
2209
/* * Agent.java October 2012 * * Copyright (C) 2002, Niall Gallagher <niallg@users.sf.net> * * 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.simpleframework.transport.trace; import java.nio.channels.SocketChannel; /** * The <code>Agent</code> object represents a tracing agent used to * monitor events on a connection. Its primary responsibilities are to * create <code>Trace</code> objects that are attached to a specific * socket channel. When any event occurs on that channel the trace is * notified and can forward the details on to the agent for analysis. * <p> * An agent implementation must make sure that it does not affect * the performance of the server. If there are delays creating a trace * or within the trace itself it will have an impact on performance. * * @author Niall Gallagher * * @see org.simpleframework.transport.trace.Trace */ public interface Agent { /** * This method is used to attach a trace to the specified channel. * Attaching a trace basically means associating events from that * trace with the specified socket. It ensures that the events * from a specific channel can be observed in isolation. * * @param channel this is the channel to associate with the trace * * @return this returns a trace associated with the channel */ Trace attach(SocketChannel channel); /** * This is used to stop the agent and clear all trace information. * Stopping the agent is typically done when the server is stopped * and is used to free any resources associated with the agent. If * an agent does not hold information this method can be ignored. */ void stop(); }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/src/test/regression/H4292/Test.java
1287
/* * 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.harmony.drlvm.tests.regression.h4292; import junit.framework.*; public class Test extends TestCase { synchronized void _testSyncRec1() { _testSyncRec1(); } public void testSyncRec1() { try { _testSyncRec1(); } catch (StackOverflowError e) { System.out.println("PASSED!"); return; } fail("FAILED:No SOE was thrown!"); } }
gpl-2.0
guobingwei/guobing
src/main/java/com/study/thread/GenerThread.java
360
package com.study.thread; /** * Created by guobing on 2016/8/2. */ public class GenerThread extends Thread { public void run() { System.out.println(Thread.currentThread().getName() + " - General thread"); } synchronized public void GServer() { System.out.println(Thread.currentThread().getName() + " - General Server"); } }
gpl-2.0
Snessy/PasswordGen-LibGDX
html/src/com/mygdx/generate/client/HtmlLauncher.java
577
package com.mygdx.generate.client; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.mygdx.main.PassGenerate; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(480, 320); } @Override public ApplicationListener getApplicationListener () { return new PassGenerate(); } }
gpl-2.0
vvdeng/vportal
src/com/vvdeng/portal/web/controller/admin/AdminController.java
3792
package com.vvdeng.portal.web.controller.admin; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.paipai.verticalframework.web.spring.BaseController; import com.vvdeng.portal.bizservice.SideMenuService; import com.vvdeng.portal.dataservice.SysMenuDataService; import com.vvdeng.portal.entity.SysMenu; import com.vvdeng.portal.model.MenuLevel; import com.vvdeng.portal.model.SysMenuType; import com.vvdeng.portal.util.EmptyUtil; import com.vvdeng.portal.web.form.SideForm; import com.vvdeng.portal.web.form.SysUserForm; @Controller public class AdminController extends BaseController { private SysMenuDataService sysMenuDataService; @RequestMapping("/admin/index.xhtml") public String index() { return "/admin/base"; } @RequestMapping(method = RequestMethod.GET, value = "/admin/login.jhtml") public String loginPage() { return "/admin/login"; } @RequestMapping(method = RequestMethod.POST, value = "/admin/login.jhtml") public String login(SysUserForm sysUserForm, HttpSession session,ModelMap model) { System.out.println("uName=" + sysUserForm.getName() + " uPwd=" + sysUserForm.getPwd()); if ("admin".equals(sysUserForm.getName()) && "admin".equals(sysUserForm.getPwd())) { System.out.println("SessionVefityCode:"+session.getAttribute("verifyCode")+" msg="+session.getAttribute("msg")); session.setAttribute("sysUser", sysUserForm); return "redirect:/admin/index.xhtml"; } else { model.put("errMsg", "用户名或密码不正确"); return "/admin/login"; } } @RequestMapping("/admin/needLogin.jhtml") public String needLogin() { return "/admin/need_login"; } @RequestMapping("/admin/logout.jhtml") public String logout(HttpSession session) { session.invalidate(); return "redirect:/admin/needLogin.jhtml"; } @RequestMapping("/admin/head.xhtml") public String head(ModelMap map) { List<SysMenu> topSysMenuList = sysMenuDataService .queryByLevel(MenuLevel.TOP.getId()); map.put("topSysMenuList", topSysMenuList); System.out.println("topSysMenuList size=" + topSysMenuList.size()); return "/admin/head"; } @RequestMapping("/admin/side.xhtml") public String side(SideForm sideForm, ModelMap map) { processSide(sideForm, map); map.put("sideForm", sideForm); return "/admin/side"; } @RequestMapping("/admin/main.xhtml") public String main() { return "/admin/main"; } @RequestMapping("/admin/welcome.xhtml") public String welcome() { return "/admin/welcome"; } public SysMenuDataService getSysMenuDataService() { return sysMenuDataService; } public void setSysMenuDataService(SysMenuDataService sysMenuDataService) { this.sysMenuDataService = sysMenuDataService; } private void processSide(SideForm sideForm, ModelMap map) { if (sideForm.getOperation() == null || sideForm.getOperation().isEmpty() || sideForm.getOperation().equals(SysMenu.DEFAULT_OPERATION)) { if (sideForm.getType() == null || sideForm.getType().equals(SysMenuType.LIST.getId())) { List<SysMenu> sysMenuList = sysMenuDataService .queryByParentId(sideForm.getId()); map.put("menuList", sysMenuList); map.put("defaultHref", EmptyUtil.isNull(sysMenuList) ? "" : sysMenuList.get(0).getHref()); } } else { SideMenuService sideMenuEditMenu = getBean("editMenu", SideMenuService.class); sideMenuEditMenu.tree(sideForm, map); } } }
gpl-2.0
FauxFaux/jdk9-jdk
src/jdk.net/share/classes/module-info.java
1249
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ module jdk.net { exports jdk.net; }
gpl-2.0
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/style/StyleFooterElement.java
18135
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * 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. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.style; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.element.table.TableTableElement; import org.odftoolkit.odfdom.dom.element.text.TextAlphabeticalIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextAlphabeticalIndexAutoMarkFileElement; import org.odftoolkit.odfdom.dom.element.text.TextBibliographyElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeEndElement; import org.odftoolkit.odfdom.dom.element.text.TextChangeStartElement; import org.odftoolkit.odfdom.dom.element.text.TextDdeConnectionDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextHElement; import org.odftoolkit.odfdom.dom.element.text.TextIllustrationIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextIndexTitleElement; import org.odftoolkit.odfdom.dom.element.text.TextListElement; import org.odftoolkit.odfdom.dom.element.text.TextObjectIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextPElement; import org.odftoolkit.odfdom.dom.element.text.TextSectionElement; import org.odftoolkit.odfdom.dom.element.text.TextSequenceDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextTableIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextTableOfContentElement; import org.odftoolkit.odfdom.dom.element.text.TextTrackedChangesElement; import org.odftoolkit.odfdom.dom.element.text.TextUserFieldDeclsElement; import org.odftoolkit.odfdom.dom.element.text.TextUserIndexElement; import org.odftoolkit.odfdom.dom.element.text.TextVariableDeclsElement; import org.odftoolkit.odfdom.dom.attribute.style.StyleDisplayAttribute; /** * DOM implementation of OpenDocument element {@odf.element style:footer}. * */ public class StyleFooterElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.STYLE, "footer"); /** * Create the instance of <code>StyleFooterElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public StyleFooterElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element style:footer}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>StyleDisplayAttribute</code> , See {@odf.attribute style:display} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getStyleDisplayAttribute() { StyleDisplayAttribute attr = (StyleDisplayAttribute) getOdfAttribute(OdfDocumentNamespace.STYLE, "display"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(StyleDisplayAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>StyleDisplayAttribute</code> , See {@odf.attribute style:display} * * @param styleDisplayValue The type is <code>Boolean</code> */ public void setStyleDisplayAttribute(Boolean styleDisplayValue) { StyleDisplayAttribute attr = new StyleDisplayAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(styleDisplayValue.booleanValue()); } /** * Create child element {@odf.element style:region-center}. * * @return the element {@odf.element style:region-center} */ public StyleRegionCenterElement newStyleRegionCenterElement() { StyleRegionCenterElement styleRegionCenter = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionCenterElement.class); this.appendChild(styleRegionCenter); return styleRegionCenter; } /** * Create child element {@odf.element style:region-left}. * * @return the element {@odf.element style:region-left} */ public StyleRegionLeftElement newStyleRegionLeftElement() { StyleRegionLeftElement styleRegionLeft = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionLeftElement.class); this.appendChild(styleRegionLeft); return styleRegionLeft; } /** * Create child element {@odf.element style:region-right}. * * @return the element {@odf.element style:region-right} */ public StyleRegionRightElement newStyleRegionRightElement() { StyleRegionRightElement styleRegionRight = ((OdfFileDom) this.ownerDocument).newOdfElement(StyleRegionRightElement.class); this.appendChild(styleRegionRight); return styleRegionRight; } /** * Create child element {@odf.element table:table}. * * @return the element {@odf.element table:table} */ public TableTableElement newTableTableElement() { TableTableElement tableTable = ((OdfFileDom) this.ownerDocument).newOdfElement(TableTableElement.class); this.appendChild(tableTable); return tableTable; } /** * Create child element {@odf.element text:alphabetical-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:alphabetical-index} */ public TextAlphabeticalIndexElement newTextAlphabeticalIndexElement(String textNameValue) { TextAlphabeticalIndexElement textAlphabeticalIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextAlphabeticalIndexElement.class); textAlphabeticalIndex.setTextNameAttribute(textNameValue); this.appendChild(textAlphabeticalIndex); return textAlphabeticalIndex; } /** * Create child element {@odf.element text:alphabetical-index-auto-mark-file}. * * @param xlinkHrefValue the <code>String</code> value of <code>XlinkHrefAttribute</code>, see {@odf.attribute xlink:href} at specification * @param xlinkTypeValue the <code>String</code> value of <code>XlinkTypeAttribute</code>, see {@odf.attribute xlink:type} at specification * @return the element {@odf.element text:alphabetical-index-auto-mark-file} */ public TextAlphabeticalIndexAutoMarkFileElement newTextAlphabeticalIndexAutoMarkFileElement(String xlinkHrefValue, String xlinkTypeValue) { TextAlphabeticalIndexAutoMarkFileElement textAlphabeticalIndexAutoMarkFile = ((OdfFileDom) this.ownerDocument).newOdfElement(TextAlphabeticalIndexAutoMarkFileElement.class); textAlphabeticalIndexAutoMarkFile.setXlinkHrefAttribute(xlinkHrefValue); textAlphabeticalIndexAutoMarkFile.setXlinkTypeAttribute(xlinkTypeValue); this.appendChild(textAlphabeticalIndexAutoMarkFile); return textAlphabeticalIndexAutoMarkFile; } /** * Create child element {@odf.element text:bibliography}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:bibliography} */ public TextBibliographyElement newTextBibliographyElement(String textNameValue) { TextBibliographyElement textBibliography = ((OdfFileDom) this.ownerDocument).newOdfElement(TextBibliographyElement.class); textBibliography.setTextNameAttribute(textNameValue); this.appendChild(textBibliography); return textBibliography; } /** * Create child element {@odf.element text:change}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change} */ public TextChangeElement newTextChangeElement(String textChangeIdValue) { TextChangeElement textChange = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeElement.class); textChange.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChange); return textChange; } /** * Create child element {@odf.element text:change-end}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change-end} */ public TextChangeEndElement newTextChangeEndElement(String textChangeIdValue) { TextChangeEndElement textChangeEnd = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeEndElement.class); textChangeEnd.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChangeEnd); return textChangeEnd; } /** * Create child element {@odf.element text:change-start}. * * @param textChangeIdValue the <code>String</code> value of <code>TextChangeIdAttribute</code>, see {@odf.attribute text:change-id} at specification * @return the element {@odf.element text:change-start} */ public TextChangeStartElement newTextChangeStartElement(String textChangeIdValue) { TextChangeStartElement textChangeStart = ((OdfFileDom) this.ownerDocument).newOdfElement(TextChangeStartElement.class); textChangeStart.setTextChangeIdAttribute(textChangeIdValue); this.appendChild(textChangeStart); return textChangeStart; } /** * Create child element {@odf.element text:dde-connection-decls}. * * @return the element {@odf.element text:dde-connection-decls} */ public TextDdeConnectionDeclsElement newTextDdeConnectionDeclsElement() { TextDdeConnectionDeclsElement textDdeConnectionDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextDdeConnectionDeclsElement.class); this.appendChild(textDdeConnectionDecls); return textDdeConnectionDecls; } /** * Create child element {@odf.element text:h}. * * @param textOutlineLevelValue the <code>Integer</code> value of <code>TextOutlineLevelAttribute</code>, see {@odf.attribute text:outline-level} at specification * @return the element {@odf.element text:h} */ public TextHElement newTextHElement(int textOutlineLevelValue) { TextHElement textH = ((OdfFileDom) this.ownerDocument).newOdfElement(TextHElement.class); textH.setTextOutlineLevelAttribute(textOutlineLevelValue); this.appendChild(textH); return textH; } /** * Create child element {@odf.element text:illustration-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:illustration-index} */ public TextIllustrationIndexElement newTextIllustrationIndexElement(String textNameValue) { TextIllustrationIndexElement textIllustrationIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextIllustrationIndexElement.class); textIllustrationIndex.setTextNameAttribute(textNameValue); this.appendChild(textIllustrationIndex); return textIllustrationIndex; } /** * Create child element {@odf.element text:index-title}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:index-title} */ public TextIndexTitleElement newTextIndexTitleElement(String textNameValue) { TextIndexTitleElement textIndexTitle = ((OdfFileDom) this.ownerDocument).newOdfElement(TextIndexTitleElement.class); textIndexTitle.setTextNameAttribute(textNameValue); this.appendChild(textIndexTitle); return textIndexTitle; } /** * Create child element {@odf.element text:list}. * * @return the element {@odf.element text:list} */ public TextListElement newTextListElement() { TextListElement textList = ((OdfFileDom) this.ownerDocument).newOdfElement(TextListElement.class); this.appendChild(textList); return textList; } /** * Create child element {@odf.element text:object-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:object-index} */ public TextObjectIndexElement newTextObjectIndexElement(String textNameValue) { TextObjectIndexElement textObjectIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextObjectIndexElement.class); textObjectIndex.setTextNameAttribute(textNameValue); this.appendChild(textObjectIndex); return textObjectIndex; } /** * Create child element {@odf.element text:p}. * * @return the element {@odf.element text:p} */ public TextPElement newTextPElement() { TextPElement textP = ((OdfFileDom) this.ownerDocument).newOdfElement(TextPElement.class); this.appendChild(textP); return textP; } /** * Create child element {@odf.element text:section}. * * @param textDisplayValue the <code>String</code> value of <code>TextDisplayAttribute</code>, see {@odf.attribute text:display} at specification * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:section} */ public TextSectionElement newTextSectionElement(String textDisplayValue, String textNameValue) { TextSectionElement textSection = ((OdfFileDom) this.ownerDocument).newOdfElement(TextSectionElement.class); textSection.setTextDisplayAttribute(textDisplayValue); textSection.setTextNameAttribute(textNameValue); this.appendChild(textSection); return textSection; } /** * Create child element {@odf.element text:sequence-decls}. * * @return the element {@odf.element text:sequence-decls} */ public TextSequenceDeclsElement newTextSequenceDeclsElement() { TextSequenceDeclsElement textSequenceDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextSequenceDeclsElement.class); this.appendChild(textSequenceDecls); return textSequenceDecls; } /** * Create child element {@odf.element text:table-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:table-index} */ public TextTableIndexElement newTextTableIndexElement(String textNameValue) { TextTableIndexElement textTableIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTableIndexElement.class); textTableIndex.setTextNameAttribute(textNameValue); this.appendChild(textTableIndex); return textTableIndex; } /** * Create child element {@odf.element text:table-of-content}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:table-of-content} */ public TextTableOfContentElement newTextTableOfContentElement(String textNameValue) { TextTableOfContentElement textTableOfContent = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTableOfContentElement.class); textTableOfContent.setTextNameAttribute(textNameValue); this.appendChild(textTableOfContent); return textTableOfContent; } /** * Create child element {@odf.element text:tracked-changes}. * * @return the element {@odf.element text:tracked-changes} */ public TextTrackedChangesElement newTextTrackedChangesElement() { TextTrackedChangesElement textTrackedChanges = ((OdfFileDom) this.ownerDocument).newOdfElement(TextTrackedChangesElement.class); this.appendChild(textTrackedChanges); return textTrackedChanges; } /** * Create child element {@odf.element text:user-field-decls}. * * @return the element {@odf.element text:user-field-decls} */ public TextUserFieldDeclsElement newTextUserFieldDeclsElement() { TextUserFieldDeclsElement textUserFieldDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextUserFieldDeclsElement.class); this.appendChild(textUserFieldDecls); return textUserFieldDecls; } /** * Create child element {@odf.element text:user-index}. * * @param textNameValue the <code>String</code> value of <code>TextNameAttribute</code>, see {@odf.attribute text:name} at specification * @return the element {@odf.element text:user-index} */ public TextUserIndexElement newTextUserIndexElement(String textNameValue) { TextUserIndexElement textUserIndex = ((OdfFileDom) this.ownerDocument).newOdfElement(TextUserIndexElement.class); textUserIndex.setTextNameAttribute(textNameValue); this.appendChild(textUserIndex); return textUserIndex; } /** * Create child element {@odf.element text:variable-decls}. * * @return the element {@odf.element text:variable-decls} */ public TextVariableDeclsElement newTextVariableDeclsElement() { TextVariableDeclsElement textVariableDecls = ((OdfFileDom) this.ownerDocument).newOdfElement(TextVariableDeclsElement.class); this.appendChild(textVariableDecls); return textVariableDecls; } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
gpl-2.0
arthurmelo88/palmetalADP
adempiere_360/base/src/org/compiere/model/X_I_ElementValue.java
15150
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.KeyNamePair; /** Generated Model for I_ElementValue * @author Adempiere (generated) * @version Release 3.6.0LTS - $Id$ */ public class X_I_ElementValue extends PO implements I_I_ElementValue, I_Persistent { /** * */ private static final long serialVersionUID = 20100614L; /** Standard Constructor */ public X_I_ElementValue (Properties ctx, int I_ElementValue_ID, String trxName) { super (ctx, I_ElementValue_ID, trxName); /** if (I_ElementValue_ID == 0) { setI_ElementValue_ID (0); setI_IsImported (false); } */ } /** Load Constructor */ public X_I_ElementValue (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 6 - System - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_I_ElementValue[") .append(get_ID()).append("]"); return sb.toString(); } /** AccountSign AD_Reference_ID=118 */ public static final int ACCOUNTSIGN_AD_Reference_ID=118; /** Natural = N */ public static final String ACCOUNTSIGN_Natural = "N"; /** Debit = D */ public static final String ACCOUNTSIGN_Debit = "D"; /** Credit = C */ public static final String ACCOUNTSIGN_Credit = "C"; /** Set Account Sign. @param AccountSign Indicates the Natural Sign of the Account as a Debit or Credit */ public void setAccountSign (String AccountSign) { set_Value (COLUMNNAME_AccountSign, AccountSign); } /** Get Account Sign. @return Indicates the Natural Sign of the Account as a Debit or Credit */ public String getAccountSign () { return (String)get_Value(COLUMNNAME_AccountSign); } /** AccountType AD_Reference_ID=117 */ public static final int ACCOUNTTYPE_AD_Reference_ID=117; /** Asset = A */ public static final String ACCOUNTTYPE_Asset = "A"; /** Liability = L */ public static final String ACCOUNTTYPE_Liability = "L"; /** Revenue = R */ public static final String ACCOUNTTYPE_Revenue = "R"; /** Expense = E */ public static final String ACCOUNTTYPE_Expense = "E"; /** Owner's Equity = O */ public static final String ACCOUNTTYPE_OwnerSEquity = "O"; /** Memo = M */ public static final String ACCOUNTTYPE_Memo = "M"; /** Set Account Type. @param AccountType Indicates the type of account */ public void setAccountType (String AccountType) { set_Value (COLUMNNAME_AccountType, AccountType); } /** Get Account Type. @return Indicates the type of account */ public String getAccountType () { return (String)get_Value(COLUMNNAME_AccountType); } public I_AD_Column getAD_Column() throws RuntimeException { return (I_AD_Column)MTable.get(getCtx(), I_AD_Column.Table_Name) .getPO(getAD_Column_ID(), get_TrxName()); } /** Set Column. @param AD_Column_ID Column in the table */ public void setAD_Column_ID (int AD_Column_ID) { if (AD_Column_ID < 1) set_Value (COLUMNNAME_AD_Column_ID, null); else set_Value (COLUMNNAME_AD_Column_ID, Integer.valueOf(AD_Column_ID)); } /** Get Column. @return Column in the table */ public int getAD_Column_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_Element getC_Element() throws RuntimeException { return (I_C_Element)MTable.get(getCtx(), I_C_Element.Table_Name) .getPO(getC_Element_ID(), get_TrxName()); } /** Set Element. @param C_Element_ID Accounting Element */ public void setC_Element_ID (int C_Element_ID) { if (C_Element_ID < 1) set_Value (COLUMNNAME_C_Element_ID, null); else set_Value (COLUMNNAME_C_Element_ID, Integer.valueOf(C_Element_ID)); } /** Get Element. @return Accounting Element */ public int getC_Element_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Element_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getC_ElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getC_ElementValue_ID(), get_TrxName()); } /** Set Account Element. @param C_ElementValue_ID Account Element */ public void setC_ElementValue_ID (int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_Value (COLUMNNAME_C_ElementValue_ID, null); else set_Value (COLUMNNAME_C_ElementValue_ID, Integer.valueOf(C_ElementValue_ID)); } /** Get Account Element. @return Account Element */ public int getC_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Default Account. @param Default_Account Name of the Default Account Column */ public void setDefault_Account (String Default_Account) { set_Value (COLUMNNAME_Default_Account, Default_Account); } /** Get Default Account. @return Name of the Default Account Column */ public String getDefault_Account () { return (String)get_Value(COLUMNNAME_Default_Account); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Element Name. @param ElementName Name of the Element */ public void setElementName (String ElementName) { set_Value (COLUMNNAME_ElementName, ElementName); } /** Get Element Name. @return Name of the Element */ public String getElementName () { return (String)get_Value(COLUMNNAME_ElementName); } /** Set Import Account. @param I_ElementValue_ID Import Account Value */ public void setI_ElementValue_ID (int I_ElementValue_ID) { if (I_ElementValue_ID < 1) set_ValueNoCheck (COLUMNNAME_I_ElementValue_ID, null); else set_ValueNoCheck (COLUMNNAME_I_ElementValue_ID, Integer.valueOf(I_ElementValue_ID)); } /** Get Import Account. @return Import Account Value */ public int getI_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_I_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Import Error Message. @param I_ErrorMsg Messages generated from import process */ public void setI_ErrorMsg (String I_ErrorMsg) { set_Value (COLUMNNAME_I_ErrorMsg, I_ErrorMsg); } /** Get Import Error Message. @return Messages generated from import process */ public String getI_ErrorMsg () { return (String)get_Value(COLUMNNAME_I_ErrorMsg); } /** Set Imported. @param I_IsImported Has this import been processed */ public void setI_IsImported (boolean I_IsImported) { set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported)); } /** Get Imported. @return Has this import been processed */ public boolean isI_IsImported () { Object oo = get_Value(COLUMNNAME_I_IsImported); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Document Controlled. @param IsDocControlled Control account - If an account is controlled by a document, you cannot post manually to it */ public void setIsDocControlled (boolean IsDocControlled) { set_Value (COLUMNNAME_IsDocControlled, Boolean.valueOf(IsDocControlled)); } /** Get Document Controlled. @return Control account - If an account is controlled by a document, you cannot post manually to it */ public boolean isDocControlled () { Object oo = get_Value(COLUMNNAME_IsDocControlled); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Summary Level. @param IsSummary This is a summary entity */ public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Summary Level. @return This is a summary entity */ public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } public I_C_ElementValue getParentElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getParentElementValue_ID(), get_TrxName()); } /** Set Parent Account. @param ParentElementValue_ID The parent (summary) account */ public void setParentElementValue_ID (int ParentElementValue_ID) { if (ParentElementValue_ID < 1) set_Value (COLUMNNAME_ParentElementValue_ID, null); else set_Value (COLUMNNAME_ParentElementValue_ID, Integer.valueOf(ParentElementValue_ID)); } /** Get Parent Account. @return The parent (summary) account */ public int getParentElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ParentElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent Key. @param ParentValue Key if the Parent */ public void setParentValue (String ParentValue) { set_Value (COLUMNNAME_ParentValue, ParentValue); } /** Get Parent Key. @return Key if the Parent */ public String getParentValue () { return (String)get_Value(COLUMNNAME_ParentValue); } /** Set Post Actual. @param PostActual Actual Values can be posted */ public void setPostActual (boolean PostActual) { set_Value (COLUMNNAME_PostActual, Boolean.valueOf(PostActual)); } /** Get Post Actual. @return Actual Values can be posted */ public boolean isPostActual () { Object oo = get_Value(COLUMNNAME_PostActual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Budget. @param PostBudget Budget values can be posted */ public void setPostBudget (boolean PostBudget) { set_Value (COLUMNNAME_PostBudget, Boolean.valueOf(PostBudget)); } /** Get Post Budget. @return Budget values can be posted */ public boolean isPostBudget () { Object oo = get_Value(COLUMNNAME_PostBudget); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Encumbrance. @param PostEncumbrance Post commitments to this account */ public void setPostEncumbrance (boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, Boolean.valueOf(PostEncumbrance)); } /** Get Post Encumbrance. @return Post commitments to this account */ public boolean isPostEncumbrance () { Object oo = get_Value(COLUMNNAME_PostEncumbrance); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Post Statistical. @param PostStatistical Post statistical quantities to this account? */ public void setPostStatistical (boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, Boolean.valueOf(PostStatistical)); } /** Get Post Statistical. @return Post statistical quantities to this account? */ public boolean isPostStatistical () { Object oo = get_Value(COLUMNNAME_PostStatistical); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
gpl-2.0
MrDunne/myblockchain
storage/ndb/clusterj/clusterj-openjpa/src/test/java/com/mysql/clusterj/openjpatest/TimestampAsUtilDateTest.java
922
/* Copyright 2010 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. 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 2 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. 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 */ package com.myblockchain.clusterj.openjpatest; public class TimestampAsUtilDateTest extends com.myblockchain.clusterj.jpatest.TimestampAsUtilDateTest { }
gpl-2.0
dschultzca/RomRaider
src/main/java/com/romraider/maps/DataCell.java
18799
/* * RomRaider Open-Source Tuning, Logging and Reflashing * Copyright (C) 2006-2022 RomRaider.com * * 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 com.romraider.maps; import java.io.Serializable; import java.text.ParseException; import java.util.LinkedList; import java.util.StringTokenizer; import org.apache.log4j.Logger; import com.romraider.Settings; import com.romraider.Settings.Endian; import com.romraider.editor.ecu.ECUEditorManager; import com.romraider.util.ByteUtil; import com.romraider.util.JEPUtil; import com.romraider.util.NumberUtil; import com.romraider.util.SettingsManager; import com.romraider.xml.RomAttributeParser; public class DataCell implements Serializable { private static final long serialVersionUID = 1111479947434817639L; private static final Logger LOGGER = Logger.getLogger(DataCell.class); //View we need to keep up to date private DataCellView view = null; private Table table; //This sounds like a View property, but the manipulations //functions depend on this, so its better to put it here private boolean isSelected = false; private double binValue = 0.0; private double originalValue = 0.0; private double compareToValue = 0.0; private String liveValue = Settings.BLANK; private String staticText = null; private Rom rom; //Index within table private int index; public DataCell(Table table, Rom rom) { this.table = table; this.rom = rom; } public DataCell(Table table, String staticText, Rom rom) { this(table, rom); final StringTokenizer st = new StringTokenizer(staticText, DataCellView.ST_DELIMITER); if (st.hasMoreTokens()) { this.staticText = st.nextToken(); } } public DataCell(Table table, int index, Rom rom) { this(table, rom); this.index = index; updateBinValueFromMemory(); this.originalValue = this.binValue; registerDataCell(this); } public void setTable(Table t) { this.table = t; } public void setRom(Rom rom) { this.rom = rom; } public byte[] getBinary() { return rom.getBinary(); } private double getValueFromMemory(int index) { double dataValue = 0.0; byte[] input = getBinary(); int storageType = table.getStorageType(); Endian endian = table.getEndian(); int ramOffset = table.getRamOffset(); int storageAddress = table.getStorageAddress(); boolean signed = table.isSignedData(); // populate data cells if (storageType == Settings.STORAGE_TYPE_FLOAT) { //float storage type byte[] byteValue = new byte[4]; byteValue[0] = input[storageAddress + index * 4 - table.getRamOffset()]; byteValue[1] = input[storageAddress + index * 4 - table.getRamOffset() + 1]; byteValue[2] = input[storageAddress + index * 4 - table.getRamOffset() + 2]; byteValue[3] = input[storageAddress + index * 4 - table.getRamOffset() + 3]; dataValue = RomAttributeParser.byteToFloat(byteValue, table.getEndian(), table.getMemModelEndian()); } else if (storageType == Settings.STORAGE_TYPE_MOVI20 || storageType == Settings.STORAGE_TYPE_MOVI20S) { // when data is in MOVI20 instruction dataValue = RomAttributeParser.parseByteValue(input, endian, storageAddress + index * 3 - ramOffset, storageType, signed); } else { // integer storage type if(table.getBitMask() == 0) { dataValue = RomAttributeParser.parseByteValue(input, endian, storageAddress + index * storageType - ramOffset, storageType, signed); } else { dataValue = RomAttributeParser.parseByteValueMasked(input, endian, storageAddress + index * storageType - ramOffset, storageType, signed, table.getBitMask()); } } return dataValue; } private double getValueFromMemory() { if (table.getDataLayout() == Table.DataLayout.BOSCH_SUBTRACT) { //Bosch Motronic subtract method double dataValue = Math.pow(2, 8 * table.getStorageType()); for (int j = table.data.length - 1; j >= index; j--) { dataValue -= getValueFromMemory(j); } return dataValue; } else { return getValueFromMemory(index); } } public void saveBinValueInFile() { if (table.getName().contains("Checksum Fix")) return; byte[] binData = getBinary(); int userLevel = table.getUserLevel(); int storageType = table.getStorageType(); Endian endian = table.getEndian(); int ramOffset = table.getRamOffset(); int storageAddress = table.getStorageAddress(); boolean isBoschSubtract = table.getDataLayout() == Table.DataLayout.BOSCH_SUBTRACT; double crossedValue = 0; //Do reverse cross referencing in for Bosch Subtract Axis array if(isBoschSubtract) { for (int i = table.data.length - 1; i >=index ; i--) { if(i == index) crossedValue -= table.data[i].getBinValue(); else if(i == table.data.length - 1) crossedValue = Math.pow(2, 8 * storageType) - getValueFromMemory(i); else { crossedValue -= getValueFromMemory(i); } } } if (userLevel <= getSettings().getUserLevel() && (userLevel < 5 || getSettings().isSaveDebugTables()) ) { // determine output byte values byte[] output; int mask = table.getBitMask(); if (storageType != Settings.STORAGE_TYPE_FLOAT) { int finalValue = 0; // convert byte values if(table.isStaticDataTable() && storageType > 0) { LOGGER.warn("Static data table: " + table.toString() + ", storageType: "+storageType); try { finalValue = Integer.parseInt(getStaticText()); } catch (NumberFormatException ex) { LOGGER.error("Error parsing static data table value: " + getStaticText(), ex); LOGGER.error("Validate the table definition storageType and data value."); return; } } else if(table.isStaticDataTable() && storageType < 1) { // Do not save the value. //if (LOGGER.isDebugEnabled()) // LOGGER.debug("The static data table value will not be saved."); return; } else { finalValue = (int) (isBoschSubtract ? crossedValue : getBinValue()); } if(mask != 0) { // Shift left again finalValue = finalValue << ByteUtil.firstOneOfMask(mask); } output = RomAttributeParser.parseIntegerValue(finalValue, endian, storageType); int byteLength = storageType; if (storageType == Settings.STORAGE_TYPE_MOVI20 || storageType == Settings.STORAGE_TYPE_MOVI20S) { // when data is in MOVI20 instruction byteLength = 3; } //If mask enabled, only change bits within the mask if(mask != 0) { int tempBitMask = 0; for (int z = 0; z < byteLength; z++) { // insert into file tempBitMask = mask; //Trim mask depending on byte, from left to right tempBitMask = (tempBitMask & (0xFF << 8 * (byteLength - 1 - z))) >> 8*(byteLength - 1 - z); // Delete old bits binData[index * byteLength + z + storageAddress - ramOffset] &= ~tempBitMask; // Overwrite binData[index * byteLength + z + storageAddress - ramOffset] |= output[z]; } } //No Masking else { for (int z = 0; z < byteLength; z++) { // insert into file binData[index * byteLength + z + storageAddress - ramOffset] = output[z]; } } } else { // float // convert byte values output = RomAttributeParser.floatToByte((float) getBinValue(), endian, table.getMemModelEndian()); for (int z = 0; z < 4; z++) { // insert in to file binData[index * 4 + z + storageAddress - ramOffset] = output[z]; } } } //On the Bosch substract model, we need to update all previous cells, because they depend on our value if(isBoschSubtract && index > 0) table.data[index-1].saveBinValueInFile(); checkForDataUpdates(); } public void registerDataCell(DataCell cell) { int memoryIndex = getMemoryStartAddress(cell); if (rom.byteCellMapping.containsKey(memoryIndex)) { rom.byteCellMapping.get(memoryIndex).add(cell); } else { LinkedList<DataCell> l = new LinkedList<DataCell>(); l.add(cell); rom.byteCellMapping.put(memoryIndex, l); } } public void checkForDataUpdates() { int memoryIndex = getMemoryStartAddress(this); if (rom.byteCellMapping.containsKey(memoryIndex)){ for(DataCell c : rom.byteCellMapping.get(memoryIndex)) { c.updateBinValueFromMemory(); } } } public static int getMemoryStartAddress(DataCell cell) { Table t = cell.getTable(); return t.getStorageAddress() + cell.getIndexInTable() * t.getStorageType() - t.getRamOffset(); } public Settings getSettings() { return SettingsManager.getSettings(); } public void setSelected(boolean selected) { if(!table.isStaticDataTable() && this.isSelected != selected) { this.isSelected = selected; if(view!=null) { ECUEditorManager.getECUEditor().getTableToolBar().updateTableToolBar(table); view.drawCell(); } } } public boolean isSelected() { return isSelected; } public void updateBinValueFromMemory() { this.binValue = getValueFromMemory(); updateView(); } public void setDataView(DataCellView v) { view = v; } public int getIndexInTable() { return index; } private void updateView() { if(view != null) view.drawCell(); } public Table getTable() { return this.table; } public String getStaticText() { return staticText; } public String getLiveValue() { return this.liveValue; } public void setLiveDataTraceValue(String liveValue) { if(this.liveValue != liveValue) { this.liveValue = liveValue; updateView(); } } public double getBinValue() { return binValue; } public double getOriginalValue() { return originalValue; } public double getCompareToValue() { return compareToValue; } public double getRealValue() { if(table.getCurrentScale() == null) return binValue; return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); } public void setRealValue(String input) throws UserLevelException { // create parser input = input.replaceAll(DataCellView.REPLACE_TEXT, Settings.BLANK); try { double result = 0.0; if (!"x".equalsIgnoreCase(input)) { if(table.getCurrentScale().getByteExpression() == null) { result = table.getCurrentScale().approximateToByteFunction(NumberUtil.doubleValue(input), table.getStorageType(), table.isSignedData()); } else { result = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), NumberUtil.doubleValue(input)); } if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT) { result = (int) Math.round(result); } if(binValue != result) { this.setBinValue(result); } } } catch (ParseException e) { // Do nothing. input is null or not a valid number. } } public double getCompareValue() { return binValue - compareToValue; } public double getRealCompareValue() { return JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue) - JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); } public double getRealCompareChangeValue() { double realBinValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), binValue); double realCompareValue = JEPUtil.evaluate(table.getCurrentScale().getExpression(), compareToValue); if(realCompareValue != 0.0) { // Compare change formula ((V2 - V1) / |V1|). return ((realBinValue - realCompareValue) / Math.abs(realCompareValue)); } else { // Use this to avoid divide by 0 or infinite increase. return realBinValue - realCompareValue; } } public void setBinValue(double newBinValue) throws UserLevelException { if(binValue == newBinValue || table.locked || table.getName().contains("Checksum Fix")) { return; } if (table.userLevel > getSettings().getUserLevel()) throw new UserLevelException(table.userLevel); double checkedValue = newBinValue; // make sure it's in range if(checkedValue < table.getMinAllowedBin()) { checkedValue = table.getMinAllowedBin(); } if(checkedValue > table.getMaxAllowedBin()) { checkedValue = table.getMaxAllowedBin(); } if(binValue == checkedValue) { return; } // set bin. binValue = checkedValue; saveBinValueInFile(); updateView(); } public void increment(double increment) throws UserLevelException { double oldValue = getRealValue(); if (table.getCurrentScale().getCoarseIncrement() < 0.0) { increment = 0.0 - increment; } double incResult = 0; if(table.getCurrentScale().getByteExpression() == null) { incResult = table.getCurrentScale().approximateToByteFunction(oldValue + increment, table.getStorageType(), table.isSignedData()); } else { incResult = JEPUtil.evaluate(table.getCurrentScale().getByteExpression(), (oldValue + increment)); } if (table.getStorageType() == Settings.STORAGE_TYPE_FLOAT) { if(binValue != incResult) { this.setBinValue(incResult); } } else { int roundResult = (int) Math.round(incResult); if(binValue != roundResult) { this.setBinValue(roundResult); } } // make sure table is incremented if change isn't great enough int maxValue = (int) Math.pow(8, table.getStorageType()); if (table.getStorageType() != Settings.STORAGE_TYPE_FLOAT && oldValue == getRealValue() && binValue > 0.0 && binValue < maxValue) { if (LOGGER.isDebugEnabled()) LOGGER.debug(maxValue + " " + binValue); increment(increment * 2); } } public void undo() throws UserLevelException { this.setBinValue(originalValue); } public void setRevertPoint() { this.setOriginalValue(binValue); updateView(); } public void setOriginalValue(double originalValue) { this.originalValue = originalValue; } public void setCompareValue(DataCell compareCell) { if(Settings.DataType.BIN == table.getCompareValueType()) { if(this.compareToValue == compareCell.binValue) { return; } this.compareToValue = compareCell.binValue; } else { if(this.compareToValue == compareCell.originalValue) { return; } this.compareToValue = compareCell.originalValue; } } public void multiply(double factor) throws UserLevelException { if(table.getCurrentScale().getCategory().equals("Raw Value")) setBinValue(binValue * factor); else { String newValue = (getRealValue() * factor) + ""; //We need to convert from dot to comma, in the case of EU Format. // This is because getRealValue to String has dot notation. if(NumberUtil.getSeperator() == ',') newValue = newValue.replace('.', ','); setRealValue(newValue); } } @Override public boolean equals(Object other) { if(other == null) { return false; } if(!(other instanceof DataCell)) { return false; } DataCell otherCell = (DataCell) other; if(this.table.isStaticDataTable() != otherCell.table.isStaticDataTable()) { return false; } return binValue == otherCell.binValue; } }
gpl-2.0
EricB02/openpnp
src/main/java/org/openpnp/gui/processes/FourPlacementBoardLocationProcess.java
18974
/* Copyright (C) 2011 Jason von Nieda <jason@vonnieda.org> This file is part of OpenPnP. OpenPnP 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. OpenPnP 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 OpenPnP. If not, see <http://www.gnu.org/licenses/>. For more information about OpenPnP visit http://openpnp.org * * Change Log: * 03/10/2012 Ami: Add four points best fit algorithm. * - Takes the two angles of the two opposing corners (the diagonals) from the placements and compare it to the indicated values. * - These are the starting point for the binary search, to find the lowest error. * - Each iteration the mid-point angle is also taken, and all three are evaluated. * - Offset is re-calculated after rotation and averaged */ package org.openpnp.gui.processes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.openpnp.gui.JobPanel; import org.openpnp.gui.MainFrame; import org.openpnp.gui.support.MessageBoxes; import org.openpnp.model.Board.Side; import org.openpnp.model.Configuration; import org.openpnp.model.Location; import org.openpnp.model.Placement; import org.openpnp.model.Point; import org.openpnp.spi.Camera; import org.openpnp.spi.Head; import org.openpnp.util.MovableUtils; import org.openpnp.util.Utils2D; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Guides the user through the two point board location operation using * step by step instructions. * * TODO: Select the right camera on startup and then disable the CameraPanel while active. * TODO: Disable the BoardLocation table while active. */ public class FourPlacementBoardLocationProcess { private static final Logger logger = LoggerFactory.getLogger(FourPlacementBoardLocationProcess.class); private final MainFrame mainFrame; private final JobPanel jobPanel; private int step = -1; private String[] instructions = new String[] { "<html><body>Pick an easily identifiable placement near the TOP-LEFT corner of the board. Select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>Next, pick another placement on the BOTTOM-RIGHT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>And now, pick another placement on the TOP-RIGHT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>Last, pick another placement on the BOTTOM-LEFT corner of the board, select it in the table below and move the camera's crosshairs to it's center location. Click Next to continue.</body></html>", "<html><body>The board's location and rotation has been set. Click Finish to position the camera at the board's origin, or Cancel to quit.</body></html>", }; private Placement placementA, placementB, placementC, placementD; private Location placementLocationA, placementLocationB, placementLocationC, placementLocationD; public FourPlacementBoardLocationProcess(MainFrame mainFrame, JobPanel jobPanel) { this.mainFrame = mainFrame; this.jobPanel = jobPanel; advance(); } private void advance() { boolean stepResult = true; if (step == 0) { stepResult = step1(); } else if (step == 1) { stepResult = step2(); } else if (step == 2) { stepResult = step3(); } else if (step == 3) { stepResult = step4(); } else if (step == 4) { stepResult = step5(); } if (!stepResult) { return; } step++; if (step == 5) { mainFrame.hideInstructions(); } else { String title = String.format("Set Board Location (%d / 5)", step + 1); mainFrame.showInstructions( title, instructions[step], true, true, step == 4 ? "Finish" : "Next", cancelActionListener, proceedActionListener); } } private boolean step1() { placementLocationA = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationA == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementA = jobPanel.getSelectedPlacement(); if (placementA == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step2() { placementLocationB = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationB == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementB = jobPanel.getSelectedPlacement(); if (placementB == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step3() { placementLocationC = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationC == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementC = jobPanel.getSelectedPlacement(); if (placementC == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a placement."); return false; } return true; } private boolean step4() { placementLocationD = MainFrame.cameraPanel.getSelectedCameraLocation(); if (placementLocationD == null) { MessageBoxes.errorBox(mainFrame, "Error", "Please position the camera."); return false; } placementD = jobPanel.getSelectedPlacement(); if (placementD == null || placementD == placementC) { MessageBoxes.errorBox(mainFrame, "Error", "Please select a second placement."); return false; } if ((placementA.getSide() != placementB.getSide()) || (placementC.getSide() != placementD.getSide())){ MessageBoxes.errorBox(mainFrame, "Error", "Both placements must be on the same side of the board."); return false; } // Get the Locations we'll be using and convert to system units. Location boardLocationA = placementLocationA.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationA = placementA.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationB = placementLocationB.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationB = placementB.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationC = placementLocationC.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationC = placementC.getLocation().convertToUnits(Configuration.get().getSystemUnits()); Location boardLocationD = placementLocationD.convertToUnits(Configuration.get().getSystemUnits()); Location placementLocationD = placementD.getLocation().convertToUnits(Configuration.get().getSystemUnits()); // If the placements are on the Bottom of the board we need to invert X if (placementA.getSide() == Side.Bottom) { // boardLocationA = boardLocationA.invert(true, false, false, false); placementLocationA = placementLocationA.invert(true, false, false, false); // boardLocationB = boardLocationB.invert(true, false, false, false); placementLocationB = placementLocationB.invert(true, false, false, false); } if (placementC.getSide() == Side.Bottom) { // boardLocationA = boardLocationA.invert(true, false, false, false); placementLocationC = placementLocationC.invert(true, false, false, false); // boardLocationB = boardLocationB.invert(true, false, false, false); placementLocationD = placementLocationD.invert(true, false, false, false); } logger.debug(String.format("locate")); logger.debug(String.format("%s - %s", boardLocationA, placementLocationA)); logger.debug(String.format("%s - %s", boardLocationB, placementLocationB)); logger.debug(String.format("%s - %s", boardLocationC, placementLocationC)); logger.debug(String.format("%s - %s", boardLocationD, placementLocationD)); double x1 = placementLocationA.getX(); double y1 = placementLocationA.getY(); double x2 = placementLocationB.getX(); double y2 = placementLocationB.getY(); // Center of the placement points used for rotation double centerX = (x1+x2)/2; double centerY = (y1+y2)/2; // Calculate the expected angle between the two coordinates, based // on their locations in the placement. double expectedAngle = Math.atan2(y1 - y2, x1 - x2); expectedAngle = Math.toDegrees(expectedAngle); logger.debug("expectedAngle A-B " + expectedAngle); // Then calculate the actual angle between the two coordinates, // based on the captured values. x1 = boardLocationA.getX(); y1 = boardLocationA.getY(); x2 = boardLocationB.getX(); y2 = boardLocationB.getY(); double indicatedAngle = Math.atan2(y1 - y2, x1 - x2); indicatedAngle = Math.toDegrees(indicatedAngle); logger.debug("indicatedAngle A-B " + indicatedAngle); // Subtract the difference and we have the angle that the board // is rotated by. double angleAB = indicatedAngle - expectedAngle ; // this is the rotation angle to be done logger.debug("angle A-B " + angleAB); // Now do the same for C-D x1 = placementLocationC.getX(); y1 = placementLocationC.getY(); x2 = placementLocationD.getX(); y2 = placementLocationD.getY(); centerX += (x1+x2)/2; centerY += (y1+y2)/2; // Calculate the expected angle between the two coordinates, based // on their locations in the placement. expectedAngle = Math.atan2(y1 - y2, x1 - x2); expectedAngle = Math.toDegrees(expectedAngle); logger.debug("expectedAngle C-D " + expectedAngle); // Then calculate the actual angle between the two coordinates, // based on the captured values. x1 = boardLocationC.getX(); y1 = boardLocationC.getY(); x2 = boardLocationD.getX(); y2 = boardLocationD.getY(); indicatedAngle = Math.atan2(y1 - y2, x1 - x2); indicatedAngle = Math.toDegrees(indicatedAngle); logger.debug("indicatedAngle C-D " + indicatedAngle); // Subtract the difference and we have the angle that the board // is rotated by. double angleCD = indicatedAngle - expectedAngle ; // this is the rotation angle to be done logger.debug("angle C-D " + angleCD); Point center = new Point(centerX/2,centerY/2); // This is the center point of the four board used for rotation double dxAB = 0, dxCD = 0, dxMP = 0; double dyAB = 0, dyCD = 0, dyMP = 0; // Now we do binary search n-times between AngleAB and AngleCD to find lowest error // This is up to as good as we want, I prefer for-loop than while-loop. for(int i = 0; i< 50;++i) { // use angleAB to calculate the displacement necessary to get placementLocation to boardLocation. // Each point will have slightly different value. // Then we can tell the error resulted from using this angleAB. Point A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleAB,0,0,center); Point B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleAB,0,0,center); Point C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleAB,0,0,center); Point D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleAB,0,0,center); double dA = (boardLocationA.getX() - A.getX()); double dB = (boardLocationB.getX() - B.getX()); double dC = (boardLocationC.getX() - C.getX()); double dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxAB = (dA + dB + dC + dD)/4; double errorAB = Math.abs(dxAB- dA) + Math.abs(dxAB- dB) + Math.abs(dxAB- dC) + Math.abs(dxAB- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyAB = (dA + dB + dC + dD)/4; errorAB += Math.abs(dyAB- dA) + Math.abs(dyAB- dB) + Math.abs(dyAB- dC) + Math.abs(dyAB- dD); // Accumulate the error // Now do the same using angleCD, find the error caused by angleCD A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleCD,0,0,center); B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleCD,0,0,center); C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleCD,0,0,center); D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleCD,0,0,center); dA = (boardLocationA.getX() - A.getX()); dB = (boardLocationB.getX() - B.getX()); dC = (boardLocationC.getX() - C.getX()); dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxCD = (dA + dB + dC + dD)/4; double errorCD = Math.abs(dxCD- dA) + Math.abs(dxCD- dB) + Math.abs(dxCD- dC) + Math.abs(dxCD- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyCD = (dA + dB + dC + dD)/4; errorCD += Math.abs(dyCD- dA) + Math.abs(dyCD- dB) + Math.abs(dyCD- dC) + Math.abs(dyCD- dD); // Accumulate the error // Now take the mid-point between the two angles, // and do the same math double angleMP = (angleAB + angleCD)/2; // MP = mid-point angle between angleAB and angleCD double deltaAngle = Math.abs(angleAB - angleCD); A = new Point(placementLocationA.getX(),placementLocationA.getY()); A = Utils2D.rotateTranslateCenterPoint(A, angleMP,0,0,center); B = new Point(placementLocationB.getX(),placementLocationB.getY()); B = Utils2D.rotateTranslateCenterPoint(B, angleMP,0,0,center); C = new Point(placementLocationC.getX(),placementLocationC.getY()); C = Utils2D.rotateTranslateCenterPoint(C, angleMP,0,0,center); D = new Point(placementLocationD.getX(),placementLocationD.getY()); D = Utils2D.rotateTranslateCenterPoint(D, angleMP,0,0,center); dA = (boardLocationA.getX() - A.getX()); dB = (boardLocationB.getX() - B.getX()); dC = (boardLocationC.getX() - C.getX()); dD = (boardLocationD.getX() - D.getX()); // Take the average of the four dxMP = (dA + dB + dC + dD)/4; double errorMP = Math.abs(dxMP- dA) + Math.abs(dxMP- dB) + Math.abs(dxMP- dC) + Math.abs(dxMP- dD); dA = (boardLocationA.getY() - A.getY()); dB = (boardLocationB.getY() - B.getY()); dC = (boardLocationC.getY() - C.getY()); dD = (boardLocationD.getY() - D.getY()); // Take the average of the four dyMP = (dA + dB + dC + dD)/4; errorMP += Math.abs(dyMP- dA) + Math.abs(dyMP- dB) + Math.abs(dyMP- dC) + Math.abs(dyMP- dD); // Accumulate the error // This is gradient descend searching for local minima (hopefully) between angleAB and angle CD logger.debug(String.format("Error AB=%g vs MP=%g vs CD=%g ", errorAB, errorMP, errorCD)); if(errorAB < errorCD) { if(errorMP > errorAB) // ok, so no local minima between AB and CD, let's search beyond AB { angleMP = angleAB; // use as temporary, this is MP of the previous cycle // Beyond means both ways if(angleAB > angleCD) angleAB += deltaAngle; else angleAB -= deltaAngle; angleCD = angleMP; } else { // Local minima is for sure between AB and CD, // best bet it's between MP and AB // otherwise next step it will look on the other side (angleCD + deltaAngle) angleCD = angleMP; } } else { if(errorMP > errorCD) // ok so no local minima between AB and CD, let's search beyond CD { angleMP = angleCD; // use as temporary, this is MP of the previous cycle // Beyond means both ways if(angleCD > angleAB) angleCD += deltaAngle; else angleCD -= deltaAngle; angleAB = angleCD; } else { // local minima is between AB and CD, // best bet it's between MP and CD, so set AB to the mid point (MP) // otherwise next step it will look on the other side (angleCD + deltaAngle) angleAB = angleMP; } } } double angle = (angleAB + angleCD)/2; // take the average logger.debug("angle final " + angle); // Take the average of the four //double dx = (dxAB + dxCD)/2; //double dy = (dyAB + dyCD)/2; double dx = dxMP; double dy = dyMP; logger.debug(String.format("dx %f, dy %f", dx, dy)); Location boardLocation = new Location(Configuration.get() .getSystemUnits(), dx, dy, 0, angle ); Location oldBoardLocation = jobPanel.getSelectedBoardLocation().getLocation(); oldBoardLocation = oldBoardLocation.convertToUnits(boardLocation.getUnits()); boardLocation = boardLocation.derive(null, null, oldBoardLocation.getZ(), null); jobPanel.getSelectedBoardLocation().setLocation(boardLocation); // TODO: Set Board center point when center points are finished. // jobPanel.getSelectedBoardLocation().setCenter(center); jobPanel.refreshSelectedBoardRow(); return true; } private boolean step5() { MainFrame.machineControlsPanel.submitMachineTask(new Runnable() { public void run() { Head head = Configuration.get().getMachine().getHeads().get(0); try { Camera camera = MainFrame.cameraPanel .getSelectedCamera(); Location location = jobPanel.getSelectedBoardLocation() .getLocation(); MovableUtils.moveToLocationAtSafeZ(camera, location, 1.0); } catch (Exception e) { MessageBoxes.errorBox(mainFrame, "Move Error", e); } } }); return true; } private void cancel() { mainFrame.hideInstructions(); } private final ActionListener proceedActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { advance(); } }; private final ActionListener cancelActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cancel(); } }; }
gpl-3.0
mbarto/mapfish-print
src/main/java/org/mapfish/print/MapPrinter.java
7087
/* * Copyright (C) 2013 Camptocamp * * This file is part of MapFish Print * * MapFish Print 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. * * MapFish Print 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 MapFish Print. If not, see <http://www.gnu.org/licenses/>. */ package org.mapfish.print; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.TreeSet; import java.util.Map; import javax.annotation.PreDestroy; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import org.mapfish.print.config.Config; import org.mapfish.print.config.ConfigFactory; import org.mapfish.print.output.OutputFactory; import org.mapfish.print.output.OutputFormat; import org.mapfish.print.output.PrintParams; import org.mapfish.print.utils.PJsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import com.lowagie.text.DocumentException; import com.lowagie.text.FontFactory; import com.lowagie.text.pdf.ByteBuffer; /** * The main class for printing maps. Will parse the spec, create the PDF * document and generate it. * * This class should not be directly created but rather obtained from an application * context object so that all plugins and dependencies are correctly injected into it */ public class MapPrinter { /** * The parsed configuration file. * * This is a per instance property and while can be set by spring typically will be set by user of printer */ private Config config; /** * The directory where the configuration file sits (used for ${configDir}) * * This is a per instance property and while can be set by spring typically will be set by user of printer */ private File configDir; /** * OutputFactory for the final output * * Injected by Spring */ private OutputFactory outputFactory; /** * Factory for creating config objects * * Injected by Spring */ private ConfigFactory configFactory; private volatile boolean fontsInitialized = false; static { //configure iText to use a higher precision for floats ByteBuffer.HIGH_PRECISION = true; } /** * OutputFactory for the final output * * Injected by Spring */ @Autowired @Required public void setOutputFactory(OutputFactory outputFactory) { this.outputFactory = outputFactory; } /** * Factory for creating config objects * * Injected by Spring */ @Autowired @Required public void setConfigFactory(ConfigFactory configFactory) { this.configFactory = configFactory; } /** * Sets both the configuration by parsing the configFile and the configDir relative to the configFile * @param configFile * @throws FileNotFoundException * @return this */ public MapPrinter setYamlConfigFile(File configFile) throws FileNotFoundException { this.config = configFactory.fromYaml(configFile); configDir = configFile.getParentFile(); if (configDir == null) { try { configDir = new File(".").getCanonicalFile(); } catch (IOException e) { configDir = new File("."); } } return this; } public MapPrinter setConfig(String strConfig) { this.config = configFactory.fromString(strConfig); return this; } public MapPrinter setConfig(InputStream inputConfig) { this.config = configFactory.fromInputStream(inputConfig); return this; } public MapPrinter setConfigDir(String configDir) { this.configDir = new File(configDir); return this; } /** * Register the user specified fonts in iText. */ private void initFonts() { if(!fontsInitialized) { synchronized (this) { if(!fontsInitialized) { //we don't do that since it takes ages and that would hurt the perfs for //the python controller: //FontFactory.registerDirectories(); FontFactory.defaultEmbedding = true; final TreeSet<String> fontPaths = config.getFonts(); if (fontPaths != null) { for (String fontPath : fontPaths) { fontPath = fontPath.replaceAll("\\$\\{configDir\\}", configDir.getPath()); File fontFile = new File(fontPath); if (fontFile.isDirectory()) { FontFactory.registerDirectory(fontPath, true); } else { FontFactory.register(fontPath); } } } } } } } /** * Generate the PDF using the given spec. * * @return The context that was used for printing. * @throws InterruptedException */ public RenderingContext print(PJsonObject jsonSpec, OutputStream outputStream, Map<String, String> headers) throws DocumentException, InterruptedException { initFonts(); OutputFormat output = this.outputFactory.create(config, jsonSpec); PrintParams params = new PrintParams(config, configDir, jsonSpec, outputStream, headers); return output.print(params ); } public static PJsonObject parseSpec(String spec) { final JSONObject jsonSpec; try { jsonSpec = new JSONObject(spec); } catch (JSONException e) { throw new RuntimeException("Cannot parse the spec file", e); } return new PJsonObject(jsonSpec, "spec"); } /** * Use by /info.json to generate its returned content. */ public void printClientConfig(JSONWriter json) throws JSONException { config.printClientConfig(json); } /** * Stop the thread pool or others. */ @PreDestroy public void stop() { config.close(); } public String getOutputFilename(String layout, String defaultName) { final String name = config.getOutputFilename(layout); return name == null ? defaultName : name; } public Config getConfig() { return config; } public OutputFormat getOutputFormat(PJsonObject jsonSpec) { return outputFactory.create(config, jsonSpec); } }
gpl-3.0
doglover129/GriefLog
src/tk/blackwolf12333/grieflog/compatibility/v1_6_R3/ChangesSender.java
1314
package tk.blackwolf12333.grieflog.compatibility.v1_6_R3; import java.util.HashSet; import org.bukkit.Chunk; import org.bukkit.entity.Player; import tk.blackwolf12333.grieflog.compatibility.ChangesSenderInterface; import tk.blackwolf12333.grieflog.rollback.SendChangesTask; public class ChangesSender implements ChangesSenderInterface { @SuppressWarnings("unchecked") @Override public void sendChanges(SendChangesTask task, HashSet<Chunk> chunks) { HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair> pairs = new HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair>(); for (Chunk c : chunks) { pairs.add(new net.minecraft.server.v1_6_R3.ChunkCoordIntPair(c.getX(), c.getZ())); } for (Player p : task.getPlayers()) { HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair> queued = new HashSet<net.minecraft.server.v1_6_R3.ChunkCoordIntPair>(); if (p != null) { net.minecraft.server.v1_6_R3.EntityPlayer ep = ((org.bukkit.craftbukkit.v1_6_R3.entity.CraftPlayer) p).getHandle(); for (Object o : ep.chunkCoordIntPairQueue) { queued.add((net.minecraft.server.v1_6_R3.ChunkCoordIntPair) o); } for (net.minecraft.server.v1_6_R3.ChunkCoordIntPair pair : pairs) { if (!queued.contains(pair)) { ep.chunkCoordIntPairQueue.add(pair); } } } } } }
gpl-3.0
ckramp/structr
structr-db-driver-api/src/main/java/org/structr/api/util/ProgressWatcher.java
857
/* * 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.api.util; /** */ public interface ProgressWatcher { boolean okToContinue(final int progress); }
gpl-3.0
jomifred/jacamo
examples/house-building/src/env/simulator/House.java
2704
package simulator; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; import cartago.OPERATION; import cartago.tools.GUIArtifact; public class House extends GUIArtifact { HouseView view; @Override public void init(){ view = new HouseView(); view.setVisible(true); } // Actions that simulate the building progress @OPERATION void prepareSite(){ view.addPart(new Site()); } @OPERATION void layFloors(){ await_time(1000); view.addPart(new Floor()); } @OPERATION void buildWalls(){ await_time(500); view.addPart(new Walls()); } @OPERATION void buildRoof(){ await_time(1000); view.addPart(new Roof()); } @OPERATION void fitDoors(){ await_time(300); view.addPart(new Doors()); } @OPERATION void fitWindows(){ await_time(300); view.addPart(new Windows()); } @OPERATION void paintExterior(){ await_time(2000); view.addPart(new ExteriorPainting()); } @OPERATION void installPlumbing(){ await_time(300); view.addPart(new Plumbing()); } @OPERATION void installElectricalSystem(){ await_time(300); view.addPart(new ElectricalSystem()); } @OPERATION void paintInterior(){ await_time(500); view.addPart(new InteriorPainting()); } class HouseView extends JFrame { HousePanel housePanel; ArrayList<HousePart> partsToDraw; public HouseView(){ setTitle(" -- Home Sweet Home -- "); setSize(800,600); partsToDraw = new ArrayList<HousePart>(); housePanel = new HousePanel(this); setContentPane(housePanel); } public synchronized void addPart(HousePart part){ partsToDraw.add(part); repaint(); } public synchronized ArrayList<HousePart> getParts(){ return (ArrayList<HousePart>)partsToDraw.clone(); } } class HousePanel extends JPanel { HouseView view; public HousePanel(HouseView view){ this.view = view; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); Dimension size = getSize(); g.fillRect(0, 0, size.width, size.height); for (HousePart part: view.getParts()){ part.draw(size,(Graphics2D)g); } } } }
gpl-3.0
expertisesolutions/ghtv-ncl-player
java/ghtv/awt/LwuitComponent.java
1801
/* (c) Copyright 2011-2014 Felipe Magno de Almeida * * 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 ghtv.awt; import java.awt.Container; import java.awt.Component; public class LwuitComponent extends Container { private com.sun.dtv.lwuit.Component lwuit_component; public LwuitComponent(com.sun.dtv.lwuit.Component c) { assert c != null; lwuit_component = c; } public void paint(java.awt.Graphics g) { java.awt.Graphics2D g2d = (java.awt.Graphics2D)g; lwuit_component.paint(new com.sun.dtv.lwuit.Graphics(g2d)); } // public void longKeyPress(int keyCode) // { // form.longKeyPress(keyCode); // } // public void keyPressed(int keyCode) // { // form.keyPressed(keyCode); // } // public void keyReleased(int keyCode) // { // form.keyReleased(keyCode); // } // public void keyRepeated(int keyCode) // { // form.keyRepeated(keyCode); // } // public void pointerPressed(int x, int y) // { // form.pointerPressed(x, y); // } // public void pointerDragged(int x, int y) // { // form.pointerDragged(x, y); // } }
gpl-3.0
DivineCooperation/bco.dal
test/src/test/java/org/openbase/bco/dal/test/layer/unit/location/AbstractBCOLocationManagerTest.java
4041
package org.openbase.bco.dal.test.layer.unit.location; /*- * #%L * BCO DAL Test * %% * Copyright (C) 2014 - 2021 openbase.org * %% * 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 General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.jupiter.api.AfterEach; import org.openbase.bco.dal.control.layer.unit.device.DeviceManagerLauncher; import org.openbase.bco.dal.control.layer.unit.user.UserManagerLauncher; import org.openbase.bco.dal.lib.layer.unit.UnitController; import org.openbase.bco.dal.test.AbstractBCOTest; import org.openbase.bco.dal.control.layer.unit.location.LocationManagerLauncher; import org.openbase.bco.dal.test.layer.unit.device.AbstractBCODeviceManagerTest; import org.openbase.jul.exception.CouldNotPerformException; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:pLeminoq@openbase.org">Tamino Huxohl</a> */ @Slf4j public class AbstractBCOLocationManagerTest extends AbstractBCOTest { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AbstractBCOLocationManagerTest.class); protected static DeviceManagerLauncher deviceManagerLauncher; protected static LocationManagerLauncher locationManagerLauncher; protected static UserManagerLauncher userManagerLauncher; @BeforeClass public static void setUpClass() throws Throwable { try { AbstractBCOTest.setUpClass(); deviceManagerLauncher = new DeviceManagerLauncher(); deviceManagerLauncher.launch().get(); userManagerLauncher = new UserManagerLauncher(); userManagerLauncher.launch().get(); locationManagerLauncher = new LocationManagerLauncher(); locationManagerLauncher.launch().get(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } } @AfterClass public static void tearDownClass() throws Throwable { try { if (userManagerLauncher != null) { userManagerLauncher.shutdown(); } if (deviceManagerLauncher != null) { deviceManagerLauncher.shutdown(); } if (locationManagerLauncher != null) { locationManagerLauncher.shutdown(); } AbstractBCOTest.tearDownClass(); } catch (Throwable ex) { throw ExceptionPrinter.printHistoryAndReturnThrowable(ex, logger); } } /** * Method is for unit tests where one has to make sure that all actions are removed from the action stack in order to minimize influence of other tests. * * @throws InterruptedException is thrown if the thread was externally interrupted */ @AfterEach @After public void cancelAllOngoingActions() throws InterruptedException { log.info("Cancel all ongoing actions..."); try { for (UnitController<?, ?> deviceController : deviceManagerLauncher.getLaunchable().getUnitControllerRegistry().getEntries()) { deviceController.cancelAllActions(); } } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory("Could not cancel all ongoing actions!", ex, log); } } }
gpl-3.0
denislobanov/grakn
mindmaps-graph/src/main/java/io/mindmaps/graph/internal/ResourceTypeImpl.java
3522
/* * MindmapsDB - A Distributed Semantic Database * Copyright (C) 2016 Mindmaps Research Ltd * * MindmapsDB 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. * * MindmapsDB 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 MindmapsDB. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package io.mindmaps.graph.internal; import io.mindmaps.concept.Resource; import io.mindmaps.concept.ResourceType; import io.mindmaps.exception.InvalidConceptValueException; import io.mindmaps.util.ErrorMessage; import io.mindmaps.util.Schema; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A Resource Type which can hold different values. * @param <D> The data tyoe of this resource type. */ class ResourceTypeImpl<D> extends TypeImpl<ResourceType<D>, Resource<D>> implements ResourceType<D> { ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph) { super(v, mindmapsGraph); } ResourceTypeImpl(Vertex v, AbstractMindmapsGraph mindmapsGraph, DataType<D> type) { super(v, mindmapsGraph); setDataType(type); } /** * * @param type The data type of the resource */ private void setDataType(DataType<D> type) { setProperty(Schema.ConceptProperty.DATA_TYPE, type.getName()); } /** * @param regex The regular expression which instances of this resource must conform to. * @return The Resource Type itself. */ @Override public ResourceType<D> setRegex(String regex) { if(!getDataType().equals(DataType.STRING)){ throw new UnsupportedOperationException(ErrorMessage.REGEX_NOT_STRING.getMessage(toString())); } if(regex != null) { Pattern pattern = Pattern.compile(regex); Matcher matcher; for (Resource<D> resource : instances()) { String value = (String) resource.getValue(); matcher = pattern.matcher(value); if(!matcher.matches()){ throw new InvalidConceptValueException(ErrorMessage.REGEX_INSTANCE_FAILURE.getMessage(regex, resource.toString())); } } } return setProperty(Schema.ConceptProperty.REGEX, regex); } /** * @return The data type which instances of this resource must conform to. */ //This unsafe cast is suppressed because at this stage we do not know what the type is when reading from the rootGraph. @SuppressWarnings("unchecked") @Override public DataType<D> getDataType() { Object object = getProperty(Schema.ConceptProperty.DATA_TYPE); return (DataType<D>) DataType.SUPPORTED_TYPES.get(String.valueOf(object)); } /** * @return The regular expression which instances of this resource must conform to. */ @Override public String getRegex() { Object object = getProperty(Schema.ConceptProperty.REGEX); if(object == null) return null; return (String) object; } }
gpl-3.0
TheMurderer/keel
src/keel/Algorithms/Instance_Generation/BasicMethods/AVG.java
4311
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.Instance_Generation.BasicMethods; import keel.Algorithms.Instance_Generation.Basic.PrototypeSet; import keel.Algorithms.Instance_Generation.Basic.PrototypeGenerator; import keel.Algorithms.Instance_Generation.Basic.Prototype; import keel.Algorithms.Instance_Generation.Basic.PrototypeGenerationAlgorithm; import keel.Algorithms.Instance_Generation.*; import java.util.*; import keel.Algorithms.Instance_Generation.utilities.*; import keel.Algorithms.Instance_Generation.utilities.KNN.*; import org.core.*; /** * Implements the reduction of the prototype set, making a centroid for each class. * That is, it adds average prototypes of each class to the reduced set. * @author diegoj */ public class AVG extends PrototypeGenerator { /** * Constructs the AVG * @param _trainingDataSet Original training prototypes set. */ public AVG(PrototypeSet _trainingDataSet) { super(_trainingDataSet); algorithmName="AVG"; } /** * Constructs the AVG * @param _trainingDataSet Original training prototypes set. * @param param Parameters of the algorithm (random seed). */ public AVG(PrototypeSet _trainingDataSet, Parameters param) { super(_trainingDataSet, param); algorithmName="AVG"; } /** * Reduces the set by adding centroid prototype of each class to reduced set. * @return Reduced set of centroids of classes of the original training set. */ @Override public PrototypeSet reduceSet() { PrototypeSet reduced = new PrototypeSet(); ArrayList<Double> classes = trainingDataSet.nonVoidClasses(); //For each class in the training data set, calculate the centroid of //its class-partition and adds it to the reduced set. for(double c : classes) { PrototypeSet Tc = trainingDataSet.getFromClass(c); //Debug.errorln("Number of ps of class " + c + ": " + Tc.size()); Prototype centroid_c =Tc.avg(); centroid_c.setLabel(c); reduced.add(centroid_c); } return reduced; } /** * General main for all the prototoype generators * Arguments: * 0: Filename with the training data set to be condensed. * 1: Filename wich will contain the test data set * @param args Arguments of the main function. */ public static void main(String[] args) { Parameters.setUse("AVG", ""); Parameters.assertBasicArgs(args); PrototypeSet training = PrototypeGenerationAlgorithm.readPrototypeSet(args[0]); PrototypeSet test = PrototypeGenerationAlgorithm.readPrototypeSet(args[1]); AVG generator = new AVG(training); PrototypeSet resultingSet = generator.execute(); int accuracy1NN = KNN.classficationAccuracy(resultingSet, test); generator.showResultsOfAccuracy(Parameters.getFileName(), accuracy1NN, test); } }//end-of-class
gpl-3.0
frogocomics/WorldPainter
WorldPainter/WPCore/src/main/java/org/pepsoft/worldpainter/layers/Jungle.java
1265
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.worldpainter.layers; import java.util.Random; import org.pepsoft.worldpainter.layers.trees.Bush; import org.pepsoft.worldpainter.layers.trees.JungleTree; import org.pepsoft.worldpainter.layers.trees.OakTree; import org.pepsoft.worldpainter.layers.trees.TreeType; /** * * @author pepijn */ public class Jungle extends TreeLayer { private Jungle() { super("Jungle", "a jungle", 43); } @Override public TreeType pickTree(Random random) { int rnd = random.nextInt(20); if (rnd == 0) { return OAK_TREE; } else if (rnd < 10) { return JUNGLE_TREE; } else { return BUSH; } } public int getDefaultTreeChance() { return 640; } @Override public int getDefaultLayerStrengthCap() { return 9; } public static final Jungle INSTANCE = new Jungle(); private static final JungleTree JUNGLE_TREE = new JungleTree(); private static final OakTree OAK_TREE = new OakTree(); private static final Bush BUSH = new Bush(); private static final long serialVersionUID = 1L; }
gpl-3.0
kirilenkoo/neo4j-mobile-android
neo4j-android/kernel-src/org/neo4j/kernel/impl/core/GraphDbModule.java
7634
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU 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.neo4j.kernel.impl.core; import java.util.Arrays; import java.util.Map; import java.util.logging.Logger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.TransactionManager; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.NotFoundException; import org.neo4j.graphdb.RelationshipType; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.kernel.Config; import org.neo4j.kernel.impl.cache.AdaptiveCacheManager; import org.neo4j.kernel.impl.core.NodeManager.CacheType; import org.neo4j.kernel.impl.nioneo.store.PropertyIndexData; import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeData; import org.neo4j.kernel.impl.persistence.EntityIdGenerator; import org.neo4j.kernel.impl.persistence.PersistenceManager; import org.neo4j.kernel.impl.transaction.LockManager; public class GraphDbModule { private static final CacheType DEFAULT_CACHE_TYPE = CacheType.soft; private static Logger log = Logger.getLogger( GraphDbModule.class.getName() ); private boolean startIsOk = true; private static final int INDEX_COUNT = 2500; private final GraphDatabaseService graphDbService; private final TransactionManager transactionManager; private final AdaptiveCacheManager cacheManager; private final LockManager lockManager; private final EntityIdGenerator idGenerator; private NodeManager nodeManager; private boolean readOnly = false; public GraphDbModule( GraphDatabaseService graphDb, AdaptiveCacheManager cacheManager, LockManager lockManager, TransactionManager transactionManager, EntityIdGenerator idGenerator, boolean readOnly ) { this.graphDbService = graphDb; this.cacheManager = cacheManager; this.lockManager = lockManager; this.transactionManager = transactionManager; this.idGenerator = idGenerator; this.readOnly = readOnly; } public void init() { } public void start( LockReleaser lockReleaser, PersistenceManager persistenceManager, RelationshipTypeCreator relTypeCreator, Map<Object,Object> params ) { if ( !startIsOk ) { return; } String cacheTypeName = (String) params.get( Config.CACHE_TYPE ); CacheType cacheType = null; try { cacheType = cacheTypeName != null ? CacheType.valueOf( cacheTypeName ) : DEFAULT_CACHE_TYPE; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( "Invalid cache type, please use one of: " + Arrays.asList( CacheType.values() ) + " or keep empty for default (" + DEFAULT_CACHE_TYPE + ")", e.getCause() ); } if ( !readOnly ) { nodeManager = new NodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, relTypeCreator, cacheType ); } else { nodeManager = new ReadOnlyNodeManager( graphDbService, cacheManager, lockManager, lockReleaser, transactionManager, persistenceManager, idGenerator, cacheType ); } // load and verify from PS RelationshipTypeData relTypes[] = null; PropertyIndexData propertyIndexes[] = null; // beginTx(); relTypes = persistenceManager.loadAllRelationshipTypes(); propertyIndexes = persistenceManager.loadPropertyIndexes( INDEX_COUNT ); // commitTx(); nodeManager.addRawRelationshipTypes( relTypes ); nodeManager.addPropertyIndexes( propertyIndexes ); if ( propertyIndexes.length < INDEX_COUNT ) { nodeManager.setHasAllpropertyIndexes( true ); } nodeManager.start( params ); startIsOk = false; } private void beginTx() { try { transactionManager.begin(); } catch ( NotSupportedException e ) { throw new TransactionFailureException( "Unable to begin transaction.", e ); } catch ( SystemException e ) { throw new TransactionFailureException( "Unable to begin transaction.", e ); } } private void commitTx() { try { transactionManager.commit(); } catch ( SecurityException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( IllegalStateException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( RollbackException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( HeuristicMixedException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( HeuristicRollbackException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } catch ( SystemException e ) { throw new TransactionFailureException( "Failed to commit.", e ); } } public void setReferenceNodeId( Long nodeId ) { nodeManager.setReferenceNodeId( nodeId.longValue() ); try { nodeManager.getReferenceNode(); } catch ( NotFoundException e ) { log.warning( "Reference node[" + nodeId + "] not valid." ); } } public Long getCurrentReferenceNodeId() { try { return nodeManager.getReferenceNode().getId(); } catch ( NotFoundException e ) { return -1L; } } public void createNewReferenceNode() { Node node = nodeManager.createNode(); nodeManager.setReferenceNodeId( node.getId() ); } public void reload( Map<Object,Object> params ) { throw new UnsupportedOperationException(); } public void stop() { nodeManager.clearPropertyIndexes(); nodeManager.clearCache(); nodeManager.stop(); } public void destroy() { } public NodeManager getNodeManager() { return this.nodeManager; } public Iterable<RelationshipType> getRelationshipTypes() { return nodeManager.getRelationshipTypes(); } }
gpl-3.0
agicquel/dut
M2103/TP9/src/Comparable.java
108
/** * Generic interface to compare objects */ public interface Comparable<T> { public int compareTo(T o); }
gpl-3.0
javadch/quis
xqt.model/src/main/java/xqt/model/functions/aggregates/Count.java
589
/* * 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 xqt.model.functions.aggregates; import xqt.model.functions.AggregateFunction; /** * * @author Javad Chamanara <chamanara@gmail.com> */ public class Count implements AggregateFunction{ long counter = 0; @Override public Long move(Object data) { // Long is a subclass of Object, hence, compatible... if(data != null) counter++; return counter; } }
gpl-3.0
ariesteam/thinklab
plugins/org.integratedmodelling.thinklab.corescience/src/org/integratedmodelling/corescience/transformations/Log10Plus1.java
1243
/** * Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and * www.integratedmodelling.org. This file is part of Thinklab. Thinklab 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. Thinklab 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 Thinklab. If not, see <http://www.gnu.org/licenses/>. */ package org.integratedmodelling.corescience.transformations; import org.integratedmodelling.thinklab.interfaces.annotations.DataTransformation; import org.integratedmodelling.thinklab.transformations.ITransformation; @DataTransformation(id="log10plus1") public class Log10Plus1 implements ITransformation { @Override public double transform(Object value, Object[] parameters) { return Math.log10((Double)value + 1.0); } }
gpl-3.0
OpenWIS/openwis
openwis-dataservice/openwis-dataservice-server/openwis-dataservice-server-ejb/src/main/java/org/openwis/datasource/server/service/impl/ProductMetadataServiceImpl.java
17721
/** * */ package org.openwis.datasource.server.service.impl; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.jws.WebParam; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.openwis.dataservice.common.domain.entity.cache.PatternMetadataMapping; import org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn; import org.openwis.dataservice.common.domain.entity.enumeration.SortDirection; import org.openwis.dataservice.common.domain.entity.request.ProductMetadata; import org.openwis.dataservice.common.domain.entity.request.Request; import org.openwis.dataservice.common.exception.CannotDeleteAllProductMetadataException; import org.openwis.dataservice.common.exception.CannotDeleteProductMetadataException; import org.openwis.dataservice.common.service.ProductMetadataService; import org.openwis.dataservice.common.util.DateTimeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Session Bean implementation of class Product metadata service */ @Remote(ProductMetadataService.class) @Stateless(name = "ProductMetadataService") @WebService(targetNamespace = "http://dataservice.openwis.org/", name = "ProductMetadataService", portName = "ProductMetadataServicePort", serviceName = "ProductMetadataService") @SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED) public class ProductMetadataServiceImpl implements ProductMetadataService { /** The Constant STOP_GAP_GTS_CATEGORY. */ private static final String STOP_GAP_GTS_CATEGORY = "WMO Additional"; /** The Constant STOP_GAP_DATA_POLICY. */ private static final String STOP_GAP_DATA_POLICY = "additional-default"; /** The Constant STOP_GAP_PROCESS. */ private static final String STOP_GAP_PROCESS = "LOCAL"; /** The Constant STOP_GAP_TITLE_TEMPLATE. */ private static final String STOP_GAP_TITLE_TEMPLATE = "[Draft] for {0}"; /** The Constant STOP_GAP_URN_TEMPLATE. */ private static final String STOP_GAP_URN_TEMPLATE = "urn:x-wmo:md:int.wmo.wis::{0}"; /** The logger */ private static Logger logger = LoggerFactory.getLogger(ProductMetadataServiceImpl.class); /** * The entity manager. */ @PersistenceContext private EntityManager entityManager; /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductMetadataByUrn(java.lang.String) */ @Override public ProductMetadata getProductMetadataByUrn(@WebParam(name = "productMetadataUrn") String urn) { ProductMetadata result; logger.debug("Get a ProductMetaData by URN: {}", urn); if (urn == null) { throw new IllegalArgumentException("Product Metadata urn must not be null!"); } Query query = entityManager.createNamedQuery("ProductMetadata.FindByUrn").setParameter("urn", urn); try { result = (ProductMetadata) query.getSingleResult(); } catch (NoResultException e) { result = null; } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductMetadataById(java.lang.Long) */ @Override public ProductMetadata getProductMetadataById(@WebParam(name = "id") Long id) { ProductMetadata result = null; logger.debug("Get a ProductMetaData by id: {}", id); if (id != null) { result = entityManager.find(ProductMetadata.class, id); } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * getAllProductsMetadata(int, int, org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn, * org.openwis.dataservice.common.domain.entity.enumeration.SortDirection) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getAllProductsMetadata( @WebParam(name = "firstResult") int firstResult, @WebParam(name = "maxResults") int maxResults, @WebParam(name = "column") ProductMetadataColumn column, @WebParam(name = "sortDirection") SortDirection sortDirection) { List<ProductMetadata> result; logger.debug("Get All ProductMetaData"); // Check arguments if (firstResult < 0) { throw new IllegalArgumentException("FirstResult must be ≥ 0!"); } if (maxResults <= 0) { throw new IllegalArgumentException("MaxResults must be > 0!"); } // Default column is URN ProductMetadataColumn col; if (column != null) { col = column; } else { col = ProductMetadataColumn.URN; } // Default direction is Descending SortDirection dir; if (sortDirection != null) { dir = sortDirection; } else { dir = SortDirection.ASC; } // Create query String q = MessageFormat.format("SELECT pm FROM ProductMetadata pm ORDER BY pm.{0} {1}", col.getAttribute(), dir); Query query = entityManager.createQuery(q); query.setFirstResult(firstResult); query.setMaxResults(maxResults); // Process query try { result = query.getResultList(); } catch (NoResultException e) { result = Collections.emptyList(); } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getLastStopGapMetadata(java.lang.String) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getLastStopGapMetadata(@WebParam(name = "since") String since) { List<ProductMetadata> result = null; Query query = null; try { Date date = DateTimeUtils.parseDateTime(since); query = entityManager.createNamedQuery("ProductMetadata.getLastStopGap"); query.setParameter("since", date); } catch (Exception e) { // ParseException or NullPointerException query = entityManager.createNamedQuery("ProductMetadata.getAllStopGap"); } result = query.getResultList(); return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#createStopGapMetadata(java.lang.String, java.lang.String, java.lang.String, int) */ @Override public Long createStopGapMetadata(@WebParam(name = "ttaaii") String ttaaii, @WebParam(name = "originator") String originator, @WebParam(name = "priority") int priority) { ProductMetadata pm = new ProductMetadata(); pm.setUrn(MessageFormat.format(STOP_GAP_URN_TEMPLATE, ttaaii)); pm.setOriginator(originator); pm.setPriority(priority); pm.setTitle(MessageFormat.format(STOP_GAP_TITLE_TEMPLATE, ttaaii)); pm.setProcess(STOP_GAP_PROCESS); pm.setDataPolicy(STOP_GAP_DATA_POLICY); pm.setGtsCategory(STOP_GAP_GTS_CATEGORY); pm.setStopGap(true); pm.setFed(Boolean.FALSE); pm.setIngested(Boolean.FALSE); pm.setLocalDataSource(""); return createProductMetadata(pm); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService#getProductsMetadataCount() */ @Override public int getProductsMetadataCount() { Query query = entityManager.createNamedQuery("ProductMetadata.count"); Number result = (Number) query.getSingleResult(); return result.intValue(); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * getProductsMetadataByUrns(java.util.List, int, int, * org.openwis.dataservice.common.domain.entity.enumeration.ProductMetadataColumn, * org.openwis.dataservice.common.domain.entity.enumeration.SortDirection) */ @SuppressWarnings("unchecked") @Override public List<ProductMetadata> getProductsMetadataByUrns( @WebParam(name = "urns") List<String> urns, @WebParam(name = "firstResult") int firstResult, @WebParam(name = "maxResults") int maxResults, @WebParam(name = "column") ProductMetadataColumn column, @WebParam(name = "sortDirection") SortDirection sortDirection) { List<ProductMetadata> result; logger.debug("Get ProductsMetaData by URNs: {}", urns); // Check arguments if (firstResult < 0) { throw new IllegalArgumentException("FirstResult must be ≥ 0 !"); } if (maxResults <= 0) { throw new IllegalArgumentException("MaxResults must be > 0 !"); } // Default column is URN ProductMetadataColumn col; if (column != null) { col = column; } else { col = ProductMetadataColumn.URN; } // Default direction is Descending SortDirection dir; if (sortDirection != null) { dir = sortDirection; } else { dir = SortDirection.ASC; } // build URNs if (urns == null || urns.isEmpty()) { result = Collections.emptyList(); } else { // create URN list String allUrns = buildUrns(urns); // Create query String q = MessageFormat .format( "SELECT pm FROM ProductMetadata pm WHERE lower(pm.urn) IN ({0}) ORDER BY pm.{1} {2}", allUrns, col.getAttribute(), dir); Query query = entityManager.createQuery(q); query.setFirstResult(firstResult); query.setMaxResults(maxResults); // Process query try { result = query.getResultList(); } catch (NoResultException e) { result = Collections.emptyList(); } } return result; } /** * Description goes here. * * @param urns the urns * @return the string */ private String buildUrns(List<String> urns) { StringBuffer allUrns = new StringBuffer(); boolean isFirst = true; for (String urn : urns) { if (StringUtils.isNotEmpty(urn)) { if (isFirst) { isFirst = false; } else { allUrns.append(", "); } allUrns.append('\''); allUrns.append(StringEscapeUtils.escapeSql(urn.toLowerCase())); allUrns.append('\''); } } return allUrns.toString(); } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * createProductMetadata(org.openwis.dataservice.common.domain.entity.request.ProductMetadata) */ @Override public Long createProductMetadata( @WebParam(name = "productMetadata") ProductMetadata productMetadata) { if (productMetadata == null) { throw new IllegalArgumentException("ProductMetadata must not being null !"); } // Check URN String urn = productMetadata.getUrn(); if (StringUtils.isEmpty(urn)) { throw new IllegalArgumentException("URN must not being empty !"); } // Check Unicity if (getProductMetadataByUrn(urn) != null) { throw new IllegalArgumentException("A product with the same URN already exists"); } if (productMetadata.getCreationDate() == null) { productMetadata.setCreationDate(DateTimeUtils.getUTCTime()); } logger.info("Creating a ProductMetaData: " + urn); // Creation entityManager.persist(productMetadata); // Get pattern String pmPattern; if (productMetadata.getOverridenFncPattern() != null) { pmPattern = productMetadata.getOverridenFncPattern(); } else { pmPattern = productMetadata.getFncPattern(); } // Handle pattern mapping PatternMetadataMapping pmm; if (StringUtils.isNotBlank(pmPattern)) { // Create pmm = new PatternMetadataMapping(); pmm.setPattern(pmPattern); pmm.setProductMetadata(productMetadata); entityManager.persist(pmm); } entityManager.flush(); return productMetadata.getId(); } /** * Gets the all pattern metadata mapping. * * @return the all pattern metadata mapping */ @SuppressWarnings("unchecked") @Override public List<PatternMetadataMapping> getAllPatternMetadataMapping() { Query query = entityManager.createNamedQuery("PatternMetadataMapping.all"); List<PatternMetadataMapping> result = query.getResultList(); if (result == null) { result = new ArrayList<PatternMetadataMapping>(); } return result; } /** * {@inheritDoc} * @throws CannotDeleteProductMetadataException * @see org.openwis.dataservice.common.service.ProductMetadataService#deleteProductMetadata(java.lang.Long) */ @Override public void deleteProductMetadata(@WebParam(name = "productMetadataId") Long id) { ProductMetadata productMetadata = entityManager.find(ProductMetadata.class, id); if (productMetadata != null) { logger.info("Removing a ProductMetaData: " + productMetadata.getUrn()); PatternMetadataMapping pmm = retrievePatternMetadataMapping(productMetadata); if (pmm != null) { entityManager.remove(pmm); } entityManager.remove(productMetadata); } } /** * Retrieve pattern metadata mapping. * * @param productMetadata the product metadata * @return the pattern metadata mapping */ private PatternMetadataMapping retrievePatternMetadataMapping(ProductMetadata productMetadata) { PatternMetadataMapping result = null; if (productMetadata != null) { Query query = entityManager.createNamedQuery("PatternMetadataMapping.byProductMetadata"); query.setParameter("pm", productMetadata); try { result = (PatternMetadataMapping) query.getSingleResult(); } catch (NoResultException e) { result = null; } } return result; } /** * {@inheritDoc} * @see org.openwis.dataservice.common.service.ProductMetadataService# * updateProductMetadata(org.openwis.dataservice.common.domain.entity.request.ProductMetadata) */ @Override public void updateProductMetadata( @WebParam(name = "productMetadata") ProductMetadata productMetadata) { logger.info("Updating a ProductMetaData: " + productMetadata.getUrn()); entityManager.merge(productMetadata); // Get pattern String pmPattern; if (productMetadata.getOverridenFncPattern() != null) { pmPattern = productMetadata.getOverridenFncPattern(); } else { pmPattern = productMetadata.getFncPattern(); } // Handle pattern mapping PatternMetadataMapping pmm = retrievePatternMetadataMapping(productMetadata); if (pmm == null && StringUtils.isNotBlank(pmPattern)) { // Create pmm = new PatternMetadataMapping(); pmm.setPattern(pmPattern); pmm.setProductMetadata(productMetadata); entityManager.persist(pmm); } else if (pmm != null && !pmm.getPattern().equals(pmPattern)) { if (pmPattern == null) { entityManager.remove(pmm); } else { // need update pmm.setPattern(pmPattern); entityManager.merge(pmm); } } } /** * {@inheritDoc} * @throws CannotDeleteProductMetadataException * @see org.openwis.dataservice.common.service.ProductMetadataService#deleteProductMetadataByURN(java.lang.String) */ @Override public void deleteProductMetadataByURN(@WebParam(name = "productMetadataUrn") String urn) throws CannotDeleteProductMetadataException { ProductMetadata productMetadata = getProductMetadataByUrn(urn); if (productMetadata != null) { // Check delete ability Query query = entityManager.createNamedQuery("Request.byProductMetadata"); query.setParameter("pm", productMetadata); @SuppressWarnings("unchecked") List<Request> lst = query.getResultList(); if (lst.isEmpty()) { deleteProductMetadata(productMetadata.getId()); } else { throw new CannotDeleteProductMetadataException(urn); } } } /** * {@inheritDoc} */ @Override public void deleteProductMetadatasWithURN(List<String> urns) throws CannotDeleteAllProductMetadataException { List<String> metadataThatCouldNotBeDeleted = null; for (String urn : urns) { try { deleteProductMetadataByURN(urn); } catch (CannotDeleteProductMetadataException e) { // Record metadata records that cannot be deleted if (metadataThatCouldNotBeDeleted == null) { metadataThatCouldNotBeDeleted = new ArrayList<String>(); } metadataThatCouldNotBeDeleted.add(urn); } } // The operation did not fully complete, so raise an exception providing the metadata URNs // that could not be deleted. if (metadataThatCouldNotBeDeleted != null) { throw new CannotDeleteAllProductMetadataException(metadataThatCouldNotBeDeleted.toArray(new String[metadataThatCouldNotBeDeleted.size()])); } } }
gpl-3.0
ifcharming/original2.0
tests/frontend/org/voltdb/quarantine/TestExportSuiteTestExportAndDroppedTableThenShutdown.java
16157
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.quarantine; import java.io.File; import org.voltdb.BackendTarget; import org.voltdb.VoltDB.Configuration; import org.voltdb.client.Client; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcedureCallback; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.compiler.VoltProjectBuilder.GroupInfo; import org.voltdb.compiler.VoltProjectBuilder.ProcedureInfo; import org.voltdb.compiler.VoltProjectBuilder.UserInfo; import org.voltdb.export.ExportTestClient; import org.voltdb.exportclient.ExportClientException; import org.voltdb.quarantine.TestExportSuite; import org.voltdb.regressionsuites.LocalCluster; import org.voltdb.regressionsuites.MultiConfigSuiteBuilder; import org.voltdb.regressionsuites.RegressionSuite; import org.voltdb.regressionsuites.TestOrderBySuite; import org.voltdb.regressionsuites.TestSQLTypesSuite; import org.voltdb.regressionsuites.VoltServerConfig; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.VoltFile; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Insert; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertAddedTable; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.InsertBase; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.RollbackInsert; import org.voltdb_testprocs.regressionsuites.sqltypesprocs.Update_Export; /** * End to end Export tests using the RawProcessor and the ExportSinkServer. * * Note, this test reuses the TestSQLTypesSuite schema and procedures. * Each table in that schema, to the extent the DDL is supported by the * DB, really needs an Export round trip test. */ public class TestExportSuiteTestExportAndDroppedTableThenShutdown extends RegressionSuite { private ExportTestClient m_tester; /** Shove a table name and pkey in front of row data */ private Object[] convertValsToParams(String tableName, final int i, final Object[] rowdata) { final Object[] params = new Object[rowdata.length + 2]; params[0] = tableName; params[1] = i; for (int ii=0; ii < rowdata.length; ++ii) params[ii+2] = rowdata[ii]; return params; } /** Push pkey into expected row data */ private Object[] convertValsToRow(final int i, final char op, final Object[] rowdata) { final Object[] row = new Object[rowdata.length + 2]; row[0] = (byte)(op == 'I' ? 1 : 0); row[1] = i; for (int ii=0; ii < rowdata.length; ++ii) row[ii+2] = rowdata[ii]; return row; } /** Push pkey into expected row data */ @SuppressWarnings("unused") private Object[] convertValsToLoaderRow(final int i, final Object[] rowdata) { final Object[] row = new Object[rowdata.length + 1]; row[0] = i; for (int ii=0; ii < rowdata.length; ++ii) row[ii+1] = rowdata[ii]; return row; } private void quiesce(final Client client) throws Exception { client.drain(); client.callProcedure("@Quiesce"); } private void quiesceAndVerifyRetryWorkOnIOException(final Client client, ExportTestClient tester) throws Exception { quiesce(client); while (true) { try { tester.work(); } catch (ExportClientException e) { boolean success = reconnect(tester); assertTrue(success); System.out.println(e.toString()); continue; } break; } assertTrue(tester.allRowsVerified()); assertTrue(tester.verifyExportOffsets()); } @Override public void setUp() throws Exception { m_username = "default"; m_password = "password"; VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name"))); File f = new File("/tmp/" + System.getProperty("user.name")); f.mkdirs(); super.setUp(); callbackSucceded = true; m_tester = new ExportTestClient(getServerConfig().getNodeCount()); m_tester.addCredentials("export", "export"); try { m_tester.connect(); } catch (ExportClientException e) { e.printStackTrace(); assertTrue(false); } } @Override public void tearDown() throws Exception { super.tearDown(); m_tester.disconnect(); assertTrue(callbackSucceded); } private boolean callbackSucceded = true; class RollbackCallback implements ProcedureCallback { @Override public void clientCallback(ClientResponse clientResponse) { if (clientResponse.getStatus() != ClientResponse.USER_ABORT) { callbackSucceded = false; System.err.println(clientResponse.getException()); } } } private boolean reconnect(ExportTestClient client) throws ExportClientException { for (int ii = 0; ii < 3; ii++) { m_tester.disconnect(); m_tester.reserveVerifiers(); boolean success = client.connect(); if (success) return true; } return false; } // Test Export of a DROPPED table. Queues some data to a table. // Then drops the table and restarts the server. Verifies that Export can successfully // drain the dropped table. IE, drop table doesn't lose Export data. // public void testExportAndDroppedTableThenShutdown() throws Exception { System.out.println("testExportAndDroppedTableThenShutdown"); Client client = getClient(); for (int i=0; i < 10; i++) { final Object[] rowdata = TestSQLTypesSuite.m_midValues; m_tester.addRow( m_tester.m_generationsSeen.first(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata)); final Object[] params = convertValsToParams("NO_NULLS", i, rowdata); client.callProcedure("Insert", params); } // now drop the no-nulls table final String newCatalogURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.jar"); final String deploymentURL = Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml"); final ClientResponse callProcedure = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL, deploymentURL); assertTrue(callProcedure.getStatus() == ClientResponse.SUCCESS); quiesce(client); m_config.shutDown(); m_config.startUp(false); client = getClient(); /** * There will be 3 disconnects. Once for the shutdown, once for first generation, * another for the 2nd generation created by the catalog change. The predicate is a complex * way of saying make sure that the tester has created verifiers for */ for (int ii = 0; m_tester.m_generationsSeen.size() < 3 || m_tester.m_verifiers.get(m_tester.m_generationsSeen.last()).size() < 6; ii++) { Thread.sleep(500); boolean threwException = false; try { m_tester.work(1000); } catch (ExportClientException e) { boolean success = reconnect(m_tester); assertTrue(success); System.out.println(e.toString()); threwException = true; } if (ii < 3) { assertTrue(threwException); } } for (int i=10; i < 20; i++) { final Object[] rowdata = TestSQLTypesSuite.m_midValues; m_tester.addRow( m_tester.m_generationsSeen.last(), "NO_NULLS", i, convertValsToRow(i, 'I', rowdata)); final Object[] params = convertValsToParams("NO_NULLS", i, rowdata); client.callProcedure("Insert", params); } client.drain(); // must still be able to verify the export data. quiesceAndVerifyRetryWorkOnIOException(client, m_tester); } static final GroupInfo GROUPS[] = new GroupInfo[] { new GroupInfo("export", false, false), new GroupInfo("proc", true, true), new GroupInfo("admin", true, true) }; static final UserInfo[] USERS = new UserInfo[] { new UserInfo("export", "export", new String[]{"export"}), new UserInfo("default", "password", new String[]{"proc"}), new UserInfo("admin", "admin", new String[]{"proc", "admin"}) }; /* * Test suite boilerplate */ static final ProcedureInfo[] PROCEDURES = { new ProcedureInfo( new String[]{"proc"}, Insert.class), new ProcedureInfo( new String[]{"proc"}, InsertBase.class), new ProcedureInfo( new String[]{"proc"}, RollbackInsert.class), new ProcedureInfo( new String[]{"proc"}, Update_Export.class) }; static final ProcedureInfo[] PROCEDURES2 = { new ProcedureInfo( new String[]{"proc"}, Update_Export.class) }; static final ProcedureInfo[] PROCEDURES3 = { new ProcedureInfo( new String[]{"proc"}, InsertAddedTable.class) }; public TestExportSuiteTestExportAndDroppedTableThenShutdown(final String name) { super(name); } public static void main(final String args[]) { org.junit.runner.JUnitCore.runClasses(TestOrderBySuite.class); } static public junit.framework.Test suite() throws Exception { VoltServerConfig config; final MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestExportSuiteTestExportAndDroppedTableThenShutdown.class); VoltProjectBuilder project = new VoltProjectBuilder(); project.setSecurityEnabled(true); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true /*enabled*/, java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); project.setTableAsExportOnly("NO_NULLS"); project.addPartitionInfo("NO_NULLS", "PKEY"); project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addProcedures(PROCEDURES); // JNI, single server // Use the cluster only config. Multiple topologies with the extra catalog for the // Add drop tests is harder. Restrict to the single (complex) topology. // // config = new LocalSingleProcessServer("export-ddl.jar", 2, // BackendTarget.NATIVE_EE_JNI); // config.compile(project); // builder.addServerConfig(config); /* * compile the catalog all tests start with */ config = new LocalCluster("export-ddl-cluster-rep.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); boolean compile = config.compile(project); assertTrue(compile); builder.addServerConfig(config); /* * compile a catalog without the NO_NULLS table for add/drop tests */ config = new LocalCluster("export-ddl-sans-nonulls.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); project = new VoltProjectBuilder(); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true, //enabled java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); // and then project builder as normal project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addProcedures(PROCEDURES2); compile = config.compile(project); MiscUtils.copyFile(project.getPathToDeployment(), Configuration.getPathToCatalogForTest("export-ddl-sans-nonulls.xml")); assertTrue(compile); /* * compile a catalog with an added table for add/drop tests */ config = new LocalCluster("export-ddl-addedtable.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true); project = new VoltProjectBuilder(); project.addGroups(GROUPS); project.addUsers(USERS); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-nonulls-ddl.sql")); project.addSchema(TestSQLTypesSuite.class.getResource("sqltypessuite-addedtable-ddl.sql")); project.addExport("org.voltdb.export.processors.RawProcessor", true /*enabled*/, java.util.Arrays.asList(new String[]{"export"})); // "WITH_DEFAULTS" is a non-exported persistent table project.setTableAsExportOnly("ALLOW_NULLS"); // persistent table project.setTableAsExportOnly("ADDED_TABLE"); // persistent table project.setTableAsExportOnly("NO_NULLS"); // streamed table // and then project builder as normal project.addPartitionInfo("ALLOW_NULLS", "PKEY"); project.addPartitionInfo("ADDED_TABLE", "PKEY"); project.addPartitionInfo("WITH_DEFAULTS", "PKEY"); project.addPartitionInfo("WITH_NULL_DEFAULTS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_WITH_NULLS", "PKEY"); project.addPartitionInfo("EXPRESSIONS_NO_NULLS", "PKEY"); project.addPartitionInfo("JUMBO_ROW", "PKEY"); project.addPartitionInfo("NO_NULLS", "PKEY"); project.addProcedures(PROCEDURES); project.addProcedures(PROCEDURES3); compile = config.compile(project); MiscUtils.copyFile(project.getPathToDeployment(), Configuration.getPathToCatalogForTest("export-ddl-addedtable.xml")); assertTrue(compile); return builder; } }
gpl-3.0
JupiterDevelopmentTeam/JupiterDevelopmentTeam
src/main/java/cn/nukkit/Player.java
218517
package cn.nukkit; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import com.google.gson.Gson; import com.google.gson.JsonObject; import cn.nukkit.AdventureSettings.Type; import cn.nukkit.block.Block; import cn.nukkit.block.BlockAir; import cn.nukkit.block.BlockCommand; import cn.nukkit.block.BlockDoor; import cn.nukkit.block.BlockEnderChest; import cn.nukkit.block.BlockNoteblock; import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntityBeacon; import cn.nukkit.blockentity.BlockEntityCommandBlock; import cn.nukkit.blockentity.BlockEntityItemFrame; import cn.nukkit.blockentity.BlockEntitySign; import cn.nukkit.blockentity.BlockEntitySpawnable; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import cn.nukkit.command.data.CommandDataVersions; import cn.nukkit.entity.Attribute; import cn.nukkit.entity.Entity; import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityInteractable; import cn.nukkit.entity.EntityLiving; import cn.nukkit.entity.data.EntityData; import cn.nukkit.entity.data.EntityMetadata; import cn.nukkit.entity.data.IntPositionEntityData; import cn.nukkit.entity.data.ShortEntityData; import cn.nukkit.entity.data.Skin; import cn.nukkit.entity.data.StringEntityData; import cn.nukkit.entity.item.EntityBoat; import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityMinecartAbstract; import cn.nukkit.entity.item.EntityMinecartEmpty; import cn.nukkit.entity.item.EntityVehicle; import cn.nukkit.entity.item.EntityXPOrb; import cn.nukkit.entity.projectile.EntityArrow; import cn.nukkit.entity.projectile.EntityFishingHook; import cn.nukkit.event.block.ItemFrameDropItemEvent; import cn.nukkit.event.block.SignChangeEvent; import cn.nukkit.event.entity.EntityDamageByBlockEvent; import cn.nukkit.event.entity.EntityDamageByEntityEvent; import cn.nukkit.event.entity.EntityDamageEvent; import cn.nukkit.event.entity.EntityDamageEvent.DamageCause; import cn.nukkit.event.entity.EntityDamageEvent.DamageModifier; import cn.nukkit.event.inventory.CraftItemEvent; import cn.nukkit.event.inventory.InventoryCloseEvent; import cn.nukkit.event.player.PlayerAnimationEvent; import cn.nukkit.event.player.PlayerBedEnterEvent; import cn.nukkit.event.player.PlayerBedLeaveEvent; import cn.nukkit.event.player.PlayerBlockPickEvent; import cn.nukkit.event.player.PlayerChatEvent; import cn.nukkit.event.player.PlayerChunkRequestEvent; import cn.nukkit.event.player.PlayerCommandPreprocessEvent; import cn.nukkit.event.player.PlayerDeathEvent; import cn.nukkit.event.player.PlayerGameModeChangeEvent; import cn.nukkit.event.player.PlayerInteractEntityEvent; import cn.nukkit.event.player.PlayerInteractEvent; import cn.nukkit.event.player.PlayerInteractEvent.Action; import cn.nukkit.event.player.PlayerInvalidMoveEvent; import cn.nukkit.event.player.PlayerItemConsumeEvent; import cn.nukkit.event.player.PlayerJoinEvent; import cn.nukkit.event.player.PlayerKickEvent; import cn.nukkit.event.player.PlayerLoginEvent; import cn.nukkit.event.player.PlayerMapInfoRequestEvent; import cn.nukkit.event.player.PlayerModalFormCloseEvent; import cn.nukkit.event.player.PlayerModalFormResponseEvent; import cn.nukkit.event.player.PlayerMouseOverEntityEvent; import cn.nukkit.event.player.PlayerMoveEvent; import cn.nukkit.event.player.PlayerPreLoginEvent; import cn.nukkit.event.player.PlayerQuitEvent; import cn.nukkit.event.player.PlayerRespawnEvent; import cn.nukkit.event.player.PlayerServerSettingsChangedEvent; import cn.nukkit.event.player.PlayerTeleportEvent; import cn.nukkit.event.player.PlayerTeleportEvent.TeleportCause; import cn.nukkit.event.player.PlayerToggleFlightEvent; import cn.nukkit.event.player.PlayerToggleGlideEvent; import cn.nukkit.event.player.PlayerToggleSneakEvent; import cn.nukkit.event.player.PlayerToggleSprintEvent; import cn.nukkit.event.server.DataPacketReceiveEvent; import cn.nukkit.event.server.DataPacketSendEvent; import cn.nukkit.inventory.AnvilInventory; import cn.nukkit.inventory.BeaconInventory; import cn.nukkit.inventory.BigCraftingGrid; import cn.nukkit.inventory.BigShapedRecipe; import cn.nukkit.inventory.BigShapelessRecipe; import cn.nukkit.inventory.CraftingGrid; import cn.nukkit.inventory.EnchantInventory; import cn.nukkit.inventory.Inventory; import cn.nukkit.inventory.InventoryHolder; import cn.nukkit.inventory.PlayerCursorInventory; import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.inventory.Recipe; import cn.nukkit.inventory.ShapedRecipe; import cn.nukkit.inventory.ShapelessRecipe; import cn.nukkit.inventory.TradingInventory; import cn.nukkit.inventory.transaction.InventoryTransaction; import cn.nukkit.inventory.transaction.SimpleInventoryTransaction; import cn.nukkit.inventory.transaction.action.InventoryAction; import cn.nukkit.inventory.transaction.action.SlotChangeAction; import cn.nukkit.inventory.transaction.data.ReleaseItemData; import cn.nukkit.inventory.transaction.data.UseItemData; import cn.nukkit.inventory.transaction.data.UseItemOnEntityData; import cn.nukkit.item.Item; import cn.nukkit.item.ItemBlock; import cn.nukkit.item.ItemBucket; import cn.nukkit.item.ItemGlassBottle; import cn.nukkit.item.ItemMap; import cn.nukkit.item.enchantment.Enchantment; import cn.nukkit.item.food.Food; import cn.nukkit.lang.TextContainer; import cn.nukkit.lang.TranslationContainer; import cn.nukkit.level.ChunkLoader; import cn.nukkit.level.Level; import cn.nukkit.level.Location; import cn.nukkit.level.Position; import cn.nukkit.level.format.FullChunk; import cn.nukkit.level.format.generic.BaseFullChunk; import cn.nukkit.level.particle.CriticalParticle; import cn.nukkit.level.particle.PunchBlockParticle; import cn.nukkit.level.sound.ExperienceOrbSound; import cn.nukkit.level.sound.ItemFrameItemRemovedSound; import cn.nukkit.math.AxisAlignedBB; import cn.nukkit.math.BlockFace; import cn.nukkit.math.BlockVector3; import cn.nukkit.math.NukkitMath; import cn.nukkit.math.NukkitRandom; import cn.nukkit.math.Vector2; import cn.nukkit.math.Vector3; import cn.nukkit.metadata.MetadataValue; import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.tag.ByteTag; import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.DoubleTag; import cn.nukkit.nbt.tag.ListTag; import cn.nukkit.nbt.tag.Tag; import cn.nukkit.network.SourceInterface; import cn.nukkit.network.protocol.AdventureSettingsPacket; import cn.nukkit.network.protocol.AnimatePacket; import cn.nukkit.network.protocol.AvailableCommandsPacket; import cn.nukkit.network.protocol.BatchPacket; import cn.nukkit.network.protocol.BlockEntityDataPacket; import cn.nukkit.network.protocol.BlockPickRequestPacket; import cn.nukkit.network.protocol.ChangeDimensionPacket; import cn.nukkit.network.protocol.ChunkRadiusUpdatedPacket; import cn.nukkit.network.protocol.ClientboundMapItemDataPacket; import cn.nukkit.network.protocol.CommandBlockUpdatePacket; import cn.nukkit.network.protocol.CommandRequestPacket; import cn.nukkit.network.protocol.ContainerClosePacket; import cn.nukkit.network.protocol.CraftingEventPacket; import cn.nukkit.network.protocol.DataPacket; import cn.nukkit.network.protocol.DisconnectPacket; import cn.nukkit.network.protocol.EntityEventPacket; import cn.nukkit.network.protocol.FullChunkDataPacket; import cn.nukkit.network.protocol.InteractPacket; import cn.nukkit.network.protocol.InventoryContentPacket; import cn.nukkit.network.protocol.InventoryTransactionPacket; import cn.nukkit.network.protocol.ItemFrameDropItemPacket; import cn.nukkit.network.protocol.LevelEventPacket; import cn.nukkit.network.protocol.LoginPacket; import cn.nukkit.network.protocol.MapInfoRequestPacket; import cn.nukkit.network.protocol.MobEquipmentPacket; import cn.nukkit.network.protocol.ModalFormRequestPacket; import cn.nukkit.network.protocol.ModalFormResponsePacket; import cn.nukkit.network.protocol.MovePlayerPacket; import cn.nukkit.network.protocol.PlayStatusPacket; import cn.nukkit.network.protocol.PlayerActionPacket; import cn.nukkit.network.protocol.PlayerHotbarPacket; import cn.nukkit.network.protocol.PlayerInputPacket; import cn.nukkit.network.protocol.PlayerSkinPacket; import cn.nukkit.network.protocol.ProtocolInfo; import cn.nukkit.network.protocol.RemoveEntityPacket; import cn.nukkit.network.protocol.RequestChunkRadiusPacket; import cn.nukkit.network.protocol.ResourcePackChunkDataPacket; import cn.nukkit.network.protocol.ResourcePackChunkRequestPacket; import cn.nukkit.network.protocol.ResourcePackClientResponsePacket; import cn.nukkit.network.protocol.ResourcePackDataInfoPacket; import cn.nukkit.network.protocol.ResourcePackStackPacket; import cn.nukkit.network.protocol.ResourcePacksInfoPacket; import cn.nukkit.network.protocol.RespawnPacket; import cn.nukkit.network.protocol.ServerSettingsResponsePacket; import cn.nukkit.network.protocol.SetCommandsEnabledPacket; import cn.nukkit.network.protocol.SetEntityMotionPacket; import cn.nukkit.network.protocol.SetPlayerGameTypePacket; import cn.nukkit.network.protocol.SetSpawnPositionPacket; import cn.nukkit.network.protocol.SetTimePacket; import cn.nukkit.network.protocol.SetTitlePacket; import cn.nukkit.network.protocol.ShowProfilePacket; import cn.nukkit.network.protocol.StartGamePacket; import cn.nukkit.network.protocol.TextPacket; import cn.nukkit.network.protocol.TransferPacket; import cn.nukkit.network.protocol.UpdateAttributesPacket; import cn.nukkit.network.protocol.UpdateBlockPacket; import cn.nukkit.network.protocol.types.ContainerIds; import cn.nukkit.network.protocol.types.NetworkInventoryAction; import cn.nukkit.permission.PermissibleBase; import cn.nukkit.permission.Permission; import cn.nukkit.permission.PermissionAttachment; import cn.nukkit.permission.PermissionAttachmentInfo; import cn.nukkit.plugin.Plugin; import cn.nukkit.potion.Effect; import cn.nukkit.potion.Potion; import cn.nukkit.resourcepacks.ResourcePack; import cn.nukkit.resourcepacks.ResourcePackManager; import cn.nukkit.utils.Binary; import cn.nukkit.utils.BlockIterator; import cn.nukkit.utils.ClientChainData; import cn.nukkit.utils.FastAppender; import cn.nukkit.utils.MainLogger; import cn.nukkit.utils.TextFormat; import cn.nukkit.utils.Utils; import cn.nukkit.utils.Zlib; import cn.nukkit.window.FormWindow; import cn.nukkit.window.ServerSettingsWindow; import co.aikar.timings.Timing; import co.aikar.timings.Timings; /** * author: MagicDroidX & Box * Nukkit Project */ public class Player extends EntityHuman implements CommandSender, InventoryHolder, ChunkLoader, IPlayer { public static final int SURVIVAL = 0; public static final int CREATIVE = 1; public static final int ADVENTURE = 2; public static final int SPECTATOR = 3; public static final int VIEW = SPECTATOR; public static final int SURVIVAL_SLOTS = 36; public static final int CREATIVE_SLOTS = 112; public static final int CRAFTING_SMALL = 0; public static final int CRAFTING_BIG = 1; public static final int CRAFTING_ANVIL = 2; public static final int CRAFTING_ENCHANT = 3; public static final int CRAFTING_STONECUTTER = 4;//使用されていない(PMMPから引用) public static final float DEFAULT_SPEED = 0.1f; public static final float MAXIMUM_SPEED = 0.5f; public static final int PERMISSION_CUSTOM = 3; public static final int PERMISSION_OPERATOR = 2; public static final int PERMISSION_MEMBER = 1; public static final int PERMISSION_VISITOR = 0; protected final SourceInterface interfaz; public boolean playedBefore; public boolean spawned = false; public boolean loggedIn = false; public int gamemode; public long lastBreak; protected int windowCnt = 2; protected Map<Inventory, Integer> windows; protected Map<Integer, Inventory> windowIndex = new HashMap<>(); protected Set<Integer> permanentWindows = new HashSet<>(); protected int messageCounter = 2; private String clientSecret; public Vector3 speed = null; public final HashSet<String> achievements = new HashSet<>(); public int craftingType = CRAFTING_SMALL; public long creationTime = 0; protected long randomClientId; protected Vector3 forceMovement = null; protected Vector3 teleportPosition = null; protected boolean connected = true; protected final String ip; protected boolean removeFormat = true; protected final int port; protected String username; protected String iusername; protected String displayName; protected String xuid; protected int startAction = -1; protected Vector3 sleeping = null; protected Long clientID = null; private Integer loaderId = null; protected float stepHeight = 0.6f; public Map<Long, Boolean> usedChunks = new HashMap<>(); protected int chunkLoadCount = 0; protected Map<Long, Integer> loadQueue = new HashMap<Long, Integer>(); protected int nextChunkOrderRun = 5; protected Map<UUID, Player> hiddenPlayers = new HashMap<>(); protected Vector3 newPosition = null; protected int chunkRadius; protected int viewDistance; protected final int chunksPerTick; protected final int spawnThreshold; protected Position spawnPosition = null; protected int inAirTicks = 0; protected int startAirTicks = 5; protected AdventureSettings adventureSettings = new AdventureSettings(this); protected boolean checkMovement = true; private final Map<Integer, Boolean> needACK = new HashMap<>(); private Map<Integer, List<DataPacket>> batchedPackets = new TreeMap<>(); private PermissibleBase perm = null; private int exp = 0; private int expLevel = 0; protected PlayerFood foodData = null; private Entity killer = null; private final AtomicReference<Locale> locale = new AtomicReference<>(null); private int hash; private String buttonText = ""; protected boolean enableClientCommand = true; private BlockEnderChest viewingEnderChest = null; protected int lastEnderPearl = -1; public boolean mute = false; public EntityFishingHook fishingHook; private boolean keepInventory = true; private boolean keepExperience = true; protected boolean enableRevert = true; public ClientChainData loginChainData; public int pickedXPOrb = 0; //看板関係 private String signText1; private String signText2; private String signText3; private String signText4; private BlockEntity blockEntity; private FormWindow activeWindow = null; private LinkedHashMap<Integer, ServerSettingsWindow> serverSettings = new LinkedHashMap<>(); private boolean printPackets; public void linkHookToPlayer(EntityFishingHook entity){ this.fishingHook = entity; EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getFishingHook().getId(); pk.event = EntityEventPacket.FISH_HOOK_HOOK; Server.broadcastPacket(this.getLevel().getPlayers().values(), pk); } public void unlinkHookFromPlayer(){ if (this.isFishing()){ EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getFishingHook().getId(); pk.event = EntityEventPacket.FISH_HOOK_TEASE; Server.broadcastPacket(this.getLevel().getPlayers().values(), pk); this.fishingHook.close(); this.fishingHook = null; } } @Deprecated public void setAllowFlight(boolean value) { this.getAdventureSettings().set(Type.ALLOW_FLIGHT, value); this.getAdventureSettings().update(); } @Deprecated public boolean getAllowFlight() { return this.getAdventureSettings().get(Type.ALLOW_FLIGHT); } @Deprecated public void setAutoJump(boolean value) { this.getAdventureSettings().set(Type.AUTO_JUMP, value); this.getAdventureSettings().update(); } @Deprecated public boolean hasAutoJump() { return this.getAdventureSettings().get(Type.AUTO_JUMP); } public int getStartActionTick() { return startAction; } public void startAction() { this.startAction = this.server.getTick(); } public void stopAction() { this.startAction = -1; } public int getLastEnderPearlThrowingTick() { return lastEnderPearl; } public void onThrowEnderPearl() { this.lastEnderPearl = this.server.getTick(); } public boolean isFishing(){ return this.fishingHook != null; } public EntityFishingHook getFishingHook(){ return this.fishingHook; } public BlockEnderChest getViewingEnderChest() { return viewingEnderChest; } public void setViewingEnderChest(BlockEnderChest chest) { if (chest == null && this.viewingEnderChest != null) { this.viewingEnderChest.getViewers().remove(this); } else if (chest != null) { chest.getViewers().add(this); } this.viewingEnderChest = chest; } public TranslationContainer getLeaveMessage() { return new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.left", this.getDisplayName()); } public String getClientSecret() { return clientSecret; } public ClientChainData getLoginChainData(){ return this.loginChainData; } /** * ClientChainDataクラスを使用してください。 */ @Deprecated public Long getClientId() { return randomClientId; } @Override public boolean isBanned() { return this.server.getNameBans().isBanned(this.getName()); } @Override public void setBanned(boolean value) { if (value) { this.server.getNameBans().addBan(this.getName(), null, null, null); this.kick(PlayerKickEvent.Reason.NAME_BANNED, "Banned by admin"); } else { this.server.getNameBans().remove(this.getName()); } } @Override public boolean isWhitelisted() { return this.server.isWhitelisted(this.getName().toLowerCase()); } @Override public void setWhitelisted(boolean value) { if (value) { this.server.addWhitelist(this.getName().toLowerCase()); } else { this.server.removeWhitelist(this.getName().toLowerCase()); } } /** * プレイヤーオブジェクトを取得します。 * @return Player */ @Override public Player getPlayer() { return this; } @Override public Long getFirstPlayed() { return this.namedTag != null ? this.namedTag.getLong("firstPlayed") : null; } @Override public Long getLastPlayed() { return this.namedTag != null ? this.namedTag.getLong("lastPlayed") : null; } @Override public boolean hasPlayedBefore() { return this.playedBefore; } /* public void setCanDestroyBlock(boolean setting){ AdventureSettings adventuresettings = this.getAdventureSettings(); adventuresettings.setCanDestroyBlock(setting); this.setAdventureSettings(adventuresettings); } */ public AdventureSettings getAdventureSettings() { return adventureSettings; } public void setAdventureSettings(AdventureSettings adventureSettings) { this.adventureSettings = adventureSettings.clone(this); this.adventureSettings.update(); } public void resetInAirTicks() { this.inAirTicks = 0; } @Override public void spawnTo(Player player) { if (this.spawned && player.spawned && this.isAlive() && player.isAlive() && player.getLevel() == this.level && player.canSee(this) && !this.isSpectator()) { super.spawnTo(player); } } /** * プレイヤーからサーバーオブジェクトを取得します。 * @return Server */ @Override public Server getServer() { return this.server; } public boolean getRemoveFormat() { return removeFormat; } public void setRemoveFormat() { this.setRemoveFormat(true); } public void setRemoveFormat(boolean remove) { this.removeFormat = remove; } public boolean canSee(Player player) { return !this.hiddenPlayers.containsKey(player.getUniqueId()); } public void hidePlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.put(player.getUniqueId(), player); player.despawnFrom(this); } public void showPlayer(Player player) { if (this == player) { return; } this.hiddenPlayers.remove(player.getUniqueId()); if (player.isOnline()) { player.spawnTo(this); } } @Override public boolean canCollideWith(Entity entity) { return false; } @Override public void resetFallDistance() { super.resetFallDistance(); if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } @Override public boolean isOnline() { return this.connected && this.loggedIn; } /** * OPかどうかを取得します。 * @return boolean trueがOP/falseが非OP */ @Override public boolean isOp() { return this.server.isOp(this.getName()); } public void setOp(){ this.setOp(true); } /** * プレイヤーをOPにします。 * @param value trueがOP/falseが非OP * @return void */ @Override public void setOp(boolean value) { if (value == this.isOp()) { return; } if (value) { this.server.addOp(this.getName()); } else { this.server.removeOp(this.getName()); } this.recalculatePermissions(); this.getAdventureSettings().update(); this.sendCommandData(); } @Override public boolean isPermissionSet(String name) { return this.perm.isPermissionSet(name); } @Override public boolean isPermissionSet(Permission permission) { return this.perm.isPermissionSet(permission); } @Override public boolean hasPermission(String name) { return this.perm != null && this.perm.hasPermission(name); } @Override public boolean hasPermission(Permission permission) { return this.perm.hasPermission(permission); } @Override public PermissionAttachment addAttachment(Plugin plugin) { return this.addAttachment(plugin, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name) { return this.addAttachment(plugin, name, null); } @Override public PermissionAttachment addAttachment(Plugin plugin, String name, Boolean value) { return this.perm.addAttachment(plugin, name, value); } @Override public void removeAttachment(PermissionAttachment attachment) { this.perm.removeAttachment(attachment); } @Override public void recalculatePermissions() { this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); if (this.perm == null) { return; } this.perm.recalculatePermissions(); if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } if (this.isEnableClientCommand()) this.sendCommandData(); } public boolean isEnableClientCommand() { return this.enableClientCommand; } public void setEnableClientCommand(boolean enable) { this.enableClientCommand = enable; SetCommandsEnabledPacket pk = new SetCommandsEnabledPacket(); pk.enabled = enable; this.dataPacket(pk); if (enable) this.sendCommandData(); } public void sendCommandData() { AvailableCommandsPacket pk = new AvailableCommandsPacket(); Map<String, CommandDataVersions> data = new HashMap<>(); int count = 0; for (Command command : this.server.getCommandMap().getCommands().values()) { if (!command.testPermissionSilent(this)) { continue; } ++count; CommandDataVersions data0 = command.generateCustomCommandData(this); data.put(command.getName(), data0); } if (count > 0) { //TODO: structure checking pk.commands = data; int identifier = this.dataPacket(pk, true); // We *need* ACK so we can be sure that the client received the packet or not Thread t = new Thread() { public void run() { // We are going to wait 3 seconds, if after 3 seconds we didn't receive a reply from the client, resend the packet. try { Thread.sleep(3000); boolean status = needACK.get(identifier); if (!status && isOnline()) { sendCommandData(); return; } } catch (InterruptedException e) {} } }; t.start(); } } @Override public Map<String, PermissionAttachmentInfo> getEffectivePermissions() { return this.perm.getEffectivePermissions(); } public Player(SourceInterface interfaz, Long clientID, String ip, int port) { super(null, new CompoundTag()); this.interfaz = interfaz; this.windows = new HashMap<>(); this.perm = new PermissibleBase(this); this.server = Server.getInstance(); this.lastBreak = Long.MAX_VALUE; this.ip = ip; this.port = port; this.clientID = clientID; this.loaderId = Level.generateChunkLoaderId(this); this.chunksPerTick = (int) this.server.getConfig("chunk-sending.per-tick", 4); this.spawnThreshold = (int) this.server.getConfig("chunk-sending.spawn-threshold", 56); this.spawnPosition = null; this.gamemode = this.server.getDefaultGamemode(); this.setLevel(this.server.getDefaultLevel()); this.viewDistance = this.server.getViewDistance(); this.chunkRadius = viewDistance; //this.newPosition = new Vector3(0, 0, 0); this.boundingBox = new AxisAlignedBB(0, 0, 0, 0, 0, 0); this.uuid = null; this.rawUUID = null; this.creationTime = System.currentTimeMillis(); this.enableRevert = this.server.getJupiterConfigBoolean("enable-revert"); this.server.getJupiterConfigBoolean("allow-snowball"); this.server.getJupiterConfigBoolean("allow-egg"); this.server.getJupiterConfigBoolean("allow-enderpearl"); this.server.getJupiterConfigBoolean("allow-experience-bottle"); this.server.getJupiterConfigBoolean("allow-splash-potion"); this.server.getJupiterConfigBoolean("allow-bow"); this.server.getJupiterConfigBoolean("allow-fishing-rod"); this.printPackets = this.getServer().printPackets(); } /** * プレイヤーオブジェクトかどうかを取得します。 * この場合、trueしか返ってきません。 * @return boolean true */ public boolean isPlayer() { return true; } public void removeAchievement(String achievementId) { achievements.remove(achievementId); } public boolean hasAchievement(String achievementId) { return achievements.contains(achievementId); } public boolean isConnected() { return connected; } /** * プレイヤーのチャット上の名前を取得します。 * @return String プレイヤーのチャット上の名前 */ public String getDisplayName() { return this.displayName; } /** * プレイヤーのチャット上の名前を設定します。 * @param displayName 設定する名前 * @return void */ public void setDisplayName(String displayName) { this.displayName = displayName; if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), this.getSkin(), this.getLoginChainData().getXUID()); } } /** * プレイヤーのスキンを設定します。 * @param skin スキンデータ * @return void */ @Override public void setSkin(Skin skin) { super.setSkin(skin); if (this.spawned) { this.server.updatePlayerListData(this.getUniqueId(), this.getId(), this.getDisplayName(), skin, this.getLoginChainData().getXUID()); } } /** * プレイヤーのIPアドレスを取得します。 * @return String プレイヤーのIPアドレス */ public String getAddress() { return this.ip; } /** * プレイヤーのポートを取得します。 * @return int プレイヤーのポート */ public int getPort() { return port; } public Position getNextPosition() { return this.newPosition != null ? new Position(this.newPosition.x, this.newPosition.y, this.newPosition.z, this.level) : this.getPosition(); } /** * プレイヤーが寝ているかどうかをを取得します。 * @return boolean trueが寝ている/falseが寝ていない */ public boolean isSleeping() { return this.sleeping != null; } public int getInAirTicks() { return this.inAirTicks; } public String getButtonText() { return this.buttonText; } public void setButtonText(String text) { if (!(text.equals(this.getButtonText()))) { this.buttonText = text; this.setDataProperty(new StringEntityData(Entity.DATA_INTERACTIVE_TAG, this.buttonText)); } } @Override protected boolean switchLevel(Level targetLevel) { Level oldLevel = this.level; if (super.switchLevel(targetLevel)) { for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.unloadChunk(chunkX, chunkZ, oldLevel); } this.usedChunks = new HashMap<>(); SetTimePacket pk = new SetTimePacket(); pk.time = this.level.getTime(); this.dataPacket(pk); // TODO: Remove this hack int distance = this.viewDistance * 2 * 16 * 2; this.sendPosition(this.add(distance, 0, distance), this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); return true; } return false; } public void unloadChunk(int x, int z) { this.unloadChunk(x, z, null); } public void unloadChunk(int x, int z, Level level) { level = level == null ? this.level : level; long index = Level.chunkHash(x, z); if (this.usedChunks.containsKey(index)) { for (Entity entity : level.getChunkEntities(x, z).values()) { if (entity != this) { entity.despawnFrom(this); } } this.usedChunks.remove(index); } level.unregisterChunkLoader(this, x, z); this.loadQueue.remove(index); } public Position getSpawn() { if (this.spawnPosition != null && this.spawnPosition.getLevel() != null && this.getServer().getJupiterConfigString("spawnpoint").equals("fromplayerdata")) { return this.spawnPosition; } else { return this.server.getDefaultLevel().getSafeSpawn(); } } public void sendChunk(int x, int z, DataPacket packet) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), true); this.chunkLoadCount++; this.dataPacket(packet); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } public void sendChunk(int x, int z, byte[] payload) { if (!this.connected) { return; } this.usedChunks.put(Level.chunkHash(x, z), true); this.chunkLoadCount++; FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = x; pk.chunkZ = z; pk.data = payload; this.batchDataPacket(pk); if (this.spawned) { for (Entity entity : this.level.getChunkEntities(x, z).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } } protected void sendNextChunk() { if (!this.connected) { return; } Timings.playerChunkSendTimer.startTiming(); int count = 0; List<Map.Entry<Long, Integer>> entryList = new ArrayList<>(this.loadQueue.entrySet()); entryList.sort(Comparator.comparingInt(Map.Entry::getValue)); for (Map.Entry<Long, Integer> entry : entryList) { long index = entry.getKey(); if (count >= this.chunksPerTick) { break; } int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); ++count; this.usedChunks.put(index, false); this.level.registerChunkLoader(this, chunkX, chunkZ, false); if (!this.level.populateChunk(chunkX, chunkZ)) { if (this.spawned && this.teleportPosition == null) { continue; } else { break; } } this.loadQueue.remove(index); PlayerChunkRequestEvent ev = new PlayerChunkRequestEvent(this, chunkX, chunkZ); this.server.getPluginManager().callEvent(ev); if (!ev.isCancelled()) { this.level.requestChunk(chunkX, chunkZ, this); } } if (this.chunkLoadCount >= this.spawnThreshold && !this.spawned && this.teleportPosition == null) { this.doFirstSpawn(); } Timings.playerChunkSendTimer.stopTiming(); } protected void doFirstSpawn() { this.spawned = true; this.server.sendRecipeList(this); this.getAdventureSettings().update(); this.sendPotionEffects(this); this.sendData(this); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.offhandInventory.sendContents(this); this.offhandInventory.sendOffhandItem(this); SetTimePacket setTimePacket = new SetTimePacket(); setTimePacket.time = this.level.getTime(); this.dataPacket(setTimePacket); PlayStatusPacket playStatusPacket = new PlayStatusPacket(); playStatusPacket.status = PlayStatusPacket.PLAYER_SPAWN; this.dataPacket(playStatusPacket); PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(this, new TranslationContainer(TextFormat.YELLOW + "%multiplayer.player.joined", new String[]{ this.getDisplayName() }) ); this.server.getPluginManager().callEvent(playerJoinEvent); if (playerJoinEvent.getJoinMessage().toString().trim().length() > 0) { //デフォルトの参加時メッセージを送るかどうかを確認 if(this.server.getJupiterConfigBoolean("join-quit-message")) this.server.broadcastMessage(playerJoinEvent.getJoinMessage()); } this.noDamageTicks = 60; for (long index : this.usedChunks.keySet()) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); for (Entity entity : this.level.getChunkEntities(chunkX, chunkZ).values()) { if (this != entity && !entity.closed && entity.isAlive()) { entity.spawnTo(this); } } } this.sendExperience(this.getExperience()); this.sendExperienceLevel(this.getExperienceLevel()); if (!this.isSpectator()) { this.spawnToAll(); } //todo Updater RespawnPacket respawnPacket = new RespawnPacket(); Position pos = this.getSpawn(); respawnPacket.x = (float) pos.x; respawnPacket.y = (float) pos.y; respawnPacket.z = (float) pos.z; this.dataPacket(respawnPacket); this.sendPlayStatus(PlayStatusPacket.PLAYER_SPAWN); //Weather this.getLevel().sendWeather(this); //FoodLevel this.getFoodData().sendFoodLevel(); if (this.isSpectator()) { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; this.dataPacket(inventoryContentPacket); } else if(this.isCreative()) { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; inventoryContentPacket.slots = Item.getCreativeItems().stream().toArray(Item[]::new); this.dataPacket(inventoryContentPacket); } } protected boolean orderChunks() { if (!this.connected) { return false; } Timings.playerChunkOrderTimer.startTiming(); this.nextChunkOrderRun = 200; Map<Long, Integer> newOrder = new HashMap<>(); Map<Long, Boolean> lastChunk = this.usedChunks; int centerX = (int) this.x >> 4; int centerZ = (int) this.z >> 4; for (int x = -this.chunkRadius; x <= this.chunkRadius; x++) { for (int z = -this.chunkRadius; z <= this.chunkRadius; z++) { int chunkX = x + centerX; int chunkZ = z + centerZ; int distance = (int) Math.sqrt((double) x * x + (double) z * z); if (distance <= this.chunkRadius) { long index; if (!(this.usedChunks.containsKey(index = Level.chunkHash(chunkX, chunkZ))) || !this.usedChunks.get(index)) { newOrder.put(index, distance); } lastChunk.remove(index); } } } for (long index : new ArrayList<>(lastChunk.keySet())) { this.unloadChunk(Level.getHashX(index), Level.getHashZ(index)); } this.loadQueue = newOrder; Timings.playerChunkOrderTimer.stopTiming(); return true; } public boolean batchDataPacket(DataPacket packet) { if (!this.connected) { return false; } try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent event = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) { timing.stopTiming(); return false; } if (!this.batchedPackets.containsKey(packet.getChannel())) { this.batchedPackets.put(packet.getChannel(), new ArrayList<>()); } this.batchedPackets.get(packet.getChannel()).add(packet.clone()); } return true; } /** * プレイヤーにパケットを送信します。 * @param packet 送るパケット * @return boolean */ public boolean dataPacket(DataPacket packet) { return this.dataPacket(packet, false) != -1; } public int dataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } if(this.printPackets) this.getServer().getLogger().info(TextFormat.YELLOW + "[SEND] " + TextFormat.WHITE + packet.getName()); try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, false); if (needACK && identifier != null) { this.needACK.put(identifier.intValue(), false); timing.stopTiming(); return identifier; } } return 0; } /** * 0 is true * -1 is false * other is identifer */ public boolean directDataPacket(DataPacket packet) { return this.directDataPacket(packet, false) != -1; } public int directDataPacket(DataPacket packet, boolean needACK) { if (!this.connected) { return -1; } if(this.printPackets) this.getServer().getLogger().info(TextFormat.LIGHT_PURPLE + "[SEND-DIRECT] " + TextFormat.WHITE + packet.getClass().getSimpleName()); try (Timing timing = Timings.getSendDataPacketTiming(packet)) { DataPacketSendEvent ev = new DataPacketSendEvent(this, packet); this.server.getPluginManager().callEvent(ev); if (ev.isCancelled()) { timing.stopTiming(); return -1; } Integer identifier = this.interfaz.putPacket(this, packet, needACK, true); if (needACK && identifier != null) { this.needACK.put(identifier.intValue(), false); timing.stopTiming(); return identifier; } } return 0; } public int getPing() { return this.interfaz.getNetworkLatency(this); } public boolean sleepOn(Vector3 pos) { if (!this.isOnline()) { return false; } for (Entity p : this.level.getNearbyEntities(this.boundingBox.grow(2, 1, 2), this)) { if (p instanceof Player) { if (((Player) p).sleeping != null && pos.distance(((Player) p).sleeping) <= 0.1) { return false; } } } PlayerBedEnterEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerBedEnterEvent(this, this.level.getBlock(pos))); if (ev.isCancelled()) { return false; } this.sleeping = pos.clone(); this.teleport(new Location(pos.x + 0.5, pos.y - 0.5, pos.z + 0.5, this.yaw, this.pitch, this.level), null); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) pos.x, (int) pos.y, (int) pos.z)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); this.setSpawn(pos); this.level.sleepTicks = 60; return true; } /** * プレイヤーのスポーン地点を設定します。 * @param pos 設定する座標 * @return void * @see "Vector3" * @see Vector3 */ public void setSpawn(Vector3 pos) { Level level; if (!(pos instanceof Position)) { level = this.level; } else { level = ((Position) pos).getLevel(); } this.spawnPosition = new Position(pos.x, pos.y, pos.z, level); SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_PLAYER_SPAWN; pk.x = (int) this.spawnPosition.x; pk.y = (int) this.spawnPosition.y; pk.z = (int) this.spawnPosition.z; this.dataPacket(pk); } public void startSleep(){ this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, true); this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, (int) this.x, (int) this.y, (int) this.z), true); this.sleeping = this.getPosition(); this.server.getPluginManager().callEvent(new PlayerBedEnterEvent(this, this.level.getBlock(this.sleeping))); } public void stopSleep() { if (this.sleeping != null) { this.server.getPluginManager().callEvent(new PlayerBedLeaveEvent(this, this.level.getBlock(this.sleeping))); this.sleeping = null; this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0)); this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false); this.level.sleepTicks = 0; AnimatePacket pk = new AnimatePacket(); pk.entityRuntimeId = this.id; pk.action = 3; //Wake up this.dataPacket(pk); } } /** * プレイヤーのゲームモードを取得します。 * <br>0:サバイバルモード * <br>1:クリエイティブモード * <br>2:アドベンチャーモード * <br>3:スペクテイターモード * @return int プレイヤーのゲームモード */ public int getGamemode() { return gamemode; } private static int getClientFriendlyGamemode(int gamemode) { gamemode &= 0x03; if (gamemode == Player.SPECTATOR) { return Player.CREATIVE; } return gamemode; } /** * プレイヤーのゲームモードを設定します。 * @param gamemode ゲームモード * <br>0:サバイバルモード * <br>1:クリエイティブモード * <br>2:アドベンチャーモード * <br>3:スペクテイターモード * @return boolean */ public boolean setGamemode(int gamemode) { return this.setGamemode(gamemode, false, null); } public boolean setGamemode(int gamemode, boolean clientSide) { return this.setGamemode(gamemode, clientSide, null); } public boolean setGamemode(int gamemode, boolean clientSide, AdventureSettings newSettings) { if (gamemode < 0 || gamemode > 3) { return false; } if (newSettings == null) { newSettings = this.getAdventureSettings().clone(this); newSettings.set(Type.BUILD_AND_MINE, gamemode != 3); newSettings.set(Type.WORLD_BUILDER, gamemode != 3); newSettings.set(Type.NO_CLIP, gamemode == 3); newSettings.set(Type.WORLD_IMMUTABLE, gamemode == 3); newSettings.set(Type.NO_PVP, gamemode == 3); newSettings.set(Type.FLYING, gamemode == 1 || gamemode == 3); newSettings.set(Type.ALLOW_FLIGHT, gamemode == 1 || gamemode == 3); } PlayerGameModeChangeEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerGameModeChangeEvent(this, gamemode, newSettings)); if (ev.isCancelled()) { return false; } this.gamemode = gamemode; if (this.isSpectator()) { this.keepMovement = true; this.despawnFromAll(); } else { this.keepMovement = false; this.spawnToAll(); } this.namedTag.putInt("playerGameType", gamemode); if (!clientSide) { SetPlayerGameTypePacket pk = new SetPlayerGameTypePacket(); pk.gamemode = getClientFriendlyGamemode(gamemode); this.dataPacket(pk); } this.setAdventureSettings(ev.getNewAdventureSettings()); this.getAdventureSettings().update(); if (this.isSpectator()) { this.teleport(this.temporalVector.setComponents(this.x, this.y + 0.1, this.z)); InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; this.dataPacket(inventoryContentPacket); } else { InventoryContentPacket inventoryContentPacket = new InventoryContentPacket(); inventoryContentPacket.inventoryId = InventoryContentPacket.SPECIAL_CREATIVE; inventoryContentPacket.slots = Item.getCreativeItems().stream().toArray(Item[]::new); this.dataPacket(inventoryContentPacket); } this.resetFallDistance(); this.inventory.sendContents(this); this.inventory.sendContents(this.getViewers().values()); this.inventory.sendHeldItem(this.hasSpawned.values()); return true; } @Deprecated public void sendSettings() { this.getAdventureSettings().update(); } public boolean isSurvival() { return (this.gamemode & 0x01) == 0; } public boolean isCreative() { return (this.gamemode & 0x01) > 0; } public boolean isSpectator() { return this.gamemode == 3; } public boolean isAdventure() { return (this.gamemode & 0x02) > 0; } @Override public Item[] getDrops() { if (!this.isCreative()) { return super.getDrops(); } return new Item[0]; } @Override public boolean setDataProperty(EntityData data) { return setDataProperty(data, true); } @Override public boolean setDataProperty(EntityData data, boolean send) { if (super.setDataProperty(data, send)) { if (send) this.sendData(this, new EntityMetadata().put(this.getDataProperty(data.getId()))); return true; } return false; } @Override protected void checkGroundState(double movX, double movY, double movZ, double dx, double dy, double dz) { if (!this.onGround || movX != 0 || movY != 0 || movZ != 0) { boolean onGround = false; AxisAlignedBB bb = this.boundingBox.clone(); bb.maxY = bb.minY + 0.5; bb.minY -= 1; AxisAlignedBB realBB = this.boundingBox.clone(); realBB.maxY = realBB.minY + 0.1; realBB.minY -= 0.2; int minX = NukkitMath.floorDouble(bb.minX); int minY = NukkitMath.floorDouble(bb.minY); int minZ = NukkitMath.floorDouble(bb.minZ); int maxX = NukkitMath.ceilDouble(bb.maxX); int maxY = NukkitMath.ceilDouble(bb.maxY); int maxZ = NukkitMath.ceilDouble(bb.maxZ); for (int z = minZ; z <= maxZ; ++z) { for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { Block block = this.level.getBlock(this.temporalVector.setComponents(x, y, z)); if (!block.canPassThrough() && block.collidesWithBB(realBB)) { onGround = true; break; } } } } this.onGround = onGround; } this.isCollided = this.onGround; } @Override protected void checkBlockCollision() { boolean portal = false; Block block = this.getLevelBlock(); if (block.getId() == Block.NETHER_PORTAL) { portal = true; } block.onEntityCollide(this); if (portal) { inPortalTicks++; } } protected void checkNearEntities() { for (Entity entity : this.level.getNearbyEntities(this.boundingBox.grow(1, 0.5, 1), this)) { entity.scheduleUpdate(); if (!entity.isAlive() || !this.isAlive()) { continue; } this.pickupEntity(entity, true); } } protected void processMovement(int tickDiff) { if (!this.isAlive() || !this.spawned || this.newPosition == null || this.teleportPosition != null || this.isSleeping()) { return; } Vector3 newPos = this.newPosition; double distanceSquared = newPos.distanceSquared(this); boolean revert = false; if ((distanceSquared / ((double) (tickDiff * tickDiff))) > 100 && (newPos.y - this.y) > -5) { revert = true; } else { if (this.chunk == null || !this.chunk.isGenerated()) { BaseFullChunk chunk = this.level.getChunk((int) newPos.x >> 4, (int) newPos.z >> 4, false); if (chunk == null || !chunk.isGenerated()) { revert = true; this.nextChunkOrderRun = 0; } else { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = chunk; } } } double tdx = newPos.x - this.x; double tdz = newPos.z - this.z; double distance = Math.sqrt(tdx * tdx + tdz * tdz); if (!revert && distanceSquared != 0) { double dx = newPos.x - this.x; double dy = newPos.y - this.y; double dz = newPos.z - this.z; this.fastMove(dx, dy, dz); double diffX = this.x - newPos.x; double diffY = this.y - newPos.y; double diffZ = this.z - newPos.z; double yS = 0.5 + this.ySize; if (diffY >= -yS || diffY <= yS) { diffY = 0; } if (diffX != 0 || diffY != 0 || diffZ != 0) { if (this.checkMovement && !server.getAllowFlight() && this.isSurvival()) { if (!this.isSleeping() && this.riding == null) { double diffHorizontalSqr = (diffX * diffX + diffZ * diffZ) / ((double) (tickDiff * tickDiff)); if (diffHorizontalSqr > 0.125) { if(enableRevert){ PlayerInvalidMoveEvent ev; this.getServer().getPluginManager().callEvent(ev = new PlayerInvalidMoveEvent(this, true)); if (!ev.isCancelled()) { revert = ev.isRevert(); if (revert) { this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidMove", this.getName())); } } } } } } this.x = newPos.x; this.y = newPos.y; this.z = newPos.z; double radius = this.getWidth() / 2; this.boundingBox.setBounds(this.x - radius, this.y, this.z - radius, this.x + radius, this.y + this.getHeight(), this.z + radius); } } Location from = new Location( this.lastX, this.lastY, this.lastZ, this.lastYaw, this.lastPitch, this.level); Location to = this.getLocation(); if (!revert && (Math.pow(this.lastX - to.x, 2) + Math.pow(this.lastY - to.y, 2) + Math.pow(this.lastZ - to.z, 2)) > (1d / 16d) || (Math.abs(this.lastYaw - to.yaw) + Math.abs(this.lastPitch - to.pitch)) > 10) { boolean isFirst = this.firstMove; this.firstMove = false; this.lastX = to.x; this.lastY = to.y; this.lastZ = to.z; this.lastYaw = to.yaw; this.lastPitch = to.pitch; if (!isFirst) { List<Block> blocksAround = this.blocksAround; List<Block> collidingBlocks = this.collisionBlocks; PlayerMoveEvent ev = new PlayerMoveEvent(this, from, to); this.blocksAround = null; this.collisionBlocks = null; this.server.getPluginManager().callEvent(ev); if (!(revert = ev.isCancelled())) { //Yes, this is intended if (!to.equals(ev.getTo())) { //If plugins modify the destination this.teleport(ev.getTo(), null); } else { this.broadcastMovement(); //this.addMovement(this.x, this.y + this.getEyeHeight(), this.z, this.yaw, this.pitch, this.yaw); } } else { this.blocksAround = blocksAround; this.collisionBlocks = collidingBlocks; } if (this.isFishing()){ if (this.distance(this.getFishingHook()) > 33 | this.getInventory().getItemInHand().getId() != Item.FISHING_ROD){ this.unlinkHookFromPlayer(); } } } if (!this.isSpectator()) { this.checkNearEntities(); } if (this.speed == null) speed = new Vector3(from.x - to.x, from.y - to.y, from.z - to.z); else this.speed.setComponents(from.x - to.x, from.y - to.y, from.z - to.z); } else { if (this.speed == null) speed = new Vector3(0, 0, 0); else this.speed.setComponents(0, 0, 0); } if (!revert && (this.isFoodEnabled() || this.getServer().getDifficulty() == 0)) { if ((this.isSurvival() || this.isAdventure())/* && !this.getRiddingOn() instanceof Entity*/) { //UpdateFoodExpLevel if (distance >= 0.05) { double jump = 0; double swimming = this.isInsideOfWater() ? 0.015 * distance : 0; if (swimming != 0) distance = 0; if (this.isSprinting()) { //Running if (this.inAirTicks == 3 && swimming == 0) { jump = 0.7; } this.getFoodData().updateFoodExpLevel(0.025 * distance + jump + swimming); } else { if (this.inAirTicks == 3 && swimming == 0) { jump = 0.2; } this.getFoodData().updateFoodExpLevel(0.01 * distance + jump + swimming); } } } } if (revert) { this.lastX = from.x; this.lastY = from.y; this.lastZ = from.z; this.lastYaw = from.yaw; this.lastPitch = from.pitch; this.sendPosition(from, from.yaw, from.pitch, MovePlayerPacket.MODE_RESET); //this.sendSettings(); this.forceMovement = new Vector3(from.x, from.y, from.z); } else { this.forceMovement = null; if (distanceSquared != 0 && this.nextChunkOrderRun > 20) { this.nextChunkOrderRun = 20; } } this.newPosition = null; } @Override public boolean setMotion(Vector3 motion) { if (super.setMotion(motion)) { if (this.chunk != null) { //this.getLevel().addEntityMotion(this.chunk.getX(), this.chunk.getZ(), this.getId(), this.motionX, this.motionY, this.motionZ); //Send to others this.broadcastMotion(); SetEntityMotionPacket pk = new SetEntityMotionPacket(); pk.entityRuntimeId = this.id; pk.motionX = (float) motion.x; pk.motionY = (float) motion.y; pk.motionZ = (float) motion.z; this.dataPacket(pk); //Send to self } if (this.motionY > 0) { //todo: check this this.startAirTicks = (int) ((-(Math.log(this.getGravity() / (this.getGravity() + this.getDrag() * this.motionY))) / this.getDrag()) * 2 + 5); } return true; } return false; } public void sendAttributes() { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entityRuntimeId = this.getId(); pk.entries = new Attribute[]{ Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0), Attribute.getAttribute(Attribute.MAX_HUNGER).setValue(this.getFoodData().getLevel()), Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(this.getMovementSpeed()), Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(this.getExperienceLevel()), Attribute.getAttribute(Attribute.EXPERIENCE).setValue(((float) this.getExperience()) / calculateRequireExperience(this.getExperienceLevel())) }; this.dataPacket(pk); } @Override public boolean onUpdate(int currentTick) { if (!this.loggedIn) { return false; } int tickDiff = currentTick - this.lastUpdate; if (tickDiff <= 0) { return true; } this.messageCounter = 2; this.lastUpdate = currentTick; if (!this.isAlive() && this.spawned) { ++this.deadTicks; if (this.deadTicks >= 10) { this.despawnFromAll(); } return true; } if (this.spawned) { this.processMovement(tickDiff); this.entityBaseTick(tickDiff); if (this.getServer().getDifficulty() == 0 && this.level.getGameRules().getBoolean("naturalRegeneration")) { if (this.getHealth() < this.getMaxHealth() && this.ticksLived % 20 == 0) { this.heal(1); } PlayerFood foodData = this.getFoodData(); if (foodData.getLevel() < 20 && this.ticksLived % 10 == 0) { foodData.addFoodLevel(1, 0); } } if (this.isOnFire() && this.lastUpdate % 10 == 0) { if (this.isCreative() && !this.isInsideOfFire()) { this.extinguish(); } else if (this.getLevel().isRaining()) { if (this.getLevel().canBlockSeeSky(this)) { this.extinguish(); } } } if (!this.isSpectator() && this.speed != null) { if (this.onGround) { if (this.inAirTicks != 0) { this.startAirTicks = 5; } this.inAirTicks = 0; this.highestPosition = this.y; } else { if (!this.isGliding() && !server.getAllowFlight() && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && this.inAirTicks > 10 && !this.isSleeping() && !this.isImmobile()) { double expectedVelocity = (-this.getGravity()) / ((double) this.getDrag()) - ((-this.getGravity()) / ((double) this.getDrag())) * Math.exp(-((double) this.getDrag()) * ((double) (this.inAirTicks - this.startAirTicks))); double diff = (this.speed.y - expectedVelocity) * (this.speed.y - expectedVelocity); if (!this.hasEffect(Effect.JUMP) && diff > 0.6 && expectedVelocity < this.speed.y) { if (this.inAirTicks < 100) { //this.sendSettings(); this.setMotion(new Vector3(0, expectedVelocity, 0)); } else if (this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server")) { return false; } } } if (this.y > highestPosition) { this.highestPosition = this.y; } if (this.isGliding()) this.resetFallDistance(); ++this.inAirTicks; } if (this.isSurvival() || this.isAdventure()) { if (this.getFoodData() != null) this.getFoodData().update(tickDiff); } } } this.checkTeleportPosition(); this.checkInteractNearby(); /* if (this.spawned && this.dummyBossBars.size() > 0 && currentTick % 100 == 0) { this.dummyBossBars.values().forEach(DummyBossBar::updateBossEntityPosition); } */ return true; } public void checkInteractNearby() { int interactDistance = isCreative() ? 5 : 3; EntityInteractable onInteract; if(this.canInteract(this, interactDistance) && (onInteract = this.getEntityPlayerLookingAt(interactDistance)) != null) { this.setButtonText(onInteract.getInteractButtonText()); } else if (this.getInventory().getItemInHand().getId() == Item.FISHING_ROD) { this.setButtonText("釣りをする"); } else { this.setButtonText(""); } } /** * Returns the Entity the player is looking at currently * * @param maxDistance the maximum distance to check for entities * @return Entity|null either NULL if no entity is found or an instance of the entity */ public EntityInteractable getEntityPlayerLookingAt(int maxDistance) { timing.startTiming(); EntityInteractable entity = null; // just a fix because player MAY not be fully initialized if (temporalVector != null) { Entity[] nearbyEntities = level.getNearbyEntities(boundingBox.grow(maxDistance, maxDistance, maxDistance), this); // get all blocks in looking direction until the max interact distance is reached (it's possible that startblock isn't found!) try { BlockIterator itr = new BlockIterator(level, getPosition(), getDirectionVector(), getEyeHeight(), maxDistance); if (itr.hasNext()) { Block block; while (itr.hasNext()) { block = itr.next(); entity = getEntityAtPosition(nearbyEntities, block.getFloorX(), block.getFloorY(), block.getFloorZ()); if (entity != null) { break; } } } } catch (Exception ex) { // nothing to log here! } } timing.stopTiming(); return entity; } private EntityInteractable getEntityAtPosition(Entity[] nearbyEntities, int x, int y, int z) { for (Entity nearestEntity : nearbyEntities) { if (nearestEntity.getFloorX() == x && nearestEntity.getFloorY() == y && nearestEntity.getFloorZ() == z && nearestEntity instanceof EntityInteractable && ((EntityInteractable) nearestEntity).canDoInteraction()) { return (EntityInteractable) nearestEntity; } } return null; } private Block breakingBlock; public void checkNetwork() { if (!this.isOnline()) { return; } if (this.nextChunkOrderRun-- <= 0 || this.chunk == null) { this.orderChunks(); } if (!this.loadQueue.isEmpty() || !this.spawned) { this.sendNextChunk(); } if (!this.batchedPackets.isEmpty()) { for (int channel : this.batchedPackets.keySet()) { this.server.batchPackets(new Player[]{this}, batchedPackets.get(channel).stream().toArray(DataPacket[]::new), false); } this.batchedPackets = new TreeMap<>(); } } public boolean canInteract(Vector3 pos, double maxDistance) { return this.canInteract(pos, maxDistance, 0.5); } public boolean canInteract(Vector3 pos, double maxDistance, double maxDiff) { if (this.distanceSquared(pos) > maxDistance * maxDistance) { return false; } Vector2 dV = this.getDirectionPlane(); double dot = dV.dot(new Vector2(this.x, this.z)); double dot1 = dV.dot(new Vector2(pos.x, pos.z)); return (dot1 - dot) >= -maxDiff; } protected void processLogin() { if (!this.server.isWhitelisted((this.getName()).toLowerCase())) { this.kick(PlayerKickEvent.Reason.NOT_WHITELISTED, "Server is white-listed"); return; } else if (this.isBanned()) { this.kick(PlayerKickEvent.Reason.NAME_BANNED, "You are banned"); return; } else if (this.server.getIPBans().isBanned(this.getAddress())) { this.kick(PlayerKickEvent.Reason.IP_BANNED, "You are banned"); return; } if (this.hasPermission(Server.BROADCAST_CHANNEL_USERS)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_USERS, this); } if (this.hasPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE)) { this.server.getPluginManager().subscribeToPermission(Server.BROADCAST_CHANNEL_ADMINISTRATIVE, this); } for (Player p : this.server.getOnlinePlayers().values()) { if (p != this && p.getName() != null && p.getName().equalsIgnoreCase(this.getName())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } else if (p.loggedIn && this.getUniqueId().equals(p.getUniqueId())) { if (!p.kick(PlayerKickEvent.Reason.NEW_CONNECTION, "logged in from another location")) { this.close(this.getLeaveMessage(), "Already connected"); return; } } } namedTag = this.server.getOfflinePlayerData(this.username); if (namedTag == null) { this.close(this.getLeaveMessage(), "Invalid data"); return; } this.playedBefore = (namedTag.getLong("lastPlayed") - namedTag.getLong("firstPlayed")) > 1; boolean alive = true; namedTag.putString("NameTag", this.username); if (0 >= namedTag.getShort("Health")) { alive = false; } int exp = namedTag.getInt("EXP"); int expLevel = namedTag.getInt("expLevel"); this.setExperience(exp, expLevel); this.setGamemode(namedTag.getInt("playerGameType") & 0x03); if (this.server.getForceGamemode()) { this.gamemode = this.server.getDefaultGamemode(); namedTag.putInt("playerGameType", this.gamemode); } Level level; if ((level = this.server.getLevelByName(namedTag.getString("Level"))) == null || !alive) { this.setLevel(this.server.getDefaultLevel()); namedTag.putString("Level", this.level.getName()); namedTag.getList("Pos", DoubleTag.class) .add(new DoubleTag("0", this.level.getSpawnLocation().x)) .add(new DoubleTag("1", this.level.getSpawnLocation().y)) .add(new DoubleTag("2", this.level.getSpawnLocation().z)); } else { this.setLevel(level); } for (Tag achievement : namedTag.getCompound("Achievements").getAllTags()) { if (!(achievement instanceof ByteTag)) { continue; } if (((ByteTag) achievement).getData() > 0) { this.achievements.add(achievement.getName()); } } namedTag.putLong("lastPlayed", System.currentTimeMillis() / 1000); if (this.server.getAutoSave()) { this.server.saveOfflinePlayerData(this.username, namedTag, true); } ListTag<DoubleTag> posList = namedTag.getList("Pos", DoubleTag.class); super.init(this.level.getChunk((int) posList.get(0).data >> 4, (int) posList.get(2).data >> 4, true), namedTag); if (!this.namedTag.contains("foodLevel")) { this.namedTag.putInt("foodLevel", 20); } int foodLevel = this.namedTag.getInt("foodLevel"); if (!this.namedTag.contains("FoodSaturationLevel")) { this.namedTag.putFloat("FoodSaturationLevel", 20); } float foodSaturationLevel = this.namedTag.getFloat("foodSaturationLevel"); this.foodData = new PlayerFood(this, foodLevel, foodSaturationLevel); PlayerLoginEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerLoginEvent(this, "Plugin reason")); if (ev.isCancelled()) { this.close(this.getLeaveMessage(), ev.getKickMessage()); return; } this.server.addOnlinePlayer(this); this.loggedIn = true; if (this.isCreative()) { this.inventory.setHeldItemSlot(0); } else { this.inventory.setHeldItemSlot(this.inventory.getHotbarSlotIndex(0)); } if (this.isSpectator()) this.keepMovement = true; if (this.spawnPosition == null && this.namedTag.contains("SpawnLevel") && (level = this.server.getLevelByName(this.namedTag.getString("SpawnLevel"))) != null) { this.spawnPosition = new Position(this.namedTag.getInt("SpawnX"), this.namedTag.getInt("SpawnY"), this.namedTag.getInt("SpawnZ"), level); } Position spawnPosition = this.getSpawn(); StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.entityUniqueId = this.id; startGamePacket.entityRuntimeId = this.id; startGamePacket.playerGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.x = (float) this.x; startGamePacket.y = (float) this.y; startGamePacket.z = (float) this.z; startGamePacket.yaw = (float) this.yaw; startGamePacket.pitch = (float) this.pitch; startGamePacket.seed = -1; startGamePacket.dimension = (byte) (spawnPosition.level.getDimension() & 0xff); startGamePacket.worldGamemode = getClientFriendlyGamemode(this.gamemode); startGamePacket.difficulty = this.server.getDifficulty(); startGamePacket.spawnX = (int) spawnPosition.x; startGamePacket.spawnY = (int) spawnPosition.y + (int) this.getEyeHeight(); startGamePacket.spawnZ = (int) spawnPosition.z; startGamePacket.hasAchievementsDisabled = true; startGamePacket.dayCycleStopTime = -1; startGamePacket.eduMode = false; startGamePacket.rainLevel = 0; startGamePacket.lightningLevel = 0; startGamePacket.commandsEnabled = this.isEnableClientCommand(); startGamePacket.levelId = ""; startGamePacket.worldName = this.getServer().getNetwork().getName(); startGamePacket.generator = 1; //0 old, 1 infinite, 2 flat this.dataPacket(startGamePacket); SetTimePacket setTimePacket = new SetTimePacket(); setTimePacket.time = this.level.getTime(); this.dataPacket(setTimePacket); this.setMovementSpeed(DEFAULT_SPEED); this.sendAttributes(); this.setNameTagVisible(true); this.setNameTagAlwaysVisible(true); this.setCanClimb(true); this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logIn", FastAppender.get(TextFormat.AQUA, this.username, TextFormat.WHITE), this.ip, String.valueOf(this.port), String.valueOf(this.id), this.level.getName(), String.valueOf(NukkitMath.round(this.x, 4)), String.valueOf(NukkitMath.round(this.y, 4)), String.valueOf(NukkitMath.round(this.z, 4)))); if (this.isOp()) { this.setRemoveFormat(false); } this.setEnableClientCommand(true); this.server.sendFullPlayerListData(this); this.forceMovement = this.teleportPosition = this.getPosition(); this.server.onPlayerLogin(this); ResourcePacksInfoPacket pk = new ResourcePacksInfoPacket(); ResourcePackManager manager = this.server.getResourcePackManager(); pk.resourcePackEntries = manager.getResourceStack(); pk.mustAccept = true; this.dataPacket(pk); } @Override protected void initEntity() { super.initEntity(); this.addDefaultWindows(); } public void handleDataPacket(DataPacket packet) { if (!connected) { return; } try (Timing timing = Timings.getReceiveDataPacketTiming(packet)) { DataPacketReceiveEvent ev = new DataPacketReceiveEvent(this, packet); this.server.getPluginManager().callEvent(ev); if(this.printPackets) { this.getServer().getLogger().info(TextFormat.AQUA + "[RECEIVE] " + TextFormat.WHITE + packet.getName()); } if (ev.isCancelled()) { timing.stopTiming(); return; } if (packet.pid() == ProtocolInfo.BATCH_PACKET) { timing.stopTiming(); this.server.getNetwork().processBatch((BatchPacket) packet, this); return; } Item item; Block block; packetswitch: switch (packet.pid()) { case ProtocolInfo.LOGIN_PACKET: if (this.loggedIn) { break; } LoginPacket loginPacket = (LoginPacket) packet; String message; if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { if (loginPacket.getProtocol() < ProtocolInfo.CURRENT_PROTOCOL) { message = "disconnectionScreen.outdatedClient"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_CLIENT); } else { message = "disconnectionScreen.outdatedServer"; this.sendPlayStatus(PlayStatusPacket.LOGIN_FAILED_SERVER); } this.close("", message, false); break; } this.loginChainData = new ClientChainData(loginPacket); this.serverSettings = this.server.getDefaultServerSettings(); this.username = TextFormat.clean(this.loginChainData.getUsername()); this.displayName = this.username; this.iusername = this.username.toLowerCase(); this.setDataProperty(new StringEntityData(DATA_NAMETAG, this.username), false); if (this.server.getOnlinePlayers().size() >= this.server.getMaxPlayers() && this.kick(PlayerKickEvent.Reason.SERVER_FULL, "disconnectionScreen.serverFull", false)) { break; } this.randomClientId = this.loginChainData.getClientId(); this.uuid = this.loginChainData.getClientUUID(); this.rawUUID = Binary.writeUUID(this.uuid); boolean valid = true; int len = this.username.length(); if (len > 16 || len < 3) { valid = false; } for (int i = 0; i < len && valid; i++) { char c = this.username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == ' ' ) { continue; } valid = false; break; } if (!valid || Objects.equals(this.iusername, "rcon") || Objects.equals(this.iusername, "console")) { this.close("", "disconnectionScreen.invalidName"); break; } if (!this.loginChainData.getSkin().isValid()) { this.close("", "disconnectionScreen.invalidSkin"); break; } else { this.setSkin(this.loginChainData.getSkin()); } PlayerPreLoginEvent playerPreLoginEvent; this.server.getPluginManager().callEvent(playerPreLoginEvent = new PlayerPreLoginEvent(this, "Plugin reason")); if (playerPreLoginEvent.isCancelled()) { this.close("", playerPreLoginEvent.getKickMessage()); break; } this.sendPlayStatus(PlayStatusPacket.LOGIN_SUCCESS); ResourcePacksInfoPacket infoPacket = new ResourcePacksInfoPacket(); infoPacket.resourcePackEntries = this.server.getResourcePackManager().getResourceStack(); infoPacket.mustAccept = this.server.getForceResources(); this.dataPacket(infoPacket); break; case ProtocolInfo.RESOURCE_PACK_CLIENT_RESPONSE_PACKET: ResourcePackClientResponsePacket responsePacket = (ResourcePackClientResponsePacket) packet; switch (responsePacket.responseStatus) { case ResourcePackClientResponsePacket.STATUS_REFUSED: this.close("", "disconnectionScreen.noReason"); break; case ResourcePackClientResponsePacket.STATUS_SEND_PACKS: for (String id : responsePacket.packIds) { ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(id); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackDataInfoPacket dataInfoPacket = new ResourcePackDataInfoPacket(); dataInfoPacket.packId = resourcePack.getPackId(); dataInfoPacket.maxChunkSize = 1048576; //megabyte dataInfoPacket.chunkCount = resourcePack.getPackSize() / dataInfoPacket.maxChunkSize; dataInfoPacket.compressedPackSize = resourcePack.getPackSize(); dataInfoPacket.sha256 = resourcePack.getSha256(); this.dataPacket(dataInfoPacket); } break; case ResourcePackClientResponsePacket.STATUS_HAVE_ALL_PACKS: ResourcePackStackPacket stackPacket = new ResourcePackStackPacket(); stackPacket.mustAccept = this.server.getForceResources(); stackPacket.resourcePackStack = this.server.getResourcePackManager().getResourceStack(); this.dataPacket(stackPacket); break; case ResourcePackClientResponsePacket.STATUS_COMPLETED: this.processLogin(); break; } break; case ProtocolInfo.RESOURCE_PACK_CHUNK_REQUEST_PACKET: ResourcePackChunkRequestPacket requestPacket = (ResourcePackChunkRequestPacket) packet; ResourcePack resourcePack = this.server.getResourcePackManager().getPackById(requestPacket.packId); if (resourcePack == null) { this.close("", "disconnectionScreen.resourcePack"); break; } ResourcePackChunkDataPacket dataPacket = new ResourcePackChunkDataPacket(); dataPacket.packId = resourcePack.getPackId(); dataPacket.chunkIndex = requestPacket.chunkIndex; dataPacket.data = resourcePack.getPackChunk(1048576 * requestPacket.chunkIndex, 1048576); dataPacket.progress = 1048576 * requestPacket.chunkIndex; this.dataPacket(dataPacket); break; case ProtocolInfo.PLAYER_INPUT_PACKET: if (!this.isAlive() || !this.spawned) { break; } PlayerInputPacket ipk = (PlayerInputPacket) packet; if (riding instanceof EntityMinecartAbstract) { ((EntityMinecartEmpty) riding).setCurrentSpeed(ipk.motionY); } break; case ProtocolInfo.MOVE_PLAYER_PACKET: if (this.teleportPosition != null) { break; } MovePlayerPacket movePlayerPacket = (MovePlayerPacket) packet; Vector3 newPos = new Vector3(movePlayerPacket.x, movePlayerPacket.y - this.getEyeHeight(), movePlayerPacket.z); if (newPos.distanceSquared(this) < 0.01 && movePlayerPacket.yaw % 360 == this.yaw && movePlayerPacket.pitch % 360 == this.pitch) { break; } boolean revert = false; if (!this.isAlive() || !this.spawned) { revert = true; this.forceMovement = new Vector3(this.x, this.y, this.z); } if (this.forceMovement != null && (newPos.distanceSquared(this.forceMovement) > 0.1 || revert)) { this.sendPosition(this.forceMovement, movePlayerPacket.yaw, movePlayerPacket.pitch, MovePlayerPacket.MODE_RESET); } else { movePlayerPacket.yaw %= 360; movePlayerPacket.pitch %= 360; if (movePlayerPacket.yaw < 0) { movePlayerPacket.yaw += 360; } this.setRotation(movePlayerPacket.yaw, movePlayerPacket.pitch); this.newPosition = newPos; this.forceMovement = null; } if (riding != null) { if (riding instanceof EntityBoat) { riding.setPositionAndRotation(this.temporalVector.setComponents(movePlayerPacket.x, movePlayerPacket.y - 1, movePlayerPacket.z), (movePlayerPacket.headYaw + 90) % 360, 0); } } break; case ProtocolInfo.ADVENTURE_SETTINGS_PACKET: //TODO: player abilities, check for other changes AdventureSettingsPacket adventureSettingsPacket = (AdventureSettingsPacket) packet; if (adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT) && !this.getAdventureSettings().get(Type.ALLOW_FLIGHT)) { this.kick(PlayerKickEvent.Reason.FLYING_DISABLED, "Flying is not enabled on this server"); break; } PlayerToggleFlightEvent playerToggleFlightEvent = new PlayerToggleFlightEvent(this, adventureSettingsPacket.getFlag(AdventureSettingsPacket.ALLOW_FLIGHT)); this.server.getPluginManager().callEvent(playerToggleFlightEvent); if (playerToggleFlightEvent.isCancelled()) { this.getAdventureSettings().update(); } else { this.getAdventureSettings().set(Type.FLYING, playerToggleFlightEvent.isFlying()); } break; case ProtocolInfo.MOB_EQUIPMENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } MobEquipmentPacket mobEquipmentPacket = (MobEquipmentPacket) packet; Item item1 = this.inventory.getItem(mobEquipmentPacket.hotbarSlot); if (!item1.equals(mobEquipmentPacket.item)) { this.server.getLogger().debug("Tried to equip " + mobEquipmentPacket.item + " but have " + item1 + " in target slot"); this.inventory.sendContents(this); return; } this.inventory.equipItem(mobEquipmentPacket.hotbarSlot); this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.PLAYER_ACTION_PACKET: PlayerActionPacket playerActionPacket = (PlayerActionPacket) packet; if (!this.spawned || (!this.isAlive() && playerActionPacket.action != PlayerActionPacket.ACTION_RESPAWN && playerActionPacket.action != PlayerActionPacket.ACTION_DIMENSION_CHANGE_REQUEST)) { break; } playerActionPacket.entityRuntimeId = this.id; Vector3 pos = new Vector3(playerActionPacket.x, playerActionPacket.y, playerActionPacket.z); BlockFace face = BlockFace.fromIndex(playerActionPacket.face); switch (playerActionPacket.action) { case PlayerActionPacket.ACTION_START_BREAK: if (this.lastBreak != Long.MAX_VALUE || pos.distanceSquared(this) > 100) { break; } Block target = this.level.getBlock(pos); PlayerInteractEvent playerInteractEvent = new PlayerInteractEvent(this, this.inventory.getItemInHand(), target, face, target.getId() == 0 ? Action.LEFT_CLICK_AIR : Action.LEFT_CLICK_BLOCK); this.getServer().getPluginManager().callEvent(playerInteractEvent); if (playerInteractEvent.isCancelled()) { this.inventory.sendHeldItem(this); break; } if (target.getId() == Block.NOTEBLOCK) { ((BlockNoteblock) target).emitSound(); break; } Block block1 = target.getSide(face); if (block1.getId() == Block.FIRE) { this.level.setBlock(block1, new BlockAir(), true); break; } if (!this.isCreative()) { //improved this to take stuff like swimming, ladders, enchanted tools into account, fix wrong tool break time calculations for bad tools (pmmp/PocketMine-MP#211) //Done by lmlstarqaq double breakTime = Math.ceil(target.getBreakTime(this.inventory.getItemInHand(), this) * 20); if (breakTime > 0) { LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_START_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = (int) (65535 / breakTime); this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); } } this.breakingBlock = target; this.lastBreak = System.currentTimeMillis(); break; case PlayerActionPacket.ACTION_ABORT_BREAK: this.lastBreak = Long.MAX_VALUE; this.breakingBlock = null; case PlayerActionPacket.ACTION_STOP_BREAK: LevelEventPacket pk = new LevelEventPacket(); pk.evid = LevelEventPacket.EVENT_BLOCK_STOP_BREAK; pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; pk.data = 0; this.getLevel().addChunkPacket(pos.getFloorX() >> 4, pos.getFloorZ() >> 4, pk); this.breakingBlock = null; break; case PlayerActionPacket.ACTION_GET_UPDATED_BLOCK: break; //TODO case PlayerActionPacket.ACTION_DROP_ITEM: break; //TODO case PlayerActionPacket.ACTION_STOP_SLEEPING: this.stopSleep(); break; case PlayerActionPacket.ACTION_RESPAWN: if (!this.spawned || this.isAlive() || !this.isOnline()) { break; } if (this.server.isHardcore()) { this.setBanned(true); break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); PlayerRespawnEvent playerRespawnEvent = new PlayerRespawnEvent(this, this.getSpawn()); this.server.getPluginManager().callEvent(playerRespawnEvent); Position respawnPos = playerRespawnEvent.getRespawnPosition(); this.teleport(respawnPos, null); RespawnPacket respawnPacket = new RespawnPacket(); respawnPacket.x = (float) respawnPos.x; respawnPacket.y = (float) respawnPos.y; respawnPacket.z = (float) respawnPos.z; this.dataPacket(respawnPacket); this.setSprinting(false, true); this.setSneaking(false); this.extinguish(); this.setDataProperty(new ShortEntityData(Player.DATA_AIR, 400), false); this.deadTicks = 0; this.noDamageTicks = 60; this.removeAllEffects(); this.setHealth(this.getMaxHealth()); this.getFoodData().setLevel(20, 20); this.sendData(this); this.setMovementSpeed(DEFAULT_SPEED); this.getAdventureSettings().update(); this.inventory.sendContents(this); this.inventory.sendArmorContents(this); this.spawnToAll(); this.scheduleUpdate(); break; case PlayerActionPacket.ACTION_JUMP: break packetswitch; case PlayerActionPacket.ACTION_START_SPRINT: PlayerToggleSprintEvent playerToggleSprintEvent = new PlayerToggleSprintEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SPRINT: playerToggleSprintEvent = new PlayerToggleSprintEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSprintEvent); if (playerToggleSprintEvent.isCancelled()) { this.sendData(this); } else { this.setSprinting(false); } break packetswitch; case PlayerActionPacket.ACTION_START_SNEAK: PlayerToggleSneakEvent playerToggleSneakEvent = new PlayerToggleSneakEvent(this, true); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_SNEAK: playerToggleSneakEvent = new PlayerToggleSneakEvent(this, false); this.server.getPluginManager().callEvent(playerToggleSneakEvent); if (playerToggleSneakEvent.isCancelled()) { this.sendData(this); } else { this.setSneaking(false); } break packetswitch; case PlayerActionPacket.ACTION_DIMENSION_CHANGE_ACK: break; //TODO case PlayerActionPacket.ACTION_START_GLIDE: PlayerToggleGlideEvent playerToggleGlideEvent = new PlayerToggleGlideEvent(this, true); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(true); } break packetswitch; case PlayerActionPacket.ACTION_STOP_GLIDE: playerToggleGlideEvent = new PlayerToggleGlideEvent(this, false); this.server.getPluginManager().callEvent(playerToggleGlideEvent); if (playerToggleGlideEvent.isCancelled()) { this.sendData(this); } else { this.setGliding(false); } break packetswitch; case PlayerActionPacket.ACTION_CONTINUE_BREAK: if (this.isBreakingBlock()) { block1 = this.level.getBlock(pos); this.level.addParticle(new PunchBlockParticle(pos, block1, face)); } break; } this.startAction = -1; this.setDataFlag(Player.DATA_FLAGS, Player.DATA_FLAG_ACTION, false); break; case ProtocolInfo.MOB_ARMOR_EQUIPMENT_PACKET: break; case ProtocolInfo.INTERACT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); InteractPacket interactPacket = (InteractPacket) packet; Entity targetEntity = this.level.getEntity(interactPacket.target); if (targetEntity == null || !this.isAlive() || !targetEntity.isAlive()) { break; } if (targetEntity instanceof EntityItem || targetEntity instanceof EntityArrow || targetEntity instanceof EntityXPOrb) { this.kick(PlayerKickEvent.Reason.INVALID_PVE, "Attempting to interact with an invalid entity"); this.server.getLogger().warning(this.getServer().getLanguage().translateString("nukkit.player.invalidEntity", this.getName())); break; } item1 = this.inventory.getItemInHand(); switch (interactPacket.action) { case InteractPacket.ACTION_MOUSEOVER: this.getServer().getPluginManager().callEvent(new PlayerMouseOverEntityEvent(this, targetEntity)); break; /* case InteractPacket.ACTION_VEHICLE_EXIT: if (!(targetEntity instanceof EntityRideable) || this.riding == null) { break; } ((EntityRideable) riding).mountEntity(this); break; */ } break; case ProtocolInfo.BLOCK_PICK_REQUEST_PACKET: BlockPickRequestPacket pickRequestPacket = (BlockPickRequestPacket) packet; Block block1 = this.level.getBlock(this.temporalVector.setComponents(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); item1 = block1.toItem(); if (pickRequestPacket.addUserData) { BlockEntity blockEntity = this.getLevel().getBlockEntity(new Vector3(pickRequestPacket.x, pickRequestPacket.y, pickRequestPacket.z)); if (blockEntity != null) { CompoundTag nbt = blockEntity.getCleanedNBT(); if (nbt != null) { Item item11 = this.getInventory().getItemInHand(); item11.setCustomBlockData(nbt); item11.setLore("+(DATA)"); this.getInventory().setItemInHand(item11); } } } PlayerBlockPickEvent pickEvent = new PlayerBlockPickEvent(this, block1, item1); if (!this.isCreative()) { this.server.getLogger().debug("Got block-pick request from " + this.getName() + " when not in creative mode (gamemode " + this.getGamemode() + ")"); pickEvent.setCancelled(); } this.server.getPluginManager().callEvent(pickEvent); if (!pickEvent.isCancelled()) { this.inventory.setItemInHand(pickEvent.getItem()); } break; case ProtocolInfo.ANIMATE_PACKET: if (!this.spawned || !this.isAlive()) { break; } PlayerAnimationEvent animationEvent = new PlayerAnimationEvent(this, ((AnimatePacket) packet).action); this.server.getPluginManager().callEvent(animationEvent); if (animationEvent.isCancelled()) { break; } AnimatePacket animatePacket = new AnimatePacket(); animatePacket.entityRuntimeId = this.getId(); animatePacket.action = animationEvent.getAnimationType(); Server.broadcastPacket(this.getViewers().values(), animatePacket); break; case ProtocolInfo.SET_HEALTH_PACKET: //use UpdateAttributePacket instead break; case ProtocolInfo.ENTITY_EVENT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); //this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); //TODO: check if this should be true EntityEventPacket entityEventPacket = (EntityEventPacket) packet; switch (entityEventPacket.event) { case EntityEventPacket.USE_ITEM: //Eating Item itemInHand = this.inventory.getItemInHand(); PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(this, itemInHand); this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } if (itemInHand.getId() == Item.POTION) { Potion potion = Potion.getPotion(itemInHand.getDamage()).setSplash(false); if (this.getGamemode() == SURVIVAL) { if (itemInHand.getCount() > 1) { ItemGlassBottle bottle = new ItemGlassBottle(); if (this.inventory.canAddItem(bottle)) { this.inventory.addItem(bottle); } --itemInHand.count; } else { itemInHand = new ItemGlassBottle(); } } if (potion != null) { potion.applyPotion(this); } } else { EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getId(); pk.event = EntityEventPacket.USE_ITEM; this.dataPacket(pk); Server.broadcastPacket(this.getViewers().values(), pk); Food food = Food.getByRelative(itemInHand); if (food != null) if (food.eatenBy(this)) --itemInHand.count; } this.inventory.setItemInHand(itemInHand); this.inventory.sendHeldItem(this); break; /*case EntityEventPacket.CONSUME_ITEM: EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.getId(); pk.event = EntityEventPacket.CONSUME_ITEM; pk.itemId = this.inventory.getItemInHand().getId(); Server.broadcastPacket(this.getViewers().values(), pk); this.dataPacket(pk); break;*/ } break; case ProtocolInfo.COMMAND_REQUEST_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = 0; CommandRequestPacket commandRequestPacket = (CommandRequestPacket) packet; PlayerCommandPreprocessEvent playerCommandPreprocessEvent = new PlayerCommandPreprocessEvent(this, commandRequestPacket.command); this.server.getPluginManager().callEvent(playerCommandPreprocessEvent); if (playerCommandPreprocessEvent.isCancelled()) { break; } Timings.playerCommandTimer.startTiming(); this.server.dispatchCommand(playerCommandPreprocessEvent.getPlayer(), playerCommandPreprocessEvent.getMessage().substring(1)); Timings.playerCommandTimer.stopTiming(); break; case ProtocolInfo.TEXT_PACKET: if (!this.spawned || !this.isAlive()) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); TextPacket textPacket = (TextPacket) packet; if (textPacket.type == TextPacket.TYPE_CHAT) { textPacket.message = this.removeFormat ? TextFormat.clean(textPacket.message) : textPacket.message; for (String msg : textPacket.message.split("\n")) { if (!"".equals(msg.trim()) && msg.length() <= 255 && this.messageCounter-- > 0) { PlayerChatEvent chatEvent = new PlayerChatEvent(this, msg); this.server.getPluginManager().callEvent(chatEvent); if (!chatEvent.isCancelled()) { this.server.broadcastMessage(this.getServer().getLanguage().translateString(chatEvent.getFormat(), new String[]{chatEvent.getPlayer().getDisplayName(), chatEvent.getMessage()}), chatEvent.getRecipients()); } } } } break; case ProtocolInfo.CONTAINER_CLOSE_PACKET: ContainerClosePacket containerClosePacket = (ContainerClosePacket) packet; if (!this.spawned || containerClosePacket.windowId == 0) { break; } this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); if (this.windowIndex.containsKey(containerClosePacket.windowId)) { /* * TODO PreSignChangeEvent * 看板を変更する画面を閉じたときにだけ呼ぶイベント。 * XがウィンドウIDだが、それが看板(未調査)の場合のみ実行。 if(containerClosePacket.windowid == X){ PreSignChangeEvent presignchangeevent = new PreSignChangeEvent(blockEntity.getBlock(), this, new String[]{ signText1, signText2, signText3, signText4 }); if (!blockEntity.namedTag.contains("Creator") || !Objects.equals(this.getUniqueId().toString(), blockEntity.namedTag.getString("Creator"))) { presignchangeevent.setCancelled(); } this.server.getPluginManager().callEvent(presignchangeevent); } */ this.server.getPluginManager().callEvent(new InventoryCloseEvent(this.windowIndex.get(containerClosePacket.windowId), this)); this.removeWindow(this.windowIndex.get(containerClosePacket.windowId)); } else { this.windowIndex.remove(containerClosePacket.windowId); } break; case ProtocolInfo.CRAFTING_EVENT_PACKET: CraftingEventPacket craftingEventPacket = (CraftingEventPacket) packet; if (!this.spawned || !this.isAlive()) { break; } Recipe recipe = this.server.getCraftingManager().getRecipe(craftingEventPacket.id); Recipe[] recipes = this.server.getCraftingManager().getRecipesByResult(craftingEventPacket.output[0]); boolean isValid = false; for (Recipe rec : recipes){ if (rec.getId().equals(recipe.getId())) { isValid = true; break; } } if (isValid) recipes = new Recipe[]{recipe}; if (!this.windowIndex.containsKey(craftingEventPacket.windowId)) { this.inventory.sendContents(this); containerClosePacket = new ContainerClosePacket(); containerClosePacket.windowId = craftingEventPacket.windowId; this.dataPacket(containerClosePacket); break; } if (isValid && (recipe == null || (((recipe instanceof BigShapelessRecipe) || (recipe instanceof BigShapedRecipe)) && this.craftingType == CRAFTING_SMALL))) { this.inventory.sendContents(this); break; } for (int i = 0; i < craftingEventPacket.input.length; i++) { Item inputItem = craftingEventPacket.input[i]; if (inputItem.getDamage() == -1 || inputItem.getDamage() == 0xffff) { inputItem.setDamage(null); } if (i < 9 && inputItem.getId() > 0) { inputItem.setCount(1); } } boolean canCraft = true; Map<String, Item> realSerialized = new HashMap<>(); for (Recipe rec : recipes) { ArrayList<Item> ingredientz = new ArrayList<>(); if (rec == null || (((rec instanceof BigShapelessRecipe) || (rec instanceof BigShapedRecipe)) && this.craftingType == CRAFTING_SMALL)) { continue; } if (rec instanceof ShapedRecipe) { Map<Integer, Map<Integer, Item>> ingredients = ((ShapedRecipe) rec).getIngredientMap(); for (Map<Integer, Item> map : ingredients.values()) { for (Item ingredient : map.values()) { if (ingredient != null && ingredient.getId() != Item.AIR) { ingredientz.add(ingredient); } } } } else if (recipe instanceof ShapelessRecipe) { ShapelessRecipe recipe0 = (ShapelessRecipe) recipe; for (Item ingredient : recipe0.getIngredientList()) { if (ingredient != null && ingredient.getId() != Item.AIR) { ingredientz.add(ingredient); } } } Map<String, Item> serialized = new HashMap<>(); for (Item ingredient : ingredientz) { String hash = ingredient.getId() + ":" + ingredient.getDamage(); Item r = serialized.get(hash); if (r != null) { r.count += ingredient.getCount(); continue; } serialized.put(hash, ingredient); } boolean isPossible = true; for (Item ingredient : serialized.values()) { if (!this.craftingGrid.contains(ingredient)) { if (isValid) { canCraft = false; break; } else { isPossible = false; break; } } } if (!isPossible) continue; recipe = rec; realSerialized = serialized; break; } if (!canCraft) { this.server.getLogger().debug("(1) Unmatched recipe " + craftingEventPacket.id + " from player " + this.getName() + " not anough ingredients"); return; } CraftItemEvent craftItemEvent = new CraftItemEvent(this, realSerialized.values().stream().toArray(Item[]::new), recipe); getServer().getPluginManager().callEvent(craftItemEvent); if (craftItemEvent.isCancelled()) { this.inventory.sendContents(this); break; } for (Item ingredient : realSerialized.values()) { this.craftingGrid.removeFromAll(ingredient); } this.inventory.addItem(recipe.getResult()); /* switch (recipe.getResult().getId()) { case Item.WORKBENCH: this.awardAchievement("buildWorkBench"); break; case Item.WOODEN_PICKAXE: this.awardAchievement("buildPickaxe"); break; case Item.FURNACE: this.awardAchievement("buildFurnace"); break; case Item.WOODEN_HOE: this.awardAchievement("buildHoe"); break; case Item.BREAD: this.awardAchievement("makeBread"); break; case Item.CAKE: //TODO: detect complex recipes like cake that leave remains this.awardAchievement("bakeCake"); this.inventory.addItem(new ItemBucket(0, 3)); break; case Item.STONE_PICKAXE: case Item.GOLD_PICKAXE: case Item.IRON_PICKAXE: case Item.DIAMOND_PICKAXE: this.awardAchievement("buildBetterPickaxe"); break; case Item.WOODEN_SWORD: this.awardAchievement("buildSword"); break; case Item.DIAMOND: this.awardAchievement("diamond"); break; default: break; } */ break; case ProtocolInfo.BLOCK_ENTITY_DATA_PACKET: if (!this.spawned || !this.isAlive()) { break; } BlockEntityDataPacket blockEntityDataPacket = (BlockEntityDataPacket) packet; this.craftingType = CRAFTING_SMALL; this.resetCraftingGridType(); pos = new Vector3(blockEntityDataPacket.x, blockEntityDataPacket.y, blockEntityDataPacket.z); if (pos.distanceSquared(this) > 10000) { break; } BlockEntity t = this.level.getBlockEntity(pos); if (t instanceof BlockEntitySign) { CompoundTag nbt; try { nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } if (!BlockEntity.SIGN.equals(nbt.getString("id"))) { ((BlockEntitySign) t).spawnTo(this); } else { String[] texts = nbt.getString("Text").split("\n"); blockEntity = t; signText1 = texts.length > 0 ? texts[0] : ""; signText2 = texts.length > 1 ? texts[1] : ""; signText3 = texts.length > 2 ? texts[2] : ""; signText4 = texts.length > 3 ? texts[3] : ""; signText1 = this.removeFormat ? TextFormat.clean(signText1) : signText1; signText2 = this.removeFormat ? TextFormat.clean(signText2) : signText2; signText3 = this.removeFormat ? TextFormat.clean(signText3) : signText3; signText4 = this.removeFormat ? TextFormat.clean(signText4) : signText4; SignChangeEvent signChangeEvent = new SignChangeEvent(blockEntity.getBlock(), this, new String[]{ signText1, signText2, signText3, signText4 }); if (!t.namedTag.contains("Creator") || !Objects.equals(this.getUniqueId().toString(), t.namedTag.getString("Creator"))) { signChangeEvent.setCancelled(); } this.server.getPluginManager().callEvent(signChangeEvent); if (!signChangeEvent.isCancelled()) { ((BlockEntitySign) t).setText(signChangeEvent.getLine(0), signChangeEvent.getLine(1), signChangeEvent.getLine(2), signChangeEvent.getLine(3)); } else { ((BlockEntitySign) t).spawnTo(this); } } } else if (t instanceof BlockEntityBeacon) { CompoundTag nbt; try { nbt = NBTIO.read(blockEntityDataPacket.namedTag, ByteOrder.LITTLE_ENDIAN, true); } catch (IOException e) { throw new RuntimeException(e); } if (!BlockEntity.BEACON.equals(nbt.getString("id"))) { ((BlockEntitySign) t).spawnTo(this); } else { BlockEntityBeacon beacon = (BlockEntityBeacon) t; beacon.setPrimary(nbt.getInt("primary")); beacon.setSecondary(nbt.getInt("secondary")); BeaconInventory inventory = this.getBeacoInventory(); if (inventory != null) { inventory.setItem(0, Item.get(0)); } } } break; case ProtocolInfo.REQUEST_CHUNK_RADIUS_PACKET: RequestChunkRadiusPacket requestChunkRadiusPacket = (RequestChunkRadiusPacket) packet; ChunkRadiusUpdatedPacket chunkRadiusUpdatePacket = new ChunkRadiusUpdatedPacket(); this.chunkRadius = Math.max(3, Math.min(requestChunkRadiusPacket.radius, this.viewDistance)); chunkRadiusUpdatePacket.radius = this.chunkRadius; this.dataPacket(chunkRadiusUpdatePacket); break; case ProtocolInfo.SET_PLAYER_GAME_TYPE_PACKET: SetPlayerGameTypePacket setPlayerGameTypePacket = (SetPlayerGameTypePacket) packet; if (setPlayerGameTypePacket.gamemode != this.gamemode) { if (!this.hasPermission("nukkit.command.gamemode")) { SetPlayerGameTypePacket setPlayerGameTypePacket1 = new SetPlayerGameTypePacket(); setPlayerGameTypePacket1.gamemode = this.gamemode & 0x01; this.dataPacket(setPlayerGameTypePacket1); this.getAdventureSettings().update(); break; } this.setGamemode(setPlayerGameTypePacket.gamemode, true); Command.broadcastCommandMessage(this, new TranslationContainer("commands.gamemode.success.self", Server.getGamemodeString(this.gamemode))); } break; case ProtocolInfo.ITEM_FRAME_DROP_ITEM_PACKET: ItemFrameDropItemPacket itemFrameDropItemPacket = (ItemFrameDropItemPacket) packet; Vector3 vector3 = this.temporalVector.setComponents(itemFrameDropItemPacket.x, itemFrameDropItemPacket.y, itemFrameDropItemPacket.z); BlockEntity blockEntityItemFrame = this.level.getBlockEntity(vector3); BlockEntityItemFrame itemFrame = (BlockEntityItemFrame) blockEntityItemFrame; if (itemFrame != null) { block1 = itemFrame.getBlock(); Item itemDrop = itemFrame.getItem(); ItemFrameDropItemEvent itemFrameDropItemEvent = new ItemFrameDropItemEvent(this, block1, itemFrame, itemDrop); this.server.getPluginManager().callEvent(itemFrameDropItemEvent); if (!itemFrameDropItemEvent.isCancelled()) { if (itemDrop.getId() != Item.AIR) { vector3 = this.temporalVector.setComponents(itemFrame.x + 0.5, itemFrame.y, itemFrame.z + 0.5); this.level.dropItem(vector3, itemDrop); itemFrame.setItem(new ItemBlock(new BlockAir())); itemFrame.setItemRotation(0); this.getLevel().addSound(new ItemFrameItemRemovedSound(this)); } } else { itemFrame.spawnTo(this); } } break; case ProtocolInfo.MAP_INFO_REQUEST_PACKET: MapInfoRequestPacket pk = (MapInfoRequestPacket) packet; Item mapItem = null; for (Item item11 : this.inventory.getContents().values()) { if (item11 instanceof ItemMap && ((ItemMap) item11).getMapId() == pk.mapId) { mapItem = item11; } } if (mapItem == null) { for (BlockEntity be : this.level.getBlockEntities().values()) { if (be instanceof BlockEntityItemFrame) { BlockEntityItemFrame itemFrame1 = (BlockEntityItemFrame) be; if (itemFrame1.getItem() instanceof ItemMap && ((ItemMap) itemFrame1.getItem()).getMapId() == pk.mapId) { ((ItemMap) itemFrame1.getItem()).sendImage(this); break; } } } } if (mapItem != null) { PlayerMapInfoRequestEvent event; getServer().getPluginManager().callEvent(event = new PlayerMapInfoRequestEvent(this, mapItem)); if (!event.isCancelled()) { ((ItemMap) mapItem).sendImage(this); } } break; case ProtocolInfo.MODAL_FORM_RESPONSE_PACKET: ModalFormResponsePacket modalFormResponsePacket = (ModalFormResponsePacket) packet; if(this.activeWindow != null && this.activeWindow.getId() == modalFormResponsePacket.formId) { if (modalFormResponsePacket.data.trim().equals("null")) { PlayerModalFormCloseEvent mfce = new PlayerModalFormCloseEvent(this, modalFormResponsePacket.formId, this.activeWindow); this.activeWindow = null; this.getServer().getPluginManager().callEvent(mfce); } else { this.activeWindow.setResponse(modalFormResponsePacket.data); PlayerModalFormResponseEvent mfre = new PlayerModalFormResponseEvent(this, modalFormResponsePacket.formId, this.activeWindow); this.activeWindow = null; this.getServer().getPluginManager().callEvent(mfre); } } else { this.serverSettings.get(modalFormResponsePacket.formId).setResponse(modalFormResponsePacket.data); PlayerServerSettingsChangedEvent ssce = new PlayerServerSettingsChangedEvent(this, modalFormResponsePacket.formId, this.serverSettings.get(modalFormResponsePacket.formId)); this.getServer().getPluginManager().callEvent(ssce); } break; case ProtocolInfo.COMMAND_BLOCK_UPDATE_PACKET: if (!(this.isOp() && this.isCreative())) { break; } CommandBlockUpdatePacket update = (CommandBlockUpdatePacket) packet; if (update.isBlock) { Vector3 commandPos = new Vector3(update.x, update.y, update.z); block1 = this.level.getBlock(commandPos); if (block1 instanceof BlockCommand) { BlockEntityCommandBlock blockEntity = ((BlockCommand)block1).getBlockEntity(); if (blockEntity == null) { break; } Block place = Block.get(Block.COMMAND_BLOCK); switch (update.commandBlockMode) { case 0: place = Block.get(Block.COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; case 1: place = Block.get(Block.REPEATING_COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; case 2: place = Block.get(Block.CHAIN_COMMAND_BLOCK); place.setDamage(block1.getDamage()); break; } if (update.isConditional) { if (place.getDamage() < 8) { place.setDamage(place.getDamage() + 8); } } else { if (place.getDamage() > 8) { place.setDamage(place.getDamage() - 8); } } this.level.setBlock(block1, place, false, false); blockEntity = (BlockEntityCommandBlock) blockEntity.clone(); blockEntity.setName(update.name); blockEntity.setMode(update.commandBlockMode); blockEntity.setCommand(update.command); blockEntity.setLastOutPut(update.lastOutput); blockEntity.setAuto(!update.isRedstoneMode); blockEntity.setConditions(update.isConditional); blockEntity.spawnToAll(); } } else { //MinercartCommandBlock } break; case ProtocolInfo.LEVEL_SOUND_EVENT_PACKET: //LevelSoundEventPacket levelSoundEventPacket = (LevelSoundEventPacket) packet; //We just need to broadcast this packet to all viewers. this.level.addChunkPacket(this.getFloorX() >> 4, this.getFloorZ() >> 4, packet); break; case ProtocolInfo.INVENTORY_TRANSACTION_PACKET: InventoryTransactionPacket transactionPacket = (InventoryTransactionPacket) packet; boolean isCrafting = false; List<InventoryAction> actions = new ArrayList<>(); for (NetworkInventoryAction networkInventoryAction : transactionPacket.actions) { try { InventoryAction a = networkInventoryAction.createInventoryAction(this); if (a != null) { if (a instanceof SlotChangeAction) { if (((SlotChangeAction) a).getInventory() instanceof CraftingGrid) isCrafting = true; } actions.add(a); } } catch (Throwable e) { MainLogger.getLogger().debug("Unhandled inventory action from " + this.getName() + ": " + e.getMessage()); this.sendAllInventories(); break packetswitch; } } switch (transactionPacket.transactionType) { case InventoryTransactionPacket.TYPE_NORMAL: if (this.isSpectator()) { this.sendAllInventories(); break; } InventoryTransaction transaction = new SimpleInventoryTransaction(this, actions); if (!transaction.execute() && !isCrafting) { for (Inventory inventory : transaction.getInventories()) { inventory.sendContents(this); if (inventory instanceof PlayerInventory) { ((PlayerInventory) inventory).sendArmorContents(this); } } MainLogger.getLogger().debug("Failed to execute inventory transaction from " + this.getName() + " with actions: " + Arrays.toString(actions.stream().toArray())); //TODO: check more stuff that might need reversion break packetswitch; //oops! } //TODO: fix achievement for getting iron from furnace break packetswitch; case InventoryTransactionPacket.TYPE_MISMATCH: if (transactionPacket.actions.length > 0) { this.server.getLogger().debug("Expected 0 actions for mismatch, got " + transactionPacket.actions.length + ", " + Arrays.toString(transactionPacket.actions)); } this.sendAllInventories(); break packetswitch; case InventoryTransactionPacket.TYPE_USE_ITEM: UseItemData useItemData = (UseItemData) transactionPacket.transactionData; BlockVector3 blockVector = useItemData.blockPos; face = useItemData.face; int type = useItemData.actionType; switch (type) { case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_BLOCK: this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7)) { if (this.isCreative()) { Item i = inventory.getItemInHand(); if (this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this) != null) { break packetswitch; } } else if (inventory.getItemInHand().equals(useItemData.itemInHand)) { Item i = inventory.getItemInHand(); Item oldItem = i.clone(); //TODO: Implement adventure mode checks if ((i = this.level.useItemOn(blockVector.asVector3(), i, face, useItemData.clickPos.x, useItemData.clickPos.y, useItemData.clickPos.z, this)) != null) { if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } break packetswitch; } } } inventory.sendHeldItem(this); if (blockVector.distanceSquared(this) > 10000) { break packetswitch; } Block target = this.level.getBlock(blockVector.asVector3()); block = target.getSide(face); this.level.sendBlocks(new Player[]{this}, new Block[]{target, block}, UpdateBlockPacket.FLAG_ALL_PRIORITY); if (target instanceof BlockDoor) { BlockDoor door = (BlockDoor) target; Block part; if ((door.getDamage() & 0x08) > 0) { //up part = target.down(); if (part.getId() == target.getId()) { target = part; this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); } } } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_BREAK_BLOCK: if (!this.spawned || !this.isAlive()) { break packetswitch; } this.resetCraftingGridType(); Item i = this.getInventory().getItemInHand(); Item oldItem = i.clone(); if (this.canInteract(blockVector.add(0.5, 0.5, 0.5), this.isCreative() ? 13 : 7) && (i = this.level.useBreakOn(blockVector.asVector3(), i, this, true)) != null) { if (this.isSurvival()) { this.getFoodData().updateFoodExpLevel(0.025); if (!i.equals(oldItem) || i.getCount() != oldItem.getCount()) { inventory.setItemInHand(i); inventory.sendHeldItem(this.getViewers().values()); } } break packetswitch; } inventory.sendContents(this); target = this.level.getBlock(blockVector.asVector3()); BlockEntity blockEntity = this.level.getBlockEntity(blockVector.asVector3()); this.level.sendBlocks(new Player[]{this}, new Block[]{target}, UpdateBlockPacket.FLAG_ALL_PRIORITY); inventory.sendHeldItem(this); if (blockEntity instanceof BlockEntitySpawnable) { ((BlockEntitySpawnable) blockEntity).spawnTo(this); } break packetswitch; case InventoryTransactionPacket.USE_ITEM_ACTION_CLICK_AIR: Vector3 directionVector = this.getDirectionVector(); if (this.isCreative()) { item1 = this.inventory.getItemInHand(); } else if (!this.inventory.getItemInHand().equals(useItemData.itemInHand)) { this.inventory.sendHeldItem(this); break packetswitch; } else { item1 = this.inventory.getItemInHand(); } PlayerInteractEvent interactEvent = new PlayerInteractEvent(this, item1, directionVector, face, Action.RIGHT_CLICK_AIR); this.server.getPluginManager().callEvent(interactEvent); if (interactEvent.isCancelled()) { this.inventory.sendHeldItem(this); break packetswitch; } if (item1.onClickAir(this, directionVector) && this.isSurvival()) { this.inventory.setItemInHand(item1); } this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, true); this.startAction = this.server.getTick(); break packetswitch; default: //unknown break; } break; case InventoryTransactionPacket.TYPE_USE_ITEM_ON_ENTITY: UseItemOnEntityData useItemOnEntityData = (UseItemOnEntityData) transactionPacket.transactionData; Entity target = this.level.getEntity(useItemOnEntityData.entityRuntimeId); if (target == null) { return; } type = useItemOnEntityData.actionType; if (!useItemOnEntityData.itemInHand.equalsExact(this.inventory.getItemInHand())) { this.inventory.sendHeldItem(this); } item1 = this.inventory.getItemInHand(); switch (type) { case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_INTERACT: PlayerInteractEntityEvent playerInteractEntityEvent = new PlayerInteractEntityEvent(this, target, item1); if (this.isSpectator()) playerInteractEntityEvent.setCancelled(); getServer().getPluginManager().callEvent(playerInteractEntityEvent); if (playerInteractEntityEvent.isCancelled()) { break; } if (target.onInteract(this, item1) && this.isSurvival()) { if (item1.isTool()) { if (item1.useOn(target) && item1.getDamage() >= item1.getMaxDurability()) { item1 = new ItemBlock(new BlockAir()); } } else { if (item1.count > 1) { item1.count--; } else { item1 = new ItemBlock(new BlockAir()); } } this.inventory.setItemInHand(item1); } break; case InventoryTransactionPacket.USE_ITEM_ON_ENTITY_ACTION_ATTACK: float itemDamage = item1.getAttackDamage(); for (Enchantment enchantment : item1.getEnchantments()) { itemDamage += enchantment.getDamageBonus(target); } Map<DamageModifier, Float> damage = new EnumMap<>(DamageModifier.class); damage.put(DamageModifier.BASE, itemDamage); if (!this.canInteract(target, isCreative() ? 8 : 5)) { break; } else if (target instanceof Player) { if ((((Player) target).getGamemode() & 0x01) > 0) { break; } else if (!this.server.getPropertyBoolean("pvp") || this.server.getDifficulty() == 0) { break; } } EntityDamageByEntityEvent entityDamageByEntityEvent = new EntityDamageByEntityEvent(this, target, DamageCause.ENTITY_ATTACK, damage); if (this.isSpectator()) entityDamageByEntityEvent.setCancelled(); if (!target.attack(entityDamageByEntityEvent)) { if (item1.isTool() && this.isSurvival()) { this.inventory.sendContents(this); } break; } for (Enchantment enchantment : item1.getEnchantments()) { enchantment.doPostAttack(this, target); } if (item1.isTool() && this.isSurvival()) { if (item1.useOn(target) && item1.getDamage() >= item1.getMaxDurability()) { this.inventory.setItemInHand(new ItemBlock(new BlockAir())); } else { this.inventory.setItemInHand(item1); } } return; default: break; //unknown } break; case InventoryTransactionPacket.TYPE_RELEASE_ITEM: if (this.isSpectator()) { this.sendAllInventories(); break packetswitch; } ReleaseItemData releaseItemData = (ReleaseItemData) transactionPacket.transactionData; try { type = releaseItemData.actionType; switch (type) { case InventoryTransactionPacket.RELEASE_ITEM_ACTION_RELEASE: if (this.isUsingItem()) { item1 = this.inventory.getItemInHand(); if (item1.onReleaseUsing(this)) { this.inventory.setItemInHand(item1); } } else { this.inventory.sendContents(this); } return; case InventoryTransactionPacket.RELEASE_ITEM_ACTION_CONSUME: Item itemInHand = this.inventory.getItemInHand(); PlayerItemConsumeEvent consumeEvent = new PlayerItemConsumeEvent(this, itemInHand); if (itemInHand.getId() == Item.POTION) { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Potion potion = Potion.getPotion(itemInHand.getDamage()).setSplash(false); if (this.getGamemode() == SURVIVAL) { --itemInHand.count; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemGlassBottle()); } if (potion != null) { potion.applyPotion(this); } } else if (itemInHand.getId() == Item.BUCKET && itemInHand.getDamage() == 1) { //milk this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } EntityEventPacket eventPacket = new EntityEventPacket(); eventPacket.entityRuntimeId = this.getId(); eventPacket.event = EntityEventPacket.USE_ITEM; this.dataPacket(eventPacket); Server.broadcastPacket(this.getViewers().values(), eventPacket); if (this.isSurvival()) { itemInHand.count--; this.inventory.setItemInHand(itemInHand); this.inventory.addItem(new ItemBucket()); } this.removeAllEffects(); } else { this.server.getPluginManager().callEvent(consumeEvent); if (consumeEvent.isCancelled()) { this.inventory.sendContents(this); break; } Food food = Food.getByRelative(itemInHand); if (food != null && food.eatenBy(this)) --itemInHand.count; this.inventory.setItemInHand(itemInHand); } return; default: break; } } finally { this.setUsingItem(false); } break; default: this.inventory.sendContents(this); break; } break; case ProtocolInfo.PLAYER_HOTBAR_PACKET: PlayerHotbarPacket hotbarPacket = (PlayerHotbarPacket) packet; if (hotbarPacket.windowId != ContainerIds.INVENTORY) { return; //In PE this should never happen } this.inventory.equipItem(hotbarPacket.selectedHotbarSlot); break; case ProtocolInfo.SERVER_SETTINGS_REQUEST_PACKET: this.serverSettings.forEach((id, window) -> { ServerSettingsResponsePacket re = new ServerSettingsResponsePacket(); re.formId = id; re.data = window.toJson(); this.dataPacket(re); }); break; case ProtocolInfo.PLAYER_SKIN_PACKET: PlayerSkinPacket skin = (PlayerSkinPacket) packet; this.setSkin(skin.skin); break; default: break; } } } public BufferedImage createMap(ItemMap mapItem) { new ArrayList<>(); List<BaseFullChunk> chunks = new ArrayList<>(); Color[][] blockColors = new Color[16][16]; BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D)img.getGraphics(); chunks.add(this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, false)); for(int x=0;x < 16;x++){ for( int y=0;y < 16;y++){ blockColors[x][y] = Block.get(chunks.get(0).getHighestBlockAt((int)this.x, (int)this.z)).getColor(); g2.drawImage(img, x, y, blockColors[x][y], null); } } BufferedImage data = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); data.createGraphics().drawImage(img, 0, 0, null); return data; } /** * プレイヤーをサーバーから追放します。 * @return void */ public boolean kick() { return this.kick(""); } /** * プレイヤーをサーバーから追放します。 * 理由はPlayerkickEvent.Reason.UNKNOWNが使われます。 * @param reason 理由文 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(String reason, boolean isAdmin) { return this.kick(PlayerKickEvent.Reason.UNKNOWN, reason, isAdmin); } /** * プレイヤーをサーバーから追放します。 * 理由はPlayerkickEvent.Reason.UNKNOWNが使われます。 * @param reason 理由文 * @return boolean * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(String reason) { return kick(PlayerKickEvent.Reason.UNKNOWN, reason); } /** * プレイヤーをサーバーから追放します。 * kicked by admin.が表示されます。 * @param reason 理由 * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason) { return this.kick(reason, true); } /** * プレイヤーをサーバーから追放します。 * kicked by admin.が表示されます。 * @param reason 理由 * @param reasonString 理由文 * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, String reasonString) { return this.kick(reason, reasonString, true); } /** * プレイヤーをサーバーから追放します。 * @param reason 理由 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, boolean isAdmin) { return this.kick(reason, reason.toString(), isAdmin); } /** * プレイヤーをサーバーから追放します。 * @param reason 理由 * @param reasonString 理由文 * @param isAdmin kicked by admin.を表示するかどうか * @return boolean * @see "理由" * @see PlayerKickEvent.Reason#FLYING_DISABLED * @see PlayerKickEvent.Reason#INVALID_PVE * @see PlayerKickEvent.Reason#IP_BANNED * @see PlayerKickEvent.Reason#KICKED_BY_ADMIN * @see PlayerKickEvent.Reason#LOGIN_TIMEOUT * @see PlayerKickEvent.Reason#NAME_BANNED * @see PlayerKickEvent.Reason#NEW_CONNECTION * @see PlayerKickEvent.Reason#NOT_WHITELISTED * @see PlayerKickEvent.Reason#SERVER_FULL * @see PlayerKickEvent.Reason#UNKNOWN */ public boolean kick(PlayerKickEvent.Reason reason, String reasonString, boolean isAdmin) { PlayerKickEvent ev; this.server.getPluginManager().callEvent(ev = new PlayerKickEvent(this, reason, this.getLeaveMessage())); if (!ev.isCancelled()) { String message; if (isAdmin) { if (!this.isBanned()) { message = "Kicked by admin." + (!"".equals(reasonString) ? " Reason: " + reasonString : ""); } else { message = reasonString; } } else { if ("".equals(reasonString)) { message = "disconnectionScreen.noReason"; } else { message = reasonString; } } this.close(ev.getQuitMessage(), message); return true; } return false; } /** * プレイヤーにメッセージを送信します。 * ミュート状態では表示されません。 * (ミュート状態...isMuted()の戻り値) * @see "ミュート状態でも表示したい場合" * @see Player#sendImportantMessage(String) sendImportantMessage * @see Player#isMuted() isMuted() * @param message メッセージ内容 * @return void */ @Override public void sendMessage(String message) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } @Override public void sendMessage(TextContainer message) { if(mute)return; if (message instanceof TranslationContainer) { this.sendTranslation(message.getText(), ((TranslationContainer) message).getParameters()); return; } this.sendMessage(message.getText()); } public void sendTranslation(String message) { if(mute)return; this.sendTranslation(message, new String[0]); } public void sendTranslation(String message, String[] parameters) { if(mute)return; TextPacket pk = new TextPacket(); if (!this.server.isLanguageForced()) { pk.type = TextPacket.TYPE_TRANSLATION; pk.message = this.server.getLanguage().translateString(message, parameters, "nukkit."); for (int i = 0; i < parameters.length; i++) { parameters[i] = this.server.getLanguage().translateString(parameters[i], parameters, "nukkit."); } pk.parameters = parameters; } else { pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message, parameters); } this.dataPacket(pk); } /** * プレイヤーにポップアップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @return void */ public void sendPopup(String message) { if(mute)return; this.sendPopup(message, ""); } /** * プレイヤーにポップアップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @param subtitle サブタイトル * @return void */ public void sendPopup(String message, String subtitle) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_POPUP; pk.source = message; pk.message = subtitle; this.dataPacket(pk); } /** * プレイヤーにチップを送信します。 * ミュート状態では表示されません。 * @param message メッセージ内容 * @return void */ public void sendTip(String message) { if(mute)return; TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_TIP; pk.message = message; this.dataPacket(pk); } /** * プレイヤーにメッセージを送信します。 * ただし、ミュート状態でも表示されます。 * @param message メッセージ内容 * @return void * @author Itsu */ public void sendImportantMessage(String message) { TextPacket pk = new TextPacket(); pk.type = TextPacket.TYPE_RAW; pk.message = this.server.getLanguage().translateString(message); this.dataPacket(pk); } public void clearTitle() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_CLEAR; this.dataPacket(pk); } /** * Resets both title animation times and subtitle for the next shown title */ public void resetTitleSettings() { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_RESET; this.dataPacket(pk); } /** * プレイヤーにタイトルを送信します。 * ミュート状態では表示されません。 * @param text タイトル内容 * @return void */ public void sendTitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_TITLE; pk.text = text; this.dataPacket(pk); } /** * プレイヤーにサブタイトルを送信します。 * ミュート状態では表示されません。 * @param text サブタイトル内容 * @return void */ public void setSubtitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_SUBTITLE; pk.text = text; this.dataPacket(pk); } public void sendActionBarTitle(String text) { if(mute)return; SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ACTION_BAR; pk.text = text; this.dataPacket(pk); } /** * Sets times for title animations * @param fadeInTime For how long title fades in * @param stayTime For how long title is shown * @param fadeOutTime For how long title fades out */ public void setTitleAnimationTimes(int fadeInTime, int stayTime, int fadeOutTime) { SetTitlePacket pk = new SetTitlePacket(); pk.type = SetTitlePacket.TYPE_ANIMATION_TIMES; pk.fadeInTime = fadeInTime; pk.stayTime = stayTime; pk.fadeOutTime = fadeOutTime; this.dataPacket(pk); } /** * 128x128の大きさでMapにpathの画像を貼り付けます。 * @param path 画像のパス * @param item Map * @return void * @author Megapix96 * @see "幅と高さを指定する場合" * @see Player#sendImage(String, ItemMap, int, int) sendImage(String, ItemMap, int, int) */ public void sendImage(String path, ItemMap item) throws IOException{ this.sendImage(path, item, 128, 128); } /** * 128x128の大きさでMapに画像を貼り付けます。 * @param img 画像 * @param item Map * @return void * @author Megapix96 * @see "幅と高さを指定する場合" * @see Player#sendImage(String, ItemMap, int, int) sendImage(String, ItemMap, int, int) */ public void sendImage(BufferedImage img, ItemMap item) throws IOException{ this.sendImage(img, item, 128, 128); } /** * Mapにpathの画像を貼り付けます。 * @param path 画像のパス * @param item Map * @param width 幅 * @param height 高さ * @return void * @author Megapix96 */ public void sendImage(String path, ItemMap item, int width, int height) throws IOException{ item.setImage(new File(path)); ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); pk.mapId = item.getMapId(); pk.update = 2; pk.scale = 0; pk.width = width; pk.height = height; pk.offsetX = 0; pk.offsetZ = 0; pk.image = item.loadImageFromNBT(); this.dataPacket(pk); } /** * Mapにpathの画像を貼り付けます。 * @param img 画像 * @param item Map * @param width 幅 * @param height 高さ * @return void * @author Megapix96 */ public void sendImage(BufferedImage img, ItemMap item, int width, int height) throws IOException{ item.setImage(img); ClientboundMapItemDataPacket pk = new ClientboundMapItemDataPacket(); pk.mapId = item.getMapId(); pk.update = 2; pk.scale = 0; pk.width = width; pk.height = height; pk.offsetX = 0; pk.offsetZ = 0; pk.image = item.loadImageFromNBT(); this.dataPacket(pk); } @Override public void close() { this.close(""); } public void close(String message) { this.close(message, "generic"); } public void close(String message, String reason) { this.close(message, reason, true); } public void close(String message, String reason, boolean notify) { this.close(new TextContainer(message), reason, notify); } public void close(TextContainer message) { this.close(message, "generic"); } public void close(TextContainer message, String reason) { this.close(message, reason, true); } public void close(TextContainer message, String reason, boolean notify) { this.unlinkHookFromPlayer(); if (this.connected && !this.closed) { if (notify && reason.length() > 0) { DisconnectPacket pk = new DisconnectPacket(); pk.message = reason; this.directDataPacket(pk); } // this.connected = false; PlayerQuitEvent ev = null; if (this.getName() != null && this.getName().length() > 0) { this.server.getPluginManager().callEvent(ev = new PlayerQuitEvent(this, message, true, reason)); if (this.loggedIn && ev.getAutoSave()) { this.save(); } } for (Player player : this.server.getOnlinePlayers().values()) { if (!player.canSee(this)) { player.showPlayer(this); } } this.hiddenPlayers = new HashMap<>(); this.removeAllWindows(true); for (long index : new ArrayList<>(this.usedChunks.keySet())) { int chunkX = Level.getHashX(index); int chunkZ = Level.getHashZ(index); this.level.unregisterChunkLoader(this, chunkX, chunkZ); this.usedChunks.remove(index); } super.close(); this.interfaz.close(this, notify ? reason : ""); if (this.loggedIn) { this.server.removeOnlinePlayer(this); } this.loggedIn = false; if (ev != null && !Objects.equals(this.username, "") && this.spawned && !Objects.equals(ev.getQuitMessage().toString(), "") && this.getServer().getJupiterConfigBoolean("join-quit-message")) { this.server.broadcastMessage(ev.getQuitMessage()); } this.server.getPluginManager().unsubscribeFromPermission(Server.BROADCAST_CHANNEL_USERS, this); this.spawned = false; this.server.getLogger().info(this.getServer().getLanguage().translateString("nukkit.player.logOut", TextFormat.AQUA + (this.getName() == null ? "" : this.getName()) + TextFormat.WHITE, this.ip, String.valueOf(this.port), this.getServer().getLanguage().translateString(reason))); this.windows = new HashMap<>(); this.windowIndex = new HashMap<>(); this.usedChunks = new HashMap<>(); this.loadQueue = new HashMap<>(); this.hasSpawned = new HashMap<>(); this.spawnPosition = null; if (this.riding instanceof EntityVehicle) { ((EntityVehicle) this.riding).linkedEntity = null; } this.riding = null; } if (this.perm != null) { this.perm.clearPermissions(); this.perm = null; } if (this.inventory != null) { this.inventory = null; } this.chunk = null; this.server.removePlayer(this); } public void save() { this.save(false); } public void save(boolean async) { if (this.closed) { throw new IllegalStateException("Tried to save closed player"); } super.saveNBT(); if (this.level != null) { this.namedTag.putString("Level", this.level.getFolderName()); if (this.spawnPosition != null && this.spawnPosition.getLevel() != null) { this.namedTag.putString("SpawnLevel", this.spawnPosition.getLevel().getFolderName()); this.namedTag.putInt("SpawnX", (int) this.spawnPosition.x); this.namedTag.putInt("SpawnY", (int) this.spawnPosition.y); this.namedTag.putInt("SpawnZ", (int) this.spawnPosition.z); } CompoundTag achievements = new CompoundTag(); for (String achievement : this.achievements) { achievements.putByte(achievement, 1); } this.namedTag.putCompound("Achievements", achievements); this.namedTag.putInt("playerGameType", this.gamemode); this.namedTag.putLong("lastPlayed", System.currentTimeMillis() / 1000); this.namedTag.putString("lastIP", this.getAddress()); this.namedTag.putInt("EXP", this.getExperience()); this.namedTag.putInt("expLevel", this.getExperienceLevel()); this.namedTag.putInt("foodLevel", this.getFoodData().getLevel()); this.namedTag.putFloat("foodSaturationLevel", this.getFoodData().getFoodSaturationLevel()); if (!"".equals(this.username) && this.namedTag != null) { this.server.saveOfflinePlayerData(this.username, this.namedTag, async); } } } /** * プレイヤー名を取得します。 * @return String プレイヤー名 */ public String getName() { if (this.username == null) { return null; } synchronized(this.username){ return this.username; } } /** * プレイヤーを殺害します。 * @return void */ @Override public void kill() { if (!this.spawned) { return; } String message = "death.attack.generic"; List<String> params = new ArrayList<>(); params.add(this.getDisplayName()); EntityDamageEvent cause = this.getLastDamageCause(); switch (cause == null ? DamageCause.CUSTOM : cause.getCause()) { case ENTITY_ATTACK: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.player"; params.add(((Player) e).getDisplayName()); break; } else if (e instanceof EntityLiving) { message = "death.attack.mob"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case PROJECTILE: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.arrow"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.arrow"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } else { params.add("Unknown"); } } break; case SUICIDE: message = "death.attack.generic"; break; case VOID: message = "death.attack.outOfWorld"; break; case FALL: if (cause != null) { if (cause.getFinalDamage() > 2) { message = "death.fell.accident.generic"; break; } } message = "death.attack.fall"; break; case SUFFOCATION: message = "death.attack.inWall"; break; case LAVA: message = "death.attack.lava"; break; case FIRE: message = "death.attack.onFire"; break; case FIRE_TICK: message = "death.attack.inFire"; break; case DROWNING: message = "death.attack.drown"; break; case CONTACT: if (cause instanceof EntityDamageByBlockEvent) { if (((EntityDamageByBlockEvent) cause).getDamager().getId() == Block.CACTUS) { message = "death.attack.cactus"; } } break; case BLOCK_EXPLOSION: case ENTITY_EXPLOSION: if (cause instanceof EntityDamageByEntityEvent) { Entity e = ((EntityDamageByEntityEvent) cause).getDamager(); killer = e; if (e instanceof Player) { message = "death.attack.explosion.player"; params.add(((Player) e).getDisplayName()); } else if (e instanceof EntityLiving) { message = "death.attack.explosion.player"; params.add(!Objects.equals(e.getNameTag(), "") ? e.getNameTag() : e.getName()); break; } } else { message = "death.attack.explosion"; } break; case MAGIC: message = "death.attack.magic"; break; case CUSTOM: break; default: } this.health = 0; this.scheduleUpdate(); PlayerDeathEvent ev = new PlayerDeathEvent(this, this.getDrops(), new TranslationContainer(message, params.stream().toArray(String[]::new)), this.getExperienceLevel()); if (this.keepInventory){ ev.setKeepInventory(true); } if (this.keepExperience){ ev.setKeepExperience(true); } this.server.getPluginManager().callEvent(ev); if (!ev.getKeepInventory()) { for (Item item : ev.getDrops()) { this.level.dropItem(this, item, null, true, 40); } if (this.inventory != null) { this.inventory.clearAll(); } } if (this.keepExperience){ ev.setKeepExperience(true); } if (!ev.getKeepExperience()) { if (this.isSurvival() || this.isAdventure()) { int exp = ev.getExperience() * 7; if (exp > 100) exp = 100; int add = 1; for (int ii = 1; ii < exp; ii += add) { this.getLevel().dropExpOrb(this, add); add = new NukkitRandom().nextRange(1, 3); } } this.setExperience(0, 0); } if (!Objects.equals(ev.getDeathMessage().toString(), "")) { this.server.broadcast(ev.getDeathMessage(), Server.BROADCAST_CHANNEL_USERS); } RespawnPacket pk = new RespawnPacket(); Position pos = this.getSpawn(); pk.x = (float) pos.x; pk.y = (float) pos.y; pk.z = (float) pos.z; this.dataPacket(pk); } /** * プレイヤーの体力を設定します。 * @param health 設定する体力量 * @return void */ @Override public void setHealth(float health) { if (health < 1) { health = 0; } super.setHealth(health); Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH).setMaxValue(this.getAbsorption() % 2 != 0 ? this.getMaxHealth() + 1 : this.getMaxHealth()).setValue(health > 0 ? (health < getMaxHealth() ? health : getMaxHealth()) : 0); if (this.spawned) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attr}; pk.entityRuntimeId = this.id; this.dataPacket(pk); } } /** * プレイヤーの経験値を取得します。 * @return int 経験値 */ public int getExperience() { return this.exp; } /** * プレイヤーの経験値レベルを取得します。 * @return int 経験値レベル */ public int getExperienceLevel() { return this.expLevel; } /** * プレイヤーの経験値を追加します。 * @param add 追加する経験値量 * @return void */ public void addExperience(int add) { if (add == 0) return; int now = this.getExperience(); int added = now + add; int level = this.getExperienceLevel(); int most = calculateRequireExperience(level); while (added >= most) { //Level Up! added = added - most; level++; most = calculateRequireExperience(level); } this.setExperience(added, level); } public static int calculateRequireExperience(int level) { if (level >= 30) { return 112 + (level - 30) * 9; } else if (level >= 15) { return 37 + (level - 15) * 5; } else { return 7 + level * 2; } } /** * プレイヤーの経験値を設定します。 * @param exp 設定する経験値量 * @return void */ public void setExperience(int exp) { setExperience(exp, this.getExperienceLevel()); } //todo something on performance, lots of exp orbs then lots of packets, could crash client /** * プレイヤーの経験値と経験値レベルを設定します。 * @param exp 設定する経験値量 * @param level 設定する経験値レベル * @return void */ public void setExperience(int exp, int level) { this.exp = exp; this.expLevel = level; this.sendExperienceLevel(level); this.sendExperience(exp); } public void sendExperience() { sendExperience(this.getExperience()); } public void sendExperience(int exp) { if (this.spawned) { float percent = ((float) exp) / calculateRequireExperience(this.getExperienceLevel()); this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE).setValue(percent)); } } public void sendExperienceLevel() { sendExperienceLevel(this.getExperienceLevel()); } public void sendExperienceLevel(int level) { if (this.spawned) { this.setAttribute(Attribute.getAttribute(Attribute.EXPERIENCE_LEVEL).setValue(level)); } } public void setAttribute(Attribute attribute) { UpdateAttributesPacket pk = new UpdateAttributesPacket(); pk.entries = new Attribute[]{attribute}; pk.entityRuntimeId = this.id; this.dataPacket(pk); } @Override public void setMovementSpeed(float speed) { super.setMovementSpeed(speed); if (this.spawned) { Attribute attribute = Attribute.getAttribute(Attribute.MOVEMENT_SPEED).setValue(speed); this.setAttribute(attribute); } } public Entity getKiller() { return killer; } @Override public boolean attack(EntityDamageEvent source) { if (!this.isAlive()) { return false; } if (this.isCreative() && source.getCause() != DamageCause.MAGIC && source.getCause() != DamageCause.SUICIDE && source.getCause() != DamageCause.VOID ) { //source.setCancelled(); return false; } else if (this.getAdventureSettings().get(Type.ALLOW_FLIGHT) && source.getCause() == DamageCause.FALL) { //source.setCancelled(); return false; } else if (source.getCause() == DamageCause.FALL) { if (this.getLevel().getBlock(this.getPosition().floor().add(0.5, -1, 0.5)).getId() == Block.SLIME_BLOCK) { if (!this.isSneaking()) { //source.setCancelled(); return false; } } } if (source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); if (damager instanceof Player) { ((Player) damager).getFoodData().updateFoodExpLevel(0.3); } if (!damager.onGround) { NukkitRandom random = new NukkitRandom(); for (int i = 0; i < 5; i++) { CriticalParticle par = new CriticalParticle(new Vector3(this.x + random.nextRange(-15, 15) / 10, this.y + random.nextRange(0, 20) / 10, this.z + random.nextRange(-15, 15) / 10)); this.getLevel().addParticle(par); } source.setDamage((float) (source.getDamage() * 1.5)); } } if (super.attack(source)) { //!source.isCancelled() if (this.getLastDamageCause() == source && this.spawned) { this.getFoodData().updateFoodExpLevel(0.3); EntityEventPacket pk = new EntityEventPacket(); pk.entityRuntimeId = this.id; pk.event = EntityEventPacket.HURT_ANIMATION; this.dataPacket(pk); } return true; } else { return false; } } public void sendPosition(Vector3 pos) { this.sendPosition(pos, this.yaw); } public void sendPosition(Vector3 pos, double yaw) { this.sendPosition(pos, yaw, this.pitch); } public void sendPosition(Vector3 pos, double yaw, double pitch) { this.sendPosition(pos, yaw, pitch, MovePlayerPacket.MODE_NORMAL); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode) { this.sendPosition(pos, yaw, pitch, mode, null); } public void sendPosition(Vector3 pos, double yaw, double pitch, int mode, Player[] targets) { MovePlayerPacket pk = new MovePlayerPacket(); pk.entityRuntimeId = this.getId(); pk.x = (float) pos.x; pk.y = (float) (pos.y + this.getEyeHeight()); pk.z = (float) pos.z; pk.headYaw = (float) yaw; pk.pitch = (float) pitch; pk.yaw = (float) yaw; pk.mode = mode; if (targets != null) { Server.broadcastPacket(targets, pk); } else { pk.entityRuntimeId = this.id; this.dataPacket(pk); } } @Override protected void checkChunks() { if (this.chunk == null || (this.chunk.getX() != ((int) this.x >> 4) || this.chunk.getZ() != ((int) this.z >> 4))) { if (this.chunk != null) { this.chunk.removeEntity(this); } this.chunk = this.level.getChunk((int) this.x >> 4, (int) this.z >> 4, true); if (!this.justCreated) { Map<Integer, Player> newChunk = new HashMap<>(this.level.getChunkPlayers((int) this.x >> 4, (int) this.z >> 4)); newChunk.remove((int) this.getLoaderId()); //List<Player> reload = new ArrayList<>(); for (Player player : new ArrayList<>(this.hasSpawned.values())) { if (!newChunk.containsKey((int) player.getLoaderId())) { this.despawnFrom(player); } else { newChunk.remove((int) player.getLoaderId()); //reload.add(player); } } for (Player player : newChunk.values()) { this.spawnTo(player); } } if (this.chunk == null) { return; } this.chunk.addEntity(this); } } protected boolean checkTeleportPosition() { if (this.teleportPosition != null) { int chunkX = (int) this.teleportPosition.x >> 4; int chunkZ = (int) this.teleportPosition.z >> 4; for (int X = -1; X <= 1; ++X) { for (int Z = -1; Z <= 1; ++Z) { long index = Level.chunkHash(chunkX + X, chunkZ + Z); if (!this.usedChunks.containsKey(index) || !this.usedChunks.get(index)) { return false; } } } this.spawnToAll(); this.forceMovement = this.teleportPosition; this.teleportPosition = null; return true; } return false; } public Inventory getWindowById(int id) { return this.windowIndex.get(id); } protected void sendPlayStatus(int status) { sendPlayStatus(status, false); } protected void sendPlayStatus(int status, boolean immediate) { PlayStatusPacket pk = new PlayStatusPacket(); pk.status = status; if (immediate) { this.directDataPacket(pk); } else { this.dataPacket(pk); } } @Override public boolean teleport(Location location, TeleportCause cause) { if (!this.isOnline()) { return false; } Location from = this.getLocation(); Location to = location; if (cause != null) { PlayerTeleportEvent event = new PlayerTeleportEvent(this, from, to, cause); this.server.getPluginManager().callEvent(event); if (event.isCancelled()) return false; to = event.getTo(); if (from.getLevel().getId() != to.getLevel().getId()) { SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = to.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } } this.getPosition(); if (super.teleport(to, null)) { // null to prevent fire of duplicate EntityTeleportEvent this.removeAllWindows(); this.teleportPosition = new Vector3(this.x, this.y, this.z); this.forceMovement = this.teleportPosition; this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_TELEPORT); this.checkTeleportPosition(); this.resetFallDistance(); this.nextChunkOrderRun = 0; this.newPosition = null; //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); return true; } return false; } public void teleportImmediate(Location location) { this.teleportImmediate(location, TeleportCause.PLUGIN); } public void teleportImmediate(Location location, TeleportCause cause) { Location from = this.getLocation(); if (super.teleport(location, cause)) { for (Inventory window : new ArrayList<>(this.windowIndex.values())) { if (window == this.inventory) { continue; } this.removeWindow(window); } if (from.getLevel().getId() != location.getLevel().getId()) { SetSpawnPositionPacket pk = new SetSpawnPositionPacket(); pk.spawnType = SetSpawnPositionPacket.TYPE_WORLD_SPAWN; Position spawn = location.getLevel().getSpawnLocation(); pk.x = spawn.getFloorX(); pk.y = spawn.getFloorY(); pk.z = spawn.getFloorZ(); dataPacket(pk); } this.forceMovement = new Vector3(this.x, this.y, this.z); this.sendPosition(this, this.yaw, this.pitch, MovePlayerPacket.MODE_RESET); this.resetFallDistance(); this.orderChunks(); this.nextChunkOrderRun = 0; this.newPosition = null; //Weather this.getLevel().sendWeather(this); //Update time this.getLevel().sendTime(this); } } /** * Creates and sends a BossBar to the player * * @param text The BossBar message * @param length The BossBar percentage * @return bossBarId The BossBar ID, you should store it if you want to remove or update the BossBar later */ /* public long createBossBar(String text, int length) { // First we spawn a entity long bossBarId = 1095216660480L + ThreadLocalRandom.current().nextLong(0, 0x7fffffffL); AddEntityPacket pkAdd = new AddEntityPacket(); pkAdd.type = EntityCreeper.NETWORK_ID; pkAdd.entityUniqueId = bossBarId; pkAdd.entityRuntimeId = bossBarId; pkAdd.x = (float) this.x; pkAdd.y = (float) -10; // Below the bedrock pkAdd.z = (float) this.z; pkAdd.speedX = (float) this.motionX; pkAdd.speedY = (float) this.motionY; pkAdd.speedZ = (float) this.motionZ; EntityMetadata metadata = new EntityMetadata() // Default Metadata tags .putLong(DATA_FLAGS, 0) .putShort(DATA_AIR, 400) .putShort(DATA_MAX_AIR, 400) .putLong(DATA_LEAD_HOLDER_EID, -1) .putFloat(DATA_SCALE, 1f) .putString(Entity.DATA_NAMETAG, text) // Set the entity name .putInt(Entity.DATA_SCALE, 0); // And make it invisible pkAdd.metadata = metadata; this.dataPacket(pkAdd); // Now we send the entity attributes // TODO: Attributes should be sent on AddEntityPacket, however it doesn't work (client bug?) UpdateAttributesPacket pkAttributes = new UpdateAttributesPacket(); pkAttributes.entityRuntimeId = bossBarId; Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH); attr.setMaxValue(100); // Max value - We need to change the max value first, or else the "setValue" will return a IllegalArgumentException attr.setValue(length); // Entity health pkAttributes.entries = new Attribute[] { attr }; this.dataPacket(pkAttributes); // And now we send the bossbar packet BossEventPacket pkBoss = new BossEventPacket(); pkBoss.entityRuntimeId = bossBarId; pkBoss.type = BossEventPacket.ADD; this.dataPacket(pkBoss); return bossBarId; } */ /** * Updates a BossBar * * @param text The new BossBar message * @param length The new BossBar length * @param bossBarId The BossBar ID */ /* public void updateBossBar(String text, int length, long bossBarId) { // First we update the boss bar length UpdateAttributesPacket pkAttributes = new UpdateAttributesPacket(); pkAttributes.entityRuntimeId = bossBarId; Attribute attr = Attribute.getAttribute(Attribute.MAX_HEALTH); attr.setMaxValue(100); // Max value - We need to change the max value first, or else the "setValue" will return a IllegalArgumentException attr.setValue(length); // Entity health pkAttributes.entries = new Attribute[] { attr }; this.dataPacket(pkAttributes); // And then the boss bar text SetEntityDataPacket pkMetadata = new SetEntityDataPacket(); pkMetadata.eid = bossBarId; pkMetadata.metadata = new EntityMetadata() // Default Metadata tags .putLong(DATA_FLAGS, 0) .putShort(DATA_AIR, 400) .putShort(DATA_MAX_AIR, 400) .putLong(DATA_LEAD_HOLDER_EID, -1) .putFloat(DATA_SCALE, 1f) .putString(Entity.DATA_NAMETAG, text) // Set the entity name .putInt(Entity.DATA_SCALE, 0); // And make it invisible this.dataPacket(pkMetadata); // And now we send the bossbar packet BossEventPacket pkBoss = new BossEventPacket(); pkBoss.entityRuntimeId = bossBarId; pkBoss.type = BossEventPacket.UPDATE; this.dataPacket(pkBoss); return; } */ /** * Removes a BossBar * * @param bossBarId The BossBar ID */ public void removeBossBar(long bossBarId) { RemoveEntityPacket pkRemove = new RemoveEntityPacket(); pkRemove.entityRuntimeId = bossBarId; this.dataPacket(pkRemove); } public int getWindowId(Inventory inventory) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } return -1; } public int addWindow(Inventory inventory){ return addWindow(inventory, null); } public int addWindow(Inventory inventory, Integer forceId) { return addWindow(inventory, forceId, false); } public int addWindow(Inventory inventory, Integer forceId, boolean isPermanent) { if (this.windows.containsKey(inventory)) { return this.windows.get(inventory); } int cnt; if (forceId == null) { this.windowCnt = cnt = Math.max(2, ++this.windowCnt % 99); } else { cnt = forceId; } this.windowIndex.put(cnt, inventory); this.windows.put(inventory, cnt); if (isPermanent) { this.permanentWindows.add(cnt); } if (inventory.open(this)) { return cnt; } else { this.removeWindow(inventory); return -1; } } public void removeWindow(Inventory inventory) { inventory.close(this); if (this.windows.containsKey(inventory)) { int id = this.windows.get(inventory); this.windows.remove(this.windowIndex.get(id)); this.windowIndex.remove(id); } } @Override public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { this.server.getPlayerMetadata().setMetadata(this, metadataKey, newMetadataValue); } @Override public List<MetadataValue> getMetadata(String metadataKey) { return this.server.getPlayerMetadata().getMetadata(this, metadataKey); } @Override public boolean hasMetadata(String metadataKey) { return this.server.getPlayerMetadata().hasMetadata(this, metadataKey); } @Override public void removeMetadata(String metadataKey, Plugin owningPlugin) { this.server.getPlayerMetadata().removeMetadata(this, metadataKey, owningPlugin); } @Override public void onChunkChanged(FullChunk chunk) { this.usedChunks.remove(Level.chunkHash(chunk.getX(), chunk.getZ())); } @Override public void onChunkLoaded(FullChunk chunk) { } @Override public void onChunkPopulated(FullChunk chunk) { } @Override public void onChunkUnloaded(FullChunk chunk) { } @Override public void onBlockChanged(Vector3 block) { } @Override public Integer getLoaderId() { return this.loaderId; } @Override public boolean isLoaderActive() { return this.isConnected(); } public static BatchPacket getChunkCacheFromData(int chunkX, int chunkZ, byte[] payload) { FullChunkDataPacket pk = new FullChunkDataPacket(); pk.chunkX = chunkX; pk.chunkZ = chunkZ; pk.data = payload; pk.encode(); BatchPacket batch = new BatchPacket(); byte[][] batchPayload = new byte[2][]; byte[] buf = pk.getBuffer(); batchPayload[0] = Binary.writeUnsignedVarInt(buf.length); batchPayload[1] = buf; byte[] data = Binary.appendBytes(batchPayload); try { batch.payload = Zlib.deflate(data, Server.getInstance().networkCompressionLevel); } catch (Exception e) { throw new RuntimeException(e); } return batch; } private boolean foodEnabled = true; private CraftingGrid craftingGrid; private PlayerCursorInventory cursorInventory; public boolean isFoodEnabled() { return !(this.isCreative() || this.isSpectator()) && this.foodEnabled; } public void setFood(int food){ this.foodData.setLevel(food); } public void setFoodEnabled(boolean foodEnabled) { this.foodEnabled = foodEnabled; } public PlayerFood getFoodData() { return this.foodData; } //todo a lot on dimension public void setDimension(int dimension) { ChangeDimensionPacket pk = new ChangeDimensionPacket(); pk.dimension = getLevel().getDimension(); this.dataPacket(pk); } public void setCheckMovement(boolean checkMovement) { this.checkMovement = checkMovement; } public synchronized void setLocale(Locale locale) { this.locale.set(locale); } public synchronized Locale getLocale() { return this.locale.get(); } public void setSprinting(boolean value, boolean setDefault) { super.setSprinting(value); if (setDefault) { this.movementSpeed = DEFAULT_SPEED; } else { float sprintSpeedChange = DEFAULT_SPEED * 0.3f; if (!value) sprintSpeedChange *= -1; this.movementSpeed += sprintSpeedChange; } this.setMovementSpeed(this.movementSpeed); } /** * プレイヤーをミュート状態にします。 * @param b trueで有効/falseで無効 * @return void * @author Itsu */ public void setMute(boolean b){ this.mute = b; } /** * プレイヤーがミュート状態かどうかを返します。 * @return boolean trueが有効/falseが無効 * @author Itsu */ public boolean isMuted(){ return this.mute; } /** * プレイヤー指定したサーバーに転送します。 * @param ip 転送先サーバーのIPアドレス * @param port 転送先サーバーのポート * @return void * @author Itsu */ public void transfer(String ip, int port){ TransferPacket pk = new TransferPacket(); pk.address = ip; pk.port = port; this.dataPacket(pk); String mes = FastAppender.get("IP: ", ip, " ポート: ", port, "のサーバーに移動しました。"); if(this.server.getJupiterConfigBoolean("transfer-server-message")){ this.server.broadcastMessage(this.getName() + "は別のサーバーへ移動しました。"); } this.close(mes, mes, false); } /** * @deprecated Nukkitとの互換性がないため削除されます。 */ @Deprecated public void transferServer(String ip, int port){ this.transfer(ip, port); } public boolean pickupEntity(Entity entity, boolean near) { if (!this.spawned || !this.isAlive() || !this.isOnline()) { return false; } entity.onCollideWithPlayer(this); int tick = this.getServer().getTick(); if (pickedXPOrb < tick && entity instanceof EntityXPOrb && this.boundingBox.isVectorInside(entity)) { EntityXPOrb xpOrb = (EntityXPOrb) entity; if (xpOrb.getPickupDelay() <= 0) { int exp = xpOrb.getExp(); this.addExperience(exp); entity.kill(); this.getLevel().addSound(new ExperienceOrbSound(this)); pickedXPOrb = tick; return true; } } return false; } @Override public int hashCode() { if ((this.hash == 0) || (this.hash == 485)) { this.hash = (485 + (getUniqueId() != null ? getUniqueId().hashCode() : 0)); } return this.hash; } @Override public boolean equals(Object obj) { if (!(obj instanceof Player)) { return false; } Player other = (Player) obj; return Objects.equals(this.getUniqueId(), other.getUniqueId()) && this.getId() == other.getId(); } /** * Notifies an ACK response from the client * * @param identification */ public void notifyACK(int identification) { needACK.put(identification, true); } public void excuteData() throws IOException{ JsonObject main = new JsonObject(); main.addProperty("Name: ", this.getName()); main.addProperty("X: ", this.getX()); main.addProperty("Y: ", this.getY()); main.addProperty("Z: ", this.getZ()); List<Item> item = new ArrayList<>(); for(int i=0;i < this.getInventory().getContents().size();i++){ item.add(this.getInventory().getContents().get(i)); } int count = 1; for(Item i : item){ main.addProperty("Inventory[" + count + "]: ", i.getName() + "[" + i.getCount() + "]"); count++; } String src = new Gson().toJson(main); Utils.writeFile("./players/JsonDatas/" + this.getName() + ".json", src); return; } protected void forceSendEmptyChunks() { int chunkPositionX = this.getFloorX() >> 4; int chunkPositionZ = this.getFloorZ() >> 4; for (int x = -3; x < 3; x++) { for (int z = -3; z < 3; z++) { FullChunkDataPacket chunk = new FullChunkDataPacket(); chunk.chunkX = chunkPositionX + x; chunk.chunkZ = chunkPositionZ + z; chunk.data = new byte[0]; this.dataPacket(chunk); } } } public boolean dropItem(Item item) { if (!this.spawned || !this.isAlive()) { return false; } if (item.isNull()) { this.server.getLogger().debug(this.getName() + " attempted to drop a null item (" + item + ")"); return true; } Vector3 motion = this.getDirectionVector().multiply(0.4); this.level.dropItem(this.add(0, 1.3, 0), item, motion, 40); this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, false); return true; } public void sendAllInventories() { for (Inventory inv : this.windowIndex.values()) { inv.sendContents(this); if (inv instanceof PlayerInventory) { ((PlayerInventory) inv).sendArmorContents(this); } } } protected void addDefaultWindows() { this.addWindow(this.getInventory(), ContainerIds.INVENTORY, true); this.cursorInventory = new PlayerCursorInventory(this); this.addWindow(this.cursorInventory, ContainerIds.CURSOR, true); this.addWindow(this.offhandInventory, ContainerIds.OFFHAND, true); this.craftingGrid = new CraftingGrid(this); //TODO: more windows } public PlayerCursorInventory getCursorInventory() { return this.cursorInventory; } public CraftingGrid getCraftingGrid() { return this.craftingGrid; } public void setCraftingGrid(CraftingGrid grid) { this.craftingGrid = grid; } public void resetCraftingGridType() { if (this.craftingGrid instanceof BigCraftingGrid) { Item[] drops = this.inventory.addItem(this.craftingGrid.getContents().values().stream().toArray(Item[]::new)); for (Item drop : drops) { this.dropItem(drop); } this.craftingGrid = new CraftingGrid(this); this.craftingType = 0; } } public void removeAllWindows() { removeAllWindows(false); } public void removeAllWindows(boolean permanent) { for (Entry<Integer, Inventory> entry : new ArrayList<>(this.windowIndex.entrySet())) { if (!permanent && this.permanentWindows.contains((int) entry.getKey())) { continue; } this.removeWindow(entry.getValue()); } } public boolean isUsingItem(){ return this.getDataFlag(DATA_FLAGS, DATA_FLAG_ACTION) && this.startAction > 1; } public void setUsingItem(boolean value) { this.startAction = value ? this.server.getTick() : -1; this.setDataFlag(DATA_FLAGS, DATA_FLAG_ACTION, value); } /** * フォームウィンドウをプレイヤーに送信します。 * @param window FormWindow * @return void */ public void sendWindow(FormWindow window){ ModalFormRequestPacket pk = new ModalFormRequestPacket(); pk.data = window.toJson(); pk.formId = window.getId(); this.activeWindow = window; this.dataPacket(pk); } public int addServerSettings(ServerSettingsWindow window) { this.serverSettings.put(window.getId(), window); return window.getId(); } public boolean isBreakingBlock() { return this.breakingBlock != null; } public void showXboxProfile() { ShowProfilePacket pk = new ShowProfilePacket(); pk.xuid = getLoginChainData().getXUID(); this.dataPacket(pk); } /** * プレイヤーのスポーン地点からの距離を取得します。 * @return double */ public double getPlaneDistanceFromSpawn(){ return this.distance(this.level.getSafeSpawn()); } public BeaconInventory getBeacoInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof BeaconInventory) { return (BeaconInventory) inventory; } } return null; } public EnchantInventory getEnchantInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof EnchantInventory) { return (EnchantInventory) inventory; } } return null; } public AnvilInventory getAnvilInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof AnvilInventory) { return (AnvilInventory) inventory; } } return null; } public TradingInventory getTradingInventory() { for (Inventory inventory : this.windows.keySet()) { if (inventory instanceof TradingInventory) { return (TradingInventory) inventory; } } return null; } }
gpl-3.0
kazoompa/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/FileSelectorPresenter.java
10008
/* * Copyright (c) 2021 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.opal.web.gwt.app.client.fs.presenter; import java.util.List; import javax.annotation.Nullable; import org.obiba.opal.web.gwt.app.client.event.NotificationEvent; import org.obiba.opal.web.gwt.app.client.fs.FileDtos; import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FileSelectionRequestEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FilesCheckedEvent; import org.obiba.opal.web.gwt.app.client.fs.event.FolderCreatedEvent; import org.obiba.opal.web.gwt.app.client.fs.service.FileService; import org.obiba.opal.web.gwt.app.client.i18n.TranslationMessages; import org.obiba.opal.web.gwt.app.client.i18n.Translations; import org.obiba.opal.web.gwt.app.client.presenter.ModalPresenterWidget; import org.obiba.opal.web.gwt.app.client.presenter.ModalProvider; import org.obiba.opal.web.gwt.app.client.presenter.SplitPaneWorkbenchPresenter; import org.obiba.opal.web.gwt.rest.client.RequestCredentials; import org.obiba.opal.web.gwt.rest.client.ResourceCallback; import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory; import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback; import org.obiba.opal.web.model.client.opal.FileDto; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.ui.HasText; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.PopupView; import com.gwtplatform.mvp.client.PresenterWidget; public class FileSelectorPresenter extends ModalPresenterWidget<FileSelectorPresenter.Display> implements FileSelectorUiHandlers { private final RequestCredentials credentials; private final FilePathPresenter filePathPresenter; private final FilePlacesPresenter filePlacesPresenter; private final FolderDetailsPresenter folderDetailsPresenter; private final ModalProvider<FileUploadModalPresenter> fileUploadModalProvider; private final Translations translations; private final TranslationMessages translationMessages; private final FileService fileService; private Object fileSelectionSource; private FileSelectionType fileSelectionType = FileSelectionType.FILE; private List<FileDto> checkedFiles; @Inject public FileSelectorPresenter(Display display, EventBus eventBus, FilePathPresenter filePathPresenter, FilePlacesPresenter filePlacesPresenter, FolderDetailsPresenter folderDetailsPresenter, ModalProvider<FileUploadModalPresenter> fileUploadModalProvider, RequestCredentials credentials, Translations translations, TranslationMessages translationMessages, FileService fileService) { super(eventBus, display); this.filePathPresenter = filePathPresenter; this.filePlacesPresenter = filePlacesPresenter; this.folderDetailsPresenter = folderDetailsPresenter; this.fileUploadModalProvider = fileUploadModalProvider.setContainer(this); this.credentials = credentials; this.translations = translations; this.translationMessages = translationMessages; this.fileService = fileService; getView().setUiHandlers(this); } public void handle(FileSelectionRequestEvent event) { setFileSelectionSource(event.getSource()); setFileSelectionType(event.getFileSelectionType()); showProject(event.getProject()); } public void showProject(String project) { filePlacesPresenter.showProject(project); } public FileDto getCurrentFolder() { return folderDetailsPresenter.getCurrentFolder(); } public List<FileDto> getCheckedFiles() { return checkedFiles; } public FileDto getSelectedFile() { return checkedFiles == null || getCheckedFiles().isEmpty() ? null : getCheckedFiles().get(0); } public void clearSelection() { checkedFiles = null; folderDetailsPresenter.getView().clearSelection(); } @Override protected void onBind() { super.onBind(); for(SplitPaneWorkbenchPresenter.Slot slot : SplitPaneWorkbenchPresenter.Slot.values()) { setInSlot(slot, getDefaultPresenter(slot)); } addRegisteredHandler(FilesCheckedEvent.getType(), new FilesCheckedEvent.FilesCheckedHandler() { @Override public void onFilesChecked(FilesCheckedEvent event) { checkedFiles = event.getCheckedFiles(); } }); folderDetailsPresenter.setSingleSelectionModel(true); } protected PresenterWidget<?> getDefaultPresenter(SplitPaneWorkbenchPresenter.Slot slot) { switch(slot) { case TOP: return filePathPresenter; case CENTER: return folderDetailsPresenter; case LEFT: return filePlacesPresenter; default: return null; } } private void setDisplaysFiles(boolean displaysFiles) { folderDetailsPresenter.getView().setDisplaysFiles(displaysFiles); } @Override public void onReveal() { // Clear previous state. clearSelection(); // clear previous selection (highlighted row) getView().clearNewFolderName(); // clear previous new folder name // Adjust display based on file selection type. setDisplaysFiles(displaysFiles()); FileDto lastFolder = fileService.getLastFolderDto(); folderDetailsPresenter.setCurrentFolder(lastFolder == null ? FileDtos.user(credentials.getUsername()) : lastFolder); } public void setFileSelectionSource(Object fileSelectionSource) { this.fileSelectionSource = fileSelectionSource; } public void setFileSelectionType(FileSelectionType fileSelectionType) { this.fileSelectionType = fileSelectionType; } public boolean displaysFiles() { return fileSelectionType == FileSelectionType.FILE || fileSelectionType == FileSelectionType.FILE_OR_FOLDER; } private void createFolder(String destination, String folder) { ResourceCallback<FileDto> createdCallback = new ResourceCallback<FileDto>() { @Override public void onResource(Response response, FileDto resource) { fireEvent(new FolderCreatedEvent(resource)); getView().clearNewFolderName(); } }; ResponseCodeCallback callbackHandler = new ResponseCodeCallback() { @Override public void onResponseCode(Request request, Response response) { fireEvent(NotificationEvent.newBuilder().error(response.getText()).build()); } }; ResourceRequestBuilderFactory.<FileDto>newBuilder().forResource("/files" + destination).post() .withBody("text/plain", folder).withCallback(createdCallback) .withCallback(Response.SC_FORBIDDEN, callbackHandler) .withCallback(Response.SC_INTERNAL_SERVER_ERROR, callbackHandler).send(); } @Nullable public FileSelection getSelection() { FileDto selectedFile = getSelectedFile(); if(selectedFile == null) { if (fileSelectionType == FileSelectionType.FOLDER) { selectedFile = getCurrentFolder(); return new FileSelection(selectedFile.getPath(), fileSelectionType); } return null; } if(fileSelectionType == FileSelectionType.FILE_OR_FOLDER) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } if(FileDtos.isFile(selectedFile) && fileSelectionType == FileSelectionType.FILE) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } if(FileDtos.isFolder(selectedFile) && fileSelectionType == FileSelectionType.FOLDER) { return new FileSelection(selectedFile.getPath(), fileSelectionType); } return null; } @Override public void onUploadFile() { FileUploadModalPresenter fileUploadModalPresenter = fileUploadModalProvider.get(); fileUploadModalPresenter.setCurrentFolder(folderDetailsPresenter.getCurrentFolder()); fileUploadModalProvider.show(); } @Override public void onSelect() { FileSelection selection = getSelection(); if(selection == null) { getView().clearErrors(); getView().showError(getNoSelectionErrorMessage()); } else { fireEvent(new FileSelectionEvent(fileSelectionSource, selection)); getView().hideDialog(); } } @Override public void onCancel() { getView().hideDialog(); } @Override public void onCreateFolder() { String newFolder = getView().getCreateFolderName().getText().trim(); FileDto currentFolder = getCurrentFolder(); if(currentFolder != null && !newFolder.isEmpty()) { createFolder(currentFolder.getPath(), newFolder); } } public String getNoSelectionErrorMessage() { if(folderDetailsPresenter.isSingleSelectionModel()) { return translationMessages.mustSelectFileFolder(translations.fileFolderTypeMap().get(fileSelectionType.name())); } return translationMessages .mustSelectAtLeastFileFolder(translations.fileFolderTypeMap().get(fileSelectionType.name())); } public enum FileSelectionType { FILE, FOLDER, FILE_OR_FOLDER } public interface Display extends PopupView, HasUiHandlers<FileSelectorUiHandlers> { void hideDialog(); HasText getCreateFolderName(); void clearNewFolderName(); void clearErrors(); void showError(String errorMessage); } public static class FileSelection { private final String selectionPath; private final FileSelectionType selectionType; public FileSelection(String selectionPath, FileSelectionType selectionType) { this.selectionPath = selectionPath; this.selectionType = selectionType; } public String getSelectionPath() { return selectionPath; } public FileSelectionType getSelectionType() { return selectionType; } } }
gpl-3.0
seapub/SourceCode
Java/corejava9/v1ch14/synch/Bank.java
2014
package synch; import java.util.concurrent.locks.*; /** * A bank with a number of bank accounts that uses locks for serializing access. * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; /** * Constructs the bank. * @param n the number of accounts * @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); } /** * Transfers money from one account to another. * @param from the account to transfer from * @param to the account to transfer to * @param amount the amount to transfer */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } } /** * Gets the sum of all account balances. * @return the total balance */ public double getTotalBalance() { bankLock.lock(); try { double sum = 0; for (double a : accounts) sum += a; return sum; } finally { bankLock.unlock(); } } /** * Gets the number of accounts in the bank. * @return the number of accounts */ public int size() { return accounts.length; } }
gpl-3.0
mchaffotte/geo-application
geobase-quarkus/src/test/java/fr/chaffotm/geobase/assertion/ListParameterizedType.java
619
package fr.chaffotm.geobase.assertion; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; public class ListParameterizedType implements ParameterizedType { private final Class resourceClass; ListParameterizedType(Class resourceClass) { this.resourceClass = resourceClass; } @Override public Type[] getActualTypeArguments() { return new Type[] { resourceClass }; } @Override public Type getRawType() { return List.class; } @Override public Type getOwnerType() { return List.class; } }
gpl-3.0
andforce/iBeebo
app/src/main/java/org/zarroboogs/weibo/hot/bean/hotweibo/HotWeibo.java
1329
package org.zarroboogs.weibo.hot.bean.hotweibo; import org.json.*; import java.util.ArrayList; public class HotWeibo { private CardlistInfo cardlistInfo; private ArrayList<Cards> cards; public HotWeibo() { } public HotWeibo(JSONObject json) { this.cardlistInfo = new CardlistInfo(json.optJSONObject("cardlistInfo")); this.cards = new ArrayList<Cards>(); JSONArray arrayCards = json.optJSONArray("cards"); if (null != arrayCards) { int cardsLength = arrayCards.length(); for (int i = 0; i < cardsLength; i++) { JSONObject item = arrayCards.optJSONObject(i); if (null != item) { this.cards.add(new Cards(item)); } } } else { JSONObject item = json.optJSONObject("cards"); if (null != item) { this.cards.add(new Cards(item)); } } } public CardlistInfo getCardlistInfo() { return this.cardlistInfo; } public void setCardlistInfo(CardlistInfo cardlistInfo) { this.cardlistInfo = cardlistInfo; } public ArrayList<Cards> getCards() { return this.cards; } public void setCards(ArrayList<Cards> cards) { this.cards = cards; } }
gpl-3.0
ufoe/Deskera-CRM
core-components/common/src/main/java/com/krawler/spring/storageHandler/storageHandlerImpl.java
2255
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * 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 com.krawler.spring.storageHandler; import com.krawler.esp.utils.ConfigReader; /** * * @author Karthik */ public class storageHandlerImpl { public static String GetServerTimezone() { return ConfigReader.getinstance().get("SERVER_TIMEZONE"); } public static String GetProfileImgStorePath() { return ConfigReader.getinstance().get("ProfileImagePathBase"); } public static String GetSOAPServerUrl() { return ConfigReader.getinstance().get("soap_server_url"); } public static String GetAuditTrailIndexPath() { return ConfigReader.getinstance().get("audittrailindex"); } public static String GetDocIndexPath() { return ConfigReader.getinstance().get("audittraildocindex"); } public static String GetDocStorePath() { return ConfigReader.getinstance().get("DocStorePath0"); } public static String GetEmailUploadFilePath() { return ConfigReader.getinstance().get("EmailUploadFile"); } public static String GetSummaryContext(String defaultContext) { return defaultContext; } public static String GetSummaryLength(String defaultLength) { return defaultLength; } public static String GetRemoteAPIKey() { return ConfigReader.getinstance().get("remoteapikey"); } public static String GetNewsLetterAddress() { return ConfigReader.getinstance().get("NewsLetterAddress"); } }
gpl-3.0
gstreamer-java/gir2java
generated-src/generated/glib20/glib/GAsyncQueue.java
7257
package generated.glib20.glib; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Library; import org.bridj.ann.Ptr; @Library("glib-2.0") public class GAsyncQueue extends StructObject { static { BridJ.register(); } public GAsyncQueue() { super(); } public GAsyncQueue(Pointer pointer) { super(pointer); } protected native int g_async_queue_length( @Ptr long queue); public int length() { return this.g_async_queue_length(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native int g_async_queue_length_unlocked( @Ptr long queue); public int length_unlocked() { return this.g_async_queue_length_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_lock( @Ptr long queue); public void lock() { this.g_async_queue_lock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_pop( @Ptr long queue); public Pointer pop() { return Pointer.pointerToAddress(this.g_async_queue_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_pop_unlocked( @Ptr long queue); public Pointer pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_push( @Ptr long queue, @Ptr long data); public void push(Pointer data) { this.g_async_queue_push(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } protected native void g_async_queue_push_unlocked( @Ptr long queue, @Ptr long data); public void push_unlocked(Pointer data) { this.g_async_queue_push_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } @Ptr protected native long g_async_queue_ref( @Ptr long queue); public Pointer ref() { return Pointer.pointerToAddress(this.g_async_queue_ref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_ref_unlocked( @Ptr long queue); public void ref_unlocked() { this.g_async_queue_ref_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_timed_pop( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timed_pop_unlocked( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop_unlocked(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timeout_pop( @Ptr long queue, long timeout); public Pointer timeout_pop(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_timeout_pop_unlocked( @Ptr long queue, long timeout); public Pointer timeout_pop_unlocked(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_try_pop( @Ptr long queue); public Pointer try_pop() { return Pointer.pointerToAddress(this.g_async_queue_try_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_try_pop_unlocked( @Ptr long queue); public Pointer try_pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_try_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_unlock( @Ptr long queue); public void unlock() { this.g_async_queue_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref( @Ptr long queue); public void unref() { this.g_async_queue_unref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref_and_unlock( @Ptr long queue); public void unref_and_unlock() { this.g_async_queue_unref_and_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected static native long g_async_queue_new(); public static Pointer _new() { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new()); } @Ptr protected static native long g_async_queue_new_full( @Ptr long item_free_func); public static Pointer<GAsyncQueue> new_full(Pointer item_free_func) { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new_full(Pointer.getPeer(item_free_func)), GAsyncQueue.class); } protected native void g_async_queue_push_sorted( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_push_sorted_unlocked( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted_unlocked(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort_unlocked( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort_unlocked(Pointer func, Pointer user_data) { this.g_async_queue_sort_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort(Pointer func, Pointer user_data) { this.g_async_queue_sort(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } }
gpl-3.0
NovaViper/TetraCraft
src-1.9.4/main/java/com/novaviper/tetracraft/common/init/ModItems.java
1268
package com.novaviper.tetracraft.common.init; import net.minecraft.item.Item; import com.novaviper.cryolib.lib.Registers; import com.novaviper.tetracraft.common.item.ItemContinousBow; import com.novaviper.tetracraft.common.item.ItemModGenericItem; import com.novaviper.tetracraft.lib.ModReference; /** * @author NovaViper <nova.gamez15@gmail.com> * @date 7/10/2016 * @purpose Main class for defining and loading all items */ public class ModItems { public static Item ballisticBow; public static Item triaxIngot; public static Item breedingBone; public static void load(){ ballisticBow = Registers.addItem(new ItemContinousBow("ballisticBow", ModCreativeTabs.tetraTab, "ballistic", 500, 10)); triaxIngot = Registers.addItem(new ItemModGenericItem("triaxIngot", ModCreativeTabs.tetraTab)); breedingBone = Registers.addItem(new ItemModGenericItem("breedingBone", ModCreativeTabs.tetraTab)); } public static void loadRenderersAndVariants(){ addItemRender(ballisticBow, 0, "ballisticBow"); addItemRender(triaxIngot, 0, "triaxIngot"); addItemRender(breedingBone, 0, "breedingBone"); } public static void addItemRender(Item item, int metadata, String itemString){ Registers.addItemRender(ModReference.MOD_ID, item, metadata, itemString); } }
gpl-3.0
rranz/meccano4j_vaadin
javalego/javalego-app-erp-model/src/main/java/com/javalego/erp/model/editors/EditorEmpleados.java
7451
package com.javalego.erp.model.editors; import java.util.Collection; import java.util.List; import com.javalego.erp.model.Icons; import com.javalego.erp.model.Texts; import com.javalego.erp.model.entity.CategoriaProfesional; import com.javalego.erp.model.entity.Departamento; import com.javalego.erp.model.entity.Empleado; import com.javalego.erp.model.entity.Empresa; import com.javalego.exception.LocalizedException; import com.javalego.security.annotation.PermitAll; import com.javalego.ui.UIContext; import com.javalego.ui.condition.ConditionType; import com.javalego.ui.field.impl.DateFieldModel; import com.javalego.ui.field.impl.EmailFieldModel; import com.javalego.ui.field.impl.ImageFieldModel; import com.javalego.ui.field.impl.PhoneNumberFieldModel; import com.javalego.ui.field.impl.TextFieldModel; import com.javalego.ui.filter.impl.FilterParam; import com.javalego.ui.filter.impl.FilterParamsService; import com.javalego.ui.mvp.beans.view.list.adapter.ListBeansViewAdapter; import com.javalego.ui.mvp.editor.rules.IEditionRulesListener.ValueChangeEvent; import com.javalego.ui.mvp.nestedbean.imp.NestedBeanListValues; import com.javalego.util.StringUtils; /** * Formulario de mantenimiento de Tarifas de Productos * * @author ROBERTO RANZ * */ @PermitAll public class EditorEmpleados extends BaseEditor<Empleado> { private static final long serialVersionUID = -8571636754447755369L; /** * Constructor para inicializar modelo. */ public EditorEmpleados() { setTitle(Texts.EMPLEADOS); setIcon(Icons.PEOPLE); setEditionTitle(Texts.EMPLEADO); // Campos addFieldModel(new TextFieldModel(EMPRESA_NOMBRE, Texts.EMPRESA, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(DEPARTAMENTO_NOMBRE, Texts.DEPARTAMENTO, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(CATEGORIA_NOMBRE, Texts.CATEGORIA, true).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(NOMBRE, Texts.NOMBRE).setColumns(30).setRequired(true)); addFieldModel(new TextFieldModel(NIF, Texts.NIF).setMaxSize(20)); addFieldModel(new DateFieldModel(ALTA, Texts.FECHA_ALTA).setReadOnly(true)); addFieldModel(new PhoneNumberFieldModel(TELEFONO, Texts.TELEFONO).setMaxSize(15)); addFieldModel(new PhoneNumberFieldModel(MOVIL, Texts.MOVIL).setMaxSize(15)); addFieldModel(new EmailFieldModel(EMAIL, Texts.EMAIL).setMaxSize(130).setColumns(40)); addFieldModel(new TextFieldModel(DOMICILIO, Texts.DIRECCION)); addFieldModel(new ImageFieldModel(FOTO, Texts.FOTO)); // Filtros basado en campos del editor. Se crea el presenter para la // edición de los campos que constituyen los parámetros del filtro addFilterService(new FilterParamsService(Texts.NOMBRE, new FilterParam(NOMBRE, Texts.NOMBRE, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.DIRECCION, new FilterParam(DOMICILIO, Texts.DIRECCION, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.NIF, new FilterParam(NIF, Texts.NIF, ConditionType.CONTAINS))); addFilterService(new FilterParamsService(Texts.EMAIL, new FilterParam(EMAIL, Texts.EMAIL, ConditionType.CONTAINS))); // Servicios del editor para beans nested relacionados. EditorServices<Empleado> services = new EditorServices<Empleado>(); setEditorServices(services); services.addNestedFieldModel(DEPARTAMENTO_NOMBRE, new NestedBeanListValues<Empleado, Departamento>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { Departamento e = (Departamento) getDataProvider().find(Departamento.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(DEPARTAMENTO_ID, e.getId()); } else { event.getEditorRules().setValue(DEPARTAMENTO_ID, null); event.getEditorRules().setValue(DEPARTAMENTO_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(Departamento.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); services.addNestedFieldModel(CATEGORIA_NOMBRE, new NestedBeanListValues<Empleado, CategoriaProfesional>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { CategoriaProfesional e = (CategoriaProfesional) getDataProvider().find(CategoriaProfesional.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(CATEGORIA_ID, e.getId()); } else { event.getEditorRules().setValue(CATEGORIA_ID, null); event.getEditorRules().setValue(CATEGORIA_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(CategoriaProfesional.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); services.addNestedFieldModel(EMPRESA_NOMBRE, new NestedBeanListValues<Empleado, Empresa>() { @Override public void valueChangeEvent(ValueChangeEvent event) throws LocalizedException { if (getDataProvider() != null) { Empresa e = (Empresa) getDataProvider().find(Empresa.class, "nombre = '" + event.getValue() + "'"); if (e != null) { event.getEditorRules().setValue(EMPRESA_ID, e.getId()); } else { event.getEditorRules().setValue(EMPRESA_ID, null); event.getEditorRules().setValue(EMPRESA_NOMBRE, null); } } } @SuppressWarnings("unchecked") @Override public Collection<String> getKeys(String constraint) throws LocalizedException { return getDataProvider() == null ? null : (Collection<String>) getDataProvider().propertyValues(Empresa.class, NOMBRE, constraint != null ? "nombre like'" + constraint + "%'" : null, NOMBRE); } @Override public boolean isAutoComplete() { return false; } }); // Vistas de datos del bean addFormatView(new ListBeansViewAdapter<Empleado>(UIContext.getText(Texts.NOMBRE) + " + " + UIContext.getText(Texts.DEPARTAMENTO), FOTO) { @Override public String toHtml(Empleado bean) { return "<h2>" + bean.getNombre() + "</h2>" + (bean.getDepartamento() != null ? bean.getDepartamento().getNombre() : "") + "<br>" + (bean.getEmpresa() != null ? bean.getEmpresa().getNombre() : ""); } }); } @Override public Collection<Empleado> getBeans(String filter, String order) throws LocalizedException { Collection<Empleado> list = getDataServices().getEmpleados(filter, order); if (order != null && list != null && list.size() > 1) { StringUtils.sortList((List<?>) list, NOMBRE); } return list; } @Override public Class<Empleado> getBeanClass() { return Empleado.class; } }
gpl-3.0
Raphcal/sigmah
src/main/java/org/sigmah/offline/js/LayoutJS.java
3072
package org.sigmah.offline.js; /* * #%L * Sigmah * %% * Copyright (C) 2010 - 2016 URD * %% * 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/gpl-3.0.html>. * #L% */ import java.util.ArrayList; import java.util.List; import org.sigmah.shared.dto.layout.LayoutDTO; import org.sigmah.shared.dto.layout.LayoutGroupDTO; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; /** * * @author Raphaël Calabro (rcalabro@ideia.fr) */ public final class LayoutJS extends JavaScriptObject { protected LayoutJS() { } public static LayoutJS toJavaScript(LayoutDTO layoutDTO) { final LayoutJS layoutJS = (LayoutJS)JavaScriptObject.createObject(); layoutJS.setId(layoutDTO.getId()); layoutJS.setRowsCount(layoutDTO.getRowsCount()); layoutJS.setColumnsCount(layoutDTO.getColumnsCount()); layoutJS.setGroups(layoutDTO.getGroups()); return layoutJS; } public LayoutDTO toDTO() { final LayoutDTO layoutDTO = new LayoutDTO(); layoutDTO.setId(getId()); layoutDTO.setRowsCount(getRowsCount()); layoutDTO.setColumnsCount(getColumnsCount()); final JsArray<LayoutGroupJS> layoutGroups = getGroups(); if(layoutGroups != null) { final ArrayList<LayoutGroupDTO> list = new ArrayList<LayoutGroupDTO>(); final int length = layoutGroups.length(); for(int index = 0; index < length; index++) { list.add(layoutGroups.get(index).toDTO()); } layoutDTO.setGroups(list); } return layoutDTO; } public native int getId() /*-{ return this.id; }-*/; public native void setId(int id) /*-{ this.id = id; }-*/; public native int getRowsCount() /*-{ return this.rowsCount; }-*/; public native void setRowsCount(int rowsCount) /*-{ this.rowsCount = rowsCount; }-*/; public native int getColumnsCount() /*-{ return this.columnsCount; }-*/; public native void setColumnsCount(int columnsCount) /*-{ this.columnsCount = columnsCount; }-*/; public native JsArray<LayoutGroupJS> getGroups() /*-{ return this.groups; }-*/; public void setGroups(List<LayoutGroupDTO> groups) { if(groups != null) { final JsArray<LayoutGroupJS> array = (JsArray<LayoutGroupJS>) JavaScriptObject.createArray(); for(final LayoutGroupDTO layoutGroupDTO : groups) { array.push(LayoutGroupJS.toJavaScript(layoutGroupDTO)); } setGroups(array); } } public native void setGroups(JsArray<LayoutGroupJS> groups) /*-{ this.groups = groups; }-*/; }
gpl-3.0
arraydev/snap-engine
snap-binning/src/test/java/org/esa/snap/binning/operator/metadata/GlobalMetadataTest.java
15038
package org.esa.snap.binning.operator.metadata; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import org.esa.snap.binning.AggregatorConfig; import org.esa.snap.binning.aggregators.AggregatorAverage; import org.esa.snap.binning.aggregators.AggregatorOnMaxSet; import org.esa.snap.binning.operator.BinningConfig; import org.esa.snap.binning.operator.BinningOp; import org.esa.snap.binning.operator.VariableConfig; import org.esa.snap.framework.datamodel.MetadataAttribute; import org.esa.snap.framework.datamodel.MetadataElement; import org.esa.snap.util.io.FileUtils; import org.junit.Test; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.SortedMap; import java.util.logging.Logger; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class GlobalMetadataTest { private static final String TEST_DIR = "test_dir"; private static final String TEST_PROPERTIES = "param_a = aaaaa\n" + "param_b = bbbb\n" + "param_c = CCCC"; @Test public void testCreate_fromBinningOp() throws ParseException { final BinningOp binningOp = createBinningOp(); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("org.esa.snap.binning.operator.BinningOp", metaProperties.get("software_qualified_name")); assertEquals("Binning", metaProperties.get("software_name")); assertEquals("1.0", metaProperties.get("software_version")); assertEquals(FileUtils.getFilenameWithoutExtension("output.file"), metaProperties.get("product_name")); //assertNotNull(metaProperties.get("processing_time")); assertEquals("2013-05-01", metaProperties.get("aggregation_period_start")); assertEquals("15.56 day(s)", metaProperties.get("aggregation_period_duration")); assertEquals("POLYGON ((10 10, 15 10, 15 12, 10 12, 10 10))", metaProperties.get("region")); assertEquals("8192", metaProperties.get("num_rows")); assertEquals("2.446286592055973", metaProperties.get("pixel_size_in_km")); assertEquals("3", metaProperties.get("super_sampling")); assertEquals("a_mask_expression", metaProperties.get("mask_expression")); } @Test public void testCreate_fromConfig() { final BinningConfig config = new BinningConfig(); config.setNumRows(12); config.setSuperSampling(13); config.setMaskExpr("14"); config.setVariableConfigs(new VariableConfig("var_name", "var_expr")); config.setAggregatorConfigs(new AggregatorAverage.Config("variable", "target", 2.076, false, true)); // @todo 3 tb/** add check for PostProcessorConfig 2014-10-17 config.setMinDataHour(15.0); config.setTimeFilterMethod(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY); config.setMetadataAggregatorName("NAME"); config.setStartDateTime("here_we_go"); config.setPeriodDuration(15.88); final GlobalMetadata metadata = GlobalMetadata.create(config); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("12", metaProperties.get("num_rows")); assertEquals("13", metaProperties.get("super_sampling")); assertEquals("14", metaProperties.get("mask_expression")); assertEquals("var_name", metaProperties.get("variable_config.0:name")); assertEquals("var_expr", metaProperties.get("variable_config.0:expr")); assertEquals("AVG", metaProperties.get("aggregator_config.0:type")); assertEquals("false", metaProperties.get("aggregator_config.0:outputCounts")); assertEquals("true", metaProperties.get("aggregator_config.0:outputSums")); assertEquals("target", metaProperties.get("aggregator_config.0:targetName")); assertEquals("variable", metaProperties.get("aggregator_config.0:varName")); assertEquals("2.076", metaProperties.get("aggregator_config.0:weightCoeff")); assertEquals("15.0", metaProperties.get("min_data_hour")); assertEquals("SPATIOTEMPORAL_DATA_DAY", metaProperties.get("time_filter_method")); assertEquals("NAME", metaProperties.get("metadata_aggregator_name")); assertEquals("here_we_go", metaProperties.get("aggregation_period_start")); assertEquals("15.88 day(s)", metaProperties.get("aggregation_period_duration")); } @Test public void testCreateFromConfig_noParametersSet() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertNull(metaProperties.get("product_name")); //assertNotNull(metaProperties.get("processing_time")); assertNull(metaProperties.get("aggregation_period_start")); assertNull(metaProperties.get("aggregation_period_duration")); assertNull(metaProperties.get("region")); assertNull(metaProperties.get("num_rows")); assertNull(metaProperties.get("pixel_size_in_km")); assertNull(metaProperties.get("super_sampling")); assertEquals("", metaProperties.get("mask_expression")); assertNull(metaProperties.get("variable_config.0:name")); } @Test public void testCreate_timeFilerMethod_timeRange() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); binningConfig.setTimeFilterMethod(BinningOp.TimeFilterMethod.TIME_RANGE); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("TIME_RANGE", metaProperties.get("time_filter_method")); assertNull(metaProperties.get("min_data_hour")); } @Test public void testCreate_timeFilterMethod_spatioTemporalDay() throws ParseException { final BinningConfig binningConfig = new BinningConfig(); binningConfig.setTimeFilterMethod(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY); binningConfig.setMinDataHour(0.8876); final GlobalMetadata metadata = GlobalMetadata.create(binningConfig); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("SPATIOTEMPORAL_DATA_DAY", metaProperties.get("time_filter_method")); assertEquals("0.8876", metaProperties.get("min_data_hour")); } @Test public void testCreate_variableConfigs() { final VariableConfig[] variableConfigs = new VariableConfig[2]; variableConfigs[0] = new VariableConfig("first", "one and one"); variableConfigs[1] = new VariableConfig("second", "is two"); final BinningOp binningOp = new BinningOp(); binningOp.setVariableConfigs(variableConfigs); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("first", metaProperties.get("variable_config.0:name")); assertEquals("one and one", metaProperties.get("variable_config.0:expr")); assertEquals("second", metaProperties.get("variable_config.1:name")); assertEquals("is two", metaProperties.get("variable_config.1:expr")); } @Test public void testCreate_aggregatorConfigs() { final AggregatorConfig[] aggregatorConfigs = new AggregatorConfig[2]; aggregatorConfigs[0] = new AggregatorAverage.Config("variable_1", "the target", 1.087, true, false); aggregatorConfigs[1] = new AggregatorOnMaxSet.Config("variable_2", "another one", "set_1", "set_2"); final BinningOp binningOp = new BinningOp(); binningOp.setAggregatorConfigs(aggregatorConfigs); final GlobalMetadata metadata = GlobalMetadata.create(binningOp); assertNotNull(metadata); final SortedMap<String, String> metaProperties = metadata.asSortedMap(); assertNotNull(metaProperties); assertEquals("AVG", metaProperties.get("aggregator_config.0:type")); assertEquals("true", metaProperties.get("aggregator_config.0:outputCounts")); assertEquals("false", metaProperties.get("aggregator_config.0:outputSums")); assertEquals("the target", metaProperties.get("aggregator_config.0:targetName")); assertEquals("variable_1", metaProperties.get("aggregator_config.0:varName")); assertEquals("1.087", metaProperties.get("aggregator_config.0:weightCoeff")); assertEquals("ON_MAX_SET", metaProperties.get("aggregator_config.1:type")); assertEquals("another one", metaProperties.get("aggregator_config.1:onMaxVarName")); assertEquals("set_1,set_2", metaProperties.get("aggregator_config.1:setVarNames")); assertEquals("variable_2", metaProperties.get("aggregator_config.1:targetName")); } @Test public void testLoad_fileIsNull() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); globalMetadata.load(null, logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertNotNull(metaProperties); assertEquals(0, metaProperties.size()); verifyNoMoreInteractions(logger); } @Test public void testLoad_fileDoesNotExist() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); globalMetadata.load(new File("over_the_rain.bow"), logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertNotNull(metaProperties); assertEquals(0, metaProperties.size()); verify(logger, times(1)).warning("Metadata properties file 'over_the_rain.bow' not found"); verifyNoMoreInteractions(logger); } @Test public void testLoad() throws IOException { final Logger logger = mock(Logger.class); final GlobalMetadata globalMetadata = new GlobalMetadata(); try { final File propertiesFile = writePropertiesFile(); globalMetadata.load(propertiesFile, logger); final SortedMap<String, String> metaProperties = globalMetadata.asSortedMap(); assertEquals("aaaaa", metaProperties.get("param_a")); assertEquals("bbbb", metaProperties.get("param_b")); assertEquals("CCCC", metaProperties.get("param_c")); verify(logger, times(1)).info(contains("Reading metadata properties file")); verifyNoMoreInteractions(logger); } finally { deletePropertiesFile(); } } @Test public void testAsMetadataElement() throws ParseException { final BinningOp binningOp = createBinningOp(); final GlobalMetadata globalMetadata = GlobalMetadata.create(binningOp); final MetadataElement processingGraphElement = globalMetadata.asMetadataElement(); assertNotNull(processingGraphElement); assertEquals("Processing_Graph", processingGraphElement.getName()); final MetadataElement node_0_Element = processingGraphElement.getElement("node.0"); assertNotNull(node_0_Element); final MetadataElement parameterElement = node_0_Element.getElement("parameters"); assertEquals(11, parameterElement.getNumAttributes()); // @todo 2 tb/tb check for other meta elements 2014-10-10 final MetadataAttribute software_qualified_name = parameterElement.getAttribute("software_qualified_name"); assertNotNull(software_qualified_name); assertEquals("org.esa.snap.binning.operator.BinningOp", software_qualified_name.getData().getElemString()); } @Test public void testAsMetadataElement_noMetadataContained() { final GlobalMetadata globalMetadata = new GlobalMetadata(); final MetadataElement metadataElement = globalMetadata.asMetadataElement(); assertNotNull(metadataElement); assertEquals("Processing_Graph", metadataElement.getName()); assertEquals(0, metadataElement.getNumAttributes()); } @Test public void testIsTimeFilterMetadataRequired() { assertFalse(GlobalMetadata.isTimeFilterMetadataRequired(null)); assertFalse(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.NONE)); assertTrue(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.SPATIOTEMPORAL_DATA_DAY)); assertTrue(GlobalMetadata.isTimeFilterMetadataRequired(BinningOp.TimeFilterMethod.TIME_RANGE)); } @Test public void testToPixelSizeString() { assertEquals("1821.593952320952", GlobalMetadata.toPixelSizeString(12)); assertEquals("2.446286592055973", GlobalMetadata.toPixelSizeString(8192)); } private void deletePropertiesFile() { final File testDir = new File(TEST_DIR); if (testDir.isDirectory()) { if (!FileUtils.deleteTree(testDir)) { fail("unable to delete test directory"); } } } private File writePropertiesFile() throws IOException { final File testDir = new File(TEST_DIR); if (!testDir.mkdirs()) { fail("unable to create test directory"); } final File testPropertiesFile = new File(testDir, "test.properties"); if (!testPropertiesFile.createNewFile()) { fail("unable to create test file"); } final FileOutputStream fileOutputStream = new FileOutputStream(testPropertiesFile); fileOutputStream.write(TEST_PROPERTIES.getBytes()); fileOutputStream.close(); return testPropertiesFile; } private BinningOp createBinningOp() throws ParseException { final BinningOp binningOp = new BinningOp(); binningOp.setOutputFile("output.file"); binningOp.setStartDateTime("2013-05-01"); binningOp.setPeriodDuration(15.56); final WKTReader wktReader = new WKTReader(); binningOp.setRegion(wktReader.read("POLYGON((10 10, 15 10, 15 12, 10 12, 10 10))")); binningOp.setTimeFilterMethod(BinningOp.TimeFilterMethod.NONE); binningOp.setNumRows(8192); binningOp.setSuperSampling(3); binningOp.setMaskExpr("a_mask_expression"); return binningOp; } }
gpl-3.0
noskill/Firesoft
src/main/java/io/firesoft/service/UserService.java
3093
package io.firesoft.service; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.transaction.Transactional; import io.firesoft.model.Post; import io.firesoft.model.Role; import io.firesoft.model.User; import io.firesoft.repository.PostRepository; import io.firesoft.repository.RoleRepository; import io.firesoft.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service @Transactional public class UserService { @Autowired private UserRepository userRepository; @PersistenceContext(unitName="punit") private EntityManager em; @Autowired private PostRepository postRepository; @Autowired private RoleRepository roleRepository; public List<User> findAll() { return userRepository.findAll(); } public User findOne(int id) { return userRepository.findOne(id); } public User findUserByEmail(String email){ CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<User> query = builder.createQuery(User.class); Root<User> root = query.from(User.class); query.select(root).where(builder.equal(root.get("username").as(String.class), email)); return findUserByCriteria(query); } private User findUserByCriteria(CriteriaQuery<User> criteria) { TypedQuery<User> pQuery= em.createQuery(criteria); User result = null; try{ result = pQuery.getSingleResult(); } catch (NoResultException e) { return result; } return result; } @Transactional public User findOneWithPosts(int id) { User user = findOne(id); List<Post> posts = postRepository.findByUser(user, new PageRequest(0, 10, Direction.DESC, "title")); user.setPosts(posts); return user; } public void save(User user) { user.setEnabled(true); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); user.setPassword(encoder.encode(user.getPassword())); List<Role> roles = new ArrayList<Role>(); roles.add(roleRepository.findByName("ROLE_USER")); user.setRoles(roles); userRepository.save(user); } public User findOneWithPosts(String name) { User user = userRepository.findByUsername(name); return findOneWithPosts(user.getId()); } public User findByName(String name) { return userRepository.findByUsername(name); } public void delete(int id) { userRepository.delete(id); } }
gpl-3.0
gstreamer-java/gir2java
generated-src/generated/gio20/gio/GIOExtensionPoint.java
2870
package generated.gio20.gio; import generated.glib20.glib.GList; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Library; import org.bridj.ann.Ptr; @Library("gio-2.0") public class GIOExtensionPoint extends StructObject { static { BridJ.register(); } public GIOExtensionPoint() { super(); } public GIOExtensionPoint(Pointer pointer) { super(pointer); } @Ptr protected native long g_io_extension_point_get_extension_by_name( @Ptr long extension_point, @Ptr long name); public Pointer<GIOExtension> get_extension_by_name(Pointer name) { return Pointer.pointerToAddress(this.g_io_extension_point_get_extension_by_name(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer(), Pointer.getPeer(name)), GIOExtension.class); } @Ptr protected native long g_io_extension_point_get_extensions( @Ptr long extension_point); public Pointer<GList> get_extensions() { return Pointer.pointerToAddress(this.g_io_extension_point_get_extensions(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer()), GList.class); } protected native long g_io_extension_point_get_required_type( @Ptr long extension_point); public long get_required_type() { return this.g_io_extension_point_get_required_type(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer()); } protected native void g_io_extension_point_set_required_type( @Ptr long extension_point, long type); public void set_required_type(long type) { this.g_io_extension_point_set_required_type(Pointer.pointerTo(this, GIOExtensionPoint.class).getPeer(), type); } @Ptr protected static native long g_io_extension_point_implement( @Ptr long extension_point_name, long type, @Ptr long extension_name, int priority); public static Pointer<GIOExtension> implement(Pointer extension_point_name, long type, Pointer extension_name, int priority) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_implement(Pointer.getPeer(extension_point_name), type, Pointer.getPeer(extension_name), priority), GIOExtension.class); } @Ptr protected static native long g_io_extension_point_lookup( @Ptr long name); public static Pointer lookup(Pointer name) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_lookup(Pointer.getPeer(name))); } @Ptr protected static native long g_io_extension_point_register( @Ptr long name); public static Pointer register(Pointer name) { return Pointer.pointerToAddress(GIOExtensionPoint.g_io_extension_point_register(Pointer.getPeer(name))); } }
gpl-3.0
sparkleDai/swiftp
src/be/ppareit/swiftp/FtpServerService.java
15378
/* Copyright 2011-2013 Pieter Pareit Copyright 2009 David Revell This file is part of SwiFTP. SwiFTP 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. SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>. */ package be.ppareit.swiftp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import be.ppareit.swiftp.server.SessionThread; import be.ppareit.swiftp.server.TcpListener; public class FtpServerService extends Service implements Runnable { private static final String TAG = FtpServerService.class.getSimpleName(); // Service will (global) broadcast when server start/stop static public final String ACTION_STARTED = "be.ppareit.swiftp.FTPSERVER_STARTED"; static public final String ACTION_STOPPED = "be.ppareit.swiftp.FTPSERVER_STOPPED"; static public final String ACTION_FAILEDTOSTART = "be.ppareit.swiftp.FTPSERVER_FAILEDTOSTART"; // RequestStartStopReceiver listens for these actions to start/stop this server static public final String ACTION_START_FTPSERVER = "be.ppareit.swiftp.ACTION_START_FTPSERVER"; static public final String ACTION_STOP_FTPSERVER = "be.ppareit.swiftp.ACTION_STOP_FTPSERVER"; protected static Thread serverThread = null; protected boolean shouldExit = false; protected ServerSocket listenSocket; // The server thread will check this often to look for incoming // connections. We are forced to use non-blocking accept() and polling // because we cannot wait forever in accept() if we want to be able // to receive an exit signal and cleanly exit. public static final int WAKE_INTERVAL_MS = 1000; // milliseconds private TcpListener wifiListener = null; private final List<SessionThread> sessionThreads = new ArrayList<SessionThread>(); private PowerManager.WakeLock wakeLock; private WifiLock wifiLock = null; @Override public int onStartCommand(Intent intent, int flags, int startId) { shouldExit = false; int attempts = 10; // The previous server thread may still be cleaning up, wait for it to finish. while (serverThread != null) { Log.w(TAG, "Won't start, server thread exists"); if (attempts > 0) { attempts--; Util.sleepIgnoreInterupt(1000); } else { Log.w(TAG, "Server thread already exists"); return START_STICKY; } } Log.d(TAG, "Creating server thread"); serverThread = new Thread(this); serverThread.start(); return START_STICKY; } public static boolean isRunning() { // return true if and only if a server Thread is running if (serverThread == null) { Log.d(TAG, "Server is not running (null serverThread)"); return false; } if (!serverThread.isAlive()) { Log.d(TAG, "serverThread non-null but !isAlive()"); } else { Log.d(TAG, "Server is alive"); } return true; } @Override public void onDestroy() { Log.i(TAG, "onDestroy() Stopping server"); shouldExit = true; if (serverThread == null) { Log.w(TAG, "Stopping with null serverThread"); return; } serverThread.interrupt(); try { serverThread.join(10000); // wait 10 sec for server thread to finish } catch (InterruptedException e) { } if (serverThread.isAlive()) { Log.w(TAG, "Server thread failed to exit"); // it may still exit eventually if we just leave the shouldExit flag set } else { Log.d(TAG, "serverThread join()ed ok"); serverThread = null; } try { if (listenSocket != null) { Log.i(TAG, "Closing listenSocket"); listenSocket.close(); } } catch (IOException e) { } if (wifiLock != null) { Log.d(TAG, "onDestroy: Releasing wifi lock"); wifiLock.release(); wifiLock = null; } if (wakeLock != null) { Log.d(TAG, "onDestroy: Releasing wake lock"); wakeLock.release(); wakeLock = null; } Log.d(TAG, "FTPServerService.onDestroy() finished"); } // This opens a listening socket on all interfaces. void setupListener() throws IOException { listenSocket = new ServerSocket(); listenSocket.setReuseAddress(true); listenSocket.bind(new InetSocketAddress(Settings.getPortNumber())); } public void run() { Log.d(TAG, "Server thread running"); if (isConnectedToLocalNetwork() == false) { Log.w(TAG, "run: There is no local network, bailing out"); stopSelf(); sendBroadcast(new Intent(ACTION_FAILEDTOSTART)); return; } // Initialization of wifi, set up the socket try { setupListener(); } catch (IOException e) { Log.w(TAG, "run: Unable to open port, bailing out."); stopSelf(); sendBroadcast(new Intent(ACTION_FAILEDTOSTART)); return; } // @TODO: when using ethernet, is it needed to take wifi lock? takeWifiLock(); takeWakeLock(); // A socket is open now, so the FTP server is started, notify rest of world Log.i(TAG, "Ftp Server up and running, broadcasting ACTION_STARTED"); sendBroadcast(new Intent(ACTION_STARTED)); while (!shouldExit) { if (wifiListener != null) { if (!wifiListener.isAlive()) { Log.d(TAG, "Joining crashed wifiListener thread"); try { wifiListener.join(); } catch (InterruptedException e) { } wifiListener = null; } } if (wifiListener == null) { // Either our wifi listener hasn't been created yet, or has crashed, // so spawn it wifiListener = new TcpListener(listenSocket, this); wifiListener.start(); } try { // TODO: think about using ServerSocket, and just closing // the main socket to send an exit signal Thread.sleep(WAKE_INTERVAL_MS); } catch (InterruptedException e) { Log.d(TAG, "Thread interrupted"); } } terminateAllSessions(); if (wifiListener != null) { wifiListener.quit(); wifiListener = null; } shouldExit = false; // we handled the exit flag, so reset it to acknowledge Log.d(TAG, "Exiting cleanly, returning from run()"); stopSelf(); sendBroadcast(new Intent(ACTION_STOPPED)); } private void terminateAllSessions() { Log.i(TAG, "Terminating " + sessionThreads.size() + " session thread(s)"); synchronized (this) { for (SessionThread sessionThread : sessionThreads) { if (sessionThread != null) { sessionThread.closeDataSocket(); sessionThread.closeSocket(); } } } } /** * Takes the wake lock * * Many devices seem to not properly honor a PARTIAL_WAKE_LOCK, which should prevent * CPU throttling. For these devices, we have a option to force the phone into a full * wake lock. */ private void takeWakeLock() { if (wakeLock == null) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (Settings.shouldTakeFullWakeLock()) { Log.d(TAG, "takeWakeLock: Taking full wake lock"); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG); } else { Log.d(TAG, "maybeTakeWakeLock: Taking parial wake lock"); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); } wakeLock.setReferenceCounted(false); } wakeLock.acquire(); } private void takeWifiLock() { Log.d(TAG, "takeWifiLock: Taking wifi lock"); if (wifiLock == null) { WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiLock = manager.createWifiLock(TAG); wifiLock.setReferenceCounted(false); } wifiLock.acquire(); } /** * Gets the local ip address * * @return local ip adress or null if not found */ public static InetAddress getLocalInetAddress() { if (isConnectedToLocalNetwork() == false) { Log.e(TAG, "getLocalInetAddress called and no connection"); return null; } // TODO: next if block could probably be removed if (isConnectedUsingWifi() == true) { Context context = FtpServerApp.getAppContext(); WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int ipAddress = wm.getConnectionInfo().getIpAddress(); if (ipAddress == 0) return null; return Util.intToInet(ipAddress); } // This next part should be able to get the local ip address, but in some case // I'm receiving the routable address try { Enumeration<NetworkInterface> netinterfaces = NetworkInterface .getNetworkInterfaces(); while (netinterfaces.hasMoreElements()) { NetworkInterface netinterface = netinterfaces.nextElement(); Enumeration<InetAddress> adresses = netinterface.getInetAddresses(); while (adresses.hasMoreElements()) { InetAddress address = adresses.nextElement(); // this is the condition that sometimes gives problems if (address.isLoopbackAddress() == false && address.isLinkLocalAddress() == false) return address; } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * Checks to see if we are connected to a local network, for instance wifi or ethernet * * @return true if connected to a local network */ public static boolean isConnectedToLocalNetwork() { Context context = FtpServerApp.getAppContext(); ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); // @TODO: this is only defined starting in api level 13 final int TYPE_ETHERNET = 0x00000009; return ni != null && ni.isConnected() == true && (ni.getType() & (ConnectivityManager.TYPE_WIFI | TYPE_ETHERNET)) != 0; } /** * Checks to see if we are connected using wifi * * @return true if connected using wifi */ public static boolean isConnectedUsingWifi() { Context context = FtpServerApp.getAppContext(); ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return ni != null && ni.isConnected() == true && ni.getType() == ConnectivityManager.TYPE_WIFI; } /** * All messages server<->client are also send to this call * * @param incoming * @param s */ public static void writeMonitor(boolean incoming, String s) { } /** * The FTPServerService must know about all running session threads so they can be * terminated on exit. Called when a new session is created. */ public void registerSessionThread(SessionThread newSession) { // Before adding the new session thread, clean up any finished session // threads that are present in the list. // Since we're not allowed to modify the list while iterating over // it, we construct a list in toBeRemoved of threads to remove // later from the sessionThreads list. synchronized (this) { List<SessionThread> toBeRemoved = new ArrayList<SessionThread>(); for (SessionThread sessionThread : sessionThreads) { if (!sessionThread.isAlive()) { Log.d(TAG, "Cleaning up finished session..."); try { sessionThread.join(); Log.d(TAG, "Thread joined"); toBeRemoved.add(sessionThread); sessionThread.closeSocket(); // make sure socket closed } catch (InterruptedException e) { Log.d(TAG, "Interrupted while joining"); // We will try again in the next loop iteration } } } for (SessionThread removeThread : toBeRemoved) { sessionThreads.remove(removeThread); } // Cleanup is complete. Now actually add the new thread to the list. sessionThreads.add(newSession); } Log.d(TAG, "Registered session thread"); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); Log.d(TAG, "user has removed my activity, we got killed! restarting..."); Intent restartService = new Intent(getApplicationContext(), this.getClass()); restartService.setPackage(getPackageName()); PendingIntent restartServicePI = PendingIntent.getService( getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmService = (AlarmManager) getApplicationContext() .getSystemService(Context.ALARM_SERVICE); alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000, restartServicePI); } }
gpl-3.0
mirage22/robo4j
robo4j-hw-rpi/src/main/java/com/robo4j/hw/rpi/i2c/adafruitbackpack/LedBackpackFactory.java
1458
/* * Copyright (c) 2014, 2019, Marcus Hirt, Miroslav Wengner * * Robo4J 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. * * Robo4J 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 Robo4J. If not, see <http://www.gnu.org/licenses/>. */ package com.robo4j.hw.rpi.i2c.adafruitbackpack; import java.io.IOException; /** * LedBackpackFactory create an Backpack device by defined type * * @author Marcus Hirt (@hirt) * @author Miroslav Wengner (@miragemiko) */ public final class LedBackpackFactory { public static AbstractBackpack createDevice(int bus, int address, LedBackpackType type, int brightness) throws IOException { switch (type) { case BI_COLOR_BAR_24: return new BiColor24BarDevice(bus, address, brightness); case BI_COLOR_MATRIX_8x8: return new BiColor8x8MatrixDevice(bus, address, brightness); case ALPHANUMERIC: return new AlphanumericDevice(bus, address, brightness); default: throw new IllegalStateException("not available backpack: " + type); } } }
gpl-3.0
robertp1984/softwarecave
springjpa/src/main/java/com/example/springjpa/PersonListController.java
1116
package com.example.springjpa; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value = "/personlist") public class PersonListController { @Autowired private PersonList list; @RequestMapping(method = RequestMethod.POST) public String add(@ModelAttribute(value = "newPerson") Person newPerson, BindingResult result, Model model) { if (result.hasErrors()) return "personlist"; list.addPerson(newPerson); return "redirect:/personlist"; } @RequestMapping(method = RequestMethod.GET) public String list(Model model) { model.addAttribute("list", list.getAll()); model.addAttribute("newPerson", new Person()); return "personlist"; } }
gpl-3.0
voyages-sncf-technologies/hesperides
core/presentation/src/main/java/org/hesperides/core/presentation/security/VerboseBasicAuthenticationEntryPoint.java
1954
/* * * This file is part of the Hesperides distribution. * (https://github.com/voyages-sncf-technologies/hesperides) * Copyright (c) 2020 VSCT. * * Hesperides is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, version 3. * * Hesperides is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * */ package org.hesperides.core.presentation.security; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; final class VerboseBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { VerboseBasicAuthenticationEntryPoint() { setRealmName("Realm"); } @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"" + getRealmName() + "\""); response.setStatus(HttpStatus.UNAUTHORIZED.value()); String errorMessage = authException.getMessage(); if (authException.getCause() != null) { // LDAP error messages have been seen to contain \u0000 characters. We remove them: errorMessage += " : " + authException.getCause().getMessage().replace("\u0000", ""); } response.getOutputStream().println(errorMessage); } }
gpl-3.0
tectronics/ingatan
src/org/jCharts/properties/ChartItem.java
3137
/*********************************************************************************************** * File Info: $Id: ChartItem.java,v 1.1 2002/11/16 19:03:24 nathaniel_auvil Exp $ * Copyright (C) 2002 * Author: Nathaniel G. Auvil * Contributor(s): * * Copyright 2002 (C) Nathaniel G. Auvil. All Rights Reserved. * * Redistribution and use of this software and associated documentation ("Software"), with or * without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain copyright statements and notices. * Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. The name "jCharts" or "Nathaniel G. Auvil" must not be used to endorse or promote * products derived from this Software without prior written permission of Nathaniel G. * Auvil. For written permission, please contact nathaniel_auvil@users.sourceforge.net * * 4. Products derived from this Software may not be called "jCharts" nor may "jCharts" appear * in their names without prior written permission of Nathaniel G. Auvil. jCharts is a * registered trademark of Nathaniel G. Auvil. * * 5. Due credit should be given to the jCharts Project (http://jcharts.sourceforge.net/). * * THIS SOFTWARE IS PROVIDED BY Nathaniel G. Auvil AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * jCharts OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE ************************************************************************************************/ package org.jCharts.properties; import java.awt.*; public abstract class ChartItem { private static final Paint DEFAULT_PAINT= Color.black; private Paint paint; public ChartItem() { this.paint= DEFAULT_PAINT; } public ChartItem( Paint paint ) { this.paint= paint; } public Paint getPaint() { return paint; } /********************************************************************************** * Sets the Paint and Stroke implementations on the Graphics2D Object * * @param graphics2D **********************************************************************************/ public void setupGraphics2D( Graphics2D graphics2D ) { graphics2D.setPaint( this.getPaint() ); } }
gpl-3.0
mhall119/Phoenicia
app/src/main/java/com/linguaculturalists/phoenicia/models/GameSession.java
7698
package com.linguaculturalists.phoenicia.models; import android.content.Context; import com.linguaculturalists.phoenicia.locale.Locale; import com.linguaculturalists.phoenicia.util.PhoeniciaContext; import com.orm.androrm.Filter; import com.orm.androrm.Model; import com.orm.androrm.QuerySet; import com.orm.androrm.field.BooleanField; import com.orm.androrm.field.CharField; import com.orm.androrm.field.DoubleField; import com.orm.androrm.field.IntegerField; import com.orm.androrm.migration.Migrator; import org.andengine.util.debug.Debug; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * Database model representing a single user's game session. */ public class GameSession extends Model { public CharField session_name; /**< user defined name for this session */ public CharField person_name; /**< locale person representing this player */ public CharField locale_pack; /**< path to the locale pack used by this session */ public DoubleField start_timestamp; /**< time when this session was created (in seconds from epoch) */ public DoubleField last_timestamp; /**< last time this session was used (in seconds from epoch) */ public IntegerField sessions_played; /**< incremented every time the session is used */ public IntegerField days_played; /**< number of unique days when this session was used */ public CharField current_level; /**< the name of the current level from the locale that the session has reached */ public IntegerField points; /**< accumulated points from various in-game actions */ public IntegerField account_balance; /**< current amount of in-game currency held by the player */ public IntegerField gross_income; /**< cumulative total of in-game currency earned over the course of this session */ public BooleanField is_active; /**< Whether this session is active (not deleted) and should be displayed */ public BooleanField pref_music; /**< Store user preference to play background music or not */ public Filter filter; public Filter session_filter; private List<ExperienceChangeListener> listeners; public static final QuerySet<GameSession> objects(Context context) { return objects(context, GameSession.class); } public GameSession(){ super(); this.session_name = new CharField(32); this.person_name = new CharField(32); this.locale_pack = new CharField(32); this.start_timestamp = new DoubleField(); this.last_timestamp = new DoubleField(); this.sessions_played = new IntegerField(); this.days_played = new IntegerField(); this.current_level = new CharField(); this.points = new IntegerField(); this.account_balance = new IntegerField(); this.gross_income = new IntegerField(); this.is_active = new BooleanField(); this.pref_music = new BooleanField(); this.listeners = new ArrayList<ExperienceChangeListener>(); } /** * Creates a new GameSession for the given local. * @param locale for the new session * @return a new session */ static public GameSession start(Locale locale) { GameSession session = new GameSession(); session.locale_pack.set(locale.name); Date now = new Date(); session.start_timestamp.set((double)now.getTime()); session.last_timestamp.set((double)now.getTime()); session.sessions_played.set(0); session.days_played.set(0); session.points.set(0); session.account_balance.set(0); session.gross_income.set(0); session.is_active.set(true); session.pref_music.set(true); return session; } static public GameSession start(String locale_path) { GameSession session = new GameSession(); session.locale_pack.set(locale_path); Date now = new Date(); session.start_timestamp.set((double)now.getTime()); session.last_timestamp.set((double)now.getTime()); session.sessions_played.set(0); session.days_played.set(0); session.points.set(0); session.account_balance.set(0); session.gross_income.set(0); session.is_active.set(true); session.pref_music.set(true); return session; } public void reset() { Date now = new Date(); this.start_timestamp.set((double)now.getTime()); this.last_timestamp.set((double)now.getTime()); this.sessions_played.set(0); this.days_played.set(0); this.current_level.reset(); this.points.set(0); this.account_balance.set(0); this.gross_income.set(0); this.is_active.set(true); this.pref_music.set(true); } public int addExperience(int points) { this.points.set(this.points.get()+points); this.experienceChanged(this.points.get()); return this.points.get(); } public int removeExperience(int points) { this.points.set(this.points.get()-points); this.experienceChanged(this.points.get()); return this.points.get(); } private void experienceChanged(int new_xp) { Debug.d("Experience points changed"); for (int i = 0; i < this.listeners.size(); i++) { Debug.d("Calling update listener: "+this.listeners.get(i).getClass()); this.listeners.get(i).onExperienceChanged(new_xp); } } public void addExperienceChangeListener(ExperienceChangeListener listener) { this.listeners.add(listener); } public void removeUpdateListener(ExperienceChangeListener listener) { this.listeners.remove(listener); } @Override public boolean save(Context context) { final boolean retval = super.save(context); if (retval && this.filter == null) { this.filter = new Filter(); this.filter.is("game", this); this.session_filter = new Filter(); this.session_filter.is("session", this); } return retval; } /** * Inform the session of a new instance of play * * Updates #last_timestamp, #sessions_played, and if it has been more than a day since the last * time, also updates the #days_played3 */ public void update() { Date now = new Date(); long diff = now.getTime() - this.last_timestamp.get().longValue(); if (TimeUnit.MILLISECONDS.toDays(diff) > 1) { this.days_played.set(this.days_played.get() + 1); } this.sessions_played.set(this.sessions_played.get() + 1); this.last_timestamp.set((double)now.getTime()); } @Override protected void migrate(Context context) { Migrator<GameSession> migrator = new Migrator<GameSession>(GameSession.class); // Add level field migrator.addField("current_level", new IntegerField()); // Add points field migrator.addField("points", new IntegerField()); migrator.addField("account_balance", new IntegerField()); migrator.addField("gross_income", new IntegerField()); migrator.addField("person_name", new CharField()); // Add state fields migrator.addField("is_active", new BooleanField()); migrator.addField("pref_music", new BooleanField()); // roll out all migrations migrator.migrate(context); return; } /** * Called by the GameSession class whenever the player's experience points changes */ public interface ExperienceChangeListener { public void onExperienceChanged(int new_xp); } }
gpl-3.0
BjerknesClimateDataCentre/QuinCe
WebApp/src/uk/ac/exeter/QuinCe/web/Instrument/newInstrument/SeparatorValidator.java
1059
package uk.ac.exeter.QuinCe.web.Instrument.newInstrument; import javax.faces.application.FacesMessage; import javax.faces.validator.ValidatorException; import uk.ac.exeter.QuinCe.data.Instrument.FileDefinition; /** * Check that the chosen separator results in more than 0 columns * * @author Steve Jones * */ public class SeparatorValidator extends NewInstrumentValidator { @Override public void doValidation(NewInstrumentBean bean, Object value) throws ValidatorException { String separator = ((String) value).trim(); if (!FileDefinition.validateSeparator(separator)) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsupported separator", "Unsupported separator")); } if (bean.getCurrentInstrumentFile().calculateColumnCount(separator) <= 1) { throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Cannot extract any columns using the specified separator", "Cannot extract any columns using the specified separator")); } } }
gpl-3.0
AEnterprise/Buildcraft-Additions
src/main/java/buildcraft/api/blueprints/SchematicBlockBase.java
412
/** * Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * The BuildCraft API is distributed under the terms of the MIT License. * Please check the contents of the license, which should be located * as "LICENSE.API" in the BuildCraft source code distribution. */ package buildcraft.api.blueprints; public abstract class SchematicBlockBase extends Schematic { }
gpl-3.0
craftercms/test-suite
src/test/java/org/craftercms/studio/test/cases/apitestcases/StartPublisherAPITest.java
2782
/* * Copyright (C) 2007-2019 Crafter Software Corporation. All Rights Reserved. * * 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.craftercms.studio.test.cases.apitestcases; import org.craftercms.studio.test.api.objects.PublishAPI; import org.craftercms.studio.test.api.objects.SecurityAPI; import org.craftercms.studio.test.api.objects.SiteManagementAPI; import org.craftercms.studio.test.utils.APIConnectionManager; import org.craftercms.studio.test.utils.JsonTester; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * Created by gustavo ortiz */ public class StartPublisherAPITest { private SiteManagementAPI siteManagementAPI; private SecurityAPI securityAPI; private PublishAPI publishAPI; private String siteId = "startpublishersite"; public StartPublisherAPITest() { APIConnectionManager apiConnectionManager = new APIConnectionManager(); JsonTester api = new JsonTester(apiConnectionManager.getProtocol(), apiConnectionManager.getHost(), apiConnectionManager.getPort()); securityAPI = new SecurityAPI(api, apiConnectionManager); publishAPI = new PublishAPI(api, apiConnectionManager); siteManagementAPI = new SiteManagementAPI(api, apiConnectionManager); } @BeforeTest public void beforeTest() { securityAPI.logInIntoStudioUsingAPICall(); siteManagementAPI.testCreateSite(siteId); } @Test(priority = 1,groups={"startPublisher"}) public void testStartPublisher() { publishAPI.testStartPublisher(siteId); } @Test(priority = 2,groups={"startPublisher"}) public void testStartPublisherInvalidParameters() { publishAPI.testStartPublisherInvalidParameters(siteId); } @Test(priority = 3,groups={"startPublisher"}) public void testStartPublisherSiteNotFound() { publishAPI.testStartPublisherSiteNotFound(siteId); } @AfterGroups(groups={"startPublisher"}) public void afterTest(){ siteManagementAPI.testDeleteSite(siteId); securityAPI.logOutFromStudioUsingAPICall(); } @Test(dependsOnGroups={"startPublisher"}) public void testStartPublisherUnauthorized(){ publishAPI.testStartPublisherUnauthorized(siteId); } }
gpl-3.0
valery-labuzhsky/EditorTools
IDEA/src/main/java/ksp/kos/ideaplugin/reference/PsiFileResolver.java
1343
package ksp.kos.ideaplugin.reference; import com.intellij.psi.PsiFileFactory; import ksp.kos.ideaplugin.KerboScriptFile; import ksp.kos.ideaplugin.KerboScriptLanguage; import ksp.kos.ideaplugin.reference.context.FileContextResolver; import ksp.kos.ideaplugin.reference.context.FileDuality; import ksp.kos.ideaplugin.reference.context.PsiFileDuality; import org.jetbrains.annotations.NotNull; /** * Created on 08/10/16. * * @author ptasha */ public class PsiFileResolver implements FileContextResolver { private final KerboScriptFile anyFile; public PsiFileResolver(KerboScriptFile anyFile) { this.anyFile = anyFile; } @Override public @NotNull FileDuality ensureFile(String name) { KerboScriptFile file = anyFile.findFile(name); if (file == null) { file = (KerboScriptFile) PsiFileFactory.getInstance(anyFile.getProject()).createFileFromText( name + ".ks", KerboScriptLanguage.INSTANCE, "@lazyglobal off."); file = (KerboScriptFile) anyFile.getContainingDirectory().add(file); } return file; } @Override public FileDuality resolveFile(String name) { KerboScriptFile file = anyFile.resolveFile(name); if (file!=null) { return new PsiFileDuality(file); } return null; } }
gpl-3.0
luiz158/ExemplosDemoiselle
artigoJM/src/main/java/org/demoiselle/artigoJM/persistence/BookmarkDAO.java
354
package org.demoiselle.artigoJM.persistence; import br.gov.frameworkdemoiselle.stereotype.PersistenceController; import br.gov.frameworkdemoiselle.template.JPACrud; import org.demoiselle.artigoJM.domain.Bookmark; @PersistenceController public class BookmarkDAO extends JPACrud<Bookmark, Long> { private static final long serialVersionUID = 1L; }
gpl-3.0
empeeoh/BACnet4J
src/com/serotonin/bacnet4j/type/notificationParameters/CommandFailure.java
4226
/* * ============================================================================ * 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.type.notificationParameters; import com.serotonin.bacnet4j.exception.BACnetException; import com.serotonin.bacnet4j.type.AmbiguousValue; import com.serotonin.bacnet4j.type.Encodable; import com.serotonin.bacnet4j.type.constructed.StatusFlags; import org.free.bacnet4j.util.ByteQueue; public class CommandFailure extends NotificationParameters { private static final long serialVersionUID = 5727410398456093753L; public static final byte TYPE_ID = 3; private final Encodable commandValue; private final StatusFlags statusFlags; private final Encodable feedbackValue; public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) { this.commandValue = commandValue; this.statusFlags = statusFlags; this.feedbackValue = feedbackValue; } @Override protected void writeImpl(ByteQueue queue) { writeEncodable(queue, commandValue, 0); write(queue, statusFlags, 1); writeEncodable(queue, feedbackValue, 2); } public CommandFailure(ByteQueue queue) throws BACnetException { commandValue = new AmbiguousValue(queue, 0); statusFlags = read(queue, StatusFlags.class, 1); feedbackValue = new AmbiguousValue(queue, 2); } @Override protected int getTypeId() { return TYPE_ID; } public Encodable getCommandValue() { return commandValue; } public StatusFlags getStatusFlags() { return statusFlags; } public Encodable getFeedbackValue() { return feedbackValue; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode()); result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode()); result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.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 CommandFailure other = (CommandFailure) obj; if (commandValue == null) { if (other.commandValue != null) return false; } else if (!commandValue.equals(other.commandValue)) return false; if (feedbackValue == null) { if (other.feedbackValue != null) return false; } else if (!feedbackValue.equals(other.feedbackValue)) return false; if (statusFlags == null) { if (other.statusFlags != null) return false; } else if (!statusFlags.equals(other.statusFlags)) return false; return true; } }
gpl-3.0
lipro/jkcemu
src/jkcemu/disk/DiskImgCreateFrm.java
40900
/* * (c) 2009-2016 Jens Mueller * * Kleincomputer-Emulator * * Fenster zum manuellen Erzeugen einer Diskettenabbilddatei */ package jkcemu.disk; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.FlavorEvent; import java.awt.datatransfer.FlavorListener; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.lang.*; import java.util.Collection; import java.util.EventObject; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import jkcemu.Main; import jkcemu.base.BaseDlg; import jkcemu.base.BaseFrm; import jkcemu.base.EmuUtil; import jkcemu.base.FileEntry; import jkcemu.base.FileNameFld; import jkcemu.base.FileTableModel; import jkcemu.base.HelpFrm; import jkcemu.base.NIOFileTimesViewFactory; import jkcemu.base.ReplyTextDlg; import jkcemu.text.TextUtil; public class DiskImgCreateFrm extends BaseFrm implements ChangeListener, DropTargetListener, FlavorListener, ListSelectionListener { private static final String HELP_PAGE = "/help/disk/creatediskimg.htm"; private static DiskImgCreateFrm instance = null; private Clipboard clipboard; private File lastOutFile; private boolean dataChanged; private JMenuItem mnuClose; private JMenuItem mnuNew; private JMenuItem mnuFileAdd; private JMenuItem mnuFileRemove; private JMenuItem mnuSort; private JMenuItem mnuSave; private JMenuItem mnuChangeAttrs; private JMenuItem mnuChangeUser; private JMenuItem mnuPaste; private JMenuItem mnuSelectAll; private JMenuItem mnuHelpContent; private JButton btnFileAdd; private JButton btnFileRemove; private JButton btnSave; private JButton btnFileUp; private JButton btnFileDown; private JButton btnSysTrackFileSelect; private JButton btnSysTrackFileRemove; private JTabbedPane tabbedPane; private FileTableModel tableModel; private JTable table; private JScrollPane scrollPane; private FloppyDiskFormatSelectFld fmtSelectFld; private JLabel labelSysTrackFile; private FileNameFld fldSysTrackFileName; private JTextField fldRemark; private JLabel labelStatus; private DropTarget dropTargetFile1; private DropTarget dropTargetFile2; private DropTarget dropTargetSysTrackFile; public static void open() { if( instance != null ) { if( instance.getExtendedState() == Frame.ICONIFIED ) { instance.setExtendedState( Frame.NORMAL ); } } else { instance = new DiskImgCreateFrm(); } instance.toFront(); instance.setVisible( true ); } /* --- ChangeListener --- */ @Override public void stateChanged( ChangeEvent e ) { Object src = e.getSource(); if( src != null ) { if( src == this.tabbedPane ) { updActionButtons(); updStatusText(); } else if( src == this.fmtSelectFld ) { updSysTrackFileFieldsEnabled(); updStatusText(); } } } /* --- DropTargetListener --- */ @Override public void dragEnter( DropTargetDragEvent e ) { if( !EmuUtil.isFileDrop( e ) ) e.rejectDrag(); } @Override public void dragExit( DropTargetEvent e ) { // leer } @Override public void dragOver( DropTargetDragEvent e ) { // leer } @Override public void drop( DropTargetDropEvent e ) { Object src = e.getSource(); if( (src == this.dropTargetFile1) || (src == this.dropTargetFile2) ) { if( EmuUtil.isFileDrop( e ) ) { e.acceptDrop( DnDConstants.ACTION_COPY ); // Quelle nicht loeschen pasteFiles( e.getTransferable() ); } } else if( src == this.dropTargetSysTrackFile ) { File file = EmuUtil.fileDrop( this, e ); if( file != null ) { addSysTrackFile( file ); } } } @Override public void dropActionChanged( DropTargetDragEvent e ) { if( !EmuUtil.isFileDrop( e ) ) e.rejectDrag(); } /* --- FlavorListener --- */ @Override public void flavorsChanged( FlavorEvent e ) { updPasteButton(); } /* --- ListSelectionListener --- */ @Override public void valueChanged( ListSelectionEvent e ) { updActionButtons(); } /* --- ueberschriebene Methoden --- */ @Override protected boolean doAction( EventObject e ) { updStatusText(); boolean rv = false; Object src = e.getSource(); if( src == this.mnuClose ) { rv = true; doClose(); } else if( (src == this.mnuFileAdd) || (src == this.btnFileAdd) ) { rv = true; doFileAdd(); } else if( (src == this.mnuFileRemove) || (src == this.btnFileRemove) ) { rv = true; doFileRemove(); } else if( src == this.mnuNew ) { rv = true; doNew(); } else if( src == this.mnuSort ) { rv = true; this.tableModel.sortAscending( 0 ); } else if( (src == this.mnuSave) || (src == this.btnSave) ) { rv = true; doSave(); } else if( src == this.btnFileDown ) { rv = true; doFileDown(); } else if( src == this.btnFileUp ) { rv = true; doFileUp(); } else if( src == this.btnSysTrackFileSelect ) { rv = true; doSysTrackFileSelect(); } else if( src == this.mnuChangeAttrs ) { rv = true; doChangeAttrs(); } else if( src == this.mnuChangeUser ) { rv = true; doChangeUser(); } else if( src == this.mnuPaste ) { rv = true; doPaste(); } else if( src == this.mnuSelectAll ) { rv = true; doSelectAll(); } else if( src == this.btnSysTrackFileRemove ) { rv = true; doSysTrackFileRemove(); } else if( src == this.mnuHelpContent ) { rv = true; HelpFrm.open( HELP_PAGE ); } return rv; } @Override public boolean doClose() { boolean rv = true; if( this.dataChanged ) { setState( Frame.NORMAL ); toFront(); if( !BaseDlg.showYesNoDlg( this, "Daten ge\u00E4ndert!\n" + "Trotzdem schlie\u00DFen?" ) ) { rv = false; } } if( rv ) { this.tableModel.clear( true ); updStatusText(); rv = super.doClose(); } if( rv ) { this.dataChanged = false; Main.checkQuit( this ); } return rv; } /* --- Aktionen --- */ private void doChangeAttrs() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { ChangeFileAttrsDlg dlg = new ChangeFileAttrsDlg( this ); dlg.setVisible( true ); Boolean readOnly = dlg.getReadOnlyValue(); Boolean sysFile = dlg.getSystemFileValue(); Boolean archive = dlg.getArchiveValue(); if( (readOnly != null) || (sysFile != null) || (archive != null) ) { for( int i = 0; i< rowNums.length; i++ ) { int rowNum = rowNums[ i ]; FileEntry entry = this.tableModel.getRow( rowNums[ i ] ); if( entry != null ) { if( readOnly != null ) { entry.setReadOnly( readOnly.booleanValue() ); } if( sysFile != null ) { entry.setSystemFile( sysFile.booleanValue() ); } if( archive != null ) { entry.setArchive( archive.booleanValue() ); } this.tableModel.fireTableRowsUpdated( rowNum, rowNum ); } } } } } } private void doChangeUser() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { // voreingestellten User-Bereich ermitteln int value = -1; for( int i = 0; i< rowNums.length; i++ ) { FileEntry entry = this.tableModel.getRow( rowNums[ i ] ); if( entry != null ) { Integer userNum = entry.getUserNum(); if( userNum != null ) { if( value >= 0 ) { if( userNum.intValue() != value ) { value = -1; break; } } else { value = userNum.intValue(); } } } } if( (value < 0) || (value > 15) ) { value = 0; } // Dialog anzeigen JPanel panel = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 5 ) ); panel.add( new JLabel( "User-Bereich:" ) ); JSpinner spinner = new JSpinner( new SpinnerNumberModel( value, 0, 15, 1 ) ); panel.add( spinner ); int option = JOptionPane.showConfirmDialog( this, panel, "User-Bereich \u00E4ndern", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE ); if( option == JOptionPane.OK_OPTION ) { Object o = spinner.getValue(); if( o != null ) { if( o instanceof Number ) { value = ((Number) o).intValue(); if( (value >= 0) && (value <= 15) ) { Integer userNum = value; for( int i = 0; i< rowNums.length; i++ ) { int rowNum = rowNums[ i ]; FileEntry entry = this.tableModel.getRow( rowNum ); if( entry != null ) { entry.setUserNum( userNum ); this.tableModel.fireTableRowsUpdated( rowNum, rowNum ); } } } } } } } } } public void doNew() { boolean status = true; StringBuilder buf = new StringBuilder( 256 ); if( this.dataChanged ) { buf.append( "Die letzten \u00C3nderungen wurden nicht gespeichert!" ); } if( (this.tableModel.getRowCount() > 0) || (this.fldSysTrackFileName.getFile() != null) ) { if( buf.length() > 0 ) { buf.append( (char) '\n' ); } buf.append( "Die hinzugef\u00FCgten Dateien werden entfernt." ); } if( buf.length() > 0 ) { status = BaseDlg.showConfirmDlg( this, buf.toString() ); } if( status ) { this.tableModel.clear( true ); this.fldSysTrackFileName.setFile( null ); this.dataChanged = false; this.lastOutFile = null; updTitle(); } } private void doPaste() { if( this.clipboard != null ) { try { pasteFiles( this.clipboard.getContents( this ) ); } catch( IllegalStateException ex ) {} } } private void doSelectAll() { int nRows = this.table.getRowCount(); if( nRows > 0 ) { this.table.setRowSelectionInterval( 0, nRows - 1 ); } } private void doSave() { boolean status = true; if( this.tableModel.getRowCount() == 0 ) { status = BaseDlg.showYesNoDlg( this, "Es wurden keine Dateien hinzugef\u00FCgt.\n" + "M\u00F6chten Sie eine leere Diskettenabbilddatei" + " erstellen?" ); } int sysTracks = this.fmtSelectFld.getSysTracks(); File sysTrackFile = this.fldSysTrackFileName.getFile(); if( (sysTrackFile != null) && (sysTracks == 0) ) { if( JOptionPane.showConfirmDialog( this, "Sie haben ein Format ohne Systemspuren ausgew\u00E4hlt,\n" + "aber eine Datei f\u00FCr die Systemspuren" + " angegeben.\n" + "Diese Datei wird ignoriert.", "Warnung", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ) != JOptionPane.OK_OPTION ) { status = false; } } if( status ) { File file = EmuUtil.showFileSaveDlg( this, "Diskettenabbilddatei speichern", this.lastOutFile != null ? this.lastOutFile : Main.getLastDirFile( Main.FILE_GROUP_DISK ), EmuUtil.getPlainDiskFileFilter(), EmuUtil.getAnaDiskFileFilter(), EmuUtil.getCopyQMFileFilter(), EmuUtil.getDskFileFilter(), EmuUtil.getImageDiskFileFilter(), EmuUtil.getTeleDiskFileFilter() ); if( file != null ) { boolean plainDisk = false; boolean anaDisk = false; boolean cpcDisk = false; boolean copyQMDisk = false; boolean imageDisk = false; boolean teleDisk = false; String fileName = file.getName(); if( fileName != null ) { String lowerName = fileName.toLowerCase(); if( lowerName.endsWith( ".gz" ) ) { lowerName = lowerName.substring( 0, lowerName.length() - 3 ); } plainDisk = TextUtil.endsWith( lowerName, DiskUtil.plainDiskFileExt ); anaDisk = TextUtil.endsWith( lowerName, DiskUtil.anaDiskFileExt ); copyQMDisk = TextUtil.endsWith( lowerName, DiskUtil.copyQMFileExt ); cpcDisk = TextUtil.endsWith( lowerName, DiskUtil.dskFileExt ); imageDisk = TextUtil.endsWith( lowerName, DiskUtil.imageDiskFileExt ); teleDisk = TextUtil.endsWith( lowerName, DiskUtil.teleDiskFileExt ); } if( plainDisk || anaDisk || copyQMDisk || cpcDisk || imageDisk || teleDisk ) { boolean cancelled = false; OutputStream out = null; try { int sides = this.fmtSelectFld.getSides(); int cyls = this.fmtSelectFld.getCylinders(); int sectPerCyl = this.fmtSelectFld.getSectorsPerCylinder(); int sectorSize = this.fmtSelectFld.getSectorSize(); DiskImgCreator diskImgCreator = new DiskImgCreator( new NIOFileTimesViewFactory(), sides, cyls, sysTracks, sectPerCyl, sectorSize, this.fmtSelectFld.isBlockNum16Bit(), this.fmtSelectFld.getBlockSize(), this.fmtSelectFld.getDirBlocks(), this.fmtSelectFld.isDateStamperEnabled() ); if( (sysTrackFile != null) && (sysTracks > 0) ) { diskImgCreator.fillSysTracks( sysTrackFile ); } int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { try { diskImgCreator.addFile( entry.getUserNum(), entry.getName(), entry.getFile(), entry.isReadOnly(), entry.isSystemFile(), entry.isArchive() ); } catch( IOException ex ) { fireSelectRowInterval( i, i ); String msg = ex.getMessage(); if( msg != null ) { if( msg.isEmpty() ) { msg = null; } } if( msg != null ) { msg = entry.getName() + ":\n" + msg; } else { msg = entry.getName() + " kann nicht hinzugef\u00FCgt werden."; } if( JOptionPane.showConfirmDialog( this, msg, "Fehler", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE ) != JOptionPane.OK_OPTION ) { cancelled = true; break; } } } } if( !cancelled ) { byte[] diskBuf = diskImgCreator.getPlainDiskByteBuffer(); if( plainDisk ) { out = EmuUtil.createOptionalGZipOutputStream( file ); out.write( diskBuf ); out.close(); out = null; } else { PlainDisk disk = PlainDisk.createForByteArray( this, file.getPath(), diskBuf, new FloppyDiskFormat( sides, cyls, sectPerCyl, sectorSize ), this.fmtSelectFld.getInterleave() ); if( disk != null ) { if( anaDisk ) { AnaDisk.export( disk, file ); } else if( copyQMDisk ) { CopyQMDisk.export( disk, file, this.fldRemark.getText() ); } else if( cpcDisk ) { CPCDisk.export( disk, file ); } else if( imageDisk ) { ImageDisk.export( disk, file, this.fldRemark.getText() ); } else if( teleDisk ) { TeleDisk.export( disk, file, this.fldRemark.getText() ); } } } this.dataChanged = false; this.lastOutFile = file; updTitle(); Main.setLastFile( file, Main.FILE_GROUP_DISK ); this.labelStatus.setText( "Diskettenabbilddatei gespeichert" ); } } catch( Exception ex ) { BaseDlg.showErrorDlg( this, ex ); } finally { EmuUtil.closeSilent( out ); } } else { BaseDlg.showErrorDlg( this, "Aus der Dateiendung der ausgew\u00E4hlten Datei\n" + "kann JKCEMU das Dateiformat nicht erkennen.\n" + "W\u00E4hlen Sie bitte einen Dateinamen" + " mit einer f\u00FCr\n" + "das gew\u00FCnschte Format \u00FCblichen" + " Dateiendung aus." ); } } } } private void doFileAdd() { java.util.List<File> files = EmuUtil.showMultiFileOpenDlg( this, "Dateien hinzuf\u00FCgen", Main.getLastDirFile( Main.FILE_GROUP_SOFTWARE ) ); if( files != null ) { int firstRowToSelect = this.table.getRowCount(); for( File file : files ) { if( addFile( file ) ) { Main.setLastFile( file, Main.FILE_GROUP_SOFTWARE ); } } updSelectAllEnabled(); fireSelectRowInterval( firstRowToSelect, this.table.getRowCount() - 1 ); } } private void doFileRemove() { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { Arrays.sort( rowNums ); for( int i = rowNums.length - 1; i >= 0; --i ) { this.tableModel.removeRow( rowNums[ i ], true ); this.mnuSort.setEnabled( this.tableModel.getRowCount() > 1 ); this.dataChanged = true; } updSelectAllEnabled(); updStatusText(); } } } private void doFileDown() { final int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0) { Arrays.sort( rowNums ); if( (rowNums[ rowNums.length - 1 ] + 1) < this.tableModel.getRowCount() ) { for( int i = rowNums.length - 1 ; i >= 0; --i ) { int row = rowNums[ i ]; FileEntry e1 = this.tableModel.getRow( row ); FileEntry e2 = this.tableModel.getRow( row + 1 ); if( (e1 != null) && (e2 != null) ) { this.tableModel.setRow( row, e2 ); this.tableModel.setRow( row + 1, e1 ); this.tableModel.fireTableDataChanged(); this.dataChanged = true; } rowNums[ i ]++; } } fireSelectRows( rowNums ); } } } private void doFileUp() { final int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0) { Arrays.sort( rowNums ); if( rowNums[ 0 ] > 0 ) { for( int i = 0; i < rowNums.length; i++ ) { int row = rowNums[ i ]; FileEntry e1 = this.tableModel.getRow( row ); FileEntry e2 = this.tableModel.getRow( row - 1 ); if( (e1 != null) && (e2 != null) ) { this.tableModel.setRow( row, e2 ); this.tableModel.setRow( row - 1, e1 ); this.tableModel.fireTableDataChanged(); this.dataChanged = true; } --rowNums[ i ]; } } fireSelectRows( rowNums ); } } } private void doSysTrackFileSelect() { File file = EmuUtil.showFileOpenDlg( this, "Datei \u00FCffnen", Main.getLastDirFile( Main.FILE_GROUP_SOFTWARE ) ); if( file != null ) { addSysTrackFile( file ); } } private void doSysTrackFileRemove() { this.fldSysTrackFileName.setFile( null ); this.btnSysTrackFileRemove.setEnabled( false ); } /* --- Konstruktor --- */ private DiskImgCreateFrm() { this.clipboard = null; this.dataChanged = false; this.lastOutFile = null; updTitle(); Main.updIcon( this ); Toolkit tk = getToolkit(); if( tk != null ) { this.clipboard = tk.getSystemClipboard(); } // Menu JMenuBar mnuBar = new JMenuBar(); setJMenuBar( mnuBar ); // Menu Datei JMenu mnuFile = new JMenu( "Datei" ); mnuFile.setMnemonic( KeyEvent.VK_D ); mnuBar.add( mnuFile ); this.mnuNew = createJMenuItem( "Neue Diskettenabbilddatei" ); mnuFile.add( this.mnuNew ); mnuFile.addSeparator(); this.mnuFileAdd = createJMenuItem( "Hinzuf\u00FCgen..." ); mnuFile.add( this.mnuFileAdd ); this.mnuFileRemove = createJMenuItem( "Entfernen", KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0 ) ); mnuFile.add( this.mnuFileRemove ); mnuFile.addSeparator(); this.mnuSort = createJMenuItem( "Sortieren" ); this.mnuSort.setEnabled( false ); mnuFile.add( this.mnuSort ); mnuFile.addSeparator(); this.mnuSave = createJMenuItem( "Diskettenabbilddatei speichern..." ); mnuFile.add( this.mnuSave ); mnuFile.addSeparator(); this.mnuClose = createJMenuItem( "Schlie\u00DFen" ); mnuFile.add( this.mnuClose ); // Menu Bearbeiten JMenu mnuEdit = new JMenu( "Bearbeiten" ); mnuEdit.setMnemonic( KeyEvent.VK_B ); mnuBar.add( mnuEdit ); this.mnuPaste = createJMenuItem( "Einf\u00FCgen" ); mnuEdit.add( this.mnuPaste ); mnuEdit.addSeparator(); this.mnuChangeAttrs = createJMenuItem( "Dateiattribute \u00E4ndern..." ); mnuEdit.add( this.mnuChangeAttrs ); this.mnuChangeUser = createJMenuItem( "User-Bereich \u00E4ndern..." ); mnuEdit.add( this.mnuChangeUser ); mnuEdit.addSeparator(); this.mnuSelectAll = createJMenuItem( "Alles ausw\u00E4hlem" ); this.mnuSelectAll.setEnabled( false ); mnuEdit.add( this.mnuSelectAll ); // Menu Hilfe JMenu mnuHelp = new JMenu( "?" ); mnuBar.add( mnuHelp ); this.mnuHelpContent = createJMenuItem( "Hilfe..." ); mnuHelp.add( this.mnuHelpContent ); // Fensterinhalt setLayout( new GridBagLayout() ); GridBagConstraints gbc = new GridBagConstraints( 0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 5, 5, 5, 5 ), 0, 0 ); // Werkzeugleiste JToolBar toolBar = new JToolBar(); toolBar.setFloatable( false ); toolBar.setBorderPainted( false ); toolBar.setOrientation( JToolBar.HORIZONTAL ); toolBar.setRollover( true ); add( toolBar, gbc ); this.btnFileAdd = createImageButton( "/images/file/open.png", "Hinzuf\u00FCgen" ); toolBar.add( this.btnFileAdd ); this.btnFileRemove = createImageButton( "/images/file/delete.png", "Entfernen" ); toolBar.add( this.btnFileRemove ); toolBar.addSeparator(); this.btnSave = createImageButton( "/images/file/save_as.png", "Diskettenabbilddatei speichern" ); toolBar.add( this.btnSave ); toolBar.addSeparator(); this.btnFileDown = createImageButton( "/images/nav/down.png", "Nach unten" ); toolBar.add( this.btnFileDown ); this.btnFileUp = createImageButton( "/images/nav/up.png", "Nach oben" ); toolBar.add( this.btnFileUp ); // TabbedPane this.tabbedPane = new JTabbedPane(); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1.0; gbc.gridy++; add( this.tabbedPane, gbc ); // Tabellenfeld this.tableModel = new FileTableModel( FileTableModel.Column.NAME, FileTableModel.Column.FILE, FileTableModel.Column.SIZE, FileTableModel.Column.LAST_MODIFIED, FileTableModel.Column.USER_NUM, FileTableModel.Column.READ_ONLY, FileTableModel.Column.SYSTEM_FILE, FileTableModel.Column.ARCHIVE ); this.table = new JTable( this.tableModel ); this.table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); this.table.setColumnSelectionAllowed( false ); this.table.setPreferredScrollableViewportSize( new Dimension( 700, 300 ) ); this.table.setRowSelectionAllowed( true ); this.table.setRowSorter( null ); this.table.setShowGrid( false ); this.table.setShowHorizontalLines( false ); this.table.setShowVerticalLines( false ); this.table.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); this.table.addMouseListener( this ); EmuUtil.setTableColWidths( this.table, 100, 280, 70, 130, 40, 40, 40, 40 ); ListSelectionModel selectionModel = this.table.getSelectionModel(); if( selectionModel != null ) { selectionModel.addListSelectionListener( this ); updActionButtons(); } this.scrollPane = new JScrollPane( this.table ); this.tabbedPane.addTab( "Dateien", this.scrollPane ); // Format JPanel panelFmt = new JPanel( new GridBagLayout() ); this.tabbedPane.addTab( "Format", new JScrollPane( panelFmt ) ); GridBagConstraints gbcFmt = new GridBagConstraints( 0, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 5, 5, 0, 5 ), 0, 0 ); this.fmtSelectFld = new FloppyDiskFormatSelectFld( true ); panelFmt.add( this.fmtSelectFld, gbcFmt ); this.labelSysTrackFile = new JLabel( "Datei f\u00FCr Systemspuren:" ); gbcFmt.insets.top = 5; gbcFmt.insets.left = 5; gbcFmt.insets.bottom = 5; gbcFmt.gridwidth = 1; gbcFmt.gridx = 0; gbcFmt.gridy++; panelFmt.add( this.labelSysTrackFile, gbcFmt ); this.fldSysTrackFileName = new FileNameFld(); this.fldSysTrackFileName.setEditable( false ); gbcFmt.fill = GridBagConstraints.HORIZONTAL; gbcFmt.weightx = 1.0; gbcFmt.gridwidth = 5; gbcFmt.gridx++; panelFmt.add( this.fldSysTrackFileName, gbcFmt ); this.btnSysTrackFileSelect = createImageButton( "/images/file/open.png", "\u00D6ffnen" ); gbcFmt.fill = GridBagConstraints.NONE; gbcFmt.weightx = 0.0; gbcFmt.gridwidth = 1; gbcFmt.gridx += 5; panelFmt.add( this.btnSysTrackFileSelect, gbcFmt ); this.btnSysTrackFileRemove = createImageButton( "/images/file/delete.png", "\u00D6ffnen" ); this.btnSysTrackFileRemove.setEnabled( false ); gbcFmt.gridx++; panelFmt.add( this.btnSysTrackFileRemove, gbcFmt ); // Kommentar JPanel panelRemark = new JPanel( new GridBagLayout() ); this.tabbedPane.addTab( "Kommentar", new JScrollPane( panelRemark ) ); GridBagConstraints gbcRemark = new GridBagConstraints( 0, 0, GridBagConstraints.REMAINDER, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 5, 5, 0, 5 ), 0, 0 ); panelRemark.add( new JLabel( "Kommentar zur Diskettenabbilddatei:" ), gbcRemark ); this.fldRemark = new JTextField( "Erzeugt mit JKCEMU" ); gbcRemark.fill = GridBagConstraints.HORIZONTAL; gbcRemark.weightx = 1.0; gbcRemark.insets.top = 0; gbcRemark.insets.bottom = 5; gbcRemark.gridy++; panelRemark.add( this.fldRemark, gbcRemark ); JLabel label = new JLabel( "Achtung!" ); Font font = label.getFont(); if( font != null ) { label.setFont( font.deriveFont( Font.BOLD ) ); } gbcRemark.fill = GridBagConstraints.NONE; gbcRemark.weightx = 0.0; gbcRemark.insets.top = 10; gbcRemark.insets.bottom = 0; gbcRemark.gridy++; panelRemark.add( label, gbcRemark ); gbcRemark.fill = GridBagConstraints.NONE; gbcRemark.weightx = 0.0; gbcRemark.insets.top = 0; gbcRemark.insets.bottom = 5; gbcRemark.gridy++; panelRemark.add( new JLabel( "Ein Kommentar wird nur bei CopyQM-, ImageDisk-" + " und TeleDisk-Dateien unterst\u00FCtzt." ), gbcRemark ); // Statuszeile this.labelStatus = new JLabel(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0.0; gbc.insets.top = 0; gbc.gridy++; add( this.labelStatus, gbc ); updStatusText(); // Fenstergroesse if( !applySettings( Main.getProperties(), true ) ) { pack(); setScreenCentered(); } setResizable( true ); // Listener this.tabbedPane.addChangeListener( this ); this.fmtSelectFld.addChangeListener( this ); if( this.clipboard != null ) { this.clipboard.addFlavorListener( this ); } // Drop-Ziele this.dropTargetFile1 = new DropTarget( this.table, this ); this.dropTargetFile2 = new DropTarget( this.scrollPane, this ); this.dropTargetSysTrackFile = new DropTarget( this.fldSysTrackFileName, this ); this.dropTargetFile1.setActive( true ); this.dropTargetFile1.setActive( true ); this.dropTargetSysTrackFile.setActive( true ); // sonstiges updActionButtons(); updBgColor(); updPasteButton(); } /* --- private Methoden --- */ private boolean addFile( File file ) { boolean rv = false; boolean done = false; if( file.isDirectory() ) { String s = file.getName(); if( s != null ) { try { int userNum = Integer.parseInt( s ); if( (userNum >= 1) && (userNum <= 15) ) { done = true; if( BaseDlg.showYesNoDlg( this, "Sollen die Dateien im Verzeichnis " + s + "\nin der Benutzerebene " + s + " hinzugef\u00FCgt werden?" ) ) { File[] files = file.listFiles(); if( files != null ) { for( File f : files ) { if( f.isFile() ) { rv = addFileInternal( userNum, f ); if( !rv ) { break; } } } } } } } catch( NumberFormatException ex ) {} } } if( !done ) { rv = addFileInternal( 0, file ); } return rv; } private boolean addFileInternal( int userNum, File file ) { boolean rv = false; long size = -1L; if( file.isFile() ) { size = file.length(); if( size < 1 ) { String fName = file.getName(); if( fName != null ) { if( fName.isEmpty() ) { fName = null; } } if( fName == null ) { fName = file.getPath(); } if( !BaseDlg.showYesNoDlg( this, "Datei " + fName + ":\nDie Datei ist leer!\n" + "Trotzdem hinzuf\u00FCgen?" ) ) { file = null; } } else if( size > (1024 * 16 * 32) ) { BaseDlg.showErrorDlg( this, "Datei ist zu gro\u00DF!" ); file = null; } else { String fileName = file.getName(); if( fileName != null ) { if( fileName.equalsIgnoreCase( DirectoryFloppyDisk.SYS_FILE_NAME ) ) { if( BaseDlg.showYesNoDlg( this, DirectoryFloppyDisk.SYS_FILE_NAME + ":\n" + "JKCEMU verwendet Dateien mit diesem Namen" + " f\u00FCr den Inhalt der Systemspuren.\n" + "M\u00F6chten Sie deshalb nun diese Datei" + " f\u00FCr die Systemspuren verwenden,\n" + "anstelle Sie als gew\u00F6hnliche Datei" + " im Directory einzubinden?" ) ) { this.fldSysTrackFileName.setFile( file ); this.btnSysTrackFileRemove.setEnabled( true ); file = null; rv = true; } } } } } else { BaseDlg.showErrorDlg( this, "Es k\u00F6nnen nur regul\u00E4re Dateien" + " hinzugef\u00FCgt werden." ); file = null; } if( file != null ) { String entryName = null; String fileName = file.getName(); if( fileName != null ) { entryName = createEntryName( fileName ); } if( entryName == null ) { String title = "Dateiname"; String defaultReply = null; if( fileName != null ) { if( !fileName.isEmpty() ) { title = "Datei: " + fileName; } StringBuilder buf = new StringBuilder( 12 ); int len = fileName.length(); int n = 0; for( int i = 0; (n < 8) && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { buf.append( ch ); n++; } else if( ch == '.' ) { break; } } if( n > 0 ) { int pos = fileName.lastIndexOf( '.' ); if( pos > 0 ) { boolean p = true; n = 0; for( int i = pos + 1; (n < 3) && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { if( p ) { buf.append( (char) '.' ); p = false; } buf.append( ch ); n++; } } } } defaultReply = buf.toString(); } String reply = null; do { reply = ReplyTextDlg.showReplyTextDlg( this, "Dateiname im 8.3-Format:", title, defaultReply ); if( reply != null ) { entryName = createEntryName( reply ); if( entryName == null ) { BaseDlg.showErrorDlg( this, "Der eingegebene Name ist ung\u00FCltig." ); } } } while( (reply != null) && (entryName == null) ); } if( entryName != null ) { boolean exists = false; int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { if( entry.getName().equals( entryName ) ) { this.table.setRowSelectionInterval( i, i ); exists = true; break; } } } if( exists ) { BaseDlg.showErrorDlg( this, "Es existiert bereits ein Eintrag mit diesem Namen." ); } else { FileEntry entry = new FileEntry( entryName ); entry.setUserNum( userNum ); if( size >= 0 ) { entry.setSize( size ); } long lastModified = file.lastModified(); if( lastModified != 0 ) { entry.setLastModified( lastModified ); } entry.setFile( file ); entry.setReadOnly( !file.canWrite() ); entry.setSystemFile( false ); entry.setArchive( false ); this.tableModel.addRow( entry, true ); updStatusText(); this.mnuSort.setEnabled( this.tableModel.getRowCount() > 1 ); this.dataChanged = true; rv = true; } } } return rv; } private void addSysTrackFile( File file ) { String errMsg = null; if( !file.exists() ) { errMsg = "Datei nicht gefunden"; } else if( !file.isFile() ) { errMsg = "Datei ist keine regul\u00E4re Datei"; } if( errMsg != null ) { BaseDlg.showErrorDlg( this, errMsg ); } else { this.fldSysTrackFileName.setFile( file ); this.btnSysTrackFileRemove.setEnabled( true ); } } private static String createEntryName( String fileName ) { StringBuilder buf = new StringBuilder( 12 ); boolean failed = false; boolean point = false; int nPre = 0; int nPost = 0; int len = fileName.length(); for( int i = 0; !failed && (i < len); i++ ) { char ch = Character.toUpperCase( fileName.charAt( i ) ); if( DiskUtil.isValidCPMFileNameChar( ch ) ) { if( !point && (nPre < 8) ) { buf.append( ch ); nPre++; } else if( point && (nPost < 3) ) { buf.append( ch ); nPost++; } else { failed = true; } } else if( ch == '.' ) { if( !point && (nPre >= 1) && (nPre <= 8) ) { buf.append( ch ); point = true; } else { failed = true; } } else { failed = true; } } return failed ? null : buf.toString(); } private void fireSelectRows( final int[] rowNums ) { final JTable table = this.table; EventQueue.invokeLater( new Runnable() { @Override public void run() { table.clearSelection(); for( int row : rowNums ) { table.addRowSelectionInterval( row, row ); } } } ); } private void fireSelectRowInterval( final int begRow, final int endRow ) { final JTable table = this.table; EventQueue.invokeLater( new Runnable() { @Override public void run() { try { int nRows = table.getRowCount(); if( (begRow >= 0) && (begRow < nRows) && (begRow <= endRow) ) { table.setRowSelectionInterval( begRow, Math.min( endRow, nRows -1 ) ); } } catch( IllegalArgumentException ex ) {} } } ); } private void pasteFiles( Transferable t ) { try { if( t != null ) { Object o = t.getTransferData( DataFlavor.javaFileListFlavor ); if( o != null ) { if( o instanceof Collection ) { int firstRowToSelect = this.table.getRowCount(); for( Object item : (Collection) o ) { if( item != null ) { File file = null; if( item instanceof File ) { file = (File) item; } else if( item instanceof String ) { file= new File( (String) item ); } if( file != null ) { if( !addFile( file ) ) { break; } } } } fireSelectRowInterval( firstRowToSelect, this.table.getRowCount() - 1 ); } } } } catch( IOException ex ) {} catch( UnsupportedFlavorException ex ) {} finally { updSelectAllEnabled(); } } private void updActionButtons() { boolean stateSelected = false; boolean stateDown = false; boolean stateUp = false; boolean fileTab = (this.tabbedPane.getSelectedIndex() == 0); if( fileTab ) { int[] rowNums = this.table.getSelectedRows(); if( rowNums != null ) { if( rowNums.length > 0 ) { stateSelected = true; Arrays.sort( rowNums ); if( (rowNums[ rowNums.length - 1 ] + 1) < this.tableModel.getRowCount() ) { stateDown = true; } if( rowNums[ 0 ] > 0 ) { stateUp = true; } } } } this.btnFileAdd.setEnabled( fileTab ); this.mnuFileRemove.setEnabled( stateSelected ); this.btnFileRemove.setEnabled( stateSelected ); this.btnFileDown.setEnabled( stateDown ); this.btnFileUp.setEnabled( stateUp ); this.mnuChangeAttrs.setEnabled( stateSelected ); this.mnuChangeUser.setEnabled( stateSelected ); } private void updBgColor() { Color color = this.table.getBackground(); JViewport vp = this.scrollPane.getViewport(); if( (color != null) && (vp != null) ) { vp.setBackground( color ); } } private void updPasteButton() { boolean state = false; if( this.clipboard != null ) { try { state = this.clipboard.isDataFlavorAvailable( DataFlavor.javaFileListFlavor ); } catch( IllegalStateException ex ) {} } this.mnuPaste.setEnabled( state ); } private void updSelectAllEnabled() { this.mnuSelectAll.setEnabled( this.table.getRowCount() > 0 ); } private void updStatusText() { String text = "Bereit"; int idx = this.tabbedPane.getSelectedIndex(); if( idx == 0 ) { long kbytes = 0; int nRows = this.tableModel.getRowCount(); for( int i = 0; i < nRows; i++ ) { FileEntry entry = this.tableModel.getRow( i ); if( entry != null ) { Long size = entry.getSize(); if( size != null ) { if( size.longValue() > 0 ) { long kb = size.longValue() / 1024L; if( (kb * 1024L) < size.longValue() ) { kb++; } kbytes += kb; } } } } StringBuilder buf = new StringBuilder( 64 ); if( nRows == 1 ) { buf.append( "1 Datei" ); } else { buf.append( nRows ); buf.append( " Dateien" ); } buf.append( " mit " ); buf.append( kbytes ); buf.append( " KByte hinzugef\u00FCgt" ); text = buf.toString(); } else if( idx == 1 ) { int sides = this.fmtSelectFld.getSides(); int cyls = this.fmtSelectFld.getCylinders(); int sysTracks = this.fmtSelectFld.getSysTracks(); int sectPerCyl = this.fmtSelectFld.getSectorsPerCylinder(); int sectorSize = this.fmtSelectFld.getSectorSize(); int kbytes = sides * cyls * sectPerCyl * sectorSize / 1024; if( sysTracks > 0 ) { text = String.format( "%d/%dK Diskettenformat eingestellt", sides * (cyls - sysTracks) * sectPerCyl * sectorSize / 1024, kbytes ); } else { text = String.format( "%dK Diskettenformat eingestellt", kbytes ); } } this.labelStatus.setText( text ); } private void updSysTrackFileFieldsEnabled() { boolean state = (this.fmtSelectFld.getSysTracks() > 0); this.labelSysTrackFile.setEnabled( state ); this.fldSysTrackFileName.setEnabled( state ); this.btnSysTrackFileSelect.setEnabled( state ); this.btnSysTrackFileRemove.setEnabled( state && (this.fldSysTrackFileName.getFile() != null) ); } private void updTitle() { String text = "JKCEMU CP/M-Diskettenabbilddatei erstellen"; if( this.lastOutFile != null ) { StringBuilder buf = new StringBuilder( 256 ); buf.append( text ); buf.append( ": " ); String fName = this.lastOutFile.getName(); if( fName != null ) { buf.append( fName ); } text = buf.toString(); } setTitle( text ); } }
gpl-3.0
lipro/jkcemu
src/jkcemu/print/PrintDataScanner.java
1904
/* * (c) 2009-2010 Jens Mueller * * Kleincomputer-Emulator * * Scanner zum Extrahieren der Zeilen und Seitenumbrueche * aus den Druckdaten */ package jkcemu.print; import java.lang.*; public class PrintDataScanner { private byte[] dataBytes; private int pos; public PrintDataScanner( byte[] dataBytes ) { this.dataBytes = dataBytes; this.pos = 0; } public boolean endReached() { return this.pos >= this.dataBytes.length; } public String readLine() { StringBuilder buf = null; while( this.pos < this.dataBytes.length ) { int b = ((int) this.dataBytes[ this.pos ]) & 0xFF; // Seitenumbruch if( b == 0x0C ) { break; } // Zeile vorhanden this.pos++; if( buf == null ) { buf = new StringBuilder(); } // Zeilenende? if( (b == 0x0A) || (b == 0x0D) || (b == 0x1E) ) { if( b == 0x0D ) { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0A ) { this.pos++; } } } break; } if( (b != 0) && (b != 3) ) { buf.append( (char) b ); } } return buf != null ? buf.toString() : null; } public boolean skipFormFeed() { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0C ) { this.pos++; return true; } } return false; } public boolean skipLine() { boolean rv = false; while( this.pos < this.dataBytes.length ) { int b = ((int) this.dataBytes[ this.pos ]) & 0xFF; if( b == 0x0C ) { break; } // Zeile vorhanden this.pos++; rv = true; // Zeilenende? if( (b == 0x0A) || (b == 0x0D) || (b == 0x1E) ) { if( b == 0x0D ) { if( this.pos < this.dataBytes.length ) { if( this.dataBytes[ this.pos ] == 0x0A ) { this.pos++; } } } break; } } return rv; } }
gpl-3.0
McSinyx/hsg
usth/ICT2.2/labwork/5/Java/interface/Circle.java
247
public class Circle extends Point { public double r; public Circle(double x, double y, double r) { super(x, y); this.r = r; } public double calArea() { return r * r * Math.PI; } public String getName() { return "Circle"; } }
gpl-3.0
dbolshak/websocket
src/main/java/hello/GreetingController.java
505
package hello; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class GreetingController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(3000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } }
gpl-3.0
Consonance/consonance
consonance-webservice/src/main/java/io/swagger/wes/api/RFC3339DateFormat.java
565
package io.swagger.wes.api; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import com.fasterxml.jackson.databind.util.ISO8601Utils; import java.text.FieldPosition; import java.util.Date; public class RFC3339DateFormat extends ISO8601DateFormat { // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } }
gpl-3.0
NathanAdhitya/Slimefun4
src/me/mrCookieSlime/Slimefun/api/energy/EnergyFlowListener.java
167
package me.mrCookieSlime.Slimefun.api.energy; import org.bukkit.block.Block; @FunctionalInterface public interface EnergyFlowListener { void onPulse(Block b); }
gpl-3.0
odomin2/ait642-Dominguez-project2-
Task 13 Detect Desing Smells/Monopoly/src/edu/towson/cis/cosc603/project2/monopoly/TradeDeal.java
2213
package edu.towson.cis.cosc603.project2.monopoly; // TODO: Auto-generated Javadoc /** * The Class TradeDeal. */ public class TradeDeal { /** The amount. */ private int amount; /** The player index. */ private int playerIndex; /** The property name. */ private String propertyName; /** * Gets the amount. * * @return the amount */ public int getAmount() { return amount; } /** * Gets the player index. * * @return the player index */ public int getPlayerIndex() { return playerIndex; } /** * Gets the property name. * * @return the property name */ public String getPropertyName() { return propertyName; } /** * Make message. * * @return the string */ public String makeMessage() { String message = GameMaster.instance().getCurrentPlayer() + " wishes to purchase " + propertyName + " from " + GameMaster.instance().getPlayer(playerIndex) + " for " + amount + ". " + GameMaster.instance().getPlayer(playerIndex) + ", do you wish to trade your property?"; return message; } /** * Sets the amount. * * @param amount the new amount */ public void setAmount(int amount) { this.amount = amount; } /** * Sets the property name. * * @param propertyName the new property name */ public void setPropertyName(String propertyName) { this.propertyName = propertyName; } /** * Sets the seller index. * * @param playerIndex the new seller index */ public void setSellerIndex(int playerIndex) { this.playerIndex = playerIndex; } /** * Complete trade. * @param gameBoard * @param gameMaster */ public void completeTrade(GameBoard gameBoard, GameMaster gameMaster) { Player seller = gameMaster.getPlayer(getPlayerIndex()); Cell property = gameBoard.queryCell(getPropertyName()); seller.sellProperty(property, getAmount()); gameMaster.getCurrentPlayer().buyProperty(property, getAmount()); } }
gpl-3.0
servinglynk/hmis-lynk-open-source
hmis-base-model/src/main/java/com/servinglynk/hmis/warehouse/enums/DataCollectionStageEnum.java
1318
package com.servinglynk.hmis.warehouse.enums; import java.util.HashMap; import java.util.Map; public enum DataCollectionStageEnum { /** Enum Constant. */ ONE("1"), /** Enum Constant. */ TWO("2"), /** Enum Constant. */ THREE("3"), /** Enum Constant. */ FIVE("5"); /** * Internal storage of status field value, see the Enum spec for * clarification. */ private final String status; /** * Enum constructor for ActiveState. * @param state Value. */ DataCollectionStageEnum(final String state) { this.status = state; } /** Construct a map for reverse lookup. */ private static Map<String, DataCollectionStageEnum> valueMap = new HashMap<String, DataCollectionStageEnum>(); static { // construct hashmap for later possible use. for (DataCollectionStageEnum unit : values()) { valueMap.put(unit.getValue(), unit); } } /** * Current string value stored in the enum. * * @return string value. */ public String getValue() { return this.status; } /** * Perform a reverse lookup (given a value, obtain the enum). * * @param value to search * @return Enum object. */ public static DataCollectionStageEnum lookupEnum(String value) { return DataCollectionStageEnum.valueMap.get(value); } }
mpl-2.0
carlwilson/veraPDF-library
core/src/main/java/org/verapdf/features/tools/ErrorsHelper.java
3457
/** * This file is part of veraPDF Library core, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Library core is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Library core as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Library core as the LICENSE.MPL file in the root of the source tree. * 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.verapdf.features.tools; import java.util.logging.Level; import java.util.logging.Logger; import org.verapdf.core.FeatureParsingException; import org.verapdf.features.FeatureExtractionResult; import org.verapdf.features.FeatureObjectType; /** * Static class with constants for feature error ids and messages * * @author Maksim Bezrukov */ public final class ErrorsHelper { private static final FeatureObjectType TYPE = FeatureObjectType.ERROR; private static final Logger LOGGER = Logger.getLogger(ErrorsHelper.class.getName()); public static final String ERRORID = "errorId"; public static final String ID = "id"; private ErrorsHelper() { // Disable default public constructor } /** * Adds an error to a {@link FeaturesCollection} * * @param collection * the {@link FeaturesCollection} to add the error to * @param element * element which contains error * @param errorMessageArg * the error message * @return id of the generated error node as String */ public static String addErrorIntoCollection(FeatureExtractionResult collection, FeatureTreeNode element, String errorMessageArg) { if (collection == null) { throw new IllegalArgumentException("Collection can not be null"); } String errorMessage = errorMessageArg; if (errorMessage == null) { errorMessage = "Exception with null message."; } try { String id = null; for (FeatureTreeNode errNode : collection.getFeatureTreesForType(TYPE)) { if (errorMessage.equals(errNode.getValue())) { id = errNode.getAttributes().get(ID); break; } } if (id == null) { id = TYPE.getNodeName() + collection.getFeatureTreesForType(TYPE).size(); FeatureTreeNode error = FeatureTreeNode.createRootNode(TYPE.getNodeName()); error.setValue(errorMessage); error.setAttribute(ErrorsHelper.ID, id); collection.addNewFeatureTree(TYPE, error); } if (element != null) { String elementErrorID = id; if (element.getAttributes().get(ERRORID) != null) { elementErrorID = element.getAttributes().get(ERRORID) + ", " + elementErrorID; } element.setAttribute(ERRORID, elementErrorID); } return id; } catch (FeatureParsingException ignore) { // This exception occurs when wrong node creates for feature tree. // The logic of the method guarantees this doesn't occur. String message = "FeatureTreeNode root instance logic failure"; LOGGER.log(Level.SEVERE, message, ignore); throw new IllegalStateException(message, ignore); } } }
mpl-2.0
miloszpiglas/h2mod
src/main/org/h2/command/dml/Call.java
3050
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.command.dml; import java.sql.ResultSet; import org.h2.command.CommandInterface; import org.h2.command.Prepared; import org.h2.engine.Session; import org.h2.expression.Expression; import org.h2.expression.ExpressionVisitor; import org.h2.result.LocalResult; import org.h2.result.ResultInterface; import org.h2.value.Value; /** * This class represents the statement * CALL. */ public class Call extends Prepared { private boolean isResultSet; private Expression expression; private Expression[] expressions; public Call(Session session) { super(session); } @Override public ResultInterface queryMeta() { LocalResult result; if (isResultSet) { Expression[] expr = expression.getExpressionColumns(session); result = new LocalResult(session, expr, expr.length); } else { result = new LocalResult(session, expressions, 1); } result.done(); return result; } @Override public int update() { Value v = expression.getValue(session); int type = v.getType(); switch(type) { case Value.RESULT_SET: // this will throw an exception // methods returning a result set may not be called like this. return super.update(); case Value.UNKNOWN: case Value.NULL: return 0; default: return v.getInt(); } } @Override public ResultInterface query(int maxrows) { setCurrentRowNumber(1); Value v = expression.getValue(session); if (isResultSet) { v = v.convertTo(Value.RESULT_SET); ResultSet rs = v.getResultSet(); return LocalResult.read(session, rs, maxrows); } LocalResult result = new LocalResult(session, expressions, 1); Value[] row = { v }; result.addRow(row); result.done(); return result; } @Override public void prepare() { expression = expression.optimize(session); expressions = new Expression[] { expression }; isResultSet = expression.getType() == Value.RESULT_SET; if (isResultSet) { prepareAlways = true; } } public void setExpression(Expression expression) { this.expression = expression; } @Override public boolean isQuery() { return true; } @Override public boolean isTransactional() { return true; } @Override public boolean isReadOnly() { return expression.isEverything(ExpressionVisitor.READONLY_VISITOR); } @Override public int getType() { return CommandInterface.CALL; } @Override public boolean isCacheable() { return !isResultSet; } }
mpl-2.0
Tanaguru/Tanaguru
rules/accessiweb2.1/src/main/java/org/tanaguru/rules/accessiweb21/Aw21Rule10011.java
2892
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.accessiweb21; import org.tanaguru.entity.audit.ProcessResult; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.entity.reference.Nomenclature; import org.tanaguru.processor.SSPHandler; import org.tanaguru.ruleimplementation.AbstractPageRuleImplementation; import org.w3c.dom.Node; /** * This rule tests if forbidden representation tags are used in the source * code. * We use the specific nomenclature "DeprecatedRepresentationTags" to determine * the presence of these * @author jkowalczyk */ public class Aw21Rule10011 extends AbstractPageRuleImplementation { private static final String XPATH_EXPR = "//*"; private static final String MESSAGE_CODE = "DeprecatedRepresentationTagFound"; private static final String DEPREC_TAG_NOM = "DeprecatedRepresentationTags"; public Aw21Rule10011() { super(); } /** * * @param sspHandler * @return */ @Override protected ProcessResult processImpl(SSPHandler sspHandler) { Nomenclature deprecatedHtmlTags = nomenclatureLoaderService. loadByCode(DEPREC_TAG_NOM); sspHandler.beginSelection(). selectDocumentNodes(deprecatedHtmlTags.getValueList()); TestSolution testSolution = TestSolution.PASSED; for (Node node : sspHandler.getSelectedElementList()) { testSolution = TestSolution.FAILED; sspHandler.getProcessRemarkService().addSourceCodeRemark( testSolution, node, MESSAGE_CODE, node.getNodeName()); } ProcessResult processResult = definiteResultFactory.create( test, sspHandler.getPage(), testSolution, sspHandler.getRemarkList()); processResult.setElementCounter( sspHandler.beginSelection().domXPathSelectNodeSet(XPATH_EXPR). getSelectedElementList().size()); return processResult; } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/chooseandbook/vo/domain/ConvPointVoAssembler.java
17066
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.chooseandbook.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Barbara Worwood */ public class ConvPointVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.chooseandbook.vo.ConvPointVo copy(ims.chooseandbook.vo.ConvPointVo valueObjectDest, ims.chooseandbook.vo.ConvPointVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_ConvPoint(valueObjectSrc.getID_ConvPoint()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // convId valueObjectDest.setConvId(valueObjectSrc.getConvId()); // msgDetails valueObjectDest.setMsgDetails(valueObjectSrc.getMsgDetails()); // creationDate valueObjectDest.setCreationDate(valueObjectSrc.getCreationDate()); 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 #createConvPointVoCollectionFromConvPoint(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(java.util.Set domainObjectSet) { return createConvPointVoCollectionFromConvPoint(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.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(DomainObjectMap map, java.util.Set domainObjectSet) { ims.chooseandbook.vo.ConvPointVoCollection voList = new ims.chooseandbook.vo.ConvPointVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.choose_book.domain.objects.ConvPoint domainObject = (ims.choose_book.domain.objects.ConvPoint) iterator.next(); ims.chooseandbook.vo.ConvPointVo 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.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(java.util.List domainObjectList) { return createConvPointVoCollectionFromConvPoint(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.choose_book.domain.objects.ConvPoint objects. */ public static ims.chooseandbook.vo.ConvPointVoCollection createConvPointVoCollectionFromConvPoint(DomainObjectMap map, java.util.List domainObjectList) { ims.chooseandbook.vo.ConvPointVoCollection voList = new ims.chooseandbook.vo.ConvPointVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.choose_book.domain.objects.ConvPoint domainObject = (ims.choose_book.domain.objects.ConvPoint) domainObjectList.get(i); ims.chooseandbook.vo.ConvPointVo 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.choose_book.domain.objects.ConvPoint 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 extractConvPointSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection) { return extractConvPointSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractConvPointSet(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection 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.chooseandbook.vo.ConvPointVo vo = voCollection.get(i); ims.choose_book.domain.objects.ConvPoint domainObject = ConvPointVoAssembler.extractConvPoint(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.choose_book.domain.objects.ConvPoint 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 extractConvPointList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection voCollection) { return extractConvPointList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractConvPointList(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVoCollection 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.chooseandbook.vo.ConvPointVo vo = voCollection.get(i); ims.choose_book.domain.objects.ConvPoint domainObject = ConvPointVoAssembler.extractConvPoint(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.choose_book.domain.objects.ConvPoint object. * @param domainObject ims.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo create(ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.choose_book.domain.objects.ConvPoint object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.chooseandbook.vo.ConvPointVo create(DomainObjectMap map, ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.chooseandbook.vo.ConvPointVo valueObject = (ims.chooseandbook.vo.ConvPointVo) map.getValueObject(domainObject, ims.chooseandbook.vo.ConvPointVo.class); if ( null == valueObject ) { valueObject = new ims.chooseandbook.vo.ConvPointVo(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.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo insert(ims.chooseandbook.vo.ConvPointVo valueObject, ims.choose_book.domain.objects.ConvPoint 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.choose_book.domain.objects.ConvPoint */ public static ims.chooseandbook.vo.ConvPointVo insert(DomainObjectMap map, ims.chooseandbook.vo.ConvPointVo valueObject, ims.choose_book.domain.objects.ConvPoint domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_ConvPoint(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; // convId valueObject.setConvId(ims.chooseandbook.vo.domain.ConvIdVoAssembler.create(map, domainObject.getConvId()) ); // msgDetails valueObject.setMsgDetails(domainObject.getMsgDetails()); // creationDate java.util.Date creationDate = domainObject.getCreationDate(); if ( null != creationDate ) { valueObject.setCreationDate(new ims.framework.utils.Date(creationDate) ); } 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.choose_book.domain.objects.ConvPoint extractConvPoint(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVo valueObject) { return extractConvPoint(domainFactory, valueObject, new HashMap()); } public static ims.choose_book.domain.objects.ConvPoint extractConvPoint(ims.domain.ILightweightDomainFactory domainFactory, ims.chooseandbook.vo.ConvPointVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_ConvPoint(); ims.choose_book.domain.objects.ConvPoint domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.choose_book.domain.objects.ConvPoint)domMap.get(valueObject); } // ims.chooseandbook.vo.ConvPointVo ID_ConvPoint field is unknown domainObject = new ims.choose_book.domain.objects.ConvPoint(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_ConvPoint()); if (domMap.get(key) != null) { return (ims.choose_book.domain.objects.ConvPoint)domMap.get(key); } domainObject = (ims.choose_book.domain.objects.ConvPoint) domainFactory.getDomainObject(ims.choose_book.domain.objects.ConvPoint.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_ConvPoint()); domainObject.setConvId(ims.chooseandbook.vo.domain.ConvIdVoAssembler.extractConvId(domainFactory, valueObject.getConvId(), domMap)); //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.getMsgDetails() != null && valueObject.getMsgDetails().equals("")) { valueObject.setMsgDetails(null); } domainObject.setMsgDetails(valueObject.getMsgDetails()); java.util.Date value3 = null; ims.framework.utils.Date date3 = valueObject.getCreationDate(); if ( date3 != null ) { value3 = date3.getDate(); } domainObject.setCreationDate(value3); return domainObject; } }
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/Perspective.java
5452
/* * 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; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import com.rapidminer.tools.FileSystemService; import com.rapidminer.tools.I18N; import com.rapidminer.tools.LogService; import com.vlsolutions.swing.docking.DockingContext; import com.vlsolutions.swing.docking.ws.Workspace; import com.vlsolutions.swing.docking.ws.WorkspaceException; /** * * @author Simon Fischer * */ public class Perspective { private final String name; private final Workspace workspace = new Workspace(); private boolean userDefined = false;; private final ApplicationPerspectives owner; public Perspective(ApplicationPerspectives owner, String name) { this.name = name; this.owner = owner; } public String getName() { return name; } public Workspace getWorkspace() { return workspace; } public void store(DockingContext dockingContext) { try { workspace.loadFrom(dockingContext); } catch (WorkspaceException e) { //LogService.getRoot().log(Level.WARNING, "Cannot save workspace: "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.saving_workspace_error", e), e); } } protected void apply(DockingContext dockingContext) { try { workspace.apply(dockingContext); } catch (WorkspaceException e) { //LogService.getRoot().log(Level.WARNING, "Cannot apply workspace: "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.applying_workspace_error", e), e); } } File getFile() { return FileSystemService.getUserConfigFile("vlperspective-"+(isUserDefined()?"user-":"predefined-")+name+".xml"); } public void save() { File file = getFile(); OutputStream out = null; try { out = new FileOutputStream(file); workspace.writeXML(out); } catch (Exception e) { //LogService.getRoot().log(Level.WARNING, "Cannot save perspective to "+file+": "+e, e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.saving_perspective_error", file, e), e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { } } } public void load() { //LogService.getRoot().fine("Loading perspective: "+getName()); LogService.getRoot().log(Level.FINE, "com.rapidminer.gui.Perspective.loading_perspective", getName()); File file = getFile(); if (!file.exists()) { return; } InputStream in = null; try { in = new FileInputStream(file); workspace.readXML(in); } catch (Exception e) { if (!userDefined) { //LogService.getRoot().log(Level.WARNING, "Cannot read perspective from "+file+": "+e+". Restoring default.", e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.reading_perspective_error_restoring", file, e), e); owner.restoreDefault(getName()); } else { //LogService.getRoot().log(Level.WARNING, "Cannot read perspective from "+file+": "+e+". Clearing perspective.", e); LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapidminer.gui.Perspective.reading_perspective_error_clearing", file, e), e); workspace.clear(); } } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } } } public void setUserDefined(boolean b) { this.userDefined = b; } public boolean isUserDefined() { return this.userDefined; } public void delete() { File file = getFile(); if (file.exists()) { file.delete(); } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Nursing/src/ims/nursing/forms/careplanreviewdialog/BaseLogic.java
2663
//############################################################################# //# # //# 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.nursing.forms.careplanreviewdialog; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.nursing.domain.CarePlanReviewDialog.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.nursing.domain.CarePlanReviewDialog domain) { setContext(engine, form); this.domain = domain; } public final void free() { super.free(); domain = null; } protected ims.nursing.domain.CarePlanReviewDialog domain; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/PatientProcedureProcsComponentLiteVoAssembler.java
18393
//############################################################################# //# # //# 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 * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Ander Telleria */ public class PatientProcedureProcsComponentLiteVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo copy(ims.core.vo.PatientProcedureProcsComponentLiteVo valueObjectDest, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_PatientProcedure(valueObjectSrc.getID_PatientProcedure()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // ProcedureDescription valueObjectDest.setProcedureDescription(valueObjectSrc.getProcedureDescription()); // AuthoringInformation valueObjectDest.setAuthoringInformation(valueObjectSrc.getAuthoringInformation()); // includeInDischargeLetter valueObjectDest.setIncludeInDischargeLetter(valueObjectSrc.getIncludeInDischargeLetter()); // ProcDate valueObjectDest.setProcDate(valueObjectSrc.getProcDate()); 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 #createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(java.util.Set domainObjectSet) { return createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voList = new ims.core.vo.PatientProcedureProcsComponentLiteVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) iterator.next(); ims.core.vo.PatientProcedureProcsComponentLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(java.util.List domainObjectList) { return createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.clinical.domain.objects.PatientProcedure objects. */ public static ims.core.vo.PatientProcedureProcsComponentLiteVoCollection createPatientProcedureProcsComponentLiteVoCollectionFromPatientProcedure(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voList = new ims.core.vo.PatientProcedureProcsComponentLiteVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.clinical.domain.objects.PatientProcedure domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainObjectList.get(i); ims.core.vo.PatientProcedureProcsComponentLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.clinical.domain.objects.PatientProcedure 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 extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection) { return extractPatientProcedureSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractPatientProcedureSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection 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.core.vo.PatientProcedureProcsComponentLiteVo vo = voCollection.get(i); ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureProcsComponentLiteVoAssembler.extractPatientProcedure(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.clinical.domain.objects.PatientProcedure 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 extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection voCollection) { return extractPatientProcedureList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractPatientProcedureList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVoCollection 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.core.vo.PatientProcedureProcsComponentLiteVo vo = voCollection.get(i); ims.core.clinical.domain.objects.PatientProcedure domainObject = PatientProcedureProcsComponentLiteVoAssembler.extractPatientProcedure(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object. * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo create(ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.clinical.domain.objects.PatientProcedure object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo create(DomainObjectMap map, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject = (ims.core.vo.PatientProcedureProcsComponentLiteVo) map.getValueObject(domainObject, ims.core.vo.PatientProcedureProcsComponentLiteVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.PatientProcedureProcsComponentLiteVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo insert(ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.PatientProcedure */ public static ims.core.vo.PatientProcedureProcsComponentLiteVo insert(DomainObjectMap map, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, ims.core.clinical.domain.objects.PatientProcedure domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_PatientProcedure(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; // ProcedureDescription valueObject.setProcedureDescription(domainObject.getProcedureDescription()); // AuthoringInformation valueObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInformation()) ); // includeInDischargeLetter valueObject.setIncludeInDischargeLetter( domainObject.isIncludeInDischargeLetter() ); // ProcDate Integer ProcDate = domainObject.getProcDate(); if ( null != ProcDate ) { valueObject.setProcDate(new ims.framework.utils.PartialDate(ProcDate) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject) { return extractPatientProcedure(domainFactory, valueObject, new HashMap()); } public static ims.core.clinical.domain.objects.PatientProcedure extractPatientProcedure(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.PatientProcedureProcsComponentLiteVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_PatientProcedure(); ims.core.clinical.domain.objects.PatientProcedure domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(valueObject); } // ims.core.vo.PatientProcedureProcsComponentLiteVo ID_PatientProcedure field is unknown domainObject = new ims.core.clinical.domain.objects.PatientProcedure(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_PatientProcedure()); if (domMap.get(key) != null) { return (ims.core.clinical.domain.objects.PatientProcedure)domMap.get(key); } domainObject = (ims.core.clinical.domain.objects.PatientProcedure) domainFactory.getDomainObject(ims.core.clinical.domain.objects.PatientProcedure.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_PatientProcedure()); //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.getProcedureDescription() != null && valueObject.getProcedureDescription().equals("")) { valueObject.setProcedureDescription(null); } domainObject.setProcedureDescription(valueObject.getProcedureDescription()); domainObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.extractAuthoringInformation(domainFactory, valueObject.getAuthoringInformation(), domMap)); domainObject.setIncludeInDischargeLetter(valueObject.getIncludeInDischargeLetter()); ims.framework.utils.PartialDate ProcDate = valueObject.getProcDate(); Integer value4 = null; if ( null != ProcDate ) { value4 = ProcDate.toInteger(); } domainObject.setProcDate(value4); return domainObject; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/ocs_if/vo/DemographicsMessageQueueVo.java
15375
//############################################################################# //# # //# 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.ocs_if.vo; /** * Linked to Hl7ADTOut.DemographicsMessageQueue business object (ID: 1103100000). */ public class DemographicsMessageQueueVo extends ims.hl7adtout.vo.DemographicsMessageQueueRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public DemographicsMessageQueueVo() { } public DemographicsMessageQueueVo(Integer id, int version) { super(id, version); } public DemographicsMessageQueueVo(ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean 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.providersystem = bean.getProviderSystem() == null ? null : new ims.core.admin.vo.ProviderSystemRefVo(new Integer(bean.getProviderSystem().getId()), bean.getProviderSystem().getVersion()); this.wasprocessed = bean.getWasProcessed(); this.wasdiscarded = bean.getWasDiscarded(); this.msgtext = bean.getMsgText(); this.acktext = bean.getAckText(); this.failuremsg = bean.getFailureMsg(); this.messagestatus = bean.getMessageStatus() == null ? null : ims.ocrr.vo.lookups.OrderMessageStatus.buildLookup(bean.getMessageStatus()); this.msgtype = bean.getMsgType() == null ? null : ims.core.vo.lookups.MsgEventType.buildLookup(bean.getMsgType()); this.queuetype = bean.getQueueType() == null ? null : ims.core.vo.lookups.QueueType.buildLookup(bean.getQueueType()); this.priorpatient = bean.getPriorPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPriorPatient().getId()), bean.getPriorPatient().getVersion()); this.mergehistory = bean.getMergeHistory() == null ? null : new ims.core.patient.vo.PatientMergeHistoryRefVo(new Integer(bean.getMergeHistory().getId()), bean.getMergeHistory().getVersion()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean 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.providersystem = bean.getProviderSystem() == null ? null : new ims.core.admin.vo.ProviderSystemRefVo(new Integer(bean.getProviderSystem().getId()), bean.getProviderSystem().getVersion()); this.wasprocessed = bean.getWasProcessed(); this.wasdiscarded = bean.getWasDiscarded(); this.msgtext = bean.getMsgText(); this.acktext = bean.getAckText(); this.failuremsg = bean.getFailureMsg(); this.messagestatus = bean.getMessageStatus() == null ? null : ims.ocrr.vo.lookups.OrderMessageStatus.buildLookup(bean.getMessageStatus()); this.msgtype = bean.getMsgType() == null ? null : ims.core.vo.lookups.MsgEventType.buildLookup(bean.getMsgType()); this.queuetype = bean.getQueueType() == null ? null : ims.core.vo.lookups.QueueType.buildLookup(bean.getQueueType()); this.priorpatient = bean.getPriorPatient() == null ? null : new ims.core.patient.vo.PatientRefVo(new Integer(bean.getPriorPatient().getId()), bean.getPriorPatient().getVersion()); this.mergehistory = bean.getMergeHistory() == null ? null : new ims.core.patient.vo.PatientMergeHistoryRefVo(new Integer(bean.getMergeHistory().getId()), bean.getMergeHistory().getVersion()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean bean = null; if(map != null) bean = (ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.ocs_if.vo.beans.DemographicsMessageQueueVoBean(); 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("PROVIDERSYSTEM")) return getProviderSystem(); if(fieldName.equals("WASPROCESSED")) return getWasProcessed(); if(fieldName.equals("WASDISCARDED")) return getWasDiscarded(); if(fieldName.equals("MSGTEXT")) return getMsgText(); if(fieldName.equals("ACKTEXT")) return getAckText(); if(fieldName.equals("FAILUREMSG")) return getFailureMsg(); if(fieldName.equals("MESSAGESTATUS")) return getMessageStatus(); if(fieldName.equals("MSGTYPE")) return getMsgType(); if(fieldName.equals("QUEUETYPE")) return getQueueType(); if(fieldName.equals("PRIORPATIENT")) return getPriorPatient(); if(fieldName.equals("MERGEHISTORY")) return getMergeHistory(); 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 getProviderSystemIsNotNull() { return this.providersystem != null; } public ims.core.admin.vo.ProviderSystemRefVo getProviderSystem() { return this.providersystem; } public void setProviderSystem(ims.core.admin.vo.ProviderSystemRefVo value) { this.isValidated = false; this.providersystem = value; } public boolean getWasProcessedIsNotNull() { return this.wasprocessed != null; } public Boolean getWasProcessed() { return this.wasprocessed; } public void setWasProcessed(Boolean value) { this.isValidated = false; this.wasprocessed = value; } public boolean getWasDiscardedIsNotNull() { return this.wasdiscarded != null; } public Boolean getWasDiscarded() { return this.wasdiscarded; } public void setWasDiscarded(Boolean value) { this.isValidated = false; this.wasdiscarded = value; } public boolean getMsgTextIsNotNull() { return this.msgtext != null; } public String getMsgText() { return this.msgtext; } public static int getMsgTextMaxLength() { return 4000; } public void setMsgText(String value) { this.isValidated = false; this.msgtext = value; } public boolean getAckTextIsNotNull() { return this.acktext != null; } public String getAckText() { return this.acktext; } public static int getAckTextMaxLength() { return 1000; } public void setAckText(String value) { this.isValidated = false; this.acktext = value; } public boolean getFailureMsgIsNotNull() { return this.failuremsg != null; } public String getFailureMsg() { return this.failuremsg; } public static int getFailureMsgMaxLength() { return 1000; } public void setFailureMsg(String value) { this.isValidated = false; this.failuremsg = value; } public boolean getMessageStatusIsNotNull() { return this.messagestatus != null; } public ims.ocrr.vo.lookups.OrderMessageStatus getMessageStatus() { return this.messagestatus; } public void setMessageStatus(ims.ocrr.vo.lookups.OrderMessageStatus value) { this.isValidated = false; this.messagestatus = value; } public boolean getMsgTypeIsNotNull() { return this.msgtype != null; } public ims.core.vo.lookups.MsgEventType getMsgType() { return this.msgtype; } public void setMsgType(ims.core.vo.lookups.MsgEventType value) { this.isValidated = false; this.msgtype = value; } public boolean getQueueTypeIsNotNull() { return this.queuetype != null; } public ims.core.vo.lookups.QueueType getQueueType() { return this.queuetype; } public void setQueueType(ims.core.vo.lookups.QueueType value) { this.isValidated = false; this.queuetype = value; } public boolean getPriorPatientIsNotNull() { return this.priorpatient != null; } public ims.core.patient.vo.PatientRefVo getPriorPatient() { return this.priorpatient; } public void setPriorPatient(ims.core.patient.vo.PatientRefVo value) { this.isValidated = false; this.priorpatient = value; } public boolean getMergeHistoryIsNotNull() { return this.mergehistory != null; } public ims.core.patient.vo.PatientMergeHistoryRefVo getMergeHistory() { return this.mergehistory; } public void setMergeHistory(ims.core.patient.vo.PatientMergeHistoryRefVo value) { this.isValidated = false; this.mergehistory = 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.acktext != null) if(this.acktext.length() > 1000) listOfErrors.add("The length of the field [acktext] in the value object [ims.ocs_if.vo.DemographicsMessageQueueVo] is too big. It should be less or equal to 1000"); if(this.failuremsg != null) if(this.failuremsg.length() > 1000) listOfErrors.add("The length of the field [failuremsg] in the value object [ims.ocs_if.vo.DemographicsMessageQueueVo] is too big. It should be less or equal to 1000"); if(this.msgtype == null) listOfErrors.add("msgType 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; DemographicsMessageQueueVo clone = new DemographicsMessageQueueVo(this.id, this.version); clone.patient = this.patient; clone.providersystem = this.providersystem; clone.wasprocessed = this.wasprocessed; clone.wasdiscarded = this.wasdiscarded; clone.msgtext = this.msgtext; clone.acktext = this.acktext; clone.failuremsg = this.failuremsg; if(this.messagestatus == null) clone.messagestatus = null; else clone.messagestatus = (ims.ocrr.vo.lookups.OrderMessageStatus)this.messagestatus.clone(); if(this.msgtype == null) clone.msgtype = null; else clone.msgtype = (ims.core.vo.lookups.MsgEventType)this.msgtype.clone(); if(this.queuetype == null) clone.queuetype = null; else clone.queuetype = (ims.core.vo.lookups.QueueType)this.queuetype.clone(); clone.priorpatient = this.priorpatient; clone.mergehistory = this.mergehistory; 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 (!(DemographicsMessageQueueVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A DemographicsMessageQueueVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((DemographicsMessageQueueVo)obj).getBoId() == null) return -1; return this.id.compareTo(((DemographicsMessageQueueVo)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.providersystem != null) count++; if(this.wasprocessed != null) count++; if(this.wasdiscarded != null) count++; if(this.msgtext != null) count++; if(this.acktext != null) count++; if(this.failuremsg != null) count++; if(this.messagestatus != null) count++; if(this.msgtype != null) count++; if(this.queuetype != null) count++; if(this.priorpatient != null) count++; if(this.mergehistory != null) count++; return count; } public int countValueObjectFields() { return 12; } protected ims.core.patient.vo.PatientRefVo patient; protected ims.core.admin.vo.ProviderSystemRefVo providersystem; protected Boolean wasprocessed; protected Boolean wasdiscarded; protected String msgtext; protected String acktext; protected String failuremsg; protected ims.ocrr.vo.lookups.OrderMessageStatus messagestatus; protected ims.core.vo.lookups.MsgEventType msgtype; protected ims.core.vo.lookups.QueueType queuetype; protected ims.core.patient.vo.PatientRefVo priorpatient; protected ims.core.patient.vo.PatientMergeHistoryRefVo mergehistory; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
medsob/Tanaguru
rules/rgaa2.2/src/test/java/org/tanaguru/rules/rgaa22/Rgaa22Rule12101Test.java
3959
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.rules.rgaa22; import org.tanaguru.entity.audit.TestSolution; import org.tanaguru.rules.rgaa22.test.Rgaa22RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 12.10 of the referential RGAA 2.2. * * @author jkowalczyk */ public class Rgaa22Rule12101Test extends Rgaa22RuleImplementationTestCase { /** * Default constructor */ public Rgaa22Rule12101Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.tanaguru.rules.rgaa22.Rgaa22Rule12101"); } @Override protected void setUpWebResourceMap() { // getWebResourceMap().put("Rgaa22.Test.12.10-1Passed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule12101/RGAA22.Test.12.10-1Passed-01.html")); // getWebResourceMap().put("Rgaa22.Test.12.10-2Failed-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule12101/RGAA22.Test.12.10-2Failed-01.html")); // getWebResourceMap().put("Rgaa22.Test.12.10-3NMI-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule12101/RGAA22.Test.12.10-3NMI-01.html")); // getWebResourceMap().put("Rgaa22.Test.12.10-4NA-01", // getWebResourceFactory().createPage( // getTestcasesFilePath() + "rgaa22/Rgaa22Rule12101/RGAA22.Test.12.10-4NA-01.html")); getWebResourceMap().put("Rgaa22.Test.12.10-5NT-01", getWebResourceFactory().createPage( getTestcasesFilePath() + "rgaa22/Rgaa22Rule12101/RGAA22.Test.12.10-5NT-01.html")); } @Override protected void setProcess() { // assertEquals(TestSolution.PASSED, // processPageTest("Rgaa22.Test.12.10-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // processPageTest("Rgaa22.Test.12.10-2Failed-01").getValue()); // assertEquals(TestSolution.NEED_MORE_INFO, // processPageTest("Rgaa22.Test.12.10-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // processPageTest("Rgaa22.Test.12.10-4NA-01").getValue()); assertEquals(TestSolution.NOT_TESTED, processPageTest("Rgaa22.Test.12.10-5NT-01").getValue()); } @Override protected void setConsolidate() { // assertEquals(TestSolution.PASSED, // consolidate("Rgaa22.Test.12.10-1Passed-01").getValue()); // assertEquals(TestSolution.FAILED, // consolidate("Rgaa22.Test.12.10-2Failed-01").getValue()); // assertEquals(TestSolution.NEED_MORE_INFO, // consolidate("Rgaa22.Test.12.10-3NMI-01").getValue()); // assertEquals(TestSolution.NOT_APPLICABLE, // consolidate("Rgaa22.Test.12.10-4NA-01").getValue()); assertEquals(TestSolution.NOT_TESTED, consolidate("Rgaa22.Test.12.10-5NT-01").getValue()); } }
agpl-3.0
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
lib/fmj/src/javax/media/pim/PlugInManager.java
8977
package javax.media.pim; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.Codec; import javax.media.Demultiplexer; import javax.media.Effect; import javax.media.Format; import javax.media.Multiplexer; import javax.media.Renderer; import net.sf.fmj.media.RegistryDefaults; import net.sf.fmj.utility.Registry; import net.sf.fmj.utility.LoggerSingleton; /** * In progress. * @author Ken Larson * */ public class PlugInManager extends javax.media.PlugInManager { private static final Logger logger = LoggerSingleton.logger; private static boolean TRACE = false; // TODO: what exactly is stored in the properties? just the class names, or the formats as well? // the properties files appears to be binary, an appears to be created using java serialization. // seems like it contains the formats. // TODO: implement efficiently using maps /** * Vectors of classname Strings. This is sorted in the order that plugins must be searched. */ private static final Vector[] classLists = new Vector[] { new Vector(), new Vector(), new Vector(), new Vector(), new Vector() }; /** * Maps of classnames to PluginInfo */ private static final HashMap[] pluginMaps = new HashMap[] { new HashMap(), new HashMap(), new HashMap(), new HashMap(), new HashMap(), }; /** * The registry that persists the data. */ private static Registry registry = Registry.getInstance(); static { try { if (TRACE) logger.info("initializing..."); // populate vectors with info from the persisted registry for (int i=0; i<5; i++) { Vector classList = classLists[i]; HashMap pluginMap = pluginMaps[i]; Iterator pluginIter = registry.getPluginList(i+1).iterator(); while (pluginIter.hasNext()) { // PlugInInfo info = (PlugInInfo) pluginIter.next(); // classList.add(info.className); // pluginMap.put(info.className, info); // registry only contains classnames, not in and out formats String classname = (String) pluginIter.next(); classList.add(classname); PlugInInfo info = getPluginInfo(classname); if (info != null) { pluginMap.put(info.className, info); } } } boolean jmfDefaults = false; try { jmfDefaults = System.getProperty("net.sf.fmj.utility.JmfRegistry.JMFDefaults", "false").equals("true"); } catch (SecurityException e) { // we must be an applet. } final int flags = jmfDefaults ? RegistryDefaults.JMF : RegistryDefaults.ALL; RegistryDefaults.registerPlugins(flags); } catch (Throwable t) { logger.log(Level.SEVERE, "Unable to initialize javax.media.pim.PlugInManager (static): " + t, t); throw new RuntimeException(t); } } /** * Private constructor so that is can not be constructed. * In JMF it is public, but this is an implementation detail that is * not important for FMJ compatibility. */ private PlugInManager() { } /** * Get a list of plugins that match the given input and output formats. * * @param input * @param output * @param type * @return A Vector of classnames */ public static synchronized Vector<String> getPlugInList(Format input, Format output, int type) { if (TRACE) logger.info("getting plugin list..."); if (!isValid(type)) { return new Vector<String>(); } final Vector<String> result = new Vector<String>(); final Vector<String> classList = getVector(type); final HashMap pluginMap = pluginMaps[type-1]; for (int i = 0; i < classList.size(); ++i) { final Object classname = classList.get(i); final PlugInInfo plugInInfo = (PlugInInfo) pluginMap.get(classname); if (plugInInfo == null) continue; if (input != null) { if (plugInInfo.inputFormats == null) { continue; } boolean match = false; for (int j = 0; j < plugInInfo.inputFormats.length; ++j) { if (input.matches(plugInInfo.inputFormats[j])) { match = true; break; } } if (!match) { continue; } } if (output != null) { if (plugInInfo.outputFormats == null) { continue; } boolean match = false; for (int j = 0; j < plugInInfo.outputFormats.length; ++j) { if (output.matches(plugInInfo.outputFormats[j])) { match = true; break; } } if (!match) { continue; } } // matched both input and output formats result.add(plugInInfo.className); } return result; } /** * according to the docs, sets the search order. does not appear to add new plugins. * * @param plugins * @param type */ public static synchronized void setPlugInList(Vector plugins, int type) { // the vector to affect Vector vector = classLists[type - 1]; // The following code does not appear to be consistent with JMF. More testing needed: // if ( vector.size() != plugins.size() || !vector.containsAll(plugins) ) { // // extra or missing classname(s) given // logger.warning("setPlugInList: extra or missing classname(s) given"); // return; // } // reorder vector vector.clear(); vector.addAll(plugins); registry.setPluginList(type, plugins); } public static synchronized void commit() throws java.io.IOException { registry.commit(); } public static synchronized boolean addPlugIn(String classname, Format[] in, Format[] out, int type) { try { Class.forName(classname); } catch (ClassNotFoundException e) { logger.finer("addPlugIn failed for nonexistant class: " + classname); return false; // class does not exist. } catch (Throwable t) { logger.log(Level.WARNING, "Unable to addPlugIn for " + classname + " due to inability to get its class: " + t, t); return false; } if (find(classname, type) != null) { return false; // already there. } final PlugInInfo plugInInfo = new PlugInInfo(classname, in, out); Vector classList = classLists[type - 1]; HashMap pluginMap = pluginMaps[type-1]; // add to end of ordered list classList.add(classname); // add to PluginInfo map pluginMap.put(classname, plugInInfo); registry.setPluginList(type, classList); return true; } public static synchronized boolean removePlugIn(String classname, int type) { Vector classList = classLists[type-1]; HashMap pluginMap = pluginMaps[type-1]; boolean result = classList.remove(classname) || (pluginMap.remove(classname) != null); registry.setPluginList(type, classList); return result; } public static synchronized Format[] getSupportedInputFormats(String className, int type) { final PlugInInfo pi = find(className, type); if (pi == null) { return null; } return pi.inputFormats; } public static synchronized Format[] getSupportedOutputFormats(String className, int type) { final PlugInInfo pi = find(className, type); if (pi == null) return null; return pi.outputFormats; } private static boolean isValid(int type) { return type >= 1 && type <= 5; } private static Vector<String> getVector(int type) { if (!isValid(type)) { return null; } return (Vector<String>) classLists[type - 1]; } private static synchronized PlugInInfo find(String classname, int type) { PlugInInfo info = (PlugInInfo) pluginMaps[type-1].get(classname); return info; } private static final PlugInInfo getPluginInfo(String pluginName) { Object pluginObject; try { Class cls = Class.forName(pluginName); pluginObject = cls.newInstance(); } catch (ClassNotFoundException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } catch (InstantiationException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } catch (IllegalAccessException e) { logger.warning("Problem loading plugin " + pluginName + ": " + e.getMessage()); return null; } Format[] in = null; Format[] out = null; if (pluginObject instanceof Demultiplexer) { Demultiplexer demux = (Demultiplexer) pluginObject; in = demux.getSupportedInputContentDescriptors(); } else if (pluginObject instanceof Codec) { Codec codec = (Codec) pluginObject; in = codec.getSupportedInputFormats(); out = codec.getSupportedOutputFormats(null); } else if (pluginObject instanceof Multiplexer) { Multiplexer mux = (Multiplexer) pluginObject; in = mux.getSupportedInputFormats(); out = mux.getSupportedOutputContentDescriptors(null); } else if (pluginObject instanceof Renderer) { Renderer renderer = (Renderer) pluginObject; in = renderer.getSupportedInputFormats(); out = null; } else if (pluginObject instanceof Effect) { Effect effect = (Effect) pluginObject; in = effect.getSupportedInputFormats(); out = effect.getSupportedOutputFormats(null); } return new PlugInInfo(pluginName, in, out); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/beans/CancerCarePlanVoBean.java
11691
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo.beans; public class CancerCarePlanVoBean extends ims.vo.ValueObjectBean { public CancerCarePlanVoBean() { } public CancerCarePlanVoBean(ims.oncology.vo.CancerCarePlanVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.clinicalcontact = vo.getClinicalContact() == null ? null : (ims.core.vo.beans.ClinicalContactShortVoBean)vo.getClinicalContact().getBean(); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(); this.careplandate = vo.getCarePlanDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getCarePlanDate().getBean(); this.consultantincharge = vo.getConsultantInCharge() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getConsultantInCharge().getBean(); this.careplanintent = vo.getCarePlanIntent() == null ? null : (ims.vo.LookupInstanceBean)vo.getCarePlanIntent().getBean(); this.recurrenceindicator = vo.getRecurrenceIndicator() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceIndicator().getBean(); this.iscurrent = vo.getIsCurrent(); this.mdtmeeting = vo.getMdtMeeting() == null ? null : (ims.oncology.vo.beans.CancerMDTMeetingVoBean)vo.getMdtMeeting().getBean(); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); this.careplannotes = vo.getCarePlanNotes(); this.treatmentmodalities = vo.getTreatmentModalities() == null ? null : vo.getTreatmentModalities().getBeanCollection(); this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getCurrentStatus().getBean(); this.agreeddate = vo.getAgreedDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getAgreedDate().getBean(); this.reasonpatientplandiffmdt = vo.getReasonPatientPlanDiffMDT(); this.noanticancertxreason = vo.getNoAntiCancerTxReason() == null ? null : vo.getNoAntiCancerTxReason().getBeanCollection(); this.hasassociatedmdtmeeting = vo.getHasAssociatedMDTMeeting(); this.reasonforrevision = vo.getReasonForRevision(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.oncology.vo.CancerCarePlanVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.clinicalcontact = vo.getClinicalContact() == null ? null : (ims.core.vo.beans.ClinicalContactShortVoBean)vo.getClinicalContact().getBean(map); this.carecontext = vo.getCareContext() == null ? null : (ims.core.vo.beans.CareContextShortVoBean)vo.getCareContext().getBean(map); this.careplandate = vo.getCarePlanDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getCarePlanDate().getBean(); this.consultantincharge = vo.getConsultantInCharge() == null ? null : (ims.core.vo.beans.HcpLiteVoBean)vo.getConsultantInCharge().getBean(map); this.careplanintent = vo.getCarePlanIntent() == null ? null : (ims.vo.LookupInstanceBean)vo.getCarePlanIntent().getBean(); this.recurrenceindicator = vo.getRecurrenceIndicator() == null ? null : (ims.vo.LookupInstanceBean)vo.getRecurrenceIndicator().getBean(); this.iscurrent = vo.getIsCurrent(); this.mdtmeeting = vo.getMdtMeeting() == null ? null : (ims.oncology.vo.beans.CancerMDTMeetingVoBean)vo.getMdtMeeting().getBean(map); this.episodeofcare = vo.getEpisodeOfCare() == null ? null : new ims.vo.RefVoBean(vo.getEpisodeOfCare().getBoId(), vo.getEpisodeOfCare().getBoVersion()); this.careplannotes = vo.getCarePlanNotes(); this.treatmentmodalities = vo.getTreatmentModalities() == null ? null : vo.getTreatmentModalities().getBeanCollection(); this.currentstatus = vo.getCurrentStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getCurrentStatus().getBean(); this.agreeddate = vo.getAgreedDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getAgreedDate().getBean(); this.reasonpatientplandiffmdt = vo.getReasonPatientPlanDiffMDT(); this.noanticancertxreason = vo.getNoAntiCancerTxReason() == null ? null : vo.getNoAntiCancerTxReason().getBeanCollection(); this.hasassociatedmdtmeeting = vo.getHasAssociatedMDTMeeting(); this.reasonforrevision = vo.getReasonForRevision(); } public ims.oncology.vo.CancerCarePlanVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.oncology.vo.CancerCarePlanVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.oncology.vo.CancerCarePlanVo vo = null; if(map != null) vo = (ims.oncology.vo.CancerCarePlanVo)map.getValueObject(this); if(vo == null) { vo = new ims.oncology.vo.CancerCarePlanVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.core.vo.beans.ClinicalContactShortVoBean getClinicalContact() { return this.clinicalcontact; } public void setClinicalContact(ims.core.vo.beans.ClinicalContactShortVoBean value) { this.clinicalcontact = value; } public ims.core.vo.beans.CareContextShortVoBean getCareContext() { return this.carecontext; } public void setCareContext(ims.core.vo.beans.CareContextShortVoBean value) { this.carecontext = value; } public ims.framework.utils.beans.DateBean getCarePlanDate() { return this.careplandate; } public void setCarePlanDate(ims.framework.utils.beans.DateBean value) { this.careplandate = value; } public ims.core.vo.beans.HcpLiteVoBean getConsultantInCharge() { return this.consultantincharge; } public void setConsultantInCharge(ims.core.vo.beans.HcpLiteVoBean value) { this.consultantincharge = value; } public ims.vo.LookupInstanceBean getCarePlanIntent() { return this.careplanintent; } public void setCarePlanIntent(ims.vo.LookupInstanceBean value) { this.careplanintent = value; } public ims.vo.LookupInstanceBean getRecurrenceIndicator() { return this.recurrenceindicator; } public void setRecurrenceIndicator(ims.vo.LookupInstanceBean value) { this.recurrenceindicator = value; } public Boolean getIsCurrent() { return this.iscurrent; } public void setIsCurrent(Boolean value) { this.iscurrent = value; } public ims.oncology.vo.beans.CancerMDTMeetingVoBean getMdtMeeting() { return this.mdtmeeting; } public void setMdtMeeting(ims.oncology.vo.beans.CancerMDTMeetingVoBean value) { this.mdtmeeting = value; } public ims.vo.RefVoBean getEpisodeOfCare() { return this.episodeofcare; } public void setEpisodeOfCare(ims.vo.RefVoBean value) { this.episodeofcare = value; } public String getCarePlanNotes() { return this.careplannotes; } public void setCarePlanNotes(String value) { this.careplannotes = value; } public ims.oncology.vo.beans.TreatmentModalitiesVoBean[] getTreatmentModalities() { return this.treatmentmodalities; } public void setTreatmentModalities(ims.oncology.vo.beans.TreatmentModalitiesVoBean[] value) { this.treatmentmodalities = value; } public ims.vo.LookupInstanceBean getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.vo.LookupInstanceBean value) { this.currentstatus = value; } public ims.framework.utils.beans.DateBean getAgreedDate() { return this.agreeddate; } public void setAgreedDate(ims.framework.utils.beans.DateBean value) { this.agreeddate = value; } public String getReasonPatientPlanDiffMDT() { return this.reasonpatientplandiffmdt; } public void setReasonPatientPlanDiffMDT(String value) { this.reasonpatientplandiffmdt = value; } public java.util.Collection getNoAntiCancerTxReason() { return this.noanticancertxreason; } public void setNoAntiCancerTxReason(java.util.Collection value) { this.noanticancertxreason = value; } public void addNoAntiCancerTxReason(java.util.Collection value) { if(this.noanticancertxreason == null) this.noanticancertxreason = new java.util.ArrayList(); this.noanticancertxreason.add(value); } public Boolean getHasAssociatedMDTMeeting() { return this.hasassociatedmdtmeeting; } public void setHasAssociatedMDTMeeting(Boolean value) { this.hasassociatedmdtmeeting = value; } public String getReasonForRevision() { return this.reasonforrevision; } public void setReasonForRevision(String value) { this.reasonforrevision = value; } private Integer id; private int version; private ims.core.vo.beans.ClinicalContactShortVoBean clinicalcontact; private ims.core.vo.beans.CareContextShortVoBean carecontext; private ims.framework.utils.beans.DateBean careplandate; private ims.core.vo.beans.HcpLiteVoBean consultantincharge; private ims.vo.LookupInstanceBean careplanintent; private ims.vo.LookupInstanceBean recurrenceindicator; private Boolean iscurrent; private ims.oncology.vo.beans.CancerMDTMeetingVoBean mdtmeeting; private ims.vo.RefVoBean episodeofcare; private String careplannotes; private ims.oncology.vo.beans.TreatmentModalitiesVoBean[] treatmentmodalities; private ims.vo.LookupInstanceBean currentstatus; private ims.framework.utils.beans.DateBean agreeddate; private String reasonpatientplandiffmdt; private java.util.Collection noanticancertxreason; private Boolean hasassociatedmdtmeeting; private String reasonforrevision; }
agpl-3.0
ManfredKarrer/exchange
common/src/main/java/io/bisq/common/proto/network/NetworkProtoResolver.java
1044
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package io.bisq.common.proto.network; import io.bisq.common.proto.ProtoResolver; import io.bisq.generated.protobuffer.PB; public interface NetworkProtoResolver extends ProtoResolver { NetworkEnvelope fromProto(PB.NetworkEnvelope proto); NetworkPayload fromProto(PB.StoragePayload proto); NetworkPayload fromProto(PB.StorageEntryWrapper proto); }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/clinical/vo/VTERiskAssessmentTCIVo.java
10084
//############################################################################# //# # //# 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.clinical.vo; public class VTERiskAssessmentTCIVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public VTERiskAssessmentTCIVo() { } public VTERiskAssessmentTCIVo(ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean) { this.patient = bean.getPatient() == null ? null : bean.getPatient().buildVo(); this.patientsummaryrecord = bean.getPatientSummaryRecord() == null ? null : bean.getPatientSummaryRecord().buildVo(); this.tci = bean.getTCI() == null ? null : bean.getTCI().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean) { this.patient = bean.getPatient() == null ? null : bean.getPatient().buildVo(map); this.patientsummaryrecord = bean.getPatientSummaryRecord() == null ? null : bean.getPatientSummaryRecord().buildVo(map); this.tci = bean.getTCI() == null ? null : bean.getTCI().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean bean = null; if(map != null) bean = (ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.clinical.vo.beans.VTERiskAssessmentTCIVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public boolean getPatientIsNotNull() { return this.patient != null; } public ims.core.vo.PatientForVTERiskAssessmentVo getPatient() { return this.patient; } public void setPatient(ims.core.vo.PatientForVTERiskAssessmentVo value) { this.isValidated = false; this.patient = value; } public boolean getPatientSummaryRecordIsNotNull() { return this.patientsummaryrecord != null; } public ims.clinical.vo.PatientSummaryRecordForVteVo getPatientSummaryRecord() { return this.patientsummaryrecord; } public void setPatientSummaryRecord(ims.clinical.vo.PatientSummaryRecordForVteVo value) { this.isValidated = false; this.patientsummaryrecord = value; } public boolean getTCIIsNotNull() { return this.tci != null; } public ims.clinical.vo.TCIForVTEWorklistVo getTCI() { return this.tci; } public void setTCI(ims.clinical.vo.TCIForVTEWorklistVo value) { this.isValidated = false; this.tci = value; } public final String getIItemText() { return toString(); } public final Integer getBoId() { return null; } public final String getBoClassName() { return null; } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof VTERiskAssessmentTCIVo)) return false; VTERiskAssessmentTCIVo compareObj = (VTERiskAssessmentTCIVo)obj; if(this.getTCI() == null && compareObj.getTCI() != null) return false; if(this.getTCI() != null && compareObj.getTCI() == null) return false; if(this.getTCI() != null && compareObj.getTCI() != null) if(!this.getTCI().equals(compareObj.getTCI())) return false; if(this.getPatient() == null && compareObj.getPatient() != null) return false; if(this.getPatient() != null && compareObj.getPatient() == null) return false; if(this.getPatient() != null && compareObj.getPatient() != null) if(!this.getPatient().equals(compareObj.getPatient())) return false; if(this.getPatientSummaryRecord() == null && compareObj.getPatientSummaryRecord() != null) return false; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() == null) return false; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() != null) return this.getPatientSummaryRecord().equals(compareObj.getPatientSummaryRecord()); return super.equals(obj); } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; VTERiskAssessmentTCIVo clone = new VTERiskAssessmentTCIVo(); if(this.patient == null) clone.patient = null; else clone.patient = (ims.core.vo.PatientForVTERiskAssessmentVo)this.patient.clone(); if(this.patientsummaryrecord == null) clone.patientsummaryrecord = null; else clone.patientsummaryrecord = (ims.clinical.vo.PatientSummaryRecordForVteVo)this.patientsummaryrecord.clone(); if(this.tci == null) clone.tci = null; else clone.tci = (ims.clinical.vo.TCIForVTEWorklistVo)this.tci.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(VTERiskAssessmentTCIVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A VTERiskAssessmentTCIVo object cannot be compared an Object of type " + obj.getClass().getName()); } VTERiskAssessmentTCIVo compareObj = (VTERiskAssessmentTCIVo)obj; int retVal = 0; if (retVal == 0) { if(this.getTCI() == null && compareObj.getTCI() != null) return -1; if(this.getTCI() != null && compareObj.getTCI() == null) return 1; if(this.getTCI() != null && compareObj.getTCI() != null) retVal = this.getTCI().compareTo(compareObj.getTCI()); } if (retVal == 0) { if(this.getPatient() == null && compareObj.getPatient() != null) return -1; if(this.getPatient() != null && compareObj.getPatient() == null) return 1; if(this.getPatient() != null && compareObj.getPatient() != null) retVal = this.getPatient().compareTo(compareObj.getPatient()); } if (retVal == 0) { if(this.getPatientSummaryRecord() == null && compareObj.getPatientSummaryRecord() != null) return -1; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() == null) return 1; if(this.getPatientSummaryRecord() != null && compareObj.getPatientSummaryRecord() != null) retVal = this.getPatientSummaryRecord().compareTo(compareObj.getPatientSummaryRecord()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patient != null) count++; if(this.patientsummaryrecord != null) count++; if(this.tci != null) count++; return count; } public int countValueObjectFields() { return 3; } protected ims.core.vo.PatientForVTERiskAssessmentVo patient; protected ims.clinical.vo.PatientSummaryRecordForVteVo patientsummaryrecord; protected ims.clinical.vo.TCIForVTEWorklistVo tci; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
Concursive/concourseconnect-community
src/main/java/com/concursive/connect/web/modules/documents/dao/DocumentFolderTemplate.java
8997
/* * ConcourseConnect * Copyright 2009 Concursive Corporation * http://www.concursive.com * * This file is part of ConcourseConnect, an open source social business * software and community platform. * * Concursive ConcourseConnect is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, version 3 of the License. * * Under the terms of the GNU Affero General Public License you must release the * complete source code for any application that uses any part of ConcourseConnect * (system header files and libraries used by the operating system are excluded). * These terms must be included in any work that has ConcourseConnect components. * If you are developing and distributing open source applications under the * GNU Affero General Public License, then you are free to use ConcourseConnect * under the GNU Affero General Public License. * * If you are deploying a web site in which users interact with any portion of * ConcourseConnect over a network, the complete source code changes must be made * available. For example, include a link to the source archive directly from * your web site. * * For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their * products, and do not license and distribute their source code under the GNU * Affero General Public License, Concursive provides a flexible commercial * license. * * To anyone in doubt, we recommend the commercial license. Our commercial license * is competitively priced and will eliminate any confusion about how * ConcourseConnect can be used and distributed. * * ConcourseConnect 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 ConcourseConnect. If not, see <http://www.gnu.org/licenses/>. * * Attribution Notice: ConcourseConnect is an Original Work of software created * by Concursive Corporation */ package com.concursive.connect.web.modules.documents.dao; import com.concursive.commons.db.DatabaseUtils; import com.concursive.commons.text.StringUtils; import com.concursive.commons.web.mvc.beans.GenericBean; import java.sql.*; import java.util.ArrayList; /** * Can be used for creating document folders from a template * * @author Kailash Bhoopalam * @created August 12, 2008 */ public class DocumentFolderTemplate extends GenericBean { private int id = -1; private int projectCategoryId = -1; private String folderNames = ""; private boolean enabled = true; private Timestamp entered = null; public DocumentFolderTemplate() { } public DocumentFolderTemplate(ResultSet rs) throws SQLException { buildRecord(rs); } public DocumentFolderTemplate(Connection db, int id) throws SQLException { queryRecord(db, id); } public void queryRecord(Connection db, int templateId) throws SQLException { StringBuffer sql = new StringBuffer(); sql.append( "SELECT dft.* " + "FROM project_document_folder_template dft " + "WHERE template_id = ? "); PreparedStatement pst = db.prepareStatement(sql.toString()); int i = 0; pst.setInt(++i, templateId); ResultSet rs = pst.executeQuery(); if (rs.next()) { buildRecord(rs); } rs.close(); pst.close(); if (id == -1) { throw new SQLException("Template record not found."); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setId(String tmp) { this.id = Integer.parseInt(tmp); } public int getProjectCategoryId() { return projectCategoryId; } public void setProjectCategoryId(int projectCategoryId) { this.projectCategoryId = projectCategoryId; } public void setProjectCategoryId(String tmp) { this.projectCategoryId = Integer.parseInt(tmp); } /** * @return the folderNames */ public String getFolderNames() { return folderNames; } /** * @param folderNames the folderNames to set */ public void setFolderNames(String folderNames) { this.folderNames = folderNames; } public Timestamp getEntered() { return entered; } public void setEntered(Timestamp entered) { this.entered = entered; } public void setEntered(String tmp) { this.entered = DatabaseUtils.parseTimestamp(tmp); } public boolean getEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setEnabled(String enabled) { this.enabled = DatabaseUtils.parseBoolean(enabled); } private void buildRecord(ResultSet rs) throws SQLException { id = rs.getInt("template_id"); projectCategoryId = DatabaseUtils.getInt(rs, "project_category_id"); folderNames = rs.getString("folder_names"); enabled = rs.getBoolean("enabled"); entered = rs.getTimestamp("entered"); } public boolean isValid() { if (folderNames == null || folderNames.trim().equals("")) { errors.put("folderNamesError", "Required field"); } return !hasErrors(); } public ArrayList<String> getFolderNamesArrayList() { ArrayList<String> folderNames = new ArrayList<String>(); String[] tempNames = StringUtils.replaceReturns(this.getFolderNames(), "|").split("[|]"); for (String name : tempNames) { if (name != null && !"".equals(name.trim())) { folderNames.add(name); } } return folderNames; } public boolean insert(Connection db) throws SQLException { if (!isValid()) { return false; } boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } StringBuffer sql = new StringBuffer(); sql.append( "INSERT INTO project_document_folder_template " + "(" + (id > -1 ? "template_id, " : "") + "project_category_id, folder_names, "); if (entered != null) { sql.append("entered, "); } sql.append( "enabled) "); sql.append("VALUES (?, ?, "); if (id > -1) { sql.append("?, "); } if (entered != null) { sql.append("?, "); } sql.append("?) "); int i = 0; PreparedStatement pst = db.prepareStatement(sql.toString()); if (id > -1) { pst.setInt(++i, id); } DatabaseUtils.setInt(pst, ++i, projectCategoryId); pst.setString(++i, folderNames); if (entered != null) { pst.setTimestamp(++i, entered); } pst.setBoolean(++i, enabled); pst.execute(); pst.close(); id = DatabaseUtils.getCurrVal(db, "project_document_folder_template_template_id_seq", id); if (commit) { db.commit(); } } catch (SQLException e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } return true; } public int update(Connection db) throws SQLException { int resultCount = 0; boolean commit = db.getAutoCommit(); try { if (commit) { db.setAutoCommit(false); } if (this.getId() == -1) { throw new SQLException("ID was not specified"); } if (!isValid()) { return -1; } int i = 0; PreparedStatement pst = db.prepareStatement( "UPDATE project_document_folder_template " + "SET project_category_id = ?, folder_names = ?, " + "enabled = ? " + "WHERE template_id = ? "); DatabaseUtils.setInt(pst, ++i, projectCategoryId); pst.setString(++i, folderNames); pst.setBoolean(++i, enabled); pst.setInt(++i, id); resultCount = pst.executeUpdate(); pst.close(); if (commit) { db.commit(); } } catch (SQLException e) { if (commit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (commit) { db.setAutoCommit(true); } } return resultCount; } public void delete(Connection db) throws SQLException { boolean autoCommit = db.getAutoCommit(); try { if (autoCommit) { db.setAutoCommit(false); } PreparedStatement pst = db.prepareStatement( "DELETE FROM project_document_folder_template " + "WHERE template_id = ? "); pst.setInt(1, id); pst.execute(); pst.close(); if (autoCommit) { db.commit(); } } catch (Exception e) { if (autoCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (autoCommit) { db.setAutoCommit(true); } } } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Admin/src/ims/admin/forms/appointmenttrakingstatuscolorconfig/GlobalContext.java
2027
//############################################################################# //# # //# 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.admin.forms.appointmenttrakingstatuscolorconfig; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); } }
agpl-3.0
iu-uits-es/kc
coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/person/creditsplit/CreditSplitCustomColumnsCollection.java
4678
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.person.creditsplit; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocumentForm; import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentViewHelperServiceImpl; import org.kuali.rice.krad.uif.component.BindingInfo; import org.kuali.rice.krad.uif.component.Component; import org.kuali.rice.krad.uif.container.CollectionGroupBase; import org.kuali.rice.krad.uif.field.DataFieldBase; import org.kuali.rice.krad.uif.lifecycle.ViewLifecycleRestriction; import org.kuali.rice.krad.uif.util.*; import java.util.ArrayList; import java.util.List; public class CreditSplitCustomColumnsCollection extends CollectionGroupBase { private static final Logger LOG = Logger.getLogger(CreditSplitCustomColumnsCollection.class); private DataFieldBase columnFieldPrototype; private BindingInfo columnBindingInfo; private Class<?> columnObjectClass; private String columnLabelPropertyName; @Override public void performInitialization(Object model) { ProposalDevelopmentDocumentForm pdForm = (ProposalDevelopmentDocumentForm) model; ((ProposalDevelopmentViewHelperServiceImpl) pdForm.getViewHelperService()).setInvestigatorCreditTypes(pdForm); if (CollectionUtils.isNotEmpty(((ProposalDevelopmentDocumentForm) model).getDevelopmentProposal().getInvestigators())) { List<Object> columnCollection = ObjectPropertyUtils.getPropertyValue(model, getColumnBindingInfo().getBindingPath()); List<Component> columns = new ArrayList<Component>(); for (Component component : this.getItems()) { if (component.isRender() || component.isHidden()) { columns.add(component); } } int index = 0; for (Object column : columnCollection) { DataFieldBase columnField = ComponentUtils.copy(columnFieldPrototype); String columnLabel = StringUtils.isEmpty(columnLabelPropertyName)?"description":columnLabelPropertyName; try { columnField.getFieldLabel().setLabelText(PropertyUtils.getNestedProperty(column,columnLabel).toString()); columnField.getBindingInfo().setBindingName("creditSplits[" + index + "].credit"); columnField.setPropertyName("creditSplits.credit"); columnField.setOrder(100 + index); columns.add(columnField); } catch (Exception e) { LOG.error("Could not retrieve column label from column collection item",e); } index++; } this.setItems(columns); } super.performInitialization(model); } @ViewLifecycleRestriction public DataFieldBase getColumnFieldPrototype() { return columnFieldPrototype; } public void setColumnFieldPrototype(DataFieldBase columnFieldPrototype) { this.columnFieldPrototype = columnFieldPrototype; } public BindingInfo getColumnBindingInfo() { return columnBindingInfo; } public void setColumnBindingInfo(BindingInfo columnBindingInfo) { this.columnBindingInfo = columnBindingInfo; } public Class<?> getColumnObjectClass() { return columnObjectClass; } public void setColumnObjectClass(Class<?> columnObjectClass) { this.columnObjectClass = columnObjectClass; } public String getColumnLabelPropertyName() { return columnLabelPropertyName; } public void setColumnLabelPropertyName(String columnLabelPropertyName) { this.columnLabelPropertyName = columnLabelPropertyName; } }
agpl-3.0
auroreallibe/Silverpeas-Core
core-war/src/main/java/org/silverpeas/web/pdc/control/PdcFieldPositionsManager.java
6060
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.web.pdc.control; import java.util.ArrayList; import java.util.List; import org.silverpeas.core.pdc.form.displayers.PdcFieldDisplayer; import org.silverpeas.core.pdc.pdc.model.ClassifyPosition; import org.silverpeas.core.pdc.pdc.model.ClassifyValue; import org.silverpeas.core.pdc.pdc.model.UsedAxis; /** * Manages the positions of a PDC field. * @author ahedin */ public class PdcFieldPositionsManager { // If true, indicates that the controller which refers to this manager is in PDC field mode. private boolean enabled; // Positions of the field. private ArrayList<ClassifyPosition> positions; // Available axis to order the object (publication) containing the field. private ArrayList<UsedAxis> usedAxisList; // Field name. private String fieldName; // PDC field displayer. private PdcFieldDisplayer displayer; /** * Constructor */ protected PdcFieldPositionsManager() { reset(); } public boolean isEnabled() { return enabled; } public String getFieldName() { return fieldName; } public ArrayList<ClassifyPosition> getPositions() { return positions; } public ArrayList<UsedAxis> getUsedAxisList() { return usedAxisList; } /** * Initializes and enables the manager. * @param fieldName The field name. * @param pattern The description of positions, following the pattern : * axisId1_1,valueId1_1;axisId1_2,valueId1_2.axisId2_1,valueId2_1... where axisIdi_j and * valueIdi_j correspond to the value #j of the position #i. * @param axis */ public void init(String fieldName, String pattern, String axis) { enabled = true; this.fieldName = fieldName; displayer = new PdcFieldDisplayer(); positions = displayer.getPositions(pattern); usedAxisList = displayer.getUsedAxisList(axis); } /** * Resets and disables the manager. */ public void reset() { enabled = false; fieldName = null; displayer = null; positions = null; usedAxisList = null; } /** * Add the position to the positions list. * @param position The new position to add. */ public void addPosition(ClassifyPosition position) { position.setPositionId(positions.size()); positions.add(position); refreshPositions(); } /** * Update the position. * @param position The position to update. * @return the status of the update. */ public int updatePosition(ClassifyPosition position) { ClassifyPosition currentPosition; int i = 0; boolean positionFound = false; while (i < positions.size() && !positionFound) { currentPosition = positions.get(i); if (currentPosition.getPositionId() == position.getPositionId()) { positions.set(i, position); positionFound = true; } i++; } refreshPositions(); return -1; } /** * Deletes the position which id corresponds to the one given as parameter. * @param positionId The id of the position to delete. */ public void deletePosition(int positionId) { ClassifyPosition position; boolean axisRemoved = false; int i = 0; while (i < positions.size() && !axisRemoved) { position = positions.get(i); if (position.getPositionId() == positionId) { positions.remove(i); axisRemoved = true; } else { i++; } } if (axisRemoved) { while (i < positions.size()) { positions.get(i).setPositionId(i); i++; } } refreshPositions(); } /** * Calls the PDC field displayer to update and complete the description of positions. */ private void refreshPositions() { positions = displayer.getPositions(getPositionsToString()); } /** * @return A pattern describing the positions : * axisId1_1,valueId1_1;axisId1_2,valueId1_2.axisId2_1,valueId2_1... where axisIdi_j and * valueIdi_j correspond to the value #j of the position #i. */ public String getPositionsToString() { StringBuffer result = new StringBuffer(); if (positions != null) { ClassifyPosition position; ClassifyValue classifyValue; String[] values; String valuesPath; for (int i = 0; i < positions.size(); i++) { if (i > 0) { result.append("."); } position = positions.get(i); List<ClassifyValue> classifyValues = position.getValues(); for (int j = 0; j < classifyValues.size(); j++) { if (j > 0) { result.append(";"); } classifyValue = classifyValues.get(j); result.append(classifyValue.getAxisId()).append(","); valuesPath = classifyValue.getValue(); if (valuesPath != null && valuesPath.length() > 0) { values = valuesPath.split("/"); result.append(values[values.length - 1]); } } } } return result.toString(); } }
agpl-3.0
gama-platform/gama.cloud
ummisco.gama.opengl_web/src/com/jogamp/opengl/GLRunnable.java
102
package com.jogamp.opengl; public interface GLRunnable { boolean run(GLAutoDrawable drawable); }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/oncology/configuration/vo/PSAConfigRefVo.java
4687
//############################################################################# //# # //# 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.oncology.configuration.vo; /** * Linked to Oncology.Configuration.PSAConfig business object (ID: 1075100015). */ public class PSAConfigRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public PSAConfigRefVo() { } public PSAConfigRefVo(Integer id, int version) { super(id, version); } public final boolean getID_PSAConfigIsNotNull() { return this.id != null; } public final Integer getID_PSAConfig() { return this.id; } public final void setID_PSAConfig(Integer value) { this.id = value; } public final int getVersion_PSAConfig() { return this.version; } public Object clone() { return new PSAConfigRefVo(this.id, this.version); } public final PSAConfigRefVo toPSAConfigRefVo() { if(this.id == null) return this; return new PSAConfigRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof PSAConfigRefVo)) return false; PSAConfigRefVo compareObj = (PSAConfigRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.oncology.configuration.domain.objects.PSAConfig"; } public Class getDomainClass() { return ims.oncology.configuration.domain.objects.PSAConfig.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof PSAConfigRefVo)) throw new ClassCastException("A PSAConfigRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((PSAConfigRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((PSAConfigRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_PSACONFIG")) return getID_PSAConfig(); return super.getFieldValueByFieldName(fieldName); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/RefMan/src/ims/RefMan/domain/impl/ClinicalNotesComponentImpl.java
6912
//############################################################################# //# # //# 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 Peter Martin using IMS Development Environment (version 1.70 build 3545.21176) // Copyright (C) 1995-2009 IMS MAXIMS. All rights reserved. package ims.RefMan.domain.impl; import java.util.ArrayList; import java.util.List; import ims.admin.domain.HcpAdmin; import ims.admin.domain.impl.HcpAdminImpl; import ims.RefMan.domain.base.impl.BaseClinicalNotesComponentImpl; import ims.RefMan.domain.objects.ConsultationClinicalNotes; import ims.domain.DomainFactory; import ims.domain.exceptions.StaleObjectException; import ims.domain.exceptions.UniqueKeyViolationException; import ims.framework.enumerations.SortOrder; import ims.framework.exceptions.CodingRuntimeException; import ims.RefMan.vo.ConsultationClinicalNotesRefVo; import ims.RefMan.vo.ConsultationClinicalNotesVoCollection; import ims.RefMan.vo.domain.ConsultationClinicalNotesVoAssembler; import ims.clinical.domain.Allergies; import ims.clinical.domain.impl.AllergiesImpl; import ims.core.patient.vo.PatientRefVo; import ims.core.vo.HcpLiteVoCollection; import ims.core.vo.PatientAllergyCollection; import ims.core.vo.PatientNoAllergyInfoVo; import ims.core.vo.PatientShort; import ims.core.vo.domain.PatientShortAssembler; public class ClinicalNotesComponentImpl extends BaseClinicalNotesComponentImpl { private static final long serialVersionUID = 1L; public ims.RefMan.vo.ConsultationClinicalNotesVo getConsultationClinicalNotesVo(ims.RefMan.vo.CatsReferralRefVo refVoCatsReferral) { DomainFactory factory = getDomainFactory(); StringBuffer hql = new StringBuffer(" from ConsultationClinicalNotes ccn"); ArrayList<String> markers = new ArrayList<String>(); ArrayList<Integer> values = new ArrayList<Integer>(); hql.append(" where ccn.catsReferral.id = :crId "); markers.add("crId"); values.add(refVoCatsReferral.getID_CatsReferral()); List listNotes = factory.find(hql.toString(), markers,values); if(listNotes != null && listNotes.size() > 0) { ConsultationClinicalNotesVoCollection voColl = ConsultationClinicalNotesVoAssembler.createConsultationClinicalNotesVoCollectionFromConsultationClinicalNotes(listNotes); if(voColl != null && voColl.size() > 0) { voColl.sort(SortOrder.DESCENDING); return voColl.get(0); } } return null; } public ims.RefMan.vo.ConsultationClinicalNotesVo getNote(ConsultationClinicalNotesRefVo note) { if (note == null) throw new RuntimeException("Cannot get ConsultationClinicalNotesVo for null ConsultationClinicalNotesRefVo"); ConsultationClinicalNotes doConsultationClinicalNotes = (ConsultationClinicalNotes) getDomainFactory().getDomainObject(ConsultationClinicalNotes.class, note.getID_ConsultationClinicalNotes()); return ConsultationClinicalNotesVoAssembler.create(doConsultationClinicalNotes); } public ims.RefMan.vo.ConsultationClinicalNotesVo saveConsultationClinicalNotesVo(ims.RefMan.vo.ConsultationClinicalNotesVo voConsultationClinicalNotes) throws ims.domain.exceptions.StaleObjectException { if(voConsultationClinicalNotes == null) throw new CodingRuntimeException("ConsultationClinicalNotesVo is null"); if(!voConsultationClinicalNotes.isValidated()) throw new CodingRuntimeException("ConsultationClinicalNotesVo has not been validated"); DomainFactory factory = getDomainFactory(); ConsultationClinicalNotes doConsultationClinicalNotes = ConsultationClinicalNotesVoAssembler.extractConsultationClinicalNotes(factory, voConsultationClinicalNotes); factory.save(doConsultationClinicalNotes); return ConsultationClinicalNotesVoAssembler.create(doConsultationClinicalNotes); } public HcpLiteVoCollection listHcpLiteByName(String hcpName) { HcpAdmin hcpAdmin = (HcpAdmin)getDomainImpl(HcpAdminImpl.class); return hcpAdmin.listHcpLiteByName(hcpName); } public PatientAllergyCollection listPatientAllergies(PatientShort patient) { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.listPatientAllergies(patient, true); } public PatientNoAllergyInfoVo getPatientNoAllergyInfo(PatientRefVo patientRefVo) { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.getPatientNoAllergyInfo(patientRefVo); } public PatientNoAllergyInfoVo savePatientNoAllergyInfo(PatientNoAllergyInfoVo patientNoAllergyInfo) throws StaleObjectException, UniqueKeyViolationException { Allergies allergies = (Allergies)getDomainImpl(AllergiesImpl.class); return allergies.savePatientNoAllergyInfo(patientNoAllergyInfo); } //wdev-10534 public PatientShort getPatientShort(PatientRefVo patientRefVo) { DomainFactory factory = getDomainFactory(); ims.core.patient.domain.objects.Patient patBo = (ims.core.patient.domain.objects.Patient) factory.getDomainObject(ims.core.patient.domain.objects.Patient.class, patientRefVo.getID_Patient().intValue()); return PatientShortAssembler.create(patBo); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/patientmergemanager/AccessLogic.java
2547
//############################################################################# //# # //# 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.71 build 3642.24101) // Copyright (C) 1995-2010 IMS MAXIMS. All rights reserved. package ims.core.forms.patientmergemanager; 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; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Nursing/src/ims/nursing/forms/dailypatientprogress/BaseLogic.java
11025
//############################################################################# //# # //# 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.nursing.forms.dailypatientprogress; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.nursing.domain.DailyPatientProgress.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.nursing.domain.DailyPatientProgress domain) { setContext(engine, form); this.domain = domain; } protected final void oncmbStatusValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatus().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusLookup(); return; } } } } else if(value instanceof ims.core.vo.lookups.PatientAssessmentStatusReason) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = (ims.core.vo.lookups.PatientAssessmentStatusReason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatus().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusLookup() { this.form.cmbStatus().clear(); ims.core.vo.lookups.PatientAssessmentStatusReasonCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatus().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusLookupValue(int id) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatus().setValue(instance); } protected final void defaultcmbStatusLookupValue() { this.form.cmbStatus().setValue((ims.core.vo.lookups.PatientAssessmentStatusReason)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.PatientAssessmentStatusReason.class, engine.getFormName().getID(), ims.core.vo.lookups.PatientAssessmentStatusReason.TYPE_ID)); } protected final void oncmbStatusReasonValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbStatusReason().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbStatusReasonLookup(); return; } } } } else if(value instanceof ims.core.vo.lookups.PatientAssessmentStatusReason) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = (ims.core.vo.lookups.PatientAssessmentStatusReason)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbStatusReasonLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.core.vo.lookups.PatientAssessmentStatusReason existingInstance = (ims.core.vo.lookups.PatientAssessmentStatusReason)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbStatusReason().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbStatusReasonLookup() { this.form.cmbStatusReason().clear(); ims.core.vo.lookups.PatientAssessmentStatusReasonCollection lookupCollection = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReason(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbStatusReason().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbStatusReasonLookupValue(int id) { ims.core.vo.lookups.PatientAssessmentStatusReason instance = ims.core.vo.lookups.LookupHelper.getPatientAssessmentStatusReasonInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbStatusReason().setValue(instance); } protected final void defaultcmbStatusReasonLookupValue() { this.form.cmbStatusReason().setValue((ims.core.vo.lookups.PatientAssessmentStatusReason)domain.getLookupService().getDefaultInstance(ims.core.vo.lookups.PatientAssessmentStatusReason.class, engine.getFormName().getID(), ims.core.vo.lookups.PatientAssessmentStatusReason.TYPE_ID)); } protected final void oncmbAssessmentTypeValueSet(Object value) { java.util.ArrayList listOfValues = this.form.cmbAssessmentType().getValues(); if(value == null) { if(listOfValues != null && listOfValues.size() > 0) { for(int x = 0; x < listOfValues.size(); x++) { ims.assessment.vo.lookups.DPPType existingInstance = (ims.assessment.vo.lookups.DPPType)listOfValues.get(x); if(!existingInstance.isActive()) { bindcmbAssessmentTypeLookup(); return; } } } } else if(value instanceof ims.assessment.vo.lookups.DPPType) { ims.assessment.vo.lookups.DPPType instance = (ims.assessment.vo.lookups.DPPType)value; if(listOfValues != null) { if(listOfValues.size() == 0) bindcmbAssessmentTypeLookup(); for(int x = 0; x < listOfValues.size(); x++) { ims.assessment.vo.lookups.DPPType existingInstance = (ims.assessment.vo.lookups.DPPType)listOfValues.get(x); if(existingInstance.equals(instance)) return; } } this.form.cmbAssessmentType().newRow(instance, instance.getText(), instance.getImage(), instance.getTextColor()); } } protected final void bindcmbAssessmentTypeLookup() { this.form.cmbAssessmentType().clear(); ims.assessment.vo.lookups.DPPTypeCollection lookupCollection = ims.assessment.vo.lookups.LookupHelper.getDPPType(this.domain.getLookupService()); for(int x = 0; x < lookupCollection.size(); x++) { this.form.cmbAssessmentType().newRow(lookupCollection.get(x), lookupCollection.get(x).getText(), lookupCollection.get(x).getImage(), lookupCollection.get(x).getTextColor()); } } protected final void setcmbAssessmentTypeLookupValue(int id) { ims.assessment.vo.lookups.DPPType instance = ims.assessment.vo.lookups.LookupHelper.getDPPTypeInstance(this.domain.getLookupService(), id); if(instance != null) this.form.cmbAssessmentType().setValue(instance); } protected final void defaultcmbAssessmentTypeLookupValue() { this.form.cmbAssessmentType().setValue((ims.assessment.vo.lookups.DPPType)domain.getLookupService().getDefaultInstance(ims.assessment.vo.lookups.DPPType.class, engine.getFormName().getID(), ims.assessment.vo.lookups.DPPType.TYPE_ID)); } protected void clearScreen() { this.form.txtStatusReason().setValue(""); this.form.txtOtherType().setValue(""); this.form.cmbStatus().setValue(null); this.form.cmbStatusReason().setValue(null); this.form.cmbAssessmentType().setValue(null); } protected void populateScreenFromData(ims.assessment.vo.PatientAssessmentVo value) { clearScreen(); if(value == null) return; this.form.txtStatusReason().setValue(value.getStatusReasonTextIsNotNull() ? value.getStatusReasonText(): null); this.form.txtOtherType().setValue(value.getDPPTypeTextIsNotNull() ? value.getDPPTypeText(): null); this.form.cmbStatus().setValue(value.getStatusIsNotNull() ? value.getStatus() : null); this.form.cmbStatusReason().setValue(value.getStatusReasonIsNotNull() ? value.getStatusReason() : null); this.form.cmbAssessmentType().setValue(value.getDPPTypeIsNotNull() ? value.getDPPType() : null); } protected ims.assessment.vo.PatientAssessmentVo populateDataFromScreen(ims.assessment.vo.PatientAssessmentVo value) { if(value == null) value = new ims.assessment.vo.PatientAssessmentVo(); value.setStatusReasonText(this.form.txtStatusReason().getValue()); value.setDPPTypeText(this.form.txtOtherType().getValue()); value.setStatus(this.form.cmbStatus().getValue()); value.setStatusReason(this.form.cmbStatusReason().getValue()); value.setDPPType(this.form.cmbAssessmentType().getValue()); return value; } protected ims.assessment.vo.PatientAssessmentVo populateDataFromScreen() { return populateDataFromScreen(new ims.assessment.vo.PatientAssessmentVo()); } public final void free() { super.free(); domain = null; } protected ims.nursing.domain.DailyPatientProgress domain; }
agpl-3.0