text
stringlengths
10
2.72M
package org.maple.jdk8.methodReference; import java.util.Arrays; import java.util.List; /** * @Author Mapleins * @Date 2019-04-05 0:23 * @Description */ public class Test1 { public static void main(String[] args) { List<String> list = Arrays.asList("hello", "world", "hello world!"); // list.forEach(x -> System.out.println(x)); list.forEach(System.out::println); } }
package com.gt.supertier.business.user.boundary; import com.gt.supertier.business.user.entitiy.User; import com.gt.supertier.business.user.entitiy.UserRepository; import javax.ejb.Stateless; import javax.inject.Inject; import java.io.Serializable; import java.util.List; @Stateless public class UserManager implements Serializable { @Inject private UserRepository userRepository; public User findByUsername(String username){ return userRepository.findOptionalByUsername(username); } public List<User> findAll(){ return userRepository.findAll(); } public User save(User user){ return userRepository.save(user); } }
package com.youngtech.fabartists.ui.activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.LinearLayout; import com.youngtech.fabartists.DTO.UserDTO; import com.youngtech.fabartists.R; import com.youngtech.fabartists.https.HttpsRequest; import com.youngtech.fabartists.interfacess.Consts; import com.youngtech.fabartists.interfacess.Helper; import com.youngtech.fabartists.network.NetworkManager; import com.youngtech.fabartists.preferences.SharedPrefrence; import com.youngtech.fabartists.utils.CustomButton; import com.youngtech.fabartists.utils.CustomEditText; import com.youngtech.fabartists.utils.CustomTextView; import com.youngtech.fabartists.utils.ProjectUtils; import org.json.JSONObject; import java.util.HashMap; public class AddMoney extends AppCompatActivity implements View.OnClickListener { private String TAG = AddMoney.class.getSimpleName(); private Context mContext; private CustomEditText etAddMoney; private CustomTextView tv1000, tv1500, tv2000; private CustomButton cbAdd; float rs = 0; float rs1 = 0; float final_rs = 0; private HashMap<String, String> parmas = new HashMap<>(); private SharedPrefrence prefrence; private UserDTO userDTO; private String amt = ""; private String currency = ""; private CustomTextView tvWallet; private ImageView ivBack; private Dialog dialog; private LinearLayout llPaypall, llStripe, llCancel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_money); mContext = AddMoney.this; prefrence = SharedPrefrence.getInstance(mContext); userDTO = prefrence.getParentUser(Consts.USER_DTO); parmas.put(Consts.USER_ID, userDTO.getUser_id()); setUiAction(); } public void setUiAction() { tvWallet = findViewById(R.id.tvWallet); ivBack = findViewById(R.id.ivBack); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); if (getIntent().hasExtra(Consts.AMOUNT)) { amt = getIntent().getStringExtra(Consts.AMOUNT); currency = getIntent().getStringExtra(Consts.CURRENCY); tvWallet.setText(currency + " " + amt); } cbAdd = findViewById(R.id.cbAdd); cbAdd.setOnClickListener(this); etAddMoney = findViewById(R.id.etAddMoney); etAddMoney.setSelection(etAddMoney.getText().length()); tv1000 = findViewById(R.id.tv1000); tv1000.setOnClickListener(this); tv1500 = findViewById(R.id.tv1500); tv1500.setOnClickListener(this); tv2000 = findViewById(R.id.tv2000); tv2000.setOnClickListener(this); tv1000.setText("+ " + currency + " 1000"); tv1500.setText("+ " + currency + " 1500"); tv2000.setText("+ " + currency + " 2000"); } @Override public void onClick(View v) { if (etAddMoney.getText().toString().trim().equalsIgnoreCase("")) { rs1 = 0; } else { rs1 = Float.parseFloat(etAddMoney.getText().toString().trim()); } switch (v.getId()) { case R.id.tv1000: rs = 1000; final_rs = rs1 + rs; etAddMoney.setText(final_rs + ""); etAddMoney.setSelection(etAddMoney.getText().length()); break; case R.id.tv1500: rs = 1500; final_rs = rs1 + rs; etAddMoney.setText(final_rs + ""); etAddMoney.setSelection(etAddMoney.getText().length()); break; case R.id.tv2000: rs = 2000; final_rs = rs1 + rs; etAddMoney.setText(final_rs + ""); etAddMoney.setSelection(etAddMoney.getText().length()); break; case R.id.cbAdd: if (etAddMoney.getText().toString().length() > 0 && Float.parseFloat(etAddMoney.getText().toString().trim())>0) { if (NetworkManager.isConnectToInternet(mContext)) { parmas.put(Consts.AMOUNT, ProjectUtils.getEditTextValue(etAddMoney)); dialogPayment(); } else { ProjectUtils.showLong(mContext, getResources().getString(R.string.internet_concation)); } } else { ProjectUtils.showLong(mContext, getResources().getString(R.string.val_money)); } break; } } @Override public void onResume() { super.onResume(); if (prefrence.getValue(Consts.SURL).equalsIgnoreCase(Consts.PAYMENT_SUCCESS)) { prefrence.clearPreferences(Consts.SURL); finish(); } else if (prefrence.getValue(Consts.FURL).equalsIgnoreCase(Consts.PAYMENT_FAIL)) { prefrence.clearPreferences(Consts.FURL); finish(); }else if (prefrence.getValue(Consts.SURL).equalsIgnoreCase(Consts.PAYMENT_SUCCESS_paypal)) { prefrence.clearPreferences(Consts.SURL); addMoney(); }else if (prefrence.getValue(Consts.FURL).equalsIgnoreCase(Consts.PAYMENT_FAIL_Paypal)) { prefrence.clearPreferences(Consts.FURL); finish(); } } public void addMoney() { new HttpsRequest(Consts.ADD_MONEY_API, parmas, mContext).stringPost(TAG, new Helper() { @Override public void backResponse(boolean flag, String msg, JSONObject response) { if (flag) { ProjectUtils.showLong(mContext, msg); finish(); } else { ProjectUtils.showLong(mContext, msg); } } }); } public void dialogPayment() { dialog = new Dialog(mContext/*, android.R.style.Theme_Dialog*/); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dailog_payment_option); ///dialog.getWindow().setBackgroundDrawableResource(R.color.black); llPaypall = (LinearLayout) dialog.findViewById(R.id.llPaypall); llStripe = (LinearLayout) dialog.findViewById(R.id.llStripe); llCancel = (LinearLayout) dialog.findViewById(R.id.llCancel); dialog.show(); dialog.setCancelable(false); llCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); llPaypall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = Consts.MAKE_PAYMENT_paypal +"amount=" + ProjectUtils.getEditTextValue(etAddMoney)+"&userId="+ userDTO.getUser_id(); Intent in2 = new Intent(mContext, PaymetWeb.class); in2.putExtra(Consts.PAYMENT_URL, url); startActivity(in2); dialog.dismiss(); } }); llStripe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = Consts.MAKE_PAYMENT + userDTO.getUser_id() + "/" + ProjectUtils.getEditTextValue(etAddMoney); Intent in2 = new Intent(mContext, PaymetWeb.class); in2.putExtra(Consts.PAYMENT_URL, url); startActivity(in2); dialog.dismiss(); } }); } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). 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 com.frostwire.gui.library; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.swing.SwingUtilities; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.frostwire.HttpFetcher; import com.frostwire.JsonEngine; import com.frostwire.core.ConfigurationManager; import com.frostwire.core.Constants; import com.frostwire.gui.Librarian; import com.frostwire.gui.httpserver.HttpServerManager; import com.frostwire.gui.library.Device.OnActionFailedListener; import com.frostwire.localpeer.Finger; import com.frostwire.localpeer.LocalPeer; import com.frostwire.localpeer.LocalPeerManager; import com.frostwire.localpeer.LocalPeerManagerImpl; import com.frostwire.localpeer.LocalPeerManagerListener; import com.limegroup.gnutella.settings.LibrarySettings; import com.limegroup.gnutella.util.FrostWireUtils; /** * @author gubatron * @author aldenml * */ public class DeviceDiscoveryClerk { private static final Log LOG = LogFactory.getLog(DeviceDiscoveryClerk.class); private final HttpServerManager httpServerManager; private final LocalPeerManager peerManager; private Map<String, Device> deviceCache; private JsonEngine jsonEngine; public DeviceDiscoveryClerk() { this.httpServerManager = new HttpServerManager(); this.peerManager = new LocalPeerManagerImpl(); this.peerManager.setListener(new LocalPeerManagerListener() { private String getKey(LocalPeer peer) { return peer.address + ":" + peer.port; } @Override public void peerResolved(LocalPeer peer) { try { handleDeviceState(getKey(peer), InetAddress.getByName(peer.address), peer.port, false, peer); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void peerRemoved(LocalPeer peer) { try { handleDeviceState(getKey(peer), InetAddress.getByName(peer.address), peer.port, true, peer); } catch (UnknownHostException e) { e.printStackTrace(); } } }); deviceCache = Collections.synchronizedMap(new HashMap<String, Device>()); jsonEngine = new JsonEngine(); if (LibrarySettings.LIBRARY_WIFI_SHARING_ENABLED.getValue()) { start(); } } public void updateLocalPeer() { peerManager.update(createLocalPeer()); } public void start() { new Thread(new Runnable() { @Override public void run() { httpServerManager.start(Constants.EXTERNAL_CONTROL_LISTENING_PORT); peerManager.start(createLocalPeer()); } }).start(); } public void stop() { new Thread(new Runnable() { @Override public void run() { httpServerManager.stop(); peerManager.stop(); for (Entry<String, Device> e : new HashSet<Entry<String, Device>>(deviceCache.entrySet())) { Device device = deviceCache.get(e.getKey()); handleDeviceStale(e.getKey(), device.getAddress(), device); } } }).start(); } public void handleDeviceState(String key, InetAddress address, int listeningPort, boolean bye, LocalPeer pinfo) { if (!bye) { retrieveFinger(key, address, listeningPort, pinfo); } else { if (deviceCache.containsKey(key)) { Device device = deviceCache.get(key); handleDeviceStale(key, address, device); } } } private LocalPeer createLocalPeer() { String address = "0.0.0.0"; int port = Constants.EXTERNAL_CONTROL_LISTENING_PORT; int numSharedFiles = Librarian.instance().getNumSharedFiles(); String nickname = ConfigurationManager.instance().getNickname(); int deviceType = Constants.DEVICE_MAJOR_TYPE_DESKTOP; String clientVersion = FrostWireUtils.getFrostWireVersion(); return new LocalPeer(address, port, true, nickname, numSharedFiles, deviceType, clientVersion); } private boolean retrieveFinger(final String key, final InetAddress address, int listeningPort, LocalPeer pinfo) { try { URI uri = new URI("http://" + address.getHostAddress() + ":" + listeningPort + "/finger"); HttpFetcher fetcher = new HttpFetcher(uri); byte[] jsonBytes = fetcher.fetch(); if (jsonBytes == null) { LOG.error("Failed to connnect to " + uri); return false; } String json = new String(jsonBytes); Finger finger = jsonEngine.toObject(json, Finger.class); synchronized (deviceCache) { if (deviceCache.containsKey(key)) { Device device = deviceCache.get(key); device.setFinger(finger); handleDeviceAlive(address, device); } else { Device device = new Device(key, address, listeningPort, finger, pinfo); device.setOnActionFailedListener(new OnActionFailedListener() { public void onActionFailed(Device device, int action, Exception e) { handleDeviceStale(key, address, device); } }); handleDeviceNew(key, address, device); } } return true; } catch (Throwable e) { LOG.error("Failed to connnect to " + address); } return false; } private void handleDeviceNew(String key, InetAddress address, final Device device) { deviceCache.put(key, device); device.setTimestamp(System.currentTimeMillis()); //LOG.info("Device New: " + device); SwingUtilities.invokeLater(new Runnable() { public void run() { LibraryMediator.instance().handleDeviceNew(device); } }); } private void handleDeviceAlive(InetAddress address, final Device device) { device.setTimestamp(System.currentTimeMillis()); //LOG.info("Device Alive: " + device); SwingUtilities.invokeLater(new Runnable() { public void run() { LibraryMediator.instance().handleDeviceAlive(device); } }); } private void handleDeviceStale(String key, InetAddress address, final Device device) { deviceCache.remove(key); LOG.info("Device Slate: " + device); SwingUtilities.invokeLater(new Runnable() { public void run() { LibraryMediator.instance().handleDeviceStale(device); } }); } }
package com.tsuro.referee; import com.tsuro.tile.ITile; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import lombok.NonNull; /** * An {@link Iterator<ITile>} that cycles through the injected Tiles. Can only be used once. */ public class CycleThroughTiles implements Iterator<ITile> { @NonNull private Queue<ITile> tiles; /** * Creates an Iterator off the given tiles. */ public CycleThroughTiles(Collection<ITile> tiles) { this.tiles = new LinkedList<>(tiles); } @Override public boolean hasNext() { return true; } @Override public ITile next() { ITile returnable = tiles.poll(); tiles.add(returnable); return returnable; } }
package com.baiwang.custom.common.base; import com.alibaba.fastjson.annotation.JSONField; import com.baiwang.bop.request.impl.invoice.common.RequestThreadLocal; import java.util.ArrayList; import java.util.List; /** * WebService返回结果<p> * @author Li Jiayi * @version 2018年7月26日 下午6:04:40 * @param <T> */ public class WebServiceResult<T> { private static final long serialVersionUID = -7532190660864165247L; @JSONField private boolean success = true; @JSONField private String errorCode = null; @JSONField private String message = null; private String requestID = null; private Long total = Long.valueOf(0L); @JSONField private List<T> data = new ArrayList(); public WebServiceResult() { String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } public WebServiceResult(String code,String message){ this.errorCode = code; this.message = message; } public WebServiceResult(String code, String message, Boolean success){ if (success){ this.errorCode = code; this.message = message; this.success = success; }else{ this.errorCode = code; this.message = message; this.success = false; } } public WebServiceResult(List<T> data) { if(data != null && data.size() > 0) { this.data = data; this.total = Long.valueOf((long)data.size()); String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } } public WebServiceResult(List<T> data, Long total) { if(data != null && data.size() > 0) { this.data = data; this.total = total; String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } } public WebServiceResult(T data) { this.data.add(data); this.total = Long.valueOf(1L); String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } public boolean isSuccess() { return this.success; } public void setSuccess(boolean success) { this.success = success; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public List<T> getData() { return this.data; } public String getRequestID() { return this.requestID; } public void setRequestID(String requestID) { this.requestID = requestID; } public Long getTotal() { return this.total; } public void setTotal(Long total) { this.total = total; } public void addData(List<T> data) { if(data != null && data.size() > 0) { this.data = data; this.total = Long.valueOf((long)data.size()); String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } } public void addData(T data) { this.data.add(data); this.total = Long.valueOf(1L); String uuid = RequestThreadLocal.getUuid(); this.requestID = uuid; } }
package com.example.hbase.util; public final class FactoryUtil { public static Object getInstance(String className) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ Class<?> class1 = Class.forName(className); return class1.newInstance(); } }
package com.eniso.regimi.services; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import com.eniso.regimi.models.Partner; import com.eniso.regimi.repository.PartnerRepository; import com.eniso.regimi.repository.RoleRepository; @Service @ComponentScan(basePackageClasses = PartnerRepository.class) public class PartnerServiceImpl implements PartnerService { @Autowired private PartnerRepository partnerRepository; @Autowired RoleRepository roleRepository; // public InstitutionServiceImpl() {} public PartnerServiceImpl( PartnerRepository partnerRepository) { super(); this.partnerRepository = partnerRepository; } @Override public List<Partner> findAll() { return partnerRepository.findAll(); } @Override public Partner findById(String theId) { Optional<Partner> result = partnerRepository.findById(theId); Partner theControl = null; if (result.isPresent()) { theControl = result.get(); } else { // we didn't find the participant throw new RuntimeException("Did not find institution id - " + theId); } return theControl; } @Override public void save(Partner partner) { partnerRepository.save(partner); } @Override public void deleteById(String theId) { partnerRepository.deleteById(theId); } @Override public Partner findByName(String name) { // TODO Auto-generated method stub return partnerRepository.findByName(name); } @Override public List<Partner> findByCity(String city) { // TODO Auto-generated method stub return partnerRepository.findByCity(city); } @Override public ResponseEntity<?> update(Partner partner) { // TODO Auto-generated method stub return null; } }
package com.meehoo.biz.core.basic.vo.bos; import com.meehoo.biz.common.util.BaseUtil; import com.meehoo.biz.common.util.DateUtil; import com.meehoo.biz.core.basic.domain.bos.AttachFile; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Created by cz on 2018/08/27. * */ @Getter @Setter @NoArgsConstructor public class AttachFileVO { private String fileId; private String attachFileId; private String code; private String fileName; /** * 序号 */ private Integer seq; private String belongEntityId; private String belongBizId; /** * 文件类型 */ private Integer fileType; private String fileTypeShow; /** * 源文件存储路径 */ private String sourceUrl; /** * 缩略图路径 */ private String thumbnailUrl; /** * 附件描述 */ private String description; /** * 创建人Id */ private String uploadUserId; /** * 创建姓名 */ private String uploadUserName; /** * 创建时间 */ private String createTime; public AttachFileVO(AttachFile attachFile) { this.attachFileId = attachFile.getId(); this.code = attachFile.getCode(); this.fileName = attachFile.getFileName(); this.fileType = attachFile.getFileType(); this.fileTypeShow = attachFile.getFileTypeShow(); this.sourceUrl = attachFile.getSourceUrl(); this.thumbnailUrl = attachFile.getThumbnailUrl(); this.description = attachFile.getDescription(); this.uploadUserId = attachFile.getUploadUserId(); this.uploadUserName = attachFile.getUploadUserName(); this.createTime = DateUtil.timeToString(attachFile.getCreateTime()); this.fileId = attachFile.getId(); } }
/* * (c) Copyright 2001-2007 PRODAXIS, S.A.S. All rights reserved. * PRODAXIS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.prodaxis.mappingfilegenerator.toplink; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.ICompilationUnit; import com.prodaxis.mappingfilegenerator.utils.AttributeToDBMapping; import com.prodaxis.mappingfilegenerator.utils.FinderMapping; import com.prodaxis.mappingfilegenerator.wizard.MappingFileWizard; /** * TopLinkGenerator creates the *BMP.map for TopLink */ public final class TopLinkGenerator extends MappingFileWizard implements ITopLink { public static IFile doFinish(ICompilationUnit compilationUnit, String packageName, String className, String tableName, Collection attributeToDBMappingCollection, Collection finderCollection, IProgressMonitor monitor) throws CoreException { monitor.beginTask("Creating " + className, 2); // Suppress 'Bean' at the end of the class name className = className.substring(0, className.length() - 4); // Retrieve the target directory IProject project = compilationUnit.getCorrespondingResource().getProject(); IResource resource = project.getFolder("resources/.metadata/.toplink"); if (!resource.exists() || !(resource instanceof IContainer)) throwCoreException("Project folder \"resources/.metadata/.toplink\" does not exist."); // Retrieve the target package directory (created if not exists) IFolder packageFolder = project.getFolder("resources/.metadata/.toplink/" + packageName); if (!packageFolder.exists()) packageFolder.create(true, true, monitor); // Create the mapping file IFile file = packageFolder.getFile(new Path(className + "BMP.map")); try { String contents = TOPLINK_MAPPING_START; contents += JAVA_CLASS.replaceFirst("&packageName", packageName).replaceFirst("&className", className + "BMP"); contents += TABLES_START + TABLE_NAME.replaceAll("&tableName", tableName) + TABLES_END; contents += PRIMARY_KEY_FIELDS_START; AttributeToDBMapping attributeToDBMapping; Iterator it = attributeToDBMappingCollection.iterator(); while (it.hasNext()) { attributeToDBMapping = (AttributeToDBMapping) it.next(); if (attributeToDBMapping.isPrimaryKey()) contents += PRIMARY_KEY_FIELD.replaceFirst("&tableName", tableName).replaceFirst("&fieldName", attributeToDBMapping.getFieldName()); } contents += PRIMARY_KEY_FIELDS_END; contents += IDENTITY_MAP_CLASS + IDENTITY_MAP_SIZE + ALIAS.replaceFirst("&className", className); contents += QUERY_MANAGER_START + DESCRIPTOR_QUERY_MANAGER_START + DESCRIPTOR_NAMED_QUERIES_START; contents += DATABASE_QUERY_START + QUERY_NAME_PK + QUERY_ARGUMENTS_START + STRING_PK + QUERY_ARGUMENTS_END + QUERY_TYPE_PK + DATABASE_QUERY_END; String request, attributeName; FinderMapping finderMapping; int index; String instanceClassName = new String("" + className.charAt(0)).toLowerCase() + className.substring(1); Iterator it2; it = finderCollection.iterator(); while (it.hasNext()) { finderMapping = (FinderMapping) it.next(); contents += DATABASE_QUERY_START + QUERY_NAME.replaceFirst("&finderName", finderMapping.getFinderName()); index = 1; request = "SELECT OBJECT(" + instanceClassName + ") FROM " + className + " " + instanceClassName + " WHERE"; it2 = finderMapping.getAttributeCollection().iterator(); while (it2.hasNext()) { attributeName = (String) it2.next(); if (index == 1) request += " " + instanceClassName + "." + attributeName + " = ?" + index++; else request += " AND " + instanceClassName + "." + attributeName + " = ?" + index++; } contents += EJBQL_STRING.replaceFirst("&eJBQL", request); contents += QUERY_ARGUMENTS_START; for (int i = 1; i < index; i++) { contents += STRING.replaceFirst("&index", "" + i); } contents += QUERY_ARGUMENTS_END + QUERY_TYPE + DATABASE_QUERY_END; } contents += DESCRIPTOR_NAMED_QUERIES_END + DESCRIPTOR_QUERY_MANAGER_END + QUERY_MANAGER_END; contents += MAPPINGS_START; it = attributeToDBMappingCollection.iterator(); while (it.hasNext()) { attributeToDBMapping = (AttributeToDBMapping) it.next(); if (attributeToDBMapping.isBoolean()) { contents += DATABASE_MAPPING_START; contents += TYPE_BOOLEAN; contents += ATTRIBUTE_NAME.replaceFirst("&attributeName", attributeToDBMapping.getAttributName()); contents += FIELD_NAME.replaceFirst("&tableName", tableName).replaceFirst("&fieldName", attributeToDBMapping.getFieldName()); contents += ATTRIBUTE_CLASSIFICATION + DEFAULT_ATTRIBUTE_VALUE; contents += FIELD_TO_ATTRIBUTE_VALUE_ASSOCIATIONS_START; contents += TYPED_ASSOCIATION_START + ASSOCIATION_KEY.replaceFirst("&associationKey", "Y"); contents += ASSOCIATION_KEY_TYPE + ASSOCIATION_VALUE_TRUE + ASSOCIATION_VALUE_TYPE + TYPED_ASSOCIATION_END; contents += TYPED_ASSOCIATION_START + ASSOCIATION_KEY.replaceFirst("&associationKey", "N"); contents += ASSOCIATION_KEY_TYPE + ASSOCIATION_VALUE_FALSE + ASSOCIATION_VALUE_TYPE + TYPED_ASSOCIATION_END; contents += FIELD_TO_ATTRIBUTE_VALUE_ASSOCIATIONS_END; contents += DATABASE_MAPPING_END; } else { contents += DATABASE_MAPPING_START; contents += TYPE; contents += ATTRIBUTE_NAME.replaceFirst("&attributeName", attributeToDBMapping.getAttributName()); contents += FIELD_NAME.replaceFirst("&tableName", tableName).replaceFirst("&fieldName", attributeToDBMapping.getFieldName()); contents += DATABASE_MAPPING_END; } } contents += MAPPINGS_END; contents += WRAPPER_POLICY_START; contents += DESCRIPTOR_WRAPPER_POLICY_START; contents += DESCRIPTOR_TYPE_VALUE; contents += HOME_NAME.replaceFirst("&pathName", packageName.replace('.', '/')).replaceFirst("&className", className); contents += HOME_INTERFACE_NAME.replaceFirst("&packageName", packageName).replaceFirst("&className", className); contents += REMOTE_INTERFACE_CLASS.replaceFirst("&packageName", packageName).replaceFirst("&className", className); contents += PRIMARY_KEY_CLASS.replaceFirst("&packageName", packageName).replaceFirst("&className", className); contents += DESCRIPTOR_WRAPPER_POLICY_END; contents += WRAPPER_POLICY_END; contents += TOPLINK_MAPPING_END; InputStream stream = new ByteArrayInputStream(contents.getBytes()); if (file.exists()) file.setContents(stream, true, true, monitor); else file.create(stream, true, monitor); stream.close(); } catch (IOException e) { } return file; } private static void throwCoreException(String message) throws CoreException { IStatus status = new Status(IStatus.ERROR, "MappingFileGenerator", IStatus.OK, message, null); throw new CoreException(status); } }
package ui.client.components; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionListener; import javax.swing.JButton; import core.Constants; public class ControlButtonGui extends JButton { private static final long serialVersionUID = -2494394522921888799L; private static final int WIDTH = Constants.SCREEN_WIDTH / 12; private static final int HEIGHT = Constants.SCREEN_HEIGHT / 12; public ControlButtonGui(String text, ActionListener listener) { super(text); setFont(new Font(Font.MONOSPACED, Font.BOLD, 20)); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setHorizontalAlignment(JButton.CENTER); addActionListener(listener); } }
package junseong.k.myapplication; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button alertbtn; Button listbtn; Button datebtn; Button timebtn; Button custombtn; AlertDialog customdialog; AlertDialog listdialog; AlertDialog alertDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alertbtn=findViewById(R.id.btn_alert); listbtn=findViewById(R.id.btn_list); datebtn=findViewById(R.id.btn_date); timebtn=findViewById(R.id.btn_time); custombtn=findViewById(R.id.btn_custom); alertbtn.setOnClickListener(this); listbtn.setOnClickListener(this); datebtn.setOnClickListener(this); timebtn.setOnClickListener(this); custombtn.setOnClickListener(this); } private void ShowToast(String message){ Toast toast=Toast.makeText(this, message, Toast.LENGTH_SHORT); toast.show(); } DialogInterface.OnClickListener dialogListener=new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { if(dialogInterface==customdialog &&which==DialogInterface.BUTTON_POSITIVE){ ShowToast("custom dialog click 혹인"); }else if(dialogInterface==listdialog){ String[] datas=getResources().getStringArray(R.array.dialog_array); ShowToast(datas[which]+"선택햇다능"); }else if(dialogInterface==alertDialog && which==DialogInterface.BUTTON_POSITIVE){ ShowToast("ALERT DIALOG 클릭"); } } }; @Override public void onClick(View v){ if(v==alertbtn){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_all_out_black_24dp); builder.setTitle("알림"); builder.setMessage("정말 종료?"); builder.setPositiveButton("ok",dialogListener); builder.setNegativeButton("no",null); alertDialog=builder.create(); alertDialog.show(); }else if(v==listbtn){ AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("알람벨소리"); builder.setSingleChoiceItems(R.array.dialog_array,0,dialogListener); builder.setPositiveButton("확인",null); builder.setNegativeButton("취소",null); listdialog=builder.create(); listdialog.show(); }else if(v==datebtn){ Calendar c=Calendar.getInstance(); int year=c.get(Calendar.YEAR); int month=c.get(Calendar.MONTH); int day=c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datedialog=new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int monthofyear, int dayofmonth) { ShowToast(year+":"+(monthofyear+1)+":"+dayofmonth); } },year,month,day); datedialog.show(); }else if(v==timebtn){ Calendar c=Calendar.getInstance(); int hour=c.get(Calendar.HOUR_OF_DAY); int minute=c.get(Calendar.MINUTE); TimePickerDialog timedialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int hourofday, int minute) { ShowToast(hourofday+":"+minute); } },hour,minute,false); timedialog.show(); }else if(v==custombtn){ AlertDialog.Builder builder=new AlertDialog.Builder(this); LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view=inflater.inflate(R.layout.dialog_layout,null); builder.setView(view); builder.setPositiveButton("확인",dialogListener); builder.setNegativeButton("취소",null); customdialog=builder.create(); customdialog.show(); } } }
public class Queue <T> implements QueueInterface<T>{ /* Circular Linked List implementation of Queue */ private Node lastnode; public void dequeueAll() { this.lastnode = null; } //checks if Queue is empty public boolean isEmpty() { return lastnode == null; } //Add item to queue public void enqueue(T item) { Node newItem = new Node(item); if(isEmpty()) { newItem.next = newItem; lastnode = newItem; } else { newItem.next = lastnode.next; lastnode.next = newItem; lastnode = newItem; } } //remove item from queue public T dequeue() { Node dequeuedItem = lastnode.next; lastnode.next = lastnode.next.next; return (T) dequeuedItem.data; } //check first item in queue public T peek() { return (T) lastnode.next.data; } }
package com.codigo.smartstore.database.domain.catalog; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.validation.constraints.Digits; import com.codigo.smartstore.database.domain.entity.ColumnPosition; @Embeddable public class Dimension implements Serializable { private static final long serialVersionUID = 1L; @Digits(integer = 3, fraction = 5) @Column(name = "WIDTH") // columnDefinition = "DECIMAL(3,5)", precision = 5, scale = 3) @ColumnPosition(position = 2) protected BigDecimal width; @Digits(integer = 3, fraction = 5) @Column(name = "HEIGHT") @ColumnPosition(position = 1) protected BigDecimal height; @Digits(integer = 3, fraction = 5) @Column(name = "DEPTH") @ColumnPosition(position = 3) protected BigDecimal depth; @Digits(integer = 3, fraction = 5) @Column(name = "GIRTH") @ColumnPosition(position = 4) protected BigDecimal girth; @Digits(integer = 3, fraction = 5) @Column(name = "CONTAINER_SIZE") @ColumnPosition(position = 5) protected String size; @Digits(integer = 3, fraction = 5) @Column(name = "CONTAINER_SHAPE") @ColumnPosition(position = 6) protected String container; @Digits(integer = 3, fraction = 5) @Column(name = "DIMENSION_UNIT_OF_MEASURE") @ColumnPosition(position = 7) protected String dimensionUnitOfMeasure; public BigDecimal getWidth() { return this.width; } public void setWidth(final BigDecimal width) { this.width = width; } public BigDecimal getHeight() { return this.height; } public void setHeight(final BigDecimal height) { this.height = height; } public BigDecimal getDepth() { return this.depth; } public void setDepth(final BigDecimal depth) { this.depth = depth; } /** * Returns the product dimensions as a String (assumes measurements are in * inches) * * @return a String value of the product dimensions */ public String getDimensionString() { return this.height + "Hx" + this.width + "Wx" + this.depth + "D\""; } public BigDecimal getGirth() { return this.girth; } public void setGirth(final BigDecimal girth) { this.girth = girth; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null) return false; if (!this.getClass() .isAssignableFrom(o.getClass())) return false; final Dimension dimension = (Dimension) o; if (this.container != null ? !this.container.equals(dimension.container) : dimension.container != null) return false; if (this.depth != null ? !this.depth.equals(dimension.depth) : dimension.depth != null) return false; if (this.dimensionUnitOfMeasure != null ? !this.dimensionUnitOfMeasure.equals(dimension.dimensionUnitOfMeasure) : dimension.dimensionUnitOfMeasure != null) return false; if (this.girth != null ? !this.girth.equals(dimension.girth) : dimension.girth != null) return false; if (this.height != null ? !this.height.equals(dimension.height) : dimension.height != null) return false; if (this.size != null ? !this.size.equals(dimension.size) : dimension.size != null) return false; if (this.width != null ? !this.width.equals(dimension.width) : dimension.width != null) return false; return true; } @Override public int hashCode() { int result = this.width != null ? this.width.hashCode() : 0; result = (31 * result) + (this.height != null ? this.height.hashCode() : 0); result = (31 * result) + (this.depth != null ? this.depth.hashCode() : 0); result = (31 * result) + (this.girth != null ? this.girth.hashCode() : 0); result = (31 * result) + (this.size != null ? this.size.hashCode() : 0); result = (31 * result) + (this.container != null ? this.container.hashCode() : 0); result = (31 * result) + (this.dimensionUnitOfMeasure != null ? this.dimensionUnitOfMeasure.hashCode() : 0); return result; } }
package com.spart.io.Controller; import com.spart.io.Model.Employee; import java.io.BufferedReader; import java.io.FileReader; import java.sql.*; public class CRUD implements DAO { @Override public void getEmployee(int id) { try{ Connector connect =Connector.getIns(); Connection connection= connect.getCon(); Statement statement =connection.createStatement(); ResultSet s=statement.executeQuery("SELECT * FROM Records WHERE Emp_ID =" + id); System.out.println( "Employee_ID: " + s.getInt("Emp_ID")+" "+ "Prefix: " +s.getString("NAME_PREFIX")+" "+ "First_Name: "+s.getString("FIRST_NAME")+" "+ "Middle_Initial: "+s.getString("MID_INITIAL")+" "+ "Last_Name: "+s.getString("LAST_NAME")+" "+ "Gender: "+s.getString("GENDER")+" "+ "Email: "+s.getString("EMAIL")+" "+ "DOB: "+s.getDate("DOB")+" "+ "DOJ: "+s.getDate("DOJ")+" "+ "SALARY: "+s.getInt("SALARY")); statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } @Override public void addNewEmployee(Employee employee) { try{ Connector connect =Connector.getIns(); Connection connection= connect.getCon(); PreparedStatement statement= connection.prepareStatement("INSERT INTO Records(Emp_ID, NAME_PREFIX, FIRST_NAME, MID_INITIAL, LAST_NAME, GENDER, EMAIL, DOB, DOJ, SALARY)" + "VALUES(?,?,?,?,?,?,?,?,?,?)"); statement.setInt(1, employee.getEmpID()); statement.setString(2, employee.getNamePrefix()); statement.setString(3, employee.getfName()); statement.setString(4, employee.getMiddleInitial()); statement.setString(5, employee.getlName()); statement.setString(6, employee.getGender()); statement.setString(7, employee.getEmail()); statement.setDate(8, employee.getDob()); statement.setDate(9, employee.getDoj()); statement.setInt(10, employee.getSalary()); statement.execute(); statement.close(); connection.setAutoCommit(false); connection.commit(); connection.close(); statement.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } @Override public void updateEmployeeSalary(int id, int newSalary) { try{ System.out.println("update"); Connector connect =Connector.getIns(); Connection connection= connect.getCon(); Statement statement =connection.createStatement(); statement.executeUpdate("UPDATE Records SET SALARY=" +newSalary + " WHERE Emp_ID = "+ id); statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } @Override public void deleteEmployee(int id){ try{ System.out.println("delete"); Connector connect =Connector.getIns(); Connection connection= connect.getCon(); Statement statement =connection.createStatement(); statement.executeUpdate("DELETE FROM Records WHERE Emp_ID = "+ id); statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } }
/** * Possible operations available to remote client. * * * @author Elena Villalon */ package jremote; import java.util.List; import java.util.Vector; public class RemoteMethodsAdapter implements RemoteMethods{ public RemoteMethodsAdapter(){ super(); } /**add video url to database*/ public void addVideo(String url){ return; } /**retrieve videos under the classification tag*/ public String videoLabel(String tag) { return ""; } /**show statistics of database*/ public String databaseStat(){ return ""; } /**connect to remote server and database*/ public void connect(int clientID){ return; } public String classifyVideo(String method, List<String>lstVideos){ return ""; } /**retrieve video metadata*/ public String describeVideo(String url){ return ""; } public void addLabel(String tag, Vector<String>urls){ } public String findSimilarCategory(String str){ return ""; } }
package com.designurway.idlidosa.ui.home_page.fragments; import androidx.annotation.NonNull; import androidx.navigation.ActionOnlyNavDirections; import androidx.navigation.NavDirections; import com.designurway.idlidosa.HomeNavGraphDirections; import com.designurway.idlidosa.R; public class EmergencyFragmentDirections { private EmergencyFragmentDirections() { } @NonNull public static NavDirections actionEmergencyFragmentToViewCartItemsFragment2() { return new ActionOnlyNavDirections(R.id.action_emergencyFragment_to_viewCartItemsFragment2); } @NonNull public static NavDirections actionGlobalNotificationListFragment() { return HomeNavGraphDirections.actionGlobalNotificationListFragment(); } }
package com.rev.dao.spring; import com.rev.dao.RoomRepository; import com.rev.model.Room; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class RoomSpringRepository extends SpringRepository<Room> implements RoomRepository { @Autowired public RoomSpringRepository(SessionFactory sf){ super(sf); } }
package com.flyingh.moguard.service; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class KillBackgroundProcessesService extends Service { private ActivityManager am; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) { am.killBackgroundProcesses(runningAppProcessInfo.processName); } return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); } }
package com.gxtc.huchuan.bean; /** * Created by Administrator on 2018/3/31. */ public class ClassOrderHeadBean { double realIncome; int count; public double getRealIncome() { return realIncome; } public void setRealIncome(double realIncome) { this.realIncome = realIncome; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
package domain; public abstract class Werknemer { private String naam, voornaam, rijksregisternummer; private int aantalGewerkteUren; public Werknemer(String naam, String voornaam, String rijksregisternummer) { if (naam.trim().isEmpty() || voornaam.trim().isEmpty() || rijksregisternummer.trim().isEmpty()) throw new IllegalArgumentException("Velden mogen niet leeg zijn."); if (!rijksregisternummer.matches("\\d{2}.\\d{2}.\\d{2}-\\d{3}.\\d{2}")) throw new IllegalArgumentException("Rijksregisternummer moet formaat respecteren."); this.naam = naam; this.voornaam = voornaam; this.rijksregisternummer = rijksregisternummer; } public abstract int verloning(); public void resetAantalUren() { aantalGewerkteUren = 0; } public void veranderUren(int aantal) { aantalGewerkteUren += aantal; } public String getNaam() { return naam; } public String getVoornaam() { return voornaam; } public String getRijksregisternummer() { return rijksregisternummer; } public int getAantalGewerkteUren() { return aantalGewerkteUren; } @Override public String toString() { return this.getClass().getSimpleName() + ": " + this.naam + " (" + this.rijksregisternummer + ")\n" + "Verloning: " + verloning() + "\n" + "Aantal uren gewerkt (nog niet betaald): " + this.aantalGewerkteUren; } }
package peropt.me.com.performaceoptimization.dn; /** * desc: */ public class HandlerTest { }
package listTest; import java.util.Stack; public class StackDemo { public static void main(String[] args) { Stack<Integer> s = new Stack(); for (int i = 0 ; i < 10 ; i ++){ s.push(i); } int r = s.pop()+s.pop(); System.out.println(r); int c = s.peek(); Stack<Integer> s2 = new Stack<>(); //int d = s.pop(); //System.out.println(d); while(s.peek()!=3){ int f= s.pop(); s2.push(f); } System.out.println("-----------------------"); System.out.println(c); System.out.println("-----------------------"); for (int a : s){ System.out.println(a); } System.out.println("-----------------------"); for (int a : s2){ System.out.println(a); } } }
package com.esum.as2.transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.as2.AS2Exception; import com.esum.as2.message.AS2Message; import com.esum.as2.message.AS2MessageException; import com.esum.as2.message.MDNMessage; import com.esum.as2.message.Message; import com.esum.as2.message.MessageUtil; import com.esum.as2.message.Routing; import com.esum.as2.msh.AS2InboundException; import com.esum.as2.msh.AdapterFactory; import com.esum.as2.msh.InboundProcessor; import com.esum.as2.msh.InboundUtil; import com.esum.as2.storage.PartnerInfoRecord; import com.esum.as2.storage.RoutingManager; import com.esum.framework.core.queue.JmsMessageHandler; /** * 특정 adapter에 대해 TransactionQueue로 들어와서 처리하는 모듈. * Inbound중에는 Synchronous/Asychronous가 있으며, 각각에 대해 AynchInboundProcessor와 SyncInboundProcessor를 호출한다. * * Copyrights(c) eSum Technologies., Inc. All rights reserved. */ public class InboundTransactionProcessor extends TransactionProcessor { private Logger log = LoggerFactory.getLogger(InboundTransactionProcessor.class); private TransactionLog transLog; /** * 특정 adapterId와 TransactionQueue에 대한 Inbound Processor를 생성한다. */ public InboundTransactionProcessor(String traceId, String channelName, JmsMessageHandler queueHandler) { super(traceId, channelName, queueHandler); transLog = new TransactionLog(); } /** * 상위의 TransactionProcessor Thread에서 TransactionEvent를 받았을때 이 메소드가 호출된다. * MDN Message와 AS2Message를 수신했을때 처리하는 루틴이다. */ public void onMessage(TransactionEvent event) throws AS2InboundException{ log.info(traceId + "Received TransactionEvent from queue."); Message message = null; try { message = MessageUtil.unmarshal(traceId, event.toInternetHeaders(), event.getMessage()); } catch (AS2MessageException e) { log.error(traceId+"message parsing error", e); return; } String logId = traceId+"["+event.getMessageId()+"] "; log.debug(logId + "Message Type: " + event.getMessageType()); if(message instanceof MDNMessage){ new InboundProcessor(logId, event, transLog).processMDN((MDNMessage)message); } else { AS2Message as2Msg = (AS2Message)message; log.debug(logId + "is async : "+as2Msg.isAsyncMessage()); if(as2Msg.isAsyncMessage()) { MDNMessage mdn = null; try{ mdn = new InboundProcessor(logId, event, transLog).process(as2Msg); } catch(AS2Exception e){ log.error(e.getMessage(), e); } if(mdn != null ) { Routing routing = event.getRouting(); try { log.debug(logId + "Searching Partner Information... From: " + routing.getFrom() ); PartnerInfoRecord partner = RoutingManager.getInstance().getPartnerInfo(routing.getFrom()); if(partner==null) throw new Exception("Can not found parter. from : "+routing.getFrom()); InboundUtil.sendAsyncMDN(logId, partner, mdn); log.debug(logId + "Sending AS2 MDN Message to Adapter"); AdapterFactory.getInstance().getAdapter().onSentMDN(mdn); log.info(logId + "Sent AS2 MDN Message to Inbound Adapter(onSentMDN)."); } catch (Exception e) { log.error(logId+"can not send to adapter.", e); } } try { log.debug(logId + "Logging Transaction into file, DB..."); transLog.updateMessageLog(event.getTransferType(), event.getMessageId(), mdn, event.getErrorCode(), event.getErrorLocation(), event.getErrorDesc(), 0); log.debug(logId + "Logged Transaction into file, DB. Message Type: MDN"); } catch (TransactionException e) { log.error(logId+"can not update message log.", e); } } else { log.error(logId+"Asynchronous Message recieved check..logs.."); } } log.info(traceId + "Processed Inbound Message."); } }
/* * 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 mwr.prototype.dao; import java.util.Date; import java.util.List; import javax.mail.Address; import javax.persistence.TypedQuery; import mwr.prototype.entities.Email; /** * * @author Jessica */ public interface EmailDaoLocal { /** * * @return all emails in the email table */ public List<Email> findAllEmails(); /** * * @param recipientId username of recipient. This is the emailToUserId in the email entity * @return applicable email entities */ public List<Email> findEmailsByRecipient(String recipientId); /** * * @param senderId username of sender. This is the emailToFromId in the email entity * @return */ public List<Email> findEmailsBySender(String senderId); public void saveEmail(Email email); public Email findEmailsById(Long id); public List<Email> findDraftEmailBySender(String username); }
package atm.utils; /** * Defines some status returned by the ATM */ public class Status{ public static final int SUCCESS = 0; public static final int TOO_LITTLE_CASH = 1; public static final int UNKNOWN_CARD = 2; public static final int UNKNOWN_FINGER = 3; public static final int WRONG_PIN = 4; public static final int INSUFFICIENT_AVAILABLE_BALANCE = 5; }
package com.exam.models; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; import java.io.Serializable; @Value @AllArgsConstructor @Builder public class Relation implements Serializable { private static final long serialVersionUID = -4708283852516612162L; private final Long id; private final Long sender; private final Long recipient; private final Integer type; }
package at.craftworks.challenge.tms.repository; import org.springframework.data.repository.CrudRepository; import at.craftworks.challenge.tms.model.Task; public interface TaskRepository extends CrudRepository<Task, Long>{ }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.robotcore.external.Telemetry; public class Movement { LinearOpMode op; RobotHardware robotHardware; Telemetry telemetry; Constants constants = new Constants(); public double strafe = 0; public double drive = 0; public double turn = 0; public double ix, iy, dx, dy, prevX, prevY = 0; public Movement(LinearOpMode op, RobotHardware robotHardware, Telemetry telemetry) { this.op = op; this.robotHardware = robotHardware; this.telemetry = telemetry; } public void setPowers() { setPowers(constants.shooterPower); } public void setPowers(double shooterPower) { //+ = forward, right, ccw robotHardware.shooter.setVelocity(shooterPower); robotHardware.fr.setPower(drive - strafe + turn); robotHardware.fl.setPower(drive + strafe - turn); robotHardware.br.setPower(drive + strafe + turn); robotHardware.bl.setPower(drive - strafe - turn); } public void resetPower() { strafe = 0; drive = 0; turn = 0; } public void turnTo(double angle, BackboardPipeline pipeline) { turn = (pipeline.getAngle() - angle) / 60; } public void turnTo(double angle) { double currentAngle = robotHardware.getAngle(); // double power = (angle == 180) ? (currentAngle >= 0 ? currentAngle - 180 : 180 + currentAngle) : currentAngle - angle; turn = (angle - currentAngle) / 40; } public void turnToX(int x, BackboardPipeline pipeline) { if (pipeline.detected()) { turn = (x - pipeline.getX()) / 300.0; } } public void goToPoint(int x, int y, int currentX, int currentY, BackboardPipeline pipeline, double power1, double power2) { //PID controller go to point //constants double kp = 1 / 80.0; double ki = 1 / 50000000.0; double kd = 1 / 400.0; //proportional(delta x/y) double deltaX = currentX - x; double deltaY = currentY - y; //proportional power value double px = deltaX * kp; double py = deltaY * kp; //derivative controller dx = (x - prevX) * kd; dy = (y - prevY) * kd; prevX = currentX; prevY = currentY; //integral controller if within 10 units from intended spot if (deltaX > 10 || deltaX <= 2) ix = 0; else ix+= deltaX * ki; if (deltaY > 10 || deltaY <= 2) iy = 0; else iy+= deltaY * ki; //set powers // strafe = px + ix - dx; // drive = py + iy - dy; strafe = px + dx; drive = py + dy; strafe*= power2; drive*= power1; } public void goToPoint(int x, int y, BackboardPipeline pipeline, boolean straight, double power1, double power2) { if (straight) { turnTo(0); } if (pipeline.detected()) { goToPoint(x, y, pipeline.getX(), pipeline.getY(), pipeline, power1, power2); } } public void goToPoint(int x, int y, BackboardPipeline pipeline) { goToPoint(x, y, pipeline, 1); } public void goToPoint(int x, int y, BackboardPipeline pipeline, double power) { goToPoint(x, y, pipeline, true, power, power / 0.8); } public void goToPoint(int x, int y, BackboardPipeline pipeline, double power1, double power2) { goToPoint(x, y, pipeline, true, power1, power2); } public void shoot(int velocity, double power) { robotHardware.shooter.setVelocity(velocity); if (Math.abs(robotHardware.shooter.getVelocity() - velocity) < 200) { robotHardware.blocker.setPosition(constants.blockerUp); robotHardware.intake.setPower(1); robotHardware.cleanser.setPower(power); } else { robotHardware.intake.setPower(0); robotHardware.cleanser.setPower(0); } } public void shoot(int velocity) { shoot(velocity, 1); } public void shoot() { shoot(constants.shooterPower); } // public void shooterOff() { // robotHardware.shooter.setVelocity(0); // robotHardware.intakeOff(); // } public boolean closeTo(int x, int y, int closeness, BackboardPipeline pipeline) { return Math.sqrt(Math.abs(Math.pow(x- pipeline.getX(), 2) + Math.pow(y - pipeline.getY(), 2))) <= closeness; } public boolean closeTo(int x, int y, BackboardPipeline pipeline) { return closeTo(x, y, 25, pipeline); } public boolean angleCloseTo(double angle) { return (Math.abs(robotHardware.getAngle()) < angle); } public double speed() { return Math.abs(drive) + Math.abs(turn) + Math.abs(strafe); } public void block() { block(true); } public void block(boolean down) { robotHardware.blocker.setPosition(down ? constants.blockerDown : constants.blockerUp); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Threads; import java.util.Scanner; /** * * @author rm */ public class Sleep_Class_Vedio5 extends Thread { public static void main(String[] args) { Sleep_Class_Vedio5 obj = new Sleep_Class_Vedio5(); System.out.println("enter 1 to start or 0 to stop"); obj.start(); obj.setstatus(new Scanner(System.in).nextInt()); } private boolean starting = true; private volatile int status = 1; private void startup() { starting = true; } private void shutdown() { starting = false; } private void changestatus() { if (getstatus() == 0) { shutdown(); exit(); } else { startup(); } } private void setstatus(int status) { this.status = status; } private int getstatus() { return status; } private void process() { while (starting) { System.out.println("system is running now"); changestatus(); try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } private void exit() { for (int index = 0; index < 30; index++) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } System.out.print(" . "); System.out.print(""); System.out.print(" system shutdown completed "); System.out.print("------------------------------------------"); } } @Override public void run() { process(); } }
package com.zheng.highconcurrent.concurrent.reentrantlock; import java.util.concurrent.locks.ReentrantLock; /** * 可中断死锁检查 * * @Author zhenglian * @Date 2019/1/12 */ public class InterruptReentrantLockApp { private static final ReentrantLock lock1 = new ReentrantLock(); private static final ReentrantLock lock2 = new ReentrantLock(); private static class ReenterLockInt implements Runnable { private int lock; public ReenterLockInt(int lock) { this.lock = lock; } @Override public void run() { try { if (lock == 1) { lock1.lockInterruptibly(); try { Thread.sleep(1000); } catch (InterruptedException e) {} lock2.lockInterruptibly(); } else { lock2.lockInterruptibly(); try { Thread.sleep(1000); } catch (InterruptedException e) {} lock1.lockInterruptibly(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { if (lock1.isHeldByCurrentThread()) { lock1.unlock(); } if (lock2.isHeldByCurrentThread()) { lock2.unlock(); } System.out.println(Thread.currentThread().getId() + "线程退出"); } } } public static void main(String[] args) throws Exception { ReenterLockInt r1 = new ReenterLockInt(1); ReenterLockInt r2 = new ReenterLockInt(2); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); t1.start(); t2.start(); Thread.sleep(2000); // 中断其中一个线程 DeadThreadChecker.check(); } }
package concursantes; import org.springframework.stereotype.Component; @Component public class Audiencia { public void sentarse(){ System.out.println("El show esta por comenzar, porfavor tomar haciento.."); } public void apagarCelulares(){ System.out.println("Favor apagar los celulares.."); } public void aplaudir(){ System.out.println("El show a terminado, bravo..bravo..chap chap chap.."); } public void devolucion(){ System.out.println("Terrible presentacion, se devolveran las entradas"); } }
package com.example.bootcamp.security; import static com.example.bootcamp.security.SecurityConstants.HEADER_STRING; import static com.example.bootcamp.security.SecurityConstants.SECRET; import static com.example.bootcamp.security.SecurityConstants.TOKEN_PREFIX; import java.io.IOException; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; public class JWTAuthorizationFilter extends BasicAuthenticationFilter { public JWTAuthorizationFilter(AuthenticationManager authManager) { super(authManager); } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader(HEADER_STRING); if (header == null || !header.startsWith(TOKEN_PREFIX)) { chain.doFilter(req, res); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(req); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); } private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) { String token = request.getHeader(HEADER_STRING); if (token != null) { // parse the token. String user = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) .getBody() .getSubject(); Collection authorities= new ArrayList<>(); try { if(Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) .getBody().get("role")!=null) { authorities = Arrays.stream(Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token.replace(TOKEN_PREFIX, "")) .getBody().get("role").toString().split(",")).map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } Claims claims = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody(); Date expirationTime = claims.getExpiration(); Date currentTime = new Date(System.currentTimeMillis()); if(claims.getExpiration()!=null) { if(expirationTime.before(currentTime)) {return null;} }else {return null;} LocalDate currentDate = LocalDate.now(); if(claims.getIssuedAt()!=null) { LocalDate issueDate = claims.getIssuedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); //System.out.println(issueDate.isEqual(currentDate)); if(!issueDate.isEqual(currentDate)) {return null;} }else { return null; } } catch (UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) { logger.error("Invalid token"); return null; } if (user != null) { return new UsernamePasswordAuthenticationToken(user, null,authorities); } return null; } return null; } }
package dacorators; import AdapterPattern.Pigeon; import AdapterPattern.Quackable; public class DoubleTab implements Quackable { private Pigeon pigeon; public DoubleTab(Pigeon pigeon){ this.pigeon = pigeon; } public void call(){ this.pigeon.coo(); } @Override public void quack() { call(); call(); System.out.println(); } }
package frameWork; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import Castlevenia.Handler; public class KeyInput extends KeyAdapter implements KeyListener { //abstraction Handler handler; public int Key; public KeyInput(Handler handler) { this.handler = handler; } //below method will move the player when a certain key is pressed public void keyPressed(KeyEvent e) { Key = e.getKeyCode(); for(int i = 0; i < handler.object.size(); i++ ) { GameObject tempObject = handler.object.get(i); if(tempObject.getId() == ObjectId.Player) { if(Key == KeyEvent.VK_RIGHT) { //if right arrow key is pressed the velocity of the player will be 2 and the player will move right tempObject.setVelX(2); } if(Key == KeyEvent.VK_LEFT) { //if left arrow key is pressed the velocity of the player will be -2 and the player will move left tempObject.setVelX(-2); } if(Key == KeyEvent.VK_UP && !tempObject.isJumping()) //the method will make the player jump { tempObject.setJumping(true); tempObject.setVelY(-5); } } if(Key == KeyEvent.VK_A) { tempObject.setVelX((float) 0.5); } if(Key == KeyEvent.VK_ESCAPE) { //if escape is pressed the window will exit System.exit(1); } } } //the method will make the velocity of the player zero public void keyReleased(KeyEvent e) { int Key = e.getKeyCode(); for(int i = 0; i < handler.object.size(); i++ ) { GameObject tempObject = handler.object.get(i); if(tempObject.getId() == ObjectId.Player) { if(Key == KeyEvent.VK_RIGHT) { tempObject.setVelX(0); } if(Key == KeyEvent.VK_LEFT) { tempObject.setVelX(0); } if(Key == KeyEvent.VK_UP ) { tempObject.setVelY(0); } if(Key == KeyEvent.VK_A) { tempObject.setVelX(0); } } } } }
/* * to change this template, choose Tools | Templates * and open the template in the editor. */ package org.jearl.email.smtp; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.concurrent.ScheduledThreadPoolExecutor; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.jearl.ejb.model.email.EMailRecipient; import org.jearl.ejb.model.email.EMailRecipientTypeEnum; import org.jearl.email.EMailSender; import org.jearl.email.exception.EMailException; import org.jearl.email.model.EMail; import org.jearl.email.model.EMailLogger; import org.jearl.email.smtp.model.SmtpProperties; import org.jearl.logback.ErrorCategory; import org.jearl.log.JearlLogger; import org.jearl.log.Logger; /** * * @author bamasyali */ public class SmtpSender implements EMailSender<SmtpProperties> { private final JearlLogger logger; public SmtpSender() { this.logger = Logger.getJearlLogger(SmtpSender.class); } @Override public void sendMail(final SmtpProperties properties, EMail email, Boolean isThreaded) throws EMailException { if (email.getFrom() == null) { email.setFrom(properties.getUsername()); } if (email.getTo().isEmpty() && email.getCc().isEmpty() && email.getBcc().isEmpty()) { throw new EMailException("Need Recipients!!!"); } if (email.getEmailTopic() == null) { throw new EMailException("Need Topic!!!"); } if (email.getEmailContent() == null) { throw new EMailException("Need Content!!!"); } if (email.getReplyTo() == null) { email.setReplyTo(properties.getUsername()); } Properties props = new Properties(); props.put("mail.smtp.host", properties.getHost()); props.put("mail.from", email.getFrom()); props.put("mail.smtp.port", properties.getPort()); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", properties.getTls()); //props.put("mail.debug", "true"); props.put("mail.smtp.auth", properties.getAuth()); props.put("mail.smtp.ssl.enable", properties.getSsl()); class PopupAuthenticator extends Authenticator { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(properties.getUsername(), properties.getPassword()); } } Authenticator authenticator = null; if (properties.getAuth().equals("true")) { authenticator = new PopupAuthenticator(); } Session session = Session.getInstance(props, authenticator); //session.setDebug(true); try { final MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setReplyTo(InternetAddress.parse(email.getReplyTo())); Integer sizeOfTo = email.getSizeOfTo(); for (int i = 0; i < sizeOfTo; i++) { InternetAddress address = new InternetAddress(email.getTo().get(i)); msg.addRecipient(MimeMessage.RecipientType.TO, address); } Integer sizeOfCc = email.getSizeOfCc(); for (int i = 0; i < sizeOfCc; i++) { InternetAddress address = new InternetAddress(email.getCc().get(i)); msg.addRecipient(MimeMessage.RecipientType.CC, address); } Integer sizeOfBcc = email.getSizeOfBcc(); for (int i = 0; i < sizeOfBcc; i++) { InternetAddress address = new InternetAddress(email.getBcc().get(i)); msg.addRecipient(MimeMessage.RecipientType.BCC, address); } msg.setSubject(email.getEmailTopic(), "utf-8"); msg.setSentDate(new Date(System.currentTimeMillis())); Multipart multipart = new MimeMultipart(); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(email.getEmailContent(), "text/html; charset=utf-8"); multipart.addBodyPart(mbp1); for (File file : email.getFileList()) { MimeBodyPart mbp2 = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); multipart.addBodyPart(mbp2); } msg.setContent(multipart); if (isThreaded) { Thread thread = new Thread() { @Override public void run() { try { Transport.send(msg); } catch (Exception ex) { logger.error(ex.getMessage(), ErrorCategory.EMAIL_ERROR, ex); } } }; thread.start(); } else { Transport.send(msg); } } catch (Exception mex) { // Prints all nested (chained) exceptions as well throw new EMailException("EMail Sent Error : " + mex.getMessage(), mex); } } @Override public void sendMail(SmtpProperties properties, List<EMail> emails) throws EMailException { for (EMail email : emails) { sendMail(properties, email, false); } } @Override public void sendMail(final SmtpProperties properties, List<EMail> emails, Integer threadNumber) throws EMailException { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(threadNumber); for (final EMail email : emails) { Runnable runnable = new Runnable() { @Override public void run() { try { sendMail(properties, email, false); } catch (EMailException ex) { logger.error(ex.getMessage(), ErrorCategory.EMAIL_ERROR, ex); } } }; executor.execute(runnable); } } @Override public void log(EMailLogger logger, List<EMail> emails) { for (EMail email : emails) { try { org.jearl.ejb.model.email.EMail mail = logger.initEmail(); mail.setMailContent(email.getEmailContent()); mail.setMailSenderip(logger.getUserIp()); mail.setMailSenttime(new Date(System.currentTimeMillis())); mail.setMailTopic(email.getEmailTopic()); mail.setMailUser(logger.getUser()); mail.setMailAccount(logger.getEMailAccount()); List<EMailRecipient> recipients = new ArrayList<EMailRecipient>(); if (email.getTo() != null) { List<String> strings = email.getTo(); for (String to : strings) { EMailRecipient recipient = logger.initRecipient(); recipient.setRcpAdress(to); recipient.setRcpMail(mail); recipient.setRcpRecipientType(logger.initRecipientType(EMailRecipientTypeEnum.TO)); recipients.add(recipient); } } if (email.getCc() != null) { List<String> strings = email.getCc(); for (String to : strings) { EMailRecipient recipient = logger.initRecipient(); recipient.setRcpAdress(to); recipient.setRcpMail(mail); recipient.setRcpRecipientType(logger.initRecipientType(EMailRecipientTypeEnum.CC)); recipients.add(recipient); } } if (email.getBcc() != null) { List<String> strings = email.getBcc(); for (String to : strings) { EMailRecipient recipient = logger.initRecipient(); recipient.setRcpAdress(to); recipient.setRcpMail(mail); recipient.setRcpRecipientType(logger.initRecipientType(EMailRecipientTypeEnum.BCC)); recipients.add(recipient); } } mail.setMailFrom(email.getFrom()); mail.setMailRecipientList(recipients); logger.getEntityManager().persist(mail); } catch (Exception ex) { //logger. } } } }
package org.uth.jdgtest1; import org.uth.jdgtest1.listeners.ExpirationEventLogListener; import java.util.concurrent.TimeUnit; import org.infinispan.client.hotrod.*; public class ExpirationTest { public static void main( String[] args ) { RemoteCacheManager rcm = new RemoteCacheManager(); RemoteCache<Integer,String> cache = rcm.getCache(); //rcm.start(); ExpirationEventLogListener listener = new ExpirationEventLogListener(); try { cache.addClientListener( listener ); ExpirationTest.log( "Adding 20 entries with 10 seconds expiration..."); long start = System.currentTimeMillis(); for( int loop = 0; loop < 20; loop++ ) { cache.put( loop, Integer.toString( loop ) ); cache.put(loop, Integer.toString(loop), 10, TimeUnit.SECONDS); } long end = System.currentTimeMillis(); ExpirationTest.log( "Added 20 items in " + ( end - start) + "ms." ); ExpirationTest.log( "Cache thinks it has " + cache.size() + "entries." ); for( int loop = 0; loop < 20; loop++ ) { String fetch = cache.get(loop); ExpirationTest.log( "Fetched " + loop + " and received " + fetch ); } // Manual remove cache.remove(10); cache.remove(15); try { Thread.sleep(11000); } catch( Exception exc ) { } ExpirationTest.log( "After 11 seconds cache thinks it has " + cache.size() + " entries." ); //rcm.stop(); } finally { cache.removeClientListener( listener ); ExpirationTest.log( "Clearing down cache (removing " + cache.size() + " entries)"); long start = System.currentTimeMillis(); cache.clear(); long end = System.currentTimeMillis(); ExpirationTest.log( "Cache cleared in " + ( end - start ) + "ms."); } } private static void log( String message ) { System.out.println( "[ExpirationTest] " + message ); } }
package myLabs; import java.util.Scanner; /** * Created by 12 on 30.10.2017. * Count summary of numbers */ public class SumOfNumbers { public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println("введите число"); int input=sc.nextInt(); sc.close(); int temp; int sum=0; while (input!=0){ temp=input%10; sum+=temp; input/=10; } System.out.println("Сумма цифр = "+sum); } }
package com.dbs.portal.ui.component.view; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.vaadin.ui.AbstractLayout; import com.vaadin.ui.CssLayout; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; public class BaseWindow extends Window implements IWindow{ private CssLayout mainLayout = new CssLayout(); private Map<String, IView> mapOfLayout = null; private Map<String, IView> hiddenLayout = new HashMap<String, IView>(); private Map<IView, Boolean> originalVisibility = new HashMap<IView, Boolean>(); private boolean timeStampRequired = true; private TimeStampView timeStampView = new TimeStampView(); private List<String> layoutPackedList = new ArrayList<String>(); private String id = null; private boolean isExporting = false; public void init() { ((AbstractLayout)this.getContent()).addStyleName("main-margin"); mainLayout.setSizeUndefined(); mainLayout.setWidth("100%"); this.setWidth("90%"); this.addComponent(mainLayout); VerticalLayout othersLayout = new VerticalLayout(); othersLayout.setSpacing(true); boolean firstLayout = true; if (mapOfLayout != null){ for (Iterator<String> it = mapOfLayout.keySet().iterator() ; it.hasNext() ;){ String key = it.next(); IView layout = mapOfLayout.get(key); if (firstLayout){ mainLayout.addComponent((AbstractLayout)layout); firstLayout = false; mainLayout.addComponent(othersLayout); }else othersLayout.addComponent((AbstractLayout)layout); if (((AbstractLayout)layout).isVisible()){ layout.packLayout(); layoutPackedList.add(key); } originalVisibility.put(layout, ((AbstractLayout)layout).isVisible()); } } if (hiddenLayout != null){ for (Iterator<String> it = hiddenLayout.keySet().iterator() ; it.hasNext() ;){ String key = it.next(); IView layout = hiddenLayout.get(key); othersLayout.addComponent((AbstractLayout)layout); if (((AbstractLayout)layout).isVisible()){ layout.packLayout(); layoutPackedList.add(key); } othersLayout.removeComponent((AbstractLayout)layout); originalVisibility.put(layout, ((AbstractLayout)layout).isVisible()); } } if (timeStampRequired){ timeStampView.packLayout(); mainLayout.addComponent(timeStampView); } //add close listener inorder to close //application immediately after user leave the page this.addListener(new CloseListener(){ @Override public void windowClose(CloseEvent e) { if (!isExporting){ BaseWindow.this.getApplication().close(); }else{ isExporting = false; } } }); } public void setMapOfLayout(Map<String, IView> mapOfLayout) { this.mapOfLayout = mapOfLayout; } public Map<String, IView> getMapOfLayout(){ return this.mapOfLayout; } public void setHiddenLayout(Map<String, IView> hiddenLayout){ this.hiddenLayout = hiddenLayout; } public IView getView(String name) { IView view = mapOfLayout.get(name); if (view == null){ view = hiddenLayout.get(name); } if (!layoutPackedList.contains(name)){ view.packLayout(); layoutPackedList.add(name); } return view; } /* public void setAllInvisible(){ int i = 0; for(Iterator<String> it = mapOfLayout.keySet().iterator() ; it.hasNext() ;){ String key = it.next(); IView layout = mapOfLayout.get(key); layout.setVisible(false); } }*/ public void setNoResultViewInvisible() { String key = "NoResultView"; if (mapOfLayout.containsKey(key)) { IView layout = mapOfLayout.get(key); if (layout != null) { layout.setVisible(false); } } } public void resetPage(){ for (Iterator<IView> it = originalVisibility.keySet().iterator() ; it.hasNext() ;){ IView visibleView = it.next(); visibleView.setVisible(originalVisibility.get(visibleView)); } } public void setTimeStampRequired(boolean timeStampRequired){ this.timeStampRequired = timeStampRequired; } public boolean getTimeStampRequired(){ return this.timeStampRequired; } public void updateTimeStamp(){ timeStampView.refresh(); } public void setId(String id){ this.id= id; } public String getId(){ return this.id; } @Override public void retrieveInfo() { if (mapOfLayout != null){ for (Iterator<String> it = mapOfLayout.keySet().iterator() ; it.hasNext() ;){ String key = it.next(); IView layout = mapOfLayout.get(key); if (layout instanceof IEnquiryView){ ((IEnquiryView)layout).retrieveInfo(); } } } if (hiddenLayout != null){ for (Iterator<String> it = hiddenLayout.keySet().iterator() ; it.hasNext() ;){ String key = it.next(); IView layout = hiddenLayout.get(key); if (layout instanceof IEnquiryView){ ((IEnquiryView)layout).retrieveInfo(); } } } } public void setExporting(boolean isExporting){ this.isExporting = isExporting; } public boolean isExporting(){ return this.isExporting; } }
package com.netcracker.app.domain.info.entities.vacancies; import com.netcracker.app.domain.info.entities.resumes.ResumeImpl; import net.minidev.json.annotate.JsonIgnore; import javax.persistence.Entity; import javax.persistence.OneToMany; import java.util.Set; @Entity public class VacancyImpl extends AbstractVacancy { public VacancyImpl(String name, String text) { super(name, text); } public VacancyImpl() { super(); } public Set<ResumeImpl> getResumes() { return resumes; } public void setResumes(Set<ResumeImpl> resumes) { this.resumes = resumes; } @OneToMany(mappedBy = "vacancy") @JsonIgnore Set<ResumeImpl> resumes; public static String[] getFieldsNames() { String[] names = {"name", "text"}; return names; } }
package com.tauros; public class UserAlreadyExists extends Throwable{ public static final String message = "User already exists"; }
package com.cairenhui.service; import com.cairenhui.model.FileStoreModel; import com.cairenhui.model.VideoModel; public interface VideoBusinessService { public int insert(VideoModel videoModel); public void update(VideoModel videoModel); public VideoModel getObjectByBizId(String string, String bizType); }
package com.esum.wp.ims.monitorinfo.struts.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.esum.appcommon.resource.application.Config; import com.esum.appcommon.session.SessionMgr; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.struts.action.BaseDelegateAction; import com.esum.appframework.struts.actionform.BeanUtilForm; import com.esum.router.RouterConfig; import com.esum.wp.ims.monitorinfo.MonitorInfo; import com.esum.wp.ims.monitorinfo.service.IMonitorInfoService; public class MonitorInfoAction extends BaseDelegateAction { protected ActionForward doService( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (method.equals("selectList")) { MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } int itemCountPerPage = Config.getInt("Common", "LIST.COUNT_PER_PAGE"); if(inputObject == null) { monitorInfo = new MonitorInfo(); monitorInfo.setCurrentPage(new Integer(1)); monitorInfo.setItemCountPerPage(new Integer(itemCountPerPage)); }else { monitorInfo = (MonitorInfo)inputObject; if(monitorInfo.getCurrentPage() == null) { monitorInfo.setCurrentPage(new Integer(1)); } if(monitorInfo.getItemCountPerPage() == null) { monitorInfo.setItemCountPerPage(new Integer(itemCountPerPage)); } } //db SessionMgr sessMgr = new SessionMgr(request); monitorInfo.setDbType(sessMgr.getValue("dbType")); beanUtilForm.setBean(monitorInfo); request.setAttribute("inputObject", monitorInfo); return super.doService(mapping, beanUtilForm, request, response); } else if (method.equals("select")) { MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { monitorInfo = new MonitorInfo(); }else { monitorInfo = (MonitorInfo)inputObject; } beanUtilForm.setBean(monitorInfo); request.setAttribute("inputObject", monitorInfo); request.setAttribute("outputObject", new MonitorInfo()); List nodeList = (List) ((IMonitorInfoService)iBaseService).selectNodeList(null); request.setAttribute("outputObject2", nodeList); return super.doService(mapping, beanUtilForm, request, response); } else if (method.equals("delete")) { MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { monitorInfo = new MonitorInfo(); }else { monitorInfo = (MonitorInfo)inputObject; } beanUtilForm.setBean(monitorInfo); request.setAttribute("inputObject", monitorInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[1]; ids[0] = monitorInfo.getMonitorId(); String configId = RouterConfig.MONITOR_INFO_TABLE_ID; } catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if (method.equals("update")) { MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { monitorInfo = new MonitorInfo(); }else { monitorInfo = (MonitorInfo)inputObject; } beanUtilForm.setBean(monitorInfo); request.setAttribute("inputObject", monitorInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[1]; ids[0] = monitorInfo.getMonitorId(); String configId = RouterConfig.MONITOR_INFO_TABLE_ID; } catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if (method.equals("insert")) { MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { monitorInfo = new MonitorInfo(); }else { monitorInfo = (MonitorInfo)inputObject; } beanUtilForm.setBean(monitorInfo); request.setAttribute("inputObject", monitorInfo); ActionForward forward = super.doService(mapping, beanUtilForm, request, response); try { String ids[] = new String[1]; ids[0] = monitorInfo.getMonitorId(); String configId = RouterConfig.MONITOR_INFO_TABLE_ID; } catch(Exception e){ e.printStackTrace(); ApplicationException ae = new ApplicationException(e); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } return forward; } else if(method.equals("saveMonitorInfoExcel")){ MonitorInfo monitorInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm)form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); }else { beanUtilForm = new BeanUtilForm(); } if(inputObject == null) { monitorInfo = new MonitorInfo(); }else { monitorInfo = (MonitorInfo)inputObject; } SessionMgr sessMgr = new SessionMgr(request); monitorInfo.setDbType(sessMgr.getValue("dbType")); monitorInfo.setLangType(sessMgr.getValue("langType")); monitorInfo.setRootPath(getServlet().getServletContext().getRealPath("/")); IMonitorInfoService service = (IMonitorInfoService)iBaseService; service.saveMonitorInfoExcel(monitorInfo, request, response); return null; }else { return super.doService(mapping, form, request, response); } } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.pipeline.launch; import org.testng.Assert; import org.testng.annotations.Test; import com.yahoo.cubed.settings.CLISettings; import com.yahoo.cubed.settings.YamlSettings; /** * Test pipeline launch script. */ public class LauncherTest { /** * Test that the launcher script is correctly populate from pipeline settings. */ @Test public void testLauncher() throws Exception { String scriptDir = LauncherTest.class.getClassLoader().getResource("bin").getPath(); PipelineLauncher launcher = new PipelineLauncher(); launcher.setPipelineName("pipeline"); launcher.setPipelineVersion("v1.0"); launcher.setPipelineOwner(CLISettings.PIPELINE_OWNER); launcher.setPipelineResourcePath("/tmp"); launcher.setScriptFileDir(scriptDir); launcher.setScriptFileName("test-success-launch.sh"); launcher.setPipelineBackfillStartDate("0"); launcher.setPipelineOozieJobType(YamlSettings.OOZIE_JOB_TYPE); launcher.setPipelineOozieBackfillJobType(YamlSettings.OOZIE_BACKFILL_JOB_TYPE); PipelineLauncher.LaunchStatus status1 = launcher.call(); Assert.assertFalse(status1.hasError); Assert.assertEquals(status1.infoMsg, "[DMART PIPELINE CD][INFO] OK\n"); launcher.setScriptFileName("test-failure.sh"); PipelineLauncher.LaunchStatus status2 = launcher.call(); Assert.assertTrue(status2.hasError); Assert.assertEquals(status2.errorMsg, "[DMART PIPELINE CD][ERROR] failure\n"); launcher.setScriptFileName("test-all.sh"); PipelineLauncher.LaunchStatus status3 = launcher.call(); Assert.assertTrue(status3.hasError); Assert.assertEquals(status3.errorMsg, "[DMART PIPELINE CD][ERROR] ERROR\n"); Assert.assertEquals(status3.infoMsg, "[DMART PIPELINE CD][INFO] OK\n"); } }
package com.mustafayuksel.notificationapplication; import java.io.IOException; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingResponseWrapper; import org.springframework.web.util.WebUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class LoggableDispatcherServlet extends DispatcherServlet { private static final long serialVersionUID = 1L; private final Logger logger = LogManager.getLogger("LoggableDispatcherServlet"); @Override protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { if (!(request instanceof ContentCachingRequestWrapper)) { request = new ContentCachingRequestWrapper(request); } if (!(response instanceof ContentCachingResponseWrapper)) { response = new ContentCachingResponseWrapper(response); } HandlerExecutionChain handler = getHandler(request); try { super.doDispatch(request, response); } finally { log(request, response, handler); updateResponse(response); } } private void log(HttpServletRequest requestToCache, HttpServletResponse responseToCache, HandlerExecutionChain handler) throws IOException { logger.info("Response Status: " + String.valueOf(responseToCache.getStatus())); logger.info("Request Method: " + requestToCache.getMethod()); logger.info("Request URI: " + requestToCache.getRequestURI()); logger.info("Request Remote Adr: " + requestToCache.getRemoteAddr()); logger.info("Handler: " + handler.toString()); logger.info("Request Body: " + requestToCache.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); logger.info("Response Body: " + getResponsePayload(responseToCache)); } private String getResponsePayload(HttpServletResponse response) { ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class); if (wrapper != null) { byte[] responseArray = wrapper.getContentAsByteArray(); if (responseArray.length > 0) { return new String(responseArray); } } return ""; } private void updateResponse(HttpServletResponse response) throws IOException { ContentCachingResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class); responseWrapper.copyBodyToResponse(); } }
package com.beike.entity.common; import java.io.Serializable; /** * <p>Title: 短信实体</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2011</p> * <p>Company: Sinobo</p> * @date May 6, 2011 * @author ye.tian * @version 1.0 */ @SuppressWarnings("serial") public class Sms implements Serializable{ private int id; private String smstitle; private String smscontent; private String smstype; public Sms(){ } public Sms(int id, String smstitle, String smscontent, String smstype) { this.id = id; this.smstitle = smstitle; this.smscontent = smscontent; this.smstype = smstype; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSmstitle() { return smstitle; } public void setSmstitle(String smstitle) { this.smstitle = smstitle; } public String getSmscontent() { return smscontent; } public void setSmscontent(String smscontent) { this.smscontent = smscontent; } public String getSmstype() { return smstype; } public void setSmstype(String smstype) { this.smstype = smstype; } }
package apiAlquilerVideoJuegos.controlador; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import apiAlquilerVideoJuegos.modelos.Titulo; import apiAlquilerVideoJuegos.servicios.TituloServicio; @CrossOrigin(origins = "*", methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE }) @Controller @ResponseBody @RequestMapping(value = "/titulo") @Api(value = "onlinestore", description = "Operaciones sobre los títulos de la tienda de videojuegos") @Validated public class TituloControlador { private TituloServicio tituloServicio; public TituloControlador() { } @Autowired public TituloControlador(TituloServicio tituloServicio) { this.tituloServicio = tituloServicio; } // Listar todos los Titulos @ApiOperation(value = "Listar los títulos de la tienda", response = List.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Lista cargada con exito"), @ApiResponse(code = 401, message = "No tiene autorización para el recurso"), @ApiResponse(code = 403, message = "Recurso prohibido"), @ApiResponse(code = 404, message = "Recurso no encontrado") }) @RequestMapping(value = "/listar", produces = "application/json", method = RequestMethod.GET) public List<Titulo> listar() { return tituloServicio.obtener(); } @ApiOperation(value = "Buscar un Título por el Id", response = Titulo.class) @RequestMapping(value = "/obtener/{id}", method = RequestMethod.GET) public Titulo obtenerTitulo(@PathVariable Long id) { return tituloServicio.obtenerTitulo(id); } @ApiOperation(value = "Agregar un nuevo Título") @RequestMapping(value = "/agregar", method = RequestMethod.POST, produces = "application/json") public ResponseEntity agregar(@RequestParam("titulo") @ModelAttribute Titulo titulo) { if (tituloServicio.guardar(titulo)) { return new ResponseEntity("Título agregado con éxito", HttpStatus.OK); } else { return new ResponseEntity("No se pudo agregar el Título", HttpStatus.NOT_ACCEPTABLE); } } @ApiOperation(value = "Actualizar un Título existente") @RequestMapping(value = "/actualizar/{id}", method = RequestMethod.POST) public boolean modificar(@ModelAttribute Titulo titulo) { return tituloServicio.guardar(titulo); } @ApiOperation(value = "Eliminar un Título") @RequestMapping(value = "/eliminar/{id}", method = RequestMethod.DELETE) public ResponseEntity eliminar(@PathVariable Long id) { if (tituloServicio.eliminar(id)) { return new ResponseEntity("Título eliminado con éxito", HttpStatus.OK); } else { return new ResponseEntity("No se pudo eliminar el Título", HttpStatus.NOT_ACCEPTABLE); } } }
package ch6; class MyMath2 { //인스턴스 변수 long a, b; //인스턴스 변수 a, b만을 이용해서 작업하므로 매개변수가 필요없다. //a,b는 인스턴스 변수 //인스턴스 메서드 long add() {return a + b;} long subtract() {return a - b;} long multiply() {return a*b;} double divide() {return a/b;} //인스턴스변수와 관계없이 매개변수만으로 작업이 가능하다. //a, b는 지역변수 //클래스 메서드 static long addClass(long a, long b) {return a+b;} static long subtrack(long a, long b) {return a-b;} static long multiply(long a, long b) {return a*b;} static double divide(double a, double b) {return a/b;} } public class MyMathTest2 { public static void main(String[] args) { System.out.println("인스턴스변수 사용 - 객체 생성 후 사용 가능"); //인스턴스 생성 MyMath2 mm = new MyMath2(); mm.a = 400L; mm.b = 200L; System.out.println(mm.add()); System.out.println(mm.subtract()); System.out.println(mm.multiply()); System.out.println(mm.divide()); System.out.println("=========================="); //클래스 메서드 호출. 인스턴스 생성없이 호출 가능 //객체를 생성하지 않고도 메서드를 호출할 수 있으려면 메서드 앞에 static System.out.println("지역변수 사용 - 객체 생성없이 사용 가능"); System.out.println(MyMath2.addClass(200L, 100L)); System.out.println(MyMath2.subtrack(200L, 100L)); System.out.println(MyMath2.multiply(200L, 100L)); System.out.println(MyMath2.divide(200d, 100d)); } }
package com.stackroute.pe2; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Text; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; public class TextFileToUpperCaseTest { private static TextFileToUpperCase textFileToUpperCase; @Before public void setUp() throws Exception { textFileToUpperCase = new TextFileToUpperCase(); } @After public void tearDown() throws Exception { } @Test public void getUpperCase() throws IOException { File file = new File("/home/pallavi/IdeaProjects/PE2/src/main/imp.txt"); assertEquals("hello, is it me you are looking for? i can see it in your eyes 12345678@#$%.",textFileToUpperCase.getUpperCase(file.getAbsolutePath())); assertNull("The return value should be null",textFileToUpperCase.getUpperCase("")); } }
/* * Copyright (c) 2019 Thermo Fisher Scientific * All rights reserved. */ package personal.springboot.example.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import personal.springboot.example.entity.Employee; /** * TODO: Class description */ @Repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { /** * TODO: Method description * * * * @param email * * @return */ @Query("SELECT e FROM Employee e WHERE e.email LIKE %:email% AND e.active = true") List<Employee> findByEmailAndActived(@Param("email") String email); }
package com.sohan.restf.messenger.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.sohan.restf.messenger.database.Database; import com.sohan.restf.messenger.model.Comment; import com.sohan.restf.messenger.model.Message; public class CommentService { private Map<Long, Message> messages = Database.getAllMessages(); public Comment getComment(long messageId, long commentId) { if(messageId < 0 || commentId < 0) return null; else return messages.get(messageId).getComments().get(commentId); } public Comment addComment(long messageId, Comment comment) { if(messageId < 0 || comment == null) return null; else { Message message = messages.get(messageId); long id = message.getComments().size() + 1; comment.setId(id); return message.getComments().put(id, comment); } } public List<Comment> getAllComment(long messageId) { if (messageId <= 0 ) return null; else return new ArrayList<>(messages.get(messageId).getComments().values()); } public Comment updateComment(long messageId, long commentId, Comment comment) { if(messageId <= 0 || comment == null) return null; else { comment.setId(commentId); return messages.get(messageId).getComments().put(commentId, comment); } } public Comment deleteComment(long messageId, long commentId) { if(messageId <= 0 || commentId <= 0) return null; else { Message message = messages.get(messageId); if(message == null) return null; return message.getComments().remove(commentId); } } }
package com.arrays; import javax.crypto.spec.PSource; public class DeleteElement { static int count=0; public static void main(String[] args) { int a[] = {12,13,14,15,16}; DeleteElement d = new DeleteElement(); count = a.length; d.print(a); System.out.println(); //d.deleteFromEnd(a); //d.deletFromValue(a,15); d.deleteFromosition(a,2); System.out.println(); d.print(a); } public void deleteFromosition(int[] a, int position) { if (position> count|| position <= 0) { System.out.println("Invalid Position"); return; } for (int i = position - 1; i < a.length - 1; i++) { a[i] = a[i+1]; } count--; } public void deletFromValue(int[] a, int value) { int i; for (i = 0; i < a.length; i++) { if (value == a[i]) { break; } } if (i == a.length) { System.out.println(" value doesn't exist in array "); return; } for (int j = i; j < a.length -1; j++) { a[j] = a[j+1]; } count--; } public void deleteFromEnd(int[] a) { if (a.length <= 0) { return; } count--; } public void print(int[] a) { for (int i = 0; i < count; i++) { System.out.print(" "+a[i]); } } }
package pro.likada.service; import pro.likada.dto.VehiclePosition; import pro.likada.model.Vehicle; import java.util.Date; import java.util.List; /** * Created by abuca on 07.03.17. */ public interface VehicleService { Vehicle findById(long id); void save(Vehicle vehicle); List<Vehicle> findAllVehicles(String searchString); Long findAmountOfVehicleWithDriversConnectedWithVehicle(Vehicle vehicle); List<Vehicle> refreshPositionData(List<Vehicle> vehicleList); List<VehiclePosition> buildTrack(Vehicle vehicle, Date from, Date to); Double buildTrackLength(Vehicle vehicle, Date from, Date to); void deleteById(long id); }
package mc.kurunegala.bop.model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import mc.kurunegala.bop.dao.UploadsMapper; @Service public class UpploadService { @Autowired UploadsMapper mapper; public void add(Uploads entity) { mapper.insertSelective(entity); } }
package action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Register; 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 dao.RegisterDaoImpl; import dao.RegisterDaoInterface; public class RegistrationAction extends Action{ RegisterDaoImpl registerDao=new RegisterDaoImpl(); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("right here"); Register register=(Register)form; Register reg=registerDao.insert(register); if(reg==null){ return mapping.findForward("errors"); } return mapping.findForward("success"); } }
package com.simple.wechatsimple.util; import android.content.Context; import android.os.Environment; import java.io.File; public class FileUtil { public static final String ROOT_DIR = "Android/data/"; public static String getDir(String name, Context context) { StringBuilder sb = new StringBuilder(); if (isSDCardAvailable()) { sb.append(getExternalStoragePath(context)); } else { sb.append(getCachePath(context)); } sb.append(name); sb.append(File.separator); String path = sb.toString(); if (createDirs(path)) { return path; } else { return null; } } public static boolean isSDCardAvailable() { if (Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { return true; } else { return false; } } public static boolean createDirs(String dirPath) { File file = new File(dirPath); if (!file.exists() || !file.isDirectory()) { return file.mkdirs(); } return true; } public static String getExternalStoragePath(Context context) { StringBuilder sb = new StringBuilder(); sb.append(Environment.getExternalStorageDirectory().getAbsolutePath()); sb.append(File.separator); sb.append(ROOT_DIR); sb.append(context.getPackageName()); sb.append(File.separator); return sb.toString(); } public static String getCachePath(Context context) { File f = context.getCacheDir(); if (null == f) { return null; } else { return f.getAbsolutePath() + "/"; } } }
package org.hpin.webservice.dao; import java.util.List; import org.hpin.common.core.orm.BaseDao; import org.hpin.webservice.bean.PreSalesMan; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.stereotype.Repository; /** * * @description: 预留营销员信息表对应dao * create by henry.xu 2017年2月8日 */ @Repository public class PreSalesManDao extends BaseDao{ /** * 根据参数查询对应的预留营销员信息数据; * create by henry.xu 2017年2月8日 * @param salesManName * @param salesManNo * @param salesChannel * @return */ public PreSalesMan findSalesManInfoByParams(String salesManName, String salesManNo, String salesChannel) { String sql = "select " + "salePre.ID, " + "salePre.SALESMAN salesman, " + "salePre.EMPLOYEE_NO employeeNo, " + "salePre.EMPLOYEE_PHONE employeePhone, " + "salePre.EMPLOYEE_COMPANY employeeCompany, " + "salePre.EMPLOYEE_CITY_COMPANY employeeCityCompany, " + "salePre.EMPLOYEE_HEAD_OFFICE employeeHeadOffice, " + "salePre.YM_COMPANY_ID ymCompanyId, " + "ship.BRANCH_COMMANY ymCompany, " + "salePre.YM_OWNCOMPANY_ID ymOwncompanyId, " + "dep.DEPT_NAME ymOwncompany, " + "salePre.IS_DELETED isDeleted, " + "salePre.MARK mark " + "from ERP_SALEMANNUM_INFO_PRE salePre " + "left join HL_CUSTOMER_RELATIONSHIP ship on salePre.YM_COMPANY_ID = ship.id " + "left join um_dept dep on dep.id = salePre.YM_OWNCOMPANY_ID " + "where " + "salePre.SALESMAN= '"+salesManName+"' " + "and salePre.EMPLOYEE_NO = '"+salesManNo+"' " + //"and salePre.MARK = '"+salesChannel+"' " + "and salePre.IS_DELETED =0 "; BeanPropertyRowMapper<PreSalesMan> rowMapper = new BeanPropertyRowMapper<PreSalesMan>(PreSalesMan.class); List<PreSalesMan> list =this.getJdbcTemplate().query(sql, rowMapper); return list != null && list.size() > 0 ? list.get(0) : null; } }
/* * Application.java * Last release on June 2008 * Created on 6 juin 2005, 17:57 * Revised on September 2011 */ package learning; import ihm.*; import java.util.*; import maze.*; /** * * @author De Loor */ public class Application { /** Creates a new instance of Application */ public Application() { /** creation du labyrinthe */ _maze = new Maze(); _timeOut=0; _timer = new Timer(); /** création de l'ihm */ _view = new LearningInMazeView(); _view.setApplication(this); _view.setVisible(true); _view.setSize(800,800); _agentTab = new ArrayList(); _simulationStatut = "stop"; } /** * Méthode de lancement de l'application, elle se contente de * créer une application .. * @param args the command line arguments */ public static void main(String[] args) { Application application = new Application(); application.run(); } public Maze getMaze(){return(_maze);} public void setTimeOut(long x){_timeOut = x;} public SarsaSituatedAgent getLearner(){return(_learner);} /** * envoie le statut de la simulation * Le statut de la simuation peut être "run", "stop" ou "pause" * il permet de savoir si l'on fait tourner l'algorithme ou non * théoriquement, c'est l'ihm qui le fixe */ public String getSimulationStatut(){return _simulationStatut;} public LearningInMazeView getLearningInMazeView(){return _view;} public void addAgent(String name){ SarsaSituatedAgent agent = new SarsaSituatedAgent(this,_view,_maze,name,"perception.PositionLearnerPerception"); _agentTab.add((SarsaSituatedAgent)agent); for(int i=0;i<_agentTab.size();i++) if(_agentTab.get(i) instanceof SarsaSituatedAgent) ((SarsaSituatedAgent)_agentTab.get(i)).setUnSelected(); agent.setSelected(); agent.startLife(); _learner = agent; _view.setNewInformations(_learner); } public void stopSimulation(){ _simulationStatut="stop"; for(int i=0;i<_agentTab.size();i++){ ((SarsaSituatedAgent)_agentTab.get(i)).setCompteur(0); ((SarsaSituatedAgent)_agentTab.get(i)).setNbEpisode(0); } } public void startSimulation(){ if(_simulationStatut.equals("stop")){ for(int i=0;i<_agentTab.size();i++) { try{ SarsaSituatedAgent sarsa = (SarsaSituatedAgent)(_agentTab.get(i)); sarsa.clearTrace(); sarsa.clearMemory(); } catch(Exception e){ System.out.println(e.getMessage()); } _view.drawGraph(); } } _simulationStatut="run"; } public void pauseSimulation(){ _simulationStatut="pause"; } public void run(){ while(true){ //System.out.println(_simulationStatut); if(_simulationStatut.equals("run")) { //System.out.println("run"); for(int i=0;i<_agentTab.size();i++){ //System.out.println(i); ((SarsaSituatedAgent)_agentTab.get(i)).oneStep(); } try{ Thread.sleep(_timeOut); } catch(Exception e) {System.out.println("Time Out problem");} //_timer.wait(_timeOut); } else { try{ Thread.sleep(_timeOut); } catch(Exception e) {System.out.println("Time Out problem");} //System.out.println("noRun"); } } } public void reset(){ _simulationStatut = "stop"; /** creation du labyrinthe */ _maze = new Maze(); _timeOut=0; _timer = new Timer(); /** création de l'ihm */ _agentTab = new ArrayList(); _view.setApplication(this); _view.drawGraph(); _view.setVisible(true); _view.setSize(800,800); } public void changeSelectedAgent(String name){ for(int i=0;i<_agentTab.size();i++) if(_agentTab.get(i) instanceof SarsaSituatedAgent) ((SarsaSituatedAgent)_agentTab.get(i)).setUnSelected(); for(int i=0;i<_agentTab.size();i++) if((_agentTab.get(i) instanceof SarsaSituatedAgent) && (((SarsaSituatedAgent)_agentTab.get(i)).getName().equals(name))) { _learner = ((SarsaSituatedAgent)_agentTab.get(i)); _learner.setSelected(); _view.setNewInformations(_learner); } } public void changeSimulationStatut(String statut){ _simulationStatut=statut; } public ArrayList getAgentTab() { return _agentTab; } public void rewardChange(){ _maze.rewardChange(); _view.repaint(); for(int i=0;i<_agentTab.size();i++) { if((_agentTab.get(i) instanceof SarsaSituatedAgent)) { ((SarsaSituatedAgent)_agentTab.get(i)).clearTrace(); } } } private Maze _maze; private LearningInMazeView _view; private ArrayList _agentTab; private SarsaSituatedAgent _learner; private String _simulationStatut; long _timeOut; Timer _timer; }
package cn.swsk.rgyxtqapp.custom; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ListView; import android.widget.ScrollView; public class InnerLV extends ListView{ private ScrollView parentScrollView; private int currentY; int mTop = 10; private int lastScrollDelta = 0; public InnerLV(Context context) { super(context); } public InnerLV(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public InnerLV(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: parentScrollView.requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: parentScrollView.requestDisallowInterceptTouchEvent(false); break; // default: break; } return super.onInterceptTouchEvent(ev); } // public void resume() { // overScrollBy(0, -lastScrollDelta, 0, getScrollY(), 0, getScrollRange(), 0, 0, true); // lastScrollDelta = 0; // } // // /** // * 将targetView滚到最顶端 // */ // public void scrollTo(View targetView) { // int oldScrollY = getScrollY(); // int top = targetView.getTop() - mTop; // int delatY = top - oldScrollY; // lastScrollDelta = delatY; // overScrollBy(0, delatY, 0, getScrollY(), 0, getScrollRange(), 0, 0, true); // } // // private int getScrollRange() { // int scrollRange = 0; // if (getChildCount() > 0) { // View child = getChildAt(0); // scrollRange = Math.max(0, child.getHeight() - (getHeight())); // } // return scrollRange; // } // // public boolean onInterceptTouchEvent(MotionEvent ev) { // Log.d("touchEvent",ev.getAction()+" @InnerListView"); // switch (ev.getAction()) { // case MotionEvent.ACTION_DOWN: // parentScrollView.requestDisallowInterceptTouchEvent(true); // currentY = (int)ev.getY(); // Log.d("touchEvent","onInterceptTouchEvent down @InnerListView"); // break; // case MotionEvent.ACTION_MOVE: // Log.d("touchEvent","onInterceptTouchEvent move @InnerListView"); // break; // case MotionEvent.ACTION_UP: // Log.d("touchEvent","onInterceptTouchEvent up @InnerListView"); // break; // case MotionEvent.ACTION_CANCEL: // Log.d("touchEvent","onInterceptTouchEvent cancel @InnerListView"); // break; //// case MotionEvent.ACTION_HOVER_ENTER: //// Log.d("touchEvent","onInterceptTouchEvent hover enter @InnerListView"); //// break; //// case MotionEvent.ACTION_HOVER_EXIT: //// Log.d("touchEvent","onInterceptTouchEvent hover exit @InnerListView"); //// break; //// case MotionEvent.ACTION_HOVER_MOVE: //// Log.d("touchEvent","onInterceptTouchEvent hover move @InnerListView"); //// break; //// case MotionEvent.ACTION_MASK: //// Log.d("touchEvent","onInterceptTouchEvent mask @InnerListView"); //// break; // default: // break; // } // boolean b =super.onInterceptTouchEvent(ev); // return true; // } // @Override // public boolean onTouchEvent(MotionEvent ev) { // View child = getChildAt(0); // if (parentScrollView != null) { // if (ev.getAction() == MotionEvent.ACTION_MOVE) { // int height = child.getMeasuredHeight(); // height = height*getCount() - getMeasuredHeight(); // int scrollY = getScrollY(); // int y = (int)ev.getY(); // System.out.println("top="+getTop()+" @ InnerListView"); // // scroll down // if (currentY < y) { // if (getFirstVisiblePosition()==0) { // setParentScrollAble(true); //// overScrollBy(0, -80, 0, 0, 0, 100, 0, 0, true); // setSelection(0); // Log.d("touchEvent","upDead onTouchEvent @InnerListView"); // return false; // } else { // setParentScrollAble(false); // } // } // //scroll up // else if (currentY > y) { // if (getLastVisiblePosition()==getCount()-1) { // setParentScrollAble(true); //// overScrollBy(0, 80, 0, 0, 0, 100, 0, 0, true); // setSelection(getCount()-1); // Log.d("touchEvent","downDead onTouchEvent @InnerListView"); // return false; // } else { // setParentScrollAble(false); // } // } // currentY = y; // } // } // boolean b =super.onTouchEvent(ev); // return true; // // } private void setParentScrollAble(boolean b) { parentScrollView.requestDisallowInterceptTouchEvent(!b); } public ScrollView getParentScrollView() { return parentScrollView; } public void setParentScrollView(ScrollView parentScrollView) { this.parentScrollView = parentScrollView; } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ /* * X509CertificateFactory.java * */ package pwnbrew.misc; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.SecureRandom; import java.security.SignatureException; import java.security.cert.CertificateException; import java.util.Date; import javax.net.ssl.SSLException; public class X509CertificateFactory { //NOTE: Java cryptography Architecture API Specification & Reference... // http://www.ida.liu.se/~TDDB32/kursbibliotek/BlueJ/docs/guide/security/CryptoSpec.html#AppA //NOTE: Some of this code is based on code acquired from an article... // at: http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html private static final String Algorithm_RSA = "RSA"; private static final String Hash_SHA256withRSA = "SHA256withRSA"; // ========================================================================== /** * * * @param name the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param issuer * @param algorithm * @param days how many days from now the Certificate is valid for * @param KeySize * * @return * @throws java.security.cert.CertificateException * @throws java.security.SignatureException * @throws java.security.InvalidKeyException * @throws java.security.NoSuchProviderException * @throws java.io.IOException * @throws java.security.NoSuchAlgorithmException */ public static Object[] generateCertificate( String name, String issuer, int days, String algorithm, int KeySize ) throws CertificateException, InvalidKeyException, IOException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { //The object array that contains the Private Key and the Certificate PrivateKey privKey = null; sun.security.x509.X509CertImpl cert = null; String hashAlg = Hash_SHA256withRSA; KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance( algorithm ); if( kpGenerator != null ){ if(!algorithm.equals(Algorithm_RSA)){ throw new SSLException("Unsupported PKI algorithm."); } kpGenerator.initialize( KeySize, new SecureRandom() ); KeyPair keyPair = kpGenerator.generateKeyPair(); Date from = new Date(); Date to = new Date( from.getTime() + ((long)days * (long)86400000) ); //Milliseconds in one day = 86400000 sun.security.x509.CertificateValidity certValidity = new sun.security.x509.CertificateValidity( from, to ); BigInteger certSerialNumber = new BigInteger( 64, new SecureRandom() ); sun.security.x509.X500Name ownerName = new sun.security.x509.X500Name( name ); sun.security.x509.X500Name issuerName = new sun.security.x509.X500Name( issuer ); sun.security.x509.X509CertInfo certInfo = new sun.security.x509.X509CertInfo(); certInfo.set( sun.security.x509.X509CertInfo.VALIDITY, certValidity ); certInfo.set( sun.security.x509.X509CertInfo.SERIAL_NUMBER, new sun.security.x509.CertificateSerialNumber( certSerialNumber ) ); String version = System.getProperty( "java.version" ); if( version.startsWith("1.8")){ certInfo.set( sun.security.x509.X509CertInfo.SUBJECT, ownerName ); certInfo.set( sun.security.x509.X509CertInfo.ISSUER, issuerName ); } else { certInfo.set( sun.security.x509.X509CertInfo.SUBJECT, new sun.security.x509.CertificateSubjectName( ownerName ) ); certInfo.set( sun.security.x509.X509CertInfo.ISSUER, new sun.security.x509.CertificateIssuerName( issuerName ) ); } certInfo.set( sun.security.x509.X509CertInfo.KEY, new sun.security.x509.CertificateX509Key( keyPair.getPublic() ) ); certInfo.set( sun.security.x509.X509CertInfo.VERSION, new sun.security.x509.CertificateVersion( sun.security.x509.CertificateVersion.V3 ) ); sun.security.x509.AlgorithmId algorithmId = new sun.security.x509.AlgorithmId( sun.security.x509.AlgorithmId.sha256WithRSAEncryption_oid ); certInfo.set( sun.security.x509.X509CertInfo.ALGORITHM_ID, new sun.security.x509.CertificateAlgorithmId( algorithmId ) ); //Sign the certificate to identify the Algorithm_RSA that's used... privKey = keyPair.getPrivate(); cert = new sun.security.x509.X509CertImpl( certInfo ); cert.sign( privKey, hashAlg ); //Update the algorith, and resign... algorithmId = (sun.security.x509.AlgorithmId)cert.get( sun.security.x509.X509CertImpl.SIG_ALG ); certInfo.set( sun.security.x509.CertificateAlgorithmId.NAME + "." + sun.security.x509.CertificateAlgorithmId.ALGORITHM, algorithmId ); cert = new sun.security.x509.X509CertImpl( certInfo ); cert.sign( privKey, hashAlg ); } return new Object[]{ privKey, cert }; }/* END generateCertificate( String, KeyPair, int, String ) */ }/* END CLASS X509CertificateFactory */
package com.example.mikeb.lostandfound.Utils; /** * Created by Mikeb on 11/18/2017. */ import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * Created by Mikeb on 11/5/2017. */ public class ConnectToDB { public String getItems(String query,String type){ HttpURLConnection connection; InputStream inputStream; try { URL url; if(type.equals("found")) url = new URL(SearchUtils.found_url+query); else url= new URL(SearchUtils.lost_url+query); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoInput(true); connection.connect(); //Read the response StringBuffer stringBuffer = new StringBuffer(); inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + "\r\n"); } inputStream.close(); connection.disconnect(); return stringBuffer.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } public void insert(String query,String type){ try { SearchUtils contactUtils = new SearchUtils(); URL object; if(type.equals("found"))object =new URL(SearchUtils.found_url); else object =new URL(SearchUtils.lost_url); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestProperty("Accept", "application/json"); con.setRequestMethod("POST"); byte[] outputBytes = query.getBytes("UTF-8"); OutputStream os = con.getOutputStream(); os.write(outputBytes); int HttpResult = con.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { System.out.println("Success"); } else { System.out.println("fail"); System.out.println(con.getResponseMessage()); } } catch (Exception e){ e.printStackTrace(); } } public String getType(String object){ String urlString = "https://api.mlab.com/api/1/databases/phone_number_profiles/collections/lostAndFound?q="; urlString = urlString + object + "&fo=true&apiKey=oQ8EeSsOWTSV9AAmp6aUCQCwnaTs08Aq"; HttpURLConnection connection; InputStream inputStream; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoInput(true); connection.connect(); //Read the response StringBuffer stringBuffer = new StringBuffer(); inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line + "\r\n"); } inputStream.close(); connection.disconnect(); return stringBuffer.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package GUI; import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; public class ButtonGUI extends JFrame { private JButton reg; private JButton custom; public ButtonGUI() { super ("Bot��es LOL"); setLayout(new FlowLayout()); Icon Android = new ImageIcon(getClass().getResource("Android-64.png")); Icon Windows = new ImageIcon(getClass().getResource("Windows-64.png")); reg = new JButton("Bot��o 1", Windows); add(reg); custom = new JButton("Bot��o 2",Android); //custom.setRolloverSelectedIcon(Windows); add(custom); HandlerClass handler = new HandlerClass(); reg.addActionListener(handler); custom.addActionListener(handler); } private class HandlerClass implements ActionListener { public void actionPerformed (ActionEvent event) { JOptionPane.showMessageDialog(null, String.format("%s",event.getActionCommand())); } } }
package org.dbdoclet.test.sample; public class Brainstorm extends Idea implements Comparable { public Brainstorm(String idea1) { super(idea1); } public boolean isBoring(Thought meeting) throws DreamingException { return true; } /** * Die Methode <code>compareTo</code> aus der Schnittstelle * <code>java.lang.Comparable</code>. * * @param o <code>Object</code> * @return <code>int</code> */ @SuppressWarnings(value={"unchecked"}) public int compareTo(Object o) { return 0; } }
package com.danharding.user; public enum Status { SUCCESS, USER_ALREADY_EXISTS, FAILURE }
<<<<<<< HEAD package com.example.sieunhan.github_client.api.model; /** * Created by dannyle on 03/12/2016. */ ======= package com.example.sieunhan.github_client.api.model; >>>>>>> rebuilt-version public class Plan { public String name; <<<<<<< HEAD public int space; public int private_repos; ======= public int space; public int private_repos; >>>>>>> rebuilt-version public int collaborators; }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.transaction.annotation; import org.springframework.transaction.TransactionDefinition; /** * Enumeration that represents transaction isolation levels for use with the * {@link Transactional @Transactional} annotation, corresponding to the * {@link TransactionDefinition} interface. * * @author Colin Sampaleanu * @author Juergen Hoeller * @since 1.2 */ public enum Isolation { /** * Use the default isolation level of the underlying data store. * <p>All other levels correspond to the JDBC isolation levels. * @see java.sql.Connection */ DEFAULT(TransactionDefinition.ISOLATION_DEFAULT), /** * A constant indicating that dirty reads, non-repeatable reads, and phantom reads * can occur. * <p>This level allows a row changed by one transaction to be read by * another transaction before any changes in that row have been committed * (a "dirty read"). If any of the changes are rolled back, the second * transaction will have retrieved an invalid row. * @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED */ READ_UNCOMMITTED(TransactionDefinition.ISOLATION_READ_UNCOMMITTED), /** * A constant indicating that dirty reads are prevented; non-repeatable reads * and phantom reads can occur. * <p>This level only prohibits a transaction from reading a row with uncommitted * changes in it. * @see java.sql.Connection#TRANSACTION_READ_COMMITTED */ READ_COMMITTED(TransactionDefinition.ISOLATION_READ_COMMITTED), /** * A constant indicating that dirty reads and non-repeatable reads are * prevented; phantom reads can occur. * <p>This level prohibits a transaction from reading a row with uncommitted changes * in it, and it also prohibits the situation where one transaction reads a row, * a second transaction alters the row, and the first transaction re-reads the row, * getting different values the second time (a "non-repeatable read"). * @see java.sql.Connection#TRANSACTION_REPEATABLE_READ */ REPEATABLE_READ(TransactionDefinition.ISOLATION_REPEATABLE_READ), /** * A constant indicating that dirty reads, non-repeatable reads, and phantom * reads are prevented. * <p>This level includes the prohibitions in {@link #REPEATABLE_READ} * and further prohibits the situation where one transaction reads all rows that * satisfy a {@code WHERE} condition, a second transaction inserts a row * that satisfies that {@code WHERE} condition, and the first transaction * re-reads for the same condition, retrieving the additional "phantom" row * in the second read. * @see java.sql.Connection#TRANSACTION_SERIALIZABLE */ SERIALIZABLE(TransactionDefinition.ISOLATION_SERIALIZABLE); private final int value; Isolation(int value) { this.value = value; } public int value() { return this.value; } }
/* * 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 ht.gouv.faes.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Benucci */ @Entity @Table(name = "UTILISATEUR") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Utilisateur.findAll", query = "SELECT u FROM Utilisateur u"), @NamedQuery(name = "Utilisateur.findByIdutilisateur", query = "SELECT u FROM Utilisateur u WHERE u.idutilisateur = :idutilisateur"), @NamedQuery(name = "Utilisateur.findByNom", query = "SELECT u FROM Utilisateur u WHERE u.nom = :nom"), @NamedQuery(name = "Utilisateur.findByPrenom", query = "SELECT u FROM Utilisateur u WHERE u.prenom = :prenom"), @NamedQuery(name = "Utilisateur.findByEmail", query = "SELECT u FROM Utilisateur u WHERE u.email = :email"), @NamedQuery(name = "Utilisateur.findByUsername", query = "SELECT u FROM Utilisateur u WHERE u.username = :username"), @NamedQuery(name = "Utilisateur.findByPassword", query = "SELECT u FROM Utilisateur u WHERE u.password = :password"), @NamedQuery(name = "Utilisateur.findByDatecreation", query = "SELECT u FROM Utilisateur u WHERE u.datecreation = :datecreation"), @NamedQuery(name = "Utilisateur.findByDateexpiration", query = "SELECT u FROM Utilisateur u WHERE u.dateexpiration = :dateexpiration"), @NamedQuery(name = "Utilisateur.findByStatut", query = "SELECT u FROM Utilisateur u WHERE u.statut = :statut"), @NamedQuery(name = "Utilisateur.findByCreatedBy", query = "SELECT u FROM Utilisateur u WHERE u.createdBy = :createdBy")}) public class Utilisateur implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = true) //@NotNull @Column(name = "IDUTILISATEUR") private Integer idutilisateur; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "NOM") private String nom; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "PRENOM") private String prenom; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "EMAIL") private String email; @Basic(optional = false) @NotNull @Size(min = 1, max = 25) @Column(name = "USERNAME") private String username; @Basic(optional = false) @NotNull @Size(min = 1, max = 200) @Column(name = "PASSWORD") private String password; @Basic(optional = false) @NotNull @Column(name = "DATECREATION") @Temporal(TemporalType.DATE) private Date datecreation; @Basic(optional = false) @NotNull @Column(name = "DATEEXPIRATION") @Temporal(TemporalType.DATE) private Date dateexpiration; @Basic(optional = false) @NotNull @Size(min = 1, max = 50) @Column(name = "STATUT") private String statut; @Column(name = "CreatedBy") private Integer createdBy; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idutilisateur") private List<Log> logList; @JoinColumn(name = "IDPRIVILEGE", referencedColumnName = "IDPRIVILEGE") @ManyToOne(optional = false) private Roles idprivilege; @OneToMany(mappedBy = "createdBy") private List<Individu> individuList; public Utilisateur() { } public Utilisateur(Integer idutilisateur) { this.idutilisateur = idutilisateur; } public Utilisateur(Integer idutilisateur, String nom, String prenom, String email, String username, String password, Date datecreation, Date dateexpiration, String statut) { this.idutilisateur = idutilisateur; this.nom = nom; this.prenom = prenom; this.email = email; this.username = username; this.password = password; this.datecreation = datecreation; this.dateexpiration = dateexpiration; this.statut = statut; } public Integer getIdutilisateur() { return idutilisateur; } public void setIdutilisateur(Integer idutilisateur) { this.idutilisateur = idutilisateur; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getDatecreation() { return datecreation; } public void setDatecreation(Date datecreation) { this.datecreation = datecreation; } public Date getDateexpiration() { return dateexpiration; } public void setDateexpiration(Date dateexpiration) { this.dateexpiration = dateexpiration; } public String getStatut() { return statut; } public void setStatut(String statut) { this.statut = statut; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } @XmlTransient public List<Log> getLogList() { return logList; } public void setLogList(List<Log> logList) { this.logList = logList; } public Roles getIdprivilege() { return idprivilege; } public void setIdprivilege(Roles idprivilege) { this.idprivilege = idprivilege; } @XmlTransient public List<Individu> getIndividuList() { return individuList; } public void setIndividuList(List<Individu> individuList) { this.individuList = individuList; } @Override public int hashCode() { int hash = 0; hash += (idutilisateur != null ? idutilisateur.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Utilisateur)) { return false; } Utilisateur other = (Utilisateur) object; if ((this.idutilisateur == null && other.idutilisateur != null) || (this.idutilisateur != null && !this.idutilisateur.equals(other.idutilisateur))) { return false; } return true; } @Override public String toString() { //return "ht.gouv.faes.entity.Utilisateur[ idutilisateur=" + idutilisateur + " ]"; return username; } }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.component.domain.module; import java.util.Set; import java.io.Serializable; /** * @author xxp * @version 2003-6-23 * */ public class Module implements Serializable { private String moduleId; private String moduleName; private String moduleImage; private String requestPath; private String visbale; private String description; private Integer priority; private Set modules; /** * @return */ public String getDescription() { return description; } /** * @return */ public String getModuleId() { return moduleId; } /** * @return */ public String getModuleImage() { return moduleImage; } /** * @return */ public String getModuleName() { return moduleName; } /** * @return */ public Set getModules() { return modules; } /** * @return */ public String getRequestPath() { return requestPath; } /** * @return */ public String getVisbale() { return visbale; } /** * @param string */ public void setDescription(String string) { description = string; } /** * @param string */ public void setModuleId(String string) { moduleId = string; } /** * @param string */ public void setModuleImage(String string) { moduleImage = string; } /** * @param string */ public void setModuleName(String string) { moduleName = string; } /** * @param set */ public void setModules(Set set) { modules = set; } /** * @param string */ public void setRequestPath(String string) { requestPath = string; } /** * @param string */ public void setVisbale(String string) { visbale = string; } /** * @return */ public Integer getPriority() { return priority; } /** * @param string */ public void setPriority(Integer integer) { priority = integer; } }
/* * @(#) BaseNodeInfo.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ims.nodeinfo.base; import com.esum.appframework.dmo.BaseDMO; /** * This is an object that contains data related to the NODE_INFO table. * Do not modify this class because it will be overwritten if the configuration file * related to this class is modified. * * @hibernate.class * table="NODE_INFO" */ public abstract class BaseNodeInfo extends BaseDMO { public static String REF = "NodeInfo"; public static String PROP_MOD_DATE = "ModDate"; public static String PROP_REG_DATE = "RegDate"; public static String PROP_HOST_NAME = "HostName"; public static String PROP_MAIN_NODE_ID = "MainNodeId"; public static String PROP_NODE_ID = "NodeId"; public static String PROP_PORT = "Port"; public static String PROP_NODE_TYPE= "Node_type"; public static String PROP_SECURITY_YN = "Security_yn"; // constructors public BaseNodeInfo () { initialize(); } /** * Constructor for primary key */ public BaseNodeInfo (java.lang.String nodeId) { this.setNodeId(nodeId); initialize(); } /** * Constructor for required fields */ public BaseNodeInfo ( java.lang.String nodeId, java.lang.String hostName, java.lang.String port, java.lang.String node_type, java.lang.String mainNodeId, java.lang.String regDate, java.lang.String modDate) { this.setNodeId(nodeId); this.setHostName(hostName); this.setPort(port); this.setNode_type(node_type); this.setMainNodeId(mainNodeId); this.setRegDate(regDate); this.setModDate(modDate); initialize(); } protected void initialize () { hostName = ""; regDate = ""; modDate = ""; security_yn = ""; mainNodeId = ""; } // primary key protected java.lang.String nodeId; // fields protected java.lang.String hostName; protected java.lang.String port; protected java.lang.String mainNodeId; protected java.lang.String node_type; protected java.lang.String regDate; protected java.lang.String modDate; protected java.lang.String security_yn; /** * Return the value associated with the column: SECURITY_YN */ public java.lang.String getSecurity_yn() { return security_yn; } /** * Set the value related to the column: SECURITY_YN * @param hostName the SECURITY_YN value */ public void setSecurity_yn(java.lang.String security_yn) { this.security_yn = security_yn; } /** * Return the value associated with the column: node_type */ public java.lang.String getNode_type() { return node_type; } /** * Set the value related to the column: port * @param node_type the node_type value */ public void setNode_type(java.lang.String node_type) { this.node_type = node_type; } /** * Return the value associated with the column: MAIN_NODE_ID */ public java.lang.String getMainNodeId() { return mainNodeId; } /** * Set the value related to the column: MAIN_NODE_ID * @param mainNodeId the mainNodeId value */ public void setMainNodeId(java.lang.String mainNodeId) { this.mainNodeId = mainNodeId; } /** * Return the value associated with the column: port */ public java.lang.String getPort() { return port; } /** * Set the value related to the column: port * @param port the port value */ public void setPort(java.lang.String port) { this.port = port; } /** * Return the unique identifier of this class * @hibernate.id * column="NODE_ID" */ public java.lang.String getNodeId () { return nodeId; } /** * Set the unique identifier of this class * @param nodeId the new ID */ public void setNodeId (java.lang.String nodeId) { this.nodeId = nodeId; } /** * Return the value associated with the column: HOST_NAME */ public java.lang.String getHostName () { return hostName; } /** * Set the value related to the column: HOST_NAME * @param hostName the HOST_NAME value */ public void setHostName (java.lang.String hostName) { this.hostName = hostName; } /** * Return the value associated with the column: REG_DATE */ public java.lang.String getRegDate () { return regDate; } /** * Set the value related to the column: REG_DATE * @param regDate the REG_DATE value */ public void setRegDate (java.lang.String regDate) { this.regDate = regDate; } /** * Return the value associated with the column: MOD_DATE */ public java.lang.String getModDate () { return modDate; } /** * Set the value related to the column: MOD_DATE * @param modDate the MOD_DATE value */ public void setModDate (java.lang.String modDate) { this.modDate = modDate; } }
package gov.nih.mipav.view.renderer.J3D.model.structures; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import gov.nih.mipav.view.dialogs.*; import java.io.*; import javax.swing.*; import javax.vecmath.*; /** * A triangle mesh that represents a level surface. The mesh is stored in its highest level of detail. The mesh also has * an associated sequence of collapse records that store incremental changes in the vertex quantity, the triangle * quantity, and the triangle connectivity array. These records are used to dynamically change the level of detail of * the mesh. The surface viewer creates a Shape3D object whose geometry can be objects generated from an ModelClodMesh * object. The surface color is provided by attaching to the Shape3D object an appearance that contains a material. The * vertex normals in ModelClodMesh are used by the lighting system in conjunction with the surface material to produce * the surface color. */ public class ModelClodMesh { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** * Java3D supports limiting the vertices to be processed by the call setValidVertexCount(int). However, there is no * equivalent call that supports limiting the triangles [setValidIndexCount(int) is needed]. The dynamic edge * collapse partially depends on changing the number of active triangles. Since this is not supported, the * setLOD(int) method is designed to create an ModelTriangleMesh object on each change. Not very efficient. Better * would be to just allow us to change the valid index count. */ private static int[] direction = new int[3]; /** DOCUMENT ME! */ private static float[] startLocation = new float[3]; /** DOCUMENT ME! */ private static float[] box = new float[3]; //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ private int[] m_aiConnect; /** the incremental changes representing the decimation. */ private ModelCollapseRecord[] m_akRecord; /** the highest level of detail data. */ private Point3f[] m_akVertex; /** current level of detail record, 0 <= m_iCurrentRecord <= m_akRecord.length-1. */ private int m_iCurrentRecord; /** the triangle mesh corresponding to the current level of detail. */ private ModelTriangleMesh m_kMesh; //~ Constructors --------------------------------------------------------------------------------------------------- /** * A triangle mesh whose vertices have a common vertex color and vertex normal vectors that are computed from the * geometry of the mesh itself. The collapse records form a sequence of incremental changes that are used to * dynamically change the level of detail by incrementing or decrementing vertex and triangle quantities. * * @param akVertex Array of vertices in the mesh. * @param aiConnect Connectivity array for the triangles. Each triple of indices represents one triangle. The * triangle is counterclockwise ordered as viewed by an observer outside the mesh. * @param akRecord Array of collapse records that are computed by ModelSurfaceDecimator. */ public ModelClodMesh(Point3f[] akVertex, int[] aiConnect, ModelCollapseRecord[] akRecord) { m_akVertex = akVertex; m_aiConnect = aiConnect; m_akRecord = akRecord; // Initialize the mesh by starting at lowest resolution, then // increasing to highest resolution. The mesh was be allocated // initially in case the input array is a single triangle, in which // case getMaximumLOD() is zero and setLOD(getMaximumLOD()) does // no work, including not allocating the mesh. m_kMesh = new ModelTriangleMesh(akVertex, aiConnect); m_kMesh.setGenerator(this); m_iCurrentRecord = 0; setLOD(0); setLOD(getMaximumLOD()); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static int[] getDirection() { return direction; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public static float[] getStartLocation() { return startLocation; } /** * Load the clod mesh from a binary file. The caller must have already opened the file and read the mesh type (0 = * ModelTriangleMesh, 1 = ModelClodMesh) and the number of meshes in the file. The caller then calls this function * for each mesh. The format for a mesh is * * <pre> int vCount; // number of vertices Point3f vertices[vCount]; Point3f normals[vCount]; int iCount; // number of indices in the connectivity array int indices[iCount]; int rCount; ModelCollapseRecord collapses[rCount]; * </pre> * * with 4-byte quantities stored in Big Endian format. * * @param kIn the file from which the triangle mesh is loaded * @param progress DOCUMENT ME! * @param added param piece * @param piece DOCUMENT ME! * * @return the loaded triangle mesh * * @exception IOException if there is an error reading from the file */ public static ModelClodMesh loadCMesh(RandomAccessFile kIn, ViewJProgressBar progress, int added, int piece) throws IOException { try { int i, index, tmpInt, prog; int b1 = 0, b2 = 0, b3 = 0, b4 = 0; int actions; boolean flip; boolean dicom; long c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0; long tmpLong; int j; //double[][] inverseDicomArray; TransMatrix inverseDicomMatrix = new TransMatrix(4); float[] tCoord = new float[3]; float[] coord = new float[3]; actions = kIn.readInt(); if ((actions == 1) || (actions == 3)) { flip = true; } else { flip = false; } if ((actions == 2) || (actions == 3)) { dicom = true; } else { dicom = false; } direction[0] = kIn.readInt(); direction[1] = kIn.readInt(); direction[2] = kIn.readInt(); byte[] buffer = new byte[24]; kIn.read(buffer); index = 0; b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[0] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[1] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[2] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[0] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[1] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[2] = Float.intBitsToFloat(tmpInt); if (dicom) { buffer = new byte[128]; kIn.read(buffer); index = 0; //inverseDicomArray = new double[4][4]; for (i = 0; i <= 3; i++) { for (j = 0; j <= 3; j++) { c1 = buffer[index++] & 0xffL; c2 = buffer[index++] & 0xffL; c3 = buffer[index++] & 0xffL; c4 = buffer[index++] & 0xffL; c5 = buffer[index++] & 0xffL; c6 = buffer[index++] & 0xffL; c7 = buffer[index++] & 0xffL; c8 = buffer[index++] & 0xffL; tmpLong = ((c1 << 56) | (c2 << 48) | (c3 << 40) | (c4 << 32) | (c5 << 24) | (c6 << 16) | (c7 << 8) | c8); inverseDicomMatrix.set(i,j, Double.longBitsToDouble(tmpLong)); } } } // if (dicom) // read vertices int iVertexCount = kIn.readInt(); Point3f[] akVertex = new Point3f[iVertexCount]; int bufferSize = 12 * iVertexCount; byte[] bufferVertex = new byte[bufferSize]; byte[] bufferNormal = new byte[bufferSize]; progress.setLocation(200, 200); progress.setVisible(true); kIn.read(bufferVertex); kIn.read(bufferNormal); prog = Math.round((float) iVertexCount * piece / 25); for (i = 0, index = 0; i < iVertexCount; i++) { akVertex[i] = new Point3f(); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].x = Float.intBitsToFloat(tmpInt); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].y = Float.intBitsToFloat(tmpInt); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].z = Float.intBitsToFloat(tmpInt); if (dicom) { tCoord[0] = akVertex[i].x - startLocation[0]; tCoord[1] = akVertex[i].y - startLocation[1]; tCoord[2] = akVertex[i].z - startLocation[2]; inverseDicomMatrix.transform(tCoord, coord); akVertex[i].x = (coord[0] * direction[0]) + startLocation[0]; akVertex[i].y = (coord[1] * direction[1]) + startLocation[1]; akVertex[i].z = (coord[2] * direction[2]) + startLocation[2]; } // if (dicom) if (flip) { // Flip (kVertex.y - startLocation[1], but // don't flip startLocation[1] akVertex[i].y = (2 * startLocation[1]) + (box[1] * direction[1]) - akVertex[i].y; akVertex[i].z = (2 * startLocation[2]) + (box[2] * direction[2]) - akVertex[i].z; } if ((prog != 0) && ((i % prog) == 0)) { progress.updateValueImmed(added + (i / prog)); } } // read normals (discarded for now) Vector3f[] akNormal = new Vector3f[iVertexCount]; for (i = 0, index = 0; i < iVertexCount; i++) { akNormal[i] = new Vector3f(); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].x = Float.intBitsToFloat(tmpInt); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].y = Float.intBitsToFloat(tmpInt); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].z = Float.intBitsToFloat(tmpInt); if ((prog != 0) && ((i % prog) == 0)) { progress.updateValueImmed(Math.round(25 / piece) + added + (i / prog)); } } // read connectivity int iIndexCount = kIn.readInt(); int[] aiConnect = new int[iIndexCount]; byte[] bufferConnect = new byte[iIndexCount * 4]; kIn.read(bufferConnect); prog = iIndexCount * piece / 25; for (i = 0, index = 0; i < iIndexCount; i++) { b1 = bufferConnect[index++] & 0x000000ff; b2 = bufferConnect[index++] & 0x000000ff; b3 = bufferConnect[index++] & 0x000000ff; b4 = bufferConnect[index++] & 0x000000ff; aiConnect[i] = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); if ((prog != 0) && ((i % prog) == 0)) { progress.updateValueImmed(Math.round(50 / piece) + added + (i / prog)); } } int iRecordCount = kIn.readInt(); ModelCollapseRecord[] akRecord = new ModelCollapseRecord[iRecordCount]; prog = iRecordCount * piece / 25; for (i = 0; i < iRecordCount; i++) { akRecord[i] = new ModelCollapseRecord(); akRecord[i].load(kIn); if ((prog != 0) && ((i % prog) == 0)) { progress.updateValueImmed(Math.round(75 / piece) + added + (i / prog)); } } return new ModelClodMesh(akVertex, aiConnect, akRecord); } catch (IOException e) { return null; } } /** * Load the clod mesh from a binary file. The caller must have already opened the file and read the mesh type (0 = * ModelTriangleMesh, 1 = ModelClodMesh) and the number of meshes in the file. The caller then calls this function * for each mesh. The format for a mesh is * * <pre> int vCount; // number of vertices Point3f vertices[vCount]; Point3f normals[vCount]; int iCount; // number of indices in the connectivity array int indices[iCount]; int rCount; ModelCollapseRecord collapses[rCount]; * </pre> * * with 4-byte quantities stored in Big Endian format. * * @param kIn the file from which the triangle mesh is loaded * @param pBar DOCUMENT ME! * @param added DOCUMENT ME! * @param piece DOCUMENT ME! * * @return the loaded triangle mesh * * @exception IOException if there is an error reading from the file */ public static ModelClodMesh loadCMesh(RandomAccessFile kIn, JProgressBar pBar, int added, int piece) throws IOException { try { int i, index, tmpInt, prog; int b1 = 0, b2 = 0, b3 = 0, b4 = 0; int actions; boolean flip; boolean dicom; long c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0; long tmpLong; int j; //double[][] inverseDicomArray; TransMatrix inverseDicomMatrix = new TransMatrix(4); float[] tCoord = new float[3]; float[] coord = new float[3]; actions = kIn.readInt(); if ((actions == 1) || (actions == 3)) { flip = true; } else { flip = false; } if ((actions == 2) || (actions == 3)) { dicom = true; } else { dicom = false; } direction[0] = kIn.readInt(); direction[1] = kIn.readInt(); direction[2] = kIn.readInt(); byte[] buffer = new byte[24]; kIn.read(buffer); index = 0; b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[0] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[1] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); startLocation[2] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[0] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[1] = Float.intBitsToFloat(tmpInt); b1 = buffer[index++] & 0xff; b2 = buffer[index++] & 0xff; b3 = buffer[index++] & 0xff; b4 = buffer[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); box[2] = Float.intBitsToFloat(tmpInt); if (dicom) { buffer = new byte[128]; kIn.read(buffer); index = 0; //inverseDicomArray = new double[4][4]; for (i = 0; i <= 3; i++) { for (j = 0; j <= 3; j++) { c1 = buffer[index++] & 0xffL; c2 = buffer[index++] & 0xffL; c3 = buffer[index++] & 0xffL; c4 = buffer[index++] & 0xffL; c5 = buffer[index++] & 0xffL; c6 = buffer[index++] & 0xffL; c7 = buffer[index++] & 0xffL; c8 = buffer[index++] & 0xffL; tmpLong = ((c1 << 56) | (c2 << 48) | (c3 << 40) | (c4 << 32) | (c5 << 24) | (c6 << 16) | (c7 << 8) | c8); inverseDicomMatrix.set(i,j, Double.longBitsToDouble(tmpLong)); } } } // if (dicom) // read vertices int iVertexCount = kIn.readInt(); Point3f[] akVertex = new Point3f[iVertexCount]; int bufferSize = 12 * iVertexCount; byte[] bufferVertex = new byte[bufferSize]; byte[] bufferNormal = new byte[bufferSize]; // progress.setLocation(200, 200); // progress.setVisible(true); kIn.read(bufferVertex); kIn.read(bufferNormal); prog = Math.round((float) iVertexCount * piece / 25); for (i = 0, index = 0; i < iVertexCount; i++) { akVertex[i] = new Point3f(); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].x = Float.intBitsToFloat(tmpInt); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].y = Float.intBitsToFloat(tmpInt); b1 = bufferVertex[index++] & 0xff; b2 = bufferVertex[index++] & 0xff; b3 = bufferVertex[index++] & 0xff; b4 = bufferVertex[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akVertex[i].z = Float.intBitsToFloat(tmpInt); if (dicom) { tCoord[0] = akVertex[i].x - startLocation[0]; tCoord[1] = akVertex[i].y - startLocation[1]; tCoord[2] = akVertex[i].z - startLocation[2]; inverseDicomMatrix.transform(tCoord, coord); akVertex[i].x = (coord[0] * direction[0]) + startLocation[0]; akVertex[i].y = (coord[1] * direction[1]) + startLocation[1]; akVertex[i].z = (coord[2] * direction[2]) + startLocation[2]; } // if (dicom) if (flip) { // Flip (kVertex.y - startLocation[1], but // don't flip startLocation[1] akVertex[i].y = (2 * startLocation[1]) + (box[1] * direction[1]) - akVertex[i].y; akVertex[i].z = (2 * startLocation[2]) + (box[2] * direction[2]) - akVertex[i].z; } if ((prog != 0) && ((i % prog) == 0)) { pBar.setValue(added + (i / prog)); pBar.update(pBar.getGraphics()); } } // read normals (discarded for now) Vector3f[] akNormal = new Vector3f[iVertexCount]; for (i = 0, index = 0; i < iVertexCount; i++) { akNormal[i] = new Vector3f(); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].x = Float.intBitsToFloat(tmpInt); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].y = Float.intBitsToFloat(tmpInt); b1 = bufferNormal[index++] & 0xff; b2 = bufferNormal[index++] & 0xff; b3 = bufferNormal[index++] & 0xff; b4 = bufferNormal[index++] & 0xff; tmpInt = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); akNormal[i].z = Float.intBitsToFloat(tmpInt); if ((prog != 0) && ((i % prog) == 0)) { pBar.setValue(Math.round(25 / piece) + added + (i / prog)); pBar.update(pBar.getGraphics()); } } // read connectivity int iIndexCount = kIn.readInt(); int[] aiConnect = new int[iIndexCount]; byte[] bufferConnect = new byte[iIndexCount * 4]; kIn.read(bufferConnect); prog = iIndexCount * piece / 25; for (i = 0, index = 0; i < iIndexCount; i++) { b1 = bufferConnect[index++] & 0x000000ff; b2 = bufferConnect[index++] & 0x000000ff; b3 = bufferConnect[index++] & 0x000000ff; b4 = bufferConnect[index++] & 0x000000ff; aiConnect[i] = ((b1 << 24) | (b2 << 16) | (b3 << 8) | b4); if ((prog != 0) && ((i % prog) == 0)) { pBar.setValue(Math.round(50 / piece) + added + (i / prog)); pBar.update(pBar.getGraphics()); } } int iRecordCount = kIn.readInt(); ModelCollapseRecord[] akRecord = new ModelCollapseRecord[iRecordCount]; prog = iRecordCount * piece / 25; for (i = 0; i < iRecordCount; i++) { akRecord[i] = new ModelCollapseRecord(); akRecord[i].load(kIn); if ((prog != 0) && ((i % prog) == 0)) { pBar.setValue(Math.round(75 / piece) + added + (i / prog)); pBar.update(pBar.getGraphics()); } } return new ModelClodMesh(akVertex, aiConnect, akRecord); } catch (IOException e) { return null; } } /** * Save an array of triangle meshes to a text file. The format for the file is * * <pre> int type; // 0 = ModelTriangleMesh, 1 = ModelClodMesh int aCount; // number of array elements array of 'aCount' meshes, each of the form: int vCount; // number of vertices vertex[0].x vertex[0].y vertex[0].z; : normal[0].x normal[0].y normal[0].z; : int tCount; // number of triangles index[0] index[1] index[2] : index[3*(tCount-1)] index[3*(tCount-1)+1] index[3*(tCount-1)+2] * </pre> * * @param kName the name of the file to which the components are saved * @param akComponent the array of mesh components to save * * @exception IOException if the specified file could not be opened for writing */ public static void print(String kName, ModelClodMesh[] akComponent) throws IOException { if (akComponent.length == 0) { return; } PrintWriter kOut = new PrintWriter(new FileWriter(kName)); kOut.println('1'); // objects are ModelClodMesh kOut.println(akComponent.length); for (int i = 0; i < akComponent.length; i++) { akComponent[i].print(kOut); } kOut.close(); } /** * Save an array of triangle meshes to a binary file. The format for the file is * * <pre> int type; // 0 = ModelTriangleMesh, 1 = ModelClodMesh int aCount; // number of array elements array of 'aCount' meshes, each of the form: int vCount; // number of vertices Point3f vertices[vCount]; Point3f normals[vCount]; int iCount; // number of indices in the connectivity array int indices[iCount]; * </pre> * * with 4-byte quantities stored in Big Endian format. * * @param kName the name of the file to which the components are saved * @param akComponent the array of mesh components to be saved * @param flip if the y axis should be flipped - true in extract and in save of JDialogSurface To * have proper orientations in surface file if flip is true flip y and z on reading. * @param direction 1 or -1 for each axis * @param startLocation DOCUMENT ME! * @param box (dim-1)*res * @param inverseDicomMatrix * * @exception IOException if there is an error writing to the file */ public static void save(String kName, ModelClodMesh[] akComponent, boolean flip, int[] direction, float[] startLocation, float[] box, TransMatrix inverseDicomMatrix) throws IOException { if (akComponent.length == 0) { return; } RandomAccessFile kOut = new RandomAccessFile(new File(kName), "rw"); kOut.writeInt(1); // objects are ModelClodMesh kOut.writeInt(akComponent.length); for (int i = 0; i < akComponent.length; i++) { akComponent[i].save(kOut, flip, direction, startLocation, box, inverseDicomMatrix); } kOut.close(); if (Preferences.debugLevel(Preferences.DEBUG_MINOR)) { ModelClodMesh.print(JDialogBase.makeImageName(kName, "_sur.txt"), akComponent); } } /** * The current level of detail C with 0 <= C <= getMaximumLOD(). * * @return DOCUMENT ME! */ public int getLOD() { return m_akRecord.length - 1 - m_iCurrentRecord; } /** * The maximum level of detail supported by the mesh. The minimum level of detail is always zero (the first collapse * record). * * @return DOCUMENT ME! */ public int getMaximumLOD() { return m_akRecord.length - 1; } /** * Accessor for the triangle mesh that corresponds to the current level of detail in the ModelClodMesh. * * @return the triangle mesh managed by the clod mesh */ public ModelTriangleMesh getMesh() { return m_kMesh; } /** * Save the triangle mesh to a text file. The format for the file is * * <pre> int type; // 0 = ModelTriangleMesh, 1 = ModelClodMesh int aCount; // 1, write the entire mesh as a single component int vCount; // number of vertices vertex[0].x vertex[0].y vertex[0].z; : normal[0].x normal[0].y normal[0].z; : int tCount; // number of triangles index[0] index[1] index[2] : index[3*(tCount-1)] index[3*(tCount-1)+1] index[3*(tCount-1)+2] * </pre> * * @param kName the name of file to which the triangle mesh is saved * * @exception IOException if the specified file could not be opened for writing */ public void print(String kName) throws IOException { PrintWriter kOut = new PrintWriter(new FileWriter(kName)); kOut.println('1'); // object is ModelClodMesh kOut.println('1'); // one component print(kOut); kOut.close(); } /** * Set the current level of detail to C with 0 <= C <= getMaximumLOD(). * * @param iLOD the desired index of the active collapse record */ public void setLOD(int iLOD) { if ((iLOD < 0) || (iLOD >= m_akRecord.length)) { // LOD out of range, do nothing return; } int iTargetRecord = m_akRecord.length - 1 - iLOD; if (m_iCurrentRecord == iTargetRecord) { // requested LOD is current LOD, do nothing return; } int i, iVQuantity = 0, iTQuantity = 0; ModelCollapseRecord kRecord; // collapse mesh (if necessary) while (m_iCurrentRecord < iTargetRecord) { m_iCurrentRecord++; // replace indices in connectivity array kRecord = m_akRecord[m_iCurrentRecord]; for (i = 0; i < kRecord.m_iIQuantity; i++) { m_aiConnect[kRecord.m_aiIndex[i]] = kRecord.m_iVKeep; } // reduce vertex count (vertices are properly ordered) iVQuantity = kRecord.m_iVQuantity; // reduce triangle count (triangles are properly ordered) iTQuantity = kRecord.m_iTQuantity; } // expand mesh (if necessary) while (m_iCurrentRecord > iTargetRecord) { // restore indices in connectivity array kRecord = m_akRecord[m_iCurrentRecord]; for (i = 0; i < kRecord.m_iIQuantity; i++) { m_aiConnect[kRecord.m_aiIndex[i]] = kRecord.m_iVThrow; } m_iCurrentRecord--; ModelCollapseRecord kPrevRecord = m_akRecord[m_iCurrentRecord]; // increase vertex count (vertices are properly ordered) iVQuantity = kPrevRecord.m_iVQuantity; // increase triangle count (triangles are properly ordered) iTQuantity = kPrevRecord.m_iTQuantity; } // get valid vertices Point3f[] akVertex = new Point3f[iVQuantity]; System.arraycopy(m_akVertex, 0, akVertex, 0, iVQuantity); // get valid indices int[] aiConnect = new int[3 * iTQuantity]; System.arraycopy(m_aiConnect, 0, aiConnect, 0, 3 * iTQuantity); // generate the mesh corresponding to the current level of detail m_kMesh = new ModelTriangleMesh(akVertex, aiConnect); m_kMesh.setGenerator(this); } /** * Accessor to reset the verticies associated with this clod. Used for smoothing. * * @param verticies New vertices for clod mesh. */ public void setVerticies(Point3f[] verticies) { m_akVertex = verticies; } /** * Internal support for 'void print (String)' and 'void print (String, ModelTriangleMesh[])'. ModelTriangleMesh uses * this function to print vertices, normals, and connectivity indices to the file. ModelClodMesh overrides this to * additionally print collapse records to the file in the form: * * <pre> int rCount; // number of collapse records r[0].keep r[0].throw r[0].vCount r[0].tcount r[0].iCount indices... : * </pre> * * @param kOut the file to which the clod mesh is saved * * @exception IOException if there is an error writing to the file */ protected void print(PrintWriter kOut) throws IOException { m_kMesh.print(kOut); // write collapse records kOut.println(m_akRecord.length); for (int i = 0; i < m_akRecord.length; i++) { m_akRecord[i].print(kOut); } } /** * Internal support for 'void save (String)' and 'void save (String, ModelTriangleMesh[])'. ModelTriangleMesh uses * this function to write vertices, normals, and connectivity indices to the file. ModelClodMesh overrides this to * additionally write collapse records to the file in the form: * * <pre> int rCount; ModelCollapseRecord collapses[rCount]; * </pre> * * with 4-byte quantities stored in Big Endian format. * * @param kOut the file to which the clod mesh is saved * @param flip if the y axis should be flipped - true in extract and in save of JDialogSurface To * have proper orientations in surface file if flip is true flip y and z on reading. * @param direction 1 or -1 for each axis * @param startLocation DOCUMENT ME! * @param box (dim-1)*res * @param inverseDicomMatrix DOCUMENT ME! * * @exception IOException if there is an error writing to the file */ protected void save(RandomAccessFile kOut, boolean flip, int[] direction, float[] startLocation, float[] box, TransMatrix inverseDicomMatrix) throws IOException { m_kMesh.save(kOut, flip, direction, startLocation, box, inverseDicomMatrix, null); // write collapse records kOut.writeInt(m_akRecord.length); for (int i = 0; i < m_akRecord.length; i++) { m_akRecord[i].save(kOut); } } }
package com.example.mycalorietracker; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.Calendar; import java.util.Date; public class ScheduledIntentService extends IntentService { public ScheduledIntentService() { super("ScheduledIntentService"); } @Override protected void onHandleIntent(Intent intent) { PostToServer postToServer = new PostToServer(); postToServer.addInReport(getApplicationContext()); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent,flags,startId); } }
package com.adi.ho.jackie.versa_news.SyncAdapter; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.SyncResult; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.adi.ho.jackie.versa_news.GSONClasses.ViceDataClass; import com.adi.ho.jackie.versa_news.ContentProvider.ViceContentProvider; import com.adi.ho.jackie.versa_news.ContentProvider.ViceDBHelper; import com.adi.ho.jackie.versa_news.MainActivity; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Rob on 3/8/16. */ public class SyncAdapter extends AbstractThreadedSyncAdapter { ContentResolver mResolver; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mResolver = context.getContentResolver(); } public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) { super(context, autoInitialize, allowParallelSyncs); mResolver = context.getContentResolver(); } @Override public void onPerformSync( Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d(SyncAdapter.class.getName(), "Starting sync"); Cursor cursor = mResolver.query(ViceContentProvider.CONTENT_URI,null,null,null,null); /* // TODO: Update the methods here to refresh the data that should be refreshed. The refreshed data should update the database and replace the existing database data. ViceDataClass title; while(cursor.moveToNext()){ title = getData(cursor.getString(cursor.getColumnIndex(ViceDBHelper.COLUMN_TITLE))); Uri uri = Uri.parse(ViceContentProvider.CONTENT_URI + "/" + cursor.getString(cursor.getColumnIndex(ViceDBHelper.COLUMN_ID))); ContentValues values = new ContentValues(); values.put(ViceDBHelper.COLUMN_BODY, getData(MainActivity.getMostPopularURL).getItems()); mResolver.update(uri,values,null,null); } */ } private ViceDataClass getData(String viceURL){ String data =""; try { URL url = new URL(viceURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream inStream = connection.getInputStream(); data = getInputData(inStream); } catch (Throwable e) { e.printStackTrace(); } Gson gson = new Gson(); return gson.fromJson(data,ViceDataClass.class); } private String getInputData(InputStream inStream) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); String data = null; while ((data = reader.readLine()) != null){ builder.append(data); } reader.close(); return builder.toString(); } }
package ggwozdz.nordea.texttransform; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import com.google.common.base.Strings; class IntendingXMLOutputWriter { private final XMLStreamWriter xmlWriter; private int depthCounter = 0; private IntendingXMLOutputWriter(OutputStream os) { this.xmlWriter = createWriter(os); } public static IntendingXMLOutputWriter forOutput(OutputStream os){ return new IntendingXMLOutputWriter(os); } private XMLStreamWriter createWriter(OutputStream os){ try { return XMLOutputFactory.newInstance().createXMLStreamWriter(new OutputStreamWriter(os, "utf-8")); } catch (UnsupportedEncodingException | XMLStreamException | FactoryConfigurationError e) { throw new IllegalStateException("Cannot create XML writer", e); } } public IntendingXMLOutputWriter createDoc(){ try { xmlWriter.writeStartDocument(); return this; } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document:"+e.getMessage(), e); } } public void closeDoc(){ try { xmlWriter.writeEndDocument(); xmlWriter.close(); } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document:"+e.getMessage(), e); } } public IntendingXMLOutputWriter startElement(String elementName){ try { this.indentNextElement(depthCounter); xmlWriter.writeStartElement(elementName); ++depthCounter; return this; } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document",e); } } public IntendingXMLOutputWriter createElementWithText(String elementName, String text){ try { this.indentNextElement(depthCounter); xmlWriter.writeStartElement(elementName); this.writeText(text); xmlWriter.writeEndElement(); return this; } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document",e); } } public IntendingXMLOutputWriter endElement() { try { this.indentNextElement(--depthCounter); xmlWriter.writeEndElement(); return this; } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document",e); } } public IntendingXMLOutputWriter writeText(String text) { try { xmlWriter.writeCharacters(text); return this; } catch (XMLStreamException e) { throw new IllegalStateException("Error generating XML document",e); } } private void indentNextElement(int depth){ this.writeText("\n"); this.writeText(Strings.repeat(" ", depth)); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow 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 any later version. * * * * Data Crow 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 net.datacrow.console.components.panels; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JToolTip; import javax.swing.SwingConstants; import javax.swing.border.Border; import net.datacrow.console.ComponentFactory; import net.datacrow.console.Layout; import net.datacrow.console.components.DcLabel; import net.datacrow.console.components.DcMenu; import net.datacrow.console.components.DcMenuItem; import net.datacrow.console.components.DcMultiLineToolTip; import net.datacrow.console.components.DcPanel; import net.datacrow.core.DataCrow; import net.datacrow.core.DcRepository; import net.datacrow.core.IconLibrary; import net.datacrow.core.modules.DcModule; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcField; import net.datacrow.settings.DcSettings; import net.datacrow.util.Utilities; public class ModuleListPanel extends JPanel { private Collection<JComponent> components = new ArrayList<JComponent>(); private static Border borderDefault; private static Border borderSelected; public ModuleListPanel() { buildPanel(); } public void rebuild() { removeAll(); buildPanel(); } @Override public void setFont(Font font) { if (components == null) return; for (JComponent c : components) { c.setFont(font); } } public void setSelectedModule(int index) { if (DataCrow.mainFrame != null) DataCrow.mainFrame.changeModule(index); } private void buildPanel() { setLayout(Layout.getGBL()); int x = 0; ModuleSelector ms; for (DcModule module : DcModules.getModules()) { if (module.isSelectableInUI() && module.isEnabled()) { ms = new ModuleSelector(module); add(ms, Layout.getGBC( x++, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); components.add(ms); } } } private class ModuleSelector extends DcPanel implements ActionListener { private MainModuleButton mmb; private List<DcModule> referencedModules = new ArrayList<DcModule>(); private DcModule module; private ModuleSelector(DcModule module) { this.module = module; this.mmb = new MainModuleButton(module); this.mmb.setBackground(getBackground()); this.setToolTipText(module.getLabel() + (Utilities.isEmpty(module.getDescription()) ? "" : "\n" + module.getDescription())); addMouseListener(new ModuleMouseListener(module.getIndex())); DcModule rm; for (DcField field : module.getFields()) { rm = DcModules.getReferencedModule(field); if ( rm.isEnabled() && rm.getIndex() != module.getIndex() && rm.getType() != DcModule._TYPE_PROPERTY_MODULE && rm.getType() != DcModule._TYPE_EXTERNALREFERENCE_MODULE && rm.getIndex() != DcModules._CONTACTPERSON && rm.getIndex() != DcModules._CONTAINER) { referencedModules.add(rm); } } build(); } @Override public JToolTip createToolTip() { return new DcMultiLineToolTip(); } @Override public Border getBorder() { return ((mmb != null && mmb.getModule() != null) && (mmb.getModule() == DcModules.getCurrent() || (mmb.getModule().getIndex() == DcModules._CONTAINER && DcModules.getCurrent().getIndex() == DcModules._ITEM))) ? borderSelected : borderDefault; } private void build() { borderDefault = BorderFactory.createTitledBorder( BorderFactory.createLineBorder(Color.LIGHT_GRAY, 0)); borderSelected = BorderFactory.createTitledBorder( BorderFactory.createLineBorder(DcSettings.getColor(DcRepository.Settings.stSelectionColor), 3)); setBorder(borderDefault); setLayout(Layout.getGBL()); mmb.addModule(module, this); ReferenceModuleButton rmb; for (DcModule rm : referencedModules) { rmb = mmb.addModule(rm, this); DcModule cm = DcModules.getCurrent(); if (rm.getIndex() == cm.getIndex()) { switchModule(rmb); } } add(mmb, Layout.getGBC(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); } public DcModule getModule() { return module; } private void switchModule(ReferenceModuleButton mb) { module = mb.getModule(); mmb.setModule(mb.module); this.setToolTipText(module.getLabel() + (Utilities.isEmpty(module.getDescription()) ? "" : "\n" + module.getDescription())); repaint(); revalidate(); } @Override public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().startsWith("module_change")) { ReferenceModuleButton mb = (ReferenceModuleButton) ae.getSource(); switchModule(mb); setSelectedModule(mb.getModule().getIndex()); } } } private class ModuleMouseListener implements MouseListener { private final int module; public ModuleMouseListener(int module) { this.module = module; } @Override public void mouseReleased(MouseEvent me) { ModuleSelector mmb = (ModuleSelector) me.getSource(); setSelectedModule(mmb.getModule().getIndex()); } @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseClicked(MouseEvent e) {} } protected class MainModuleButton extends JPanel { private DcModule module; private final Color selectedColor; private final Color normalColor; private final JMenuBar mb; private final JMenu menu; DcLabel lblModule; public MainModuleButton(DcModule module) { super(Layout.getGBL()); this.mb = ComponentFactory.getMenuBar(); this.mb.setBorderPainted(false); this.mb.setBackground(getBackground()); components.add(mb); this.module = module; this.selectedColor = DcSettings.getColor(DcRepository.Settings.stSelectionColor); this.normalColor = super.getBackground(); setBorder(null); setMinimumSize(new Dimension(60, 50)); setPreferredSize(new Dimension(60, 50)); lblModule = ComponentFactory.getLabel(module.getIcon32()); add(lblModule, Layout.getGBC( 0, 0, 1, 1, 1.0, 1.0 ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); menu = new DcMenu(""); menu.setIcon(IconLibrary._icoModuleBarSelector); menu.setFont(null); menu.setBorderPainted(false); mb.setBorderPainted(false); menu.setHorizontalAlignment(SwingConstants.CENTER); menu.setVerticalAlignment(SwingConstants.CENTER); menu.setRolloverEnabled(false); menu.setContentAreaFilled(false); menu.setMinimumSize(new Dimension(60, 10)); menu.setPreferredSize(new Dimension(60, 10)); mb.add(menu); add(mb, Layout.getGBC(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); } public void setModule(DcModule module) { this.lblModule.setIcon(module.getIcon32()); this.module = module; } public ReferenceModuleButton addModule(DcModule module, ModuleSelector ms) { ReferenceModuleButton rmb = new ReferenceModuleButton(module); rmb.setActionCommand("module_change"); rmb.addActionListener(ms); rmb.setBackground(getBackground()); rmb.setMinimumSize(new Dimension(180, 39)); rmb.setPreferredSize(new Dimension(180, 39)); menu.add(rmb); return rmb; } public DcModule getModule() { return module; } @Override public Color getBackground() { if (getModule() != null && ( getModule() == DcModules.getCurrent() || (getModule().getIndex() == DcModules._CONTAINER && DcModules.getCurrent().getIndex() == DcModules._ITEM))) { return selectedColor; } else { return normalColor; } } @Override public JToolTip createToolTip() { return new DcMultiLineToolTip(); } @Override public String getToolTipText() { return module.getDescription(); } @Override public void setFont(Font font) { Component[] components = getComponents(); for (int i = 0; i < components.length; i++) { components[i].setFont(font); components[i].setForeground(ComponentFactory.getCurrentForegroundColor()); } } } private class ReferenceModuleButton extends DcMenuItem { private DcModule module; private ReferenceModuleButton(DcModule module) { super(module.getLabel()); this.module = module; setBorder(null); setRolloverEnabled(false); setFont(DcSettings.getFont(DcRepository.Settings.stSystemFontBold)); setMinimumSize(new Dimension(50, 35)); setPreferredSize(new Dimension(50, 35)); } public DcModule getModule() { return module; } @Override public Icon getIcon() { return module.getIcon32(); } @Override public String getLabel() { return module.getLabel(); } @Override public String getText() { return module != null ? module.getLabel() : ""; } } }
package com.nmt.crud.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Getter @Setter @Table(name = "Student_Class") @NoArgsConstructor public class StudentClass implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "Id_Class") @GeneratedValue(strategy = GenerationType.IDENTITY) private int idClass; @Column(name = "Name_Class") private String nameClass; }
package com.ledungcobra.entites; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.MappedSuperclass; @MappedSuperclass @Getter @Setter @NoArgsConstructor public abstract class User extends BaseEntity { @Column(name = "PASSWORD", nullable = false) protected String password; public User(String password) { this.password = password; } public abstract String getUserId(); public abstract String getFullName(); }
package kr.co.shop.batch.cmm.repository.master.base; import java.util.List; import java.lang.Object; import kr.co.shop.batch.cmm.model.master.CmMessageSendHistory; /** * ※ 절대 수정 금지. 해당 파일은 code generator 작동 시 내용을 전부 덮어 씌우게 됩니다. * */ public interface BaseCmMessageSendHistoryDao { /** * 이 select 메소드는 Code Generator를 통하여 생성 되었습니다. */ public List<CmMessageSendHistory> select(CmMessageSendHistory cmMessageSendHistory) throws Exception; /** * 이 select 메소드는 Code Generator를 통하여 생성 되었습니다. */ public int insert(CmMessageSendHistory cmMessageSendHistory) throws Exception; /** * 이 select 메소드는 Code Generator를 통하여 생성 되었습니다. */ public int update(CmMessageSendHistory cmMessageSendHistory) throws Exception; /** * 이 select 메소드는 Code Generator를 통하여 생성 되었습니다. */ public int delete(CmMessageSendHistory cmMessageSendHistory) throws Exception; }
package org.usfirst.frc.team3164.lib.baseComponents.motors; import edu.wpi.first.wpilibj.Victor; public class VicMotor implements IMotor { private int pwmLoc; private Victor m; private double power; private boolean reversed; /** * Make a new Motor Object * @param pwmLoc PWM location of the motor */ public VicMotor(int pwmLoc) { this.pwmLoc = pwmLoc; this.m = new Victor(this.pwmLoc); this.power = 0; } /** * Make a new Motor Object * @param pwmLoc PWM location of the motor * @param reversed true if the motor should be reversed. */ public VicMotor(final int pwmLoc, boolean reversed) { this(pwmLoc); this.reversed = reversed; } /** * Please Please Please Please don't mess with this unless you MUST! D: * @return The Jag cotroller */ @Deprecated public Victor getVic() { return m; } //***************** //****Overridden*** //***************** /** * Set the power of the motor * @param pwr power of the motor, -1.0 to 1.0 */ @Override public void setPower(double pwr) { this.power = pwr; m.set(reversed ? -power : power); } /** * Set the scaled power of the motor * @param pwr power of the motor, -100 to 100 */ @Override public void setScaledPower(int pwr) { this.power = pwr/100.0; m.set(reversed ? -power : power); } /** * Adds power for incrementing power purposes * @param pwr power to increase/decrease by. */ @Override public void addPower(double pwr) { this.power += pwr; this.checkPower(); m.set(reversed ? -power : power); } /** * Stop the motor. */ @Override public void stop() { m.set(0); } @Override @Deprecated //Unfinished public void slowStop() { //TODO Use a thread calling back here to stop slowly } //***************** //*****Private***** //***************** private void checkPower() { if(this.power>1.0) { this.power = 1.0; } if(this.power<-1.0) { this.power = -1.0; } } }
package com.trump.auction.web.service; import java.util.Map; import com.trump.auction.web.util.HandleResult; public interface PayService { /** * <p> * Title: 主动查询是否支付成功 * </p> * <p> * Description: * </p> * @param outTradeNo * @param type * @return */ HandleResult isPaySuccess(String outTradeNo, String type); /** * <p> * Title: 微信支付回调 * </p> * <p> * Description: * </p> * @param map * @param body * @return */ HandleResult handeWechatPayBack(Map<String, String> map, String body); /** * <p> * Title: 支付宝支付回调 * </p> * <p> * Description: * </p> * @param params * @param dataJson * @return */ HandleResult handleAlipayBack(Map<String, String> params, String dataJson); // HandleResult testToPay(String bathNo,String type); }
package ejercicio03; import java.util.StringTokenizer; /** * * @author Javier */ public class Ejercicio03 { public static void main(String[] args) { StringTokenizer nombre = new StringTokenizer ("Javier;Berrocal;Martín", ";"); for (int i = 0; i < nombre.countTokens(); i++) { System.out.println(nombre.nextToken()); } String numeroStr = "777"; System.out.println(Integer.parseInt(numeroStr)+333); } }
package com.ai.platform.agent.entity; import java.util.ArrayList; import java.util.List; public class AgentClientInfo { private String aid; private String name; private String common; /** agent可管理服务器列表 */ private List<OSServerInfo> computerList = new ArrayList<OSServerInfo>(); public String getAid() { return aid; } public void setAid(String aid) { this.aid = aid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCommon() { return common; } public void setCommon(String common) { this.common = common; } public List<OSServerInfo> getComputerList() { return computerList; } public void setComputerList(List<OSServerInfo> computerList) { this.computerList = computerList; } }
package com.lenovohit.ssm.treat.model; /** * 就诊卡 * @author xiaweiyi * */ public class MedicalCard { private String id; private String cardNo; private String createDate; private String holderId; private String holderName; private String holderIdNo; private String balance; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getHolderId() { return holderId; } public void setHolderId(String holderId) { this.holderId = holderId; } public String getHolderName() { return holderName; } public void setHolderName(String holderName) { this.holderName = holderName; } public String getHolderIdNo() { return holderIdNo; } public void setHolderIdNo(String holderIdNo) { this.holderIdNo = holderIdNo; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } }
package cn.hellohao.utils; import org.omg.CORBA.Environment; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; /** * @author Hellohao * @version 1.0 * @date 2019/11/29 14:32 */ @Configuration public class FirstRun implements InitializingBean { @Value("${spring.datasource.username}") private String jdbcusername; @Value("${spring.datasource.password}") private String jdbcpass; @Value("${spring.datasource.url}") private String jdbcurl; @Override public void afterPropertiesSet() throws Exception { RunSqlScript.USERNAME = jdbcusername; RunSqlScript.PASSWORD = jdbcpass; RunSqlScript.DBURL = jdbcurl; Print.Normal("正在校验数据库参数..."); Integer ret1 = RunSqlScript.RunSelectCount(sql1); if(ret1==0){ Print.Normal("In execution..."); RunSqlScript.RunInsert(sql2); }else{ if(ret1>0){ Print.Normal("Good! No action required!"); }else{ Print.Normal("Mysql 报了一个错"); } } } //创建blacklist 2019-11-29 private String sql1 = "select count(*) from information_schema.columns where table_name = 'uploadconfig' and column_name = 'blacklist'"; private String sql2 = "alter table uploadconfig add blacklist varchar(500);"; }
package test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class TreeDepth { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in) ; int n = scan.nextInt(); int root =0; HashMap<Integer,HashMap<Integer,Boolean>> graph = new HashMap<Integer,HashMap<Integer,Boolean>>(); for(int i =0;i<n-1;i++) { int fa = scan.nextInt(); if(i==0) { root=fa; } int child = scan.nextInt(); HashMap<Integer,Boolean> node; if(graph.containsKey(fa)) { node = graph.get(fa); }else { node = new HashMap<Integer,Boolean>(); } node.put(child, true); graph.put(fa, node); } List<Integer> toProcess = new ArrayList<Integer>(); List<Integer> layerNode = new ArrayList<Integer>(); int depth=0; toProcess.add(root); while(toProcess.size()>0) { int node = toProcess.remove(0); HashMap<Integer,Boolean> ajdantNodes = graph.get(node); if(ajdantNodes!=null) { for(Integer adjNode:ajdantNodes.keySet()) { layerNode.add(adjNode); } } if(toProcess.size()==0) { toProcess=layerNode; depth++; layerNode = new ArrayList<Integer>(); } } System.out.println(depth); } }
package me.leaver.bloger.app.mvp.model.fundamental; import java.util.Arrays; /** * Created by zhiyuan.lzy on 2016/3/13. */ public class Post { private int id; private String type; private String slug; private String url; private String status; private String title; private String title_plain; private String content; private String excerpt; private String date; private String modified; private Category[] categories; private Tag[] tags; private Author author; private Comment[] comments; private Attachment[] attachments; private int comment_count; private String comment_status; private String thumbnail; //TODO // private Object custom_fields; public Post() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getExcerpt() { return excerpt; } public void setExcerpt(String excerpt) { this.excerpt = excerpt; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getModified() { return modified; } public void setModified(String modified) { this.modified = modified; } public Category[] getCategories() { return categories; } public void setCategories(Category[] categories) { this.categories = categories; } public Tag[] getTags() { return tags; } public void setTags(Tag[] tags) { this.tags = tags; } public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Comment[] getComments() { return comments; } public void setComments(Comment[] comments) { this.comments = comments; } public Attachment[] getAttachments() { return attachments; } public void setAttachments(Attachment[] attachments) { this.attachments = attachments; } public int getComment_count() { return comment_count; } public void setComment_count(int comment_count) { this.comment_count = comment_count; } public String getComment_status() { return comment_status; } public void setComment_status(String comment_status) { this.comment_status = comment_status; } public String getThumbnail() { return thumbnail; } public void setThumbnail(String thumbnail) { this.thumbnail = thumbnail; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTitle_plain() { return title_plain; } public void setTitle_plain(String title_plain) { this.title_plain = title_plain; } @Override public String toString() { return "Post{" + "id=" + id + ", type='" + type + '\'' + ", slug='" + slug + '\'' + ", url='" + url + '\'' + ", status='" + status + '\'' + ", title='" + title + '\'' + ", title_plain='" + title_plain + '\'' + ", content='" + content + '\'' + ", excerpt='" + excerpt + '\'' + ", date='" + date + '\'' + ", modified='" + modified + '\'' + ", categories=" + Arrays.toString(categories) + ", tags=" + Arrays.toString(tags) + ", author=" + author + ", comments=" + Arrays.toString(comments) + ", attachments=" + Arrays.toString(attachments) + ", comment_count=" + comment_count + ", comment_status='" + comment_status + '\'' + ", thumbnail='" + thumbnail + '\'' + '}'; } }
package xhu.wncg.firesystem.modules.controller.vo; import xhu.wncg.firesystem.modules.pojo.PoliceStation; /** * 派出所表 * * @author zhaobo * @email 15528330581@163.com * @version 2017-11-02 15:58:16 */ public class PoliceStationVO extends PoliceStation { }
package com.driva.drivaapi.model.product; public enum ProductCategory { KURS(1), LEKCJA(2); private int index; ProductCategory(int index) { this.index = index; } public int getIndex() { return index; } }
package com.zc.pivas.workReport.controller; import com.zc.base.common.controller.SdBaseController; import com.zc.base.common.util.DateUtil; import com.zc.pivas.workReport.bean.WorkBean; import com.zc.pivas.workReport.service.WorkReportService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller @RequestMapping(value = "/workReport") public class WorkReportController extends SdBaseController { @Resource private WorkReportService workReportService; /** * * 班次统计 * @param model * @param request * @return * @throws Exception * */ @RequestMapping(value = "/initCount") public String initCount(Model model, HttpServletRequest request) throws Exception { String todayDate = DateUtil.getCurrentDay8Str(); model.addAttribute("todayDate",todayDate); List<WorkBean> workList = workReportService.getWorkList(); model.addAttribute("workList",workList); return "/pivas/workReport"; } }
package com.example.workreview_java; import com.example.workreview_java.model.EventModel; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import io.reactivex.Single; import retrofit2.Call; import retrofit2.Callback; import okhttp3.OkHttpClient; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; public class RetrofitHelper { private final static String API_URL = "http://tks3589.ddns.net:1021/akbtp/api/"; private final static OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS).build(); private final static Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(httpClient) .build(); private final static Api api = retrofit.create(Api.class); public static void getEventData(Callback<ArrayList<EventModel>> callback){ api.getEvent().enqueue(new Callback<ArrayList<EventModel>>() { @Override public void onResponse(Call<ArrayList<EventModel>> call, Response<ArrayList<EventModel>> response) { if(response.isSuccessful()){ callback.onResponse(call, response); } } @Override public void onFailure(Call<ArrayList<EventModel>> call, Throwable t) { callback.onFailure(call, t); } }); } public static Single<String> getMembers(){ return api.getMembers(); } public static Single<String> getProduct(String ename){ return api.getProduct(ename); } }
package com.fsj.action; import java.util.HashMap; import java.util.Map; import com.fsj.entity.Managergroup; import com.fsj.entity.Pager; import com.fsj.service.ManagergroupDAO; import com.fsj.service.impl.ManagergroupDAOImpl; //用户管理组Action动作类 public class ManagergroupAction extends SuperAction { private static final long serialVersionUID = 1L; // 保存总页数 public Pager<Managergroup> getPageCount(String hql, Map<String, Object> map) { // 定义业务逻辑类的对象 Pager<Managergroup> pager = new Pager<Managergroup>(); ManagergroupDAO managergroupdao = new ManagergroupDAOImpl(); pager.setRowCount(managergroupdao.queryAll(hql, map));// 总记录数 // 将传出的集合数据list放入session中,首先判断list数据 if (pager.getRowCount() > 0) { // 在session中保存 int t1 = pager.getRowCount() % pager.getPageSize(); int t2 = pager.getRowCount() / pager.getPageSize(); pager.setPageCount(t1 == 0 ? t2 : t2 + 1); } else { pager.setPageCount(0); } return pager; } // 获取当前页数 public int getPageNumber() { String number = request.getParameter("pageNumber"); if (number == null) { return 1; } else { int pageNumber = Integer.parseInt(number); // 获得传过来的pageNumber值 return pageNumber; } } // 实现查询所有用户管理组的操作(可选查询条件:名称) public String query() { StringBuffer hql = new StringBuffer(); hql.append("select count(mgid) from Managergroup as managergroup where 1=1 "); Map<String, Object> map = new HashMap<String, Object>(); if (request.getParameter("name") != null && request.getParameter("name").length() > 0) { map.put("name", "%" + request.getParameter("name") + "%"); hql.append("and managergroup.name like :name "); } String queryHql = hql.substring(19); // 定义业务逻辑类的对象 Pager<Managergroup> pager = getPageCount(hql.toString(), map); ManagergroupDAO managergroupdao = new ManagergroupDAOImpl(); pager.setPageNo(getPageNumber()); pager.setResult(managergroupdao.querypage(pager.getPageNo(), pager.getPageSize(), queryHql, map)); // 将传出的集合数据list放入session中,首先判断list数据 if (pager.getResult() != null && pager.getResult().size() > 0) { // 在session中保存list信息到list中,将来可以调用 session.setAttribute("pager", pager); } return "query"; } // 添加用户管理组操作 public String add() throws Exception { Managergroup managergroup = new Managergroup(); ManagergroupDAO managergroupdao = new ManagergroupDAOImpl(); managergroupdao.addManagergroup(setAll(managergroup)); return "operationsuccess"; } // 更新用户管理组操作 public String save() throws Exception { Managergroup managergroup = new Managergroup(); ManagergroupDAO managergroupdao = new ManagergroupDAOImpl(); managergroupdao.updateManagergroup(setAll(managergroup)); return "operationsuccess"; } // 删除用户管理组操作 public String delete() { // 定义用户管理组业务逻辑类的对象 ManagergroupDAO managergroupdao = new ManagergroupDAOImpl(); int mgid = Integer.parseInt(request.getParameter("mgid")); // 获得传过来的要删除用户管理组的id值 managergroupdao.deleteManagergroup(mgid); return "operationsuccess"; } // 持久化类 public Managergroup setAll(Managergroup managergroup) throws Exception { return managergroup; } }
//////////////////////////////////////////////////////////////////////////////////// // MIT License // // // // Copyright (c) 2020 Utkarsh Priyam // // // // 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 OR COPYRIGHT HOLDERS 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 hangouts_history_reader.elements; import json.elements.JSONArray; import json.elements.JSONObject; import json.elements.JSONValue; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; import static hangouts_history_reader.HangoutsUtil.getStringValue; import static hangouts_history_reader.HangoutsUtil.getValue; public class HangoutsMessage extends HangoutsEvent { public final EventType type() { return EventType.REGULAR_CHAT_MESSAGE; } private final List<String> MESSAGES; public HangoutsMessage(JSONObject message) { super(message); // Get messages MESSAGES = new LinkedList<>(); JSONArray arr = (JSONArray) getValue(message.findElements("chat_message.message_content.segment"), JSONValue.ValueType.ARRAY); if (arr != null) { Iterator<JSONValue> it = arr.iterator(); while (it.hasNext()) { JSONValue obj = it.next(); switch (getStringValue(obj.findElements("type"))) { case "TEXT": case "LINK": String text = getStringValue(obj.findElements("text")); if (text != null) MESSAGES.add(text); break; case "LINE_BREAK": MESSAGES.add(null); break; default: break; } } } MESSAGES.add(null); for (JSONValue obj : message.findElements("chat_message.message_content.attachment[*].embed_item")) { String type = getStringValue(obj.findElements("type[*]")), path; switch (type) { case "PLUS_PHOTO": path = "plus_photo"; break; default: path = ""; break; } String url = getStringValue(obj.findElements(path + ".original_content_url")); if (url == null) url = getStringValue(obj.findElements(path + ".url")); if (url == null) continue; MESSAGES.add("UPLOADED " + url); } } public String toString(HangoutsChat chat) { StringBuilder builder = toStringHeaderHelper(chat); MESSAGES.add(null); Iterator<String> it = MESSAGES.iterator(); while (it.hasNext()) { StringBuilder temp = new StringBuilder(); String next = it.next(); while (next != null) { temp.append(next); next = it.next(); } if (temp.length() == 0) continue; builder.append(toStringMessageHelper(new StringTokenizer(temp.toString()))); } return builder.toString(); } }
/** * Core package of the JMS support. * Provides a JmsTemplate class and various callback interfaces. */ @NonNullApi @NonNullFields package org.springframework.jms.core; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
/** * Copyright 2017 伊永飞 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yea.shiro.cache.redis; import java.io.Serializable; import java.util.Collection; import java.util.Set; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import com.yea.cache.jedis.cache.RedisCache; public class ShiroCache<K extends Serializable, V> implements Cache<K, V> { private RedisCache<K, V> cache; public void setCache(RedisCache<K, V> cache) { this.cache = cache; } @Override public V get(K key) throws CacheException { try { if (key == null) { return null; } else { return cache.get(key); } } catch (Throwable t) { throw new CacheException(t); } } @Override public V put(K key, V value) throws CacheException { try { return cache.put(key, value); } catch (Throwable t) { throw new CacheException(t); } } @Override public V remove(K key) throws CacheException { try { return cache.remove(key); } catch (Throwable t) { throw new CacheException(t); } } @Override public void clear() throws CacheException { try { cache.clear(); } catch (Throwable t) { throw new CacheException(t); } } @Override public int size() { try { return cache.size(); } catch (Throwable t) { throw new CacheException(t); } } @Override public Set<K> keys() { try { return cache.keySet(); } catch (Throwable t) { throw new CacheException(t); } } @Override public Collection<V> values() { try { return cache.values(); } catch (Throwable t) { throw new CacheException(t); } } }
/* * 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. */ import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author dangh */ @WebServlet(urlPatterns = {"/GiaoVien"}) public class GiaoVien extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * @throws java.lang.ClassNotFoundException * @throws java.sql.SQLException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { HttpSession session = request.getSession(); String giaoVien = (String) session.getAttribute("Username"); String queryString = ""; queryString = request.getQueryString(); if(queryString == null) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<link rel=\"stylesheet\" href=\"css/style_1.css\">"); //out.println("<link href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css\" rel=\"stylesheet\" id=\"bootstrap-css\">"); out.println("<link href=\"css/bootstrap.min.css\" rel=\"stylesheet\" id=\"bootstrap-css\">"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println("<title>Giáo Viên: " + giaoVien + " </title>"); out.println("</head>"); out.println("<body>"); out.println("<nav class='navbar navbar-inverse navbar-fixed-top'>"); out.println("<div class='container-fluid'>"); out.println("<div class='navbar-header'>"); out.println("<a class='navbar-brand' href='#'>" + giaoVien +" </a>"); out.println("</div>"); out.println("<ul class='nav navbar-nav'>"); out.println("<li class='active'><a href='#'>Home</a></li>"); out.println("<li><a href='DangXuat'>Đăng Xuất</a></li>"); out.println("</ul>"); out.println("</div>"); out.println("</nav>"); out.println("<br></br>"); out.println("<br></br>"); out.println("<div class=text-center>"); out.println("<h3>Giáo Viên: " + giaoVien + "</h3>"); out.println("<h4>Danh sách các sinh viên đã tham gia trả lời:</h4>"); out.println("</div>"); out.println("<br></br>"); Connection conn = Connect(); //Show List Statement st = conn.createStatement(); String sql = "SELECT DISTINCT Username FROM TraLoi"; ResultSet rs = st.executeQuery(sql); while(rs.next()) { String userName = rs.getString("Username"); out.println("<div class='alert alert-info col-md-4 col-md-offset-4' role='alert'>"); out.println("<div class=text-center>"); out.println("<strong><a href='GiaoVien?show=" + userName + "&cauhoi=1'>" + userName + "</a></strong>"); out.println("</div>"); out.println("</div>"); out.println("<br></br>"); out.println("<br></br>"); } out.println("</body>"); out.println("</html>"); } else { String user = request.getParameter("show"); String sttCauHoi = request.getParameter("cauhoi"); Connection conn = Connect(); Statement st = conn.createStatement(); String cauHoi = "SELECT * FROM CauHoi WHERE STTCauHoi = " + sttCauHoi; String traLoi = "SELECT CauTraLoi FROM TraLoi WHERE STTCauHoi = " + sttCauHoi + " AND Username = '" + user + "'"; ResultSet ch = st.executeQuery(cauHoi); String cauHoiHienThi = ""; String cauTraLoiDung = ""; String cauTraLoiCuaUser = ""; if(ch.next()) { cauHoiHienThi = ch.getString("NoiDungCauHoi"); cauTraLoiDung = ch.getString("CauTraLoiChinhXac"); cauTraLoiCuaUser = ""; ResultSet trl = st.executeQuery(traLoi); if(trl.next()) cauTraLoiCuaUser = trl.getString("CauTraLoi"); } int back = Integer.parseInt(sttCauHoi) - 1; int next = Integer.parseInt(sttCauHoi) + 1; out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<link rel=\"stylesheet\" href=\"css/style_1.css\">"); //out.println("<link href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css\" rel=\"stylesheet\" id=\"bootstrap-css\">"); out.println("<link href=\"css/bootstrap.min.css\" rel=\"stylesheet\" id=\"bootstrap-css\">"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println("<title>Giáo Viên: " + giaoVien + " </title>"); out.println("</head>"); out.println("<body>"); out.println("<nav class='navbar navbar-inverse navbar-fixed-top'>"); out.println("<div class='container-fluid'>"); out.println("<div class='navbar-header'>"); out.println("<a class='navbar-brand' href='#'>" + giaoVien + " </a>"); out.println("</div>"); out.println("<ul class='nav navbar-nav'>"); out.println("<li class='active'><a href='#'>Home</a></li>"); out.println("<li><a href='DangXuat'>Đăng Xuất</a></li>"); out.println("</ul>"); out.println("</div>"); out.println("</nav>"); out.println("<div class='form'>"); out.println("<div class='form-triangle'></div>"); out.println("<h2 class='form-header'> Giáo Viên: " + giaoVien + "&nbsp&nbsp&nbsp&nbsp&nbspHọc Sinh: " + user + "</h2>"); out.println("<form class='form-container' action='GiaoVien' method='get'>"); out.println("<p><textarea rows=5 cols=90 readonly='readonly'>" + cauHoiHienThi + "</textarea></p>"); out.println("<p><textarea rows=7 cols=90 readonly='readonly'>" + cauTraLoiCuaUser +"</textarea></p>"); out.println("<p><textarea rows=7 cols=90 readonly='readonly'>" + cauTraLoiDung +"</textarea></p>"); out.println("<p hidden><textarea name=show rows=0 cols=0 readonly='readonly'>" + user +"</textarea></p>"); out.println("<p><button name='cauhoi' value='"+back+"' type='submit' onclick='{document.frm.hdnbt.value=this.value;document.frm.submit();}'>Back</button> <button name='cauhoi' value='"+next+"' type='submit' onclick='{document.frm.hdnbt.value=this.value;document.frm.submit();}'>Next</button></p>"); out.println("</form>"); out.println("</div>"); out.println("</body>"); out.println("</html>"); } } } public Connection Connect() throws ClassNotFoundException, SQLException { String driver = "com.mysql.jdbc.Driver"; Class.forName(driver); String url = "jdbc:mysql://localhost:3306/"; String dbName = "PTUDCSDL2";//ten csdl ma ban can ket noi Properties info = new Properties(); info.setProperty("characterEncoding", "utf8"); info.setProperty("user", "root"); info.setProperty("password", ""); Connection conn = DriverManager.getConnection(url + dbName, info); return conn; } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (ClassNotFoundException ex) { Logger.getLogger(GiaoVien.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(GiaoVien.class.getName()).log(Level.SEVERE, null, ex); } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { processRequest(request, response); } catch (ClassNotFoundException ex) { Logger.getLogger(GiaoVien.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(GiaoVien.class.getName()).log(Level.SEVERE, null, ex); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package com.softserveinc.uschedule.security; import com.softserveinc.uschedule.entity.ApplicationRole; import com.softserveinc.uschedule.entity.UserToGroup; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Set; public class CustomUserDetails implements UserDetails { private String username; private String password; private Boolean locked; private ApplicationRole applicationRole; private Set<UserToGroup> userToGroups; private Set<GrantedAuthority> authorities; public void setAuthorities(Set<GrantedAuthority> authorities) { this.authorities = authorities; } public Set<UserToGroup> getUserToGroups() { return userToGroups; } public void setUserToGroups(Set<UserToGroup> userToGroups) { this.userToGroups = userToGroups; } public ApplicationRole getApplicationRole() { return applicationRole; } public void setApplicationRole(ApplicationRole applicationRole) { this.applicationRole = applicationRole; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return !locked; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
package com.ross.ui.shops; import com.ross.domain.shops.ShopDetailViewModel; import com.ross.game.ItemId; import javax.swing.*; import java.awt.*; public class ShopDetailPanel extends JPanel { public ShopDetailPanel(ShopDetailViewModel shopDetails, ShopTabContentPanel parent) { JButton button = new JButton("Leave"); button.addActionListener(e -> { parent.switchToOverview(); }); add(button); setLayout(new GridLayout(0,1,3,3)); for(ItemId item : shopDetails.getItemsForSale()){ add(new ShopItemPanel(item, shopDetails.getPrices().get(item), parent.getShopController())); } } }
package com.bnade.wow.utils; /** * String工具类 * Created by liufeng0103@163.com on 2017/7/11. */ public class StringUtils { private StringUtils() {} /** * 判断字符串不会空 * @param s String * @return 是否为空 */ public static boolean isNotEmpty(String s) { return s != null && s.length() != 0; } }
package de.ilouminaten.plugin; public enum Games { VIERGEWINNT(); // CHESS(); // TICTACTOE(), // BILLARD(); <- Just kidding :D }
package checkers.server.rules; import checkers.core.Checker; import checkers.core.Coordinates; import checkers.server.game.Game; public interface RulesManager { int checkMove(Game game, Coordinates currLocation, Coordinates destination, Checker checker); }
package com.springMVCHibernate.service; import java.util.List; import com.springMVCHibernate.form.Country; public interface CountryService { public void addCountry(Country country); public List<Country> listCountry(); public void removeCountry(Integer countryid); }