hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
fa98b31df7aa65fc1829f5278b2906cfd2a508d7 | 1,509 | package nl.jaapcoomans.boardgame.domain.command;
import java.util.List;
import java.util.UUID;
import nl.jaapcoomans.boardgame.domain.BoardGame;
import nl.jaapcoomans.boardgame.domain.GameMechanic;
public class CreateBoardGameCommand {
private String title;
private String publisher;
private String author;
private int minPlayers;
private int maxPlayers;
private List<GameMechanic> gameMechanics;
private Integer boardGameGeekId;
public CreateBoardGameCommand(final String title, final String publisher, final String author, final int minPlayers, final int maxPlayers,
final List<GameMechanic> gameMechanics, final Integer boardGameGeekId) {
this.title = title;
this.publisher = publisher;
this.author = author;
this.minPlayers = minPlayers;
this.maxPlayers = maxPlayers;
this.gameMechanics = gameMechanics;
this.boardGameGeekId = boardGameGeekId;
}
public String getTitle() {
return title;
}
public String getPublisher() {
return publisher;
}
public String getAuthor() {
return author;
}
public int getMinPlayers() {
return minPlayers;
}
public int getMaxPlayers() {
return maxPlayers;
}
public List<GameMechanic> getGameMechanics() {
return gameMechanics;
}
public Integer getBoardGameGeekId() {
return boardGameGeekId;
}
public BoardGame execute() {
return new BoardGame(
UUID.randomUUID(),
this.title,
this.author,
this.publisher,
this.minPlayers,
this.maxPlayers,
this.gameMechanics,
this.boardGameGeekId);
}
}
| 21.869565 | 139 | 0.758118 |
e43e044f11e6cad912b4c550bd94ac33940bcca5 | 2,346 | package com.blithe.cms.controller.system;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.blithe.cms.common.exception.R;
import com.blithe.cms.common.tools.StringUtil;
import com.blithe.cms.pojo.system.Loginfo;
import com.blithe.cms.service.system.LoginfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @ClassName LogIngoController
* @Description: 登陆日志信息controller
* @Author: 夏小颜
* @Date: 12:29
* @Version: 1.0
**/
@RestController
@RequestMapping("/log")
public class LogInfoController {
@Autowired
private LoginfoService loginfoService;
/**
* 查询 含导出功能
* @return
*/
@GetMapping("/list")
public R queryLogList(Loginfo loginfo) {
EntityWrapper wrapper = new EntityWrapper<>();
// 条件构造b
wrapper.like(StringUtils.isNotBlank(loginfo.getLoginname()),"loginname",loginfo.getLoginname());
wrapper.like(StringUtils.isNotBlank(loginfo.getLoginip()),"loginip",loginfo.getLoginip());
wrapper.ge(loginfo.getStartTime()!=null,"logintime",loginfo.getStartTime());
wrapper.le(loginfo.getEndTime()!=null,"logintime",loginfo.getEndTime());
wrapper.orderBy("logintime",false);
if(!StringUtil.isNull(loginfo.getPage()) && !StringUtil.isNull(loginfo.getLimit())){
Page page = new Page(loginfo.getPage(),loginfo.getLimit());
this.loginfoService.selectPage(page, wrapper);
return R.ok().put("count",page.getTotal()).put("data",page.getRecords());
}else {
List list = this.loginfoService.selectList(wrapper);
return R.ok().put("data",list);
}
}
@PostMapping(value = "/deleteBatch")
public R deleteBatch(@RequestBody List<Map<String,Object>> params){
try {
if(CollectionUtils.isNotEmpty(params)){
for (Map<String, Object> param : params) {
this.loginfoService.deleteByMap(param);
}
}
}catch (Exception e){
return R.error(e.getMessage());
}
return R.ok();
}
} | 34 | 104 | 0.664962 |
7c2ce81455476b0062a302d2caed58d7cfae897d | 2,260 | package com.fongmi.android.tv.source;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import com.fongmi.android.tv.App;
import com.fongmi.android.tv.impl.AsyncCallback;
import com.forcetech.service.P5PService;
import com.google.android.exoplayer2.PlaybackException;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
public class Force {
private final Handler handler;
private AsyncCallback callback;
private static class Loader {
static volatile Force INSTANCE = new Force();
}
public static Force get() {
return Loader.INSTANCE;
}
public Force() {
this.handler = new Handler(Looper.getMainLooper());
}
public void init() {
App.get().bindService(new Intent(App.get(), P5PService.class), mConn, Context.BIND_AUTO_CREATE);
}
public void start(AsyncCallback callback, String source) {
this.callback = callback;
this.onPrepare(source);
}
public void destroy() {
try {
App.get().unbindService(mConn);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onPrepare(String source) {
Uri uri = Uri.parse(source);
String cmd = "http://127.0.0.1:6001/cmd.xml?cmd=switch_chan&server=" + uri.getHost() + ":" + uri.getPort() + "&id=";
String tmp = uri.getLastPathSegment();
int index = tmp.lastIndexOf(".");
if (index == -1) cmd = cmd + tmp;
else cmd = cmd + tmp.substring(0, index);
connect(cmd + "&" + uri.getQuery());
String result = "http://127.0.0.1:6001" + uri.getPath();
handler.post(() -> callback.onResponse(result));
}
private void connect(String url) {
try {
new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute();
} catch (IOException e) {
if (callback == null) return;
handler.post(() -> callback.onError(new PlaybackException(null, null, 0)));
}
}
private final ServiceConnection mConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
| 25.681818 | 118 | 0.715044 |
836d25e637086fbb31f8d42093355ff1b7652b8a | 127,800 | // uniCenta oPOS - Touch Friendly Point Of Sale
// Copyright (c) 2009-2015 uniCenta & previous Openbravo POS works
// http://www.unicenta.com
//
// This file is part of uniCenta oPOS
//
// uniCenta oPOS 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.
//
// uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.config;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.pos.forms.AppConfig;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.pos.util.ReportUtils;
import com.openbravo.pos.util.StringParser;
import java.awt.CardLayout;
import java.awt.Component;
import java.util.Map;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.SubstanceSkin;
import org.pushingpixels.substance.api.skin.SkinInfo;
// JG 16 May 2013 deprecated for pushingpixels
// import org.jvnet.substance.SubstanceLookAndFeel;
// import org.jvnet.substance.api.SubstanceSkin;
// import org.jvnet.substance.skin.SkinInfo;
/**
*
* @author JG uniCenta
*/
public class JPanelConfigPeripheral extends javax.swing.JPanel implements PanelConfig {
private DirtyManager dirty = new DirtyManager();
private ParametersConfig printer1printerparams;
private ParametersConfig printer2printerparams;
private ParametersConfig printer3printerparams;
private ParametersConfig printer4printerparams;
private ParametersConfig printer5printerparams;
private ParametersConfig printer6printerparams;
/** Creates new form JPanelConfigGeneral */
public JPanelConfigPeripheral() {
initComponents();
String[] printernames = ReportUtils.getPrintNames();
jcboMachineDisplay.addActionListener(dirty);
jcboConnDisplay.addActionListener(dirty);
jcboSerialDisplay.addActionListener(dirty);
m_jtxtJPOSName.getDocument().addDocumentListener(dirty);
jcboMachinePrinter.addActionListener(dirty);
jcboConnPrinter.addActionListener(dirty);
jcboSerialPrinter.addActionListener(dirty);
m_jtxtJPOSPrinter.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer.getDocument().addDocumentListener(dirty);
printer1printerparams = new ParametersPrinter(printernames);
printer1printerparams.addDirtyManager(dirty);
m_jPrinterParams1.add(printer1printerparams.getComponent(), "printer");
jcboMachinePrinter2.addActionListener(dirty);
jcboConnPrinter2.addActionListener(dirty);
jcboSerialPrinter2.addActionListener(dirty);
m_jtxtJPOSPrinter2.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer2.getDocument().addDocumentListener(dirty);
printer2printerparams = new ParametersPrinter(printernames);
printer2printerparams.addDirtyManager(dirty);
m_jPrinterParams2.add(printer2printerparams.getComponent(), "printer");
jcboMachinePrinter3.addActionListener(dirty);
jcboConnPrinter3.addActionListener(dirty);
jcboSerialPrinter3.addActionListener(dirty);
m_jtxtJPOSPrinter3.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer3.getDocument().addDocumentListener(dirty);
printer3printerparams = new ParametersPrinter(printernames);
printer3printerparams.addDirtyManager(dirty);
m_jPrinterParams3.add(printer3printerparams.getComponent(), "printer");
// New printers add JDL 10.11.12
jcboMachinePrinter4.addActionListener(dirty);
jcboConnPrinter4.addActionListener(dirty);
jcboSerialPrinter4.addActionListener(dirty);
m_jtxtJPOSPrinter4.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer4.getDocument().addDocumentListener(dirty);
printer4printerparams = new ParametersPrinter(printernames);
printer4printerparams.addDirtyManager(dirty);
m_jPrinterParams4.add(printer4printerparams.getComponent(), "printer");
jcboMachinePrinter5.addActionListener(dirty);
jcboConnPrinter5.addActionListener(dirty);
jcboSerialPrinter5.addActionListener(dirty);
m_jtxtJPOSPrinter5.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer5.getDocument().addDocumentListener(dirty);
printer5printerparams = new ParametersPrinter(printernames);
printer5printerparams.addDirtyManager(dirty);
m_jPrinterParams5.add(printer5printerparams.getComponent(), "printer");
jcboMachinePrinter6.addActionListener(dirty);
jcboConnPrinter6.addActionListener(dirty);
jcboSerialPrinter6.addActionListener(dirty);
m_jtxtJPOSPrinter6.getDocument().addDocumentListener(dirty);
m_jtxtJPOSDrawer6.getDocument().addDocumentListener(dirty);
printer6printerparams = new ParametersPrinter(printernames);
printer6printerparams.addDirtyManager(dirty);
m_jPrinterParams6.add(printer6printerparams.getComponent(), "printer");
//
jcboMachineScale.addActionListener(dirty);
jcboSerialScale.addActionListener(dirty);
jcboMachineScanner.addActionListener(dirty);
jcboSerialScanner.addActionListener(dirty);
cboPrinters.addActionListener(dirty);
// Printer 1
jcboMachinePrinter.addItem("Not defined");
jcboMachinePrinter.addItem("screen");
jcboMachinePrinter.addItem("printer");
jcboMachinePrinter.addItem("epson");
jcboMachinePrinter.addItem("tmu220");
jcboMachinePrinter.addItem("star");
jcboMachinePrinter.addItem("ODP1000");
jcboMachinePrinter.addItem("ithaca");
jcboMachinePrinter.addItem("surepos");
jcboMachinePrinter.addItem("plain");
jcboMachinePrinter.addItem("javapos");
jcboConnPrinter.addItem("serial");
jcboConnPrinter.addItem("file");
jcboSerialPrinter.addItem("COM1");
jcboSerialPrinter.addItem("COM2");
jcboSerialPrinter.addItem("COM3");
jcboSerialPrinter.addItem("COM4");
jcboSerialPrinter.addItem("COM5");
jcboSerialPrinter.addItem("COM6");
jcboSerialPrinter.addItem("COM7");
jcboSerialPrinter.addItem("COM8");
jcboSerialPrinter.addItem("LPT1");
jcboSerialPrinter.addItem("/dev/ttyS0");
jcboSerialPrinter.addItem("/dev/ttyS1");
jcboSerialPrinter.addItem("/dev/ttyS2");
jcboSerialPrinter.addItem("/dev/ttyS3");
jcboSerialPrinter.addItem("/dev/ttyS4");
jcboSerialPrinter.addItem("/dev/ttyS5");
// Printer 2
jcboMachinePrinter2.addItem("Not defined");
jcboMachinePrinter2.addItem("screen");
jcboMachinePrinter2.addItem("printer");
jcboMachinePrinter2.addItem("epson");
jcboMachinePrinter2.addItem("tmu220");
jcboMachinePrinter2.addItem("star");
jcboMachinePrinter2.addItem("ODP1000");
jcboMachinePrinter2.addItem("ithaca");
jcboMachinePrinter2.addItem("surepos");
jcboMachinePrinter2.addItem("plain");
jcboMachinePrinter2.addItem("javapos");
jcboConnPrinter2.addItem("serial");
jcboConnPrinter2.addItem("file");
jcboSerialPrinter2.addItem("COM1");
jcboSerialPrinter2.addItem("COM2");
jcboSerialPrinter2.addItem("COM3");
jcboSerialPrinter2.addItem("COM4");
jcboSerialPrinter2.addItem("COM5");
jcboSerialPrinter2.addItem("COM6");
jcboSerialPrinter2.addItem("COM7");
jcboSerialPrinter2.addItem("COM8");
jcboSerialPrinter2.addItem("LPT1");
jcboSerialPrinter2.addItem("/dev/ttyS0");
jcboSerialPrinter2.addItem("/dev/ttyS1");
jcboSerialPrinter2.addItem("/dev/ttyS2");
jcboSerialPrinter2.addItem("/dev/ttyS3");
jcboSerialPrinter2.addItem("/dev/ttyS4");
jcboSerialPrinter2.addItem("/dev/ttyS5");
// Printer 3
jcboMachinePrinter3.addItem("Not defined");
jcboMachinePrinter3.addItem("screen");
jcboMachinePrinter3.addItem("printer");
jcboMachinePrinter3.addItem("epson");
jcboMachinePrinter3.addItem("tmu220");
jcboMachinePrinter3.addItem("star");
jcboMachinePrinter3.addItem("ODP1000");
jcboMachinePrinter3.addItem("ithaca");
jcboMachinePrinter3.addItem("surepos");
jcboMachinePrinter3.addItem("plain");
jcboMachinePrinter3.addItem("javapos");
jcboConnPrinter3.addItem("serial");
jcboConnPrinter3.addItem("file");
jcboSerialPrinter3.addItem("COM1");
jcboSerialPrinter3.addItem("COM2");
jcboSerialPrinter3.addItem("COM3");
jcboSerialPrinter3.addItem("COM4");
jcboSerialPrinter3.addItem("COM5");
jcboSerialPrinter3.addItem("COM6");
jcboSerialPrinter3.addItem("COM7");
jcboSerialPrinter3.addItem("COM8");
jcboSerialPrinter3.addItem("LPT1");
jcboSerialPrinter3.addItem("/dev/ttyS0");
jcboSerialPrinter3.addItem("/dev/ttyS1");
jcboSerialPrinter3.addItem("/dev/ttyS2");
jcboSerialPrinter3.addItem("/dev/ttyS3");
jcboSerialPrinter3.addItem("/dev/ttyS4");
jcboSerialPrinter3.addItem("/dev/ttyS5");
// New printer add JDL 10.11.12
// Printer 4
jcboMachinePrinter4.addItem("Not defined");
jcboMachinePrinter4.addItem("screen");
jcboMachinePrinter4.addItem("printer");
jcboMachinePrinter4.addItem("epson");
jcboMachinePrinter4.addItem("tmu220");
jcboMachinePrinter4.addItem("star");
jcboMachinePrinter4.addItem("ODP1000");
jcboMachinePrinter4.addItem("ithaca");
jcboMachinePrinter4.addItem("surepos");
jcboMachinePrinter4.addItem("plain");
jcboMachinePrinter4.addItem("javapos");
jcboConnPrinter4.addItem("serial");
jcboConnPrinter4.addItem("file");
jcboSerialPrinter4.addItem("COM1");
jcboSerialPrinter4.addItem("COM2");
jcboSerialPrinter4.addItem("COM3");
jcboSerialPrinter4.addItem("COM4");
jcboSerialPrinter4.addItem("COM5");
jcboSerialPrinter4.addItem("COM6");
jcboSerialPrinter4.addItem("COM7");
jcboSerialPrinter4.addItem("COM8");
jcboSerialPrinter4.addItem("LPT1");
jcboSerialPrinter4.addItem("/dev/ttyS0");
jcboSerialPrinter4.addItem("/dev/ttyS1");
jcboSerialPrinter4.addItem("/dev/ttyS2");
jcboSerialPrinter4.addItem("/dev/ttyS3");
jcboSerialPrinter4.addItem("/dev/ttyS4");
jcboSerialPrinter4.addItem("/dev/ttyS5");
// Printer 5
jcboMachinePrinter5.addItem("Not defined");
jcboMachinePrinter5.addItem("screen");
jcboMachinePrinter5.addItem("printer");
jcboMachinePrinter5.addItem("epson");
jcboMachinePrinter5.addItem("tmu220");
jcboMachinePrinter5.addItem("star");
jcboMachinePrinter5.addItem("ODP1000");
jcboMachinePrinter5.addItem("ithaca");
jcboMachinePrinter5.addItem("surepos");
jcboMachinePrinter5.addItem("plain");
jcboMachinePrinter5.addItem("javapos");
jcboConnPrinter5.addItem("serial");
jcboConnPrinter5.addItem("file");
jcboSerialPrinter5.addItem("COM1");
jcboSerialPrinter5.addItem("COM2");
jcboSerialPrinter5.addItem("COM3");
jcboSerialPrinter5.addItem("COM4");
jcboSerialPrinter5.addItem("COM5");
jcboSerialPrinter5.addItem("COM6");
jcboSerialPrinter5.addItem("COM7");
jcboSerialPrinter5.addItem("COM8");
jcboSerialPrinter5.addItem("LPT1");
jcboSerialPrinter5.addItem("/dev/ttyS0");
jcboSerialPrinter5.addItem("/dev/ttyS1");
jcboSerialPrinter5.addItem("/dev/ttyS2");
jcboSerialPrinter5.addItem("/dev/ttyS3");
jcboSerialPrinter5.addItem("/dev/ttyS4");
jcboSerialPrinter5.addItem("/dev/ttyS5");
// Printer 6
jcboMachinePrinter6.addItem("Not defined");
jcboMachinePrinter6.addItem("screen");
jcboMachinePrinter6.addItem("printer");
jcboMachinePrinter6.addItem("epson");
jcboMachinePrinter6.addItem("tmu220");
jcboMachinePrinter6.addItem("star");
jcboMachinePrinter6.addItem("ODP1000");
jcboMachinePrinter6.addItem("ithaca");
jcboMachinePrinter6.addItem("surepos");
jcboMachinePrinter6.addItem("plain");
jcboMachinePrinter6.addItem("javapos");
jcboConnPrinter6.addItem("serial");
jcboConnPrinter6.addItem("file");
jcboSerialPrinter6.addItem("COM1");
jcboSerialPrinter6.addItem("COM2");
jcboSerialPrinter6.addItem("COM3");
jcboSerialPrinter6.addItem("COM4");
jcboSerialPrinter6.addItem("COM5");
jcboSerialPrinter6.addItem("COM6");
jcboSerialPrinter6.addItem("COM7");
jcboSerialPrinter6.addItem("COM8");
jcboSerialPrinter6.addItem("LPT1");
jcboSerialPrinter6.addItem("/dev/ttyS0");
jcboSerialPrinter6.addItem("/dev/ttyS1");
jcboSerialPrinter6.addItem("/dev/ttyS2");
jcboSerialPrinter6.addItem("/dev/ttyS3");
jcboSerialPrinter6.addItem("/dev/ttyS4");
jcboSerialPrinter6.addItem("/dev/ttyS5");
//
// Display
jcboMachineDisplay.addItem("Not defined");
jcboMachineDisplay.addItem("screen");
jcboMachineDisplay.addItem("window");
jcboMachineDisplay.addItem("javapos");
jcboMachineDisplay.addItem("epson");
jcboMachineDisplay.addItem("ld200");
jcboMachineDisplay.addItem("surepos");
jcboConnDisplay.addItem("serial");
jcboConnDisplay.addItem("file");
jcboSerialDisplay.addItem("COM1");
jcboSerialDisplay.addItem("COM2");
jcboSerialDisplay.addItem("COM3");
jcboSerialDisplay.addItem("COM4");
jcboSerialDisplay.addItem("COM5");
jcboSerialDisplay.addItem("COM6");
jcboSerialDisplay.addItem("COM7");
jcboSerialDisplay.addItem("COM8");
jcboSerialDisplay.addItem("LPT1");
jcboSerialDisplay.addItem("/dev/ttyS0");
jcboSerialDisplay.addItem("/dev/ttyS1");
jcboSerialDisplay.addItem("/dev/ttyS2");
jcboSerialDisplay.addItem("/dev/ttyS3");
jcboSerialDisplay.addItem("/dev/ttyS4");
jcboSerialDisplay.addItem("/dev/ttyS5");
// Scale
// JG 20 Aug 13 Add Casio PD1 Scale
jcboMachineScale.addItem("Not defined");
jcboMachineScale.addItem("screen");
jcboMachineScale.addItem("casiopd1");
jcboMachineScale.addItem("caspdII");
jcboMachineScale.addItem("dialog1");
jcboMachineScale.addItem("samsungesp");
jcboSerialScale.addItem("COM1");
jcboSerialScale.addItem("COM2");
jcboSerialScale.addItem("COM3");
jcboSerialScale.addItem("COM4");
jcboSerialScale.addItem("COM5");
jcboSerialScale.addItem("COM6");
jcboSerialScale.addItem("COM7");
jcboSerialScale.addItem("COM8");
jcboSerialScale.addItem("/dev/ttyS0");
jcboSerialScale.addItem("/dev/ttyS1");
jcboSerialScale.addItem("/dev/ttyS2");
jcboSerialScale.addItem("/dev/ttyS3");
jcboSerialScale.addItem("/dev/ttyS4");
jcboSerialScale.addItem("/dev/ttyS5");
// Scanner
jcboMachineScanner.addItem("Not defined");
jcboMachineScanner.addItem("scanpal2");
jcboSerialScanner.addItem("COM1");
jcboSerialScanner.addItem("COM2");
jcboSerialScanner.addItem("COM3");
jcboSerialScanner.addItem("COM4");
jcboSerialScanner.addItem("COM5");
jcboSerialScanner.addItem("COM6");
jcboSerialScanner.addItem("COM7");
jcboSerialScanner.addItem("COM8");
jcboSerialScanner.addItem("/dev/ttyS0");
jcboSerialScanner.addItem("/dev/ttyS1");
jcboSerialScanner.addItem("/dev/ttyS2");
jcboSerialScanner.addItem("/dev/ttyS3");
jcboSerialScanner.addItem("/dev/ttyS4");
jcboSerialScanner.addItem("/dev/ttyS5");
// Printers
cboPrinters.addItem("(Default)");
cboPrinters.addItem("(Show dialog)");
for (String name : printernames) {
cboPrinters.addItem(name);
}
}
/**
*
* @return
*/
@Override
public boolean hasChanged() {
return dirty.isDirty();
}
/**
*
* @return
*/
@Override
public Component getConfigComponent() {
return this;
}
/**
*
* @param config
*/
@Override
public void loadProperties(AppConfig config) {
// JG 6 May 2013 to switch
StringParser p = new StringParser(config.getProperty("machine.printer"));
String sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter.setSelectedItem("epson");
jcboConnPrinter.setSelectedItem(sparam);
jcboSerialPrinter.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter.setSelectedItem(sparam);
m_jtxtJPOSPrinter.setText(p.nextToken(','));
m_jtxtJPOSDrawer.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter.setSelectedItem(sparam);
printer1printerparams.setParameters(p);
break;
default:
jcboMachinePrinter.setSelectedItem(sparam);
jcboConnPrinter.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter.setSelectedItem(p.nextToken(','));
break;
}
// JG 6 May 2013 to switch
p = new StringParser(config.getProperty("machine.printer.2"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter2.setSelectedItem("epson");
jcboConnPrinter2.setSelectedItem(sparam);
jcboSerialPrinter2.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter2.setSelectedItem(sparam);
m_jtxtJPOSPrinter2.setText(p.nextToken(','));
m_jtxtJPOSDrawer2.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter2.setSelectedItem(sparam);
printer2printerparams.setParameters(p);
break;
default:
jcboMachinePrinter2.setSelectedItem(sparam);
jcboConnPrinter2.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter2.setSelectedItem(p.nextToken(','));
break;
}
// JG 6 May 2013 to switch
p = new StringParser(config.getProperty("machine.printer.3"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter3.setSelectedItem("epson");
jcboConnPrinter3.setSelectedItem(sparam);
jcboSerialPrinter3.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter3.setSelectedItem(sparam);
m_jtxtJPOSPrinter3.setText(p.nextToken(','));
m_jtxtJPOSDrawer3.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter3.setSelectedItem(sparam);
printer3printerparams.setParameters(p);
break;
default:
jcboMachinePrinter3.setSelectedItem(sparam);
jcboConnPrinter3.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter3.setSelectedItem(p.nextToken(','));
break;
}
// new printers add jdl 10.11.12
p = new StringParser(config.getProperty("machine.printer.4"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter4.setSelectedItem("epson");
jcboConnPrinter4.setSelectedItem(sparam);
jcboSerialPrinter4.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter4.setSelectedItem(sparam);
m_jtxtJPOSPrinter4.setText(p.nextToken(','));
m_jtxtJPOSDrawer4.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter4.setSelectedItem(sparam);
printer4printerparams.setParameters(p);
break;
default:
jcboMachinePrinter4.setSelectedItem(sparam);
jcboConnPrinter4.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter4.setSelectedItem(p.nextToken(','));
break;
}
p = new StringParser(config.getProperty("machine.printer.5"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter5.setSelectedItem("epson");
jcboConnPrinter5.setSelectedItem(sparam);
jcboSerialPrinter5.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter5.setSelectedItem(sparam);
m_jtxtJPOSPrinter5.setText(p.nextToken(','));
m_jtxtJPOSDrawer5.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter5.setSelectedItem(sparam);
printer5printerparams.setParameters(p);
break;
default:
jcboMachinePrinter5.setSelectedItem(sparam);
jcboConnPrinter5.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter5.setSelectedItem(p.nextToken(','));
break;
}
p = new StringParser(config.getProperty("machine.printer.6"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachinePrinter6.setSelectedItem("epson");
jcboConnPrinter6.setSelectedItem(sparam);
jcboSerialPrinter6.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachinePrinter6.setSelectedItem(sparam);
m_jtxtJPOSPrinter6.setText(p.nextToken(','));
m_jtxtJPOSDrawer6.setText(p.nextToken(','));
break;
case "printer":
jcboMachinePrinter6.setSelectedItem(sparam);
printer6printerparams.setParameters(p);
break;
default:
jcboMachinePrinter6.setSelectedItem(sparam);
jcboConnPrinter6.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialPrinter6.setSelectedItem(p.nextToken(','));
break;
}
// JG 6 May 2013 to switch
p = new StringParser(config.getProperty("machine.display"));
sparam = unifySerialInterface(p.nextToken(':'));
switch (sparam) {
case "serial":
case "file":
jcboMachineDisplay.setSelectedItem("epson");
jcboConnDisplay.setSelectedItem(sparam);
jcboSerialDisplay.setSelectedItem(p.nextToken(','));
break;
case "javapos":
jcboMachineDisplay.setSelectedItem(sparam);
m_jtxtJPOSName.setText(p.nextToken(','));
break;
default:
jcboMachineDisplay.setSelectedItem(sparam);
jcboConnDisplay.setSelectedItem(unifySerialInterface(p.nextToken(',')));
jcboSerialDisplay.setSelectedItem(p.nextToken(','));
break;
}
p = new StringParser(config.getProperty("machine.scale"));
sparam = p.nextToken(':');
jcboMachineScale.setSelectedItem(sparam);
if ("casiopd1".equals(sparam)
|| "caspdII".equals(sparam)
|| "dialog1".equals(sparam)
|| "samsungesp".equals(sparam)) {
jcboSerialScale.setSelectedItem(p.nextToken(','));
}
p = new StringParser(config.getProperty("machine.scanner"));
sparam = p.nextToken(':');
jcboMachineScanner.setSelectedItem(sparam);
if ("scanpal2".equals(sparam)) {
jcboSerialScanner.setSelectedItem(p.nextToken(','));
}
cboPrinters.setSelectedItem(config.getProperty("machine.printername"));
dirty.setDirty(false);
}
/**
*
* @param config
*/
@Override
public void saveProperties(AppConfig config) {
// JG 6 May 2013 to switch
String sMachinePrinter = comboValue(jcboMachinePrinter.getSelectedItem());
switch (sMachinePrinter) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer", sMachinePrinter + ":" + comboValue(jcboConnPrinter.getSelectedItem()) + "," + comboValue(jcboSerialPrinter.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer", sMachinePrinter + ":" + m_jtxtJPOSPrinter.getText() + "," + m_jtxtJPOSDrawer.getText());
break;
case "printer":
config.setProperty("machine.printer", sMachinePrinter + ":" + printer1printerparams.getParameters());
break;
default:
config.setProperty("machine.printer", sMachinePrinter);
break;
}
// JG 6 May 2013 to switch
String sMachinePrinter2 = comboValue(jcboMachinePrinter2.getSelectedItem());
switch (sMachinePrinter2) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer.2", sMachinePrinter2 + ":" + comboValue(jcboConnPrinter2.getSelectedItem()) + "," + comboValue(jcboSerialPrinter2.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer.2", sMachinePrinter2 + ":" + m_jtxtJPOSPrinter2.getText() + "," + m_jtxtJPOSDrawer2.getText());
break;
case "printer":
config.setProperty("machine.printer.2", sMachinePrinter2 + ":" + printer2printerparams.getParameters());
break;
default:
config.setProperty("machine.printer.2", sMachinePrinter2);
break;
}
// JG 6 May 2013 to switch
String sMachinePrinter3 = comboValue(jcboMachinePrinter3.getSelectedItem());
switch (sMachinePrinter3) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer.3", sMachinePrinter3 + ":" + comboValue(jcboConnPrinter3.getSelectedItem()) + "," + comboValue(jcboSerialPrinter3.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer.3", sMachinePrinter3 + ":" + m_jtxtJPOSPrinter3.getText() + "," + m_jtxtJPOSDrawer3.getText());
break;
case "printer":
config.setProperty("machine.printer.3", sMachinePrinter3 + ":" + printer3printerparams.getParameters());
break;
default:
config.setProperty("machine.printer.3", sMachinePrinter3);
break;
}
// new printers added 10.11.12
String sMachinePrinter4 = comboValue(jcboMachinePrinter4.getSelectedItem());
switch (sMachinePrinter4) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer.4", sMachinePrinter4 + ":" + comboValue(jcboConnPrinter4.getSelectedItem()) + "," + comboValue(jcboSerialPrinter4.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer.4", sMachinePrinter4 + ":" + m_jtxtJPOSPrinter4.getText() + "," + m_jtxtJPOSDrawer4.getText());
break;
case "printer":
config.setProperty("machine.printer.4", sMachinePrinter4 + ":" + printer4printerparams.getParameters());
break;
default:
config.setProperty("machine.printer.4", sMachinePrinter4);
break;
}
String sMachinePrinter5 = comboValue(jcboMachinePrinter5.getSelectedItem());
switch (sMachinePrinter5) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer.5", sMachinePrinter5 + ":" + comboValue(jcboConnPrinter5.getSelectedItem()) + "," + comboValue(jcboSerialPrinter5.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer.5", sMachinePrinter5 + ":" + m_jtxtJPOSPrinter5.getText() + "," + m_jtxtJPOSDrawer5.getText());
break;
case "printer":
config.setProperty("machine.printer.5", sMachinePrinter5 + ":" + printer5printerparams.getParameters());
break;
default:
config.setProperty("machine.printer.5", sMachinePrinter5);
break;
}
String sMachinePrinter6 = comboValue(jcboMachinePrinter6.getSelectedItem());
switch (sMachinePrinter6) {
case "epson":
case "tmu220":
case "star":
case "ODP1000":
case "ithaca":
case "surepos":
config.setProperty("machine.printer.6", sMachinePrinter6 + ":" + comboValue(jcboConnPrinter6.getSelectedItem()) + "," + comboValue(jcboSerialPrinter6.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.printer.6", sMachinePrinter6 + ":" + m_jtxtJPOSPrinter6.getText() + "," + m_jtxtJPOSDrawer6.getText());
break;
case "printer":
config.setProperty("machine.printer.6", sMachinePrinter6 + ":" + printer6printerparams.getParameters());
break;
default:
config.setProperty("machine.printer.6", sMachinePrinter6);
break;
}
// JG 6 May 2013 to switch
String sMachineDisplay = comboValue(jcboMachineDisplay.getSelectedItem());
switch (sMachineDisplay) {
case "epson":
case "ld200":
case "surepos":
config.setProperty("machine.display", sMachineDisplay + ":" + comboValue(jcboConnDisplay.getSelectedItem()) + "," + comboValue(jcboSerialDisplay.getSelectedItem()));
break;
case "javapos":
config.setProperty("machine.display", sMachineDisplay + ":" + m_jtxtJPOSName.getText());
break;
default:
config.setProperty("machine.display", sMachineDisplay);
break;
}
//JG 20 Aug 2013 Add Casio PD1 Scale
String sMachineScale = comboValue(jcboMachineScale.getSelectedItem());
if ("casiopd1".equals(sMachineScale)
|| "caspdII".equals(sMachineScale)
|| "dialog1".equals(sMachineScale)
|| "samsungesp".equals(sMachineScale)) {
config.setProperty("machine.scale", sMachineScale + ":" + comboValue(jcboSerialScale.getSelectedItem()));
} else {
config.setProperty("machine.scale", sMachineScale);
}
// El scanner
String sMachineScanner = comboValue(jcboMachineScanner.getSelectedItem());
if ("scanpal2".equals(sMachineScanner)) {
config.setProperty("machine.scanner", sMachineScanner + ":" + comboValue(jcboSerialScanner.getSelectedItem()));
} else {
config.setProperty("machine.scanner", sMachineScanner);
}
config.setProperty("machine.printername", comboValue(cboPrinters.getSelectedItem()));
dirty.setDirty(false);
}
private String unifySerialInterface(String sparam) {
// for backward compatibility
return ("rxtx".equals(sparam))
? "serial"
: sparam;
}
private String comboValue(Object value) {
return value == null ? "" : value.toString();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel13 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jcboMachineDisplay = new javax.swing.JComboBox();
jcboMachinePrinter = new javax.swing.JComboBox();
jcboMachinePrinter2 = new javax.swing.JComboBox();
jcboMachinePrinter3 = new javax.swing.JComboBox();
jcboMachinePrinter4 = new javax.swing.JComboBox();
jcboMachinePrinter5 = new javax.swing.JComboBox();
jcboMachinePrinter6 = new javax.swing.JComboBox();
jcboMachineScale = new javax.swing.JComboBox();
jcboMachineScanner = new javax.swing.JComboBox();
cboPrinters = new javax.swing.JComboBox();
m_jDisplayParams = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jlblConnDisplay = new javax.swing.JLabel();
jcboConnDisplay = new javax.swing.JComboBox();
jlblDisplayPort = new javax.swing.JLabel();
jcboSerialDisplay = new javax.swing.JComboBox();
jPanel3 = new javax.swing.JPanel();
jLabel20 = new javax.swing.JLabel();
m_jtxtJPOSName = new javax.swing.JTextField();
m_jPrinterParams1 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel6 = new javax.swing.JPanel();
jlblConnPrinter = new javax.swing.JLabel();
jcboConnPrinter = new javax.swing.JComboBox();
jlblPrinterPort = new javax.swing.JLabel();
jcboSerialPrinter = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel21 = new javax.swing.JLabel();
m_jtxtJPOSPrinter = new javax.swing.JTextField();
m_jtxtJPOSDrawer = new javax.swing.JTextField();
jLabel24 = new javax.swing.JLabel();
m_jPrinterParams2 = new javax.swing.JPanel();
jPanel7 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
jlblConnPrinter2 = new javax.swing.JLabel();
jcboConnPrinter2 = new javax.swing.JComboBox();
jlblPrinterPort2 = new javax.swing.JLabel();
jcboSerialPrinter2 = new javax.swing.JComboBox();
jPanel11 = new javax.swing.JPanel();
m_jtxtJPOSPrinter2 = new javax.swing.JTextField();
m_jtxtJPOSDrawer2 = new javax.swing.JTextField();
jLabel27 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
m_jPrinterParams3 = new javax.swing.JPanel();
jPanel9 = new javax.swing.JPanel();
jPanel10 = new javax.swing.JPanel();
jlblConnPrinter3 = new javax.swing.JLabel();
jcboConnPrinter3 = new javax.swing.JComboBox();
jlblPrinterPort3 = new javax.swing.JLabel();
jcboSerialPrinter3 = new javax.swing.JComboBox();
jPanel12 = new javax.swing.JPanel();
m_jtxtJPOSPrinter3 = new javax.swing.JTextField();
m_jtxtJPOSDrawer3 = new javax.swing.JTextField();
jLabel28 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
m_jPrinterParams4 = new javax.swing.JPanel();
jPanel14 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jlblConnPrinter4 = new javax.swing.JLabel();
jcboConnPrinter4 = new javax.swing.JComboBox();
jlblPrinterPort6 = new javax.swing.JLabel();
jcboSerialPrinter4 = new javax.swing.JComboBox();
jPanel18 = new javax.swing.JPanel();
m_jtxtJPOSPrinter4 = new javax.swing.JTextField();
m_jtxtJPOSDrawer4 = new javax.swing.JTextField();
jLabel30 = new javax.swing.JLabel();
jLabel31 = new javax.swing.JLabel();
m_jPrinterParams5 = new javax.swing.JPanel();
jPanel20 = new javax.swing.JPanel();
jPanel21 = new javax.swing.JPanel();
jlblConnPrinter5 = new javax.swing.JLabel();
jcboConnPrinter5 = new javax.swing.JComboBox();
jlblPrinterPort7 = new javax.swing.JLabel();
jcboSerialPrinter5 = new javax.swing.JComboBox();
jPanel22 = new javax.swing.JPanel();
m_jtxtJPOSPrinter5 = new javax.swing.JTextField();
m_jtxtJPOSDrawer5 = new javax.swing.JTextField();
jLabel33 = new javax.swing.JLabel();
jLabel34 = new javax.swing.JLabel();
m_jPrinterParams6 = new javax.swing.JPanel();
jPanel23 = new javax.swing.JPanel();
jPanel25 = new javax.swing.JPanel();
jlblConnPrinter6 = new javax.swing.JLabel();
jcboConnPrinter6 = new javax.swing.JComboBox();
jlblPrinterPort8 = new javax.swing.JLabel();
jcboSerialPrinter6 = new javax.swing.JComboBox();
jPanel26 = new javax.swing.JPanel();
m_jtxtJPOSPrinter6 = new javax.swing.JTextField();
m_jtxtJPOSDrawer6 = new javax.swing.JTextField();
jLabel36 = new javax.swing.JLabel();
jLabel37 = new javax.swing.JLabel();
m_jScaleParams = new javax.swing.JPanel();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jlblPrinterPort4 = new javax.swing.JLabel();
jcboSerialScale = new javax.swing.JComboBox();
m_jScannerParams = new javax.swing.JPanel();
jPanel24 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jlblPrinterPort5 = new javax.swing.JLabel();
jcboSerialScanner = new javax.swing.JComboBox();
setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
setPreferredSize(new java.awt.Dimension(700, 400));
jPanel13.setPreferredSize(new java.awt.Dimension(700, 400));
jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel5.setText(AppLocal.getIntString("Label.MachineDisplay")); // NOI18N
jLabel5.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel6.setText(AppLocal.getIntString("Label.MachinePrinter")); // NOI18N
jLabel6.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel7.setText(AppLocal.getIntString("Label.MachinePrinter2")); // NOI18N
jLabel7.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel8.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel8.setText(AppLocal.getIntString("Label.MachinePrinter3")); // NOI18N
jLabel8.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel9.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel9.setText(AppLocal.getIntString("Label.MachinePrinter4")); // NOI18N
jLabel9.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel10.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel10.setText(AppLocal.getIntString("Label.MachinePrinter5")); // NOI18N
jLabel10.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel11.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel11.setText(AppLocal.getIntString("Label.MachinePrinter6")); // NOI18N
jLabel11.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel12.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel12.setText(AppLocal.getIntString("label.scale")); // NOI18N
jLabel12.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel13.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel13.setText(AppLocal.getIntString("label.scanner")); // NOI18N
jLabel13.setPreferredSize(new java.awt.Dimension(110, 25));
jLabel14.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel14.setText(AppLocal.getIntString("label.reportsprinter")); // NOI18N
jLabel14.setPreferredSize(new java.awt.Dimension(110, 25));
jcboMachineDisplay.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachineDisplay.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachineDisplay.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachineDisplay.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineDisplayActionPerformed(evt);
}
});
jcboMachinePrinter.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinterActionPerformed(evt);
}
});
jcboMachinePrinter2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter2.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter2ActionPerformed(evt);
}
});
jcboMachinePrinter3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter3.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter3ActionPerformed(evt);
}
});
jcboMachinePrinter4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter4.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter4.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter4ActionPerformed(evt);
}
});
jcboMachinePrinter5.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter5.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter5.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter5ActionPerformed(evt);
}
});
jcboMachinePrinter6.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachinePrinter6.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachinePrinter6.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachinePrinter6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachinePrinter6ActionPerformed(evt);
}
});
jcboMachineScale.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachineScale.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachineScale.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachineScale.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScaleActionPerformed(evt);
}
});
jcboMachineScanner.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jcboMachineScanner.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jcboMachineScanner.setPreferredSize(new java.awt.Dimension(200, 23));
jcboMachineScanner.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jcboMachineScannerActionPerformed(evt);
}
});
cboPrinters.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
cboPrinters.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
cboPrinters.setPreferredSize(new java.awt.Dimension(200, 23));
m_jDisplayParams.setPreferredSize(new java.awt.Dimension(200, 25));
m_jDisplayParams.setLayout(new java.awt.CardLayout());
m_jDisplayParams.add(jPanel2, "empty");
jlblConnDisplay.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnDisplay.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnDisplay.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnDisplay.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnDisplay.setPreferredSize(new java.awt.Dimension(100, 23));
jlblDisplayPort.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblDisplayPort.setText(AppLocal.getIntString("label.machinedisplayport")); // NOI18N
jlblDisplayPort.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialDisplay.setEditable(true);
jcboSerialDisplay.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialDisplay.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblDisplayPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblDisplayPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jDisplayParams.add(jPanel1, "comm");
jLabel20.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel20.setText(AppLocal.getIntString("Label.Name")); // NOI18N
jLabel20.setPreferredSize(new java.awt.Dimension(50, 25));
m_jtxtJPOSName.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSName.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
m_jtxtJPOSNameActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(204, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jDisplayParams.add(jPanel3, "javapos");
m_jPrinterParams1.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams1.setLayout(new java.awt.CardLayout());
jPanel5.setPreferredSize(new java.awt.Dimension(10, 25));
m_jPrinterParams1.add(jPanel5, "empty");
jlblConnPrinter.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter.setEditable(true);
jcboSerialPrinter.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams1.add(jPanel6, "comm");
jLabel21.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel21.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel21.setPreferredSize(new java.awt.Dimension(50, 25));
m_jtxtJPOSPrinter.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel24.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel24.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel24.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams1.add(jPanel4, "javapos");
m_jPrinterParams2.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams2.setLayout(new java.awt.CardLayout());
m_jPrinterParams2.add(jPanel7, "empty");
jlblConnPrinter2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter2.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter2.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter2.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort2.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort2.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter2.setEditable(true);
jcboSerialPrinter2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter2.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams2.add(jPanel8, "comm");
m_jtxtJPOSPrinter2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter2.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer2.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel27.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel27.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel27.setPreferredSize(new java.awt.Dimension(50, 25));
jLabel22.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel22.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel22.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
jPanel11.setLayout(jPanel11Layout);
jPanel11Layout.setHorizontalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel11Layout.setVerticalGroup(
jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel11Layout.createSequentialGroup()
.addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams2.add(jPanel11, "javapos");
m_jPrinterParams3.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams3.setLayout(new java.awt.CardLayout());
m_jPrinterParams3.add(jPanel9, "empty");
jlblConnPrinter3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter3.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter3.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter3.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort3.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort3.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter3.setEditable(true);
jcboSerialPrinter3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter3.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort3, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel10Layout.createSequentialGroup()
.addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams3.add(jPanel10, "comm");
m_jtxtJPOSPrinter3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter3.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer3.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel28.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel28.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel28.setPreferredSize(new java.awt.Dimension(50, 25));
jLabel23.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel23.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel23.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel12Layout.createSequentialGroup()
.addGroup(jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams3.add(jPanel12, "javapos");
m_jPrinterParams4.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams4.setLayout(new java.awt.CardLayout());
m_jPrinterParams4.add(jPanel14, "empty");
jlblConnPrinter4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter4.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter4.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter4.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort6.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort6.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter4.setEditable(true);
jcboSerialPrinter4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter4.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel15Layout.createSequentialGroup()
.addGroup(jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams4.add(jPanel15, "comm");
m_jtxtJPOSPrinter4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter4.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer4.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel30.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel30.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel30.setPreferredSize(new java.awt.Dimension(50, 25));
jLabel31.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel31.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel31.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addGroup(jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams4.add(jPanel18, "javapos");
m_jPrinterParams5.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams5.setLayout(new java.awt.CardLayout());
m_jPrinterParams5.add(jPanel20, "empty");
jlblConnPrinter5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter5.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter5.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter5.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort7.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort7.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter5.setEditable(true);
jcboSerialPrinter5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter5.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addGroup(jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams5.add(jPanel21, "comm");
m_jtxtJPOSPrinter5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter5.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer5.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel33.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel33.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel33.setPreferredSize(new java.awt.Dimension(50, 25));
jLabel34.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel34.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel34.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel22Layout = new javax.swing.GroupLayout(jPanel22);
jPanel22.setLayout(jPanel22Layout);
jPanel22Layout.setHorizontalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel22Layout.setVerticalGroup(
jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel22Layout.createSequentialGroup()
.addGroup(jPanel22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel34, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel33, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams5.add(jPanel22, "javapos");
m_jPrinterParams6.setPreferredSize(new java.awt.Dimension(200, 25));
m_jPrinterParams6.setLayout(new java.awt.CardLayout());
m_jPrinterParams6.add(jPanel23, "empty");
jlblConnPrinter6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblConnPrinter6.setText(AppLocal.getIntString("label.machinedisplayconn")); // NOI18N
jlblConnPrinter6.setPreferredSize(new java.awt.Dimension(50, 25));
jcboConnPrinter6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboConnPrinter6.setPreferredSize(new java.awt.Dimension(100, 23));
jlblPrinterPort8.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort8.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort8.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialPrinter6.setEditable(true);
jcboSerialPrinter6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialPrinter6.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel25Layout = new javax.swing.GroupLayout(jPanel25);
jPanel25.setLayout(jPanel25Layout);
jPanel25Layout.setHorizontalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel25Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblConnPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboConnPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jlblPrinterPort8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(54, Short.MAX_VALUE))
);
jPanel25Layout.setVerticalGroup(
jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel25Layout.createSequentialGroup()
.addGroup(jPanel25Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboConnPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboSerialPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblConnPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams6.add(jPanel25, "comm");
m_jtxtJPOSPrinter6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSPrinter6.setPreferredSize(new java.awt.Dimension(120, 25));
m_jtxtJPOSDrawer6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
m_jtxtJPOSDrawer6.setPreferredSize(new java.awt.Dimension(120, 25));
jLabel36.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel36.setText(AppLocal.getIntString("label.javapos.printer")); // NOI18N
jLabel36.setPreferredSize(new java.awt.Dimension(50, 25));
jLabel37.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel37.setText(AppLocal.getIntString("label.javapos.drawer")); // NOI18N
jLabel37.setPreferredSize(new java.awt.Dimension(50, 25));
javax.swing.GroupLayout jPanel26Layout = new javax.swing.GroupLayout(jPanel26);
jPanel26.setLayout(jPanel26Layout);
jPanel26Layout.setHorizontalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel26Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(m_jtxtJPOSDrawer6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
jPanel26Layout.setVerticalGroup(
jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel26Layout.createSequentialGroup()
.addGroup(jPanel26Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(m_jtxtJPOSPrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel37, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_jtxtJPOSDrawer6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jPrinterParams6.add(jPanel26, "javapos");
m_jScaleParams.setPreferredSize(new java.awt.Dimension(200, 25));
m_jScaleParams.setLayout(new java.awt.CardLayout());
m_jScaleParams.add(jPanel16, "empty");
jlblPrinterPort4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort4.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort4.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialScale.setEditable(true);
jcboSerialScale.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialScale.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(224, Short.MAX_VALUE))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel17Layout.createSequentialGroup()
.addGroup(jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jScaleParams.add(jPanel17, "comm");
m_jScannerParams.setPreferredSize(new java.awt.Dimension(200, 25));
m_jScannerParams.setLayout(new java.awt.CardLayout());
m_jScannerParams.add(jPanel24, "empty");
jlblPrinterPort5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jlblPrinterPort5.setText(AppLocal.getIntString("label.machineprinterport")); // NOI18N
jlblPrinterPort5.setPreferredSize(new java.awt.Dimension(50, 25));
jcboSerialScanner.setEditable(true);
jcboSerialScanner.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jcboSerialScanner.setPreferredSize(new java.awt.Dimension(100, 23));
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jlblPrinterPort5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(234, Short.MAX_VALUE))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel19Layout.createSequentialGroup()
.addGroup(jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jcboSerialScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jlblPrinterPort5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0))
);
m_jScannerParams.add(jPanel19, "comm");
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jScaleParams, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jScannerParams, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jcboMachinePrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE))
.addGroup(jPanel13Layout.createSequentialGroup()
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addContainerGap())
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachineDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jDisplayParams, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachinePrinter6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jPrinterParams6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachineScale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(m_jScaleParams, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jcboMachineScanner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cboPrinters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(m_jScannerParams, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(74, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, 734, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel13, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void jcboMachinePrinter3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter3ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams3.getLayout());
if ("epson".equals(jcboMachinePrinter3.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter3.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter3.getSelectedItem()) || "star".equals(jcboMachinePrinter3.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter3.getSelectedItem()) || "surepos".equals(jcboMachinePrinter3.getSelectedItem())) {
cl.show(m_jPrinterParams3, "comm");
} else if ("javapos".equals(jcboMachinePrinter3.getSelectedItem())) {
cl.show(m_jPrinterParams3, "javapos");
} else if ("printer".equals(jcboMachinePrinter3.getSelectedItem())) {
cl.show(m_jPrinterParams3, "printer");
} else {
cl.show(m_jPrinterParams3, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter3ActionPerformed
private void jcboMachinePrinter2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter2ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams2.getLayout());
if ("epson".equals(jcboMachinePrinter2.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter2.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter2.getSelectedItem()) || "star".equals(jcboMachinePrinter2.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter2.getSelectedItem()) || "surepos".equals(jcboMachinePrinter2.getSelectedItem())) {
cl.show(m_jPrinterParams2, "comm");
} else if ("javapos".equals(jcboMachinePrinter2.getSelectedItem())) {
cl.show(m_jPrinterParams2, "javapos");
} else if ("printer".equals(jcboMachinePrinter2.getSelectedItem())) {
cl.show(m_jPrinterParams2, "printer");
} else {
cl.show(m_jPrinterParams2, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter2ActionPerformed
private void jcboMachinePrinterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinterActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams1.getLayout());
if ("epson".equals(jcboMachinePrinter.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter.getSelectedItem()) || "star".equals(jcboMachinePrinter.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter.getSelectedItem()) || "surepos".equals(jcboMachinePrinter.getSelectedItem())) {
cl.show(m_jPrinterParams1, "comm");
} else if ("javapos".equals(jcboMachinePrinter.getSelectedItem())) {
cl.show(m_jPrinterParams1, "javapos");
} else if ("printer".equals(jcboMachinePrinter.getSelectedItem())) {
cl.show(m_jPrinterParams1, "printer");
} else {
cl.show(m_jPrinterParams1, "empty");
}
}//GEN-LAST:event_jcboMachinePrinterActionPerformed
private void jcboMachinePrinter4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter4ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams4.getLayout());
if ("epson".equals(jcboMachinePrinter4.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter4.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter4.getSelectedItem()) || "star".equals(jcboMachinePrinter4.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter4.getSelectedItem()) || "surepos".equals(jcboMachinePrinter4.getSelectedItem())) {
cl.show(m_jPrinterParams4, "comm");
} else if ("javapos".equals(jcboMachinePrinter4.getSelectedItem())) {
cl.show(m_jPrinterParams4, "javapos");
} else if ("printer".equals(jcboMachinePrinter4.getSelectedItem())) {
cl.show(m_jPrinterParams4, "printer");
} else {
cl.show(m_jPrinterParams4, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter4ActionPerformed
private void jcboMachinePrinter5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter5ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams5.getLayout());
if ("epson".equals(jcboMachinePrinter5.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter5.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter5.getSelectedItem()) || "star".equals(jcboMachinePrinter5.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter5.getSelectedItem()) || "surepos".equals(jcboMachinePrinter5.getSelectedItem())) {
cl.show(m_jPrinterParams5, "comm");
} else if ("javapos".equals(jcboMachinePrinter5.getSelectedItem())) {
cl.show(m_jPrinterParams5, "javapos");
} else if ("printer".equals(jcboMachinePrinter5.getSelectedItem())) {
cl.show(m_jPrinterParams5, "printer");
} else {
cl.show(m_jPrinterParams5, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter5ActionPerformed
private void jcboMachinePrinter6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachinePrinter6ActionPerformed
CardLayout cl = (CardLayout) (m_jPrinterParams6.getLayout());
if ("epson".equals(jcboMachinePrinter6.getSelectedItem()) || "ODP1000".equals(jcboMachinePrinter6.getSelectedItem()) || "tmu220".equals(jcboMachinePrinter6.getSelectedItem()) || "star".equals(jcboMachinePrinter6.getSelectedItem()) || "ithaca".equals(jcboMachinePrinter6.getSelectedItem()) || "surepos".equals(jcboMachinePrinter6.getSelectedItem())) {
cl.show(m_jPrinterParams6, "comm");
} else if ("javapos".equals(jcboMachinePrinter6.getSelectedItem())) {
cl.show(m_jPrinterParams6, "javapos");
} else if ("printer".equals(jcboMachinePrinter6.getSelectedItem())) {
cl.show(m_jPrinterParams6, "printer");
} else {
cl.show(m_jPrinterParams6, "empty");
}
}//GEN-LAST:event_jcboMachinePrinter6ActionPerformed
private void m_jtxtJPOSNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jtxtJPOSNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_m_jtxtJPOSNameActionPerformed
private void jcboMachineScannerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineScannerActionPerformed
CardLayout cl = (CardLayout) (m_jScannerParams.getLayout());
if ("scanpal2".equals(jcboMachineScanner.getSelectedItem())) {
cl.show(m_jScannerParams, "comm");
} else {
cl.show(m_jScannerParams, "empty");
}
}//GEN-LAST:event_jcboMachineScannerActionPerformed
private void jcboMachineScaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineScaleActionPerformed
CardLayout cl = (CardLayout) (m_jScaleParams.getLayout());
// JG 29 Aug 13 - Add Casio PD1 Scale
if ("casiopd1".equals(jcboMachineScale.getSelectedItem())
|| "caspdII".equals(jcboMachineScale.getSelectedItem())
|| "dialog1".equals(jcboMachineScale.getSelectedItem())
|| "samsungesp".equals(jcboMachineScale.getSelectedItem())) {
cl.show(m_jScaleParams, "comm");
} else {
cl.show(m_jScaleParams, "empty");
}
}//GEN-LAST:event_jcboMachineScaleActionPerformed
private void jcboMachineDisplayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcboMachineDisplayActionPerformed
CardLayout cl = (CardLayout) (m_jDisplayParams.getLayout());
if ("epson".equals(jcboMachineDisplay.getSelectedItem()) || "ld200".equals(jcboMachineDisplay.getSelectedItem()) || "surepos".equals(jcboMachineDisplay.getSelectedItem())) {
cl.show(m_jDisplayParams, "comm");
} else if ("javapos".equals(jcboMachineDisplay.getSelectedItem())) {
cl.show(m_jDisplayParams, "javapos");
} else {
cl.show(m_jDisplayParams, "empty");
}
}//GEN-LAST:event_jcboMachineDisplayActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cboPrinters;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel22;
private javax.swing.JPanel jPanel23;
private javax.swing.JPanel jPanel24;
private javax.swing.JPanel jPanel25;
private javax.swing.JPanel jPanel26;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JComboBox jcboConnDisplay;
private javax.swing.JComboBox jcboConnPrinter;
private javax.swing.JComboBox jcboConnPrinter2;
private javax.swing.JComboBox jcboConnPrinter3;
private javax.swing.JComboBox jcboConnPrinter4;
private javax.swing.JComboBox jcboConnPrinter5;
private javax.swing.JComboBox jcboConnPrinter6;
private javax.swing.JComboBox jcboMachineDisplay;
private javax.swing.JComboBox jcboMachinePrinter;
private javax.swing.JComboBox jcboMachinePrinter2;
private javax.swing.JComboBox jcboMachinePrinter3;
private javax.swing.JComboBox jcboMachinePrinter4;
private javax.swing.JComboBox jcboMachinePrinter5;
private javax.swing.JComboBox jcboMachinePrinter6;
private javax.swing.JComboBox jcboMachineScale;
private javax.swing.JComboBox jcboMachineScanner;
private javax.swing.JComboBox jcboSerialDisplay;
private javax.swing.JComboBox jcboSerialPrinter;
private javax.swing.JComboBox jcboSerialPrinter2;
private javax.swing.JComboBox jcboSerialPrinter3;
private javax.swing.JComboBox jcboSerialPrinter4;
private javax.swing.JComboBox jcboSerialPrinter5;
private javax.swing.JComboBox jcboSerialPrinter6;
private javax.swing.JComboBox jcboSerialScale;
private javax.swing.JComboBox jcboSerialScanner;
private javax.swing.JLabel jlblConnDisplay;
private javax.swing.JLabel jlblConnPrinter;
private javax.swing.JLabel jlblConnPrinter2;
private javax.swing.JLabel jlblConnPrinter3;
private javax.swing.JLabel jlblConnPrinter4;
private javax.swing.JLabel jlblConnPrinter5;
private javax.swing.JLabel jlblConnPrinter6;
private javax.swing.JLabel jlblDisplayPort;
private javax.swing.JLabel jlblPrinterPort;
private javax.swing.JLabel jlblPrinterPort2;
private javax.swing.JLabel jlblPrinterPort3;
private javax.swing.JLabel jlblPrinterPort4;
private javax.swing.JLabel jlblPrinterPort5;
private javax.swing.JLabel jlblPrinterPort6;
private javax.swing.JLabel jlblPrinterPort7;
private javax.swing.JLabel jlblPrinterPort8;
private javax.swing.JPanel m_jDisplayParams;
private javax.swing.JPanel m_jPrinterParams1;
private javax.swing.JPanel m_jPrinterParams2;
private javax.swing.JPanel m_jPrinterParams3;
private javax.swing.JPanel m_jPrinterParams4;
private javax.swing.JPanel m_jPrinterParams5;
private javax.swing.JPanel m_jPrinterParams6;
private javax.swing.JPanel m_jScaleParams;
private javax.swing.JPanel m_jScannerParams;
private javax.swing.JTextField m_jtxtJPOSDrawer;
private javax.swing.JTextField m_jtxtJPOSDrawer2;
private javax.swing.JTextField m_jtxtJPOSDrawer3;
private javax.swing.JTextField m_jtxtJPOSDrawer4;
private javax.swing.JTextField m_jtxtJPOSDrawer5;
private javax.swing.JTextField m_jtxtJPOSDrawer6;
private javax.swing.JTextField m_jtxtJPOSName;
private javax.swing.JTextField m_jtxtJPOSPrinter;
private javax.swing.JTextField m_jtxtJPOSPrinter2;
private javax.swing.JTextField m_jtxtJPOSPrinter3;
private javax.swing.JTextField m_jtxtJPOSPrinter4;
private javax.swing.JTextField m_jtxtJPOSPrinter5;
private javax.swing.JTextField m_jtxtJPOSPrinter6;
// End of variables declaration//GEN-END:variables
}
| 58.894009 | 358 | 0.689264 |
8c685e07205af9a486287037b948b49c739dbaeb | 7,589 | // Copyright 2007 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); You may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
// applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
package com.google.scrollview.ui;
import edu.umd.cs.piccolo.nodes.PImage;
import java.awt.image.BufferedImage;
import java.util.HashMap;
/**
* The ScrollViewImageHandler is a helper class which takes care of image
* processing. It is used to construct an Image from the message-stream and
* basically consists of a number of utility functions to process the input
* stream.
*
* @author wanke@google.com
*/
public class SVImageHandler {
/**
* Stores a mapping from the name of the string to its actual image. It
* enables us to re-use images without having to load or transmit them again
*/
static HashMap<String, PImage> images = new HashMap<String, PImage>();
/** A global flag stating whether we are currently expecting Image data */
static boolean readImageData = false;
// TODO(wanke) Consider moving all this into an SVImage class.
/** These are all values belonging to the image which is currently being read */
static String imageName = null; // Image name
static int bytesRead = 0; // Nr. of bytes already read
static int bpp = 0; // Bit depth
static int pictureArray[]; // The array holding the actual image
static int bytePerPixel = 0; // # of used bytes to transmit a pixel (32 bpp
// -> 7 BPP)
static int width = 0;
static int height = 0;
/* All methods are static, so we forbid to construct SVImageHandler objects */
private SVImageHandler() {
}
/**
* Takes a binary input string (consisting of '0' and '1' characters) and
* converts it to an integer representation usable as image data.
*/
private static int[] processBinaryImage(String inputLine) {
int BLACK = 0;
int WHITE = Integer.MAX_VALUE;
int[] imgData = new int[inputLine.length()];
for (int i = 0; i < inputLine.length(); i++) {
if (inputLine.charAt(i) == '0') {
imgData[i] = WHITE;
} else if (inputLine.charAt(i) == '1') {
imgData[i] = BLACK;
} // BLACK is default anyway
else { // Something is wrong: We did get unexpected data
System.out.println("Error: unexpected non-image-data: ("
+ SVImageHandler.bytesRead + "," + inputLine.length() + ","
+ (SVImageHandler.height * SVImageHandler.width) + ")");
System.exit(1);
}
}
return imgData;
}
/**
* Takes an input string with pixel depth of 8 (represented by 2 bytes in
* hexadecimal format, e.g. FF for white) and converts it to an
* integer representation usable as image data
*/
private static int[] processGrayImage(String inputLine) {
int[] imgData = new int[inputLine.length() / 2];
// Note: This is really inefficient, splitting it 2-byte-arrays in one pass
// would be wa faster than substring everytime.
for (int i = 0; i < inputLine.length(); i +=2) {
String s = inputLine.substring(i, i+1);
imgData[i] = Integer.parseInt(s, 16);
}
return imgData;
}
/**
* Takes an input string with pixel depth of 32 (represented by HTML-like
* colors in hexadecimal format, e.g. #00FF00 for green) and converts it to an
* integer representation usable as image data
*/
private static int[] process32bppImage(String inputLine) {
String[] strData = inputLine.split("#");
int[] imgData = new int[strData.length - 1];
for (int i = 1; i < strData.length; i++) {
imgData[i - 1] = Integer.parseInt(strData[i], 16);
}
return imgData;
}
/**
* Called when all image data is transmitted. Generates the actual image used
* by java and puts it into the images-hashmap.
*/
private static void closeImage() {
BufferedImage bi = null;
if (bpp == 1) {
bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
} else if (bpp == 8) {
bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
} else if (bpp == 32) {
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
} else {
System.out.println("Unsupported Image Type: " + bpp + " bpp");
System.exit(1);
}
bi.setRGB(0, 0, width, height, pictureArray, 0, width);
PImage img = new PImage(bi);
images.put(imageName, img);
imageName = null;
readImageData = false;
System.out.println("(server, #Bytes:" + bytesRead + ") Image Completed");
bytesRead = 0;
bpp = 0;
}
/** Starts creation of a new image. */
public static void createImage(String name, int width, int height,
int bitsPerPixel) {
// Create buffered image that does not support transparency
bpp = bitsPerPixel;
if (bpp == 1) {
bytePerPixel = 1;
} else if (bpp == 8) {
bytePerPixel = 2;
} else if (bpp == 32) {
bytePerPixel = 7;
} else {
throw new IllegalArgumentException(
"bpp should be 1 (binary), 8 (gray) or 32 (argb), is " + bpp);
}
if (imageName != null) {
throw new IllegalArgumentException("Image " + imageName + " already opened!");
}
else {
imageName = name;
bytesRead = 0;
readImageData = true;
SVImageHandler.height = height;
SVImageHandler.width = width;
pictureArray = new int[width * height];
}
System.out.println("Processing Image with " + bpp + " bpp, size " + width + "x" + height);
}
/**
* Opens an Image from location. This means the image does not have to be
* actually transfered over the network. Thus, it is a lot faster than using
* the createImage method.
*
* @param location The (local) location from where to open the file. This is
* also the internal name associated with the image (if you want to draw it).
*/
public static void openImage(String location) {
PImage img = new PImage(location);
images.put(location, img);
}
/** Find the image corresponding to a given name */
public static PImage getImage(String name) {
return images.get(name);
}
/**
* Gets called while currently reading image data. Decides, how to process it
* (which image type, whether all data is there).
*/
public static void parseData(String inputLine) {
int[] data = null;
if (bpp == 1) {
data = processBinaryImage(inputLine);
} else if (bpp == 8) {
data = processGrayImage(inputLine);
} else if (bpp == 32) {
data = process32bppImage(inputLine);
} else {
System.out.println("Unsupported Bit Type: " + bpp);
}
System.arraycopy(data, 0, pictureArray, bytesRead, data.length);
bytesRead += data.length;
// We have read all image data - close the image
if (bytesRead == (height * width)) {
closeImage();
}
}
/** Returns whether we a currently reading image data or not */
public static boolean getReadImageData() {
return readImageData;
}
/** Computes how many bytes of the image data are still missing */
public static int getMissingRemainingBytes() {
return (height * width * bytePerPixel) - bytesRead;
}
}
| 33.139738 | 94 | 0.651601 |
6dfd21880c2fbba5253d0514b0ca4808be334e49 | 2,003 | /*
* Copyright 2004-2011 H2 Group.
* Copyright 2011 James Moger.
*
* 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.iciql;
/**
* This class represents a query with join and an incomplete condition.
*
* @param <A>
* the incomplete condition data type
*/
public class QueryJoinCondition<T, A> {
private Query<T> query;
private SelectTable<T> join;
private A x;
QueryJoinCondition(Query<T> query, SelectTable<T> join, A x) {
this.query = query;
this.join = join;
this.x = x;
}
public Query<T> is(boolean y) {
return addPrimitive(y);
}
public Query<T> is(byte y) {
return addPrimitive(y);
}
public Query<T> is(short y) {
return addPrimitive(y);
}
public Query<T> is(int y) {
return addPrimitive(y);
}
public Query<T> is(long y) {
return addPrimitive(y);
}
public Query<T> is(float y) {
return addPrimitive(y);
}
public Query<T> is(double y) {
return addPrimitive(y);
}
@SuppressWarnings("unchecked")
private Query<T> addPrimitive(Object o) {
A alias = query.getPrimitiveAliasByValue((A) o);
if (alias == null) {
join.addConditionToken(new Condition<A>(x, (A) o, CompareType.EQUAL));
} else {
join.addConditionToken(new Condition<A>(x, alias, CompareType.EQUAL));
}
return query;
}
public Query<T> is(A y) {
join.addConditionToken(new Condition<A>(x, y, CompareType.EQUAL));
return query;
}
}
| 23.845238 | 76 | 0.654518 |
0dc6c2a980ccdb6178e1dab9550bd605e999e198 | 1,463 | /*
* Copyright (c) 2022 DenaryDev
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package io.sapphiremc.chromium.client.dummy;
import io.sapphiremc.chromium.ChromiumMod;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.tag.BlockTags;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryEntry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.Difficulty;
import net.minecraft.world.dimension.DimensionType;
import java.util.OptionalLong;
public class DummyClientWorld extends ClientWorld {
private static DummyClientWorld instance;
private static final DimensionType DUMMY_OVERWORLD = DimensionType.create(OptionalLong.empty(), true, false, false, false, 1.0, false, false, false, false, false, 0, 256, 256, BlockTags.INFINIBURN_OVERWORLD, DimensionType.OVERWORLD_ID, 1.0f);
public static DummyClientWorld getInstance() {
if (instance == null) instance = new DummyClientWorld();
return instance;
}
private DummyClientWorld() {
super(DummyClientPlayNetworkHandler.getInstance(), new Properties(Difficulty.EASY, false, true), RegistryKey.of(Registry.WORLD_KEY, new Identifier(ChromiumMod.MOD_ID, "dummy")), RegistryEntry.of(DUMMY_OVERWORLD), 0, 0, () -> null, null, false, 0L);
}
}
| 39.540541 | 256 | 0.766234 |
64ca7eda0821bab1ea39290d28bb2ac607d12cd3 | 93 | class HDnmzDfnIR8E {
}
class KEsFD2lV {
}
class vL3uclvroC {
public boolean[][] O;
}
| 7.75 | 25 | 0.634409 |
49065cbbc8e87c9ad3be44985fcfefa9aa96d144 | 1,464 | ///*
// * To change this template, choose Tools | Templates
// * and open the template in the editor.
// */
//package net.clementlevallois.utils;
//
///**
// *
// * @author C. Levallois
// * @param <T>
// */
//public class Pair<T> {
//
// private T left;
// private T right;
//
// public Pair(T left, T right) {
// this.left = left;
// this.right = right;
// }
//
// public Pair() {
// }
//
// public void setLeft(T left) {
// this.left = left;
// }
//
// public void setRight(T right) {
// this.right = right;
// }
//
//
//
// public T getLeft() {
// return left;
// }
//
// public T getRight() {
// return right;
// }
//
// @Override
// public int hashCode() {
// return left.hashCode() ^ right.hashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Pair<T> other = (Pair<T>) obj;
// if (this.left != other.left && (this.left == null || !this.left.equals(other.left))) {
// return false;
// }
// if (this.right != other.right && (this.right == null || !this.right.equals(other.right))) {
// return false;
// }
// return true;
// }
//}
| 22.181818 | 102 | 0.446721 |
fb31c9c127a28b65ce94ed31b24b5e635d024cbb | 1,078 | package com.learn.leetcode.onehundredFiftyToTwohundred;
/**
* Description:
* date: 2021/6/28 13:29
* Package: com.learn.leetcode.onehundredFiftyToTwohundred
*
* @author 李佳乐
* @email 18066550996@163.com
*/
@SuppressWarnings("all")
public class LC165 {
public static void main(String[] args) {
String s1 = "1.2.3";
String s2 = "1.2";
int i = compareVersion(s1, s2);
System.out.println(i);
}
/**
* 比较版本号
*/
public static int compareVersion(String version1, String version2) {
String[] v1s = version1.split("\\.");
String[] v2s = version2.split("\\.");
int length1 = v1s.length;//3
int length2 = v2s.length;//2
int i1, i2;
for (int i = 0; i < Math.max(length1, length2); ++i) { //2
//位数较少的版本号 需要补零
i1 = i < length1 ? Integer.parseInt(v1s[i]) : 0;//1 2 3
i2 = i < length2 ? Integer.parseInt(v2s[i]) : 0;//1 2 0
if (i1 != i2) {
return i1 > i2 ? 1 : -1;
}
}
return 0;
}
}
| 25.666667 | 72 | 0.528757 |
727d4f445d63c30dff02f3aa540c774bc8088b98 | 2,422 | package org.opencyc.api;
/**
* Class CycApiServerException indicates an error condition during
* a Cyc API call that occurred on the Cyc server. If an error is
* detected on the Java client, then a CycApiException is thrown
* instead.
*
* @version $Id: CycApiServerSideException.java 138070 2012-01-10 19:46:08Z sbrown $
* @author tbrussea
*
* <p>Copyright 2004 Cycorp, Inc., license is open source GNU LGPL.
* <p><a href="http://www.opencyc.org/license.txt">the license</a>
* <p><a href="http://www.opencyc.org">www.opencyc.org</a>
* <p><a href="http://www.sourceforge.net/projects/opencyc">OpenCyc at SourceForge</a>
* <p>
* THIS SOFTWARE AND KNOWLEDGE BASE CONTENT ARE PROVIDED ``AS IS'' AND
* ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OPENCYC
* ORGANIZATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE AND KNOWLEDGE
* BASE CONTENT, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class CycApiServerSideException extends CycApiException {
/**
* Construct a CycApiServerSideException object with no
* specified message.
*/
public CycApiServerSideException() {
super();
}
/**
* Construct a CycApiServerSideException object with a
* specified message.
* @param s a message describing the exception.
*/
public CycApiServerSideException(String s) {
super(s);
}
/**
* Construct a CycApiServerSideException object with a
* specified message and throwable.
* @param s the message string
* @param cause the throwable that caused this exception
*/
public CycApiServerSideException(String s, Throwable cause) {
super(s, cause);
}
/**
* Construct a CycApiServerSideException object with the
* specified throwable.
* @param cause the throwable that caused this exception
*/
public CycApiServerSideException(Throwable cause) {
super(cause);
}
}
| 35.101449 | 86 | 0.726259 |
5f180487353382b6e6adba220a8cf62d0c3b26d2 | 14,753 | /**********************************************************************
Copyright (c) 2004 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
2004 Erik Bengtson - add dependent elements
...
**********************************************************************/
package org.datanucleus.metadata;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Set;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.exceptions.ClassNotResolvedException;
import org.datanucleus.util.ClassUtils;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.StringUtils;
/**
* Representation of the MetaData of a collection.
*/
public class CollectionMetaData extends ContainerMetaData
{
private static final long serialVersionUID = -5567408442228331561L;
/** Representation of the element of the collection. */
protected ContainerComponent element;
/**
* Whether this collection handles more than one element. Some collection, e.g. java.lang.Optional, will
* always hold only one element.
*/
protected boolean singleElement = false;
/**
* Constructor to create a copy of the passed metadata.
* @param collmd The metadata to copy
*/
public CollectionMetaData(CollectionMetaData collmd)
{
super(collmd);
element = new ContainerComponent();
element.embedded = collmd.element.embedded;
element.serialized = collmd.element.serialized;
element.dependent = collmd.element.dependent;
element.typeName = collmd.element.typeName;
element.classMetaData = collmd.element.classMetaData;
singleElement = collmd.singleElement;
}
/**
* Default constructor. Set the fields using setters, before populate().
*/
public CollectionMetaData()
{
element = new ContainerComponent();
}
/**
* Method to populate any defaults, and check the validity of the MetaData.
* @param clr ClassLoaderResolver to use for any loading operations
* @param primary the primary ClassLoader to use (or null)
*/
public void populate(ClassLoaderResolver clr, ClassLoader primary)
{
AbstractMemberMetaData mmd = (AbstractMemberMetaData)parent;
if (!StringUtils.isWhitespace(element.typeName) && element.typeName.indexOf(',') > 0)
{
throw new InvalidMemberMetaDataException("044131", mmd.getClassName(), mmd.getName());
}
// Make sure the type in "element" is set
element.populate(mmd.getAbstractClassMetaData().getPackageName(), clr, primary);
// "element-type"
if (element.typeName == null)
{
throw new InvalidMemberMetaDataException("044133", mmd.getClassName(), mmd.getName());
}
// Check that the element type exists TODO Remove this since performed in element.populate
Class elementTypeClass = null;
try
{
elementTypeClass = clr.classForName(element.typeName, primary);
if (!elementTypeClass.getName().equals(element.typeName))
{
// The element-type has been resolved from what was specified in the MetaData - update to the fully-qualified name
NucleusLogger.METADATA.info(Localiser.msg("044135", getMemberName(), mmd.getClassName(false), element.typeName, elementTypeClass.getName()));
element.typeName = elementTypeClass.getName();
}
}
catch (ClassNotResolvedException cnre)
{
throw new InvalidMemberMetaDataException("044134", mmd.getClassName(), getMemberName(), element.typeName);
}
// "embedded-element"
MetaDataManager mmgr = getMetaDataManager();
if (element.embedded == null)
{
// Assign default for "embedded-element" based on 18.13.1 of JDO 2 spec
if (mmgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(elementTypeClass))
{
element.embedded = Boolean.TRUE;
}
else
{
// Use "readMetaDataForClass" in case we havent yet initialised the metadata for the element
AbstractClassMetaData elemCmd = mmgr.readMetaDataForClass(elementTypeClass.getName());
if (elemCmd == null)
{
// Try to load it just in case using annotations and only pulled in one side of the relation
try
{
elemCmd = mmgr.getMetaDataForClass(elementTypeClass, clr);
}
catch (Throwable thr)
{
}
}
if (elemCmd != null)
{
element.embedded = (elemCmd.isEmbeddedOnly() ? Boolean.TRUE : Boolean.FALSE);
}
else if (elementTypeClass.isInterface() || elementTypeClass == Object.class)
{
// Collection<interface> or Object not explicitly marked as embedded defaults to false
element.embedded = Boolean.FALSE;
}
else
{
// Fallback to true
NucleusLogger.METADATA.debug("Member with collection of elementType=" + elementTypeClass.getName()+
" not explicitly marked as embedded, so defaulting to embedded since not persistable");
element.embedded = Boolean.TRUE;
}
}
}
else if (Boolean.FALSE.equals(element.embedded))
{
// Use "readMetaDataForClass" in case we havent yet initialised the metadata for the element
AbstractClassMetaData elemCmd = mmgr.readMetaDataForClass(elementTypeClass.getName());
if (elemCmd == null && !elementTypeClass.isInterface() && elementTypeClass != java.lang.Object.class)
{
// If the user has set a non-PC/non-Interface as not embedded, correct it since not supported.
// Note : this fails when using in the enhancer since not yet PC
NucleusLogger.METADATA.debug("Member with collection of element type " + elementTypeClass.getName() +
" marked as not embedded, but only persistable as embedded, so resetting");
element.embedded = Boolean.TRUE;
}
}
ElementMetaData elemmd = mmd.getElementMetaData();
if (elemmd != null && elemmd.getEmbeddedMetaData() != null)
{
element.embedded = Boolean.TRUE;
}
if (Boolean.TRUE.equals(element.dependent))
{
// If the user has set a non-PC/non-reference as dependent, correct it since not valid.
// Note : this fails when using in the enhancer since not yet PC
if (!mmgr.getApiAdapter().isPersistable(elementTypeClass) && !elementTypeClass.isInterface() && elementTypeClass != java.lang.Object.class)
{
element.dependent = Boolean.FALSE;
}
}
// Keep a reference to the MetaData for the element
element.classMetaData = mmgr.getMetaDataForClassInternal(elementTypeClass, clr);
if (hasExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES))
{
// Check/fix the validity of the implementation-classes and qualify them where required.
StringBuilder str = new StringBuilder();
String[] implTypes = getValuesForExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES);
for (int i=0;i<implTypes.length;i++)
{
String implTypeName = ClassUtils.createFullClassName(mmd.getPackageName(), implTypes[i]);
if (i > 0)
{
str.append(",");
}
try
{
clr.classForName(implTypeName);
str.append(implTypeName);
}
catch (ClassNotResolvedException cnre)
{
try
{
// Maybe the user specified a java.lang class without fully-qualifying it
// This is beyond the scope of the JDO spec which expects java.lang cases to be fully-qualified
String langClassName = ClassUtils.getJavaLangClassForType(implTypeName);
clr.classForName(langClassName);
str.append(langClassName);
}
catch (ClassNotResolvedException cnre2)
{
// Implementation type not found
throw new InvalidMemberMetaDataException("044116", mmd.getClassName(), mmd.getName(), implTypes[i]);
}
}
}
addExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES, str.toString()); // Replace with this new value
}
// Make sure anything in the superclass is populated too
super.populate();
setPopulated();
}
public boolean elementIsPersistent()
{
return element.classMetaData != null;
}
/**
* Convenience accessor for the Element ClassMetaData.
* @param clr ClassLoader resolver (in case we need to initialise it)
* @return element ClassMetaData
*/
public AbstractClassMetaData getElementClassMetaData(final ClassLoaderResolver clr)
{
if (element.classMetaData != null && !element.classMetaData.isInitialised())
{
// Do as PrivilegedAction since uses reflection
// [JDOAdapter.isValidPrimaryKeyClass calls reflective methods]
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
element.classMetaData.initialise(clr);
return null;
}
});
}
return element.classMetaData;
}
/**
* Accessor for the embedded-element tag value
* @return embedded-element tag value
*/
public boolean isEmbeddedElement()
{
if (element.embedded == null)
{
return false;
}
return element.embedded.booleanValue();
}
/**
* Accessor for The dependent-element attribute indicates that the
* collection's element contains a reference that is to be deleted if the
* referring instance is deleted.
*
* @return dependent-element tag value
*/
public boolean isDependentElement()
{
if (element.dependent == null)
{
return false;
}
else if (element.classMetaData == null)
{
return false;
}
else
{
return element.dependent.booleanValue();
}
}
/**
* Accessor for the serialized-element tag value
* @return serialized-element tag value
*/
public boolean isSerializedElement()
{
if (element.serialized == null)
{
return false;
}
return element.serialized.booleanValue();
}
/**
* Accessor for the element-type tag value.
* @return element-type tag value
*/
public String getElementType()
{
return element.typeName;
}
public String[] getElementTypes()
{
return ((AbstractMemberMetaData)getParent()).getValuesForExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES);
}
// TODO Keep implementation types separate from declared type
public CollectionMetaData setElementType(String type)
{
// TODO Set implementation-classes using this if appropriate
// This is only valid pre-populate
element.setTypeName(type);
return this;
}
public CollectionMetaData setEmbeddedElement(boolean embedded)
{
element.setEmbedded(embedded);
return this;
}
public CollectionMetaData setSerializedElement(boolean serialized)
{
element.setSerialized(serialized);
return this;
}
public CollectionMetaData setDependentElement(boolean dependent)
{
element.setDependent(dependent);
return this;
}
public CollectionMetaData setSingleElement(boolean singleElement)
{
this.singleElement = singleElement;
return this;
}
/**
* Accessor for all ClassMetaData referenced by this array.
* @param orderedCmds List of ordered ClassMetaData objects (added to).
* @param referencedCmds Set of all ClassMetaData objects (added to).
* @param clr the ClassLoaderResolver
*/
void getReferencedClassMetaData(final List<AbstractClassMetaData> orderedCmds, final Set<AbstractClassMetaData> referencedCmds, final ClassLoaderResolver clr)
{
AbstractClassMetaData elementCmd = getMetaDataManager().getMetaDataForClass(element.typeName, clr);
if (elementCmd != null)
{
elementCmd.getReferencedClassMetaData(orderedCmds, referencedCmds, clr);
}
}
public String toString()
{
StringBuilder str = new StringBuilder(super.toString()).append(" [" + element.typeName + "]");
if (element.getEmbedded() == Boolean.TRUE)
{
str.append(" embedded");
}
if (element.getSerialized() == Boolean.TRUE)
{
str.append(" serialised");
}
if (element.getDependent() == Boolean.TRUE)
{
str.append(" dependent");
}
return str.toString();
}
}
| 38.023196 | 163 | 0.589168 |
7981ff9d3dd0849bd86cf7a5a62a1191085c8fbf | 868 | package jepperscore.dao.model;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* This class represents a single real person.
* @author Chuck
*
*/
@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
public class Person {
/**
* The name of the person.
*/
@XmlAttribute(required=true)
@JsonProperty
private String name;
/**
* @return The name of the person.
*/
@Nonnull
public String getName() {
return name;
}
/**
* Sets the name of the person.
* @param name The name.
*/
public void setName(@Nonnull String name) {
this.name = name;
}
}
| 20.666667 | 54 | 0.693548 |
e360a2c584d2b50852d3cf3f3cc44189423601d4 | 25,916 | /*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 8008925
* 8014217 8025003 8026330 8028397 8129544 8165243 8176379 8222187
* @summary tests java.util.Base64
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main TestBase64
* @key randomness
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;
import jdk.test.lib.RandomFactory;
public class TestBase64 {
private static final Random rnd = RandomFactory.getRandom();
public static void main(String args[]) throws Throwable {
int numRuns = 10;
int numBytes = 200;
if (args.length > 1) {
numRuns = Integer.parseInt(args[0]);
numBytes = Integer.parseInt(args[1]);
}
test(Base64.getEncoder(), Base64.getDecoder(), numRuns, numBytes);
test(Base64.getUrlEncoder(), Base64.getUrlDecoder(), numRuns, numBytes);
test(Base64.getMimeEncoder(), Base64.getMimeDecoder(), numRuns, numBytes);
byte[] nl_1 = new byte[] {'\n'};
byte[] nl_2 = new byte[] {'\n', '\r'};
byte[] nl_3 = new byte[] {'\n', '\r', '\n'};
for (int i = 0; i < 10; i++) {
int len = rnd.nextInt(200) + 4;
test(Base64.getMimeEncoder(len, nl_1),
Base64.getMimeDecoder(),
numRuns, numBytes);
test(Base64.getMimeEncoder(len, nl_2),
Base64.getMimeDecoder(),
numRuns, numBytes);
test(Base64.getMimeEncoder(len, nl_3),
Base64.getMimeDecoder(),
numRuns, numBytes);
}
// test mime case with < 4 length
for (int len = 0; len < 4; len++) {
test(Base64.getMimeEncoder(len, nl_1),
Base64.getMimeDecoder(),
numRuns, numBytes);
test(Base64.getMimeEncoder(len, nl_2),
Base64.getMimeDecoder(),
numRuns, numBytes);
test(Base64.getMimeEncoder(len, nl_3),
Base64.getMimeDecoder(),
numRuns, numBytes);
}
testNull(Base64.getEncoder());
testNull(Base64.getUrlEncoder());
testNull(Base64.getMimeEncoder());
testNull(Base64.getMimeEncoder(10, new byte[]{'\n'}));
testNull(Base64.getDecoder());
testNull(Base64.getUrlDecoder());
testNull(Base64.getMimeDecoder());
checkNull(() -> Base64.getMimeEncoder(10, null));
testIOE(Base64.getEncoder());
testIOE(Base64.getUrlEncoder());
testIOE(Base64.getMimeEncoder());
testIOE(Base64.getMimeEncoder(10, new byte[]{'\n'}));
byte[] src = new byte[1024];
rnd.nextBytes(src);
final byte[] decoded = Base64.getEncoder().encode(src);
testIOE(Base64.getDecoder(), decoded);
testIOE(Base64.getMimeDecoder(), decoded);
testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));
// illegal line separator
checkIAE(() -> Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}));
// malformed padding/ending
testMalformedPadding();
// illegal base64 character
decoded[2] = (byte)0xe0;
checkIAE(() -> Base64.getDecoder().decode(decoded));
checkIAE(() -> Base64.getDecoder().decode(decoded, new byte[1024]));
checkIAE(() -> Base64.getDecoder().decode(ByteBuffer.wrap(decoded)));
// test single-non-base64 character for mime decoding
testSingleNonBase64MimeDec();
// test decoding of unpadded data
testDecodeUnpadded();
// test mime decoding with ignored character after padding
testDecodeIgnoredAfterPadding();
// given invalid args, encoder should not produce output
testEncoderKeepsSilence(Base64.getEncoder());
testEncoderKeepsSilence(Base64.getUrlEncoder());
testEncoderKeepsSilence(Base64.getMimeEncoder());
// given invalid args, decoder should not consume input
testDecoderKeepsAbstinence(Base64.getDecoder());
testDecoderKeepsAbstinence(Base64.getUrlDecoder());
testDecoderKeepsAbstinence(Base64.getMimeDecoder());
// tests patch addressing JDK-8222187
// https://bugs.openjdk.java.net/browse/JDK-8222187
testJDK_8222187();
}
private static void test(Base64.Encoder enc, Base64.Decoder dec,
int numRuns, int numBytes) throws Throwable {
enc.encode(new byte[0]);
dec.decode(new byte[0]);
for (boolean withoutPadding : new boolean[] { false, true}) {
if (withoutPadding) {
enc = enc.withoutPadding();
}
for (int i=0; i<numRuns; i++) {
for (int j=1; j<numBytes; j++) {
byte[] orig = new byte[j];
rnd.nextBytes(orig);
// --------testing encode/decode(byte[])--------
byte[] encoded = enc.encode(orig);
byte[] decoded = dec.decode(encoded);
checkEqual(orig, decoded,
"Base64 array encoding/decoding failed!");
if (withoutPadding) {
if (encoded[encoded.length - 1] == '=')
throw new RuntimeException(
"Base64 enc.encode().withoutPadding() has padding!");
}
// --------testing encodetoString(byte[])/decode(String)--------
String str = enc.encodeToString(orig);
if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {
throw new RuntimeException(
"Base64 encodingToString() failed!");
}
byte[] buf = dec.decode(new String(encoded, "ASCII"));
checkEqual(buf, orig, "Base64 decoding(String) failed!");
//-------- testing encode/decode(Buffer)--------
testEncode(enc, ByteBuffer.wrap(orig), encoded);
ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);
bin.put(orig).flip();
testEncode(enc, bin, encoded);
testDecode(dec, ByteBuffer.wrap(encoded), orig);
bin = ByteBuffer.allocateDirect(encoded.length);
bin.put(encoded).flip();
testDecode(dec, bin, orig);
// --------testing decode.wrap(input stream)--------
// 1) random buf length
ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
InputStream is = dec.wrap(bais);
buf = new byte[orig.length + 10];
int len = orig.length;
int off = 0;
while (true) {
int n = rnd.nextInt(len);
if (n == 0)
n = 1;
n = is.read(buf, off, n);
if (n == -1) {
checkEqual(off, orig.length,
"Base64 stream decoding failed");
break;
}
off += n;
len -= n;
if (len == 0)
break;
}
buf = Arrays.copyOf(buf, off);
checkEqual(buf, orig, "Base64 stream decoding failed!");
// 2) read one byte each
bais.reset();
is = dec.wrap(bais);
buf = new byte[orig.length + 10];
off = 0;
int b;
while ((b = is.read()) != -1) {
buf[off++] = (byte)b;
}
buf = Arrays.copyOf(buf, off);
checkEqual(buf, orig, "Base64 stream decoding failed!");
// --------testing encode.wrap(output stream)--------
ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);
OutputStream os = enc.wrap(baos);
off = 0;
len = orig.length;
for (int k = 0; k < 5; k++) {
if (len == 0)
break;
int n = rnd.nextInt(len);
if (n == 0)
n = 1;
os.write(orig, off, n);
off += n;
len -= n;
}
if (len != 0)
os.write(orig, off, len);
os.close();
buf = baos.toByteArray();
checkEqual(buf, encoded, "Base64 stream encoding failed!");
// 2) write one byte each
baos.reset();
os = enc.wrap(baos);
off = 0;
while (off < orig.length) {
os.write(orig[off++]);
}
os.close();
buf = baos.toByteArray();
checkEqual(buf, encoded, "Base64 stream encoding failed!");
// --------testing encode(in, out); -> bigger buf--------
buf = new byte[encoded.length + rnd.nextInt(100)];
int ret = enc.encode(orig, buf);
checkEqual(ret, encoded.length,
"Base64 enc.encode(src, null) returns wrong size!");
buf = Arrays.copyOf(buf, ret);
checkEqual(buf, encoded,
"Base64 enc.encode(src, dst) failed!");
// --------testing decode(in, out); -> bigger buf--------
buf = new byte[orig.length + rnd.nextInt(100)];
ret = dec.decode(encoded, buf);
checkEqual(ret, orig.length,
"Base64 enc.encode(src, null) returns wrong size!");
buf = Arrays.copyOf(buf, ret);
checkEqual(buf, orig,
"Base64 dec.decode(src, dst) failed!");
}
}
}
}
private static final byte[] ba_null = null;
private static final String str_null = null;
private static final ByteBuffer bb_null = null;
private static void testNull(Base64.Encoder enc) {
checkNull(() -> enc.encode(ba_null));
checkNull(() -> enc.encodeToString(ba_null));
checkNull(() -> enc.encode(ba_null, new byte[10]));
checkNull(() -> enc.encode(new byte[10], ba_null));
checkNull(() -> enc.encode(bb_null));
checkNull(() -> enc.wrap((OutputStream)null));
}
private static void testNull(Base64.Decoder dec) {
checkNull(() -> dec.decode(ba_null));
checkNull(() -> dec.decode(str_null));
checkNull(() -> dec.decode(ba_null, new byte[10]));
checkNull(() -> dec.decode(new byte[10], ba_null));
checkNull(() -> dec.decode(bb_null));
checkNull(() -> dec.wrap((InputStream)null));
}
@FunctionalInterface
private static interface Testable {
public void test() throws Throwable;
}
private static void testIOE(Base64.Encoder enc) throws Throwable {
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
OutputStream os = enc.wrap(baos);
os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
os.close();
checkIOE(() -> os.write(10));
checkIOE(() -> os.write(new byte[] {10}));
checkIOE(() -> os.write(new byte[] {10}, 1, 4));
}
private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
InputStream is = dec.wrap(bais);
is.read(new byte[10]);
is.close();
checkIOE(() -> is.read());
checkIOE(() -> is.read(new byte[] {10}));
checkIOE(() -> is.read(new byte[] {10}, 1, 4));
checkIOE(() -> is.available());
checkIOE(() -> is.skip(20));
}
private static final void checkNull(Runnable r) {
try {
r.run();
throw new RuntimeException("NPE is not thrown as expected");
} catch (NullPointerException npe) {}
}
private static final void checkIOE(Testable t) throws Throwable {
try {
t.test();
throw new RuntimeException("IOE is not thrown as expected");
} catch (IOException ioe) {}
}
private static final void checkIAE(Runnable r) throws Throwable {
try {
r.run();
throw new RuntimeException("IAE is not thrown as expected");
} catch (IllegalArgumentException iae) {}
}
private static void testDecodeIgnoredAfterPadding() throws Throwable {
for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
byte[][] src = new byte[][] {
"A".getBytes("ascii"),
"AB".getBytes("ascii"),
"ABC".getBytes("ascii"),
"ABCD".getBytes("ascii"),
"ABCDE".getBytes("ascii")
};
Base64.Encoder encM = Base64.getMimeEncoder();
Base64.Decoder decM = Base64.getMimeDecoder();
Base64.Encoder enc = Base64.getEncoder();
Base64.Decoder dec = Base64.getDecoder();
for (int i = 0; i < src.length; i++) {
// decode(byte[])
byte[] encoded = encM.encode(src[i]);
encoded = Arrays.copyOf(encoded, encoded.length + 1);
encoded[encoded.length - 1] = nonBase64;
checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
byte[] decoded = new byte[src[i].length];
decM.decode(encoded, decoded);
checkEqual(decoded, src[i], "Non-base64 char is not ignored");
try {
dec.decode(encoded);
throw new RuntimeException("No IAE for non-base64 char");
} catch (IllegalArgumentException iae) {}
}
}
}
private static void testMalformedPadding() throws Throwable {
Object[] data = new Object[] {
"$=#", "", 0, // illegal ending unit
"A", "", 0, // dangling single byte
"A=", "", 0,
"A==", "", 0,
"QUJDA", "ABC", 4,
"QUJDA=", "ABC", 4,
"QUJDA==", "ABC", 4,
"=", "", 0, // unnecessary padding
"QUJD=", "ABC", 4, //"ABC".encode() -> "QUJD"
"AA=", "", 0, // incomplete padding
"QQ=", "", 0,
"QQ=N", "", 0, // incorrect padding
"QQ=?", "", 0,
"QUJDQQ=", "ABC", 4,
"QUJDQQ=N", "ABC", 4,
"QUJDQQ=?", "ABC", 4,
};
Base64.Decoder[] decs = new Base64.Decoder[] {
Base64.getDecoder(),
Base64.getUrlDecoder(),
Base64.getMimeDecoder()
};
for (Base64.Decoder dec : decs) {
for (int i = 0; i < data.length; i += 3) {
final String srcStr = (String)data[i];
final byte[] srcBytes = srcStr.getBytes("ASCII");
final ByteBuffer srcBB = ByteBuffer.wrap(srcBytes);
byte[] expected = ((String)data[i + 1]).getBytes("ASCII");
int pos = (Integer)data[i + 2];
// decode(byte[])
checkIAE(() -> dec.decode(srcBytes));
// decode(String)
checkIAE(() -> dec.decode(srcStr));
// decode(ByteBuffer)
checkIAE(() -> dec.decode(srcBB));
// wrap stream
checkIOE(new Testable() {
public void test() throws IOException {
try (InputStream is = dec.wrap(new ByteArrayInputStream(srcBytes))) {
while (is.read() != -1);
}
}});
}
}
// anything left after padding is "invalid"/IAE, if
// not MIME. In case of MIME, non-base64 character(s)
// is ignored.
checkIAE(() -> Base64.getDecoder().decode("AA==\u00D2"));
checkIAE(() -> Base64.getUrlDecoder().decode("AA==\u00D2"));
Base64.getMimeDecoder().decode("AA==\u00D2");
}
private static void testDecodeUnpadded() throws Throwable {
byte[] srcA = new byte[] { 'Q', 'Q' };
byte[] srcAA = new byte[] { 'Q', 'Q', 'E'};
Base64.Decoder dec = Base64.getDecoder();
byte[] ret = dec.decode(srcA);
if (ret[0] != 'A')
throw new RuntimeException("Decoding unpadding input A failed");
ret = dec.decode(srcAA);
if (ret[0] != 'A' && ret[1] != 'A')
throw new RuntimeException("Decoding unpadding input AA failed");
ret = new byte[10];
if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 1 &&
ret[0] != 'A')
throw new RuntimeException("Decoding unpadding input A from stream failed");
if (dec.wrap(new ByteArrayInputStream(srcA)).read(ret) != 2 &&
ret[0] != 'A' && ret[1] != 'A')
throw new RuntimeException("Decoding unpadding input AA from stream failed");
}
// single-non-base64-char should be ignored for mime decoding, but
// iae for basic decoding
private static void testSingleNonBase64MimeDec() throws Throwable {
for (String nonBase64 : new String[] {"#", "(", "!", "\\", "-", "_"}) {
if (Base64.getMimeDecoder().decode(nonBase64).length != 0) {
throw new RuntimeException("non-base64 char is not ignored");
}
try {
Base64.getDecoder().decode(nonBase64);
throw new RuntimeException("No IAE for single non-base64 char");
} catch (IllegalArgumentException iae) {}
}
}
private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected)
throws Throwable {
ByteBuffer bout = enc.encode(bin);
byte[] buf = new byte[bout.remaining()];
bout.get(buf);
if (bin.hasRemaining()) {
throw new RuntimeException(
"Base64 enc.encode(ByteBuffer) failed!");
}
checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!");
}
private static final void testDecode(Base64.Decoder dec, ByteBuffer bin, byte[] expected)
throws Throwable {
ByteBuffer bout = dec.decode(bin);
byte[] buf = new byte[bout.remaining()];
bout.get(buf);
checkEqual(buf, expected, "Base64 dec.decode(bf) failed!");
}
private static final void checkEqual(int v1, int v2, String msg)
throws Throwable {
if (v1 != v2) {
System.out.printf(" v1=%d%n", v1);
System.out.printf(" v2=%d%n", v2);
throw new RuntimeException(msg);
}
}
private static final void checkEqual(byte[] r1, byte[] r2, String msg)
throws Throwable {
if (!Arrays.equals(r1, r2)) {
System.out.printf(" r1[%d]=[%s]%n", r1.length, new String(r1));
System.out.printf(" r2[%d]=[%s]%n", r2.length, new String(r2));
throw new RuntimeException(msg);
}
}
// remove line feeds,
private static final byte[] normalize(byte[] src) {
int n = 0;
boolean hasUrl = false;
for (int i = 0; i < src.length; i++) {
if (src[i] == '\r' || src[i] == '\n')
n++;
if (src[i] == '-' || src[i] == '_')
hasUrl = true;
}
if (n == 0 && hasUrl == false)
return src;
byte[] ret = new byte[src.length - n];
int j = 0;
for (int i = 0; i < src.length; i++) {
if (src[i] == '-')
ret[j++] = '+';
else if (src[i] == '_')
ret[j++] = '/';
else if (src[i] != '\r' && src[i] != '\n')
ret[j++] = src[i];
}
return ret;
}
private static void testEncoderKeepsSilence(Base64.Encoder enc)
throws Throwable {
List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,
Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
rnd.nextInt()));
byte[] buf = new byte[] {1, 0, 91};
for (int off : vals) {
for (int len : vals) {
if (off >= 0 && len >= 0 && off <= buf.length - len) {
// valid args, skip them
continue;
}
// invalid args, test them
System.out.println("testing off=" + off + ", len=" + len);
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
try (OutputStream os = enc.wrap(baos)) {
os.write(buf, off, len);
throw new RuntimeException("Expected IOOBEx was not thrown");
} catch (IndexOutOfBoundsException expected) {
}
if (baos.size() > 0)
throw new RuntimeException("No output was expected, but got "
+ baos.size() + " bytes");
}
}
}
private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
throws Throwable {
List<Integer> vals = new ArrayList<>(List.of(Integer.MIN_VALUE,
Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
Integer.MAX_VALUE - 1, Integer.MAX_VALUE));
vals.addAll(List.of(rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
rnd.nextInt()));
byte[] buf = new byte[3];
for (int off : vals) {
for (int len : vals) {
if (off >= 0 && len >= 0 && off <= buf.length - len) {
// valid args, skip them
continue;
}
// invalid args, test them
System.out.println("testing off=" + off + ", len=" + len);
String input = "AAAAAAAAAAAAAAAAAAAAAA";
ByteArrayInputStream bais =
new ByteArrayInputStream(input.getBytes("Latin1"));
try (InputStream is = dec.wrap(bais)) {
is.read(buf, off, len);
throw new RuntimeException("Expected IOOBEx was not thrown");
} catch (IndexOutOfBoundsException expected) {
}
if (bais.available() != input.length())
throw new RuntimeException("No input should be consumed, "
+ "but consumed " + (input.length() - bais.available())
+ " bytes");
}
}
}
private static void testJDK_8222187() throws Throwable {
byte[] orig = "12345678".getBytes("US-ASCII");
byte[] encoded = Base64.getEncoder().encode(orig);
// decode using different buffer sizes, up to a longer one than needed
for (int bufferSize = 1; bufferSize <= encoded.length + 1; bufferSize++) {
try (
InputStream in = Base64.getDecoder().wrap(
new ByteArrayInputStream(encoded));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
byte[] buffer = new byte[bufferSize];
int read;
while ((read = in.read(buffer, 0, bufferSize)) >= 0) {
baos.write(buffer, 0, read);
}
// compare result, output info if lengths do not match
byte[] decoded = baos.toByteArray();
checkEqual(decoded, orig, "Base64 stream decoding failed!");
}
}
}
}
| 40.684458 | 107 | 0.503434 |
bc3677c75516f0d39fccb673ac784d3ab95bd9d8 | 989 | package de.sandstorm.junit.examples.nestedEntities;
import de.sandstorm.junit.examples.simpleEntity.Person;
/**
* test entity with references to another one
*/
public class Mail {
private final Person recipient;
private final Person sender;
/**
* constructor for mail with unknown sender
*
* @param recipient
*/
public Mail(Person recipient) {
this(recipient, null);
}
/**
* constructor
*
* @param recipient
* @param sender
*/
public Mail(Person recipient, Person sender) {
this.recipient = recipient;
this.sender = sender;
}
/**
* @return exact clone of this instance
*/
public Mail duplicate() {
return new Mail(
recipient.duplicate(),
sender == null ? null : sender.duplicate()
);
}
public Person getRecipient() {
return recipient;
}
public Person getSender() {
return sender;
}
}
| 19.392157 | 55 | 0.584429 |
48b60884d21d208951f47b3945c54bb9ba4ad6c2 | 3,051 | package se.chalmers.ju2jmh.experiments.workloads;
import com.github.javaparser.ast.CompilationUnit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ParseJavaSourceTest {
private String input = ParseJavaSource.INPUT;
private CompilationUnit expected = ParseJavaSource.getOutput();
@Test
public void testRunWorkloadOnce() {
CompilationUnit result = ParseJavaSource.runWorkload(input);
assertEquals(expected, result);
}
@Test
public void testRunWorkloadTwice() {
CompilationUnit result1 = ParseJavaSource.runWorkload(input);
CompilationUnit result2 = ParseJavaSource.runWorkload(input);
assertEquals(expected, result1);
assertEquals(expected, result2);
}
@Test
public void testRunWorkloadThrice() {
CompilationUnit result1 = ParseJavaSource.runWorkload(input);
CompilationUnit result2 = ParseJavaSource.runWorkload(input);
CompilationUnit result3 = ParseJavaSource.runWorkload(input);
assertEquals(expected, result1);
assertEquals(expected, result2);
assertEquals(expected, result3);
}
@org.openjdk.jmh.annotations.State(org.openjdk.jmh.annotations.Scope.Thread)
public static class _Benchmark {
private _Payloads payloads;
private ParseJavaSourceTest instance;
@org.openjdk.jmh.annotations.Benchmark
public void benchmark_testRunWorkloadOnce() throws java.lang.Throwable {
this.runBenchmark(this.payloads.testRunWorkloadOnce);
}
@org.openjdk.jmh.annotations.Benchmark
public void benchmark_testRunWorkloadTwice() throws java.lang.Throwable {
this.runBenchmark(this.payloads.testRunWorkloadTwice);
}
@org.openjdk.jmh.annotations.Benchmark
public void benchmark_testRunWorkloadThrice() throws java.lang.Throwable {
this.runBenchmark(this.payloads.testRunWorkloadThrice);
}
private void runBenchmark(se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTest> payload) throws java.lang.Throwable {
this.instance = new ParseJavaSourceTest();
payload.accept(this.instance);
}
private static class _Payloads {
public se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTest> testRunWorkloadOnce;
public se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTest> testRunWorkloadTwice;
public se.chalmers.ju2jmh.api.ThrowingConsumer<ParseJavaSourceTest> testRunWorkloadThrice;
}
@org.openjdk.jmh.annotations.Setup(org.openjdk.jmh.annotations.Level.Trial)
public void makePayloads() {
this.payloads = new _Payloads();
this.payloads.testRunWorkloadOnce = ParseJavaSourceTest::testRunWorkloadOnce;
this.payloads.testRunWorkloadTwice = ParseJavaSourceTest::testRunWorkloadTwice;
this.payloads.testRunWorkloadThrice = ParseJavaSourceTest::testRunWorkloadThrice;
}
}
}
| 37.207317 | 132 | 0.71452 |
6eeecb730189099fcef8ff0dfa11b9bf28a8696b | 644 | package leetcode;
/**
* https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/
*/
public class Problem1663 {
public String getSmallestString(int n, int k) {
char[] chars = new char[n];
int remaining = k;
for (int i = chars.length - 1; i >= 0; i--) {
int x = remaining - 26 - i;
if (x < 0) {
x = remaining - i;
chars[i] = (char) (x + 'a' - 1);
remaining -= x;
} else {
chars[i] = 'z';
remaining -= 'z' - 'a' + 1;
}
}
return new String(chars);
}
}
| 26.833333 | 76 | 0.439441 |
106f6538a4331b99b5ff023b83c533c1e3b0ade7 | 1,753 | package tests;
import java.io.FileWriter;
import java.io.IOException;
import mitl.MiTL;
import model.Trajectory;
import parsers.MitlFactory;
import rand.ApacheMT;
import ssa.CTMCModel;
import ssa.GillespieSSA;
import ssa.StochasticSimulationAlgorithm;
import biopepa.BiopepaFile;
public class TestSSA {
public static void main(String[] args) throws IOException {
compare_traj_timeseries();
}
public static void compare_traj_timeseries() throws IOException {
final String modelFile = "models/SIR.biopepa";
final String mitlText = "(F[100,120] I = 0) & ( G<=100 I > 0 )\n";
BiopepaFile bio = new BiopepaFile(modelFile);
CTMCModel model = bio.getModel();
StochasticSimulationAlgorithm ssa = new GillespieSSA(model);
long seed = 7642325;
seed = (long) (Math.random() * 10000000);
System.out.println("seed: " + seed);
ssa.setRandomEngine(new ApacheMT(seed));
Trajectory x = ssa.generateTrajectory(0, 200);
ssa.setRandomEngine(new ApacheMT(seed));
Trajectory y = ssa.generateTimeseries(0, 200, 100);
MitlFactory factory = new MitlFactory(model.getStateVariables());
MiTL mtl = factory.constructProperties(mitlText).getProperties().get(0);
FileWriter fw;
System.out.println("Trajectory:");
System.out.println("-----------");
System.out.println(x);
System.out.println(mtl);
System.out.println(mtl.evaluate(x, 0));
fw = new FileWriter("src/tests/SIR_trajectory.csv");
fw.write(x.toCSV());
fw.close();
System.out.println("\n");
System.out.println("Timeseries:");
System.out.println("-----------");
System.out.println(y);
System.out.println(mtl);
System.out.println(mtl.evaluate(y, 0));
fw = new FileWriter("src/tests/SIR_timeseries.csv");
fw.write(y.toCSV());
fw.close();
}
}
| 26.560606 | 74 | 0.710211 |
32decb005f4de96910973cc324478475f1909685 | 571 | package ru.dm.shop.service;
import ru.dm.shop.entity.SignupConfirmation;
import java.util.List;
/**
* Created by alt on 16.03.17.
*/
public interface SignupConfirmationService {
SignupConfirmation create(SignupConfirmation signupConfirmation);
SignupConfirmation delete(SignupConfirmation signupConfirmation);
SignupConfirmation delete(long id);
List<SignupConfirmation> findAll();
SignupConfirmation update(SignupConfirmation signupConfirmation);
SignupConfirmation findById(long id);
SignupConfirmation findByCode(String code);
}
| 22.84 | 69 | 0.782837 |
a08442561ae14d58ab38817348b259a11d7ffffa | 250 | class Dummy {
public static void main(String... args) {
if (args.length == 0) {
System.err.println("99 TSP - No input file");
System.exit(1);
}
System.out.println("99 TSP - Input file is " + args[0] + ".tsp or .xml");
}
}
| 25 | 77 | 0.564 |
e71ce26cd9739469fe3f1cd8b7472c78cd964092 | 1,144 | package org.cloudburstmc.protocol.java.codec.v754.serializer.play.clientbound;
import io.netty.buffer.ByteBuf;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.cloudburstmc.protocol.common.util.VarInts;
import org.cloudburstmc.protocol.java.codec.JavaCodecHelper;
import org.cloudburstmc.protocol.java.codec.JavaPacketSerializer;
import org.cloudburstmc.protocol.java.packet.play.clientbound.CooldownPacket;
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class CooldownSerializer_v754 implements JavaPacketSerializer<CooldownPacket> {
public static final CooldownSerializer_v754 INSTANCE = new CooldownSerializer_v754();
@Override
public void serialize(ByteBuf buffer, JavaCodecHelper helper, CooldownPacket packet) {
VarInts.writeUnsignedInt(buffer, packet.getItemId());
VarInts.writeUnsignedInt(buffer, packet.getCooldownTicks());
}
@Override
public void deserialize(ByteBuf buffer, JavaCodecHelper helper, CooldownPacket packet) {
packet.setItemId(VarInts.readUnsignedInt(buffer));
packet.setCooldownTicks(VarInts.readUnsignedInt(buffer));
}
}
| 42.37037 | 92 | 0.802448 |
ad7c49bca1d5d1edc40e94473b74b7a1f6afe483 | 2,816 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.inventario.util;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;
import java.util.Date;
import java.sql.Timestamp;
import org.hibernate.validator.*;
import com.bydan.framework.erp.business.entity.GeneralEntity;
import com.bydan.framework.erp.business.entity.GeneralEntityParameterReturnGeneral;
import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral;
import com.bydan.framework.erp.business.entity.Classe;
import com.bydan.framework.erp.business.dataaccess.ConstantesSql;
//import com.bydan.framework.erp.business.entity.Mensajes;
import com.bydan.framework.erp.util.Constantes;
import com.bydan.framework.erp.util.DeepLoadType;
import com.bydan.erp.inventario.util.ControlVehiculoConstantesFunciones;
import com.bydan.erp.inventario.business.entity.*;//ControlVehiculo
import com.bydan.erp.seguridad.business.entity.*;
@SuppressWarnings("unused")
public class ControlVehiculoParameterReturnGeneral extends GeneralEntityParameterReturnGeneral implements Serializable {
private static final long serialVersionUID=1L;
protected ControlVehiculo controlvehiculo;
protected List<ControlVehiculo> controlvehiculos;
public List<Empresa> empresasForeignKey;
public ControlVehiculoParameterReturnGeneral () throws Exception {
super();
this.controlvehiculos= new ArrayList<ControlVehiculo>();
this.controlvehiculo= new ControlVehiculo();
this.empresasForeignKey=new ArrayList<Empresa>();
}
public ControlVehiculo getControlVehiculo() throws Exception {
return controlvehiculo;
}
public void setControlVehiculo(ControlVehiculo newControlVehiculo) {
this.controlvehiculo = newControlVehiculo;
}
public List<ControlVehiculo> getControlVehiculos() throws Exception {
return controlvehiculos;
}
public void setControlVehiculos(List<ControlVehiculo> newControlVehiculos) {
this.controlvehiculos = newControlVehiculos;
}
public List<Empresa> getempresasForeignKey() {
return this.empresasForeignKey;
}
public void setempresasForeignKey(List<Empresa> empresasForeignKey) {
this.empresasForeignKey=empresasForeignKey;
}
}
| 31.640449 | 121 | 0.78267 |
539a0411021315385400df13c6d5a02fbe5b04e7 | 17,484 | import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class PacMan extends Shape {
/**
* Class which "controls" most of the in game happenings!
* Extends shape so that it's easier to make the level when setting up the stage
* If the game is paused or Pac eats a big cookie, the Timers within this class control the movements
* This was done so that the calls to "ancestor" classes, such as Playground, would be minimized
* @Note The TimerTasks are declared more than one times in this class because when timer.cancel()
* called, the TimerTasks are finalized, so they need to be redeclared
* @Note The ghosts' speeds are controlled by the slightly different refresh rates!
* However, it's always close to 60fps so it's crystal smooth ;)
*/
private ArrayList<BufferedImage> image;
private char direction;
private char wantedDirection;
private int imageModifier;
private int horOffset;
private int verOffset;
private int scoreMultiplier;
private Timer huntTimer, normalTimer, newTimer;
private boolean hunting;
public PacMan(int x, int y, int width, int height, Playground stage) {
super(x, y, width, height);
// this.state = state;
this.horOffset = 0;
this.verOffset = 0;
this.imageModifier = 0;
this.direction = 's'; // stand still
this.wantedDirection = 's'; // stand still
this.setStage(stage);
image = new ArrayList<>();
try {
this.image.add( 0, ImageIO.read(new File("PM0.gif")));
this.image.add( 1, ImageIO.read(new File("PMup1.gif")));
this.image.add( 2, ImageIO.read(new File("PMup2.gif")));
this.image.add( 3, ImageIO.read(new File("PMup3.gif")));
this.image.add( 4, ImageIO.read(new File("PM0.gif")));
this.image.add( 5, ImageIO.read(new File("PMdown1.gif")));
this.image.add( 6, ImageIO.read(new File("PMdown2.gif")));
this.image.add( 7, ImageIO.read(new File("PMdown3.gif")));
this.image.add( 8, ImageIO.read(new File("PM0.gif")));
this.image.add( 9, ImageIO.read(new File("PMleft1.gif")));
this.image.add(10, ImageIO.read(new File("PMleft2.gif")));
this.image.add(11, ImageIO.read(new File("PMleft3.gif")));
this.image.add(12, ImageIO.read(new File("PM0.gif")));
this.image.add(13, ImageIO.read(new File("PMright1.gif")));
this.image.add(14, ImageIO.read(new File("PMright2.gif")));
this.image.add(15, ImageIO.read(new File("PMright3.gif")));
} catch (IOException e) {
System.out.println("Error loading images! " + e.getMessage());
}
}
private boolean checkEdges(char direction, ArrayList<String> stage) {
int pacX, pacY;
char checked;
switch (direction) {
case ('u') :
pacX = this.getX() / 24;
pacY = (this.getY() - 1) / 24;
checked = stage.get(pacY).charAt(pacX);
if (checked == '#' || checked == '-') return false; // check upper left
pacX = (this.getX() + 23) / 24;
pacY = (this.getY() - 1) / 24;
checked = stage.get(pacY).charAt(pacX);
if (checked == '#' || checked == '-') return false; // check upper right
break;
case ('d') :
pacX = this.getX() / 24;
pacY = (this.getY() + 24) / 24;
checked = stage.get(pacY).charAt(pacX);
if (checked == '#' || checked == '-') return false; // check lower left
pacX = (this.getX() + 23) / 24;
pacY = (this.getY() + 24) / 24;
checked = stage.get(pacY).charAt(pacX);
if (stage.get(pacY).charAt(pacX) == '#') return false; // check lower right
break;
case ('l') :
pacX = (this.getX() - 1) / 24;
pacY = this.getY() / 24;
checked = stage.get(pacY).charAt(pacX);
if (stage.get(pacY).charAt(pacX) == '#') return false; // check upper left
pacX = (this.getX() - 1) / 24;
pacY = (this.getY() + 23) / 24;
checked = stage.get(pacY).charAt(pacX);
if (stage.get(pacY).charAt(pacX) == '#') return false; // check lower left
break;
case ('r') :
pacX = (this.getX() + 24) / 24;
pacY = this.getY() / 24;
checked = stage.get(pacY).charAt(pacX);
if (stage.get(pacY).charAt(pacX) == '#') return false; // check upper right
pacX = (this.getX() + 24) / 24;
pacY = (this.getY() + 23) / 24;
checked = stage.get(pacY).charAt(pacX);
if (stage.get(pacY).charAt(pacX) == '#') return false; // check lower right
break;
case ('s') :
return true;
}
return true;
}
public void stopTimers() {
Timer myTimer = getStage().getPacTimer();
myTimer.cancel();
myTimer.purge();
if (normalTimer != null) {
normalTimer.cancel();
normalTimer.purge();
}
if (newTimer != null) {
newTimer.cancel();
newTimer.purge();
}
if (huntTimer != null) {
huntTimer.cancel();
huntTimer.purge();
}
if (newTimer != null) {
newTimer.cancel();
newTimer.purge();
}
}
private void startHunt() {
scoreMultiplier = 1;
for (Ghost g : getStage().getGhosts()) {
g.setHunted(true);
g.setImageModifierOffset(2);
}
stopTimers();
Playground temp = getStage();
TimerTask refreshPac = new TimerTask() {
@Override
public void run() {
update();
temp.revalidate();
temp.repaint();
}
};
TimerTask refreshGhosts = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) g.update();
temp.revalidate();
temp.repaint();
}
};
TimerTask changeGhostPics = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) {
int im = g.getImageModifier();
g.setImageModifier((im + 1) % 2);
}
}
};
TimerTask changePacPic = new TimerTask() {
@Override
public void run() {
int im = getImageModifier();
setImageModifier((im + 1) % 4); // 4 images for each pac direction
}
};
huntTimer = new Timer();
huntTimer.schedule(refreshPac, 17, 17); // normal speed
huntTimer.schedule(refreshGhosts, 19, 19); // 10% slower -> .9 * normal_speed -> refresh per 19ms
huntTimer.schedule(changePacPic, 70, 70); // refresh pic every 70ms
huntTimer.schedule(changeGhostPics, 1000, 1000); // refresh pics every sec
}
private void endHunt() {
hunting = false;
for (Ghost g : getStage().getGhosts()) {
g.setHunted(false);
g.setImageModifierOffset(0);
}
stopTimers();
Playground temp = getStage();
TimerTask refreshPac = new TimerTask() {
@Override
public void run() {
update();
temp.revalidate();
temp.repaint();
}
};
TimerTask refreshGhosts = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) g.update();
temp.revalidate();
temp.repaint();
}
};
TimerTask changeGhostPics = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) {
int im = g.getImageModifier();
g.setImageModifier((im + 1) % 2);
}
}
};
TimerTask changePacPic = new TimerTask() {
@Override
public void run() {
// if (pac.getDirection() != 's') {
int im = getImageModifier();
setImageModifier((im + 1) % 4); // 4 images for each pac direction
// } // don't change pics if pac's still
}
};
normalTimer = new Timer();
normalTimer.schedule(refreshPac, 17, 17); // normal speed
if (getStage().getEatenCookies() >= Math.round(.6 * getStage().getTotalCookies()))
normalTimer.schedule(refreshGhosts, 13, 13); // 30% faster if close to end
else
normalTimer.schedule(refreshGhosts, 17, 17); // normal speed
normalTimer.schedule(changePacPic, 70, 70); // refresh pic every 70ms
normalTimer.schedule(changeGhostPics, 1000, 1000); // refresh pics every sec
}
public void startTimers() {
Playground temp = getStage();
TimerTask refreshPac = new TimerTask() {
@Override
public void run() {
update();
temp.revalidate();
temp.repaint();
}
};
TimerTask refreshGhosts = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) g.update();
temp.revalidate();
temp.repaint();
}
};
TimerTask changeGhostPics = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) {
int im = g.getImageModifier();
g.setImageModifier((im + 1) % 2);
}
}
};
TimerTask changePacPic = new TimerTask() {
@Override
public void run() {
int im = getImageModifier();
setImageModifier((im + 1) % 4); // 4 images for each pac direction
}
};
normalTimer = new Timer();
normalTimer.schedule(refreshPac, 17, 17); // normal speed
if (getStage().getEatenCookies() >= Math.round(.6 * getStage().getTotalCookies()))
normalTimer.schedule(refreshGhosts, 13, 13); // 30% faster if close to end
else
normalTimer.schedule(refreshGhosts, 17, 17); // normal speed
normalTimer.schedule(changePacPic, 70, 70); // refresh pic every 70ms
normalTimer.schedule(changeGhostPics, 1000, 1000); // refresh pics every sec
}
private void checkCookies(char direction, ArrayList<String> stage, ArrayList<ArrayList<Shape>> level) {
int pacX, pacY;
char[] temp;
MainWindow rootWindow;
pacX = (this.getX() + 12) / 24; pacY = (this.getY() + 12) / 24; // middle of the pac block
if (stage.get(pacY).charAt(pacX) == '.') {
temp = stage.get(pacY).toCharArray();
temp[pacX] = ' ';
stage.set(pacY, String.valueOf(temp));
Space sp = new Space(24 * pacX, 24 * pacY, 23, 23);
level.get(pacY).set(pacX, sp); // place Space in place of cookie (Circle)
PlayerInfo tmpPi = getStage().getPlayerInfo(); // increases score when simple cookie is eaten
tmpPi.setScore(tmpPi.getScore() + 10); // small cookies are worth 10 points each
getStage().setEatenCookies(getStage().getEatenCookies() + 1);
if (getStage().getEatenCookies() == Math.round(.6 * getStage().getTotalCookies()))
accelerateGhosts();
rootWindow = getStage().getRoot();
if (getStage().getEatenCookies() == getStage().getTotalCookies()) {
// if (getStage().getEatenCookies() == 3) {
if (rootWindow.getCurrentStage() == rootWindow.getNumOfLevels()) {
rootWindow.declareSuccess();
return;
}
rootWindow.setCurrentStage(rootWindow.getCurrentStage() + 1); // next stage number
rootWindow.loadStage(rootWindow.getCurrentStage() + 1); // success, load next
}
}
if (stage.get(pacY).charAt(pacX) == 'o') {
temp = stage.get(pacY).toCharArray();
temp[pacX] = ' ';
stage.set(pacY, String.valueOf(temp));
Space sp = new Space(24 * pacX, 24 * pacY, 23, 23);
level.get(pacY).set(pacX, sp); // place Space in place of cookie (Circle)
PlayerInfo tmpPi = getStage().getPlayerInfo(); // increases score when simple cookie is eaten
tmpPi.setScore(tmpPi.getScore() + 50); // big cookies are worth 50 points each
startHunt(); // get huntin
Timer huntTimer = new Timer();
huntTimer.schedule(new TimerTask() {
@Override
public void run() {
endHunt();
}
}, 7000); // end hunt after 7 seconds!
}
}
private void accelerateGhosts() {
stopTimers();
Playground temp = getStage();
TimerTask refreshPac = new TimerTask() {
@Override
public void run() {
update();
temp.revalidate();
temp.repaint();
}
};
TimerTask refreshGhosts = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) g.update();
temp.revalidate();
temp.repaint();
}
};
TimerTask changeGhostPics = new TimerTask() {
@Override
public void run() {
for (Ghost g : getStage().getGhosts()) {
int im = g.getImageModifier();
g.setImageModifier((im + 1) % 2);
}
}
};
TimerTask changePacPic = new TimerTask() {
@Override
public void run() {
// if (pac.getDirection() != 's') {
int im = getImageModifier();
setImageModifier((im + 1) % 4); // 4 images for each pac direction
// } // don't change pics if pac's still
}
};
newTimer = new Timer();
newTimer.schedule(refreshPac, 17, 17); // normal speed
newTimer.schedule(refreshGhosts, 13, 13); // 30% faster -> 1.3 * normal_speed -> refresh per 13ms
newTimer.schedule(changePacPic, 70, 70); // refresh pic every 70ms
newTimer.schedule(changeGhostPics, 1000, 1000); // refresh pics every sec
}
private void setOffSets(char wantedDirection) {
switch (wantedDirection) {
case ('u') :
setHorOffset(0);
setVerOffset(-1);
break;
case ('d') :
setHorOffset(0);
setVerOffset(+1);
break;
case ('l') :
setHorOffset(-1);
setVerOffset(0);
break;
case ('r') :
setHorOffset(+1);
setVerOffset(0);
break;
case ('s') :
setHorOffset(0);
setVerOffset(0);
}
}
public void update() {
int x = this.getX();
int y = this.getY();
if (checkEdges(this.wantedDirection, getStage().getPg())) {
this.setDirection(this.wantedDirection);
setOffSets(this.wantedDirection);
}
else if (checkEdges(this.direction, getStage().getPg()))
setOffSets(this.direction);
else {
this.setDirection('s');
setOffSets(this.direction);
}
this.setX(x + horOffset);
this.setY(y + verOffset);
checkCookies(this.direction, getStage().getPg(), getStage().getLevel());
}
public int getScoreMultiplier() {
return scoreMultiplier;
}
public void setScoreMultiplier(int scoreMultiplier) {
this.scoreMultiplier = scoreMultiplier;
}
public ArrayList<BufferedImage> getImage() {
return image;
}
public char getDirection() {
return direction;
}
public int getImageModifier() {
return imageModifier;
}
public void setImageModifier(int imageModifier) {
this.imageModifier = imageModifier;
}
public void setDirection(char direction) {
this.direction = direction;
}
public void setWantedDirection(char wantedDirection) {
this.wantedDirection = wantedDirection;
}
public void setVerOffset(int verOffset) {
this.verOffset = verOffset;
}
public void setHorOffset(int horOffset) {
this.horOffset = horOffset;
}
@Override
public void draw(Graphics g) {} // empty because we just need to draw the pacman image!
}
| 37.681034 | 107 | 0.518989 |
eb8de6da19891cd2ddca7de299697880e99800ad | 7,398 | package ca.gc.ip346.classification.resource;
import static javax.ws.rs.HttpMethod.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
// import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.media.multipart.FormDataParam;
import ca.gc.ip346.classification.model.Ruleset;
import ca.gc.ip346.util.ClassificationProperties;
import ca.gc.ip346.util.RequestURL;
@Path("")
public class UploadRESTService {
// import static org.apache.logging.log4j.Level.*;
private static final Logger logger = LogManager.getLogger(UploadRESTService.class);
private static final String RULESETS_ROOT = "dtables";
private static final String SLASH = "/";
private static final String EXTENSION = ".xls";
@Context
private HttpServletRequest request;
// @OPTIONS
// @Path("/upload")
// @Consumes(MediaType.MULTIPART_FORM_DATA)
// @Produces(MediaType.APPLICATION_JSON)
// public Response uploadFilePreflight() {
// Map<String, String> msg = new HashMap<String, String>();
// msg.put("message", "upload REST service pre-flight");
// return FoodsResource.getResponse(OPTIONS, Response.Status.OK, msg);
// }
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(@BeanParam Ruleset bean, @FormDataParam("rulesetname") String rulesetname) {
String target = buildTarget();
Map<?, ?> externalPath = (Map<?, ?>)getRulesetsHome().getEntity();
String home = externalPath.get("rulesetshome").toString().replaceAll("^\\/", "").replaceAll("\\/$", "");
Map<?, ?> availableSlot = (Map<?, ?>)getAvailableSlot().getEntity();
if (availableSlot.get("slot") == null) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "No ruleset slots available");
return FoodsResource.getResponse(POST, Response.Status.OK, msg);
}
String slot = availableSlot.get("slot").toString();
// if (bean.getRefamtZ() == null || bean.getFopZ() == null || bean.getShortcutZ() == null || bean.getThresholdsZ() == null || bean.getInitZ() == null || bean.getTierZ() == null) {
// Map<String, String> msg = new HashMap<String, String>();
// msg.put("message", "Files appear to be of the wrong media-type");
// return FoodsResource.getResponse(POST, Response.Status.UNSUPPORTED_MEDIA_TYPE, msg);
// }
Map<String, InputStream> streams = new HashMap<String, InputStream>();
if (bean.getRefamtZ() != null) streams.put(bean.getRefamtZ() .getName(), bean.getRefamt());
if (bean.getFopZ() != null) streams.put(bean.getFopZ() .getName(), bean.getFop());
if (bean.getShortcutZ() != null) streams.put(bean.getShortcutZ() .getName(), bean.getShortcut());
if (bean.getThresholdsZ() != null) streams.put(bean.getThresholdsZ() .getName(), bean.getThresholds());
if (bean.getInitZ() != null) streams.put(bean.getInitZ() .getName(), bean.getInit());
if (bean.getTierZ() != null) streams.put(bean.getTierZ() .getName(), bean.getTier());
// logger.debug("[01;03;34m" + "Empty: " + bean .isRefamtEmpty() + "[00;00;00m");
// logger.debug("[01;03;31m" + "Empty: " + bean .isFopEmpty() + "[00;00;00m");
// logger.debug("[01;03;34m" + "Empty: " + bean .isShortcutEmpty() + "[00;00;00m");
// logger.debug("[01;03;31m" + "Empty: " + bean .isThresholdsEmpty() + "[00;00;00m");
// logger.debug("[01;03;34m" + "Empty: " + bean .isInitEmpty() + "[00;00;00m");
// logger.debug("[01;03;31m" + "Empty: " + bean .isTierEmpty() + "[00;00;00m");
// if (bean.isRefamtEmpty() || bean.isFopEmpty() || bean.isShortcutEmpty() || bean.isThresholdsEmpty() || bean.isInitEmpty() || bean.isTierEmpty()) {
if (bean.getRefamtZ() == null || bean.getFopZ() == null || bean.getShortcutZ() == null || bean.getThresholdsZ() == null || bean.getInitZ() == null || bean.getTierZ() == null) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "All files need to be selected");
return FoodsResource.getResponse(POST, Response.Status.BAD_REQUEST, msg);
}
for (String rule : streams.keySet()) {
OutputStream outputStream = null;
String filePath = SLASH + home + SLASH + RULESETS_ROOT + SLASH + rule + SLASH + slot + SLASH + rule + slot + EXTENSION;
try {
int read = 0;
byte[] bytes = new byte[1024];
outputStream = new FileOutputStream(new File(filePath));
while ((read = streams.get(rule).read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
} catch(FileNotFoundException e) {
Map<String, String> msg = new HashMap<String, String>();
msg.put("message", "Tomcat account needs permissions to write to filesystem");
logger.debug("[01;03;35m" + msg.get("message") + "[00;00;00m");
return FoodsResource.getResponse(POST, Response.Status.UNAUTHORIZED, msg);
} catch(IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Map<String, Object> ruleset = new HashMap<String, Object>();
ruleset.put("active", true);
ruleset.put("isProd", false);
if (rulesetname == null || rulesetname.trim().isEmpty()) {
Date date = new Date();
rulesetname = date.toString();
}
ruleset.put("name", rulesetname);
ruleset.put("rulesetId", Integer.valueOf(slot));
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesets")
.request()
.post(Entity.entity(ruleset, MediaType.APPLICATION_JSON));
return FoodsResource.getResponse(POST, Response.Status.OK, response.readEntity(Object.class));
}
public Response getRulesetsHome() {
String target = buildTarget();
Response response = ClientBuilder
.newClient()
.target(target)
.path("/rulesetshome")
.request()
.get();
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
}
public Response getAvailableSlot() {
String target = buildTarget();
Response response = ClientBuilder
.newClient()
.target(target)
.path("/slot")
.request()
.get();
return FoodsResource.getResponse(GET, Response.Status.OK, response.readEntity(Object.class));
}
private String buildTarget() {
if ((request.getServerPort() == 80) || (request.getServerPort() == 443)) {
return RequestURL.getHost() + ClassificationProperties.getEndPoint();
} else if ((request.getServerPort() == 8080) || (request.getServerPort() == 8443)) {
return RequestURL.getHost() + ":8080" + /* request.getServerPort() + */ ClassificationProperties.getEndPoint();
}
return RequestURL.getAddr() + ClassificationProperties.getEndPoint();
}
}
| 39.989189 | 181 | 0.679102 |
e58a85c8d18cf185dac429edc7615d1929a727c7 | 4,707 | /*
* Sender - Testing topics support with AMQP 1.0 brokers
*/
package test;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.commons.cli.*;
import java.util.Hashtable;
import org.apache.qpid.jms.JmsTopic;
public class TopicSender {
private static final int DELIVERY_MODE = DeliveryMode.NON_PERSISTENT;
private static final String usr = "test";
private static final String pwd = "test";
public static void main(String[] args) throws Exception {
String port = "5675";
String node = "croads";
Options options = new Options();
Option op2 = new Option("p", "port", true, "port to connect to");
op2.setRequired(false);
options.addOption(op2);
Option op4 = new Option("h", "help", false, "help");
op4.setRequired(false);
options.addOption(op4);
Option op3 = new Option("n", "node", true, "node (i.e. exchange, queue, ...)");
op2.setRequired(false);
options.addOption(op3);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
port = cmd.getOptionValue("p", "5675");
node = cmd.getOptionValue("n", node);
if ( cmd.hasOption( "help" ) ) {
formatter.printHelp("Sender", options);
System.exit(1);
}
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("Sender", options);
System.exit(1);
}
String conn_str = "amqp://localhost:" + port;
try {
// set up JNDI context
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("connectionfactory.myFactoryLookup", conn_str );
hashtable.put("topic.myTopicLookup", node);
hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
Context context = new InitialContext(hashtable);
ConnectionFactory factory = (ConnectionFactory) context.lookup("myFactoryLookup");
Connection connection = factory.createConnection(usr, pwd);
connection.setClientID("java-sender");
connection.setExceptionListener(new MyExceptionListener());
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
System.out.println("connection_open: "+conn_str);
System.out.println("node: "+node);
String[] nat = {"it", "at", "at", "it", "it"};
String[] prod = {"a22", "xyz", "xyz", "a22", "a22"};
String[] type = {"asn1", "datex", "asn1", "asn1", "asn1"};
String[] det = {"denm", "ivim", "denm", "ivim", "denm"};
String[] geo = {"u0j2ws2", "", "", "u0j2x5z", "u0j8rkm"};
System.out.println("sending messages..."+nat.length);
long start = System.currentTimeMillis();
for (int i = 0; i < nat.length; i++) {
String body = "test"+(i+1);
TextMessage message = session.createTextMessage(body);
message.setStringProperty("nat", nat[i]);
message.setStringProperty("prod", prod[i]);
message.setStringProperty("type", type[i]);
message.setStringProperty("det", det[i]);
message.setStringProperty("geo", geo[i]);
String topic = nat[i]+"."+prod[i]+"."+type[i]+"."+det[i];
if (geo[i] != null) {
String[] chars = geo[i].split("");
String geoTopic = geo[i].substring(0, Math.min(4, geo[i].length()));
for (int k = 4; k < chars.length; k++) {
geoTopic += "."+chars[k];
}
topic += "."+geoTopic;
}
System.out.println(i + "-sent: " + body + ", topic: " + node+"/"+topic);
topicSend(node+"/"+topic, message, session);
}
long finish = System.currentTimeMillis();
long taken = finish - start;
System.out.println("Sent " + nat.length + " messages in " + taken + "ms");
connection.close();
} catch (Exception exp) {
System.out.println("Caught exception, exiting.");
exp.printStackTrace(System.out);
System.exit(1);
}
}
public static void topicSend(String topic, Message message, Session session) throws Exception {
MessageProducer messageProducer = session.createProducer(new JmsTopic(topic));
messageProducer.send(message, DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);
messageProducer.close();
}
private static class MyExceptionListener implements ExceptionListener {
@Override
public void onException(JMSException exception) {
System.out.println("Connection ExceptionListener fired, exiting.");
exception.printStackTrace(System.out);
System.exit(1);
}
}
}
| 32.239726 | 103 | 0.682175 |
3fd26ec84fef6281a48a56c3afe2bbeaa4ef937e | 3,119 | /*
* MIT License
*
* Copyright (c) 2019 Udo Borkowski, (ub@abego.org)
*
* 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.
*/
/**
* Easily write GUI Tests in Java (for Swing).
* <p>
* Use the abego GuiTesting Swing library to quickly write GUI tests for Swing
* applications in the same way you write "headless" JUnit tests.
* <p>
* <b>The GT Interface</b>
* <p>
* GUITesting Swing provides most of its features through the
* {@link org.abego.guitesting.swing.GT} interface.
* The interface covers many areas related to GUI testing,
* like dealing with windows or components, using input devices like
* keyboard or mouse, checking test results with GUI specific
* "assert..." methods and many more.
* <p>
* <b>Example</b>
* <p>
* A typical code snippet using {@link org.abego.guitesting.swing.GT} may look
* like this:
* <pre>
* import static org.abego.guitesting.swing.GuiTesting.newGT;
*
* ...
*
* // A GT instance is the main thing we need when testing GUI code.
* GT gt = newGT();
*
* // run some application code that opens a window
* openSampleWindow();
*
* // In that window we are interested in a JTextField named "input"
* JTextField input = gt.waitForComponentNamed(JTextField.class, "input");
*
* // we move the focus to that input field and type "Your name" ", please!"
* gt.setFocusOwner(input);
* gt.type("Your name");
* gt.type(", please!");
*
* // Verify if the text field really contains the expected text.
* gt.assertEqualsRetrying("Your name, please!", input::getText);
*
* // When we are done with our tests we can ask GT to cleanup
* // (This will dispose open windows etc.)
* gt.cleanup();
* </pre>
* <b>Unit Testing</b>
* <p>
* When writing JUnit tests you may want to subclass from
* {@link org.abego.guitesting.swing.GuiTestBase}.
* <p>
* <b>Sample Code</b>
* <p>
* For samples how to use the GUITesting Swing library have a look at the
* test code of this project, in the {@code src/test/java} folder.
*/
@NonNullByDefault
package org.abego.guitesting.swing;
import org.eclipse.jdt.annotation.NonNullByDefault; | 37.130952 | 81 | 0.716896 |
9f071f1dd036c9168a1486f355d7431475822d68 | 4,317 | /*
* Copyright 2018 Key Bridge.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadbandforum.tr069.internetgatewaydevice;
import java.util.ArrayList;
import java.util.Collection;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.broadbandforum.annotation.CWMPObject;
import org.broadbandforum.annotation.CWMPParameter;
import org.broadbandforum.tr069.internetgatewaydevice.layer3forwarding.Forwarding;
/**
* This object allows the handling of the routing and forwarding configuration of the device.
*
* @since TR069 v1.0
*/
@CWMPObject(name = "InternetGatewayDevice.Layer3Forwarding.")
@XmlRootElement(name = "InternetGatewayDevice.Layer3Forwarding")
@XmlType(name = "InternetGatewayDevice.Layer3Forwarding")
@XmlAccessorType(XmlAccessType.FIELD)
public class Layer3Forwarding {
/**
* Specifies the default WAN interface. The content is the full hierarchical parameter name of the default layer-3 connection object. Example: ''InternetGatewayDevice.WANDevice.1.WANConnectionDevice.2.WANPPPConnection.1''.
*
* @since 1.0
*/
@XmlElement(name = "DefaultConnectionService")
@CWMPParameter(access = "readWrite")
@Size(max = 256)
public String defaultConnectionService;
/**
* Layer-3 forwarding table.
*/
@XmlElementWrapper(name = "Forwardings")
@XmlElement(name = "Forwarding")
@CWMPParameter(access = "readWrite")
public Collection<Forwarding> forwardings;
public Layer3Forwarding() {
}
//<editor-fold defaultstate="collapsed" desc="Getter and Setter">
/**
* Get the specifies the default WAN interface. The content is the full hierarchical parameter name of the default layer-3 connection object. Example: ''InternetGatewayDevice.WANDevice.1.WANConnectionDevice.2.WANPPPConnection.1''.
*
* @since 1.0
* @return the value
*/
public String getDefaultConnectionService() {
return defaultConnectionService;
}
/**
* Set the specifies the default WAN interface. The content is the full hierarchical parameter name of the default layer-3 connection object. Example: ''InternetGatewayDevice.WANDevice.1.WANConnectionDevice.2.WANPPPConnection.1''.
*
* @since 1.0
* @param defaultConnectionService the input value
*/
public void setDefaultConnectionService(String defaultConnectionService) {
this.defaultConnectionService = defaultConnectionService;
}
/**
* Set the specifies the default WAN interface. The content is the full hierarchical parameter name of the default layer-3 connection object. Example: ''InternetGatewayDevice.WANDevice.1.WANConnectionDevice.2.WANPPPConnection.1''.
*
* @since 1.0
* @param defaultConnectionService the input value
* @return this instance
*/
public Layer3Forwarding withDefaultConnectionService(String defaultConnectionService) {
this.defaultConnectionService = defaultConnectionService;
return this;
}
/**
* Get the layer-3 forwarding table.
*
* @return the value
*/
public Collection<Forwarding> getForwardings() {
if (this.forwardings == null){ this.forwardings=new ArrayList<>();}
return forwardings;
}
/**
* Set the layer-3 forwarding table.
*
* @param forwardings the input value
*/
public void setForwardings(Collection<Forwarding> forwardings) {
this.forwardings = forwardings;
}
/**
* Set the layer-3 forwarding table.
*
* @param forwarding the input value
* @return this instance
*/
public Layer3Forwarding withForwarding(Forwarding forwarding) {
getForwardings().add(forwarding);
return this;
}
//</editor-fold>
} | 33.992126 | 233 | 0.763262 |
b58855bd7da11d468395ef4bb8145ddab3580796 | 4,590 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.plugin.hive.containers;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.google.common.collect.ImmutableMap;
import io.trino.testing.containers.Minio;
import io.trino.util.AutoCloseableCloser;
import org.testcontainers.containers.Network;
import java.util.Map;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.testcontainers.containers.Network.newNetwork;
public class HiveMinioDataLake
implements AutoCloseable
{
public static final String ACCESS_KEY = "accesskey";
public static final String SECRET_KEY = "secretkey";
private final String bucketName;
private final Minio minio;
private final HiveHadoop hiveHadoop;
private final AutoCloseableCloser closer = AutoCloseableCloser.create();
private State state = State.INITIAL;
private AmazonS3 s3Client;
public HiveMinioDataLake(String bucketName, Map<String, String> hiveHadoopFilesToMount)
{
this(bucketName, hiveHadoopFilesToMount, HiveHadoop.DEFAULT_IMAGE);
}
public HiveMinioDataLake(String bucketName, Map<String, String> hiveHadoopFilesToMount, String hiveHadoopImage)
{
this.bucketName = requireNonNull(bucketName, "bucketName is null");
Network network = closer.register(newNetwork());
this.minio = closer.register(
Minio.builder()
.withNetwork(network)
.withEnvVars(ImmutableMap.<String, String>builder()
.put("MINIO_ACCESS_KEY", ACCESS_KEY)
.put("MINIO_SECRET_KEY", SECRET_KEY)
.buildOrThrow())
.build());
this.hiveHadoop = closer.register(
HiveHadoop.builder()
.withFilesToMount(ImmutableMap.<String, String>builder()
.put("hive_s3_insert_overwrite/hive-core-site.xml", "/etc/hadoop/conf/core-site.xml")
.putAll(hiveHadoopFilesToMount)
.buildOrThrow())
.withImage(hiveHadoopImage)
.withNetwork(network)
.build());
}
public void start()
{
checkState(state == State.INITIAL, "Already started: %s", state);
state = State.STARTING;
minio.start();
hiveHadoop.start();
s3Client = AmazonS3ClientBuilder
.standard()
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
"http://localhost:" + minio.getMinioApiEndpoint().getPort(),
"us-east-1"))
.withPathStyleAccessEnabled(true)
.withCredentials(new AWSStaticCredentialsProvider(
new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)))
.build();
s3Client.createBucket(this.bucketName);
closer.register(() -> s3Client.shutdown());
state = State.STARTED;
}
public AmazonS3 getS3Client()
{
checkState(state == State.STARTED, "Can't provide client when MinIO state is: %s", state);
return s3Client;
}
public void stop()
throws Exception
{
closer.close();
state = State.STOPPED;
}
public Minio getMinio()
{
return minio;
}
public HiveHadoop getHiveHadoop()
{
return hiveHadoop;
}
public String getBucketName()
{
return bucketName;
}
@Override
public void close()
throws Exception
{
stop();
}
private enum State
{
INITIAL,
STARTING,
STARTED,
STOPPED,
}
}
| 33.26087 | 117 | 0.629412 |
e77e7b88800e82556b28395a4530d0161b3621f3 | 3,154 | /*
*
* MIT License
*
* Copyright (c) 2017 朱辉 https://blog.yeetor.com
*
* 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 com.yeetor.server.handler;
import com.yeetor.server.HttpServer;
import com.yeetor.util.Constant;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
public class HTTPHandler extends SimpleChannelInboundHandler<Object> {
HttpServer server;
public HTTPHandler(HttpServer server) {
this.server = server;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof HttpRequest)) {
throw new IllegalArgumentException("Not a http request!");
}
HttpRequest request = (HttpRequest) msg;
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
boolean isKeepAlive = HttpUtil.isKeepAlive(request);
response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Server", "Yeetor");
server.onRequest(ctx, request, response);
// HttpResponse response = server.onRequest(ctx, request);
// if (response == null) {
// return;
// }
// if (isKeepAlive) {
// response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
// } else {
// ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
// }
// ctx.writeAndFlush(response);
}
}
| 37.105882 | 101 | 0.716867 |
8efdb88fb9a0a4a0b66434a1014693fc115c92c4 | 3,447 | package com.jlfex.hermes.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.jlfex.hermes.common.dict.Dicts;
import com.jlfex.hermes.common.dict.Element;
/**
* 借款审核信息模型
*/
@Entity
@Table(name = "hm_loan_audit")
public class LoanAudit extends Model {
private static final long serialVersionUID = 6837844941000452215L;
/** 借款 */
@ManyToOne
@JoinColumn(name = "loan")
private Loan loan;
/** 审核人 */
@Column(name = "auditor")
private String auditor;
/** 日期 */
@Column(name = "datetime")
private Date datetime;
/** 备注 */
@Column(name = "remark")
private String remark;
/** 状态 */
@Column(name = "status")
private String status;
/** 类型 */
@Column(name = "type")
private String type;
/** 审核前金额 */
@Column(name = "audit_before_amount")
private BigDecimal auditBeforeamount;
/** 审核后金额 */
@Column(name = "audit_after_amount")
private BigDecimal auditAfteramount;
/**
* 读取借款
*
* @return
* @see #loan
*/
public Loan getLoan() {
return loan;
}
/**
* 设置借款
*
* @param loan
* @see #loan
*/
public void setLoan(Loan loan) {
this.loan = loan;
}
/**
* 读取审核人
*
* @return
* @see #auditor
*/
public String getAuditor() {
return auditor;
}
/**
* 设置审核人
*
* @param auditor
* @see #auditor
*/
public void setAuditor(String auditor) {
this.auditor = auditor;
}
/**
* 读取日期
*
* @return
* @see #datetime
*/
public Date getDatetime() {
return datetime;
}
/**
* 设置日期
*
* @param datetime
* @see #datetime
*/
public void setDatetime(Date datetime) {
this.datetime = datetime;
}
/**
* 读取备注
*
* @return
* @see #remark
*/
public String getRemark() {
return remark;
}
/**
* 设置备注
*
* @param remark
* @see #remark
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 读取状态
*
* @return
* @see #status
*/
public String getStatus() {
return status;
}
/**
* 设置状态
*
* @param status
* @see #status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* 读取类型
*
* @return
* @see #type
*/
public String getType() {
return type;
}
/**
* 设置类型
*
* @param type
* @see #type
*/
public void setType(String type) {
this.type = type;
}
/**
* @return description:取得类型名称
*/
public String getTypeName() {
return Dicts.name(type, type, Type.class);
}
/**
* @return description:取得状态名称
*/
public String getStatusName() {
return Dicts.name(status, status, Status.class);
}
public BigDecimal getAuditBeforeamount() {
return auditBeforeamount;
}
public void setAuditBeforeamount(BigDecimal auditBeforeamount) {
this.auditBeforeamount = auditBeforeamount;
}
public BigDecimal getAuditAfteramount() {
return auditAfteramount;
}
public void setAuditAfteramount(BigDecimal auditAfteramount) {
this.auditAfteramount = auditAfteramount;
}
/**
* 审核类型
*/
public static final class Type {
@Element("初审")
public static final String FIRST_AUDIT = "00";
@Element("终审")
public static final String FINALL_AUDIT = "01";
}
/**
* 审核结果
*/
public static final class Status {
@Element("通过")
public static final String PASS = "00";
@Element("驳回")
public static final String REJECT = "01";
}
}
| 15.052402 | 67 | 0.637076 |
ba0526284181df56b01a0b0af5aa6e8c8e76ea1f | 4,161 | /*
* Copyright 2020 White Magic Software, Ltd.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o 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.
*
* 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
* HOLDER 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.
*/
package com.whitemagicsoftware.kmcaster.listeners;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
* Responsible for notifying its list of managed listeners when property
* change events have occurred. The change events will only be fired if the
* new value differs from the old value.
*
* @param <P> Type of property that, when changed, will try to issue a change
* event to any listeners.
*/
public abstract class PropertyDispatcher<P> {
/**
* Calling {@link PropertyChangeSupport#getPropertyChangeListeners()} creates
* a new list every time. Calls to add listeners are only performed during
* setup, so this is a micro-optimization to avoid recreating the list on
* each event fired.
*/
private PropertyChangeListener[] mListeners;
private final PropertyChangeSupport mDispatcher =
new PropertyChangeSupport( this );
/**
* Adds a new listener to the internal dispatcher. The dispatcher uses a map,
* so calling this multiple times for the same listener will not result in
* the same listener receiving multiple notifications for one event.
*
* @param listener The class to notify when property values change, a value
* of {@code null} will have no effect.
*/
public void addPropertyChangeListener(
final PropertyChangeListener listener ) {
mDispatcher.addPropertyChangeListener( listener );
mListeners = mDispatcher.getPropertyChangeListeners();
}
/**
* Called to fire the property change with the two given values differ.
* Normally events for the same old and new value are swallowed silently,
* which prevents double-key presses from bubbling up. Tracking double-key
* presses is used to increment a counter that is displayed on the key when
* the user continually types the same regular key.
*
* @param p Property name that has changed.
* @param o Old property value.
* @param n New property value.
*/
protected void fire( final P p, final String o, final String n ) {
final var pName = p.toString();
final var event = new PropertyChangeEvent( mDispatcher, pName, o, n );
for( final var listener : mListeners ) {
listener.propertyChange( event );
}
}
/**
* Delegates to {@link #fire(P, String, String)} with {@link Boolean} values
* as strings. If the old and new values are the same, this will not send
* the event.
*
* @param p Property name that has changed.
* @param o Old property value.
* @param n New property value.
*/
protected void tryFire( final P p, final boolean o, final boolean n ) {
if( o != n ) {
fire( p, Boolean.toString( o ), Boolean.toString( n ) );
}
}
}
| 40.398058 | 79 | 0.724826 |
93b4f021377829552919e5aff602b9beadaed2e2 | 7,202 | /*
* This file is generated by jOOQ.
*/
package com.epam.ta.reportportal.jooq.tables.records;
import com.epam.ta.reportportal.jooq.tables.JAclObjectIdentity;
import javax.annotation.processing.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record6;
import org.jooq.Row6;
import org.jooq.impl.UpdatableRecordImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.12.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class JAclObjectIdentityRecord extends UpdatableRecordImpl<JAclObjectIdentityRecord> implements Record6<Long, Long, String, Long, Long, Boolean> {
private static final long serialVersionUID = 1370439583;
/**
* Setter for <code>public.acl_object_identity.id</code>.
*/
public void setId(Long value) {
set(0, value);
}
/**
* Getter for <code>public.acl_object_identity.id</code>.
*/
public Long getId() {
return (Long) get(0);
}
/**
* Setter for <code>public.acl_object_identity.object_id_class</code>.
*/
public void setObjectIdClass(Long value) {
set(1, value);
}
/**
* Getter for <code>public.acl_object_identity.object_id_class</code>.
*/
public Long getObjectIdClass() {
return (Long) get(1);
}
/**
* Setter for <code>public.acl_object_identity.object_id_identity</code>.
*/
public void setObjectIdIdentity(String value) {
set(2, value);
}
/**
* Getter for <code>public.acl_object_identity.object_id_identity</code>.
*/
public String getObjectIdIdentity() {
return (String) get(2);
}
/**
* Setter for <code>public.acl_object_identity.parent_object</code>.
*/
public void setParentObject(Long value) {
set(3, value);
}
/**
* Getter for <code>public.acl_object_identity.parent_object</code>.
*/
public Long getParentObject() {
return (Long) get(3);
}
/**
* Setter for <code>public.acl_object_identity.owner_sid</code>.
*/
public void setOwnerSid(Long value) {
set(4, value);
}
/**
* Getter for <code>public.acl_object_identity.owner_sid</code>.
*/
public Long getOwnerSid() {
return (Long) get(4);
}
/**
* Setter for <code>public.acl_object_identity.entries_inheriting</code>.
*/
public void setEntriesInheriting(Boolean value) {
set(5, value);
}
/**
* Getter for <code>public.acl_object_identity.entries_inheriting</code>.
*/
public Boolean getEntriesInheriting() {
return (Boolean) get(5);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Long> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record6 type implementation
// -------------------------------------------------------------------------
@Override
public Row6<Long, Long, String, Long, Long, Boolean> fieldsRow() {
return (Row6) super.fieldsRow();
}
@Override
public Row6<Long, Long, String, Long, Long, Boolean> valuesRow() {
return (Row6) super.valuesRow();
}
@Override
public Field<Long> field1() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.ID;
}
@Override
public Field<Long> field2() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.OBJECT_ID_CLASS;
}
@Override
public Field<String> field3() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.OBJECT_ID_IDENTITY;
}
@Override
public Field<Long> field4() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.PARENT_OBJECT;
}
@Override
public Field<Long> field5() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.OWNER_SID;
}
@Override
public Field<Boolean> field6() {
return JAclObjectIdentity.ACL_OBJECT_IDENTITY.ENTRIES_INHERITING;
}
@Override
public Long component1() {
return getId();
}
@Override
public Long component2() {
return getObjectIdClass();
}
@Override
public String component3() {
return getObjectIdIdentity();
}
@Override
public Long component4() {
return getParentObject();
}
@Override
public Long component5() {
return getOwnerSid();
}
@Override
public Boolean component6() {
return getEntriesInheriting();
}
@Override
public Long value1() {
return getId();
}
@Override
public Long value2() {
return getObjectIdClass();
}
@Override
public String value3() {
return getObjectIdIdentity();
}
@Override
public Long value4() {
return getParentObject();
}
@Override
public Long value5() {
return getOwnerSid();
}
@Override
public Boolean value6() {
return getEntriesInheriting();
}
@Override
public JAclObjectIdentityRecord value1(Long value) {
setId(value);
return this;
}
@Override
public JAclObjectIdentityRecord value2(Long value) {
setObjectIdClass(value);
return this;
}
@Override
public JAclObjectIdentityRecord value3(String value) {
setObjectIdIdentity(value);
return this;
}
@Override
public JAclObjectIdentityRecord value4(Long value) {
setParentObject(value);
return this;
}
@Override
public JAclObjectIdentityRecord value5(Long value) {
setOwnerSid(value);
return this;
}
@Override
public JAclObjectIdentityRecord value6(Boolean value) {
setEntriesInheriting(value);
return this;
}
@Override
public JAclObjectIdentityRecord values(Long value1, Long value2, String value3, Long value4, Long value5, Boolean value6) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached JAclObjectIdentityRecord
*/
public JAclObjectIdentityRecord() {
super(JAclObjectIdentity.ACL_OBJECT_IDENTITY);
}
/**
* Create a detached, initialised JAclObjectIdentityRecord
*/
public JAclObjectIdentityRecord(Long id, Long objectIdClass, String objectIdIdentity, Long parentObject, Long ownerSid, Boolean entriesInheriting) {
super(JAclObjectIdentity.ACL_OBJECT_IDENTITY);
set(0, id);
set(1, objectIdClass);
set(2, objectIdIdentity);
set(3, parentObject);
set(4, ownerSid);
set(5, entriesInheriting);
}
}
| 23.847682 | 153 | 0.583727 |
20efe0df5b9bab66be8e4b6e47b23200b8f1ade7 | 6,067 | package com.github.hilol14707.customservermod.util;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
public class ConfigHandler {
private File configFolder;
private Configuration config;
private ConfigValues configValues = new ConfigValues();
public ConfigHandler(File modConfigDir) {
configFolder = new File(modConfigDir + "/" + Reference.MOD_ID);
configFolder.mkdirs();
}
public void init() {
String category;
config = new Configuration(new File(configFolder.getPath(), Reference.MOD_ID + ".cfg"));
category = "_IMPORTANT_INFO";
config.addCustomCategoryComment(category,
"This is the config file for "
+ Reference.NAME
+ ".\n"
+ "\nCommands must have a Name to use them in game when they are enabled."
+ "\nA command's aliases is an alternative command name that can be used in addition to that command's name to call that command."
+ "\nA command's alias can be blank which means there is no aliases in game for them to be used.\n"
+ "\n*If you have upgraded from a previous version there may be a chance that a config has changed."
+ "\nConfigs that are currently in use have a comment above them."
+ "\nThis means the configs that have no comment above them are no longer in use.");
config.get(category, "example_used", "this config WOULD be USED", "has a comment so this config is used");
config.get(category, "example_not_used", "this config would NOT be used");
category = "Command_Coords";
config.addCustomCategoryComment(category, "Settings related to the /coords command from this mod.");
config.setCategoryRequiresWorldRestart(category, true);
configValues.commands.coords.ENABLED = config.getBoolean("Enabled", category, true, "True to enable, false disable the coords command.");
configValues.commands.coords.NAME = config.getString("Name", category, "coords", "Name of /coords command. (required)");
configValues.commands.coords.PERM_LEVEL = config.getInt("Permission_Level", category, 4, 0, 4, "Minium OP level required to use /coords command.");
configValues.commands.coords.ALIASES = config.getString("Alias", category, "dox", "An alias for the /coords command that can be used to run it. (can be empty)");
category = "Command_TpDim";
config.addCustomCategoryComment(category, "Settings related to the /tpdim command from this mod.");
config.setCategoryRequiresWorldRestart(category, true);
configValues.commands.tpDim.ENABLED = config.getBoolean("Enabled", category, true, "True to enable, false to disable the tpdim command.");
configValues.commands.tpDim.NAME = config.getString("Name", category, "tpdim", "Name of /tpdim command. (required)");
configValues.commands.tpDim.PERM_LEVEL = config.getInt("Permission_Level", category, 2, 0, 4, "Minium OP level required to use /tpdim command.");
configValues.commands.tpDim.ALIASES = config.getString("Alias", category, "tpdimension", "An alias for the /tpdim command that can be used to run it. (can be empty)");
category = "Logging_Events";
config.addCustomCategoryComment(category, "Enable of disable some logging features.\nThe log file is located at logs/cms/");
config.setCategoryRequiresWorldRestart(category, true);
configValues.events.logEvents = config.getBoolean("_Enable_All_Events", category, true, "Enables (true) or disables (false) all the event logging messages. (this overrides the settings bellow)\n*Note the logging messages from the commands will still be logged");
configValues.events.logAdvancements = config.getBoolean("Log_Advancements", category, true, "Enables (true) or disables (false) logging of whenever a player gets an advancement.");
configValues.events.logServerChat = config.getBoolean("Log_Chat_Messages", category, true, "Enables (true) or disables (false) logging of chat messages.");
configValues.events.logCommands = config.getBoolean("Log_Commands", category, true, "Enables (true) or disables (false) logging of specified commands.");
configValues.events.logCommandsList = config.getStringList("Log_Commands_List", category, new String[] {"give", "gamemode", "tp"}, "List of commands to log when they are used.");
configValues.events.logPlayerDeaths = config.getBoolean("Log_Player_Deaths", category, true, "Enables (true) or disables (false) logging of player deaths.");
configValues.events.logPlayerJoin = config.getBoolean("Log_Player_Join", category, true, "Enables (true) or disables (false) logging of whenever a player joins the game.");
configValues.events.logPlayerLeave = config.getBoolean("Log_Player_Leave", category, true, "Enables (true) or disables (false) logging of whenever a player leaves the game .");
config.save();
config.load();
}
public ConfigValues getConfig() {
return configValues;
}
public class ConfigValues {
public Commands commands = new Commands();
public Events events = new Events();
public class Commands {
public CommandConfigBase coords = new CommandConfigBase();
public CommandConfigBase tpDim = new CommandConfigBase();
public class CommandConfigBase {
public Boolean ENABLED;
public String NAME;
public int PERM_LEVEL;
public String ALIASES;
}
}
public class Events {
public boolean logEvents;
public boolean logServerChat;
public boolean logCommands;
public String[] logCommandsList;
public boolean logPlayerDeaths;
public boolean logPlayerJoin;
public boolean logPlayerLeave;
public boolean logAdvancements;
}
}
} | 60.67 | 278 | 0.681556 |
212ef4b6dc8f28d50c2a4eedf3ec0e8c6fb6a197 | 1,196 | package janktastic.jankbot.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame;
import java.nio.Buffer;
import net.dv8tion.jda.api.audio.AudioSendHandler;
import java.nio.ByteBuffer;
//Implementation of JDA AudioSendHandler that wraps lava audio player
public class LavaPlayerSendHandler implements AudioSendHandler {
private final AudioPlayer audioPlayer;
private final ByteBuffer buffer;
private final MutableAudioFrame frame;
// wrap lava audioplayer
public LavaPlayerSendHandler(AudioPlayer audioPlayer) {
this.audioPlayer = audioPlayer;
this.buffer = ByteBuffer.allocate(1024);
this.frame = new MutableAudioFrame();
this.frame.setBuffer(buffer);
}
@Override
public boolean canProvide() {
// returns true if audio was provided
return audioPlayer.provide(frame);
}
@Override
public ByteBuffer provide20MsAudio() {
// flip byte buffer to read mode
((Buffer) buffer).flip();
return buffer;
}
// youtube already provides audio in opus format, tell jda it doesnt need to encode
@Override
public boolean isOpus() {
return true;
}
} | 28.47619 | 85 | 0.758361 |
8f85864547732b9277d0b3964d222addf00f0eb2 | 3,157 | /**
* 언더스코어 문자열과 CamelCase 간의 상호변환 규칙 테스트
*/
package jcf.naming;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import junit.framework.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.junit.rules.ExpectedException;
/**
* @author setq
*
*/
public class UnderScoreColumnNameConverterTest {
@Rule
public ErrorCollector collector = new ErrorCollector();
@Rule
public ExpectedException thrown = ExpectedException.none();
private ColumnNameConverter converter = new UnderScoreColumnNameConverter();
@Test
public void testEncode() {
assertEquals("USER_ID", converter.encode("userId"));
}
@Test
public void testDecode() {
Assert.assertEquals("userId", converter.decode("USER_ID"));
}
@Test
public void 디코드_불가능한_문자열() {
thrown.expect(ColumnNameConversionException.class);
roundTripDecodeFirst("USER_1D");
}
/**
* 소문자 입력도 받아들이도록 한다. 단, 이 경우는 결과가 대문자로 바뀐다.
*/
@Test
public void testRountTripDecodeFirst() {
roundTripDecodeFirst("USER_ID");
roundTripDecodeFirst("user_id");
roundTripDecodeFirst("user__id");
roundTripDecodeFirst("user_Id");
roundTripDecodeFirst("_USERID");
roundTripDecodeFirst("USER__ID");
}
private void roundTripDecodeFirst(String encodedString) {
try {
String decoded = converter.decode(encodedString);
String encodedAgain = converter.encode(decoded);
collector.checkThat(encodedAgain.toLowerCase(),
is(encodedString.toLowerCase()));
} catch (Exception e) {
collector.addError(e);
}
}
@Test
public void testRountTripEncodeFirst() {
roundTripEncodeFirst("USER_ID");
roundTripEncodeFirst("user_id");
roundTripEncodeFirst("user_Id");
roundTripEncodeFirst("_USERID");
roundTripEncodeFirst("USER_1D");
roundTripEncodeFirst("USER__ID");
}
/*
* 1. 소문자를 나타낼 수 없는 영역에서 대문자 및 기타 기호로만 표현할 수 있는데 소문자 및 대문자를 표현할 수 있는 문자열을
* escape할 수 있는 방법 (공백은 제외한다.)
*
* 2. 빈 프로퍼티 이름 규칙과 1의 규칙의 조합
*
* AbcDef123_456aBc _ABC_DEF123_456A_BC
*/
private void roundTripEncodeFirst(String decodedString) {
try {
String encoded = converter.encode(decodedString);
String decodedAgain = converter.decode(encoded);
collector.checkThat(decodedAgain, is(decodedString));
// System.out.println(decodedString.equals(decodedAgain) ? "OK" :
// "Failed");
} catch (Exception e) {
collector.addError(e);
}
}
/**
* 디코더 입력에 언더스코어 뒤에는 항상 영문(대문자)가 한 글자 있어야 함.
*/
@Test
public void testSymmetryCheck() {
thrown.expect(ColumnNameConversionException.class);
converter.decode("USER_1");
}
/**
* 빈 문자열에 대해 에러를 발생시키지 않아야 한다.
*/
@Test
public void testEmpty() {
assertEquals("", converter.encode(""));
assertEquals("", converter.decode(""));
}
/**
* NULL에 대해 에러를 발생시키지 않아야 한다.
*/
@Test
public void testNull() {
assertEquals(null, converter.encode(null));
assertEquals(null, converter.decode(null));
}
@Test
public void test길게한번에() {
String origin = "아무거나_걸려라__이런것도 되나 Spring __user_Id_1.what? USER_1D user_1d";
String enc = converter.encode(origin);
String dec = converter.decode(enc);
assertEquals(origin, dec);
}
}
| 22.076923 | 79 | 0.712702 |
25ebf458a30f2f8895b4ae053405c90dde4007f6 | 1,747 | package net.predictblty.machinelearning.mlcommon;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by berkgokden on 12/17/14.
*/
public class UnclassifiedFeature implements DataSerializable, Serializable {
private static final long serialVersionUID = 1L;
protected double confidence;
protected Map<String, Serializable> featureMap;
public UnclassifiedFeature() {
this.featureMap = new ConcurrentHashMap<String, Serializable>();
this.confidence = 1.0;
}
public UnclassifiedFeature(Map<String, Serializable> feature) {
this.featureMap = feature;
this.confidence = 1.0;
}
public UnclassifiedFeature(Map<String, Serializable> feature, double confidence) {
this.featureMap = feature;
this.confidence = confidence;
}
public double getConfidence() {
return confidence;
}
public void setConfidence(double confidence) {
this.confidence = confidence;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeObject(featureMap);
out.writeDouble(confidence);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
this.featureMap = in.readObject();
this.confidence = in.readDouble();
}
public Map<String, Serializable> getFeatureMap() {
return featureMap;
}
public void setFeatureMap(Map<String, Serializable> featureMap) {
this.featureMap = featureMap;
}
}
| 26.876923 | 86 | 0.704064 |
b2af73cbb148d1037191332ea2ffa1ef5f4cd321 | 2,189 | package org.naddeo.elm.features.imports;
import java.util.Optional;
import org.junit.Test;
import org.naddeo.elm.lang.Exposed;
import org.naddeo.elm.lang.ImportStatement;
import org.naddeo.elm.lang.ImportStatements;
import org.naddeo.elm.lang.Module;
import org.naddeo.elm.lang.ModuleDefinition;
import static junit.framework.TestCase.assertEquals;
public class AlphabeticalImportOrganizerTest
{
@Test
public void test_organizeImports()
{
Module input = moduleTemplate.withImportStatements(ImportStatements.builder()
.importStatement(importStatementTemplate.withName("First"))
.importStatement(importStatementTemplate.withName("Second"))
.importStatement(importStatementTemplate.withName("Third"))
.importStatement(importStatementTemplate.withName("Fourth"))
.importStatement(importStatementTemplate.withName("Fifth"))
.build());
Module expected = moduleTemplate.withImportStatements(ImportStatements.builder()
.importStatement(importStatementTemplate.withName("Fifth"))
.importStatement(importStatementTemplate.withName("First"))
.importStatement(importStatementTemplate.withName("Fourth"))
.importStatement(importStatementTemplate.withName("Second"))
.importStatement(importStatementTemplate.withName("Third"))
.build());
Module actual = importOrganizer.organizeImports(input);
assertEquals(expected, actual);
}
private final AlphabeticalImportOrganizer importOrganizer = new AlphabeticalImportOrganizer();
private final ImportStatement importStatementTemplate = ImportStatement.builder()
.name("__template__")
.alias(Optional.empty())
.exposed(Optional.empty())
.build();
private final Module moduleTemplate = Module.builder()
.importStatements(ImportStatements.EMPTY)
.moduleDefinition(ModuleDefinition.builder()
.name("MyModule")
.exposes(Exposed.NOTHING)
.build())
.build();
} | 39.089286 | 98 | 0.676565 |
bad589df42d7d90369bc219e33328959c85679a5 | 4,909 | package com.ceiba.categoria.entidad;
import com.ceiba.BasePrueba;
import com.ceiba.categoria.modelo.entidad.Categoria;
import com.ceiba.categoria.servicio.testdatabuilder.CategoriaTestDataBuilder;
import com.ceiba.dominio.excepcion.ExcepcionLongitudValor;
import com.ceiba.dominio.excepcion.ExcepcionValorInvalido;
import com.ceiba.dominio.excepcion.ExcepcionValorObligatorio;
import com.ceiba.generadores.Generadores;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
final class CategoriaTest {
@Test
@DisplayName("Deberia crear correctamente una categoria")
void deberiaCrearCorrectamenteUnaCategoria() {
// arrange
//act
Categoria categoria = new CategoriaTestDataBuilder().conId(1L).build();
//assert
assertEquals(1, categoria.getId());
assertEquals("Categoria", categoria.getNombre());
assertEquals("CAT", categoria.getCodigo());
assertEquals(10, categoria.getCostoHora());
assertEquals(20, categoria.getCostoDia());
assertEquals(30, categoria.getCostoSemana());
}
@Test
@DisplayName("Deberia fallar si excede la longitud de NOMBRE de la categoria")
void deberiaFallarSiExcedeLongitudDeNombreDeCategoria() {
final int LONGITUD_MAXIMA = 100;
String nombreInvalida = Generadores.palabra(LONGITUD_MAXIMA+1);
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conNombre(nombreInvalida).conId(1L);
//act-assert
BasePrueba.assertThrows(categoriaTestDataBuilder::build,
ExcepcionLongitudValor.class, String.format("Longitud maxima excedida para NOMBRE es de %s caracteres", LONGITUD_MAXIMA));
}
@Test
@DisplayName("Deberia fallar si excede la longitud de CODIGO de la categoria")
void deberiaFallarSiExcedeLongitudDeCodigoDeCategoria() {
final int LONGITUD_MAXIMA = 5;
String nombreInvalida = Generadores.palabra(LONGITUD_MAXIMA+1);
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conCodigo(nombreInvalida).conId(1L);
//act-assert
BasePrueba.assertThrows(categoriaTestDataBuilder::build,
ExcepcionLongitudValor.class, String.format("Longitud maxima excedida para CODIGO es de %s caracteres", LONGITUD_MAXIMA));
}
@Test
@DisplayName("Deberia fallar si no se tiene NOMBRE de categoria")
void deberiaFallarSinNombreDeCategoria() {
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conNombre(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
categoriaTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar el nombre de categoria");
}
@Test
@DisplayName("Deberia fallar si no se tiene CODIGO de categoria")
void deberiaFallarSinCcodigoDeCategoria() {
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conCodigo(null).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
categoriaTestDataBuilder.build();
},
ExcepcionValorObligatorio.class, "Se debe ingresar el codigo");
}
@Test
@DisplayName("Deberia fallar COSTO POR HORA negativo")
void deberiaFallarCostoPorHoraNegativo() {
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conCostoHora(-1.0).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
categoriaTestDataBuilder.build();
},
ExcepcionValorInvalido.class, "Se debe ingresar un número mayor que cero");
}
@Test
@DisplayName("Deberia fallar COSTO POR DIA negativo")
void deberiaFallarCostoPorDiaNegativo() {
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conCostoDia(-1.0).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
categoriaTestDataBuilder.build();
},
ExcepcionValorInvalido.class, "Se debe ingresar un número mayor que cero");
}
@Test
@DisplayName("Deberia fallar COSTO POR SEMANA negativo")
void deberiaFallarCostoPorSemanaNegativo() {
//Arrange
CategoriaTestDataBuilder categoriaTestDataBuilder = new CategoriaTestDataBuilder().conCostoSemana(-1.0).conId(1L);
//act-assert
BasePrueba.assertThrows(() -> {
categoriaTestDataBuilder.build();
},
ExcepcionValorInvalido.class, "Se debe ingresar un número mayor que cero");
}
}
| 39.272 | 138 | 0.686902 |
6929763e566ae64eca99484e0011d5e535110ef8 | 451 | package org.phoenix.leetcode.challenges;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class Problem11_FloodFillTest {
private final Problem11_FloodFill test = new Problem11_FloodFill();
@Test
void floodFill() {
int[][] arr = new int[][]{{0, 0, 0}, {0, 1, 1}};
int[][] excepted = new int[][]{{0, 0, 0}, {0, 1, 1}};
assertEquals(arr, test.floodFill(arr, 1, 1, 1));
}
} | 26.529412 | 71 | 0.620843 |
9aa00398a304e1ba86015029956ccacaf70ebb01 | 1,754 | package com.ramamosr;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class RotationGameArray {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
int useCaseCount = input.nextInt();
input.nextLine();
if (useCaseCount > 0) {
while (input.hasNextLine()) {
String arrayInput = input.nextLine();
if (arrayInput.length() > 0) {
String[] inputStr = arrayInput.split(" ");
int arrayLength = Integer.parseInt(inputStr[0]);
int[] numberArray = new int[arrayLength];
for (int i = 0; i < inputStr.length - 1; i++) {
numberArray[i] = Integer.parseInt(inputStr[i + 1]);
}
int rotateSteps = Integer.parseInt(input.nextLine());
if(rotateSteps > numberArray.length){
rotateSteps = rotateSteps % numberArray.length;
}
numberArray = reverseArray(numberArray, 0, numberArray.length - rotateSteps - 1);
numberArray = reverseArray(numberArray, numberArray.length - rotateSteps, numberArray.length - 1);
numberArray = reverseArray(numberArray, 0, numberArray.length - 1);
System.out.println("Rotated Array is " + Arrays.toString(numberArray));
}
}
}
}
public static int[] reverseArray(int[] A, int start, int end){
for(int i = start,j=end;i<j;i++,j--){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
return A;
}
}
| 38.977778 | 118 | 0.527366 |
8c84e99106f1fbff30e156eec8ea2a0aa29f8619 | 198 | package com.github.datalking.web.mvc.condition;
/**
* @author yaoo on 4/28/18
*/
public interface NameValueExpression<T> {
String getName();
T getValue();
boolean isNegated();
}
| 12.375 | 47 | 0.656566 |
69580e19103a4b2e1cad0521d9ea399ee17bf367 | 2,261 | package edu.pku.gg.pokemonbutton.type;
import android.animation.ArgbEvaluator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import edu.pku.gg.pokemonbutton.TypeView;
import edu.pku.gg.pokemonbutton.Utils;
/**
* Created by Gg on 2016/10/12.
*/
public class Fire extends TypeView {
private ArgbEvaluator argbEvaluator = new ArgbEvaluator();
private int COLOR_1 = 0xFFFF512F;
private int COLOR_2 = 0xFFF09819;
private int COLOR_3 = 0xFFFD7B1D;
private Paint paintFire;
private Path pathFire = new Path();
public Fire(Context context) {
super(context);
}
public Fire(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Fire(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init() {
paintFire = new Paint();
paintFire.setAntiAlias(true);
paintFire.setStyle((Paint.Style.FILL));
}
@Override
protected void drawType(float cx, float cy, float radius, Canvas canvas) {
pathFire.reset();
pathFire.moveTo(cx ,cy - radius);
pathFire.arcTo(new RectF(cx - radius,cy - radius,cx + radius, cy + radius),-90, -180);
pathFire.arcTo(new RectF(cx - radius/2,cy,cx + radius/2, cy + radius),90, -160);
pathFire.quadTo(cx - radius/2,cy + radius,cx - radius/3, cy - radius/3);
canvas.drawPath(pathFire,paintFire);
}
@Override
protected void updateTypesPaints(float currentProgress) {
if (currentProgress < 0.5f) {
float progress = (float) Utils.mapValueFromRangeToRange(currentProgress, 0f, 0.5f, 0, 1f);
paintFire.setColor((Integer) argbEvaluator.evaluate(progress, COLOR_1, COLOR_2));
} else {
float progress = (float) Utils.mapValueFromRangeToRange(currentProgress, 0.5f, 1f, 0, 1f);
paintFire.setColor((Integer) argbEvaluator.evaluate(progress, COLOR_2, COLOR_3));
}
}
@Override
protected void updateTypesAlpha(int alpha) {
paintFire.setAlpha(alpha);
}
}
| 29.75 | 102 | 0.670942 |
2bc9e7f814388c97edf25ee809c75401b0f468b3 | 34,101 | /*
* Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.carbonserver.base.manager;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jst.server.generic.core.internal.GenericServer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.ServerCore;
import org.eclipse.wst.server.core.ServerPort;
import org.wso2.developerstudio.eclipse.carbonserver.base.Activator;
import org.wso2.developerstudio.eclipse.carbonserver.base.exception.NoSuchCarbonOperationDefinedException;
import org.wso2.developerstudio.eclipse.carbonserver.base.impl.Credentials;
import org.wso2.developerstudio.eclipse.carbonserver.base.interfaces.ICredentials;
import org.wso2.developerstudio.eclipse.carbonserver.base.monitor.CarbonServerLifeCycleListener;
import org.wso2.developerstudio.eclipse.carbonserver.base.utils.CarbonServerUtils;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.server.base.core.IServerManager;
import org.wso2.developerstudio.eclipse.server.base.core.ServerController;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
@SuppressWarnings("restriction")
public final class CarbonServerManager implements IServerManager {
private static final String CARBON_SERVER_TYPE_REMOTE = "org.wso2.developerstudio.eclipse.carbon.server.remote";
private static final String RESOURCE = "resource";
private static final String RESOURCE_CHANGE_KIND = "resourceChangeKind";
private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
private static List<IServer> servers;
private static Map<String, ICarbonOperationManager> serverPlugins;
private static Map<String, String> serverRuntimePlugins;
private static CarbonServerManager instance;
private static Map<IServer, CarbonServerInformation> appServerInformation;
private static CarbonServerLifeCycleListener carbonServerLifeCycleListener;
private static boolean isServerAdded;
private IProject rootProject;
private int resourceChngeKind;
private CarbonServerManager() {
init();
}
public static CarbonServerManager getInstance() {
if (instance == null)
instance = new CarbonServerManager();
return instance;
}
private static Map<String, ICarbonOperationManager> getServerPlugin() {
if (serverPlugins == null)
serverPlugins = new HashMap<String, ICarbonOperationManager>();
if (serverRuntimePlugins == null)
serverRuntimePlugins = new HashMap<String, String>();
return serverPlugins;
}
private static Map<String, String> getServerRuntimeIdPlugin() {
if (serverRuntimePlugins == null)
serverRuntimePlugins = new HashMap<String, String>();
return serverRuntimePlugins;
}
public static List<IServer> getServers() {
if (servers == null)
servers = new ArrayList<IServer>();
return servers;
}
public static void serverAdded(IServer server) {
ICarbonOperationManager serverOperationManager = getServerOperationManager(server);
if (serverOperationManager != null) {
getServers().add(server);
isServerAdded = true;
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVER_PORTS);
Object r;
CarbonServerInformation serverInformation = new CarbonServerInformation();
serverInformation.setServerId(server.getId());
ServerPort[] wsasPorts = new ServerPort[] {};
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof ServerPort[])
wsasPorts = (ServerPort[]) r;
CarbonServerUtils.setServicePath(server);
} catch (NoSuchCarbonOperationDefinedException e) {
// ports cannot be retrieved
} catch (Exception e) {
log.error(e);
}
serverInformation.setServerPorts(wsasPorts);
// The localrepo path is for now is the bin distribution path. this
// needs to be fixed in order to be set inside the workspace path
// String workspaceRootPath =
// ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
// String serverPath=FileUtils.addNodesToPath(workspaceRootPath, new
// String[]{".metadata",".carbon",server.getId()});
IPath serverHome = getServerHome(server);
if (serverHome != null) {
String serverPath = serverHome.toOSString();
(new File(serverPath)).mkdirs();
serverInformation.setServerLocalWorkspacePath(serverPath);
}
getAppServerInformation().put(server, serverInformation);
try {
initializeServerConfigurations(server);
} catch (Exception e) {
log.error(e);
}
}
}
public static void serverRemoved(IServer server) {
if (getServers().contains(server)) {
try {
cleanupServerConfigurations(server);
} catch (Exception e) {
log.error(e);
}
getServers().remove(server);
if (getAppServerInformation().containsKey(server))
getAppServerInformation().remove(server);
}
}
public static void serverStateChanged(IServer server) {
}
public static void registerAppServerPlugin(String serverId, ICarbonOperationManager opManager) {
if (!getServerPlugin().containsKey(serverId)) {
getServerPlugin().put(serverId, opManager);
getServerRuntimeIdPlugin().put(opManager.getRuntimeId(), serverId);
addExistingServers();
}
}
public static void unregisterAppServerPlugin(String serverId) {
if (getServerPlugin().containsKey(serverId))
serverPlugins.remove(serverId);
}
public static ICarbonOperationManager getServerOperationManager(IServer server) {
return getServerOperationManager(server.getId());
}
public static ICarbonOperationManager getServerOperationManager(String serverId) {
IServer server = getServer(serverId);
if (getServerPlugin().containsKey(server.getServerType().getId()))
return getServerPlugin().get(server.getServerType().getId());
else {
return null;
}
}
public static ICarbonOperationManager getServerOperationManagerByServerType(String serverTypeId) {
if (getServerPlugin().containsKey(serverTypeId))
return getServerPlugin().get(serverTypeId);
else {
return null;
}
}
public Object executeOperationOnServer(IServer server, Map<String, Object> operation) throws Exception {
return executeOperationOnServer(server.getId(), operation);
}
public Object executeOperationOnServer(String serverId, Map<String, Object> operation) throws Exception {
ICarbonOperationManager serverOperationManager = getServerOperationManager(serverId);
if (!operation.containsKey(ICarbonOperationManager.PARAMETER_SERVER))
addServerToParameters(operation, getServer(serverId));
if (serverOperationManager == null)
return null;
else
return serverOperationManager.executeOperation(operation);
}
public static IServer getServer(String serverId) {
IServer server = null;
for (IServer s : getServers()) {
if (s.getId().equalsIgnoreCase(serverId)) {
server = s;
break;
}
}
if (server == null) {
IServer[] s = ServerCore.getServers();
for (IServer aserver : s) {
if (aserver.getId().equals(serverId)) {
server = aserver;
break;
}
}
}
return server;
}
public IProject[] getProjectsUsedByRuntime(String serverId) {
return null;
}
public String getRuntimeServerIdForProject(IProject project) {
// for(IServer server:getServers()){
// for(IModule module:server.getModules()){
// if (module.getProject()==project){
// break;
// }
// }
// }
return null;
}
public static String[] getServerIdForProject(IProject project) {
List<String> serverIds = new ArrayList<String>();
IServer[] serversForProject = getServersForProject(project);
for (IServer server : serversForProject) {
serverIds.add(server.getId());
}
return serverIds.toArray(new String[] {});
}
public static IServer[] getServersForProject(IProject project) {
List<IServer> serverIds = new ArrayList<IServer>();
for (IServer server : getServers()) {
for (IModule module : server.getModules()) {
if (module.getProject() == project) {
serverIds.add(server);
}
}
}
return serverIds.toArray(new IServer[] {});
}
public IPath getServerHome(String serverId) {
IServer server = getServer(serverId);
return getServerHome(server);
}
public static IPath getServerHome(IServer server) {
IPath location = null;
if (server != null) {
IServerManager wsasServerManager = getInstance();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVER_HOME);
Object r;
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof IPath)
location = (IPath) r;
} catch (NoSuchCarbonOperationDefinedException e) {
return null;
} catch (Exception e) {
log.error(e);
}
}
return location;
}
public static IPath getServerConfDir(IServer server) {
IPath location = null;
if (server != null) {
IServerManager wsasServerManager = getInstance();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVER_CONF);
Object r;
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof IPath)
location = (IPath) r;
} catch (NoSuchCarbonOperationDefinedException e) {
return null;
} catch (Exception e) {
log.error(e);
}
}
return location;
}
public int getServerStatus(String serverId) {
IServer server = getServer(serverId);
if (server == null)
return 0;
else
return server.getServerState();
}
public boolean restartServer(String serverId) {
IServer server = getServer(serverId);
if (server == null)
return false;
else {
// TODO the restart a server
return false;
}
}
public boolean startServer(String serverId, Object shell) {
IServer server = getServer(serverId);
if (server == null)
return false;
else {
try {
if (server.getServerState() != IServer.STATE_STARTING) {
server.start("run", (IProgressMonitor) null);
}
if (shell == null)
return true;
else {
if (shell instanceof Shell)
return waitUntilTheServerStarts(server, (Shell) shell);
else
return true;
}
} catch (CoreException e) {
return false;
}
}
}
public static IServer getRunningServer() {
IServer server = null;
for (IServer s : getServers()) {
if (s.getServerState() == IServer.STATE_STARTED) {
server = s;
break;
}
}
return server;
}
public boolean stopServer(String serverId) {
IServer server = getServer(serverId);
if (server == null)
return false;
else {
server.stop(false);
return true;
}
}
public static void initiateAppServerManagementOperations() {
carbonServerLifeCycleListener = new CarbonServerLifeCycleListener();
ServerCore.addServerLifecycleListener(carbonServerLifeCycleListener);
}
public static void deInitiateAppServerManagementOperations() {
if (carbonServerLifeCycleListener != null) {
ServerCore.removeServerLifecycleListener(carbonServerLifeCycleListener);
}
}
public static void addExistingServers() {
IServer[] s = ServerCore.getServers();
for (IServer server : s) {
if (!getServers().contains(server))
serverAdded(server);
}
}
public String[] getServerIds() {
List<String> list = new ArrayList<String>();
for (IServer server : getServers()) {
list.add(server.getId());
}
return list.toArray(new String[] {});
}
public String[] getServerLibraryPaths(String serverId) throws Exception {
IServer server = getServer(serverId);
return getServerLibraryPaths(server);
}
public static String[] getServerLibraryPaths(IServer server) throws Exception {
String[] result = null;
if (server != null) {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]) {
result = (String[]) r;
IPath serverLocation = getServerHome(server);
for (int i = 0; i < result.length; i++) {
result[i] = FileUtils.addAnotherNodeToPath(serverLocation.toOSString(), result[i]);
}
}
}
return result;
}
public static URL getServiceWSDLUrl(IServer server, String serviceName) throws Exception {
URL result = null;
if (server != null) {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVICE_WSDL_URL);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof URL) {
result = (URL) r;
}
}
return result;
}
public static URL getServiceTryItUrl(IServer server, String serviceName) throws Exception {
URL result = null;
if (server != null) {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVICE_TRY_IT_URL);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVICE_NAME, serviceName);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof URL) {
result = (URL) r;
}
}
return result;
}
public static Map<IServer, CarbonServerInformation> getAppServerInformation() {
if (appServerInformation == null)
appServerInformation = new HashMap<IServer, CarbonServerInformation>();
return appServerInformation;
}
public ServerPort[] getServerPorts(IServer server) {
GenericServer gserver = (GenericServer) server.getAdapter(GenericServer.class);
return gserver.getServerPorts();
}
public static String getServerLocalWorkspacePath(IServer server) {
if (getAppServerInformation().containsKey(server)) {
return getAppServerInformation().get(server).getServerLocalWorkspacePath();
} else
return null;
}
public Map<String, Integer> getServerPorts(String serverId) throws Exception {
Map<String, Integer> result = new HashMap<String, Integer>();
IServer server = getServer(serverId);
if (server != null) {
ServerPort[] serverPorts2 = getServerPorts(server);
if (serverPorts2 != null)
for (ServerPort s : serverPorts2) {
result.put(s.getProtocol(), s.getPort());
}
}
return result;
}
public static void addServerToParameters(Map<String, Object> properties, IServer server) {
properties.put(ICarbonOperationManager.PARAMETER_SERVER, server);
}
public static boolean isOperationSupported(IServer server, int operation) throws Exception {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_SUPPORTED_OPERATIONS);
operationParameters.put(ICarbonOperationManager.PARAMETER_OP_TYPES, operation);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof Boolean) {
return (Boolean) r;
}
return false;
}
public static void initializeServerConfigurations(IServer server) throws Exception {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_INITIALIZE_SERVER_CONFIGURATIONS);
wsasServerManager.executeOperationOnServer(server, operationParameters);
}
public static void cleanupServerConfigurations(IServer server) throws Exception {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_CLEANUP_SERVER_CONFIGURATIONS);
wsasServerManager.executeOperationOnServer(server, operationParameters);
}
public boolean publishServiceModule(String serverId, String webTempPath, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_PUBLISH_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean hotUpdateServiceModule(String serverId, String webTempPath, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_HOT_UPDATE_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean hotUpdateWebApp(String serverId, IResource resource, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_HOT_UPDATE_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, "");
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
operationParameters.put(RESOURCE, resource);
operationParameters.put(RESOURCE_CHANGE_KIND, new Integer(resourceChngeKind));
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean redeployServiceModule(String serverId, String webTempPath, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_REDEPLOY_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public boolean unpublishServiceModule(String serverId, String webTempPath, String projectName) {
IServer server = getServer(serverId);
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
CarbonServerManager wsasServerManager = this;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_UNPUBLISH_MODULE);
operationParameters.put(ICarbonOperationManager.PARAMETER_WebTempPath, webTempPath);
operationParameters.put(ICarbonOperationManager.PARAMETER_PROJECT, project);
try {
wsasServerManager.executeOperationOnServer(server, operationParameters);
return true;
} catch (Exception e) {
log.error(e);
return false;
}
}
public static boolean waitForServerToChangeState(IServer server, Shell shell, int changeStateFrom,
int changeStateTo, String msg) {
ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(shell);
CarbonServerStateChange serverStateChange =
new CarbonServerStateChange(server, changeStateFrom, changeStateTo,
180000, msg);
progressMonitorDialog.setBlockOnOpen(false);
try {
progressMonitorDialog.run(true, true, serverStateChange);
return progressMonitorDialog.getReturnCode() != ProgressMonitorDialog.CANCEL;
} catch (InvocationTargetException e) {
log.error(e);
} catch (InterruptedException e) {
log.error(e);
}
return false;
}
public static boolean waitUntilTheServerStarts(IServer server, Shell shell) {
return waitForServerToChangeState(server, shell, IServer.STATE_STOPPED, IServer.STATE_STARTED,
"Starting WSAS Server " + server.getId() + "...");
}
public Map<IFolder, IProject> getPublishedPaths(String serverId) {
return getPublishedPaths(getServer(serverId));
}
public static Map<IFolder, IProject> getPublishedPaths(IServer server) {
if (server == null)
return null;
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_PUBLISHED_SERVICES);
try {
Object result = wsasServerManager.executeOperationOnServer(server, operationParameters);
if (result instanceof Map) {
return (Map<IFolder, IProject>) result;
}
return null;
} catch (Exception e) {
log.error(e);
return null;
}
}
public IProject[] getPublishedProjects(String serverId) {
return null;
}
public IProject[] getPublishedProjectsFromAllServers() {
return null;
}
public String getServerRuntimeId(String serverId) {
return getServerOperationManager(serverId).getRuntimeId();
}
public boolean isRuntimeIdPresent(String runtimeId) {
return getServerRuntimeIdPlugin().containsKey(runtimeId);
}
public String getServerTypeIdForRuntimeId(String runtimeId) {
if (getServerRuntimeIdPlugin().containsKey(runtimeId))
return getServerRuntimeIdPlugin().get(runtimeId);
else
return null;
}
public String[] getServerRelativeLibraryPaths(String serverTypeId) throws Exception {
String[] result = null;
ICarbonOperationManager serverOperationManager = getServerOperationManagerByServerType(serverTypeId);
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_LIBRARY_PATHS);
Object r = serverOperationManager.executeOperation(operationParameters);
if (r instanceof String[]) {
result = (String[]) r;
}
return result;
}
public String[] getServerCodegenLibraries(String serverId) throws Exception {
IServer server = getServer(serverId);
return getServerCodegenLibraries(server);
}
public static String[] getServerCodegenLibraries(IServer server) throws Exception {
String[] result = null;
if (server != null) {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
Object r = wsasServerManager.executeOperationOnServer(server, operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]) {
result = (String[]) r;
}
}
return result;
}
public String[] getServerAxis2Libraries(String serverTypeId, String wsasHome) throws Exception {
String[] result = null;
ICarbonOperationManager serverOperationManager = getServerOperationManagerByServerType(serverTypeId);
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_AXIS2_LIBRARIES);
operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, wsasHome);
Object r = serverOperationManager.executeOperation(operationParameters);
if (r instanceof String[]) {
result = (String[]) r;
}
return result;
}
private void init() {
createWorkspaceListener();
}
private void createWorkspaceListener() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceChangeListener listener = new IResourceChangeListener() {
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta projectDelta;
if (isServerAdded) {
IResourceDelta resourceDelta = event.getDelta();
for (IResourceDelta modifideResourceDelta : resourceDelta.getAffectedChildren()) {
rootProject = (IProject) modifideResourceDelta.getResource();
projectDelta = modifideResourceDelta;
IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() {
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
resourceChngeKind = delta.getKind();
if (resource.getType() == IResource.FILE || resource.getType() == IResource.FOLDER) {
IServer[] serversForProject = getServersForProject(rootProject);
for (IServer server : serversForProject) {
if (!CARBON_SERVER_TYPE_REMOTE.equalsIgnoreCase(server.getServerType().getId())) {
CarbonServerInformation serverInformation =
getAppServerInformation().get(server);
if (!serverInformation.getChangedProjects().contains(rootProject)) {
serverInformation.getChangedProjects().add(rootProject);
hotUpdateWebApp(server.getId(), resource, rootProject.getName());
}
}
}
}
return true;
}
};
try {
projectDelta.accept(visitor);
} catch (CoreException e) {
log.error(" adding IResourceDeltaVisitor to projectDelta was failed " + e);
}
}
}
}
};
workspace.addResourceChangeListener(listener, IResourceChangeEvent.POST_BUILD);
}
public String[] getServerCodegenLibrariesFromRuntimeId(String runtimeId, String runtimePath) throws Exception {
String serverTypeId = getServerTypeIdForRuntimeId(runtimeId);
String[] result = null;
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_CODEGEN_LIBRARIES);
operationParameters.put(ICarbonOperationManager.PARAMETER_RUNTIME, runtimeId);
operationParameters.put(ICarbonOperationManager.PARAMETER_PATH, runtimePath);
ICarbonOperationManager wsasOperationManager = getServerOperationManagerByServerType(serverTypeId);
Object r = wsasOperationManager.executeOperation(operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof String[]) {
result = (String[]) r;
}
return result;
}
public static ICredentials getServerCredentials(IServer server) throws Exception {
Map<String, String> result = null;
if (server != null) {
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVER_CREDENTIALS);
Object r = esbServerManager.executeOperationOnServer(server, operationParameters);// getWSDLConversionResultUrl(resourceFile);
if (r instanceof Map) {
result = (Map<String, String>) r;
}
}
Credentials credentials = null;
if (result != null) {
credentials = new Credentials(result.get("esb.username"), result.get("esb.password"));
}
return credentials;
}
public static URL getServerURL(IServer server) throws Exception {
if (server != null) {
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_SERVER_URL);
Object serverURL = esbServerManager.executeOperationOnServer(server, operationParameters);
if (serverURL instanceof URL) {
String serverId = server.getServerType().getId();
URL urlWithContextRoot = (URL) serverURL;
if (!CARBON_SERVER_TYPE_REMOTE.equals(serverId)) {
urlWithContextRoot = new URL(urlWithContextRoot, CarbonServerUtils.getWebContextRoot(server));
}
return urlWithContextRoot;
}
}
return null;
}
public static String getServerAuthenticatedCookie(IServer server, String httpsPort) throws Exception {
String result = null;
if (server != null) {
IServerManager esbServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_GET_SERVER_AUTHENTICATED_COOKIE);
operationParameters.put(ICarbonOperationManager.PARAMETER_SERVER_PORT, httpsPort);
Object r = esbServerManager.executeOperationOnServer(server, operationParameters);
if (r instanceof String) {
result = (String) r;
}
}
return result;
}
public static String getServerAuthenticatedCookie(IServer server) throws Exception {
String result = null;
if (server != null) {
ServerPort[] serverPorts = getInstance().getServerPorts(server);
String httpsPort = "9443";
for (ServerPort port : serverPorts) {
if (port.getProtocol().equalsIgnoreCase("https")) {
httpsPort = Integer.toString(port.getPort());
}
}
result = getServerAuthenticatedCookie(server, httpsPort);
}
return result;
}
public static String getServerCarbonVersion(IServer server) {
String result = null;
if (server != null) {
IServerManager wsasServerManager = ServerController.getInstance().getServerManager();
HashMap<String, Object> operationParameters = new HashMap<String, Object>();
operationParameters.put(ICarbonOperationManager.PARAMETER_TYPE,
ICarbonOperationManager.OPERATION_SERVER_VERSION);
Object r = null;
try {
r = wsasServerManager.executeOperationOnServer(server, operationParameters);
} catch (Exception e) {
log.error(e);
}
result = (String) r;
}
return result;
}
}
| 37.89 | 130 | 0.747808 |
bc4b8cf5d92d648ab51c7f3881279c74105e7332 | 286 | package city.restaurant.omar;
public class FoodTicket {
OmarCustomerRole c;
OmarWaiterRole w;
public FoodTicket(OmarWaiterRole w, OmarCustomerRole c){
this.w = w;
this.c = c;
}
public OmarCustomerRole getC(){
return c;
}
public OmarWaiterRole getW(){
return w;
}
}
| 15.052632 | 57 | 0.706294 |
f44ed1ec9a7898d7acc6a2b57373d53eb1acd92e | 1,858 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.gradle.internal.test.rest.transform.length;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.elasticsearch.gradle.internal.test.rest.transform.AssertObjectNodes;
import org.elasticsearch.gradle.internal.test.rest.transform.TransformTests;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
public class ReplaceValueInLengthTests extends TransformTests {
private static final YAMLFactory YAML_FACTORY = new YAMLFactory();
private static final ObjectMapper MAPPER = new ObjectMapper(YAML_FACTORY);
@Test
public void testReplaceMatch() throws Exception {
String test_original = "/rest/transform/length/length_replace_original.yml";
List<ObjectNode> tests = getTests(test_original);
String test_transformed = "/rest/transform/length/length_replace_transformed_value.yml";
List<ObjectNode> expectedTransformation = getTests(test_transformed);
NumericNode replacementNode = MAPPER.convertValue(99, NumericNode.class);
List<ObjectNode> transformedTests = transformTests(
tests,
Collections.singletonList(new ReplaceValueInLength("key.in_length_to_replace", replacementNode, null))
);
AssertObjectNodes.areEqual(transformedTests, expectedTransformation);
}
}
| 40.391304 | 114 | 0.772336 |
f947f388a243b1594542b529a7fb6330f69e8bb8 | 692 | package com.example.electrowayfinal.repositories;
import com.example.electrowayfinal.models.Favourite;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface FavouriteRepository extends JpaRepository<Favourite, Long> {
List<Favourite> findAllByStationId(long station_id);
@Override
List<Favourite> findAll();
Optional<Favourite> findFavouriteByStationIdAndId(long stationId, long favouriteId);
Optional<Favourite> findFavouriteById(long stationId);
@Override
<F extends Favourite> F save(F entity);
void deleteById(long id);
@Override
void delete(Favourite entity);
}
| 25.62963 | 88 | 0.773121 |
d426765ffc1470467f010d63138930b6df4440dd | 3,616 | package com.crud.cloud.evanliu2968.controller.file;
import com.baomidou.mybatisplus.plugins.Page;
import com.crud.cloud.evanliu2968.dto.ResponseData;
import com.crud.cloud.evanliu2968.dto.request.GetFileReq;
import com.crud.cloud.evanliu2968.dto.response.FileGroupRes;
import com.crud.cloud.evanliu2968.dto.response.FileRes;
import com.crud.cloud.evanliu2968.service.FileService;
import com.crud.cloud.evanliu2968.service.MailService;
import com.crud.cloud.evanliu2968.util.bigFile.BigFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
/**
* 上传文件管理接口
* @author luoshuai
*/
@Api(tags = "上传文件_上传文件管理接口")
@RequestMapping(path = "/evanliu2968/file", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class FileController {
@Autowired
private FileService fileService;
@Autowired
MailService mailService;
@Autowired
private BigFileUtil fileUtil;
@ApiOperation(nickname = "uploadFileController", value = "上传文件")
@PostMapping(value = "/uploadFile", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseData<String> uploadFile(@Valid @RequestBody MultipartFile file) {
// 参数错误返回
if (file.isEmpty()) {
return ResponseData.fail("上传文件不能为空");
}
//成功返回
return ResponseData.success(this.fileService.uploadFile(file, null));
}
/**
*
* @Description:
* 接受文件分片,合并分片
* @param md5value
* 文件的MD5值
* @param chunks
* 当前所传文件的分片总数
* @param chunk
* 当前所传文件的当前分片数
* @param id
* 文件ID,如WU_FILE_1,后面数字代表当前传的是第几个文件,后续使用此ID来创建临时目录,将属于该文件ID的所有分片全部放在同一个文件夹中
* @param name
* 文件名称,如07-中文分词器和业务域的配置.avi
* @param file 当前所传分片
*/
@ResponseBody
@RequestMapping(value = "/bigfileup")
public String fileUpload(String md5value, String chunks, String chunk, String id, String name,
MultipartFile file,HttpServletRequest request) {
return this.fileUtil.fileUpload(md5value, chunks, chunk, id, name, file, request);
}
@ApiOperation(nickname = "getGroupFileList", value = "文件分组查询")
@PostMapping(value = "/getGroupFileList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseData<List<FileGroupRes>> getGroupFileList(@Valid @RequestBody GetFileReq getFileReq){
List<FileGroupRes> resultList = this.fileService.getGroupFileList(getFileReq.getTaskType(), getFileReq.getNodeType());
return ResponseData.success(resultList);
}
@ApiOperation(nickname = "getFileList", value = "文件列表查询")
@PostMapping(value = "/getFileList", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseData<Page<FileRes>> getFileList(@Valid @RequestBody GetFileReq getFileReq){
return ResponseData.success(this.fileService.getFileList(getFileReq));
}
@ApiOperation(nickname = "updateFileDownCount", value = "更新文件下载次数")
@PutMapping(value = "/updateFileDownCount/{fileId}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseData<Integer> updateFileDownCount(@PathVariable("fileId") Integer fileId){
return ResponseData.success(this.fileService.updateFileDownCount(fileId));
}
}
| 37.666667 | 126 | 0.721792 |
18eaa448b20876ff1d6739b8886a38ac88f492a2 | 3,436 | package ru.project.cscm.model;
import java.util.Calendar;
import java.util.Collection;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import ru.project.cscm.base.NotNullOrEmpty;
import ru.project.cscm.base.security.AppRole;
import ru.project.cscm.base.security.HasAuthenticationAccess;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
@Entity
@Table(name = "users")
@NamedQueries({ @NamedQuery(name = "findUserById", query = CscmUser.NamedQueries.FIND_USER_BY_ID) })
public class CscmUser extends BaseIdentifiableObject<String> implements HasAuthenticationAccess<String> {
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "user_roles", uniqueConstraints = {
@UniqueConstraint(name = "idx_user_id", columnNames = { "cscm_user_id", "roles" })
}, joinColumns = {
@JoinColumn(name = "cscm_user_id", referencedColumnName = "id")
})
@Enumerated(EnumType.STRING)
private Set<AppRole> roles;
@Column(length = 64, nullable = false)
private String password;
@Column
private boolean isActive;
private static final Function<AppRole, GrantedAuthority> roleToGrantedAuthority = new Function<AppRole, GrantedAuthority>() {
@Override
@NotNull
public GrantedAuthority apply(@NotNull AppRole role) {
return new SimpleGrantedAuthority(role.name());
}
};
protected CscmUser() {
super();
}
public CscmUser(@NotNullOrEmpty final String id, @NotNullOrEmpty final String password,
@NotNullOrEmpty final Set<AppRole> roles, final boolean isActive, @NotNull final Calendar createdTime,
@NotNull final Calendar modifiedTime) {
super(id, createdTime, modifiedTime);
this.password = password;
this.roles = roles;
this.isActive = isActive;
}
public CscmUser(@NotNullOrEmpty final String id, @NotNullOrEmpty final String password,
@NotNullOrEmpty final Set<AppRole> roles) {
super(id);
this.password = password;
this.roles = roles;
this.isActive = true;
}
@Override
@NotNullOrEmpty
public Collection<GrantedAuthority> getRoles() {
return Collections2.transform(roles, roleToGrantedAuthority);
}
@NotNull
public Collection<AppRole> getAppRoles() {
return roles;
}
@Override
@NotNullOrEmpty
public String getPassword() {
return password;
}
@Override
public boolean isActive() {
return isActive;
}
public void setActive(final boolean isActive) {
this.isActive = isActive;
}
public void setPassword(@NotNullOrEmpty final String password) {
this.password = password;
}
@PrePersist
@PreUpdate
public void preModify() {
modifiedTime = Calendar.getInstance();
}
static class NamedQueries {
public static final String FIND_USER_BY_ID = "SELECT u FROM CscmUser u WHERE u.isActive = true AND u.id = :userId";
}
}
| 27.488 | 126 | 0.774447 |
874f8b8d49ed30ae273fba6f434fbaa768ba4cfd | 1,223 | package io.treehopper.desktop.demos.sandbox;
import java.util.ArrayList;
import java.util.List;
import io.treehopper.ConnectionService;
import io.treehopper.*;
import io.treehopper.libraries.io.adc.nau7802.ConversionRates;
import io.treehopper.libraries.io.adc.nau7802.Gains;
import io.treehopper.libraries.io.adc.nau7802.Nau7802;
public class Sandbox {
public static void main(String[] args) {
ConnectionService service = new ConnectionService();
List<TreehopperUsb> boards = service.getBoards();
TreehopperUsb board = boards.get(0);
board.connect();
// Adxl345 imu = new Adxl345(board.i2c, false, 100);
Nau7802 adc = new Nau7802(board.i2c);
adc.setGain(Gains.x1);
adc.setConversionRate(ConversionRates.Sps_80);
adc.calibrate();
while(true)
{
System.out.println(adc.getAdcValue());
// Vector3 dater = imu.getAccelerometer();
// System.out.println(String.format("(%.2f, %.2f, %.2f)", dater.x, dater.y, dater.z));
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
}
| 31.358974 | 97 | 0.623058 |
bf0b424277e1a57623d1026b1737a6198442c5fc | 1,122 | package cn.iocoder.springboot.lab03.kafkademo.producer;
import cn.iocoder.springboot.lab03.kafkademo.message.Demo01Message;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;
@Component
public class Demo01Producer {
@Resource
private KafkaTemplate<Object, Object> kafkaTemplate;
public SendResult syncSend(Integer id) throws ExecutionException, InterruptedException {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// 同步发送消息
return kafkaTemplate.send(Demo01Message.TOPIC, message).get();
}
public ListenableFuture<SendResult<Object, Object>> asyncSend(Integer id) {
// 创建 Demo01Message 消息
Demo01Message message = new Demo01Message();
message.setId(id);
// 异步发送消息
return kafkaTemplate.send(Demo01Message.TOPIC, message);
}
}
| 32.057143 | 92 | 0.746881 |
f39ff775ff70d38c88433141202fffc1c4dcc1d1 | 1,606 | package ru.vyarus.guice.persist.orient.db.scheme.initializer.core.ext;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import ru.vyarus.guice.persist.orient.db.scheme.initializer.core.spi.field.FieldExtension;
import ru.vyarus.guice.persist.orient.db.scheme.initializer.core.spi.type.TypeExtension;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
/**
* Model class scheme extensions object.
*
* @author Vyacheslav Rusakov
* @since 04.03.2015
*/
@SuppressWarnings("checkstyle:VisibilityModifier")
public class ExtensionsDescriptor {
/**
* Type extensions found on class.
*/
public List<Ext<TypeExtension, Class>> type;
/**
* Field extensions found on class fields.
*/
public Multimap<String, Ext<FieldExtension, Field>> fields = LinkedHashMultimap.create();
/**
* Extension descriptor object.
*
* @param <E> extension type
* @param <S> extension source object
*/
@SuppressWarnings("checkstyle:VisibilityModifier")
public static class Ext<E, S> {
/**
* Extension instance.
*/
public E extension;
/**
* Extension annotation.
*/
public Annotation annotation;
/**
* Extension source object.
*/
public S source;
public Ext(final E extension, final Annotation annotation, final S source) {
this.extension = extension;
this.annotation = annotation;
this.source = source;
}
}
}
| 27.689655 | 93 | 0.655044 |
aabe59accd3c7b09d8a3c973ec4ad17278b8217e | 415 | package ai.cellbots.robotlib;
import org.jboss.netty.buffer.ChannelBuffer;
import nav_msgs.MapMetaData;
import std_msgs.Header;
/**
* Interface to generate an {@link nav_msgs.OccupancyGrid} to be published by
* {@link ROSNode}.
*/
public interface OccupancyGridGenerator {
void fillHeader(Header header);
void fillInformation(MapMetaData information);
ChannelBuffer generateChannelBufferData();
}
| 24.411765 | 77 | 0.775904 |
2df29bfa391814924bab920a5c9040e513d154a4 | 1,009 | package com.xhhf.shaika.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
import java.util.List;
/**
* 商家界面viewpager适配器
*/
public class MyFragmentAdapter extends FragmentStatePagerAdapter {
private List<String> mTitle; //页卡标题集合
private List<Fragment>mFragments;
public MyFragmentAdapter(FragmentManager mFm , List<Fragment>mFragments, List<String> mTitle) {
super(mFm);
this.mFragments = mFragments;
this.mTitle = mTitle;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
@Override
public CharSequence getPageTitle(int position) {
return mTitle.get(position);
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
@Override
public int getCount() {
return mFragments.size();
}
}
| 22.931818 | 99 | 0.702676 |
da45c83a60fe3cab55ab3066a8791d0472850338 | 661 | package StoreInventoryMV;
import StoreInventoryMV.controller.StoreController;
import StoreInventoryMV.ui.StoreUI;
import java.io.IOException;
public class App {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// Product p=new Product();
//p.read();
StoreController c = new StoreController();
c.readProducts("products.txt");
StoreUI u = new StoreUI(c);
u.run();
//c.addProduct(p);
// for(Product q:c.getProductsCategory("second")){
// System.out.println(q.toString());
//}
// for(Product q:c.stockSituationProduct("Laptop"))
// System.out.println(q.toString());
//
}
}
| 20.030303 | 60 | 0.685325 |
0f553e2322ef97551659b9c09998351ba97cf92f | 431 |
// Author: Pierce Brooks
package com.piercelbrooks.common;
import androidx.annotation.NonNull;
import android.util.Log;
public class UnimplementedException extends RuntimeException
{
private static final String TAG = "PLB-UnimplementExcept";
public UnimplementedException(@NonNull String tag)
{
super("\""+tag+"\" is not implemented!");
Log.e(TAG, getMessage());
printStackTrace();
}
}
| 21.55 | 62 | 0.698376 |
a026db23e68a79169f8e37a4771924bdbfecce98 | 7,831 | package org.s3s3l.yggdrasil.orm.bind.express.common;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.s3s3l.yggdrasil.orm.bind.ColumnStruct;
import org.s3s3l.yggdrasil.orm.bind.Table;
import org.s3s3l.yggdrasil.orm.bind.annotation.Column;
import org.s3s3l.yggdrasil.orm.bind.annotation.Condition;
import org.s3s3l.yggdrasil.orm.bind.annotation.TableDefine;
import org.s3s3l.yggdrasil.orm.bind.condition.ConditionStruct;
import org.s3s3l.yggdrasil.orm.bind.condition.RawConditionNode;
import org.s3s3l.yggdrasil.orm.bind.express.DataBindExpress;
import org.s3s3l.yggdrasil.orm.bind.select.SelectStruct;
import org.s3s3l.yggdrasil.orm.bind.set.SetNode;
import org.s3s3l.yggdrasil.orm.bind.set.SetStruct;
import org.s3s3l.yggdrasil.orm.bind.sql.DefaultSqlStruct;
import org.s3s3l.yggdrasil.orm.bind.sql.SqlStruct;
import org.s3s3l.yggdrasil.orm.bind.value.ValuesStruct;
import org.s3s3l.yggdrasil.orm.exception.DataBindExpressException;
import org.s3s3l.yggdrasil.orm.handler.TypeHandlerManager;
import org.s3s3l.yggdrasil.orm.meta.ColumnMeta;
import org.s3s3l.yggdrasil.orm.meta.MetaManager;
import org.s3s3l.yggdrasil.orm.validator.ValidatorFactory;
import org.s3s3l.yggdrasil.utils.common.StringUtils;
import org.s3s3l.yggdrasil.utils.reflect.PropertyDescriptorReflectionBean;
import org.s3s3l.yggdrasil.utils.reflect.ReflectionUtils;
import org.s3s3l.yggdrasil.utils.verify.Verify;
/**
*
* <p>
* </p>
* ClassName: DefaultDataBindExpress <br>
* date: Sep 20, 2019 11:27:43 AM <br>
*
* @author kehw_zwei
* @version 1.0.0
* @since JDK 1.8
*/
public class DefaultDataBindExpress implements DataBindExpress {
private final ValidatorFactory validatorFactory;
private final TypeHandlerManager typeHandlerManager;
// TODO 优化成使用MetaManager
private ConditionStruct selectCondition = new ConditionStruct();
private ConditionStruct updateCondtion = new ConditionStruct();
private ConditionStruct deleteCondtion = new ConditionStruct();
private SelectStruct select = new SelectStruct();
private SetStruct set = new SetStruct();
private ValuesStruct values = new ValuesStruct();
private Table table = new Table();
public DefaultDataBindExpress(Class<?> modelType, MetaManager metaManager) {
this.validatorFactory = metaManager.getValidatorFactory();
this.typeHandlerManager = metaManager.getTypeHandlerManager();
express(modelType);
}
@Override
public String getAlias(String name) {
return this.select.getAlias(name);
}
@Override
public synchronized DataBindExpress express(Class<?> modelType) {
Verify.notNull(modelType);
if (!modelType.isAnnotationPresent(TableDefine.class)) {
throw new DataBindExpressException("No 'SqlModel' annotation found.");
}
TableDefine sqlModel = modelType.getAnnotation(TableDefine.class);
if (StringUtils.isEmpty(sqlModel.table())) {
throw new DataBindExpressException("Table name can`t be empty.");
}
this.table.setName(sqlModel.table());
List<ColumnStruct> colums = new ArrayList<>();
for (Field field : ReflectionUtils.getFields(modelType)) {
if (!field.isAnnotationPresent(Column.class)) {
continue;
}
Column column = field.getAnnotation(Column.class);
ColumnStruct columnStruct = ColumnStruct.builder()
.meta(ColumnMeta.builder()
.field(field)
.name(StringUtils.isEmpty(column.name()) ? field.getName() : column.name())
.alias(field.getName())
.validator(this.validatorFactory.getValidator(column.validator()))
.typeHandler(typeHandlerManager.getOrNew(column.typeHandler()))
.build())
.build();
colums.add(columnStruct);
this.select.addNode(columnStruct);
this.values.addNode(columnStruct.getMeta());
if (!column.isPrimary()) {
this.set.addNode(new SetNode(columnStruct));
}
if (field.isAnnotationPresent(Condition.class)) {
Condition condition = field.getAnnotation(Condition.class);
RawConditionNode conditionNode = new RawConditionNode(columnStruct);
conditionNode.setPattern(condition.pattern());
if (condition.forSelect()) {
this.selectCondition.addNode(conditionNode);
}
if (condition.forUpdate()) {
this.updateCondtion.addNode(conditionNode);
}
if (condition.forDelete()) {
this.deleteCondtion.addNode(conditionNode);
}
}
}
return this;
}
@Override
public SqlStruct getInsert(List<?> models) {
Verify.notEmpty(models);
DefaultSqlStruct struct = new DefaultSqlStruct();
AtomicBoolean first = new AtomicBoolean(true);
List<DefaultSqlStruct> valueStructs = models.stream()
.map(r -> this.values.toSqlStruct(new PropertyDescriptorReflectionBean(r), first.getAndSet(false)))
.collect(Collectors.toList());
struct.setSql("INSERT INTO ");
struct.appendSql(this.table.getName());
valueStructs.forEach(r -> {
struct.appendSql(r.getSql());
struct.addParams(r.getParams());
});
return struct;
}
@Override
public SqlStruct getDelete(Object model) {
Verify.notNull(model);
DefaultSqlStruct struct = new DefaultSqlStruct();
SqlStruct deleteStruct = this.deleteCondtion.toSqlStruct(new PropertyDescriptorReflectionBean(model));
struct.setSql("DELETE FROM ");
struct.appendSql(this.table.getName());
if (deleteStruct != null) {
struct.appendSql(deleteStruct.getSql());
struct.addParams(deleteStruct.getParams());
}
return struct;
}
@Override
public SqlStruct getUpdate(Object model) {
Verify.notNull(model);
DefaultSqlStruct struct = new DefaultSqlStruct();
PropertyDescriptorReflectionBean ref = new PropertyDescriptorReflectionBean(model);
SqlStruct setStruct = this.set.toSqlStruct(ref);
SqlStruct conditionStruct = this.updateCondtion.toSqlStruct(ref);
if (setStruct == null) {
return null;
}
struct.setSql("UPDATE ");
struct.appendSql(this.table.getName())
.appendSql(setStruct.getSql())
.appendSql(conditionStruct.getSql());
struct.addParams(setStruct.getParams())
.addParams(conditionStruct.getParams());
return struct;
}
@Override
public SqlStruct getSelect(Object model) {
Verify.notNull(model);
DefaultSqlStruct struct = new DefaultSqlStruct();
PropertyDescriptorReflectionBean ref = new PropertyDescriptorReflectionBean(model);
SqlStruct selectStruct = this.select.toSqlStruct(ref);
SqlStruct conditionStruct = this.selectCondition.toSqlStruct(ref);
if (selectStruct == null) {
return null;
}
struct.setSql("SELECT ");
struct.appendSql(selectStruct.getSql())
.appendSql(" FROM ")
.appendSql(this.table.getName());
if (conditionStruct != null) {
struct.appendSql(conditionStruct.getSql());
struct.addParams(conditionStruct.getParams());
}
return struct;
}
}
| 36.25463 | 115 | 0.656366 |
099c02c36a525f97f5a82e331f12ac19e17a3cce | 2,701 | package org.zmsoft.jfp.framework.oss;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.zmsoft.jfp.framework.constants.IFrameworkConstants;
import org.zmsoft.jfp.framework.utils.DateHelper;
import org.zmsoft.jfp.framework.utils.PKHelper;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import net.coobird.thumbnailator.Thumbnails;
/**
* 断点续传上传用法示例
*
* @since 2.4.2 2016/1/6
*/
public class OSSOperateHelper implements IFrameworkConstants {
private static String publicServer = "http://zmsoft.oss-cn-hangzhou.aliyuncs.com/";
private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
private static String accessKeyId = "LTAIbdAu0xQvAsQx";
private static String accessKeySecret = "aEQ9SKfxm4PZoBbayYfx9ZP0x5as4c";
private static String bucketName = "zmsoft";
public static String putObject(byte[] file, String docname) throws Throwable {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
String key = PKHelper.creatUUKey();
String[] ft = docname.split("\\.");
String realFileName = key;
if (ft.length == 2)
realFileName = key + CURRENT_PATH + ft[1];
realFileName = DateHelper.currentDate3() + FOLDER_SEPARATOR + realFileName;
// 待上传的本地文件
ossClient.putObject(bucketName, realFileName, new ByteArrayInputStream(file));
return publicServer + realFileName;
} finally {
ossClient.shutdown();
}
}
public static String putObject(MultipartFile file, boolean pubUrl) throws Throwable {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
String key = PKHelper.creatUUKey();
String[] ft = file.getOriginalFilename().split("\\.");
String realFileName = key;
if (ft.length == 2)
realFileName = key + CURRENT_PATH + ft[1];
realFileName = DateHelper.currentDate3() + FOLDER_SEPARATOR + realFileName;
InputStream is = file.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
//图片尺寸不变,压缩图片文件质量大小outputQuality实现,参数1为最高质量,scale为尺寸大小压缩
Thumbnails.of(is).outputQuality(0.75f).scale(1f).toOutputStream(os);
is = new ByteArrayInputStream(os.toByteArray());
ossClient.putObject(bucketName, realFileName, is);
if (pubUrl)
return publicServer + realFileName;
return realFileName;
} finally {
ossClient.shutdown();
}
}
public static void removeObject(String key) throws IOException {
// String key = "231395c199b74e7d84bedb146f957ae6.png";
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
client.deleteObject(bucketName, key);
}
}
| 32.154762 | 86 | 0.750833 |
2151a6421ed8805dd80912215be3fdb3e0b3b803 | 712 | package com.infinityworks.pafclient.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
@Value.Immutable
@JsonIgnoreProperties(ignoreUnknown = true)
@Value.Style(init = "with*")
@JsonDeserialize(as = ImmutableInfo.class)
@JsonSerialize(as = ImmutableInfo.class)
public interface Info {
@Value.Default @JsonProperty("phone") default String telephone() {
return "";
}
@Value.Default @JsonProperty("email") default String email() {
return "";
}
}
| 32.363636 | 70 | 0.766854 |
6ef20a0b026fbd1896392a31dc3b5c5e2a89037f | 13,130 | /*
* ======================================================================
* || Copyright (c) 2020 Colin Robertson (wobblyyyy@gmail.com) ||
* || ||
* || This file is part of the "Pathfinder" project, which is licensed ||
* || and distributed under the GPU General Public License V3. ||
* || ||
* || Pathfinder is available on GitHub: ||
* || https://github.com/Wobblyyyy/Pathfinder ||
* || ||
* || Pathfinder's license is available: ||
* || https://www.gnu.org/licenses/gpl-3.0.en.html ||
* || ||
* || Re-distribution of this, or any other files, is allowed so long ||
* || as this same copyright notice is included and made evident. ||
* || ||
* || Unless required by applicable law or agreed to in writing, any ||
* || 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 specific language ||
* || governing permissions and limitations under the license. ||
* || ||
* || Along with this file, you should have received a license file, ||
* || containing a copy of the GNU General Public License V3. If you ||
* || did not receive a copy of the license, you may find it online. ||
* ======================================================================
*
*/
package me.wobblyyyy.pathfinder.trajectory;
import me.wobblyyyy.edt.Arrayable;
import me.wobblyyyy.edt.DynamicArray;
import me.wobblyyyy.edt.StaticArray;
import me.wobblyyyy.pathfinder.geometry.Angle;
import me.wobblyyyy.pathfinder.geometry.HeadingPoint;
import me.wobblyyyy.pathfinder.geometry.Point;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Splines are incredibly useful in making complex movement
* trajectories and profiles. Unlike regular lines, splines, as you know, have
* an element of curvature. This element of curvature allows for your robot to
* continually move without ever having to come to a stop or a hard direction
* change. Splines themselves are representations of a concept, not fully
* fledged implementations of a trajectory following algorithm.
*
* <p>
* Splines, or at least these splines, make use of the Fritsch-Carlson method
* for computing internal spline parameters. This method isn't incredibly
* computationally expensive, but as a best practice, it's suggested that you
* do as little runtime execution of spline initialization.
* </p>
*
* <p>
* Interpolation is handled by yet another rather complex algorithm that nobody
* quite understands - including me, probably. Anyways, if you really are quite
* sincerely interested in learning how spline interpolation works, you can
* go check out the {@link SplineInterpolator} class - that has all the cool
* and sexy math you might want to look at.
* </p>
*
* @author Colin Robertson
* @since 0.3.0
*/
public class Spline implements Segment {
/**
* The internal spline interpolator. All of the hard math behind splines
* is handled in a separate class as to reduce code clutter and make the
* {@code Spline} class a bit more readable, especially for those without
* much experience in building splines.
*/
private final SplineInterpolator interpolator;
/**
* A set of each of the points that the spline should hit. This is used
* mostly for metadata about the spline.
*/
private final StaticArray<HeadingPoint> points;
/**
* An array of all of the angles contained on the spline's path.
* TODO implement angles
*/
private final DynamicArray<Angle> angles;
/**
* The minimum X value of the spline.
*/
private double xMinimum;
/**
* The minimum Y value of the spline.
*/
private double yMinimum;
/**
* The maximum X value of the spline.
*/
private double xMaximum;
/**
* The maximum Y value of the spline.
*/
private double yMaximum;
/**
* Is the spline's internal interpolator inverted?
*/
private final boolean isInverted;
/**
* Create a new {@code Spline} that will hit each of the required points.
* Splines are created so that they hit each and every one of the target
* points, meaning that if you tell the robot to pass through (10, 10),
* the robot will pass through (10, 10) no matter what.
*
* @param points a container that contains each of the required points.
* Each and every one of these points will be passed through
* directly by the spline computational system, meaning that
* the robot will go exactly where you tell it to go.
*/
public Spline(Arrayable<HeadingPoint> points) {
this.points = new StaticArray<>(points);
int size = points.size();
DynamicArray<Double> xValues = new DynamicArray<>(size);
DynamicArray<Double> yValues = new DynamicArray<>(size);
angles = new DynamicArray<>(size);
xMinimum = points.get(0).getX();
yMaximum = points.get(0).getY();
xMaximum = xMinimum;
yMaximum = yMinimum;
/*
* For each of the values contained in the arrays of points, check
* to see if those values are technically new minimums or maximums.
*
* If they're either of those, re-assign the min and max values.
*/
points.itr().forEach(point -> {
double x = point.getX();
double y = point.getY();
xValues.add(x);
yValues.add(y);
angles.add(point.getAngle());
xMinimum = Math.min(xMinimum, x);
yMinimum = Math.min(yMinimum, y);
xMaximum = Math.max(xMaximum, x);
yMaximum = Math.max(yMaximum, y);
});
ArrayList<Double> xList = fromDynamicArray(xValues);
ArrayList<Double> yList = fromDynamicArray(yValues);
/*
* Inline conditional assignment, I'm sorry. Oh well.
*
* isInverted is set to INVERSE of onlyIncreasing (x values)
*
* if isInverted is false:
* create a new monotone cubic spline
* if isInverted is true:
* create a new inverted monotone cubic spline
*/
interpolator = !(isInverted = !onlyIncreasing(xList)) ?
SplineInterpolator.monotoneCubic(xList, yList) :
SplineInterpolator.invertedMonotoneCubic(xList, yList);
}
/**
* Check to see if an {@code ArrayList} only has a sequence of increasing
* values - used for spline inversion.
*
* @param values the values to check.
* @return whether or not the values exclusively sequentially increase.
*/
private static boolean onlyIncreasing(ArrayList<Double> values) {
double lastValue = values.get(0);
for (double value : values) {
if (value != lastValue) {
if (!(value > lastValue)) return false;
}
lastValue = value;
}
return true;
}
/**
* Convert an {@code DynamicArray} into an {@code ArrayList}.
*
* @param array the {@code DynamicArray} to convert.
* @return the {@code ArrayList} that's been created.
*/
private ArrayList<Double> fromDynamicArray(DynamicArray<Double> array) {
Double[] doubleArray = array.toDoubleArray();
return new ArrayList<>(Arrays.asList(doubleArray));
}
/**
* Get a point from the segment based on an X value. This point should fit
* within the bounds of the segment and should be represented partially by
* the provided value, which provides a basis for interpolation from there.
*
* @param xValue the value that the segment should interpolate from. This
* means, in essence, that the segment should determine the
* nearest possible point to the requested X value.
* @return an interpolated point based on an inputted value. This point has
* no regard for heading - rather, it's a simple and plain point that can
* be used for following the trajectory or just figuring out where a
* certain value on the trajectory lies.
*/
@Override
public Point interpolateFromX(double xValue) {
return new Point(
xValue,
interpolator.interpolateFromX(!isInverted ?
xValue :
(Math.abs(xMaximum - xValue)) + xMaximum)
);
}
/**
* Get a point from the segment based on an Y value. This point should fit
* within the bounds of the segment and should be represented partially by
* the provided value, which provides a basis for interpolation from there.
*
* @param yValue the value that the segment should interpolate from. This
* means, in essence, that the segment should determine the
* nearest possible point to the requested Y value.
* @return an interpolated point based on an inputted value. This point has
* no regard for heading - rather, it's a simple and plain point that can
* be used for following the trajectory or just figuring out where a
* certain value on the trajectory lies.
*/
@Override
public Point interpolateFromY(double yValue) {
return new Point(
interpolator.interpolateFromY(!isInverted ?
yValue :
(Math.abs(yMaximum - yValue)) + yMaximum),
yValue
);
}
/**
* Get the angle which the robot should be facing at the given trajectory.
* This angle is handled separately from the interpolation methods to
* increase the degree of flexibility the {@code Segment} interface will
* provide both internally and externally.
*
* @param point the point that will serve as a basis for fetching the
* desired robot heading.
* @return the most closely interpolated heading/angle at a given point.
* This angle typically corresponds to how far along the segment the robot
* has travelled, but it's up to the implementations of the segment class
* to decide how exactly this is handled. Yay interfaces!
*/
@Override
public Angle angleAt(Point point) {
return points.get(points.size() - 1).getAngle();
}
/**
* Get a combination of the minimum X and Y values for the segment. This
* point is used to reduce primitive clutter - instead of returning an
* individual X and Y double, we can return a single point that represents
* our requested information.
*
* @return a combination of the requested X and Y values. This is used
* mostly in segment interpolation, as individual segments are predicated
* on raw X and Y coordinates, not interpolatable coordinates.
*/
@Override
public Point minimum() {
return new Point(
xMinimum,
yMinimum
);
}
/**
* Get a combination of the maximum X and Y values for the segment. This
* point is used to reduce primitive clutter - instead of returning an
* individual X and Y double, we can return a single point that represents
* our requested information.
*
* @return a combination of the requested X and Y values. This is used
* mostly in segment interpolation, as individual segments are predicated
* on raw X and Y coordinates, not interpolatable coordinates.
*/
@Override
public Point maximum() {
return new Point(
xMaximum,
yMaximum
);
}
/**
* Convert the spline to a string representation of the spline.
*
* @return the interpolator's representation of the spline in the very
* readable String form.
*/
@Override
public String toString() {
return interpolator.toString();
}
/**
* Get the point where the segment starts. This is defined as the position
* that represents 0 percent of the segment's completion.
*
* @return the point at which the segment begins.
*/
@Override
public Point start() {
return points.get(0);
}
/**
* Get the point where the segment ends. This is defined as the position
* that represents 100 percent of the segment's completion.
*
* @return the point at which the segment ends.
*/
@Override
public Point end() {
return points.get(points.size() - 1);
}
}
| 38.279883 | 79 | 0.606931 |
0e8d0dcfbd6b224186d1d6da9793171f45d83624 | 23,980 | package com.bewitchment.client.render.entity.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
/**
* lilith2 - cybercat5555
* Created using Tabula 5.1.0
*/
public class ModelLilith extends ModelBase {
public ModelRenderer bipedBody;
public ModelRenderer stomach;
public ModelRenderer boobs;
public ModelRenderer bipedHead;
public ModelRenderer bipedLeftArm;
public ModelRenderer bipedRightArm;
public ModelRenderer bipedLeftLeg;
public ModelRenderer bipedRightLeg;
public ModelRenderer hips;
public ModelRenderer skirtB;
public ModelRenderer skirtF;
public ModelRenderer lSkirt;
public ModelRenderer rSkirt;
public ModelRenderer lHorn01;
public ModelRenderer rHorn01;
public ModelRenderer mhair01;
public ModelRenderer lHair01;
public ModelRenderer rHair01;
public ModelRenderer mhair02;
public ModelRenderer upperJaw;
public ModelRenderer lowerJaw;
public ModelRenderer lEara;
public ModelRenderer rEara;
public ModelRenderer lHorn02;
public ModelRenderer lHorn03a;
public ModelRenderer lHorn03b;
public ModelRenderer lHorn03c;
public ModelRenderer lHorn03d;
public ModelRenderer lHorn04a;
public ModelRenderer lHorn04b;
public ModelRenderer lHorn04c;
public ModelRenderer lHorn04d;
public ModelRenderer lHorn05;
public ModelRenderer rHorn02;
public ModelRenderer rHorn03a;
public ModelRenderer rHorn03b;
public ModelRenderer rHorn03c;
public ModelRenderer rHorn03d;
public ModelRenderer rHorn04a;
public ModelRenderer rHorn04b;
public ModelRenderer rHorn04c;
public ModelRenderer rHorn04d;
public ModelRenderer rHorn05;
public ModelRenderer nose;
public ModelRenderer lFang;
public ModelRenderer rFang;
public ModelRenderer lEarb;
public ModelRenderer rEarb;
public ModelRenderer lArm02;
public ModelRenderer lClaw;
public ModelRenderer lWing01;
public ModelRenderer lWing02;
public ModelRenderer lWing01b;
public ModelRenderer lWing03;
public ModelRenderer lWing02b;
public ModelRenderer lWing04;
public ModelRenderer lWing03b;
public ModelRenderer lWing05;
public ModelRenderer lWing04b;
public ModelRenderer lWing05b;
public ModelRenderer lWing05c;
public ModelRenderer rArm02;
public ModelRenderer rClaw;
public ModelRenderer rWing01;
public ModelRenderer rWing02;
public ModelRenderer rWing01b;
public ModelRenderer rWing03;
public ModelRenderer rWing02b;
public ModelRenderer rWing04;
public ModelRenderer rWing03b;
public ModelRenderer rWing05;
public ModelRenderer rWing04b;
public ModelRenderer rWing05b;
public ModelRenderer rWing05c;
public ModelRenderer lLeg02;
public ModelRenderer lLeg03;
public ModelRenderer lHoof;
public ModelRenderer rLeg02;
public ModelRenderer rLeg03;
public ModelRenderer rHoof;
public ModelLilith() {
this.textureWidth = 128;
this.textureHeight = 64;
this.lowerJaw = new ModelRenderer(this, 32, 58);
this.lowerJaw.setRotationPoint(0.0F, -1.0F, -3.0F);
this.lowerJaw.addBox(-2.0F, -0.5F, -2.0F, 4, 1, 2, 0.0F);
this.setRotateAngle(lowerJaw, -0.13962634015954636F, 0.0F, 0.0F);
this.lHorn01 = new ModelRenderer(this, 37, 0);
this.lHorn01.setRotationPoint(2.0F, -6.4F, 1.5F);
this.lHorn01.addBox(0.0F, -1.0F, -1.0F, 2, 2, 2, 0.0F);
this.setRotateAngle(lHorn01, 0.0F, 0.0F, -0.6632251157578453F);
this.bipedLeftArm = new ModelRenderer(this, 44, 16);
this.bipedLeftArm.setRotationPoint(4.5F, 2.3F, -0.0F);
this.bipedLeftArm.addBox(-1.0F, -2.0F, -1.5F, 3, 11, 3, 0.0F);
this.setRotateAngle(bipedLeftArm, 0.10471975511965977F, 0.0F, -0.10000736613927509F);
this.lWing04b = new ModelRenderer(this, 81, 25);
this.lWing04b.setRotationPoint(0.0F, 1.7F, 0.8F);
this.lWing04b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 7, 0.0F);
this.rHorn02 = new ModelRenderer(this, 37, 6);
this.rHorn02.mirror = true;
this.rHorn02.setRotationPoint(-1.5F, 0.1F, 0.0F);
this.rHorn02.addBox(-3.0F, -1.0F, -1.0F, 3, 2, 2, 0.0F);
this.setRotateAngle(rHorn02, 0.0F, 0.0F, 0.5235987755982988F);
this.rSkirt = new ModelRenderer(this, 112, 45);
this.rSkirt.mirror = true;
this.rSkirt.setRotationPoint(-3.0F, 0.3F, -0.1F);
this.rSkirt.addBox(-1.4F, -0.8F, -2.0F, 2, 12, 5, 0.0F);
this.setRotateAngle(rSkirt, -0.22689280275926282F, 0.0F, 0.06981317007977318F);
this.lHorn03d = new ModelRenderer(this, 47, 0);
this.lHorn03d.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn03d.addBox(0.0F, -0.2F, -0.2F, 3, 1, 1, 0.0F);
this.nose = new ModelRenderer(this, 46, 58);
this.nose.setRotationPoint(0.0F, -0.8F, -2.0F);
this.nose.addBox(-1.5F, -2.9F, 0.0F, 3, 3, 0, 0.0F);
this.setRotateAngle(nose, 0.13962634015954636F, 0.0F, 0.0F);
this.lClaw = new ModelRenderer(this, 46, 48);
this.lClaw.setRotationPoint(0.0F, 11.5F, -0.6F);
this.lClaw.addBox(0.0F, 0.0F, -1.0F, 1, 5, 2, 0.0F);
this.setRotateAngle(lClaw, -0.3490658503988659F, 0.0F, 0.0F);
this.rWing05 = new ModelRenderer(this, 64, 46);
this.rWing05.mirror = true;
this.rWing05.setRotationPoint(0.0F, 0.0F, 6.6F);
this.rWing05.addBox(-0.5F, -0.5F, 0.0F, 1, 1, 7, 0.0F);
this.setRotateAngle(rWing05, 0.3490658503988659F, 0.0F, 0.0F);
this.lEara = new ModelRenderer(this, 22, 0);
this.lEara.setRotationPoint(2.9F, -4.0F, 0.0F);
this.lEara.addBox(-2.0F, -4.5F, -0.5F, 4, 5, 1, 0.0F);
this.setRotateAngle(lEara, -0.13962634015954636F, -0.6981317007977318F, 0.6981317007977318F);
this.rClaw = new ModelRenderer(this, 46, 48);
this.rClaw.mirror = true;
this.rClaw.setRotationPoint(0.0F, 11.5F, -0.6F);
this.rClaw.addBox(-1.0F, 0.0F, -1.0F, 1, 5, 2, 0.0F);
this.setRotateAngle(rClaw, -0.3490658503988659F, 0.0F, 0.0F);
this.rHair01 = new ModelRenderer(this, 109, 0);
this.rHair01.setRotationPoint(-2.7F, -5.5F, 0.6F);
this.rHair01.addBox(-0.5F, 0.0F, -3.5F, 1, 10, 7, 0.0F);
this.setRotateAngle(rHair01, 0.3665191429188092F, 0.0F, 0.22689280275926282F);
this.rWing05c = new ModelRenderer(this, 67, 55);
this.rWing05c.mirror = true;
this.rWing05c.setRotationPoint(0.0F, 0.2F, 7.4F);
this.rWing05c.addBox(-0.5F, -0.5F, -0.7F, 1, 1, 6, 0.0F);
this.setRotateAngle(rWing05c, 0.19198621771937624F, 0.0F, 0.0F);
this.lHoof = new ModelRenderer(this, 0, 58);
this.lHoof.setRotationPoint(0.0F, 7.4F, -0.2F);
this.lHoof.addBox(-1.5F, 0.0F, -2.3F, 3, 1, 4, 0.0F);
this.setRotateAngle(lHoof, 0.03490658503988659F, 0.0F, 0.0F);
this.bipedHead = new ModelRenderer(this, 0, 0);
this.bipedHead.setRotationPoint(0.0F, 0.0F, 0.0F);
this.bipedHead.addBox(-3.5F, -7.0F, -3.5F, 7, 7, 7, 0.0F);
this.rHorn03d = new ModelRenderer(this, 47, 0);
this.rHorn03d.mirror = true;
this.rHorn03d.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn03d.addBox(-3.0F, -0.2F, -0.2F, 3, 1, 1, 0.0F);
this.rHorn04b = new ModelRenderer(this, 47, 0);
this.rHorn04b.mirror = true;
this.rHorn04b.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn04b.addBox(-3.0F, -0.2F, -0.8F, 3, 1, 1, 0.0F);
this.rEarb = new ModelRenderer(this, 29, 8);
this.rEarb.mirror = true;
this.rEarb.setRotationPoint(0.9F, -4.0F, 0.0F);
this.rEarb.addBox(-1.0F, -3.2F, -0.5F, 2, 3, 1, 0.0F);
this.setRotateAngle(rEarb, 0.0F, 0.0F, 0.22689280275926282F);
this.rWing01 = new ModelRenderer(this, 64, 17);
this.rWing01.mirror = true;
this.rWing01.setRotationPoint(0.0F, 11.0F, 0.0F);
this.rWing01.addBox(-1.0F, -1.5F, 0.0F, 2, 3, 5, 0.0F);
this.setRotateAngle(rWing01, 0.10471975511965977F, 0.0F, -0.13962634015954636F);
this.lWing02 = new ModelRenderer(this, 64, 26);
this.lWing02.setRotationPoint(0.01F, 0.2F, 4.1F);
this.lWing02.addBox(-1.0F, -1.5F, 0.0F, 2, 3, 6, 0.0F);
this.setRotateAngle(lWing02, 0.41887902047863906F, 0.0F, 0.0F);
this.boobs = new ModelRenderer(this, 19, 48);
this.boobs.setRotationPoint(0.0F, 1.3F, -0.3F);
this.boobs.addBox(-3.5F, 0.0F, -2.0F, 7, 4, 4, 0.0F);
this.setRotateAngle(boobs, -0.593411945678072F, 0.0F, 0.0F);
this.lHorn04a = new ModelRenderer(this, 47, 0);
this.lHorn04a.setRotationPoint(2.7F, 0.1F, 0.0F);
this.lHorn04a.addBox(0.0F, -0.8F, -0.8F, 3, 1, 1, 0.0F);
this.setRotateAngle(lHorn04a, 0.0F, 0.0F, -0.3141592653589793F);
this.rHorn04a = new ModelRenderer(this, 47, 0);
this.rHorn04a.mirror = true;
this.rHorn04a.setRotationPoint(-2.7F, 0.1F, 0.0F);
this.rHorn04a.addBox(-3.0F, -0.8F, -0.8F, 3, 1, 1, 0.0F);
this.setRotateAngle(rHorn04a, 0.0F, 0.0F, 0.3141592653589793F);
this.rWing03b = new ModelRenderer(this, 74, 38);
this.rWing03b.mirror = true;
this.rWing03b.setRotationPoint(0.0F, 1.5F, 0.3F);
this.rWing03b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 8, 0.0F);
this.lFang = new ModelRenderer(this, 14, 57);
this.lFang.setRotationPoint(1.5F, 0.0F, -1.4F);
this.lFang.addBox(-0.49F, 0.0F, -0.5F, 1, 3, 1, 0.0F);
this.rHorn03a = new ModelRenderer(this, 47, 0);
this.rHorn03a.mirror = true;
this.rHorn03a.setRotationPoint(-2.7F, 0.1F, 0.0F);
this.rHorn03a.addBox(-3.0F, -0.8F, -0.8F, 3, 1, 1, 0.0F);
this.setRotateAngle(rHorn03a, 0.0F, 0.0F, 0.3665191429188092F);
this.rWing02 = new ModelRenderer(this, 64, 26);
this.rWing02.mirror = true;
this.rWing02.setRotationPoint(-0.01F, 0.2F, 4.1F);
this.rWing02.addBox(-1.0F, -1.5F, 0.0F, 2, 3, 6, 0.0F);
this.setRotateAngle(rWing02, 0.41887902047863906F, 0.0F, 0.0F);
this.lHair01 = new ModelRenderer(this, 90, 0);
this.lHair01.setRotationPoint(2.7F, -5.5F, 0.6F);
this.lHair01.addBox(-0.5F, 0.0F, -3.5F, 1, 10, 7, 0.0F);
this.setRotateAngle(lHair01, 0.3665191429188092F, 0.0F, -0.22689280275926282F);
this.rHoof = new ModelRenderer(this, 0, 58);
this.rHoof.mirror = true;
this.rHoof.setRotationPoint(0.0F, 7.4F, -0.2F);
this.rHoof.addBox(-1.5F, 0.0F, -2.3F, 3, 1, 4, 0.0F);
this.setRotateAngle(rHoof, 0.03490658503988659F, 0.0F, 0.0F);
this.rHorn01 = new ModelRenderer(this, 37, 0);
this.rHorn01.mirror = true;
this.rHorn01.setRotationPoint(-2.0F, -6.4F, 1.5F);
this.rHorn01.addBox(-2.0F, -1.0F, -1.0F, 2, 2, 2, 0.0F);
this.setRotateAngle(rHorn01, 0.0F, 0.0F, 0.6632251157578453F);
this.rWing04 = new ModelRenderer(this, 63, 36);
this.rWing04.mirror = true;
this.rWing04.setRotationPoint(0.0F, 0.0F, 6.6F);
this.rWing04.addBox(-1.0F, -1.0F, 0.0F, 2, 2, 7, 0.0F);
this.setRotateAngle(rWing04, 0.3490658503988659F, 0.0F, 0.0F);
this.rLeg02 = new ModelRenderer(this, 0, 32);
this.rLeg02.mirror = true;
this.rLeg02.setRotationPoint(-0.2F, 7.6F, -0.3F);
this.rLeg02.addBox(-1.5F, 0.0F, -2.0F, 3, 8, 4, 0.0F);
this.setRotateAngle(rLeg02, 0.6981317007977318F, 0.0F, -0.10471975511965977F);
this.lHorn04d = new ModelRenderer(this, 47, 0);
this.lHorn04d.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn04d.addBox(0.0F, -0.2F, -0.2F, 3, 1, 1, 0.0F);
this.rWing04b = new ModelRenderer(this, 81, 25);
this.rWing04b.mirror = true;
this.rWing04b.setRotationPoint(0.0F, 1.7F, 0.8F);
this.rWing04b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 7, 0.0F);
this.stomach = new ModelRenderer(this, 19, 28);
this.stomach.setRotationPoint(0.0F, 5.8F, 0.0F);
this.stomach.addBox(-3.0F, 0.0F, -1.5F, 6, 7, 3, 0.0F);
this.lHorn05 = new ModelRenderer(this, 47, 5);
this.lHorn05.setRotationPoint(2.8F, 0.0F, 0.0F);
this.lHorn05.addBox(0.0F, -0.5F, -0.5F, 3, 1, 1, 0.0F);
this.setRotateAngle(lHorn05, 0.0F, 0.0F, -0.22689280275926282F);
this.lHorn04c = new ModelRenderer(this, 47, 0);
this.lHorn04c.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn04c.addBox(0.0F, -0.8F, -0.2F, 3, 1, 1, 0.0F);
this.upperJaw = new ModelRenderer(this, 19, 57);
this.upperJaw.setRotationPoint(0.0F, -1.9F, -3.2F);
this.upperJaw.addBox(-2.0F, -1.5F, -2.0F, 4, 2, 2, 0.0F);
this.rArm02 = new ModelRenderer(this, 44, 31);
this.rArm02.mirror = true;
this.rArm02.setRotationPoint(-0.4F, 8.4F, 0.1F);
this.rArm02.addBox(-1.5F, 0.0F, -1.5F, 3, 12, 3, 0.0F);
this.setRotateAngle(rArm02, -0.3665191429188092F, 0.0F, 0.0F);
this.lWing04 = new ModelRenderer(this, 63, 36);
this.lWing04.setRotationPoint(0.0F, 0.0F, 6.6F);
this.lWing04.addBox(-1.0F, -1.0F, 0.0F, 2, 2, 7, 0.0F);
this.setRotateAngle(lWing04, 0.3490658503988659F, 0.0F, 0.0F);
this.lWing01 = new ModelRenderer(this, 64, 17);
this.lWing01.setRotationPoint(0.0F, 11.0F, 0.0F);
this.lWing01.addBox(-1.0F, -1.5F, 0.0F, 2, 3, 5, 0.0F);
this.setRotateAngle(lWing01, 0.10471975511965977F, 0.0F, 0.13962634015954636F);
this.rHorn05 = new ModelRenderer(this, 47, 5);
this.rHorn05.mirror = true;
this.rHorn05.setRotationPoint(-2.8F, 0.0F, 0.0F);
this.rHorn05.addBox(-3.0F, -0.5F, -0.5F, 3, 1, 1, 0.0F);
this.setRotateAngle(rHorn05, 0.0F, 0.0F, 0.22689280275926282F);
this.rWing03 = new ModelRenderer(this, 63, 36);
this.rWing03.mirror = true;
this.rWing03.setRotationPoint(0.0F, 0.2F, 5.6F);
this.rWing03.addBox(-1.0F, -1.0F, 0.0F, 2, 2, 7, 0.0F);
this.setRotateAngle(rWing03, 0.3665191429188092F, 0.0F, 0.0F);
this.lWing03 = new ModelRenderer(this, 63, 36);
this.lWing03.setRotationPoint(0.0F, 0.2F, 5.6F);
this.lWing03.addBox(-1.0F, -1.0F, 0.0F, 2, 2, 7, 0.0F);
this.setRotateAngle(lWing03, 0.3665191429188092F, 0.0F, 0.0F);
this.lWing02b = new ModelRenderer(this, 81, 25);
this.lWing02b.setRotationPoint(0.0F, 1.7F, 0.0F);
this.lWing02b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 7, 0.0F);
this.lLeg02 = new ModelRenderer(this, 0, 32);
this.lLeg02.setRotationPoint(0.2F, 7.6F, -0.3F);
this.lLeg02.addBox(-1.5F, 0.0F, -2.0F, 3, 8, 4, 0.0F);
this.setRotateAngle(lLeg02, 0.6981317007977318F, 0.0F, 0.10471975511965977F);
this.skirtB = new ModelRenderer(this, 98, 19);
this.skirtB.setRotationPoint(0.0F, -0.1F, 1.5F);
this.skirtB.addBox(-4.0F, 0.0F, -0.9F, 8, 12, 2, 0.0F);
this.lHorn02 = new ModelRenderer(this, 37, 6);
this.lHorn02.setRotationPoint(1.5F, 0.1F, 0.0F);
this.lHorn02.addBox(0.0F, -1.0F, -1.0F, 3, 2, 2, 0.0F);
this.setRotateAngle(lHorn02, 0.0F, 0.0F, -0.5235987755982988F);
this.bipedRightLeg = new ModelRenderer(this, 0, 16);
this.bipedRightLeg.mirror = true;
this.bipedRightLeg.setRotationPoint(-1.7F, 14.7F, -0.2F);
this.bipedRightLeg.addBox(-2.0F, -1.0F, -2.5F, 4, 10, 5, 0.0F);
this.setRotateAngle(bipedRightLeg, -0.3141592653589793F, 0.0F, 0.10471975511965977F);
this.lWing05 = new ModelRenderer(this, 64, 46);
this.lWing05.setRotationPoint(0.0F, 0.0F, 6.6F);
this.lWing05.addBox(-0.5F, -0.5F, 0.0F, 1, 1, 7, 0.0F);
this.setRotateAngle(lWing05, 0.3490658503988659F, 0.0F, 0.0F);
this.lHorn03a = new ModelRenderer(this, 47, 0);
this.lHorn03a.setRotationPoint(2.7F, 0.1F, 0.0F);
this.lHorn03a.addBox(0.0F, -0.8F, -0.8F, 3, 1, 1, 0.0F);
this.setRotateAngle(lHorn03a, 0.0F, 0.0F, -0.3665191429188092F);
this.rHorn04c = new ModelRenderer(this, 47, 0);
this.rHorn04c.mirror = true;
this.rHorn04c.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn04c.addBox(-3.0F, -0.8F, -0.2F, 3, 1, 1, 0.0F);
this.lWing01b = new ModelRenderer(this, 81, 18);
this.lWing01b.setRotationPoint(0.0F, 1.8F, 0.0F);
this.lWing01b.addBox(-0.5F, -1.2F, 0.0F, 1, 2, 5, 0.0F);
this.lHorn03c = new ModelRenderer(this, 47, 0);
this.lHorn03c.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn03c.addBox(0.0F, -0.8F, -0.2F, 3, 1, 1, 0.0F);
this.lLeg03 = new ModelRenderer(this, 0, 46);
this.lLeg03.setRotationPoint(0.0F, 7.4F, -0.2F);
this.lLeg03.addBox(-1.0F, 0.0F, -1.5F, 2, 8, 3, 0.0F);
this.setRotateAngle(lLeg03, -0.41887902047863906F, 0.0F, 0.0F);
this.rHorn04d = new ModelRenderer(this, 47, 0);
this.rHorn04d.mirror = true;
this.rHorn04d.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn04d.addBox(-3.0F, -0.2F, -0.2F, 3, 1, 1, 0.0F);
this.rLeg03 = new ModelRenderer(this, 0, 46);
this.rLeg03.mirror = true;
this.rLeg03.setRotationPoint(0.0F, 7.4F, -0.2F);
this.rLeg03.addBox(-1.0F, 0.0F, -1.5F, 2, 8, 3, 0.0F);
this.setRotateAngle(rLeg03, -0.41887902047863906F, 0.0F, 0.0F);
this.rFang = new ModelRenderer(this, 14, 57);
this.rFang.mirror = true;
this.rFang.setRotationPoint(-1.5F, 0.0F, -1.4F);
this.rFang.addBox(-0.51F, 0.0F, -0.5F, 1, 3, 1, 0.0F);
this.rHorn03c = new ModelRenderer(this, 47, 0);
this.rHorn03c.mirror = true;
this.rHorn03c.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn03c.addBox(-3.0F, -0.8F, -0.2F, 3, 1, 1, 0.0F);
this.lWing05b = new ModelRenderer(this, 81, 49);
this.lWing05b.setRotationPoint(0.0F, 1.6F, 0.2F);
this.lWing05b.addBox(-0.49F, -1.2F, -0.7F, 1, 2, 8, 0.0F);
this.setRotateAngle(lWing05b, 0.19198621771937624F, 0.0F, 0.0F);
this.lHorn03b = new ModelRenderer(this, 47, 0);
this.lHorn03b.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn03b.addBox(0.0F, -0.2F, -0.8F, 3, 1, 1, 0.0F);
this.bipedRightArm = new ModelRenderer(this, 44, 16);
this.bipedRightArm.mirror = true;
this.bipedRightArm.setRotationPoint(-4.5F, 2.3F, 0.0F);
this.bipedRightArm.addBox(-2.0F, -2.0F, -1.5F, 3, 11, 3, 0.0F);
this.setRotateAngle(bipedRightArm, 0.10471975511965977F, 0.0F, 0.10000736613927509F);
this.skirtF = new ModelRenderer(this, 93, 35);
this.skirtF.setRotationPoint(0.0F, -0.1F, -1.3F);
this.skirtF.addBox(-4.5F, -0.6F, -0.9F, 9, 12, 2, 0.0F);
this.setRotateAngle(skirtF, -0.3490658503988659F, 0.0F, 0.0F);
this.rWing05b = new ModelRenderer(this, 81, 49);
this.rWing05b.mirror = true;
this.rWing05b.setRotationPoint(0.0F, 1.6F, 0.2F);
this.rWing05b.addBox(-0.51F, -1.2F, -0.7F, 1, 2, 8, 0.0F);
this.setRotateAngle(rWing05b, 0.19198621771937624F, 0.0F, 0.0F);
this.lArm02 = new ModelRenderer(this, 44, 31);
this.lArm02.setRotationPoint(0.4F, 8.4F, 0.1F);
this.lArm02.addBox(-1.5F, 0.0F, -1.5F, 3, 12, 3, 0.0F);
this.setRotateAngle(lArm02, -0.3665191429188092F, 0.0F, 0.0F);
this.rEara = new ModelRenderer(this, 22, 0);
this.rEara.mirror = true;
this.rEara.setRotationPoint(-2.9F, -4.0F, 0.0F);
this.rEara.addBox(-2.0F, -4.5F, -0.5F, 4, 5, 1, 0.0F);
this.setRotateAngle(rEara, -0.13962634015954636F, 0.6981317007977318F, -0.6981317007977318F);
this.lWing05c = new ModelRenderer(this, 67, 55);
this.lWing05c.setRotationPoint(0.0F, 0.2F, 7.4F);
this.lWing05c.addBox(-0.5F, -0.5F, -0.7F, 1, 1, 6, 0.0F);
this.setRotateAngle(lWing05c, 0.19198621771937624F, 0.0F, 0.0F);
this.mhair02 = new ModelRenderer(this, 75, 0);
this.mhair02.setRotationPoint(0.0F, -2.0F, 3.0F);
this.mhair02.addBox(-3.0F, -1.0F, 0.0F, 6, 8, 1, 0.0F);
this.setRotateAngle(mhair02, 0.41887902047863906F, 0.0F, 0.0F);
this.lEarb = new ModelRenderer(this, 29, 8);
this.lEarb.setRotationPoint(-0.9F, -4.0F, 0.0F);
this.lEarb.addBox(-1.0F, -3.2F, -0.5F, 2, 3, 1, 0.0F);
this.setRotateAngle(lEarb, 0.0F, 0.0F, -0.22689280275926282F);
this.bipedLeftLeg = new ModelRenderer(this, 0, 16);
this.bipedLeftLeg.setRotationPoint(1.7F, 14.7F, -0.2F);
this.bipedLeftLeg.addBox(-2.0F, -1.0F, -2.5F, 4, 10, 5, 0.0F);
this.setRotateAngle(bipedLeftLeg, -0.3141592653589793F, 0.0F, -0.10471975511965977F);
this.rHorn03b = new ModelRenderer(this, 47, 0);
this.rHorn03b.mirror = true;
this.rHorn03b.setRotationPoint(0.0F, 0.0F, 0.0F);
this.rHorn03b.addBox(-3.0F, -0.2F, -0.8F, 3, 1, 1, 0.0F);
this.lWing03b = new ModelRenderer(this, 74, 38);
this.lWing03b.setRotationPoint(0.0F, 1.5F, 0.3F);
this.lWing03b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 8, 0.0F);
this.mhair01 = new ModelRenderer(this, 57, 0);
this.mhair01.setRotationPoint(0.0F, -5.6F, 3.1F);
this.mhair01.addBox(-3.5F, -1.0F, 0.0F, 7, 10, 1, 0.0F);
this.setRotateAngle(mhair01, 0.5235987755982988F, 0.0F, 0.0F);
this.bipedBody = new ModelRenderer(this, 19, 16);
this.bipedBody.setRotationPoint(0.0F, -12.6F, 0.0F);
this.bipedBody.addBox(-4.0F, 0.0F, -2.0F, 8, 6, 4, 0.0F);
this.hips = new ModelRenderer(this, 19, 39);
this.hips.setRotationPoint(0.0F, 6.3F, 0.0F);
this.hips.addBox(-3.5F, 0.0F, -2.0F, 7, 4, 4, 0.0F);
this.rWing01b = new ModelRenderer(this, 81, 18);
this.rWing01b.mirror = true;
this.rWing01b.setRotationPoint(0.0F, 1.8F, 0.0F);
this.rWing01b.addBox(-0.5F, -1.2F, 0.0F, 1, 2, 5, 0.0F);
this.rWing02b = new ModelRenderer(this, 81, 25);
this.rWing02b.mirror = true;
this.rWing02b.setRotationPoint(0.0F, 1.7F, 0.0F);
this.rWing02b.addBox(-0.5F, -1.2F, -0.7F, 1, 2, 7, 0.0F);
this.lSkirt = new ModelRenderer(this, 112, 45);
this.lSkirt.setRotationPoint(3.0F, 0.3F, -0.1F);
this.lSkirt.addBox(-0.6F, -0.8F, -2.0F, 2, 12, 5, 0.0F);
this.setRotateAngle(lSkirt, -0.22689280275926282F, 0.0F, -0.06981317007977318F);
this.lHorn04b = new ModelRenderer(this, 47, 0);
this.lHorn04b.setRotationPoint(0.0F, 0.0F, 0.0F);
this.lHorn04b.addBox(0.0F, -0.2F, -0.8F, 3, 1, 1, 0.0F);
this.bipedHead.addChild(this.lowerJaw);
this.bipedHead.addChild(this.lHorn01);
this.bipedBody.addChild(this.bipedLeftArm);
this.lWing04.addChild(this.lWing04b);
this.rHorn01.addChild(this.rHorn02);
this.hips.addChild(this.rSkirt);
this.lHorn03a.addChild(this.lHorn03d);
this.upperJaw.addChild(this.nose);
this.lArm02.addChild(this.lClaw);
this.rWing04.addChild(this.rWing05);
this.bipedHead.addChild(this.lEara);
this.rArm02.addChild(this.rClaw);
this.bipedHead.addChild(this.rHair01);
this.rWing05b.addChild(this.rWing05c);
this.lLeg03.addChild(this.lHoof);
this.bipedBody.addChild(this.bipedHead);
this.rHorn03a.addChild(this.rHorn03d);
this.rHorn04a.addChild(this.rHorn04b);
this.rEara.addChild(this.rEarb);
this.rArm02.addChild(this.rWing01);
this.lWing01.addChild(this.lWing02);
this.bipedBody.addChild(this.boobs);
this.lHorn03a.addChild(this.lHorn04a);
this.rHorn03a.addChild(this.rHorn04a);
this.rWing03.addChild(this.rWing03b);
this.upperJaw.addChild(this.lFang);
this.rHorn02.addChild(this.rHorn03a);
this.rWing01.addChild(this.rWing02);
this.bipedHead.addChild(this.lHair01);
this.rLeg03.addChild(this.rHoof);
this.bipedHead.addChild(this.rHorn01);
this.rWing03.addChild(this.rWing04);
this.bipedRightLeg.addChild(this.rLeg02);
this.lHorn04a.addChild(this.lHorn04d);
this.rWing04.addChild(this.rWing04b);
this.bipedBody.addChild(this.stomach);
this.lHorn04a.addChild(this.lHorn05);
this.lHorn04a.addChild(this.lHorn04c);
this.bipedHead.addChild(this.upperJaw);
this.bipedRightArm.addChild(this.rArm02);
this.lWing03.addChild(this.lWing04);
this.lArm02.addChild(this.lWing01);
this.rHorn04a.addChild(this.rHorn05);
this.rWing02.addChild(this.rWing03);
this.lWing02.addChild(this.lWing03);
this.lWing02.addChild(this.lWing02b);
this.bipedLeftLeg.addChild(this.lLeg02);
this.hips.addChild(this.skirtB);
this.lHorn01.addChild(this.lHorn02);
this.bipedBody.addChild(this.bipedRightLeg);
this.lWing04.addChild(this.lWing05);
this.lHorn02.addChild(this.lHorn03a);
this.rHorn04a.addChild(this.rHorn04c);
this.lWing01.addChild(this.lWing01b);
this.lHorn03a.addChild(this.lHorn03c);
this.lLeg02.addChild(this.lLeg03);
this.rHorn04a.addChild(this.rHorn04d);
this.rLeg02.addChild(this.rLeg03);
this.upperJaw.addChild(this.rFang);
this.rHorn03a.addChild(this.rHorn03c);
this.lWing05.addChild(this.lWing05b);
this.lHorn03a.addChild(this.lHorn03b);
this.bipedBody.addChild(this.bipedRightArm);
this.hips.addChild(this.skirtF);
this.rWing05.addChild(this.rWing05b);
this.bipedLeftArm.addChild(this.lArm02);
this.bipedHead.addChild(this.rEara);
this.lWing05b.addChild(this.lWing05c);
this.bipedHead.addChild(this.mhair02);
this.lEara.addChild(this.lEarb);
this.bipedBody.addChild(this.bipedLeftLeg);
this.rHorn03a.addChild(this.rHorn03b);
this.lWing03.addChild(this.lWing03b);
this.bipedHead.addChild(this.mhair01);
this.stomach.addChild(this.hips);
this.rWing01.addChild(this.rWing01b);
this.rWing02.addChild(this.rWing02b);
this.hips.addChild(this.lSkirt);
this.lHorn04a.addChild(this.lHorn04b);
}
@Override
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) {
this.bipedBody.render(f5);
}
/**
* This is a helper function from Tabula to set the rotation of model parts
*/
public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
| 46.472868 | 95 | 0.706422 |
9dbfb6b135909eb578b3763b7c6e32338fbdbdae | 2,365 | package org.sunbird.cb.hubservices.model;
import java.util.Date;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
public class ConnectionRequest {
@NotNull
@JsonProperty("userIdFrom")
private String userId;
@NotNull
@JsonProperty("userIdTo")
private String connectionId;
// name - department = label
@JsonProperty("userNameFrom")
private String userName;
@JsonProperty("userDepartmentFrom")
private String userDepartment;
public Integer getUserNodeId() {
return userNodeId;
}
public void setUserNodeId(Integer userNodeId) {
this.userNodeId = userNodeId;
}
public Integer getConnectionNodeId() {
return connectionNodeId;
}
public void setConnectionNodeId(Integer connectionNodeId) {
this.connectionNodeId = connectionNodeId;
}
@JsonProperty("userNameTo")
private String connectionName;
@JsonProperty("userDepartmentTo")
private String connectionDepartment;
private String status;
private String type;
private Date endDate;
private Integer userNodeId;
private Integer connectionNodeId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserDepartment() {
return userDepartment;
}
public void setUserDepartment(String userDepartment) {
this.userDepartment = userDepartment;
}
public String getConnectionName() {
return connectionName;
}
public void setConnectionName(String connectionName) {
this.connectionName = connectionName;
}
public String getConnectionDepartment() {
return connectionDepartment;
}
public void setConnectionDepartment(String connectionDepartment) {
this.connectionDepartment = connectionDepartment;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getConnectionId() {
return connectionId;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| 19.072581 | 67 | 0.757717 |
156bb812c268edaa2cabe56dde9d164e58f1648f | 364 | package com.t.core.remote.exception;
/**
* @author tb
* @date 2018/12/18 13:52
*/
public class RemoteCommandFieldCheckException extends Exception {
public RemoteCommandFieldCheckException(String message) {
super(message);
}
public RemoteCommandFieldCheckException(String message, Throwable cause) {
super(message, cause);
}
}
| 21.411765 | 78 | 0.708791 |
f4a42496e805fa1f833f234f4b5b5c8cbe4ad34f | 639 | package ru.job4j.tracker;
import java.util.ArrayList;
/**
* Interface for the "Tracker" class.
*
* @author Dmitrii Eskov (eskovdmi@gmail.com)
* @version 1.0
* @since 12.12.2018
*/
public interface Input {
/**
* Asks user a question and returns their answer.
* @param question - a question
* @return - user's answer
*/
public String ask(String question);
/**
* Asks user a question and returns their answer. This method is used for operating exceptions.
* @param question - a question
* @return - user's answer
*/
public int ask(String question, ArrayList<Integer> range);
} | 23.666667 | 99 | 0.649452 |
e4d47c1cff0f99c51fc6d42c33ecb1dd24d946a1 | 7,800 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.common.utils;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.util.Arrays;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SerialDetector extends ObjectInputStream {
private static final Logger logger = LoggerFactory.getLogger(SerialDetector.class);
private static final BlacklistConfiguration configuration = new BlacklistConfiguration();
/**
* Wrapper Constructor.
*
* @param inputStream The original InputStream, used by your service to receive serialized objects
* @throws java.io.IOException File I/O exception
* @throws IllegalStateException Invalid configuration exception
*/
public SerialDetector(final InputStream inputStream) throws IOException {
super(inputStream);
}
@Override
protected Class<?> resolveClass(final ObjectStreamClass serialInput) throws IOException, ClassNotFoundException {
if (isClassInBlacklist(serialInput)) {
if (!configuration.shouldCheck()) {
// Reporting mode
logger.info(String.format("Blacklist match: '%s'", serialInput.getName()));
} else {
// Blocking mode
logger.error(String.format("Blocked by blacklist'. Match found for '%s'", serialInput.getName()));
throw new InvalidClassException(serialInput.getName(), "Class blocked from deserialization (blacklist)");
}
}
return super.resolveClass(serialInput);
}
public static boolean isClassInBlacklist(final ObjectStreamClass serialInput) {
// Enforce SerialDetector's blacklist
Iterable<Pattern> blacklistIterable = configuration.blacklist();
if (blacklistIterable == null) {
return false;
}
boolean inBlacklist = false;
for (Pattern blackPattern : blacklistIterable) {
Matcher blackMatcher = blackPattern.matcher(serialInput.getName());
if (blackMatcher.find()) {
inBlacklist = true;
break;
}
}
return inBlacklist;
}
public static boolean shouldCheck() {
return configuration.shouldCheck();
}
static final class BlacklistConfiguration {
private static final String DUBBO_SECURITY_SERIALIZATION_CHECK = "dubbo.security.serialization.check";
private static final String DUBBO_SECURITY_SERIALIZATION_BLACKLIST = "dubbo.security.serialization.blacklist";
private static final String DUBBO_SECURITY_SERIALIZATION_BLACKLIST_FILE = "dubbo.registry.serialization.blacklist.file";
private boolean check;
private PatternList blacklistPattern;
BlacklistConfiguration() {
try {
check = Boolean.parseBoolean(getSecurityProperty(DUBBO_SECURITY_SERIALIZATION_CHECK, "false"));
String blacklist = getSecurityProperty(DUBBO_SECURITY_SERIALIZATION_BLACKLIST, "");
if (StringUtils.isEmpty(blacklist)) {
String blacklistFile = getSecurityProperty(DUBBO_SECURITY_SERIALIZATION_BLACKLIST_FILE, "");
if (StringUtils.isNotEmpty(blacklistFile)) {
blacklist = loadBlacklistFile(blacklistFile);
}
}
blacklistPattern = new PatternList(Constants.COMMA_SPLIT_PATTERN.split(blacklist));
} catch (Throwable t) {
logger.warn("Failed to initialize the Serialization Security Checker component!", t);
}
}
Iterable<Pattern> blacklist() {
return blacklistPattern;
}
boolean shouldCheck() {
return check;
}
private String loadBlacklistFile(String fileName) {
StringBuilder blacklist = new StringBuilder();
InputStream is = null;
File file = new File(fileName);
if (file.exists()) {
try {
is = new FileInputStream(fileName);
} catch (Throwable e) {
logger.warn("Failed to load " + fileName + " file " + e.getMessage(), e);
}
} else {
is = this.getClass().getClassLoader().getResourceAsStream(fileName);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("#") && StringUtils.isNotEmpty(line)) {
blacklist.append(line);
blacklist.append(",");
}
}
} catch (Throwable e) {
logger.warn("Failed to read from file " + fileName + e.getMessage(), e);
}
return blacklist.toString();
}
private String getSecurityProperty(String key, String defaultValue) {
String value = ConfigUtils.getSystemProperty(key);
if (StringUtils.isEmpty(value)) {
value = ConfigUtils.getProperty(key);
}
return StringUtils.isEmpty(value) ? defaultValue : value;
}
}
static final class PatternList implements Iterable<Pattern> {
private final Pattern[] patterns;
PatternList(final String... regExps) {
for (int i = 0; i < regExps.length; i++) {
if (regExps[i] == null) {
throw new IllegalStateException("Deserialization blacklist reg expression cannot be null!");
}
}
this.patterns = new Pattern[regExps.length];
for (int i = 0; i < regExps.length; i++) {
patterns[i] = Pattern.compile(regExps[i]);
}
}
@Override
public Iterator<Pattern> iterator() {
return new Iterator<Pattern>() {
int index = 0;
@Override
public boolean hasNext() {
return index < patterns.length;
}
@Override
public Pattern next() {
return patterns[index++];
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
@Override
public String toString() {
return Arrays.toString(patterns);
}
}
} | 37.320574 | 128 | 0.609872 |
886dac5c3b3969884da01ffb3eaec567b639a430 | 4,601 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache;
import java.io.Externalizable;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.query.FieldsQueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.lang.IgniteFuture;
/**
* Cache proxy.
*/
public interface IgniteCacheProxy<K, V> extends IgniteCache<K, V>, Externalizable {
/**
* @return Context.
*/
public GridCacheContext<K, V> context();
/**
* Gets cache proxy which does not acquire read lock on gateway enter, should be used only if grid read lock is
* externally acquired.
*
* @return Ignite cache proxy with simple gate.
*/
public IgniteCacheProxy<K, V> cacheNoGate();
/**
* Creates projection that will operate with binary objects.
* <p> Projection returned by this method will force cache not to deserialize binary objects,
* so keys and values will be returned from cache API methods without changes.
* Therefore, signature of the projection can contain only following types:
* <ul>
* <li>{@code BinaryObject} for binary classes</li>
* <li>All primitives (byte, int, ...) and there boxed versions (Byte, Integer, ...)</li>
* <li>Arrays of primitives (byte[], int[], ...)</li>
* <li>{@link String} and array of {@link String}s</li>
* <li>{@link UUID} and array of {@link UUID}s</li>
* <li>{@link Date} and array of {@link Date}s</li>
* <li>{@link java.sql.Timestamp} and array of {@link java.sql.Timestamp}s</li>
* <li>Enums and array of enums</li>
* <li> Maps, collections and array of objects (but objects inside them will still be converted if they are binary) </li>
* </ul>
* <p> For example, if you use {@link Integer} as a key and {@code Value} class as a value (which will be
* stored in binary format), you should acquire following projection to avoid deserialization:
* <pre>
* IgniteInternalCache<Integer, GridBinaryObject> prj = cache.keepBinary();
*
* // Value is not deserialized and returned in binary format.
* GridBinaryObject po = prj.get(1);
* </pre>
* <p> Note that this method makes sense only if cache is working in binary mode ({@code
* CacheConfiguration#isBinaryEnabled()} returns {@code true}. If not, this method is no-op and will return
* current projection.
*
* @return Projection for binary objects.
*/
public <K1, V1> IgniteCache<K1, V1> keepBinary();
/**
* @param dataCenterId Data center ID.
* @return Projection for data center id.
*/
public IgniteCache<K, V> withDataCenterId(byte dataCenterId);
/**
* @return Cache with skip store enabled.
*/
public IgniteCache<K, V> skipStore();
/** {@inheritDoc} */
@Override public IgniteCache<K, V> withAllowAtomicOpsInTx();
/**
* @return Internal proxy.
*/
public GridCacheProxyImpl<K, V> internalProxy();
/**
* @return {@code True} if proxy was closed.
*/
public boolean isProxyClosed();
/**
* Closes this proxy instance.
*/
public void closeProxy();
/**
* @return Future that contains cache destroy operation.
*/
public IgniteFuture<?> destroyAsync();
/**
* @return Future that contains cache close operation.
*/
public IgniteFuture<?> closeAsync();
/**
* Queries cache with multiple statements. Accepts {@link SqlFieldsQuery} class.
*
* @param qry SqlFieldsQuery.
* @return List of cursors.
* @see SqlFieldsQuery
*/
public List<FieldsQueryCursor<List<?>>> queryMultipleStatements(SqlFieldsQuery qry);
}
| 36.515873 | 129 | 0.667681 |
5e4b377c61b253f45880cc472afe8fb9fdc283c2 | 1,442 | package uk.gov.hmcts.reform.sscs.migration;
import java.util.Optional;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import uk.gov.hmcts.reform.sscs.ccd.domain.Benefit;
import uk.gov.hmcts.reform.sscs.ccd.domain.SscsCaseData;
@Service
@ConditionalOnProperty(value = "migration.case_access_management.enabled", havingValue = "true")
public class CaseAccessManagementDataMigration implements DataMigrationStep {
@Override
public void apply(SscsCaseData sscsCaseData) {
addCaseCategories(sscsCaseData);
addCaseNames(sscsCaseData);
setOgdTypeToDwp(sscsCaseData);
}
private void addCaseCategories(SscsCaseData sscsCaseData) {
Optional<Benefit> benefit = sscsCaseData.getBenefitType();
benefit.ifPresent(value -> sscsCaseData.getWorkAllocationFields().setCategories(value));
}
private void addCaseNames(SscsCaseData sscsCaseData) {
String caseName = sscsCaseData.getAppeal().getAppellant() != null
&& sscsCaseData.getAppeal().getAppellant().getName() != null
? sscsCaseData.getAppeal().getAppellant().getName().getFullNameNoTitle()
: null;
sscsCaseData.getWorkAllocationFields().setCaseNames(caseName);
}
private void setOgdTypeToDwp(SscsCaseData sscsCaseData) {
sscsCaseData.getWorkAllocationFields().setOgdType("DWP");
}
}
| 37.947368 | 96 | 0.744799 |
3f2a2388f82dbf90c93c6b17a788843a804e18f0 | 5,043 | /*
* MIT License
*
* Copyright (c) 2020 TerraForged
*
* 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 com.terraforged.core.cell;
import com.terraforged.core.concurrent.Resource;
import com.terraforged.core.concurrent.pool.ObjectPool;
import com.terraforged.core.concurrent.thread.context.ContextualThread;
import com.terraforged.world.biome.BiomeType;
import com.terraforged.world.terrain.Terrain;
// General Notes:
// - all float are values expected to be within the range 0.0 - 1.0 inclusive
// - an 'identity' is a value that is constant for all cells within a voronoi cell
// - the 'edge' value is the corresponding worley/distance noise for that voronoi cell
public class Cell {
// purely used to reset a cell's to defaults
// this is separate to the public Cell.EMPTY as that may accidentally be mutated
private static final Cell defaults = new Cell();
// represents a 'null' cell
private static final Cell EMPTY = new Cell() {
@Override
public boolean isAbsent() {
return true;
}
};
private static final ObjectPool<Cell> POOL = new ObjectPool<>(32, Cell::new);
public int continentX;
public int continentZ;
public float continentEdge;
public float continentIdentity;
public float terrainRegionEdge;
public float terrainRegionIdentity;
public Terrain terrain = Terrain.NONE;
public float biomeEdge = 1F;
public float biomeIdentity;
// represents the distance to a river/lake. value decreases the closer to a river the cell is
public float riverMask = 1F;
// a flag that tells the erosion filter not to apply any changes to this cell
public boolean erosionMask = false;
// the actual height data
public float value;
public float waterLevel = 0F;
// climate data
public float moisture = 0.5F;
public float temperature = 0.5F;
public BiomeType biomeType = BiomeType.GRASSLAND;
// random noise assigned to a large biome-aligned area
// current use-case is to change all sand biomes within a certain area to a single colour (yellow or red)
public float macroNoise;
// how steep the surface is at this cell's location
public float gradient;
// how much material was eroded at this cell's location
public float erosion;
// how much material was deposited at this cell's location
public float sediment;
public void copy(Cell other) {
value = other.value;
waterLevel = other.waterLevel;
continentIdentity = other.continentIdentity;
continentEdge = other.continentEdge;
terrainRegionIdentity = other.terrainRegionIdentity;
terrainRegionEdge = other.terrainRegionEdge;
biomeIdentity = other.biomeIdentity;
biomeEdge = other.biomeEdge;
riverMask = other.riverMask;
erosionMask = other.erosionMask;
moisture = other.moisture;
temperature = other.temperature;
macroNoise = other.macroNoise;
gradient = other.gradient;
erosion = other.erosion;
sediment = other.sediment;
biomeType = other.biomeType;
terrain = other.terrain;
}
public void reset() {
copy(defaults);
}
public boolean isAbsent() {
return false;
}
public static Cell empty() {
return EMPTY;
}
public static Resource<Cell> pooled() {
// prefer obtaining a cell from ContextualThreads
Thread current = Thread.currentThread();
if (current instanceof ContextualThread) {
ContextualThread contextual = (ContextualThread) current;
return contextual.getContext().cell;
} else {
Resource<Cell> item = POOL.get();
item.get().reset();
return item;
}
}
public interface Visitor {
void visit(Cell cell, int dx, int dz);
}
public interface ContextVisitor<C> {
void visit(Cell cell, int dx, int dz, C ctx);
}
}
| 32.535484 | 109 | 0.690065 |
424ccd55bd2765324f6e799b96586793f4255512 | 654 | package weather.sunrays.com.helper;
import android.net.Uri;
import java.util.Map;
/**
* Created by brajesh on 16/11/14.
*/
public class NetworkHelper {
// making it private so the that it cant be instantiated
private NetworkHelper(){}
public static String makeUrl(String baseUrl, Map<String , String > params){
Uri.Builder uriBuilder = Uri.parse(baseUrl).buildUpon();
if(params != null ){
for(Map.Entry<String, String> entry : params.entrySet()){
uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
return uriBuilder.build().toString();
}
}
| 27.25 | 82 | 0.639144 |
ff003053393d89fa335f6d34335d082ca23a820d | 1,225 | package bean;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Date;
import database.annotation.Column;
import database.annotation.Id;
import database.annotation.Table;
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 6768866785999319045L;
public User() throws RemoteException {
super();
}
public void setLastLoginToNow() {
lastLogin = new Timestamp((new Date()).getTime());
}
@Id
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "last_login")
private Timestamp lastLogin;
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 Timestamp getLastLogin() {
return lastLogin;
}
public void setLastLogin(Timestamp lastLogin) {
this.lastLogin = lastLogin;
}
}
| 20.081967 | 70 | 0.658776 |
c333e47e1c2224966ef24e3200ce3f6c258b8e9d | 870 | package org.jboss.resteasy.test.providers.jaxb.resource;
public class JaxbElementReadableWritableEntity {
private String entity;
public static final String NAME = "READABLEWRITEABLE";
private static final String PREFIX = "<" + NAME + ">";
private static final String SUFFIX = "</" + NAME + ">";
public JaxbElementReadableWritableEntity(final String entity) {
this.entity = entity;
}
public String toXmlString() {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX).append(entity).append(SUFFIX);
return sb.toString();
}
@Override
public String toString() {
return entity;
}
public static JaxbElementReadableWritableEntity fromString(String stream) {
String entity = stream.replaceAll(PREFIX, "").replaceAll(SUFFIX, "");
return new JaxbElementReadableWritableEntity(entity);
}
}
| 30 | 78 | 0.698851 |
9dcaff7f8ec029f9672b0086d5c1713ebe1348ce | 268 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package visao.processos;
/**
*
* @author brunn_000
*/
public class BuscaVenda extends Thread{
@Override
public void run(){
}
}
| 12.761905 | 52 | 0.597015 |
dcdd32ae081a37057da156c3a931d3a1f0658a12 | 3,565 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.security;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.net.URI;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.command.ActiveMQQueue;
public class JaasNetworkTest extends TestCase {
BrokerService broker1;
BrokerService broker2;
@Override
public void setUp() throws Exception {
System.setProperty("java.security.auth.login.config", "src/test/resources/login.config");
broker1 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker1.xml"));
broker2 = BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/security/broker2.xml"));
broker1.waitUntilStarted();
broker2.waitUntilStarted();
Thread.sleep(2000);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
broker1.stop();
broker1.waitUntilStopped();
broker2.stop();
broker2.waitUntilStopped();
}
public void testNetwork() throws Exception {
System.setProperty("javax.net.ssl.trustStore", "src/test/resources/org/apache/activemq/security/client.ts");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
System.setProperty("javax.net.ssl.trustStoreType", "jks");
System.setProperty("javax.net.ssl.keyStore", "src/test/resources/org/apache/activemq/security/client.ks");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.keyStoreType", "jks");
ActiveMQConnectionFactory producerFactory = new ActiveMQConnectionFactory("ssl://localhost:61617");
Connection producerConn = producerFactory.createConnection();
Session producerSess = producerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSess.createProducer(new ActiveMQQueue("test"));
producerConn.start();
TextMessage sentMessage = producerSess.createTextMessage("test");
producer.send(sentMessage);
ActiveMQConnectionFactory consumerFactory = new ActiveMQConnectionFactory("ssl://localhost:61618");
Connection consumerConn = consumerFactory.createConnection();
Session consumerSess = consumerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumerConn.start();
MessageConsumer consumer = consumerSess.createConsumer(new ActiveMQQueue("test"));
TextMessage receivedMessage = (TextMessage) consumer.receive(100);
assertEquals(sentMessage, receivedMessage);
}
}
| 41.941176 | 114 | 0.752595 |
43b85d9cc0bbda18525b22ad45e05bd8c5d42702 | 820 | package pl.jkkk.task0;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
/*------------------------ FIELDS REGION ------------------------*/
private static final IntWritable ONE = new IntWritable(1);
private Text word = new Text();
/*------------------------ METHODS REGION ------------------------*/
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
for (String token : value.toString().split("\\s+")) {
word.set(token);
context.write(word, ONE);
}
}
}
| 31.538462 | 72 | 0.591463 |
3bad58856c9c4568c522a885b045d2492a444cf9 | 363 | package eps.focuspro.test_data_dtos;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement
public class TestData {
@XmlElement
public List<TestGroup> testGroups;
@XmlElement
public List<TestUser> testUsers;
@XmlElement
public List<TestSpace> testSpaces;
}
| 20.166667 | 48 | 0.76584 |
e561377cecdb792c1d62643ecfdaeb1aac727ef0 | 4,232 | package com.jhomlala.persons.view;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.jhomlala.persons.data.R;
import com.jhomlala.persons.view.adapter.PersonAdapter;
import com.jhomlala.persons.model.Person;
import com.jhomlala.persons.viewmodel.PersonViewModel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class PersonsFragment extends Fragment {
private final String TAG = "PersonsFragment";
private PersonViewModel mViewModel;
private RecyclerView mRecyclerView;
private PersonAdapter mPersonAdapter;
private ProgressDialog mProgressDialog;
private Disposable mRemoveObservable;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_persons_list, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getActivity()).get(PersonViewModel.class);
mViewModel.getPersons().observe(getActivity(), personList-> {
updateRecycler(personList);
});
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupPersonRecycler(view);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mRemoveObservable != null) {
mRemoveObservable.dispose();
}
}
private void setupPersonRecycler(View rootView) {
mRecyclerView = rootView.findViewById(R.id.persons_recycler_view);
List<Person> initalPersonList = new ArrayList<>();
RecyclerViewClickListener clickListener = ((view, position) -> {
removePerson(position);
});
mPersonAdapter = new PersonAdapter(initalPersonList,clickListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mPersonAdapter);
}
private void removePerson(int position) {
showLoadingDialog();
mRemoveObservable = io.reactivex.Observable.defer((Callable<ObservableSource<String>>) () -> {
boolean status = mViewModel.removePerson(position);
String statusCode = status == true ? "Success": "Error";
return io.reactivex.Observable.just(statusCode);
}).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(status -> {
Log.d(TAG,"Element removed");
hideLoadingDialog();
Toast.makeText(getActivity(), "Person removed",
Toast.LENGTH_LONG).show();
});
}
private void updateRecycler(List<Person> personList) {
if (mPersonAdapter != null) {
Log.d(TAG, "Update recycler");
mPersonAdapter.updatePersonList(personList);
mPersonAdapter.notifyDataSetChanged();
}
}
private void showLoadingDialog(){
mProgressDialog = ProgressDialog.show(getActivity(), "",
"Loading. Please wait...", true);
}
private void hideLoadingDialog(){
if (mProgressDialog != null){
mProgressDialog.cancel();
}
}
}
| 35.266667 | 132 | 0.710066 |
40d3532a44409c83a253edbda0de10bf361bcbee | 5,011 | package servidor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import comandos.ComandosServer;
import mensajeria.Comando;
import mensajeria.Paquete;
import mensajeria.PaqueteAtacar;
import mensajeria.PaqueteBatalla;
import mensajeria.PaqueteDeMovimientos;
import mensajeria.PaqueteDeNpcs;
import mensajeria.PaqueteDePersonajes;
import mensajeria.PaqueteFinalizarBatalla;
import mensajeria.PaqueteMovimiento;
import mensajeria.PaquetePersonaje;
import mensajeria.PaqueteUsuario;
public class EscuchaCliente extends Thread {
private final Socket socket;
private final ObjectInputStream entrada;
private final ObjectOutputStream salida;
private int idPersonaje;
private final Gson gson = new Gson();
private PaquetePersonaje paquetePersonaje;
private PaqueteMovimiento paqueteMovimiento;
private PaqueteBatalla paqueteBatalla;
private PaqueteAtacar paqueteAtacar;
private PaqueteFinalizarBatalla paqueteFinalizarBatalla;
private PaqueteUsuario paqueteUsuario;
private PaqueteDeMovimientos paqueteDeMovimiento;
private PaqueteDePersonajes paqueteDePersonajes;
private PaqueteDeNpcs paqueteDeNpcs;
public EscuchaCliente(String ip, Socket socket, ObjectInputStream entrada, ObjectOutputStream salida) throws IOException {
this.socket = socket;
this.entrada = entrada;
this.salida = salida;
paquetePersonaje = new PaquetePersonaje();
}
public void run() {
try {
ComandosServer comand;
Paquete paquete;
Paquete paqueteSv = new Paquete(null, 0);
paqueteUsuario = new PaqueteUsuario();
String cadenaLeida = (String) entrada.readObject();
while (!((paquete = gson.fromJson(cadenaLeida, Paquete.class)).getComando() == Comando.DESCONECTAR)){
comand = (ComandosServer) paquete.getObjeto(Comando.NOMBREPAQUETE);
comand.setCadena(cadenaLeida);
comand.setEscuchaCliente(this);
comand.ejecutar();
cadenaLeida = (String) entrada.readObject();
}
entrada.close();
salida.close();
socket.close();
Servidor.getPersonajesConectados().remove(paquetePersonaje.getId());
Servidor.getUbicacionPersonajes().remove(paquetePersonaje.getId());
Servidor.getClientesConectados().remove(this);
for (EscuchaCliente conectado : Servidor.getClientesConectados()) {
paqueteDePersonajes = new PaqueteDePersonajes(Servidor.getPersonajesConectados());
paqueteDePersonajes.setComando(Comando.CONEXION);
conectado.salida.writeObject(gson.toJson(paqueteDePersonajes, PaqueteDePersonajes.class));
}
Servidor.log.append(paquete.getIp() + " se ha desconectado." + System.lineSeparator());
} catch (IOException | ClassNotFoundException e) {
Servidor.log.append("Error de conexion: " + e.getMessage() + System.lineSeparator());
}
}
public Socket getSocket() {
return socket;
}
public ObjectInputStream getEntrada() {
return entrada;
}
public ObjectOutputStream getSalida() {
return salida;
}
public PaquetePersonaje getPaquetePersonaje(){
return paquetePersonaje;
}
public int getIdPersonaje() {
return idPersonaje;
}
public PaqueteMovimiento getPaqueteMovimiento() {
return paqueteMovimiento;
}
public void setPaqueteMovimiento(PaqueteMovimiento paqueteMovimiento) {
this.paqueteMovimiento = paqueteMovimiento;
}
public PaqueteBatalla getPaqueteBatalla() {
return paqueteBatalla;
}
public void setPaqueteBatalla(PaqueteBatalla paqueteBatalla) {
this.paqueteBatalla = paqueteBatalla;
}
public PaqueteAtacar getPaqueteAtacar() {
return paqueteAtacar;
}
public void setPaqueteAtacar(PaqueteAtacar paqueteAtacar) {
this.paqueteAtacar = paqueteAtacar;
}
public PaqueteFinalizarBatalla getPaqueteFinalizarBatalla() {
return paqueteFinalizarBatalla;
}
public void setPaqueteFinalizarBatalla(PaqueteFinalizarBatalla paqueteFinalizarBatalla) {
this.paqueteFinalizarBatalla = paqueteFinalizarBatalla;
}
public PaqueteDeMovimientos getPaqueteDeMovimiento() {
return paqueteDeMovimiento;
}
public void setPaqueteDeMovimiento(PaqueteDeMovimientos paqueteDeMovimiento) {
this.paqueteDeMovimiento = paqueteDeMovimiento;
}
public PaqueteDePersonajes getPaqueteDePersonajes() {
return paqueteDePersonajes;
}
public void setPaqueteDePersonajes(PaqueteDePersonajes paqueteDePersonajes) {
this.paqueteDePersonajes = paqueteDePersonajes;
}
public void setIdPersonaje(int idPersonaje) {
this.idPersonaje = idPersonaje;
}
public void setPaquetePersonaje(PaquetePersonaje paquetePersonaje) {
this.paquetePersonaje = paquetePersonaje;
}
public PaqueteUsuario getPaqueteUsuario() {
return paqueteUsuario;
}
public void setPaqueteUsuario(PaqueteUsuario paqueteUsuario) {
this.paqueteUsuario = paqueteUsuario;
}
public PaqueteDeNpcs getPaqueteDeNpcs()
{
return paqueteDeNpcs;
}
public void setPaqueteDeNpcs(PaqueteDeNpcs paqueteDeNpcs)
{
this.paqueteDeNpcs = paqueteDeNpcs;
}
}
| 27.233696 | 123 | 0.789663 |
a0ce63a880069c6b9a8bc000026ed213dca0f855 | 933 | package au.id.tindall.distalg.raft.log.storage;
import au.id.tindall.distalg.raft.log.Term;
import au.id.tindall.distalg.raft.log.entries.LogEntry;
import java.util.List;
import java.util.Optional;
public interface LogStorage {
void add(LogEntry logEntry);
void truncate(int fromIndex);
default boolean hasEntry(int index) {
return size() >= index;
}
LogEntry getEntry(int index);
List<LogEntry> getEntries();
List<LogEntry> getEntries(int fromIndexInclusive, int toIndexExclusive);
default int getLastLogIndex() {
return size();
}
default int getNextLogIndex() {
return size() + 1;
}
default Optional<Term> getLastLogTerm() {
return isEmpty() ?
Optional.empty()
: Optional.of(getEntry(getLastLogIndex()).getTerm());
}
default boolean isEmpty() {
return size() == 0;
}
int size();
}
| 20.733333 | 76 | 0.636656 |
6b01c3e3d80808d9b7954c7557bd9e5bfa94dcb3 | 5,938 | package com.datastax.tutorial;
import java.time.Duration;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.hc.client5.http.auth.StandardAuthScheme;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.core5.util.Timeout;
import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.config.TypedDriverOption;
import com.datastax.stargate.sdk.StargateClient;
import com.datastax.stargate.sdk.audit.AnsiConsoleLogger;
import com.datastax.stargate.sdk.config.StargateNodeConfig;
import com.evanlennick.retry4j.config.RetryConfigBuilder;
public class StargateCrossDCFailover {
public static final int NB_TRY_BEFORE_FAILOVER = 3;
public static final String DC1 = "DC1";
public static final String DC2 = "DC2";
public static void main(String[] args) {
try (StargateClient stargateClient = setupStargate()) {
while(true) {
int idx = 0;
while(idx++ < NB_TRY_BEFORE_FAILOVER) {
Thread.sleep(2000);
System.out.println("- TEST -");
testCqlApi(stargateClient);
testRestApi(stargateClient);
testDocumentaApi(stargateClient);
testGraphQLApi(stargateClient);
//testGrpcApi(stargateClient);
}
}
} catch (InterruptedException e) {}
}
public static StargateClient setupStargate() {
return StargateClient.builder()
.withApplicationName("FullSample")
// Setup DC1
.withLocalDatacenter(DC1)
.withAuthCredentials("cassandra", "cassandra")
.withCqlContactPoints("localhost:9052")
.withCqlKeyspace("system")
.withCqlConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM)
.withCqlDriverOption(TypedDriverOption.CONNECTION_CONNECT_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOption(TypedDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOption(TypedDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOption(TypedDriverOption.CONTROL_CONNECTION_TIMEOUT, Duration.ofSeconds(10))
.withApiNode(new StargateNodeConfig("dc1s1", "localhost", 8081, 8082, 8080, 8083))
.withApiNode(new StargateNodeConfig("dc1s2", "localhost", 9091, 9092, 9090, 9093))
// Setup DC2
.withApiNodeDC(DC2, new StargateNodeConfig("dc2s1", "localhost", 6061, 6062, 6060, 6063))
.withApiNodeDC(DC2, new StargateNodeConfig("dc2s2", "localhost", 7071, 7072, 7070, 7073))
.withCqlContactPointsDC(DC2, "localhost:9062")
.withCqlDriverOptionDC(DC2,TypedDriverOption.CONNECTION_CONNECT_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOptionDC(DC2,TypedDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOptionDC(DC2,TypedDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT, Duration.ofSeconds(10))
.withCqlDriverOptionDC(DC2,TypedDriverOption.CONTROL_CONNECTION_TIMEOUT, Duration.ofSeconds(10))
// Setup HTTP
.withHttpRequestConfig(RequestConfig.custom()
.setCookieSpec(StandardCookieSpec.STRICT)
.setExpectContinueEnabled(true)
.setConnectionRequestTimeout(Timeout.ofSeconds(5))
.setConnectTimeout(Timeout.ofSeconds(5))
.setTargetPreferredAuthSchemes(Arrays.asList(StandardAuthScheme.NTLM, StandardAuthScheme.DIGEST))
.build())
.withHttpRetryConfig(new RetryConfigBuilder()
//.retryOnSpecificExceptions(ConnectException.class, IOException.class)
.retryOnAnyException()
.withDelayBetweenTries( Duration.ofMillis(100))
.withExponentialBackoff()
.withMaxNumberOfTries(3)
.build())
.addHttpObserver("logger_light", new AnsiConsoleLogger())
.build();
}
public static void testCqlApi(StargateClient stargateClient) {
//CqlSession cqlSession = stargateClient.cqlSession().get();
System.out.println("DataCenter Name (cql) : " +
stargateClient.cqlSession().get()
.execute("SELECT data_center from system.local")
.one().getString("data_center"));
}
public static void testRestApi(StargateClient stargateClient) {
//System.out.println("Keyspaces (rest) : " + stargateClient.apiRest()
// .keyspaceNames().collect(Collectors.toList()));
stargateClient.apiRest().keyspaceNames().collect(Collectors.toList());
}
public static void testDocumentaApi(StargateClient stargateClient) {
// System.out.println("Namespaces (doc) : " + stargateClient.apiDocument()
// .namespaceNames().collect(Collectors.toList()));
stargateClient.apiDocument().namespaceNames().collect(Collectors.toList());
}
public static void testGraphQLApi(StargateClient stargateClient) {
//System.out.println("Keyspaces (graphQL) : " + stargateClient.apiGraphQL().cqlSchema().keyspaces());
stargateClient.apiGraphQL().cqlSchema().keyspaces();
}
public static void testGrpcApi(StargateClient stargateClient) {
System.out.println("Cql Version (grpc) : " + stargateClient.apiGrpc().execute("SELECT cql_version from system.local")
.one().getString("cql_version"));
}
}
| 50.322034 | 126 | 0.64062 |
7810d7f8396009a58daade0e456de3b1fd6711a5 | 11,048 | /* */ package net.querz.nbt;
/* */
/* */ import java.io.DataInputStream;
/* */ import java.io.DataOutputStream;
/* */ import java.io.IOException;
/* */ import java.util.Collection;
/* */ import java.util.HashMap;
/* */ import java.util.Iterator;
/* */ import java.util.Map;
/* */ import java.util.Objects;
/* */ import java.util.Set;
/* */ import java.util.function.BiConsumer;
/* */
/* */ public class CompoundTag
/* */ extends Tag<Map<String, Tag<?>>> implements Iterable<Map.Entry<String, Tag<?>>>, Comparable<CompoundTag> {
/* */ public CompoundTag() {
/* 17 */ super(createEmptyValue());
/* */ }
/* */
/* */ private static Map<String, Tag<?>> createEmptyValue() {
/* 21 */ return new HashMap<>(8);
/* */ }
/* */
/* */ public int size() {
/* 25 */ return getValue().size();
/* */ }
/* */
/* */ public Tag<?> remove(String key) {
/* 29 */ return getValue().remove(key);
/* */ }
/* */
/* */ public void clear() {
/* 33 */ getValue().clear();
/* */ }
/* */
/* */ public boolean containsKey(String key) {
/* 37 */ return getValue().containsKey(key);
/* */ }
/* */
/* */ public boolean containsValue(Tag<?> value) {
/* 41 */ return getValue().containsValue(value);
/* */ }
/* */
/* */ public Collection<Tag<?>> values() {
/* 45 */ return getValue().values();
/* */ }
/* */
/* */ public Set<String> keySet() {
/* 49 */ return getValue().keySet();
/* */ }
/* */
/* */ public Set<Map.Entry<String, Tag<?>>> entrySet() {
/* 53 */ return new NonNullEntrySet<>(getValue().entrySet());
/* */ }
/* */
/* */
/* */ public Iterator<Map.Entry<String, Tag<?>>> iterator() {
/* 58 */ return entrySet().iterator();
/* */ }
/* */
/* */ public void forEach(BiConsumer<String, Tag<?>> action) {
/* 62 */ getValue().forEach(action);
/* */ }
/* */
/* */ public <C extends Tag<?>> C get(String key, Class<C> type) {
/* 66 */ Tag<?> t = getValue().get(key);
/* 67 */ if (t != null) {
/* 68 */ return type.cast(t);
/* */ }
/* 70 */ return null;
/* */ }
/* */
/* */ public Tag<?> get(String key) {
/* 74 */ return getValue().get(key);
/* */ }
/* */
/* */ public ByteTag getByteTag(String key) {
/* 78 */ return get(key, ByteTag.class);
/* */ }
/* */
/* */ public ShortTag getShortTag(String key) {
/* 82 */ return get(key, ShortTag.class);
/* */ }
/* */
/* */ public IntTag getIntTag(String key) {
/* 86 */ return get(key, IntTag.class);
/* */ }
/* */
/* */ public LongTag getLongTag(String key) {
/* 90 */ return get(key, LongTag.class);
/* */ }
/* */
/* */ public FloatTag getFloatTag(String key) {
/* 94 */ return get(key, FloatTag.class);
/* */ }
/* */
/* */ public DoubleTag getDoubleTag(String key) {
/* 98 */ return get(key, DoubleTag.class);
/* */ }
/* */
/* */ public StringTag getStringTag(String key) {
/* 102 */ return get(key, StringTag.class);
/* */ }
/* */
/* */ public ByteArrayTag getByteArrayTag(String key) {
/* 106 */ return get(key, ByteArrayTag.class);
/* */ }
/* */
/* */ public IntArrayTag getIntArrayTag(String key) {
/* 110 */ return get(key, IntArrayTag.class);
/* */ }
/* */
/* */ public LongArrayTag getLongArrayTag(String key) {
/* 114 */ return get(key, LongArrayTag.class);
/* */ }
/* */
/* */ public ListTag<?> getListTag(String key) {
/* 118 */ return get(key, ListTag.class);
/* */ }
/* */
/* */ public CompoundTag getCompoundTag(String key) {
/* 122 */ return get(key, CompoundTag.class);
/* */ }
/* */
/* */ public boolean getBoolean(String key) {
/* 126 */ Tag<?> t = get(key);
/* 127 */ return (t instanceof ByteTag && ((ByteTag)t).asByte() > 0);
/* */ }
/* */
/* */ public byte getByte(String key) {
/* 131 */ ByteTag t = getByteTag(key);
/* 132 */ return (t == null) ? 0 : t.asByte();
/* */ }
/* */
/* */ public short getShort(String key) {
/* 136 */ ShortTag t = getShortTag(key);
/* 137 */ return (t == null) ? 0 : t.asShort();
/* */ }
/* */
/* */ public int getInt(String key) {
/* 141 */ IntTag t = getIntTag(key);
/* 142 */ return (t == null) ? 0 : t.asInt();
/* */ }
/* */
/* */ public long getLong(String key) {
/* 146 */ LongTag t = getLongTag(key);
/* 147 */ return (t == null) ? 0L : t.asLong();
/* */ }
/* */
/* */ public float getFloat(String key) {
/* 151 */ FloatTag t = getFloatTag(key);
/* 152 */ return (t == null) ? 0.0F : t.asFloat();
/* */ }
/* */
/* */ public double getDouble(String key) {
/* 156 */ DoubleTag t = getDoubleTag(key);
/* 157 */ return (t == null) ? 0.0D : t.asDouble();
/* */ }
/* */
/* */ public String getString(String key) {
/* 161 */ StringTag t = getStringTag(key);
/* 162 */ return (t == null) ? "" : t.getValue();
/* */ }
/* */
/* */ public byte[] getByteArray(String key) {
/* 166 */ ByteArrayTag t = getByteArrayTag(key);
/* 167 */ return (t == null) ? ByteArrayTag.ZERO_VALUE : t.getValue();
/* */ }
/* */
/* */ public int[] getIntArray(String key) {
/* 171 */ IntArrayTag t = getIntArrayTag(key);
/* 172 */ return (t == null) ? IntArrayTag.ZERO_VALUE : t.getValue();
/* */ }
/* */
/* */ public long[] getLongArray(String key) {
/* 176 */ LongArrayTag t = getLongArrayTag(key);
/* 177 */ return (t == null) ? LongArrayTag.ZERO_VALUE : t.getValue();
/* */ }
/* */
/* */ public Tag<?> put(String key, Tag<?> tag) {
/* 181 */ return getValue().put(Objects.requireNonNull(key), Objects.requireNonNull(tag));
/* */ }
/* */
/* */ public Tag<?> putBoolean(String key, boolean value) {
/* 185 */ return put(key, new ByteTag(value));
/* */ }
/* */
/* */ public Tag<?> putByte(String key, byte value) {
/* 189 */ return put(key, new ByteTag(value));
/* */ }
/* */
/* */ public Tag<?> putShort(String key, short value) {
/* 193 */ return put(key, new ShortTag(value));
/* */ }
/* */
/* */ public Tag<?> putInt(String key, int value) {
/* 197 */ return put(key, new IntTag(value));
/* */ }
/* */
/* */ public Tag<?> putLong(String key, long value) {
/* 201 */ return put(key, new LongTag(value));
/* */ }
/* */
/* */ public Tag<?> putFloat(String key, float value) {
/* 205 */ return put(key, new FloatTag(value));
/* */ }
/* */
/* */ public Tag<?> putDouble(String key, double value) {
/* 209 */ return put(key, new DoubleTag(value));
/* */ }
/* */
/* */ public Tag<?> putString(String key, String value) {
/* 213 */ return put(key, new StringTag(value));
/* */ }
/* */
/* */ public Tag<?> putByteArray(String key, byte[] value) {
/* 217 */ return put(key, new ByteArrayTag(value));
/* */ }
/* */
/* */ public Tag<?> putIntArray(String key, int[] value) {
/* 221 */ return put(key, new IntArrayTag(value));
/* */ }
/* */
/* */ public Tag<?> putLongArray(String key, long[] value) {
/* 225 */ return put(key, new LongArrayTag(value));
/* */ }
/* */
/* */
/* */ public void serializeValue(DataOutputStream dos, int maxDepth) throws IOException {
/* 230 */ for (Map.Entry<String, Tag<?>> e : getValue().entrySet()) {
/* 231 */ ((Tag)e.getValue()).serialize(dos, e.getKey(), decrementMaxDepth(maxDepth));
/* */ }
/* 233 */ EndTag.INSTANCE.serialize(dos, maxDepth);
/* */ }
/* */
/* */
/* */ public void deserializeValue(DataInputStream dis, int maxDepth) throws IOException {
/* 238 */ clear();
/* 239 */ for (int id = dis.readByte() & 0xFF; id != 0; id = dis.readByte() & 0xFF) {
/* 240 */ Tag<?> tag = TagFactory.fromID(id);
/* 241 */ String name = dis.readUTF();
/* 242 */ tag.deserializeValue(dis, decrementMaxDepth(maxDepth));
/* 243 */ put(name, tag);
/* */ }
/* */ }
/* */
/* */
/* */ public String valueToString(int maxDepth) {
/* 249 */ StringBuilder sb = new StringBuilder("{");
/* 250 */ boolean first = true;
/* 251 */ for (Map.Entry<String, Tag<?>> e : getValue().entrySet()) {
/* 252 */ sb.append(first ? "" : ",")
/* 253 */ .append(escapeString(e.getKey(), false)).append(":")
/* 254 */ .append(((Tag)e.getValue()).toString(decrementMaxDepth(maxDepth)));
/* 255 */ first = false;
/* */ }
/* 257 */ sb.append("}");
/* 258 */ return sb.toString();
/* */ }
/* */
/* */
/* */ public String valueToTagString(int maxDepth) {
/* 263 */ StringBuilder sb = new StringBuilder("{");
/* 264 */ boolean first = true;
/* 265 */ for (Map.Entry<String, Tag<?>> e : getValue().entrySet()) {
/* 266 */ sb.append(first ? "" : ",")
/* 267 */ .append(escapeString(e.getKey(), true)).append(":")
/* 268 */ .append(((Tag)e.getValue()).valueToTagString(decrementMaxDepth(maxDepth)));
/* 269 */ first = false;
/* */ }
/* 271 */ sb.append("}");
/* 272 */ return sb.toString();
/* */ }
/* */
/* */
/* */ public boolean equals(Object other) {
/* 277 */ if (this == other) {
/* 278 */ return true;
/* */ }
/* 280 */ if (!super.equals(other) || size() != ((CompoundTag)other).size()) {
/* 281 */ return false;
/* */ }
/* 283 */ for (Map.Entry<String, Tag<?>> e : getValue().entrySet()) {
/* */ Tag<?> v;
/* 285 */ if ((v = ((CompoundTag)other).get(e.getKey())) == null || !((Tag)e.getValue()).equals(v)) {
/* 286 */ return false;
/* */ }
/* */ }
/* 289 */ return true;
/* */ }
/* */
/* */
/* */ public int compareTo(CompoundTag o) {
/* 294 */ return Integer.compare(size(), o.getValue().size());
/* */ }
/* */
/* */
/* */ public CompoundTag clone() {
/* 299 */ CompoundTag copy = new CompoundTag();
/* 300 */ for (Map.Entry<String, Tag<?>> e : getValue().entrySet()) {
/* 301 */ copy.put(e.getKey(), ((Tag)e.getValue()).clone());
/* */ }
/* 303 */ return copy;
/* */ }
/* */ }
/* Location: C:\Users\Main\AppData\Roaming\StreamCraf\\updates\Launcher.jar!\net\querz\nbt\CompoundTag.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 35.524116 | 121 | 0.478639 |
b2767cc422d2246fc9838dde586063096a1e39a5 | 10,597 | /*
* The MIT License
*
* Copyright 2016 Liu.
*
* 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 Hint;
import Model.ACClass;
import Model.Field;
import Model.InputParameter;
import Model.Method;
import Model.MethodLine;
import Model.MethodLineFunctions;
import Model.ModelFactory;
import Model.Project;
import Utility.GetArrayList;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Liu
*/
public class HintGeneratorTest
{
HintGenerator _HintGenerator;
List<MethodLine> _CurrentMethodLines;
List<Field> _CurrentFields;
ACClass _CurrentCLS;
public HintGeneratorTest()
{
GetArrayList<Field> fieldListGetter = new GetArrayList<>();
GetArrayList<Method> methodListGetter = new GetArrayList<>();
GetArrayList<ACClass> clsListGetter = new GetArrayList<>();
Field mjfa = ModelFactory.GetFieldWithValue("", "mjfa", "public", "", new ArrayList<String>(), false, false);
Field mjfbs = ModelFactory.GetFieldWithValue("", "mjfbs", "public", "", new ArrayList<String>(), true, false);
List<Field> mjfields = fieldListGetter.Get(mjfa, mjfbs);
Method mjma = ModelFactory.GetMethodWithValue("void", "mjma", "public", false, false, false, new ArrayList<InputParameter>(), new ArrayList<String>(), new ArrayList<>());
List<Method> mjmethods = methodListGetter.Get(mjma);
ACClass mjcls = ModelFactory.GetClassWithValue("mjcls", "public", false, false, new ArrayList<String>(), new ArrayList<String>(), mjfields, mjmethods, new ArrayList<String>(), false, false, 0, 0);
List<ACClass> mjclses = clsListGetter.Get(mjcls);
Model_Java mj = new Model_Java("", mjclses);
MethodLine pamal1 = ModelFactory.GetMethodLineWithValue("int", "index", MethodLineFunctions.Other, "", 0, 0, "", new ArrayList<String>(), new ArrayList<>());
MethodLine pamal2 = ModelFactory.GetMethodLineWithValue("", "", MethodLineFunctions.For, "int id = 0; id < 5; id++", 0, 0, "", new ArrayList<String>(), new ArrayList<>());
List<MethodLine> pamamethodlLines = (new GetArrayList<MethodLine>()).Get(pamal1,pamal2);
_CurrentMethodLines = pamamethodlLines;
Method pama = ModelFactory.GetMethodWithValue("void", "pama", "public", false, false, false, new ArrayList<InputParameter>(), new ArrayList<String>(), pamamethodlLines);
List<Method> pamethods = methodListGetter.Get(pama);
Field pafa = ModelFactory.GetFieldWithValue("", "pafa", "public", "", new ArrayList<String>(), false, false);
Field pafbs = ModelFactory.GetFieldWithValue("", "pafbs", "public", "", new ArrayList<String>(), true, true);
List<Field> pafields = fieldListGetter.Get(pafa, pafbs);
_CurrentFields = pafields;
ACClass pacls = ModelFactory.GetClassWithValue("pacls", "public", false, false, new ArrayList<String>(), new ArrayList<String>(), pafields, pamethods, new ArrayList<String>(), false, false, 0, 0);
_CurrentCLS = pacls;
List<ACClass> paclses = clsListGetter.Get(pacls);
Project pj = ModelFactory.GetProjectWithValue(paclses, "test");
_HintGenerator = new HintGenerator(pj, mj);
}
@Test
public void testGetClsNamesFromSDKPkgs()
{
System.out.println("GetClsNamesFromSDKPkgs");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetClsNamesFromSDKPkgs();
assertEquals(result.size(), 1);
assertTrue(result.contains("mjcls"));
assertFalse(result.contains("pacls"));
}
@Test
public void testGetMthdNamesFromSDKPkgs()
{
System.out.println("GetMthdNamesFromSDKPkgs");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetMthdNamesFromSDKPkgs();
assertTrue(result.contains("mjma"));
assertFalse(result.contains("pama"));
}
@Test
public void testGetStaticFieldNamesFromSDKPkgs()
{
System.out.println("GetStaticFieldNamesFromSDKPkgs");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetStaticFieldNamesFromSDKPkgs();
assertEquals(result.size(), 1);
assertTrue(result.contains("mjcls.mjfbs"));
}
@Test
public void testGetNamesStartWithInput()
{
System.out.println("GetNamesStartWithInput");
String input = "abc";
GetArrayList<String> getter = new GetArrayList<>();
List<String> variableNames = getter.Get("abcd", "abd", "def", "def.abcd");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetNamesStartWithInput(input, variableNames);
assertEquals(2,result.size());
assertTrue(result.contains("abcd"));
assertTrue(result.contains("def.abcd"));
}
@Test
public void testGetStaticVariableNamesOfCurrentProject()
{
System.out.println("GetStaticVariableNamesOfCurrentProject");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetStaticFieldNamesOfCurrentProject();
assertEquals(result.size(), 1);
assertTrue(result.contains("pacls.pafbs"));
}
@Test
public void testGetMethodNamesOfCurrentProject()
{
System.out.println("GetMethodNamesOfCurrentProject");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetMethodNamesOfCurrentProject();
assertEquals(1, result.size());
assertTrue(result.contains("pama"));
assertFalse(result.contains("mjma"));
}
@Test
public void testGetClassNamesOfCurrentProject()
{
System.out.println("GetClassNamesOfCurrentProject");
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetClassNamesOfCurrentProject();
assertEquals(1, result.size());
assertTrue(result.contains("pacls"));
}
@Test
public void testGetVariablesOfCurrentMethod()
{
System.out.println("GetVariablesOfCurrentMethod");
List<MethodLine> methodlines = _CurrentMethodLines;
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetVariablesOfCurrentMethod(methodlines);
assertEquals(1, result.size());
assertTrue(result.contains("index"));
}
@Test
public void testGetFieldNamesOfCurrentCls()
{
System.out.println("GetFieldNamesOfCurrentCls");
List<Field> fields = _CurrentFields;
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetFieldNamesOfCurrentCls(fields);
assertEquals(1, result.size());
assertTrue(result.contains("pafa"));
}
@Test
public void testGetHint()
{
System.out.println("GetHint");
String input = "";
List<MethodLine> methodLines = _CurrentMethodLines;
ACClass currentCls = _CurrentCLS;
HintGenerator instance = _HintGenerator;
List<String> result = instance.GetHint(input, methodLines, currentCls);
GetArrayList<String> getter = new GetArrayList<>();
List<String> list = getter.Get("void","mjcls", "mjcls.mjfbs", "mjma", "index", "pama", "pafa", "pacls.pafbs", "pacls", "new", "this");
assertEquals(list.size(), result.size());
assertTrue(result.containsAll(list));
input = "p";
list = getter.Get("pama", "pafa", "pacls.pafbs", "pacls");
result = instance.GetHint(input, methodLines, currentCls);
assertEquals(list.size(), result.size());
assertTrue(result.containsAll(list));
input = "mjfbs";
list = getter.Get("mjcls.mjfbs");
result = instance.GetHint(input, methodLines, currentCls);
assertEquals(list.size(), result.size());
assertTrue(result.containsAll(list));
input = "abc.";
list = getter.Get("mjcls", "mjcls.mjfbs", "mjma", "index", "pama", "pafa", "pacls.pafbs", "pacls", "new", "this", "void");
result = instance.GetHint(input, methodLines, currentCls);
assertEquals(list.size(), result.size());
assertTrue(result.containsAll(list));
}
@Test
public void testIsReset()
{
String input = "";
boolean result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = "in";
result = _HintGenerator.IsReset(input);
assertEquals(false, result);
input = "int ";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = "int in";
result = _HintGenerator.IsReset(input);
assertEquals(false, result);
input = "int index";
result = _HintGenerator.IsReset(input);
assertEquals(false, result);
input = "int index ";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = "index =";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = " = 1";
result = _HintGenerator.IsReset(input);
assertEquals(false, result);
input = "ModelFactory.";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = "IsReset(";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
input = "List<";
result = _HintGenerator.IsReset(input);
assertEquals(true, result);
}
}
| 41.720472 | 204 | 0.662074 |
36e13e99463dc2ef3ff2afc98c02a7235970d57b | 1,308 | package org.firstinspires.ftc.robotcontroller.external.samples;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.Range;
/**
* Created by Tejas Mehta on 11/21/16.
*/
@TeleOp(name="TankDrive", group="A-Team")
public class TankDrive extends OpMode {
HardwarePushbot robot = new HardwarePushbot();
public void init() {
robot.init(hardwareMap);
}
public void loop() {
float leftY = gamepad1.left_stick_y;
float rightY = gamepad1.right_stick_y;
float cannon = -gamepad2.right_trigger;
float spinnerR = gamepad2.left_trigger;
robot.leftMotor.setPower(leftY);
robot.rightMotor.setPower(rightY);
robot.spinner.setPower(spinnerR);
if (cannon < 0) {
robot.cannon.setPower(0.5);
} else {
robot.cannon.setPower(0);
}
// hello world! i may or may not be a comment
// plz dont kill meh
// plzplzplzplzplzplzplzplzplzplz
// i didnt do anything wrong D:D:D:D:D:D:D:D:D:D:D:D:D:D:
}
}
| 22.947368 | 65 | 0.659786 |
ab1e7cf29fa27b9e8d9eca10eb5a31ceef52f7f9 | 435 | package at.medunigraz.imi.bst.n2c2.model.metrics;
import at.medunigraz.imi.bst.n2c2.model.Criterion;
import java.util.List;
import java.util.Map;
public interface Metrics {
double getOfficialRankingMeasure();
double getOfficialRankingMeasureByCriterion(Criterion c);
void add(Metrics addend);
void divideBy(double divisor);
List<String> getMetricNames();
Map<String, Double> getMetrics(Criterion c);
}
| 19.772727 | 61 | 0.751724 |
f3be05e6515a52ee3fbda45450c7f657fa7dcd87 | 7,340 | package co.com.codesoftware.beans.contabilidad;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import co.com.codesoftware.beans.ProvedorBean;
import co.com.codesoftware.beans.admin.ClienteBean;
import co.com.codesoftware.logica.admin.ContabilidadLogic;
import co.com.codesoftware.servicio.contabilidad.MoviContableEntity;
import co.com.codesoftware.servicio.usuario.UsuarioEntity;
import co.com.codesoftware.utilities.ErrorEnum;
import co.com.codesoftware.utilities.GeneralBean;
@ManagedBean
@ViewScoped
/*
* MO-001 Consulta movimientos contables terceros: se modifica la consulta para
* que reciba el id del tercero y el tipo jmorenor1986 07/11/2016
* ----------------
* --------------------------------------------------------------
* -------------------------
*/
public class ConsCuentaContBean implements GeneralBean {
private UsuarioEntity objetoSesion;
private Date fechaInicial;
private Date fechaFinal;
private String cuenta;
private String tipoTercero;
private List<MoviContableEntity> listaMovimientos;
private List<MoviContableEntity> obtenerAsiento;
private ArrayList<String> cuentasCons;
private BigDecimal total;
private BigDecimal debito;
private BigDecimal credito;
// Objetos inyectados
@ManagedProperty(value = "#{clienteBean}")
private ClienteBean clienteBean;
@ManagedProperty(value = "#{provedorBean}")
private ProvedorBean provedorBean;
public UsuarioEntity getObjetoSesion() {
return objetoSesion;
}
public void setObjetoSesion(UsuarioEntity objetoSesion) {
this.objetoSesion = objetoSesion;
}
@PostConstruct
public void init() {
try {
this.objetoSesion = (UsuarioEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dataSession");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion con la cual genero la consulta
*/
public void generarConsulta() {
try {
ContabilidadLogic objLogic = new ContabilidadLogic();
this.cuentasCons = null;
// MO-001
this.listaMovimientos = objLogic.obtenerMoviContXCuenta(fechaInicial, fechaFinal, cuenta,this.tipoTercero,verificaTercero());
// MO-001
if (this.listaMovimientos == null || this.listaMovimientos.size() == 0) {
this.messageBean("La consulta no arrojo ningun resultado", ErrorEnum.ERROR);
} else {
this.cuentasCons = null;
this.total = new BigDecimal(0);
this.debito = new BigDecimal(0);
this.credito = new BigDecimal(0);
if (this.listaMovimientos != null) {
for (MoviContableEntity item : this.listaMovimientos) {
this.armoListaCuenta(item.getSubcuenta().getCodigo());
if ("DEBITO".equalsIgnoreCase(item.getNaturaleza())) {
debito = debito.add(item.getValor());
} else {
credito = credito.add(item.getValor());
}
}
total = debito.subtract(credito);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion con la cual creo una lista para realizar visualizar las cuentas
* implicadas
*
* @param cuenta
*/
public void armoListaCuenta(String cuenta) {
boolean valida = true;
try {
if (this.cuentasCons == null) {
this.cuentasCons = new ArrayList<>();
}
for (String item : this.cuentasCons) {
if (cuenta.equalsIgnoreCase(item)) {
valida = false;
break;
}
}
if (valida) {
this.cuentasCons.add(cuenta);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion que totaliza
*
* @return
*/
public String getTotal() {
this.total = new BigDecimal(0);
this.debito = new BigDecimal(0);
this.credito = new BigDecimal(0);
if (this.listaMovimientos != null) {
for (MoviContableEntity item : this.listaMovimientos) {
this.armoListaCuenta(item.getSubcuenta().getCodigo());
if ("DEBITO".equalsIgnoreCase(item.getNaturaleza())) {
debito = debito.add(item.getValor());
} else {
credito = credito.add(item.getValor());
}
}
total = debito.subtract(credito);
}
// return new DecimalFormat("###,###.##").format(total);
return new DecimalFormat("###,###.##").format(total);
}
/**
* Funcion que totaliza los creditos
*
* @return
*/
public String getCreditos() {
this.total = new BigDecimal(0);
this.debito = new BigDecimal(0);
this.credito = new BigDecimal(0);
if (this.listaMovimientos != null) {
for (MoviContableEntity item : this.listaMovimientos) {
this.armoListaCuenta(item.getSubcuenta().getCodigo());
if ("DEBITO".equalsIgnoreCase(item.getNaturaleza())) {
debito = debito.add(item.getValor());
} else {
credito = credito.add(item.getValor());
}
}
}
return new DecimalFormat("###,###.##").format(this.credito);
}
/**
* Funcion que totaliza los debitos
*
* @return
*/
public String getDebitos() {
this.total = new BigDecimal(0);
this.debito = new BigDecimal(0);
this.credito = new BigDecimal(0);
if (this.listaMovimientos != null) {
for (MoviContableEntity item : this.listaMovimientos) {
this.armoListaCuenta(item.getSubcuenta().getCodigo());
if ("DEBITO".equalsIgnoreCase(item.getNaturaleza())) {
debito = debito.add(item.getValor());
} else {
credito = credito.add(item.getValor());
}
}
}
return new DecimalFormat("###,###.##").format(this.debito);
}
/**
* metodo que verifica el tercero mediante el tipo
* 1 = Cliente
* 2 = Proveedor
* MO-001
* @return
*/
public Integer verificaTercero() {
try {
switch (this.tipoTercero) {
case "1":
return this.clienteBean.getCliente().getId();
case "2":
return this.provedorBean.getProveedor().getId();
default:
return -1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public Date getFechaInicial() {
return fechaInicial;
}
public void setFechaInicial(Date fechaInicial) {
this.fechaInicial = fechaInicial;
}
public Date getFechaFinal() {
return fechaFinal;
}
public void setFechaFinal(Date fechaFinal) {
this.fechaFinal = fechaFinal;
}
public String getCuenta() {
return cuenta;
}
public void setCuenta(String cuenta) {
this.cuenta = cuenta;
}
public List<MoviContableEntity> getListaMovimientos() {
return listaMovimientos;
}
public void setListaMovimientos(List<MoviContableEntity> listaMovimientos) {
this.listaMovimientos = listaMovimientos;
}
public List<MoviContableEntity> getObtenerAsiento() {
return obtenerAsiento;
}
public void setObtenerAsiento(List<MoviContableEntity> obtenerAsiento) {
this.obtenerAsiento = obtenerAsiento;
}
public ArrayList<String> getCuentasCons() {
return cuentasCons;
}
public void setCuentasCons(ArrayList<String> cuentasCons) {
this.cuentasCons = cuentasCons;
}
public String getTipoTercero() {
return tipoTercero;
}
public void setTipoTercero(String tipoTercero) {
this.tipoTercero = tipoTercero;
}
public void setClienteBean(ClienteBean clienteBean) {
this.clienteBean = clienteBean;
}
public void setProvedorBean(ProvedorBean provedorBean) {
this.provedorBean = provedorBean;
}
}
| 24.965986 | 129 | 0.692234 |
81af67b76a13f10d41a412ce255bfbe3a05f1388 | 2,368 | package com.newxton.nxtframework.controller.api.admin;
import com.google.gson.Gson;
import com.newxton.nxtframework.entity.NxtProduct;
import com.newxton.nxtframework.service.NxtProductService;
import com.newxton.nxtframework.struct.NxtStructApiResult;
import com.newxton.nxtframework.struct.admin.NxtStructAdminProductSetTrashPost;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* @author soyojo.earth@gmail.com
* @address Shenzhen, China
* @copyright NxtFramework
*/
@RestController
public class NxtApiAdminProductSetTrashController {
@Resource
private NxtProductService nxtProductService;
@RequestMapping(value = "/api/admin/product/set_trash", method = RequestMethod.POST)
public Map<String, Object> index(@RequestBody String json) {
Gson gson = new Gson();
NxtStructAdminProductSetTrashPost postData;
try {
postData = gson.fromJson(json, NxtStructAdminProductSetTrashPost.class);
}
catch (Exception e){
return new NxtStructApiResult(54,"json数据不对").toMap();
}
Map<String, Object> result = new HashMap<>();
result.put("status", 0);
result.put("message", "");
if (postData.getId() != null) {
/*先查询*/
NxtProduct nxtProduct = nxtProductService.queryById(postData.getId());
if (nxtProduct == null) {
return new NxtStructApiResult(49, "对应的产品不存在").toMap();
}
nxtProduct.setIsTrash(postData.getTrash() ? 1 : 0);//1放入回收站 0恢复
nxtProductService.update(nxtProduct);
}
if (postData.getIdList() != null){
for (Long productId : postData.getIdList()) {
/*先查询*/
NxtProduct nxtProduct = nxtProductService.queryById(productId);
if (nxtProduct != null) {
nxtProduct.setIsTrash(postData.getTrash() ? 1 : 0);//1放入回收站 0恢复
nxtProductService.update(nxtProduct);
}
}
}
return new NxtStructApiResult().toMap();
}
}
| 33.352113 | 88 | 0.660473 |
1a438c54a0e472193a1416295f450ef89643e156 | 8,865 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.eventgrid.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.eventgrid.models.EventTypeInfo;
import com.azure.resourcemanager.eventgrid.models.PartnerTopicActivationState;
import com.azure.resourcemanager.eventgrid.models.PartnerTopicProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.UUID;
/** Properties of the Partner Topic. */
@Fluent
public final class PartnerTopicProperties {
/*
* The immutableId of the corresponding partner registration.
*/
@JsonProperty(value = "partnerRegistrationImmutableId")
private UUID partnerRegistrationImmutableId;
/*
* Source associated with this partner topic. This represents a unique
* partner resource.
*/
@JsonProperty(value = "source")
private String source;
/*
* Event Type information from the corresponding event channel.
*/
@JsonProperty(value = "eventTypeInfo")
private EventTypeInfo eventTypeInfo;
/*
* Expiration time of the partner topic. If this timer expires while the
* partner topic is still never activated,
* the partner topic and corresponding event channel are deleted.
*/
@JsonProperty(value = "expirationTimeIfNotActivatedUtc")
private OffsetDateTime expirationTimeIfNotActivatedUtc;
/*
* Provisioning state of the partner topic.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private PartnerTopicProvisioningState provisioningState;
/*
* Activation state of the partner topic.
*/
@JsonProperty(value = "activationState")
private PartnerTopicActivationState activationState;
/*
* Friendly description about the topic. This can be set by the
* publisher/partner to show custom description for the customer partner
* topic.
* This will be helpful to remove any ambiguity of the origin of creation
* of the partner topic for the customer.
*/
@JsonProperty(value = "partnerTopicFriendlyDescription")
private String partnerTopicFriendlyDescription;
/*
* Context or helpful message that can be used during the approval process
* by the subscriber.
*/
@JsonProperty(value = "messageForActivation")
private String messageForActivation;
/**
* Get the partnerRegistrationImmutableId property: The immutableId of the corresponding partner registration.
*
* @return the partnerRegistrationImmutableId value.
*/
public UUID partnerRegistrationImmutableId() {
return this.partnerRegistrationImmutableId;
}
/**
* Set the partnerRegistrationImmutableId property: The immutableId of the corresponding partner registration.
*
* @param partnerRegistrationImmutableId the partnerRegistrationImmutableId value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withPartnerRegistrationImmutableId(UUID partnerRegistrationImmutableId) {
this.partnerRegistrationImmutableId = partnerRegistrationImmutableId;
return this;
}
/**
* Get the source property: Source associated with this partner topic. This represents a unique partner resource.
*
* @return the source value.
*/
public String source() {
return this.source;
}
/**
* Set the source property: Source associated with this partner topic. This represents a unique partner resource.
*
* @param source the source value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withSource(String source) {
this.source = source;
return this;
}
/**
* Get the eventTypeInfo property: Event Type information from the corresponding event channel.
*
* @return the eventTypeInfo value.
*/
public EventTypeInfo eventTypeInfo() {
return this.eventTypeInfo;
}
/**
* Set the eventTypeInfo property: Event Type information from the corresponding event channel.
*
* @param eventTypeInfo the eventTypeInfo value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withEventTypeInfo(EventTypeInfo eventTypeInfo) {
this.eventTypeInfo = eventTypeInfo;
return this;
}
/**
* Get the expirationTimeIfNotActivatedUtc property: Expiration time of the partner topic. If this timer expires
* while the partner topic is still never activated, the partner topic and corresponding event channel are deleted.
*
* @return the expirationTimeIfNotActivatedUtc value.
*/
public OffsetDateTime expirationTimeIfNotActivatedUtc() {
return this.expirationTimeIfNotActivatedUtc;
}
/**
* Set the expirationTimeIfNotActivatedUtc property: Expiration time of the partner topic. If this timer expires
* while the partner topic is still never activated, the partner topic and corresponding event channel are deleted.
*
* @param expirationTimeIfNotActivatedUtc the expirationTimeIfNotActivatedUtc value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withExpirationTimeIfNotActivatedUtc(OffsetDateTime expirationTimeIfNotActivatedUtc) {
this.expirationTimeIfNotActivatedUtc = expirationTimeIfNotActivatedUtc;
return this;
}
/**
* Get the provisioningState property: Provisioning state of the partner topic.
*
* @return the provisioningState value.
*/
public PartnerTopicProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the activationState property: Activation state of the partner topic.
*
* @return the activationState value.
*/
public PartnerTopicActivationState activationState() {
return this.activationState;
}
/**
* Set the activationState property: Activation state of the partner topic.
*
* @param activationState the activationState value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withActivationState(PartnerTopicActivationState activationState) {
this.activationState = activationState;
return this;
}
/**
* Get the partnerTopicFriendlyDescription property: Friendly description about the topic. This can be set by the
* publisher/partner to show custom description for the customer partner topic. This will be helpful to remove any
* ambiguity of the origin of creation of the partner topic for the customer.
*
* @return the partnerTopicFriendlyDescription value.
*/
public String partnerTopicFriendlyDescription() {
return this.partnerTopicFriendlyDescription;
}
/**
* Set the partnerTopicFriendlyDescription property: Friendly description about the topic. This can be set by the
* publisher/partner to show custom description for the customer partner topic. This will be helpful to remove any
* ambiguity of the origin of creation of the partner topic for the customer.
*
* @param partnerTopicFriendlyDescription the partnerTopicFriendlyDescription value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withPartnerTopicFriendlyDescription(String partnerTopicFriendlyDescription) {
this.partnerTopicFriendlyDescription = partnerTopicFriendlyDescription;
return this;
}
/**
* Get the messageForActivation property: Context or helpful message that can be used during the approval process by
* the subscriber.
*
* @return the messageForActivation value.
*/
public String messageForActivation() {
return this.messageForActivation;
}
/**
* Set the messageForActivation property: Context or helpful message that can be used during the approval process by
* the subscriber.
*
* @param messageForActivation the messageForActivation value to set.
* @return the PartnerTopicProperties object itself.
*/
public PartnerTopicProperties withMessageForActivation(String messageForActivation) {
this.messageForActivation = messageForActivation;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (eventTypeInfo() != null) {
eventTypeInfo().validate();
}
}
}
| 36.632231 | 120 | 0.718443 |
e4ce7ca8e17acbc606bf7876c8aef67191c84a3f | 3,228 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import java.io.NotSerializableException;
import java.io.Serializable;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import static org.apache.camel.util.ObjectHelper.equal;
public class DataFormatTest extends ContextTestSupport {
@Test
public void testMarshalThenUnmarshalBean() throws Exception {
MyBean bean = new MyBean();
bean.name = "James";
bean.counter = 5;
MockEndpoint resultEndpoint = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
resultEndpoint.expectedBodiesReceived(bean);
template.sendBody("direct:start", bean);
resultEndpoint.assertIsSatisfied();
}
@Test
public void testMarshalNonSerializableBean() throws Exception {
MyNonSerializableBean bean = new MyNonSerializableBean("James");
try {
template.sendBody("direct:start", bean);
fail("Should throw exception");
} catch (CamelExecutionException e) {
assertIsInstanceOf(NotSerializableException.class, e.getCause());
}
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").marshal().serialization().to("direct:marshalled");
from("direct:marshalled").unmarshal().serialization().to("mock:result");
}
};
}
protected static class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public int counter;
@Override
public boolean equals(Object o) {
if (o instanceof MyBean) {
MyBean that = (MyBean) o;
return equal(this.name, that.name) && equal(this.counter, that.counter);
}
return false;
}
@Override
public int hashCode() {
return name.hashCode() + counter;
}
}
protected static class MyNonSerializableBean {
private String name;
public MyNonSerializableBean(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
} | 32.938776 | 98 | 0.662949 |
1c6d711f59ca718408feabca54903939db91ae65 | 1,155 | package com.logscape.disco.grokit;
import com.liquidlabs.common.Pool;
import java.lang.management.ManagementFactory;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: neil
* Date: 23/06/2014
* Time: 13:04
* To change this template use File | Settings | File Templates.
*/
public class GrokItPool implements Pool.Factory {
private Pool pool;
@Override
public Object newInstance() {
return new GrokIt();
}
public void process(String line) {
}
public GrokItPool() {
}
private Pool getPool(int cores) {
return new Pool(cores, cores, this);
}
public Map<String, String> processLine(String filename, String data) {
if (this.pool == null) {
int cores = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
this.pool = getPool(cores);
}
GrokIt grokIt = (GrokIt) this.pool.fetchFromPool();
Map<String, String> results = null;
try {
results = grokIt.processLine(filename, data);
} finally {
this.pool.putInPool(grokIt);
}
return results;
}
}
| 23.571429 | 94 | 0.625108 |
355dc81ce3cf3a0ef5bc54adac3876b6f49aece7 | 717 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 商品标签返回结果集
*
* @author auto create
* @since 1.0, 2021-12-31 09:40:21
*/
public class GoodsTagResult extends AlipayObject {
private static final long serialVersionUID = 3849141367645341515L;
/**
* 标签code
*/
@ApiField("tag_code")
private String tagCode;
/**
* 标签名称
*/
@ApiField("tag_name")
private String tagName;
public String getTagCode() {
return this.tagCode;
}
public void setTagCode(String tagCode) {
this.tagCode = tagCode;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
}
| 16.674419 | 67 | 0.705718 |
bd598bf011caa560c0d15497ceb1d07f03bf6128 | 1,257 | /*
* @lc app=leetcode.cn id=154 lang=java
*
* [154] Find Minimum in Rotated Sorted Array II
*/
// Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
// (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
// Find the minimum element.
// The array may contain duplicates.
// Example 1:
// Input: [1,3,5]
// Output: 1
// Example 2:
// Input: [2,2,2,0,1]
// Output: 0
// Note:
// This is a follow up problem to Find Minimum in Rotated Sorted Array.
// Would allow duplicates affect the run-time complexity? How and why?
// @lc code=start
class Solution {
public int findMin(int[] nums) {
// Accepted
// 192/192 cases passed (0 ms)
// Your runtime beats 100 % of java submissions
// Your memory usage beats 60 % of java submissions (39.5 MB)
int l = nums.length;
if (l < 2) {
return nums[0];
}
int last = l - 1, i = l - 2;
while (i > -1 && nums[i] <= nums[last]) {
if (nums[i >> 1] < nums[last]) {
last = i >> 1;
i = last - 1;
} else {
last = i;
i--;
}
}
return nums[last];
}
}
// @lc code=end
| 24.647059 | 98 | 0.522673 |
fd4cf6a9f81cfd5853d8ff4cab0e4fae7b210fcd | 1,684 | package UltimaAula;
import java.util.Scanner;
public class Pagar {
static final int n = 3;
public double valor[] = new double [ n ];
public double vlpagar[] = new double [ n ];
public double multa, juros;
public final double taxamulta = 0.02, taxajuros = 0.00033;
public int dias[] = new int [ n ];
public void Ler(Scanner leitor){
for (int i = 0; i < n ; i ++){
System.out.println("\nLer Valor:");
valor[i] = leitor.nextDouble();
System.out.println("\nLer Dias:");
dias[i] = leitor.nextInt();
}
}
public void Calcular(){
for (int i = 0; i < n ; i ++){
multa = valor[i] * taxamulta;
juros = (dias[i] / 30) * 0.01;
vlpagar[i] = valor[i] + multa + juros;
}
}
public void exibir() {
for (int i = 0; i < n ; i ++){
System.out.println("\nMulta..:" + multa);
System.out.println("\nJuros..:" + juros);
System.out.println("\nValor a Pagar:" + vlpagar[i]);
}
}
public static void main(String[] args) {
Scanner leitor = new Scanner(System.in);
Pagar p = new Pagar();
int tecla = 0;
while (tecla != 4) {
System.out.println("\nmenu\n1 Ler\n2 Calcular\n3 Exibir\n4 Sair\nItem:");
tecla = leitor.nextInt();
if (tecla == 1 ) {
p.Ler(leitor);
}
else if (tecla ==2 ){
p.Calcular( );
}
else if (tecla ==3 ){
p.exibir();
}
}
}
} | 26.3125 | 85 | 0.456651 |
a82f48d1a3804b4d51a3df886dda6f9df9d5815d | 368 | package com.ppfuns.report.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ppfuns.report.entity.NoappAlbumUserCountRankWeek;
/**
* 所有专区专辑播放用户数周排行榜(NoappAlbumUserCountRankWeek)表数据库访问层
*
* @author jdq
* @since 2021-07-08 11:39:40
*/
public interface NoappAlbumUserCountRankWeekMapper extends BaseMapper<NoappAlbumUserCountRankWeek> {
}
| 24.533333 | 100 | 0.8125 |
360b9ace35ba717419b97c42c444bb03fa92c303 | 250 | package org.acme.metric;
import io.micrometer.core.instrument.MeterRegistry;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public abstract class CommonMetricDetails {
protected String identifier;
protected MeterRegistry registry;
}
| 22.727273 | 51 | 0.824 |
6140760cf02092ed161a2b741d826d9ce8978cc5 | 46,119 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/iot/v1/resources.proto
package com.google.cloud.iot.v1;
/**
*
*
* <pre>
* Details of an X.509 certificate. For informational purposes only.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.X509CertificateDetails}
*/
public final class X509CertificateDetails extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iot.v1.X509CertificateDetails)
X509CertificateDetailsOrBuilder {
private static final long serialVersionUID = 0L;
// Use X509CertificateDetails.newBuilder() to construct.
private X509CertificateDetails(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private X509CertificateDetails() {
issuer_ = "";
subject_ = "";
signatureAlgorithm_ = "";
publicKeyType_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private X509CertificateDetails(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
issuer_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
subject_ = s;
break;
}
case 26:
{
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (startTime_ != null) {
subBuilder = startTime_.toBuilder();
}
startTime_ =
input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(startTime_);
startTime_ = subBuilder.buildPartial();
}
break;
}
case 34:
{
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (expiryTime_ != null) {
subBuilder = expiryTime_.toBuilder();
}
expiryTime_ =
input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(expiryTime_);
expiryTime_ = subBuilder.buildPartial();
}
break;
}
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
signatureAlgorithm_ = s;
break;
}
case 50:
{
java.lang.String s = input.readStringRequireUtf8();
publicKeyType_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_X509CertificateDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_X509CertificateDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.X509CertificateDetails.class,
com.google.cloud.iot.v1.X509CertificateDetails.Builder.class);
}
public static final int ISSUER_FIELD_NUMBER = 1;
private volatile java.lang.Object issuer_;
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public java.lang.String getIssuer() {
java.lang.Object ref = issuer_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
issuer_ = s;
return s;
}
}
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public com.google.protobuf.ByteString getIssuerBytes() {
java.lang.Object ref = issuer_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
issuer_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SUBJECT_FIELD_NUMBER = 2;
private volatile java.lang.Object subject_;
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public java.lang.String getSubject() {
java.lang.Object ref = subject_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subject_ = s;
return s;
}
}
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public com.google.protobuf.ByteString getSubjectBytes() {
java.lang.Object ref = subject_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
subject_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int START_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp startTime_;
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public boolean hasStartTime() {
return startTime_ != null;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public com.google.protobuf.Timestamp getStartTime() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
return getStartTime();
}
public static final int EXPIRY_TIME_FIELD_NUMBER = 4;
private com.google.protobuf.Timestamp expiryTime_;
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public boolean hasExpiryTime() {
return expiryTime_ != null;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public com.google.protobuf.Timestamp getExpiryTime() {
return expiryTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : expiryTime_;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public com.google.protobuf.TimestampOrBuilder getExpiryTimeOrBuilder() {
return getExpiryTime();
}
public static final int SIGNATURE_ALGORITHM_FIELD_NUMBER = 5;
private volatile java.lang.Object signatureAlgorithm_;
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public java.lang.String getSignatureAlgorithm() {
java.lang.Object ref = signatureAlgorithm_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
signatureAlgorithm_ = s;
return s;
}
}
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public com.google.protobuf.ByteString getSignatureAlgorithmBytes() {
java.lang.Object ref = signatureAlgorithm_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
signatureAlgorithm_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PUBLIC_KEY_TYPE_FIELD_NUMBER = 6;
private volatile java.lang.Object publicKeyType_;
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public java.lang.String getPublicKeyType() {
java.lang.Object ref = publicKeyType_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
publicKeyType_ = s;
return s;
}
}
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public com.google.protobuf.ByteString getPublicKeyTypeBytes() {
java.lang.Object ref = publicKeyType_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
publicKeyType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!getIssuerBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, issuer_);
}
if (!getSubjectBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, subject_);
}
if (startTime_ != null) {
output.writeMessage(3, getStartTime());
}
if (expiryTime_ != null) {
output.writeMessage(4, getExpiryTime());
}
if (!getSignatureAlgorithmBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, signatureAlgorithm_);
}
if (!getPublicKeyTypeBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, publicKeyType_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getIssuerBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, issuer_);
}
if (!getSubjectBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, subject_);
}
if (startTime_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getStartTime());
}
if (expiryTime_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getExpiryTime());
}
if (!getSignatureAlgorithmBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, signatureAlgorithm_);
}
if (!getPublicKeyTypeBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, publicKeyType_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.iot.v1.X509CertificateDetails)) {
return super.equals(obj);
}
com.google.cloud.iot.v1.X509CertificateDetails other =
(com.google.cloud.iot.v1.X509CertificateDetails) obj;
if (!getIssuer().equals(other.getIssuer())) return false;
if (!getSubject().equals(other.getSubject())) return false;
if (hasStartTime() != other.hasStartTime()) return false;
if (hasStartTime()) {
if (!getStartTime().equals(other.getStartTime())) return false;
}
if (hasExpiryTime() != other.hasExpiryTime()) return false;
if (hasExpiryTime()) {
if (!getExpiryTime().equals(other.getExpiryTime())) return false;
}
if (!getSignatureAlgorithm().equals(other.getSignatureAlgorithm())) return false;
if (!getPublicKeyType().equals(other.getPublicKeyType())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ISSUER_FIELD_NUMBER;
hash = (53 * hash) + getIssuer().hashCode();
hash = (37 * hash) + SUBJECT_FIELD_NUMBER;
hash = (53 * hash) + getSubject().hashCode();
if (hasStartTime()) {
hash = (37 * hash) + START_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStartTime().hashCode();
}
if (hasExpiryTime()) {
hash = (37 * hash) + EXPIRY_TIME_FIELD_NUMBER;
hash = (53 * hash) + getExpiryTime().hashCode();
}
hash = (37 * hash) + SIGNATURE_ALGORITHM_FIELD_NUMBER;
hash = (53 * hash) + getSignatureAlgorithm().hashCode();
hash = (37 * hash) + PUBLIC_KEY_TYPE_FIELD_NUMBER;
hash = (53 * hash) + getPublicKeyType().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.X509CertificateDetails parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.iot.v1.X509CertificateDetails prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Details of an X.509 certificate. For informational purposes only.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.X509CertificateDetails}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iot.v1.X509CertificateDetails)
com.google.cloud.iot.v1.X509CertificateDetailsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_X509CertificateDetails_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_X509CertificateDetails_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.X509CertificateDetails.class,
com.google.cloud.iot.v1.X509CertificateDetails.Builder.class);
}
// Construct using com.google.cloud.iot.v1.X509CertificateDetails.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
issuer_ = "";
subject_ = "";
if (startTimeBuilder_ == null) {
startTime_ = null;
} else {
startTime_ = null;
startTimeBuilder_ = null;
}
if (expiryTimeBuilder_ == null) {
expiryTime_ = null;
} else {
expiryTime_ = null;
expiryTimeBuilder_ = null;
}
signatureAlgorithm_ = "";
publicKeyType_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iot.v1.ResourcesProto
.internal_static_google_cloud_iot_v1_X509CertificateDetails_descriptor;
}
@java.lang.Override
public com.google.cloud.iot.v1.X509CertificateDetails getDefaultInstanceForType() {
return com.google.cloud.iot.v1.X509CertificateDetails.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iot.v1.X509CertificateDetails build() {
com.google.cloud.iot.v1.X509CertificateDetails result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iot.v1.X509CertificateDetails buildPartial() {
com.google.cloud.iot.v1.X509CertificateDetails result =
new com.google.cloud.iot.v1.X509CertificateDetails(this);
result.issuer_ = issuer_;
result.subject_ = subject_;
if (startTimeBuilder_ == null) {
result.startTime_ = startTime_;
} else {
result.startTime_ = startTimeBuilder_.build();
}
if (expiryTimeBuilder_ == null) {
result.expiryTime_ = expiryTime_;
} else {
result.expiryTime_ = expiryTimeBuilder_.build();
}
result.signatureAlgorithm_ = signatureAlgorithm_;
result.publicKeyType_ = publicKeyType_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.iot.v1.X509CertificateDetails) {
return mergeFrom((com.google.cloud.iot.v1.X509CertificateDetails) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iot.v1.X509CertificateDetails other) {
if (other == com.google.cloud.iot.v1.X509CertificateDetails.getDefaultInstance()) return this;
if (!other.getIssuer().isEmpty()) {
issuer_ = other.issuer_;
onChanged();
}
if (!other.getSubject().isEmpty()) {
subject_ = other.subject_;
onChanged();
}
if (other.hasStartTime()) {
mergeStartTime(other.getStartTime());
}
if (other.hasExpiryTime()) {
mergeExpiryTime(other.getExpiryTime());
}
if (!other.getSignatureAlgorithm().isEmpty()) {
signatureAlgorithm_ = other.signatureAlgorithm_;
onChanged();
}
if (!other.getPublicKeyType().isEmpty()) {
publicKeyType_ = other.publicKeyType_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.iot.v1.X509CertificateDetails parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.iot.v1.X509CertificateDetails) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object issuer_ = "";
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public java.lang.String getIssuer() {
java.lang.Object ref = issuer_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
issuer_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public com.google.protobuf.ByteString getIssuerBytes() {
java.lang.Object ref = issuer_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
issuer_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public Builder setIssuer(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
issuer_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public Builder clearIssuer() {
issuer_ = getDefaultInstance().getIssuer();
onChanged();
return this;
}
/**
*
*
* <pre>
* The entity that signed the certificate.
* </pre>
*
* <code>string issuer = 1;</code>
*/
public Builder setIssuerBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
issuer_ = value;
onChanged();
return this;
}
private java.lang.Object subject_ = "";
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public java.lang.String getSubject() {
java.lang.Object ref = subject_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subject_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public com.google.protobuf.ByteString getSubjectBytes() {
java.lang.Object ref = subject_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
subject_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public Builder setSubject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
subject_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public Builder clearSubject() {
subject_ = getDefaultInstance().getSubject();
onChanged();
return this;
}
/**
*
*
* <pre>
* The entity the certificate and public key belong to.
* </pre>
*
* <code>string subject = 2;</code>
*/
public Builder setSubjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
subject_ = value;
onChanged();
return this;
}
private com.google.protobuf.Timestamp startTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
startTimeBuilder_;
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public boolean hasStartTime() {
return startTimeBuilder_ != null || startTime_ != null;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public com.google.protobuf.Timestamp getStartTime() {
if (startTimeBuilder_ == null) {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
} else {
return startTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
startTime_ = value;
onChanged();
} else {
startTimeBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (startTimeBuilder_ == null) {
startTime_ = builderForValue.build();
onChanged();
} else {
startTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public Builder mergeStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (startTime_ != null) {
startTime_ =
com.google.protobuf.Timestamp.newBuilder(startTime_).mergeFrom(value).buildPartial();
} else {
startTime_ = value;
}
onChanged();
} else {
startTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public Builder clearStartTime() {
if (startTimeBuilder_ == null) {
startTime_ = null;
onChanged();
} else {
startTime_ = null;
startTimeBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() {
onChanged();
return getStartTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
if (startTimeBuilder_ != null) {
return startTimeBuilder_.getMessageOrBuilder();
} else {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
}
/**
*
*
* <pre>
* The time the certificate becomes valid.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getStartTimeFieldBuilder() {
if (startTimeBuilder_ == null) {
startTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getStartTime(), getParentForChildren(), isClean());
startTime_ = null;
}
return startTimeBuilder_;
}
private com.google.protobuf.Timestamp expiryTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
expiryTimeBuilder_;
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public boolean hasExpiryTime() {
return expiryTimeBuilder_ != null || expiryTime_ != null;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public com.google.protobuf.Timestamp getExpiryTime() {
if (expiryTimeBuilder_ == null) {
return expiryTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: expiryTime_;
} else {
return expiryTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public Builder setExpiryTime(com.google.protobuf.Timestamp value) {
if (expiryTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
expiryTime_ = value;
onChanged();
} else {
expiryTimeBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public Builder setExpiryTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (expiryTimeBuilder_ == null) {
expiryTime_ = builderForValue.build();
onChanged();
} else {
expiryTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public Builder mergeExpiryTime(com.google.protobuf.Timestamp value) {
if (expiryTimeBuilder_ == null) {
if (expiryTime_ != null) {
expiryTime_ =
com.google.protobuf.Timestamp.newBuilder(expiryTime_).mergeFrom(value).buildPartial();
} else {
expiryTime_ = value;
}
onChanged();
} else {
expiryTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public Builder clearExpiryTime() {
if (expiryTimeBuilder_ == null) {
expiryTime_ = null;
onChanged();
} else {
expiryTime_ = null;
expiryTimeBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public com.google.protobuf.Timestamp.Builder getExpiryTimeBuilder() {
onChanged();
return getExpiryTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
public com.google.protobuf.TimestampOrBuilder getExpiryTimeOrBuilder() {
if (expiryTimeBuilder_ != null) {
return expiryTimeBuilder_.getMessageOrBuilder();
} else {
return expiryTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: expiryTime_;
}
}
/**
*
*
* <pre>
* The time the certificate becomes invalid.
* </pre>
*
* <code>.google.protobuf.Timestamp expiry_time = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getExpiryTimeFieldBuilder() {
if (expiryTimeBuilder_ == null) {
expiryTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getExpiryTime(), getParentForChildren(), isClean());
expiryTime_ = null;
}
return expiryTimeBuilder_;
}
private java.lang.Object signatureAlgorithm_ = "";
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public java.lang.String getSignatureAlgorithm() {
java.lang.Object ref = signatureAlgorithm_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
signatureAlgorithm_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public com.google.protobuf.ByteString getSignatureAlgorithmBytes() {
java.lang.Object ref = signatureAlgorithm_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
signatureAlgorithm_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public Builder setSignatureAlgorithm(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
signatureAlgorithm_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public Builder clearSignatureAlgorithm() {
signatureAlgorithm_ = getDefaultInstance().getSignatureAlgorithm();
onChanged();
return this;
}
/**
*
*
* <pre>
* The algorithm used to sign the certificate.
* </pre>
*
* <code>string signature_algorithm = 5;</code>
*/
public Builder setSignatureAlgorithmBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
signatureAlgorithm_ = value;
onChanged();
return this;
}
private java.lang.Object publicKeyType_ = "";
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public java.lang.String getPublicKeyType() {
java.lang.Object ref = publicKeyType_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
publicKeyType_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public com.google.protobuf.ByteString getPublicKeyTypeBytes() {
java.lang.Object ref = publicKeyType_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
publicKeyType_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public Builder setPublicKeyType(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
publicKeyType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public Builder clearPublicKeyType() {
publicKeyType_ = getDefaultInstance().getPublicKeyType();
onChanged();
return this;
}
/**
*
*
* <pre>
* The type of public key in the certificate.
* </pre>
*
* <code>string public_key_type = 6;</code>
*/
public Builder setPublicKeyTypeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
publicKeyType_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.iot.v1.X509CertificateDetails)
}
// @@protoc_insertion_point(class_scope:google.cloud.iot.v1.X509CertificateDetails)
private static final com.google.cloud.iot.v1.X509CertificateDetails DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iot.v1.X509CertificateDetails();
}
public static com.google.cloud.iot.v1.X509CertificateDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<X509CertificateDetails> PARSER =
new com.google.protobuf.AbstractParser<X509CertificateDetails>() {
@java.lang.Override
public X509CertificateDetails parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new X509CertificateDetails(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<X509CertificateDetails> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<X509CertificateDetails> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iot.v1.X509CertificateDetails getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 28.860451 | 100 | 0.624883 |
903ddb8ba03509a8ebb2f71bc72d4d596c26cbff | 10,143 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for TemplateType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="TemplateType">
* <complexContent>
* <extension base="{}ResourceType">
* <sequence>
* <element name="OperatingSystem" type="{}ReferenceType" minOccurs="0"/>
* <element name="Description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="PriceMatrix" type="{}PriceMatrixType" minOccurs="0"/>
* <element name="Processor" type="{}ConfigurationOptionRangeType" minOccurs="0"/>
* <element name="Memory" type="{}ResourceUnitRangeType" minOccurs="0"/>
* <element name="Storage" type="{}TemplateStorageType" minOccurs="0"/>
* <element name="NetworkAdapters" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="Customization" type="{}CustomizationOptionType" minOccurs="0"/>
* <element name="LicensedSoftware" type="{}DeviceLicensedSoftwareType" minOccurs="0"/>
* <element name="Version" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TemplateVersions" type="{}TemplateVersionsType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TemplateType", propOrder = {
"operatingSystem",
"description",
"priceMatrix",
"processor",
"memory",
"storage",
"networkAdapters",
"customization",
"licensedSoftware",
"version",
"templateVersions"
})
public class TemplateType
extends ResourceType {
@XmlElementRef(name = "OperatingSystem", type = JAXBElement.class, required = false)
protected JAXBElement<ReferenceType> operatingSystem;
@XmlElementRef(name = "Description", type = JAXBElement.class, required = false)
protected JAXBElement<String> description;
@XmlElementRef(name = "PriceMatrix", type = JAXBElement.class, required = false)
protected JAXBElement<PriceMatrixType> priceMatrix;
@XmlElementRef(name = "Processor", type = JAXBElement.class, required = false)
protected JAXBElement<ConfigurationOptionRangeType> processor;
@XmlElementRef(name = "Memory", type = JAXBElement.class, required = false)
protected JAXBElement<ResourceUnitRangeType> memory;
@XmlElementRef(name = "Storage", type = JAXBElement.class, required = false)
protected JAXBElement<TemplateStorageType> storage;
@XmlElement(name = "NetworkAdapters")
protected Integer networkAdapters;
@XmlElementRef(name = "Customization", type = JAXBElement.class, required = false)
protected JAXBElement<CustomizationOptionType> customization;
@XmlElementRef(name = "LicensedSoftware", type = JAXBElement.class, required = false)
protected JAXBElement<DeviceLicensedSoftwareType> licensedSoftware;
@XmlElementRef(name = "Version", type = JAXBElement.class, required = false)
protected JAXBElement<String> version;
@XmlElementRef(name = "TemplateVersions", type = JAXBElement.class, required = false)
protected JAXBElement<TemplateVersionsType> templateVersions;
/**
* Gets the value of the operatingSystem property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
*/
public JAXBElement<ReferenceType> getOperatingSystem() {
return operatingSystem;
}
/**
* Sets the value of the operatingSystem property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link ReferenceType }{@code >}
*/
public void setOperatingSystem(JAXBElement<ReferenceType> value) {
this.operatingSystem = value;
}
/**
* Gets the value of the description property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*/
public JAXBElement<String> getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*/
public void setDescription(JAXBElement<String> value) {
this.description = value;
}
/**
* Gets the value of the priceMatrix property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link PriceMatrixType }{@code >}
*/
public JAXBElement<PriceMatrixType> getPriceMatrix() {
return priceMatrix;
}
/**
* Sets the value of the priceMatrix property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link PriceMatrixType }{@code >}
*/
public void setPriceMatrix(JAXBElement<PriceMatrixType> value) {
this.priceMatrix = value;
}
/**
* Gets the value of the processor property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link ConfigurationOptionRangeType }{@code >}
*/
public JAXBElement<ConfigurationOptionRangeType> getProcessor() {
return processor;
}
/**
* Sets the value of the processor property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link ConfigurationOptionRangeType }{@code >}
*/
public void setProcessor(JAXBElement<ConfigurationOptionRangeType> value) {
this.processor = value;
}
/**
* Gets the value of the memory property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link ResourceUnitRangeType }{@code >}
*/
public JAXBElement<ResourceUnitRangeType> getMemory() {
return memory;
}
/**
* Sets the value of the memory property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link ResourceUnitRangeType }{@code >}
*/
public void setMemory(JAXBElement<ResourceUnitRangeType> value) {
this.memory = value;
}
/**
* Gets the value of the storage property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link TemplateStorageType }{@code >}
*/
public JAXBElement<TemplateStorageType> getStorage() {
return storage;
}
/**
* Sets the value of the storage property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link TemplateStorageType }{@code >}
*/
public void setStorage(JAXBElement<TemplateStorageType> value) {
this.storage = value;
}
/**
* Gets the value of the networkAdapters property.
*
* @return possible object is
* {@link Integer }
*/
public Integer getNetworkAdapters() {
return networkAdapters;
}
/**
* Sets the value of the networkAdapters property.
*
* @param value allowed object is
* {@link Integer }
*/
public void setNetworkAdapters(Integer value) {
this.networkAdapters = value;
}
/**
* Gets the value of the customization property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link CustomizationOptionType }{@code >}
*/
public JAXBElement<CustomizationOptionType> getCustomization() {
return customization;
}
/**
* Sets the value of the customization property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link CustomizationOptionType }{@code >}
*/
public void setCustomization(JAXBElement<CustomizationOptionType> value) {
this.customization = value;
}
/**
* Gets the value of the licensedSoftware property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link DeviceLicensedSoftwareType }{@code >}
*/
public JAXBElement<DeviceLicensedSoftwareType> getLicensedSoftware() {
return licensedSoftware;
}
/**
* Sets the value of the licensedSoftware property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link DeviceLicensedSoftwareType }{@code >}
*/
public void setLicensedSoftware(JAXBElement<DeviceLicensedSoftwareType> value) {
this.licensedSoftware = value;
}
/**
* Gets the value of the version property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*/
public JAXBElement<String> getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*/
public void setVersion(JAXBElement<String> value) {
this.version = value;
}
/**
* Gets the value of the templateVersions property.
*
* @return possible object is
* {@link JAXBElement }{@code <}{@link TemplateVersionsType }{@code >}
*/
public JAXBElement<TemplateVersionsType> getTemplateVersions() {
return templateVersions;
}
/**
* Sets the value of the templateVersions property.
*
* @param value allowed object is
* {@link JAXBElement }{@code <}{@link TemplateVersionsType }{@code >}
*/
public void setTemplateVersions(JAXBElement<TemplateVersionsType> value) {
this.templateVersions = value;
}
}
| 33.365132 | 116 | 0.63709 |
10de9624b0447ae8c6260991f2b4958d89253549 | 1,426 | package com.houseninja.web.svc;
import com.houseninja.db.dao.PlannedCookDao;
import com.houseninja.db.gen.tables.pojos.Plannedcooks;
import com.houseninja.sec.HouseninjaUserDetails;
import com.houseninja.web.svc.util.UserPrincipalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
@RestController
public class PlannedCookController {
private static final String BASE_PATH = "/cook";
@Autowired
private PlannedCookDao plannedCookDao;
@RequestMapping(value = BASE_PATH + "/retrieve/{day}", method = RequestMethod.GET)
public List<Plannedcooks> fetchPlannedCooks(@PathVariable(value = "day") String day) {
Long userHouseholdId = UserPrincipalUtil.getUserPrincipal().getHouseholdId();
if (userHouseholdId == null) {
return Collections.emptyList();
}
LocalDate localDay = LocalDate.parse(day, DateTimeFormatter.ISO_DATE);
return plannedCookDao.retrieve(localDay, userHouseholdId);
}
}
| 37.526316 | 90 | 0.784011 |
4e9a59fae031266a730a34eb69ab2f8bca22c0a3 | 630 | package br.com.zupacademy.mercadolivre.dto.requests;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
public class RankingRequest {
@NotNull
@Positive
private Long idCompra;
@NotNull
@Positive
private Long idDonoProduto;
public RankingRequest(Long idCompra, Long idDonoProduto) {
super();
this.idCompra = idCompra;
this.idDonoProduto = idDonoProduto;
}
@Override
public String toString() {
return "RankingRequest [idCompra=" + this.idCompra + ", idComprador="
+ this.idDonoProduto + "]";
}
}
| 24.230769 | 77 | 0.669841 |
ec3e738a44d622e9a39692d10630d683a35e206e | 795 | // Modulo Arithmetics | Compute answer modulo 1000000007
package problem7.mathsalgo;
import java.util.Scanner;
public class Problem7MathsAlgo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Number : ");
int n1 = input.nextInt();
System.out.print("Enter Power : ");
int n2 = input.nextInt();
System.out.println("Power : " + fastPower(n1, n2, 1000000007));
}
static int fastPower(int a, int b, int n) {
int res = 1;
while (b > 0) {
if ((b & 1) != 0) {
res = (res * a % n) % n;
}
a = (a % n * a % n) % n;
b = b >> 1;
}
return res;
}
}
| 22.714286 | 72 | 0.480503 |
60cffdfba12a33217d03ef54e3a31296cf0c828f | 146,854 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.cache;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.cache.CacheBuilder.NULL_TICKER;
import static com.google.common.cache.CacheBuilder.UNSET_INT;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Stopwatch;
import com.google.common.base.Ticker;
import com.google.common.cache.AbstractCache.SimpleStatsCounter;
import com.google.common.cache.AbstractCache.StatsCounter;
import com.google.common.cache.CacheBuilder.NullListener;
import com.google.common.cache.CacheBuilder.OneWeigher;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
import com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException;
import com.google.common.collect.AbstractSequentialIterator;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ExecutionError;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.j2objc.annotations.Weak;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractQueue;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* The concurrent hash map implementation built by {@link CacheBuilder}.
*
* <p>This implementation is heavily derived from revision 1.96 of <a
* href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>.
*
* @author Charles Fry
* @author Bob Lee ({@code com.google.common.collect.MapMaker})
* @author Doug Lea ({@code ConcurrentHashMap})
*/
@GwtCompatible(emulated = true)
class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {
/*
* The basic strategy is to subdivide the table among Segments, each of which itself is a
* concurrently readable hash table. The map supports non-blocking reads and concurrent writes
* across different segments.
*
* If a maximum size is specified, a best-effort bounding is performed per segment, using a
* page-replacement algorithm to determine which entries to evict when the capacity has been
* exceeded.
*
* The page replacement algorithm's data structures are kept casually consistent with the map. The
* ordering of writes to a segment is sequentially consistent. An update to the map and recording
* of reads may not be immediately reflected on the algorithm's data structures. These structures
* are guarded by a lock and operations are applied in batches to avoid lock contention. The
* penalty of applying the batches is spread across threads so that the amortized cost is slightly
* higher than performing just the operation without enforcing the capacity constraint.
*
* This implementation uses a per-segment queue to record a memento of the additions, removals,
* and accesses that were performed on the map. The queue is drained on writes and when it exceeds
* its capacity threshold.
*
* The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit
* rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation
* operates per-segment rather than globally for increased implementation simplicity. We expect
* the cache hit rate to be similar to that of a global LRU algorithm.
*/
// Constants
/**
* The maximum capacity, used if a higher value is implicitly specified by either of the
* constructors with arguments. MUST be a power of two <= 1<<30 to ensure that entries are
* indexable using ints.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/** The maximum number of segments to allow; used to bound constructor arguments. */
static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
/** Number of (unsynchronized) retries in the containsValue method. */
static final int CONTAINS_VALUE_RETRIES = 3;
/**
* Number of cache access operations that can be buffered per segment before the cache's recency
* ordering information is updated. This is used to avoid lock contention by recording a memento
* of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs.
*
* <p>This must be a (2^n)-1 as it is used as a mask.
*/
static final int DRAIN_THRESHOLD = 0x3F;
/**
* Maximum number of entries to be drained in a single cleanup run. This applies independently to
* the cleanup queue and both reference queues.
*/
// TODO(fry): empirically optimize this
static final int DRAIN_MAX = 16;
// Fields
static final Logger logger = Logger.getLogger(LocalCache.class.getName());
/**
* Mask value for indexing into segments. The upper bits of a key's hash code are used to choose
* the segment.
*/
final int segmentMask;
/**
* Shift value for indexing within segments. Helps prevent entries that end up in the same segment
* from also ending up in the same bucket.
*/
final int segmentShift;
/** The segments, each of which is a specialized hash table. */
final Segment<K, V>[] segments;
/** The concurrency level. */
final int concurrencyLevel;
/** Strategy for comparing keys. */
final Equivalence<Object> keyEquivalence;
/** Strategy for comparing values. */
final Equivalence<Object> valueEquivalence;
/** Strategy for referencing keys. */
final Strength keyStrength;
/** Strategy for referencing values. */
final Strength valueStrength;
/** The maximum weight of this map. UNSET_INT if there is no maximum. */
final long maxWeight;
/** Weigher to weigh cache entries. */
final Weigher<K, V> weigher;
/** How long after the last access to an entry the map will retain that entry. */
final long expireAfterAccessNanos;
/** How long after the last write to an entry the map will retain that entry. */
final long expireAfterWriteNanos;
/** How long after the last write an entry becomes a candidate for refresh. */
final long refreshNanos;
/** Entries waiting to be consumed by the removal listener. */
// TODO(fry): define a new type which creates event objects and automates the clear logic
final Queue<RemovalNotification<K, V>> removalNotificationQueue;
/**
* A listener that is invoked when an entry is removed due to expiration or garbage collection of
* soft/weak entries.
*/
final RemovalListener<K, V> removalListener;
/** Measures time in a testable way. */
final Ticker ticker;
/** Factory used to create new entries. */
final EntryFactory entryFactory;
/**
* Accumulates global cache statistics. Note that there are also per-segments stats counters
* which must be aggregated to obtain a global stats view.
*/
final StatsCounter globalStatsCounter;
/**
* The default cache loader to use on loading operations.
*/
@Nullable
final CacheLoader<? super K, V> defaultLoader;
/**
* Creates a new, empty map with the specified strategy, initial capacity and concurrency level.
*/
LocalCache(
CacheBuilder<? super K, ? super V> builder, @Nullable CacheLoader<? super K, V> loader) {
concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS);
keyStrength = builder.getKeyStrength();
valueStrength = builder.getValueStrength();
keyEquivalence = builder.getKeyEquivalence();
valueEquivalence = builder.getValueEquivalence();
maxWeight = builder.getMaximumWeight();
weigher = builder.getWeigher();
expireAfterAccessNanos = builder.getExpireAfterAccessNanos();
expireAfterWriteNanos = builder.getExpireAfterWriteNanos();
refreshNanos = builder.getRefreshNanos();
removalListener = builder.getRemovalListener();
removalNotificationQueue = (removalListener == NullListener.INSTANCE)
? LocalCache.<RemovalNotification<K, V>>discardingQueue()
: new ConcurrentLinkedQueue<RemovalNotification<K, V>>();
ticker = builder.getTicker(recordsTime());
entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries());
globalStatsCounter = builder.getStatsCounterSupplier().get();
defaultLoader = loader;
int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY);
if (evictsBySize() && !customWeigher()) {
initialCapacity = Math.min(initialCapacity, (int) maxWeight);
}
// Find the lowest power-of-two segmentCount that exceeds concurrencyLevel, unless
// maximumSize/Weight is specified in which case ensure that each segment gets at least 10
// entries. The special casing for size-based eviction is only necessary because that eviction
// happens per segment instead of globally, so too many segments compared to the maximum size
// will result in random eviction behavior.
int segmentShift = 0;
int segmentCount = 1;
while (segmentCount < concurrencyLevel
&& (!evictsBySize() || segmentCount * 20 <= maxWeight)) {
++segmentShift;
segmentCount <<= 1;
}
this.segmentShift = 32 - segmentShift;
segmentMask = segmentCount - 1;
this.segments = newSegmentArray(segmentCount);
int segmentCapacity = initialCapacity / segmentCount;
if (segmentCapacity * segmentCount < initialCapacity) {
++segmentCapacity;
}
int segmentSize = 1;
while (segmentSize < segmentCapacity) {
segmentSize <<= 1;
}
if (evictsBySize()) {
// Ensure sum of segment max weights = overall max weights
long maxSegmentWeight = maxWeight / segmentCount + 1;
long remainder = maxWeight % segmentCount;
for (int i = 0; i < this.segments.length; ++i) {
if (i == remainder) {
maxSegmentWeight--;
}
this.segments[i] =
createSegment(segmentSize, maxSegmentWeight, builder.getStatsCounterSupplier().get());
}
} else {
for (int i = 0; i < this.segments.length; ++i) {
this.segments[i] =
createSegment(segmentSize, UNSET_INT, builder.getStatsCounterSupplier().get());
}
}
}
boolean evictsBySize() {
return maxWeight >= 0;
}
boolean customWeigher() {
return weigher != OneWeigher.INSTANCE;
}
boolean expires() {
return expiresAfterWrite() || expiresAfterAccess();
}
boolean expiresAfterWrite() {
return expireAfterWriteNanos > 0;
}
boolean expiresAfterAccess() {
return expireAfterAccessNanos > 0;
}
boolean refreshes() {
return refreshNanos > 0;
}
boolean usesAccessQueue() {
return expiresAfterAccess() || evictsBySize();
}
boolean usesWriteQueue() {
return expiresAfterWrite();
}
boolean recordsWrite() {
return expiresAfterWrite() || refreshes();
}
boolean recordsAccess() {
return expiresAfterAccess();
}
boolean recordsTime() {
return recordsWrite() || recordsAccess();
}
boolean usesWriteEntries() {
return usesWriteQueue() || recordsWrite();
}
boolean usesAccessEntries() {
return usesAccessQueue() || recordsAccess();
}
boolean usesKeyReferences() {
return keyStrength != Strength.STRONG;
}
boolean usesValueReferences() {
return valueStrength != Strength.STRONG;
}
enum Strength {
/*
* TODO(kevinb): If we strongly reference the value and aren't loading, we needn't wrap the
* value. This could save ~8 bytes per entry.
*/
STRONG {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new StrongValueReference<K, V>(value)
: new WeightedStrongValueReference<K, V>(value, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.equals();
}
},
SOFT {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedSoftValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
},
WEAK {
@Override
<K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) {
return (weight == 1)
? new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry)
: new WeightedWeakValueReference<K, V>(
segment.valueReferenceQueue, value, entry, weight);
}
@Override
Equivalence<Object> defaultEquivalence() {
return Equivalence.identity();
}
};
/**
* Creates a reference for the given value according to this value strength.
*/
abstract <K, V> ValueReference<K, V> referenceValue(
Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight);
/**
* Returns the default equivalence strategy used to compare and hash keys or values referenced
* at this strength. This strategy will be used unless the user explicitly specifies an
* alternate strategy.
*/
abstract Equivalence<Object> defaultEquivalence();
}
/**
* Creates new entries.
*/
enum EntryFactory {
STRONG {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongEntry<K, V>(key, hash, next);
}
},
STRONG_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongAccessEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
STRONG_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongWriteEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
STRONG_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new StrongAccessWriteEntry<K, V>(key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
},
WEAK_ACCESS {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakAccessEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyAccessEntry(original, newEntry);
return newEntry;
}
},
WEAK_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakWriteEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyWriteEntry(original, newEntry);
return newEntry;
}
},
WEAK_ACCESS_WRITE {
@Override
<K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return new WeakAccessWriteEntry<K, V>(segment.keyReferenceQueue, key, hash, next);
}
@Override
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext);
copyAccessEntry(original, newEntry);
copyWriteEntry(original, newEntry);
return newEntry;
}
};
/**
* Masks used to compute indices in the following table.
*/
static final int ACCESS_MASK = 1;
static final int WRITE_MASK = 2;
static final int WEAK_MASK = 4;
/**
* Look-up table for factories.
*/
static final EntryFactory[] factories = {
STRONG, STRONG_ACCESS, STRONG_WRITE, STRONG_ACCESS_WRITE,
WEAK, WEAK_ACCESS, WEAK_WRITE, WEAK_ACCESS_WRITE,
};
static EntryFactory getFactory(Strength keyStrength, boolean usesAccessQueue,
boolean usesWriteQueue) {
int flags = ((keyStrength == Strength.WEAK) ? WEAK_MASK : 0)
| (usesAccessQueue ? ACCESS_MASK : 0)
| (usesWriteQueue ? WRITE_MASK : 0);
return factories[flags];
}
/**
* Creates a new entry.
*
* @param segment to create the entry for
* @param key of the entry
* @param hash of the key
* @param next entry in the same bucket
*/
abstract <K, V> ReferenceEntry<K, V> newEntry(
Segment<K, V> segment, K key, int hash, @Nullable ReferenceEntry<K, V> next);
/**
* Copies an entry, assigning it a new {@code next} entry.
*
* @param original the entry to copy
* @param newNext entry in the same bucket
*/
// Guarded By Segment.this
<K, V> ReferenceEntry<K, V> copyEntry(
Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
return newEntry(segment, original.getKey(), original.getHash(), newNext);
}
// Guarded By Segment.this
<K, V> void copyAccessEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectAccessOrder, nullifyAccessOrder.
newEntry.setAccessTime(original.getAccessTime());
connectAccessOrder(original.getPreviousInAccessQueue(), newEntry);
connectAccessOrder(newEntry, original.getNextInAccessQueue());
nullifyAccessOrder(original);
}
// Guarded By Segment.this
<K, V> void copyWriteEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) {
// TODO(fry): when we link values instead of entries this method can go
// away, as can connectWriteOrder, nullifyWriteOrder.
newEntry.setWriteTime(original.getWriteTime());
connectWriteOrder(original.getPreviousInWriteQueue(), newEntry);
connectWriteOrder(newEntry, original.getNextInWriteQueue());
nullifyWriteOrder(original);
}
}
/**
* A reference to a value.
*/
interface ValueReference<K, V> {
/**
* Returns the value. Does not block or throw exceptions.
*/
@Nullable
V get();
/**
* Waits for a value that may still be loading. Unlike get(), this method can block (in the
* case of FutureValueReference).
*
* @throws ExecutionException if the loading thread throws an exception
* @throws ExecutionError if the loading thread throws an error
*/
V waitForValue() throws ExecutionException;
/**
* Returns the weight of this entry. This is assumed to be static between calls to setValue.
*/
int getWeight();
/**
* Returns the entry associated with this value reference, or {@code null} if this value
* reference is independent of any entry.
*/
@Nullable
ReferenceEntry<K, V> getEntry();
/**
* Creates a copy of this reference for the given entry.
*
* <p>{@code value} may be null only for a loading reference.
*/
ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry);
/**
* Notifify pending loads that a new value was set. This is only relevant to loading
* value references.
*/
void notifyNewValue(@Nullable V newValue);
/**
* Returns true if a new value is currently loading, regardless of whether or not there is an
* existing value. It is assumed that the return value of this method is constant for any given
* ValueReference instance.
*/
boolean isLoading();
/**
* Returns true if this reference contains an active value, meaning one that is still considered
* present in the cache. Active values consist of live values, which are returned by cache
* lookups, and dead values, which have been evicted but awaiting removal. Non-active values
* consist strictly of loading values, though during refresh a value may be both active and
* loading.
*/
boolean isActive();
}
/**
* Placeholder. Indicates that the value hasn't been set yet.
*/
static final ValueReference<Object, Object> UNSET = new ValueReference<Object, Object>() {
@Override
public Object get() {
return null;
}
@Override
public int getWeight() {
return 0;
}
@Override
public ReferenceEntry<Object, Object> getEntry() {
return null;
}
@Override
public ValueReference<Object, Object> copyFor(ReferenceQueue<Object> queue,
@Nullable Object value, ReferenceEntry<Object, Object> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return false;
}
@Override
public Object waitForValue() {
return null;
}
@Override
public void notifyNewValue(Object newValue) {}
};
/**
* Singleton placeholder that indicates a value is being loaded.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ValueReference<K, V> unset() {
return (ValueReference<K, V>) UNSET;
}
/**
* An entry in a reference map.
*
* Entries in the map can be in the following states:
*
* Valid:
* - Live: valid key/value are set
* - Loading: loading is pending
*
* Invalid:
* - Expired: time expired (key/value may still be set)
* - Collected: key/value was partially collected, but not yet cleaned up
* - Unset: marked as unset, awaiting cleanup or reuse
*/
interface ReferenceEntry<K, V> {
/**
* Returns the value reference from this entry.
*/
ValueReference<K, V> getValueReference();
/**
* Sets the value reference for this entry.
*/
void setValueReference(ValueReference<K, V> valueReference);
/**
* Returns the next entry in the chain.
*/
@Nullable
ReferenceEntry<K, V> getNext();
/**
* Returns the entry's hash.
*/
int getHash();
/**
* Returns the key for this entry.
*/
@Nullable
K getKey();
/*
* Used by entries that use access order. Access entries are maintained in a doubly-linked list.
* New entries are added at the tail of the list at write time; stale entries are expired from
* the head of the list.
*/
/**
* Returns the time that this entry was last accessed, in ns.
*/
long getAccessTime();
/**
* Sets the entry access time in ns.
*/
void setAccessTime(long time);
/**
* Returns the next entry in the access queue.
*/
ReferenceEntry<K, V> getNextInAccessQueue();
/**
* Sets the next entry in the access queue.
*/
void setNextInAccessQueue(ReferenceEntry<K, V> next);
/**
* Returns the previous entry in the access queue.
*/
ReferenceEntry<K, V> getPreviousInAccessQueue();
/**
* Sets the previous entry in the access queue.
*/
void setPreviousInAccessQueue(ReferenceEntry<K, V> previous);
/*
* Implemented by entries that use write order. Write entries are maintained in a
* doubly-linked list. New entries are added at the tail of the list at write time and stale
* entries are expired from the head of the list.
*/
/**
* Returns the time that this entry was last written, in ns.
*/
long getWriteTime();
/**
* Sets the entry write time in ns.
*/
void setWriteTime(long time);
/**
* Returns the next entry in the write queue.
*/
ReferenceEntry<K, V> getNextInWriteQueue();
/**
* Sets the next entry in the write queue.
*/
void setNextInWriteQueue(ReferenceEntry<K, V> next);
/**
* Returns the previous entry in the write queue.
*/
ReferenceEntry<K, V> getPreviousInWriteQueue();
/**
* Sets the previous entry in the write queue.
*/
void setPreviousInWriteQueue(ReferenceEntry<K, V> previous);
}
private enum NullEntry implements ReferenceEntry<Object, Object> {
INSTANCE;
@Override
public ValueReference<Object, Object> getValueReference() {
return null;
}
@Override
public void setValueReference(ValueReference<Object, Object> valueReference) {}
@Override
public ReferenceEntry<Object, Object> getNext() {
return null;
}
@Override
public int getHash() {
return 0;
}
@Override
public Object getKey() {
return null;
}
@Override
public long getAccessTime() {
return 0;
}
@Override
public void setAccessTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInAccessQueue() {
return this;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInAccessQueue() {
return this;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<Object, Object> previous) {}
@Override
public long getWriteTime() {
return 0;
}
@Override
public void setWriteTime(long time) {}
@Override
public ReferenceEntry<Object, Object> getNextInWriteQueue() {
return this;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<Object, Object> next) {}
@Override
public ReferenceEntry<Object, Object> getPreviousInWriteQueue() {
return this;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<Object, Object> previous) {}
}
abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> {
@Override
public ValueReference<K, V> getValueReference() {
throw new UnsupportedOperationException();
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNext() {
throw new UnsupportedOperationException();
}
@Override
public int getHash() {
throw new UnsupportedOperationException();
}
@Override
public K getKey() {
throw new UnsupportedOperationException();
}
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <K, V> ReferenceEntry<K, V> nullEntry() {
return (ReferenceEntry<K, V>) NullEntry.INSTANCE;
}
static final Queue<? extends Object> DISCARDING_QUEUE = new AbstractQueue<Object>() {
@Override
public boolean offer(Object o) {
return true;
}
@Override
public Object peek() {
return null;
}
@Override
public Object poll() {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Object> iterator() {
return ImmutableSet.of().iterator();
}
};
/**
* Queue that discards all elements.
*/
@SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value
static <E> Queue<E> discardingQueue() {
return (Queue) DISCARDING_QUEUE;
}
/*
* Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins!
* To maintain this code, make a change for the strong reference type. Then, cut and paste, and
* replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that
* strong entries store the key reference directly while soft and weak entries delegate to their
* respective superclasses.
*/
/**
* Used for strongly-referenced keys.
*/
static class StrongEntry<K, V> extends AbstractReferenceEntry<K, V> {
final K key;
StrongEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
this.key = key;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return this.key;
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class StrongAccessEntry<K, V> extends StrongEntry<K, V> {
StrongAccessEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class StrongWriteEntry<K, V> extends StrongEntry<K, V> {
StrongWriteEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class StrongAccessWriteEntry<K, V> extends StrongEntry<K, V> {
StrongAccessWriteEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/**
* Used for weakly-referenced keys.
*/
static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> {
WeakEntry(ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(key, queue);
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return get();
}
/*
* It'd be nice to get these for free from AbstractReferenceEntry, but we're already extending
* WeakReference<K>.
*/
// null access
@Override
public long getAccessTime() {
throw new UnsupportedOperationException();
}
@Override
public void setAccessTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// null write
@Override
public long getWriteTime() {
throw new UnsupportedOperationException();
}
@Override
public void setWriteTime(long time) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
throw new UnsupportedOperationException();
}
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
throw new UnsupportedOperationException();
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
throw new UnsupportedOperationException();
}
// The code below is exactly the same for each entry type.
final int hash;
final ReferenceEntry<K, V> next;
volatile ValueReference<K, V> valueReference = unset();
@Override
public ValueReference<K, V> getValueReference() {
return valueReference;
}
@Override
public void setValueReference(ValueReference<K, V> valueReference) {
this.valueReference = valueReference;
}
@Override
public int getHash() {
return hash;
}
@Override
public ReferenceEntry<K, V> getNext() {
return next;
}
}
static final class WeakAccessEntry<K, V> extends WeakEntry<K, V> {
WeakAccessEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
}
static final class WeakWriteEntry<K, V> extends WeakEntry<K, V> {
WeakWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
static final class WeakAccessWriteEntry<K, V> extends WeakEntry<K, V> {
WeakAccessWriteEntry(
ReferenceQueue<K> queue, K key, int hash, @Nullable ReferenceEntry<K, V> next) {
super(queue, key, hash, next);
}
// The code below is exactly the same for each access entry type.
volatile long accessTime = Long.MAX_VALUE;
@Override
public long getAccessTime() {
return accessTime;
}
@Override
public void setAccessTime(long time) {
this.accessTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousAccess = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
// The code below is exactly the same for each write entry type.
volatile long writeTime = Long.MAX_VALUE;
@Override
public long getWriteTime() {
return writeTime;
}
@Override
public void setWriteTime(long time) {
this.writeTime = time;
}
// Guarded By Segment.this
ReferenceEntry<K, V> nextWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
// Guarded By Segment.this
ReferenceEntry<K, V> previousWrite = nullEntry();
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
}
/**
* References a weak value.
*/
static class WeakValueReference<K, V>
extends WeakReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeakValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a soft value.
*/
static class SoftValueReference<K, V>
extends SoftReference<V> implements ValueReference<K, V> {
final ReferenceEntry<K, V> entry;
SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) {
super(referent, queue);
this.entry = entry;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return entry;
}
@Override
public void notifyNewValue(V newValue) {}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new SoftValueReference<K, V>(queue, value, entry);
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
}
/**
* References a strong value.
*/
static class StrongValueReference<K, V> implements ValueReference<K, V> {
final V referent;
StrongValueReference(V referent) {
this.referent = referent;
}
@Override
public V get() {
return referent;
}
@Override
public int getWeight() {
return 1;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return this;
}
@Override
public boolean isLoading() {
return false;
}
@Override
public boolean isActive() {
return true;
}
@Override
public V waitForValue() {
return get();
}
@Override
public void notifyNewValue(V newValue) {}
}
/**
* References a weak value.
*/
static final class WeightedWeakValueReference<K, V> extends WeakValueReference<K, V> {
final int weight;
WeightedWeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry,
int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedWeakValueReference<K, V>(queue, value, entry, weight);
}
}
/**
* References a soft value.
*/
static final class WeightedSoftValueReference<K, V> extends SoftValueReference<K, V> {
final int weight;
WeightedSoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry,
int weight) {
super(queue, referent, entry);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) {
return new WeightedSoftValueReference<K, V>(queue, value, entry, weight);
}
}
/**
* References a strong value.
*/
static final class WeightedStrongValueReference<K, V> extends StrongValueReference<K, V> {
final int weight;
WeightedStrongValueReference(V referent, int weight) {
super(referent);
this.weight = weight;
}
@Override
public int getWeight() {
return weight;
}
}
/**
* Applies a supplemental hash function to a given hash code, which defends against poor quality
* hash functions. This is critical when the concurrent hash map uses power-of-two length hash
* tables, that otherwise encounter collisions for hash codes that do not differ in lower or
* upper bits.
*
* @param h hash code
*/
static int rehash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
// TODO(kevinb): use Hashing/move this to Hashing?
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#newEntry} directly.
*/
@VisibleForTesting
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
Segment<K, V> segment = segmentFor(hash);
segment.lock();
try {
return segment.newEntry(key, hash, next);
} finally {
segment.unlock();
}
}
/**
* This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly.
*/
// Guarded By Segment.this
@VisibleForTesting
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
int hash = original.getHash();
return segmentFor(hash).copyEntry(original, newNext);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#setValue} instead.
*/
// Guarded By Segment.this
@VisibleForTesting
ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value, int weight) {
int hash = entry.getHash();
return valueStrength.referenceValue(segmentFor(hash), entry, checkNotNull(value), weight);
}
int hash(@Nullable Object key) {
int h = keyEquivalence.hash(key);
return rehash(h);
}
void reclaimValue(ValueReference<K, V> valueReference) {
ReferenceEntry<K, V> entry = valueReference.getEntry();
int hash = entry.getHash();
segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference);
}
void reclaimKey(ReferenceEntry<K, V> entry) {
int hash = entry.getHash();
segmentFor(hash).reclaimKey(entry, hash);
}
/**
* This method is a convenience for testing. Code should call {@link Segment#getLiveValue}
* instead.
*/
@VisibleForTesting
boolean isLive(ReferenceEntry<K, V> entry, long now) {
return segmentFor(entry.getHash()).getLiveValue(entry, now) != null;
}
/**
* Returns the segment that should be used for a key with the given hash.
*
* @param hash the hash code for the key
* @return the segment
*/
Segment<K, V> segmentFor(int hash) {
// TODO(fry): Lazily create segments?
return segments[(hash >>> segmentShift) & segmentMask];
}
Segment<K, V> createSegment(
int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) {
return new Segment<K, V>(this, initialCapacity, maxSegmentWeight, statsCounter);
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to
* cleanup stale entries. As such it should only be called outside of a segment context, such as
* during iteration.
*/
@Nullable
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
return null;
}
if (isExpired(entry, now)) {
return null;
}
return value;
}
// expiration
/**
* Returns true if the entry has expired.
*/
boolean isExpired(ReferenceEntry<K, V> entry, long now) {
checkNotNull(entry);
if (expiresAfterAccess()
&& (now - entry.getAccessTime() >= expireAfterAccessNanos)) {
return true;
}
if (expiresAfterWrite()
&& (now - entry.getWriteTime() >= expireAfterWriteNanos)) {
return true;
}
return false;
}
// queues
// Guarded By Segment.this
static <K, V> void connectAccessOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInAccessQueue(next);
next.setPreviousInAccessQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyAccessOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInAccessQueue(nullEntry);
nulled.setPreviousInAccessQueue(nullEntry);
}
// Guarded By Segment.this
static <K, V> void connectWriteOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) {
previous.setNextInWriteQueue(next);
next.setPreviousInWriteQueue(previous);
}
// Guarded By Segment.this
static <K, V> void nullifyWriteOrder(ReferenceEntry<K, V> nulled) {
ReferenceEntry<K, V> nullEntry = nullEntry();
nulled.setNextInWriteQueue(nullEntry);
nulled.setPreviousInWriteQueue(nullEntry);
}
/**
* Notifies listeners that an entry has been automatically removed due to expiration, eviction,
* or eligibility for garbage collection. This should be called every time expireEntries or
* evictEntry is called (once the lock is released).
*/
void processPendingNotifications() {
RemovalNotification<K, V> notification;
while ((notification = removalNotificationQueue.poll()) != null) {
try {
removalListener.onRemoval(notification);
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception thrown by removal listener", e);
}
}
}
@SuppressWarnings("unchecked")
final Segment<K, V>[] newSegmentArray(int ssize) {
return new Segment[ssize];
}
// Inner Classes
/**
* Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock
* opportunistically, just to simplify some locking and avoid separate construction.
*/
@SuppressWarnings("serial") // This class is never serialized.
static class Segment<K, V> extends ReentrantLock {
/*
* TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class.
* It will require more memory but will reduce indirection.
*/
/*
* Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can
* be read without locking. Next fields of nodes are immutable (final). All list additions are
* performed at the front of each bin. This makes it easy to check changes, and also fast to
* traverse. When nodes would otherwise be changed, new nodes are created to replace them. This
* works well for hash tables since the bin lists tend to be short. (The average length is less
* than two.)
*
* Read operations can thus proceed without locking, but rely on selected uses of volatiles to
* ensure that completed write operations performed by other threads are noticed. For most
* purposes, the "count" field, tracking the number of elements, serves as that volatile
* variable ensuring visibility. This is convenient because this field needs to be read in many
* read operations anyway:
*
* - All (unsynchronized) read operations must first read the "count" field, and should not
* look at table entries if it is 0.
*
* - All (synchronized) write operations should write to the "count" field after structurally
* changing any bin. The operations must not take any action that could even momentarily
* cause a concurrent read operation to see inconsistent data. This is made easier by the
* nature of the read operations in Map. For example, no operation can reveal that the table
* has grown but the threshold has not yet been updated, so there are no atomicity requirements
* for this with respect to reads.
*
* As a guide, all critical volatile reads and writes to the count field are marked in code
* comments.
*/
@Weak final LocalCache<K, V> map;
/**
* The number of live elements in this segment's region.
*/
volatile int count;
/**
* The weight of the live elements in this segment's region.
*/
@GuardedBy("this")
long totalWeight;
/**
* Number of updates that alter the size of the table. This is used during bulk-read methods to
* make sure they see a consistent snapshot: If modCounts change during a traversal of segments
* loading size or checking containsValue, then we might have an inconsistent view of state
* so (usually) must retry.
*/
int modCount;
/**
* The table is expanded when its size exceeds this threshold. (The value of this field is
* always {@code (int) (capacity * 0.75)}.)
*/
int threshold;
/**
* The per-segment table.
*/
volatile AtomicReferenceArray<ReferenceEntry<K, V>> table;
/**
* The maximum weight of this segment. UNSET_INT if there is no maximum.
*/
final long maxSegmentWeight;
/**
* The key reference queue contains entries whose keys have been garbage collected, and which
* need to be cleaned up internally.
*/
final ReferenceQueue<K> keyReferenceQueue;
/**
* The value reference queue contains value references whose values have been garbage collected,
* and which need to be cleaned up internally.
*/
final ReferenceQueue<V> valueReferenceQueue;
/**
* The recency queue is used to record which entries were accessed for updating the access
* list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is
* crossed or a write occurs on the segment.
*/
final Queue<ReferenceEntry<K, V>> recencyQueue;
/**
* A counter of the number of reads since the last write, used to drain queues on a small
* fraction of read operations.
*/
final AtomicInteger readCount = new AtomicInteger();
/**
* A queue of elements currently in the map, ordered by write time. Elements are added to the
* tail of the queue on write.
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> writeQueue;
/**
* A queue of elements currently in the map, ordered by access time. Elements are added to the
* tail of the queue on access (note that writes count as accesses).
*/
@GuardedBy("this")
final Queue<ReferenceEntry<K, V>> accessQueue;
/** Accumulates cache statistics. */
final StatsCounter statsCounter;
Segment(LocalCache<K, V> map, int initialCapacity, long maxSegmentWeight,
StatsCounter statsCounter) {
this.map = map;
this.maxSegmentWeight = maxSegmentWeight;
this.statsCounter = checkNotNull(statsCounter);
initTable(newEntryArray(initialCapacity));
keyReferenceQueue = map.usesKeyReferences()
? new ReferenceQueue<K>() : null;
valueReferenceQueue = map.usesValueReferences()
? new ReferenceQueue<V>() : null;
recencyQueue = map.usesAccessQueue()
? new ConcurrentLinkedQueue<ReferenceEntry<K, V>>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
writeQueue = map.usesWriteQueue()
? new WriteQueue<K, V>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
accessQueue = map.usesAccessQueue()
? new AccessQueue<K, V>()
: LocalCache.<ReferenceEntry<K, V>>discardingQueue();
}
AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) {
return new AtomicReferenceArray<ReferenceEntry<K, V>>(size);
}
void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) {
this.threshold = newTable.length() * 3 / 4; // 0.75
if (!map.customWeigher() && this.threshold == maxSegmentWeight) {
// prevent spurious expansion before eviction
this.threshold++;
}
this.table = newTable;
}
@GuardedBy("this")
ReferenceEntry<K, V> newEntry(K key, int hash, @Nullable ReferenceEntry<K, V> next) {
return map.entryFactory.newEntry(this, checkNotNull(key), hash, next);
}
/**
* Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry,
* or {@code null} if {@code original} was already garbage collected.
*/
@GuardedBy("this")
ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) {
if (original.getKey() == null) {
// key collected
return null;
}
ValueReference<K, V> valueReference = original.getValueReference();
V value = valueReference.get();
if ((value == null) && valueReference.isActive()) {
// value collected
return null;
}
ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext);
newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry));
return newEntry;
}
/**
* Sets a new value of an entry. Adds newly created entries at the end of the access queue.
*/
@GuardedBy("this")
void setValue(ReferenceEntry<K, V> entry, K key, V value, long now) {
ValueReference<K, V> previous = entry.getValueReference();
int weight = map.weigher.weigh(key, value);
checkState(weight >= 0, "Weights must be non-negative");
ValueReference<K, V> valueReference =
map.valueStrength.referenceValue(this, entry, value, weight);
entry.setValueReference(valueReference);
recordWrite(entry, weight, now);
previous.notifyNewValue(value);
}
// loading
V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException {
checkNotNull(key);
checkNotNull(loader);
try {
if (count != 0) { // read-volatile
// don't call getLiveEntry, which would ignore loading values
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e != null) {
long now = map.ticker.read();
V value = getLiveValue(e, now);
if (value != null) {
recordRead(e, now);
statsCounter.recordHits(1);
return scheduleRefresh(e, key, hash, value, now, loader);
}
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()) {
return waitForLoadingValue(e, key, valueReference);
}
}
}
// at this point e is either null or expired;
return lockedGetOrLoad(key, hash, loader);
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
} else if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
}
throw ee;
} finally {
postReadCleanup();
}
}
V lockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader)
throws ExecutionException {
ReferenceEntry<K, V> e;
ValueReference<K, V> valueReference = null;
LoadingValueReference<K, V> loadingValueReference = null;
boolean createNewEntry = true;
lock();
try {
// re-read ticker once inside the lock
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
valueReference = e.getValueReference();
if (valueReference.isLoading()) {
createNewEntry = false;
} else {
V value = valueReference.get();
if (value == null) {
enqueueNotification(entryKey, hash, value,
valueReference.getWeight(), RemovalCause.COLLECTED);
} else if (map.isExpired(e, now)) {
// This is a duplicate check, as preWriteCleanup already purged expired
// entries, but let's accomodate an incorrect expiration queue.
enqueueNotification(entryKey, hash, value,
valueReference.getWeight(), RemovalCause.EXPIRED);
} else {
recordLockedRead(e, now);
statsCounter.recordHits(1);
// we were concurrent with loading; don't consider refresh
return value;
}
// immediately reuse invalid entries
writeQueue.remove(e);
accessQueue.remove(e);
this.count = newCount; // write-volatile
}
break;
}
}
if (createNewEntry) {
loadingValueReference = new LoadingValueReference<K, V>();
if (e == null) {
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
} else {
e.setValueReference(loadingValueReference);
}
}
} finally {
unlock();
postWriteCleanup();
}
if (createNewEntry) {
try {
// Synchronizes on the entry to allow failing fast when a recursive load is
// detected. This may be circumvented when an entry is copied, but will fail fast most
// of the time.
synchronized (e) {
return loadSync(key, hash, loadingValueReference, loader);
}
} finally {
statsCounter.recordMisses(1);
}
} else {
// The entry already exists. Wait for loading.
return waitForLoadingValue(e, key, valueReference);
}
}
V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference)
throws ExecutionException {
if (!valueReference.isLoading()) {
throw new AssertionError();
}
checkState(!Thread.holdsLock(e), "Recursive load of: %s", key);
// don't consider expiration as we're concurrent with loading
try {
V value = valueReference.waitForValue();
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
// re-read ticker now that loading has completed
long now = map.ticker.read();
recordRead(e, now);
return value;
} finally {
statsCounter.recordMisses(1);
}
}
// at most one of loadSync/loadAsync may be called for any given LoadingValueReference
V loadSync(K key, int hash, LoadingValueReference<K, V> loadingValueReference,
CacheLoader<? super K, V> loader) throws ExecutionException {
ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
return getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
}
ListenableFuture<V> loadAsync(final K key, final int hash,
final LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) {
final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader);
loadingFuture.addListener(
new Runnable() {
@Override
public void run() {
try {
getAndRecordStats(key, hash, loadingValueReference, loadingFuture);
} catch (Throwable t) {
logger.log(Level.WARNING, "Exception thrown during refresh", t);
loadingValueReference.setException(t);
}
}
}, directExecutor());
return loadingFuture;
}
/**
* Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats.
*/
V getAndRecordStats(K key, int hash, LoadingValueReference<K, V> loadingValueReference,
ListenableFuture<V> newValue) throws ExecutionException {
V value = null;
try {
value = getUninterruptibly(newValue);
if (value == null) {
throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + ".");
}
statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos());
storeLoadedValue(key, hash, loadingValueReference, value);
return value;
} finally {
if (value == null) {
statsCounter.recordLoadException(loadingValueReference.elapsedNanos());
removeLoadingValue(key, hash, loadingValueReference);
}
}
}
V scheduleRefresh(ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now,
CacheLoader<? super K, V> loader) {
if (map.refreshes() && (now - entry.getWriteTime() > map.refreshNanos)
&& !entry.getValueReference().isLoading()) {
V newValue = refresh(key, hash, loader, true);
if (newValue != null) {
return newValue;
}
}
return oldValue;
}
/**
* Refreshes the value associated with {@code key}, unless another thread is already doing so.
* Returns the newly refreshed value associated with {@code key} if it was refreshed inline, or
* {@code null} if another thread is performing the refresh or if an error occurs during
* refresh.
*/
@Nullable
V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) {
final LoadingValueReference<K, V> loadingValueReference =
insertLoadingValueReference(key, hash, checkTime);
if (loadingValueReference == null) {
return null;
}
ListenableFuture<V> result = loadAsync(key, hash, loadingValueReference, loader);
if (result.isDone()) {
try {
return Uninterruptibles.getUninterruptibly(result);
} catch (Throwable t) {
// don't let refresh exceptions propagate; error was already logged
}
}
return null;
}
/**
* Returns a newly inserted {@code LoadingValueReference}, or null if the live value reference
* is already loading.
*/
@Nullable
LoadingValueReference<K, V> insertLoadingValueReference(final K key, final int hash,
boolean checkTime) {
ReferenceEntry<K, V> e = null;
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
if (valueReference.isLoading()
|| (checkTime && (now - e.getWriteTime() < map.refreshNanos))) {
// refresh is a no-op if loading is pending
// if checkTime, we want to check *after* acquiring the lock if refresh still needs
// to be scheduled
return null;
}
// continue returning old value while loading
++modCount;
LoadingValueReference<K, V> loadingValueReference =
new LoadingValueReference<K, V>(valueReference);
e.setValueReference(loadingValueReference);
return loadingValueReference;
}
}
++modCount;
LoadingValueReference<K, V> loadingValueReference = new LoadingValueReference<K, V>();
e = newEntry(key, hash, first);
e.setValueReference(loadingValueReference);
table.set(index, e);
return loadingValueReference;
} finally {
unlock();
postWriteCleanup();
}
}
// reference queues, for garbage collection cleanup
/**
* Cleanup collected entries when the lock is available.
*/
void tryDrainReferenceQueues() {
if (tryLock()) {
try {
drainReferenceQueues();
} finally {
unlock();
}
}
}
/**
* Drain the key and value reference queues, cleaning up internal entries containing garbage
* collected keys or values.
*/
@GuardedBy("this")
void drainReferenceQueues() {
if (map.usesKeyReferences()) {
drainKeyReferenceQueue();
}
if (map.usesValueReferences()) {
drainValueReferenceQueue();
}
}
@GuardedBy("this")
void drainKeyReferenceQueue() {
Reference<? extends K> ref;
int i = 0;
while ((ref = keyReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref;
map.reclaimKey(entry);
if (++i == DRAIN_MAX) {
break;
}
}
}
@GuardedBy("this")
void drainValueReferenceQueue() {
Reference<? extends V> ref;
int i = 0;
while ((ref = valueReferenceQueue.poll()) != null) {
@SuppressWarnings("unchecked")
ValueReference<K, V> valueReference = (ValueReference<K, V>) ref;
map.reclaimValue(valueReference);
if (++i == DRAIN_MAX) {
break;
}
}
}
/**
* Clears all entries from the key and value reference queues.
*/
void clearReferenceQueues() {
if (map.usesKeyReferences()) {
clearKeyReferenceQueue();
}
if (map.usesValueReferences()) {
clearValueReferenceQueue();
}
}
void clearKeyReferenceQueue() {
while (keyReferenceQueue.poll() != null) {}
}
void clearValueReferenceQueue() {
while (valueReferenceQueue.poll() != null) {}
}
// recency queue, shared by expiration and eviction
/**
* Records the relative order in which this read was performed by adding {@code entry} to the
* recency queue. At write-time, or when the queue is full past the threshold, the queue will
* be drained and the entries therein processed.
*
* <p>Note: locked reads should use {@link #recordLockedRead}.
*/
void recordRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
recencyQueue.add(entry);
}
/**
* Updates the eviction metadata that {@code entry} was just read. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*
* <p>Note: this method should only be called under lock, as it directly manipulates the
* eviction queues. Unlocked reads should use {@link #recordRead}.
*/
@GuardedBy("this")
void recordLockedRead(ReferenceEntry<K, V> entry, long now) {
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
accessQueue.add(entry);
}
/**
* Updates eviction metadata that {@code entry} was just written. This currently amounts to
* adding {@code entry} to relevant eviction lists.
*/
@GuardedBy("this")
void recordWrite(ReferenceEntry<K, V> entry, int weight, long now) {
// we are already under lock, so drain the recency queue immediately
drainRecencyQueue();
totalWeight += weight;
if (map.recordsAccess()) {
entry.setAccessTime(now);
}
if (map.recordsWrite()) {
entry.setWriteTime(now);
}
accessQueue.add(entry);
writeQueue.add(entry);
}
/**
* Drains the recency queue, updating eviction metadata that the entries therein were read in
* the specified relative order. This currently amounts to adding them to relevant eviction
* lists (accounting for the fact that they could have been removed from the map since being
* added to the recency queue).
*/
@GuardedBy("this")
void drainRecencyQueue() {
ReferenceEntry<K, V> e;
while ((e = recencyQueue.poll()) != null) {
// An entry may be in the recency queue despite it being removed from
// the map . This can occur when the entry was concurrently read while a
// writer is removing it from the segment or after a clear has removed
// all of the segment's entries.
if (accessQueue.contains(e)) {
accessQueue.add(e);
}
}
}
// expiration
/**
* Cleanup expired entries when the lock is available.
*/
void tryExpireEntries(long now) {
if (tryLock()) {
try {
expireEntries(now);
} finally {
unlock();
// don't call postWriteCleanup as we're in a read
}
}
}
@GuardedBy("this")
void expireEntries(long now) {
drainRecencyQueue();
ReferenceEntry<K, V> e;
while ((e = writeQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
while ((e = accessQueue.peek()) != null && map.isExpired(e, now)) {
if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) {
throw new AssertionError();
}
}
}
// eviction
@GuardedBy("this")
void enqueueNotification(@Nullable K key, int hash, @Nullable V value, int weight,
RemovalCause cause) {
totalWeight -= weight;
if (cause.wasEvicted()) {
statsCounter.recordEviction();
}
if (map.removalNotificationQueue != DISCARDING_QUEUE) {
RemovalNotification<K, V> notification = RemovalNotification.create(key, value, cause);
map.removalNotificationQueue.offer(notification);
}
}
/**
* Performs eviction if the segment is over capacity. Avoids flushing the entire cache if the
* newest entry exceeds the maximum weight all on its own.
*
* @param newest the most recently added entry
*/
@GuardedBy("this")
void evictEntries(ReferenceEntry<K, V> newest) {
if (!map.evictsBySize()) {
return;
}
drainRecencyQueue();
// If the newest entry by itself is too heavy for the segment, don't bother evicting
// anything else, just that
if (newest.getValueReference().getWeight() > maxSegmentWeight) {
if (!removeEntry(newest, newest.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
while (totalWeight > maxSegmentWeight) {
ReferenceEntry<K, V> e = getNextEvictable();
if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) {
throw new AssertionError();
}
}
}
// TODO(fry): instead implement this with an eviction head
@GuardedBy("this")
ReferenceEntry<K, V> getNextEvictable() {
for (ReferenceEntry<K, V> e : accessQueue) {
int weight = e.getValueReference().getWeight();
if (weight > 0) {
return e;
}
}
throw new AssertionError();
}
/**
* Returns first entry of bin for given hash.
*/
ReferenceEntry<K, V> getFirst(int hash) {
// read this volatile field only once
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
return table.get(hash & (table.length() - 1));
}
// Specialized implementations of map methods
@Nullable
ReferenceEntry<K, V> getEntry(Object key, int hash) {
for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) {
if (e.getHash() != hash) {
continue;
}
K entryKey = e.getKey();
if (entryKey == null) {
tryDrainReferenceQueues();
continue;
}
if (map.keyEquivalence.equivalent(key, entryKey)) {
return e;
}
}
return null;
}
@Nullable
ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) {
ReferenceEntry<K, V> e = getEntry(key, hash);
if (e == null) {
return null;
} else if (map.isExpired(e, now)) {
tryExpireEntries(now);
return null;
}
return e;
}
/**
* Gets the value from an entry. Returns null if the entry is invalid, partially-collected,
* loading, or expired.
*/
V getLiveValue(ReferenceEntry<K, V> entry, long now) {
if (entry.getKey() == null) {
tryDrainReferenceQueues();
return null;
}
V value = entry.getValueReference().get();
if (value == null) {
tryDrainReferenceQueues();
return null;
}
if (map.isExpired(entry, now)) {
tryExpireEntries(now);
return null;
}
return value;
}
@Nullable
V get(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return null;
}
V value = e.getValueReference().get();
if (value != null) {
recordRead(e, now);
return scheduleRefresh(e, e.getKey(), hash, value, now, map.defaultLoader);
}
tryDrainReferenceQueues();
}
return null;
} finally {
postReadCleanup();
}
}
boolean containsKey(Object key, int hash) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
ReferenceEntry<K, V> e = getLiveEntry(key, hash, now);
if (e == null) {
return false;
}
return e.getValueReference().get() != null;
}
return false;
} finally {
postReadCleanup();
}
}
/**
* This method is a convenience for testing. Code should call {@link
* LocalCache#containsValue} directly.
*/
@VisibleForTesting
boolean containsValue(Object value) {
try {
if (count != 0) { // read-volatile
long now = map.ticker.read();
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int length = table.length();
for (int i = 0; i < length; ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
V entryValue = getLiveValue(e, now);
if (entryValue == null) {
continue;
}
if (map.valueEquivalence.equivalent(value, entryValue)) {
return true;
}
}
}
}
return false;
} finally {
postReadCleanup();
}
}
@Nullable
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
// Look for an existing entry.
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
// We found an existing entry.
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
++modCount;
if (valueReference.isActive()) {
enqueueNotification(key, hash, entryValue,
valueReference.getWeight(), RemovalCause.COLLECTED);
setValue(e, key, value, now);
newCount = this.count; // count remains unchanged
} else {
setValue(e, key, value, now);
newCount = this.count + 1;
}
this.count = newCount; // write-volatile
evictEntries(e);
return null;
} else if (onlyIfAbsent) {
// Mimic
// "if (!map.containsKey(key)) ...
// else return map.get(key);
recordLockedRead(e, now);
return entryValue;
} else {
// clobber existing entry, count remains unchanged
++modCount;
enqueueNotification(key, hash, entryValue,
valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, value, now);
evictEntries(e);
return entryValue;
}
}
}
// Create a new entry.
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, value, now);
table.set(index, newEntry);
newCount = this.count + 1;
this.count = newCount; // write-volatile
evictEntries(newEntry);
return null;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Expands the table if possible.
*/
@GuardedBy("this")
void expand() {
AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table;
int oldCapacity = oldTable.length();
if (oldCapacity >= MAXIMUM_CAPACITY) {
return;
}
/*
* Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move with a power of two offset.
* We eliminate unnecessary node creation by catching cases where old nodes can be reused
* because their next fields won't change. Statistically, at the default threshold, only
* about one-sixth of them need cloning when a table doubles. The nodes they replace will be
* garbage collectable as soon as they are no longer referenced by any reader thread that may
* be in the midst of traversing table right now.
*/
int newCount = count;
AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1);
threshold = newTable.length() * 3 / 4;
int newMask = newTable.length() - 1;
for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) {
// We need to guarantee that any existing reads of old Map can
// proceed. So we cannot yet null out each bin.
ReferenceEntry<K, V> head = oldTable.get(oldIndex);
if (head != null) {
ReferenceEntry<K, V> next = head.getNext();
int headIndex = head.getHash() & newMask;
// Single node on list
if (next == null) {
newTable.set(headIndex, head);
} else {
// Reuse the consecutive sequence of nodes with the same target
// index from the end of the list. tail points to the first
// entry in the reusable list.
ReferenceEntry<K, V> tail = head;
int tailIndex = headIndex;
for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
if (newIndex != tailIndex) {
// The index changed. We'll need to copy the previous entry.
tailIndex = newIndex;
tail = e;
}
}
newTable.set(tailIndex, tail);
// Clone nodes leading up to the tail.
for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) {
int newIndex = e.getHash() & newMask;
ReferenceEntry<K, V> newNext = newTable.get(newIndex);
ReferenceEntry<K, V> newFirst = copyEntry(e, newNext);
if (newFirst != null) {
newTable.set(newIndex, newFirst);
} else {
removeCollectedEntry(e);
newCount--;
}
}
}
}
}
table = newTable;
this.count = newCount;
}
boolean replace(K key, int hash, V oldValue, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(
first, e, entryKey, hash, entryValue, valueReference, RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return false;
}
if (map.valueEquivalence.equivalent(oldValue, entryValue)) {
++modCount;
enqueueNotification(key, hash, entryValue,
valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return true;
} else {
// Mimic
// "if (map.containsKey(key) && map.get(key).equals(oldValue))..."
recordLockedRead(e, now);
return false;
}
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@Nullable
V replace(K key, int hash, V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
if (entryValue == null) {
if (valueReference.isActive()) {
// If the value disappeared, this entry is partially collected.
int newCount = this.count - 1;
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(
first, e, entryKey, hash, entryValue, valueReference, RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
}
return null;
}
++modCount;
enqueueNotification(key, hash, entryValue,
valueReference.getWeight(), RemovalCause.REPLACED);
setValue(e, key, newValue, now);
evictEntries(e);
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
@Nullable
V remove(Object key, int hash) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (entryValue != null) {
cause = RemovalCause.EXPLICIT;
} else if (valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return null;
}
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(
first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return entryValue;
}
}
return null;
} finally {
unlock();
postWriteCleanup();
}
}
boolean storeLoadedValue(K key, int hash, LoadingValueReference<K, V> oldValueReference,
V newValue) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count + 1;
if (newCount > this.threshold) { // ensure capacity
expand();
newCount = this.count + 1;
}
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
// replace the old LoadingValueReference if it's live, otherwise
// perform a putIfAbsent
if (oldValueReference == valueReference
|| (entryValue == null && valueReference != UNSET)) {
++modCount;
if (oldValueReference.isActive()) {
RemovalCause cause =
(entryValue == null) ? RemovalCause.COLLECTED : RemovalCause.REPLACED;
enqueueNotification(key, hash, entryValue, oldValueReference.getWeight(), cause);
newCount--;
}
setValue(e, key, newValue, now);
this.count = newCount; // write-volatile
evictEntries(e);
return true;
}
// the loaded value was already clobbered
enqueueNotification(key, hash, newValue, 0, RemovalCause.REPLACED);
return false;
}
}
++modCount;
ReferenceEntry<K, V> newEntry = newEntry(key, hash, first);
setValue(newEntry, key, newValue, now);
table.set(index, newEntry);
this.count = newCount; // write-volatile
evictEntries(newEntry);
return true;
} finally {
unlock();
postWriteCleanup();
}
}
boolean remove(Object key, int hash, Object value) {
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> valueReference = e.getValueReference();
V entryValue = valueReference.get();
RemovalCause cause;
if (map.valueEquivalence.equivalent(value, entryValue)) {
cause = RemovalCause.EXPLICIT;
} else if (entryValue == null && valueReference.isActive()) {
cause = RemovalCause.COLLECTED;
} else {
// currently loading
return false;
}
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(
first, e, entryKey, hash, entryValue, valueReference, cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return (cause == RemovalCause.EXPLICIT);
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
void clear() {
if (count != 0) { // read-volatile
lock();
try {
long now = map.ticker.read();
preWriteCleanup(now);
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
for (int i = 0; i < table.length(); ++i) {
for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) {
// Loading references aren't actually in the map yet.
if (e.getValueReference().isActive()) {
K key = e.getKey();
V value = e.getValueReference().get();
RemovalCause cause = (key == null || value == null)
? RemovalCause.COLLECTED
: RemovalCause.EXPLICIT;
enqueueNotification(key, e.getHash(), value,
e.getValueReference().getWeight(), cause);
}
}
}
for (int i = 0; i < table.length(); ++i) {
table.set(i, null);
}
clearReferenceQueues();
writeQueue.clear();
accessQueue.clear();
readCount.set(0);
++modCount;
count = 0; // write-volatile
} finally {
unlock();
postWriteCleanup();
}
}
}
@GuardedBy("this")
@Nullable
ReferenceEntry<K, V> removeValueFromChain(ReferenceEntry<K, V> first,
ReferenceEntry<K, V> entry, @Nullable K key, int hash, V value,
ValueReference<K, V> valueReference, RemovalCause cause) {
enqueueNotification(key, hash, value, valueReference.getWeight(), cause);
writeQueue.remove(entry);
accessQueue.remove(entry);
if (valueReference.isLoading()) {
valueReference.notifyNewValue(null);
return first;
} else {
return removeEntryFromChain(first, entry);
}
}
@GuardedBy("this")
@Nullable
ReferenceEntry<K, V> removeEntryFromChain(ReferenceEntry<K, V> first,
ReferenceEntry<K, V> entry) {
int newCount = count;
ReferenceEntry<K, V> newFirst = entry.getNext();
for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) {
ReferenceEntry<K, V> next = copyEntry(e, newFirst);
if (next != null) {
newFirst = next;
} else {
removeCollectedEntry(e);
newCount--;
}
}
this.count = newCount;
return newFirst;
}
@GuardedBy("this")
void removeCollectedEntry(ReferenceEntry<K, V> entry) {
enqueueNotification(entry.getKey(), entry.getHash(), entry.getValueReference().get(),
entry.getValueReference().getWeight(), RemovalCause.COLLECTED);
writeQueue.remove(entry);
accessQueue.remove(entry);
}
/**
* Removes an entry whose key has been garbage collected.
*/
boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) {
lock();
try {
int newCount = count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, e.getKey(), hash,
e.getValueReference().get(), e.getValueReference(), RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
/**
* Removes an entry whose value has been garbage collected.
*/
boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) {
lock();
try {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, entryKey, hash,
valueReference.get(), valueReference, RemovalCause.COLLECTED);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
return false;
}
}
return false;
} finally {
unlock();
if (!isHeldByCurrentThread()) { // don't cleanup inside of put
postWriteCleanup();
}
}
}
boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) {
lock();
try {
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
K entryKey = e.getKey();
if (e.getHash() == hash && entryKey != null
&& map.keyEquivalence.equivalent(key, entryKey)) {
ValueReference<K, V> v = e.getValueReference();
if (v == valueReference) {
if (valueReference.isActive()) {
e.setValueReference(valueReference.getOldValue());
} else {
ReferenceEntry<K, V> newFirst = removeEntryFromChain(first, e);
table.set(index, newFirst);
}
return true;
}
return false;
}
}
return false;
} finally {
unlock();
postWriteCleanup();
}
}
@VisibleForTesting
@GuardedBy("this")
boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) {
int newCount = this.count - 1;
AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table;
int index = hash & (table.length() - 1);
ReferenceEntry<K, V> first = table.get(index);
for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) {
if (e == entry) {
++modCount;
ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, e.getKey(), hash,
e.getValueReference().get(), e.getValueReference(), cause);
newCount = this.count - 1;
table.set(index, newFirst);
this.count = newCount; // write-volatile
return true;
}
}
return false;
}
/**
* Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup
* is not observed after a sufficient number of reads, try cleaning up from the read thread.
*/
void postReadCleanup() {
if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) {
cleanUp();
}
}
/**
* Performs routine cleanup prior to executing a write. This should be called every time a
* write thread acquires the segment lock, immediately after acquiring the lock.
*
* <p>Post-condition: expireEntries has been run.
*/
@GuardedBy("this")
void preWriteCleanup(long now) {
runLockedCleanup(now);
}
/**
* Performs routine cleanup following a write.
*/
void postWriteCleanup() {
runUnlockedCleanup();
}
void cleanUp() {
long now = map.ticker.read();
runLockedCleanup(now);
runUnlockedCleanup();
}
void runLockedCleanup(long now) {
if (tryLock()) {
try {
drainReferenceQueues();
expireEntries(now); // calls drainRecencyQueue
readCount.set(0);
} finally {
unlock();
}
}
}
void runUnlockedCleanup() {
// locked cleanup may generate notifications we can send unlocked
if (!isHeldByCurrentThread()) {
map.processPendingNotifications();
}
}
}
static class LoadingValueReference<K, V> implements ValueReference<K, V> {
volatile ValueReference<K, V> oldValue;
// TODO(fry): rename get, then extend AbstractFuture instead of containing SettableFuture
final SettableFuture<V> futureValue = SettableFuture.create();
final Stopwatch stopwatch = Stopwatch.createUnstarted();
public LoadingValueReference() {
this(LocalCache.<K, V>unset());
}
public LoadingValueReference(ValueReference<K, V> oldValue) {
this.oldValue = oldValue;
}
@Override
public boolean isLoading() {
return true;
}
@Override
public boolean isActive() {
return oldValue.isActive();
}
@Override
public int getWeight() {
return oldValue.getWeight();
}
public boolean set(@Nullable V newValue) {
return futureValue.set(newValue);
}
public boolean setException(Throwable t) {
return futureValue.setException(t);
}
private ListenableFuture<V> fullyFailedFuture(Throwable t) {
return Futures.immediateFailedFuture(t);
}
@Override
public void notifyNewValue(@Nullable V newValue) {
if (newValue != null) {
// The pending load was clobbered by a manual write.
// Unblock all pending gets, and have them return the new value.
set(newValue);
} else {
// The pending load was removed. Delay notifications until loading completes.
oldValue = unset();
}
// TODO(fry): could also cancel loading if we had a handle on its future
}
public ListenableFuture<V> loadFuture(K key, CacheLoader<? super K, V> loader) {
try {
stopwatch.start();
V previousValue = oldValue.get();
if (previousValue == null) {
V newValue = loader.load(key);
return set(newValue) ? futureValue : Futures.immediateFuture(newValue);
}
ListenableFuture<V> newValue = loader.reload(key, previousValue);
if (newValue == null) {
return Futures.immediateFuture(null);
}
// To avoid a race, make sure the refreshed value is set into loadingValueReference
// *before* returning newValue from the cache query.
return Futures.transform(newValue, new Function<V, V>() {
@Override
public V apply(V newValue) {
LoadingValueReference.this.set(newValue);
return newValue;
}
});
} catch (Throwable t) {
ListenableFuture<V> result = setException(t) ? futureValue : fullyFailedFuture(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return result;
}
}
public long elapsedNanos() {
return stopwatch.elapsed(NANOSECONDS);
}
@Override
public V waitForValue() throws ExecutionException {
return getUninterruptibly(futureValue);
}
@Override
public V get() {
return oldValue.get();
}
public ValueReference<K, V> getOldValue() {
return oldValue;
}
@Override
public ReferenceEntry<K, V> getEntry() {
return null;
}
@Override
public ValueReference<K, V> copyFor(
ReferenceQueue<V> queue, @Nullable V value, ReferenceEntry<K, V> entry) {
return this;
}
}
// Queues
/**
* A custom queue for managing eviction order. Note that this is tightly integrated with {@code
* ReferenceEntry}, upon which it relies to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyWriteEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class WriteQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
@Override
public long getWriteTime() {
return Long.MAX_VALUE;
}
@Override
public void setWriteTime(long time) {}
ReferenceEntry<K, V> nextWrite = this;
@Override
public ReferenceEntry<K, V> getNextInWriteQueue() {
return nextWrite;
}
@Override
public void setNextInWriteQueue(ReferenceEntry<K, V> next) {
this.nextWrite = next;
}
ReferenceEntry<K, V> previousWrite = this;
@Override
public ReferenceEntry<K, V> getPreviousInWriteQueue() {
return previousWrite;
}
@Override
public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) {
this.previousWrite = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectWriteOrder(entry.getPreviousInWriteQueue(), entry.getNextInWriteQueue());
// add to tail
connectWriteOrder(head.getPreviousInWriteQueue(), entry);
connectWriteOrder(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInWriteQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue();
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
connectWriteOrder(previous, next);
nullifyWriteOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextInWriteQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInWriteQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInWriteQueue(); e != head;
e = e.getNextInWriteQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInWriteQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInWriteQueue();
nullifyWriteOrder(e);
e = next;
}
head.setNextInWriteQueue(head);
head.setPreviousInWriteQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInWriteQueue();
return (next == head) ? null : next;
}
};
}
}
/**
* A custom queue for managing access order. Note that this is tightly integrated with
* {@code ReferenceEntry}, upon which it reliese to perform its linking.
*
* <p>Note that this entire implementation makes the assumption that all elements which are in
* the map are also in this queue, and that all elements not in the queue are not in the map.
*
* <p>The benefits of creating our own queue are that (1) we can replace elements in the middle
* of the queue as part of copyWriteEntry, and (2) the contains method is highly optimized
* for the current model.
*/
static final class AccessQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> {
final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() {
@Override
public long getAccessTime() {
return Long.MAX_VALUE;
}
@Override
public void setAccessTime(long time) {}
ReferenceEntry<K, V> nextAccess = this;
@Override
public ReferenceEntry<K, V> getNextInAccessQueue() {
return nextAccess;
}
@Override
public void setNextInAccessQueue(ReferenceEntry<K, V> next) {
this.nextAccess = next;
}
ReferenceEntry<K, V> previousAccess = this;
@Override
public ReferenceEntry<K, V> getPreviousInAccessQueue() {
return previousAccess;
}
@Override
public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) {
this.previousAccess = previous;
}
};
// implements Queue
@Override
public boolean offer(ReferenceEntry<K, V> entry) {
// unlink
connectAccessOrder(entry.getPreviousInAccessQueue(), entry.getNextInAccessQueue());
// add to tail
connectAccessOrder(head.getPreviousInAccessQueue(), entry);
connectAccessOrder(entry, head);
return true;
}
@Override
public ReferenceEntry<K, V> peek() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
return (next == head) ? null : next;
}
@Override
public ReferenceEntry<K, V> poll() {
ReferenceEntry<K, V> next = head.getNextInAccessQueue();
if (next == head) {
return null;
}
remove(next);
return next;
}
@Override
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue();
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
connectAccessOrder(previous, next);
nullifyAccessOrder(e);
return next != NullEntry.INSTANCE;
}
@Override
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
ReferenceEntry<K, V> e = (ReferenceEntry) o;
return e.getNextInAccessQueue() != NullEntry.INSTANCE;
}
@Override
public boolean isEmpty() {
return head.getNextInAccessQueue() == head;
}
@Override
public int size() {
int size = 0;
for (ReferenceEntry<K, V> e = head.getNextInAccessQueue(); e != head;
e = e.getNextInAccessQueue()) {
size++;
}
return size;
}
@Override
public void clear() {
ReferenceEntry<K, V> e = head.getNextInAccessQueue();
while (e != head) {
ReferenceEntry<K, V> next = e.getNextInAccessQueue();
nullifyAccessOrder(e);
e = next;
}
head.setNextInAccessQueue(head);
head.setPreviousInAccessQueue(head);
}
@Override
public Iterator<ReferenceEntry<K, V>> iterator() {
return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) {
@Override
protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) {
ReferenceEntry<K, V> next = previous.getNextInAccessQueue();
return (next == head) ? null : next;
}
};
}
}
// Cache support
public void cleanUp() {
for (Segment<?, ?> segment : segments) {
segment.cleanUp();
}
}
// ConcurrentMap methods
@Override
public boolean isEmpty() {
/*
* Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and
* removed in one segment while checking another, in which case the table was never actually
* empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment
* modifications before recheck.) Method containsValue() uses similar constructions for
* stability checks.
*/
long sum = 0L;
Segment<K, V>[] segments = this.segments;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum += segments[i].modCount;
}
if (sum != 0L) { // recheck unless no modifications
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0) {
return false;
}
sum -= segments[i].modCount;
}
if (sum != 0L) {
return false;
}
}
return true;
}
long longSize() {
Segment<K, V>[] segments = this.segments;
long sum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += Math.max(0, segments[i].count); // see https://github.com/google/guava/issues/2108
}
return sum;
}
@Override
public int size() {
return Ints.saturatedCast(longSize());
}
@Override
@Nullable
public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).get(key, hash);
}
@Nullable
public V getIfPresent(Object key) {
int hash = hash(checkNotNull(key));
V value = segmentFor(hash).get(key, hash);
if (value == null) {
globalStatsCounter.recordMisses(1);
} else {
globalStatsCounter.recordHits(1);
}
return value;
}
// Only becomes available in Java 8 when it's on the interface.
// @Override
@Nullable
public V getOrDefault(@Nullable Object key, @Nullable V defaultValue) {
V result = get(key);
return (result != null) ? result : defaultValue;
}
V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException {
int hash = hash(checkNotNull(key));
return segmentFor(hash).get(key, hash, loader);
}
V getOrLoad(K key) throws ExecutionException {
return get(key, defaultLoader);
}
ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
int hits = 0;
int misses = 0;
Map<K, V> result = Maps.newLinkedHashMap();
for (Object key : keys) {
V value = get(key);
if (value == null) {
misses++;
} else {
// TODO(fry): store entry key instead of query key
@SuppressWarnings("unchecked")
K castKey = (K) key;
result.put(castKey, value);
hits++;
}
}
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
return ImmutableMap.copyOf(result);
}
ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
int hits = 0;
int misses = 0;
Map<K, V> result = Maps.newLinkedHashMap();
Set<K> keysToLoad = Sets.newLinkedHashSet();
for (K key : keys) {
V value = get(key);
if (!result.containsKey(key)) {
result.put(key, value);
if (value == null) {
misses++;
keysToLoad.add(key);
} else {
hits++;
}
}
}
try {
if (!keysToLoad.isEmpty()) {
try {
Map<K, V> newEntries = loadAll(keysToLoad, defaultLoader);
for (K key : keysToLoad) {
V value = newEntries.get(key);
if (value == null) {
throw new InvalidCacheLoadException("loadAll failed to return a value for " + key);
}
result.put(key, value);
}
} catch (UnsupportedLoadingOperationException e) {
// loadAll not implemented, fallback to load
for (K key : keysToLoad) {
misses--; // get will count this miss
result.put(key, get(key, defaultLoader));
}
}
}
return ImmutableMap.copyOf(result);
} finally {
globalStatsCounter.recordHits(hits);
globalStatsCounter.recordMisses(misses);
}
}
/**
* Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't
* implement {@code loadAll}.
*/
@Nullable
Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader)
throws ExecutionException {
checkNotNull(loader);
checkNotNull(keys);
Stopwatch stopwatch = Stopwatch.createStarted();
Map<K, V> result;
boolean success = false;
try {
@SuppressWarnings("unchecked") // safe since all keys extend K
Map<K, V> map = (Map<K, V>) loader.loadAll(keys);
result = map;
success = true;
} catch (UnsupportedLoadingOperationException e) {
success = true;
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ExecutionException(e);
} catch (RuntimeException e) {
throw new UncheckedExecutionException(e);
} catch (Exception e) {
throw new ExecutionException(e);
} catch (Error e) {
throw new ExecutionError(e);
} finally {
if (!success) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
}
}
if (result == null) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null map from loadAll");
}
stopwatch.stop();
// TODO(fry): batch by segment
boolean nullsPresent = false;
for (Map.Entry<K, V> entry : result.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
if (key == null || value == null) {
// delay failure until non-null entries are stored
nullsPresent = true;
} else {
put(key, value);
}
}
if (nullsPresent) {
globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS));
throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll");
}
// TODO(fry): record count of loaded entries
globalStatsCounter.recordLoadSuccess(stopwatch.elapsed(NANOSECONDS));
return result;
}
/**
* Returns the internal entry for the specified key. The entry may be loading, expired, or
* partially collected.
*/
ReferenceEntry<K, V> getEntry(@Nullable Object key) {
// does not impact recency ordering
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).getEntry(key, hash);
}
void refresh(K key) {
int hash = hash(checkNotNull(key));
segmentFor(hash).refresh(key, hash, defaultLoader, false);
}
@Override
public boolean containsKey(@Nullable Object key) {
// does not impact recency ordering
if (key == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).containsKey(key, hash);
}
@Override
public boolean containsValue(@Nullable Object value) {
// does not impact recency ordering
if (value == null) {
return false;
}
// This implementation is patterned after ConcurrentHashMap, but without the locking. The only
// way for it to return a false negative would be for the target value to jump around in the map
// such that none of the subsequent iterations observed it, despite the fact that at every point
// in time it was present somewhere int the map. This becomes increasingly unlikely as
// CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible.
long now = ticker.read();
final Segment<K, V>[] segments = this.segments;
long last = -1L;
for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) {
long sum = 0L;
for (Segment<K, V> segment : segments) {
// ensure visibility of most recent completed write
int unused = segment.count; // read-volatile
AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table;
for (int j = 0; j < table.length(); j++) {
for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) {
V v = segment.getLiveValue(e, now);
if (v != null && valueEquivalence.equivalent(value, v)) {
return true;
}
}
}
sum += segment.modCount;
}
if (sum == last) {
break;
}
last = sum;
}
return false;
}
@Override
public V put(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, false);
}
@Override
public V putIfAbsent(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).put(key, hash, value, true);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Entry<? extends K, ? extends V> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public V remove(@Nullable Object key) {
if (key == null) {
return null;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash);
}
@Override
public boolean remove(@Nullable Object key, @Nullable Object value) {
if (key == null || value == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).remove(key, hash, value);
}
@Override
public boolean replace(K key, @Nullable V oldValue, V newValue) {
checkNotNull(key);
checkNotNull(newValue);
if (oldValue == null) {
return false;
}
int hash = hash(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
@Override
public V replace(K key, V value) {
checkNotNull(key);
checkNotNull(value);
int hash = hash(key);
return segmentFor(hash).replace(key, hash, value);
}
@Override
public void clear() {
for (Segment<K, V> segment : segments) {
segment.clear();
}
}
void invalidateAll(Iterable<?> keys) {
// TODO(fry): batch by segment
for (Object key : keys) {
remove(key);
}
}
Set<K> keySet;
@Override
public Set<K> keySet() {
// does not impact recency ordering
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet(this));
}
Collection<V> values;
@Override
public Collection<V> values() {
// does not impact recency ordering
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values(this));
}
Set<Entry<K, V>> entrySet;
@Override
@GwtIncompatible // Not supported.
public Set<Entry<K, V>> entrySet() {
// does not impact recency ordering
Set<Entry<K, V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet(this));
}
// Iterator Support
abstract class HashIterator<T> implements Iterator<T> {
int nextSegmentIndex;
int nextTableIndex;
Segment<K, V> currentSegment;
AtomicReferenceArray<ReferenceEntry<K, V>> currentTable;
ReferenceEntry<K, V> nextEntry;
WriteThroughEntry nextExternal;
WriteThroughEntry lastReturned;
HashIterator() {
nextSegmentIndex = segments.length - 1;
nextTableIndex = -1;
advance();
}
@Override
public abstract T next();
final void advance() {
nextExternal = null;
if (nextInChain()) {
return;
}
if (nextInTable()) {
return;
}
while (nextSegmentIndex >= 0) {
currentSegment = segments[nextSegmentIndex--];
if (currentSegment.count != 0) {
currentTable = currentSegment.table;
nextTableIndex = currentTable.length() - 1;
if (nextInTable()) {
return;
}
}
}
}
/**
* Finds the next entry in the current chain. Returns true if an entry was found.
*/
boolean nextInChain() {
if (nextEntry != null) {
for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) {
if (advanceTo(nextEntry)) {
return true;
}
}
}
return false;
}
/**
* Finds the next entry in the current table. Returns true if an entry was found.
*/
boolean nextInTable() {
while (nextTableIndex >= 0) {
if ((nextEntry = currentTable.get(nextTableIndex--)) != null) {
if (advanceTo(nextEntry) || nextInChain()) {
return true;
}
}
}
return false;
}
/**
* Advances to the given entry. Returns true if the entry was valid, false if it should be
* skipped.
*/
boolean advanceTo(ReferenceEntry<K, V> entry) {
try {
long now = ticker.read();
K key = entry.getKey();
V value = getLiveValue(entry, now);
if (value != null) {
nextExternal = new WriteThroughEntry(key, value);
return true;
} else {
// Skip stale entry.
return false;
}
} finally {
currentSegment.postReadCleanup();
}
}
@Override
public boolean hasNext() {
return nextExternal != null;
}
WriteThroughEntry nextEntry() {
if (nextExternal == null) {
throw new NoSuchElementException();
}
lastReturned = nextExternal;
advance();
return lastReturned;
}
@Override
public void remove() {
checkState(lastReturned != null);
LocalCache.this.remove(lastReturned.getKey());
lastReturned = null;
}
}
final class KeyIterator extends HashIterator<K> {
@Override
public K next() {
return nextEntry().getKey();
}
}
final class ValueIterator extends HashIterator<V> {
@Override
public V next() {
return nextEntry().getValue();
}
}
/**
* Custom Entry class used by EntryIterator.next(), that relays setValue changes to the
* underlying map.
*/
final class WriteThroughEntry implements Entry<K, V> {
final K key; // non-null
V value; // non-null
WriteThroughEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public boolean equals(@Nullable Object object) {
// Cannot use key and value equivalence
if (object instanceof Entry) {
Entry<?, ?> that = (Entry<?, ?>) object;
return key.equals(that.getKey()) && value.equals(that.getValue());
}
return false;
}
@Override
public int hashCode() {
// Cannot use key and value equivalence
return key.hashCode() ^ value.hashCode();
}
@Override
public V setValue(V newValue) {
throw new UnsupportedOperationException();
}
/**
* Returns a string representation of the form <code>{key}={value}</code>.
*/
@Override public String toString() {
return getKey() + "=" + getValue();
}
}
final class EntryIterator extends HashIterator<Entry<K, V>> {
@Override
public Entry<K, V> next() {
return nextEntry();
}
}
abstract class AbstractCacheSet<T> extends AbstractSet<T> {
@Weak final ConcurrentMap<?, ?> map;
AbstractCacheSet(ConcurrentMap<?, ?> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public void clear() {
map.clear();
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
private static <E> ArrayList<E> toArrayList(Collection<E> c) {
// Avoid calling ArrayList(Collection), which may call back into toArray.
ArrayList<E> result = new ArrayList<E>(c.size());
Iterators.addAll(result, c.iterator());
return result;
}
@WeakOuter
final class KeySet extends AbstractCacheSet<K> {
KeySet(ConcurrentMap<?, ?> map) {
super(map);
}
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public boolean contains(Object o) {
return map.containsKey(o);
}
@Override
public boolean remove(Object o) {
return map.remove(o) != null;
}
}
@WeakOuter
final class Values extends AbstractCollection<V> {
private final ConcurrentMap<?, ?> map;
Values(ConcurrentMap<?, ?> map) {
this.map = map;
}
@Override public int size() {
return map.size();
}
@Override public boolean isEmpty() {
return map.isEmpty();
}
@Override public void clear() {
map.clear();
}
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public boolean contains(Object o) {
return map.containsValue(o);
}
// super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android.
// https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508
@Override
public Object[] toArray() {
return toArrayList(this).toArray();
}
@Override
public <E> E[] toArray(E[] a) {
return toArrayList(this).toArray(a);
}
}
@WeakOuter
final class EntrySet extends AbstractCacheSet<Entry<K, V>> {
EntrySet(ConcurrentMap<?, ?> map) {
super(map);
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
if (key == null) {
return false;
}
V v = LocalCache.this.get(key);
return v != null && valueEquivalence.equivalent(e.getValue(), v);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry<?, ?> e = (Entry<?, ?>) o;
Object key = e.getKey();
return key != null && LocalCache.this.remove(key, e.getValue());
}
}
// Serialization Support
/**
* Serializes the configuration of a LocalCache, reconsitituting it as a Cache using
* CacheBuilder upon deserialization. An instance of this class is fit for use by the writeReplace
* of LocalManualCache.
*
* Unfortunately, readResolve() doesn't get called when a circular dependency is present, so the
* proxy must be able to behave as the cache itself.
*/
static class ManualSerializationProxy<K, V>
extends ForwardingCache<K, V> implements Serializable {
private static final long serialVersionUID = 1;
final Strength keyStrength;
final Strength valueStrength;
final Equivalence<Object> keyEquivalence;
final Equivalence<Object> valueEquivalence;
final long expireAfterWriteNanos;
final long expireAfterAccessNanos;
final long maxWeight;
final Weigher<K, V> weigher;
final int concurrencyLevel;
final RemovalListener<? super K, ? super V> removalListener;
final Ticker ticker;
final CacheLoader<? super K, V> loader;
transient Cache<K, V> delegate;
ManualSerializationProxy(LocalCache<K, V> cache) {
this(
cache.keyStrength,
cache.valueStrength,
cache.keyEquivalence,
cache.valueEquivalence,
cache.expireAfterWriteNanos,
cache.expireAfterAccessNanos,
cache.maxWeight,
cache.weigher,
cache.concurrencyLevel,
cache.removalListener,
cache.ticker,
cache.defaultLoader);
}
private ManualSerializationProxy(
Strength keyStrength, Strength valueStrength,
Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
long expireAfterWriteNanos, long expireAfterAccessNanos, long maxWeight,
Weigher<K, V> weigher, int concurrencyLevel,
RemovalListener<? super K, ? super V> removalListener,
Ticker ticker, CacheLoader<? super K, V> loader) {
this.keyStrength = keyStrength;
this.valueStrength = valueStrength;
this.keyEquivalence = keyEquivalence;
this.valueEquivalence = valueEquivalence;
this.expireAfterWriteNanos = expireAfterWriteNanos;
this.expireAfterAccessNanos = expireAfterAccessNanos;
this.maxWeight = maxWeight;
this.weigher = weigher;
this.concurrencyLevel = concurrencyLevel;
this.removalListener = removalListener;
this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER)
? null : ticker;
this.loader = loader;
}
CacheBuilder<K, V> recreateCacheBuilder() {
CacheBuilder<K, V> builder = CacheBuilder.newBuilder()
.setKeyStrength(keyStrength)
.setValueStrength(valueStrength)
.keyEquivalence(keyEquivalence)
.valueEquivalence(valueEquivalence)
.concurrencyLevel(concurrencyLevel)
.removalListener(removalListener);
builder.strictParsing = false;
if (expireAfterWriteNanos > 0) {
builder.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS);
}
if (expireAfterAccessNanos > 0) {
builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS);
}
if (weigher != OneWeigher.INSTANCE) {
builder.weigher(weigher);
if (maxWeight != UNSET_INT) {
builder.maximumWeight(maxWeight);
}
} else {
if (maxWeight != UNSET_INT) {
builder.maximumSize(maxWeight);
}
}
if (ticker != null) {
builder.ticker(ticker);
}
return builder;
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.delegate = builder.build();
}
private Object readResolve() {
return delegate;
}
@Override
protected Cache<K, V> delegate() {
return delegate;
}
}
/**
* Serializes the configuration of a LocalCache, reconsitituting it as an LoadingCache using
* CacheBuilder upon deserialization. An instance of this class is fit for use by the writeReplace
* of LocalLoadingCache.
*
* Unfortunately, readResolve() doesn't get called when a circular dependency is present, so the
* proxy must be able to behave as the cache itself.
*/
static final class LoadingSerializationProxy<K, V>
extends ManualSerializationProxy<K, V> implements LoadingCache<K, V>, Serializable {
private static final long serialVersionUID = 1;
transient LoadingCache<K, V> autoDelegate;
LoadingSerializationProxy(LocalCache<K, V> cache) {
super(cache);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
CacheBuilder<K, V> builder = recreateCacheBuilder();
this.autoDelegate = builder.build(loader);
}
@Override
public V get(K key) throws ExecutionException {
return autoDelegate.get(key);
}
@Override
public V getUnchecked(K key) {
return autoDelegate.getUnchecked(key);
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return autoDelegate.getAll(keys);
}
@Override
public final V apply(K key) {
return autoDelegate.apply(key);
}
@Override
public void refresh(K key) {
autoDelegate.refresh(key);
}
private Object readResolve() {
return autoDelegate;
}
}
static class LocalManualCache<K, V> implements Cache<K, V>, Serializable {
final LocalCache<K, V> localCache;
LocalManualCache(CacheBuilder<? super K, ? super V> builder) {
this(new LocalCache<K, V>(builder, null));
}
private LocalManualCache(LocalCache<K, V> localCache) {
this.localCache = localCache;
}
// Cache methods
@Override
@Nullable
public V getIfPresent(Object key) {
return localCache.getIfPresent(key);
}
@Override
public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException {
checkNotNull(valueLoader);
return localCache.get(key, new CacheLoader<Object, V>() {
@Override
public V load(Object key) throws Exception {
return valueLoader.call();
}
});
}
@Override
public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) {
return localCache.getAllPresent(keys);
}
@Override
public void put(K key, V value) {
localCache.put(key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
localCache.putAll(m);
}
@Override
public void invalidate(Object key) {
checkNotNull(key);
localCache.remove(key);
}
@Override
public void invalidateAll(Iterable<?> keys) {
localCache.invalidateAll(keys);
}
@Override
public void invalidateAll() {
localCache.clear();
}
@Override
public long size() {
return localCache.longSize();
}
@Override
public ConcurrentMap<K, V> asMap() {
return localCache;
}
@Override
public CacheStats stats() {
SimpleStatsCounter aggregator = new SimpleStatsCounter();
aggregator.incrementBy(localCache.globalStatsCounter);
for (Segment<K, V> segment : localCache.segments) {
aggregator.incrementBy(segment.statsCounter);
}
return aggregator.snapshot();
}
@Override
public void cleanUp() {
localCache.cleanUp();
}
// Serialization Support
private static final long serialVersionUID = 1;
Object writeReplace() {
return new ManualSerializationProxy<K, V>(localCache);
}
}
static class LocalLoadingCache<K, V>
extends LocalManualCache<K, V> implements LoadingCache<K, V> {
LocalLoadingCache(CacheBuilder<? super K, ? super V> builder,
CacheLoader<? super K, V> loader) {
super(new LocalCache<K, V>(builder, checkNotNull(loader)));
}
// LoadingCache methods
@Override
public V get(K key) throws ExecutionException {
return localCache.getOrLoad(key);
}
@Override
public V getUnchecked(K key) {
try {
return get(key);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
@Override
public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
return localCache.getAll(keys);
}
@Override
public void refresh(K key) {
localCache.refresh(key);
}
@Override
public final V apply(K key) {
return getUnchecked(key);
}
// Serialization Support
private static final long serialVersionUID = 1;
@Override
Object writeReplace() {
return new LoadingSerializationProxy<K, V>(localCache);
}
}
}
| 29.793873 | 100 | 0.621924 |
48c01cf29573ebf67b6e2662231e4e5498f3479c | 1,580 | package com.tryadhawk.airtable;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tryadhawk.airtable.internal.http.AirtableHttpClient;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
public class AirtableTest {
private AirtableHttpClient httpClient = mock(AirtableHttpClient.class);
private ObjectMapper objectMapper = mock(ObjectMapper.class);
/**
* Should create a default ObjectMapper and AirtableHttpClient if none are set in the builder
*/
@Test
public void builderDefaultsTest() {
Configuration config = Configuration.builder().apiKey("abc123").endpointUrl("https://localhost").build();
Airtable airtable = Airtable.builder().config(config).build();
assertNotNull(airtable);
assertNotNull(airtable.buildAsyncTable("base", "table", String.class));
assertNotNull(airtable.buildSyncTable("base", "table", String.class));
}
/**
* Should create an instance and allow async and sync clients to be created
*/
@Test
public void builderTest() {
Configuration config = Configuration.builder().apiKey("abc123").endpointUrl("https://localhost").build();
Airtable airtable = Airtable.builder().airtableHttpClient(httpClient).objectMapper(objectMapper)
.config(config).build();
assertNotNull(airtable);
assertNotNull(airtable.buildAsyncTable("base", "table", String.class));
assertNotNull(airtable.buildSyncTable("base", "table", String.class));
}
}
| 37.619048 | 113 | 0.711392 |
662c482fba7960db9559db36b07a96fa78cd6df1 | 2,690 | /*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws.wsdl.document.jaxws;
import javax.xml.namespace.QName;
/**
* @author Vivek Pandey
*
* class representing jaxws:parameter
*
*/
public class Parameter {
private String part;
private QName element;
private String name;
private String messageName;
/**
* @param part
* @param element
* @param name
*/
public Parameter(String msgName, String part, QName element, String name) {
this.part = part;
this.element = element;
this.name = name;
this.messageName = msgName;
}
public String getMessageName() {
return messageName;
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
/**
* @return Returns the element.
*/
public QName getElement() {
return element;
}
/**
* @param element The element to set.
*/
public void setElement(QName element) {
this.element = element;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the part.
*/
public String getPart() {
return part;
}
/**
* @param part The part to set.
*/
public void setPart(String part) {
this.part = part;
}
}
| 25.865385 | 79 | 0.649814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.