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 |
|---|---|---|---|---|---|
fa9e941d39b5f744ce7e7fb68658b8c15c77f266 | 2,584 | package servlet;
import dao.Impl.UserDaoImpl;
import domain.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
/**
* @author lbf
* @date 2020/8/29 14:07
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置request编码
req.setCharacterEncoding("utf-8");
//获取参数
String username = req.getParameter("username");
String password = req.getParameter("password");
String checkCode = req.getParameter("checkCode");
//先获取预先生成好的验证码
HttpSession session = req.getSession();
String check_session = (String) session.getAttribute("checkCode_session");
//删除session中的验证码
session.removeAttribute("checkCode_session");
//先判断验证码是否正确
if (check_session != null && check_session.equalsIgnoreCase(checkCode)){
//判断用户名和密码是否正确
User user = new User();
UserDaoImpl dao = new UserDaoImpl();
user.setUsrname(username);
user.setPassword(password);
try {
dao.login(user);
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (dao.login(user) != null){
// if ("zhangsan".equals(username) && "123".equals(password)){
//登陆成功
//将用户的信息存储到session里面
session.setAttribute("user",username);
//重定向到session里面
resp.sendRedirect(req.getContextPath() + "/success.jsp");
}else {
//登陆失败
req.setAttribute("login_error","用户名或者密码错误");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
} catch (SQLException e) {
e.printStackTrace();
}
}else {
//验证码不一致
req.setAttribute("cc_error","验证码错误");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
}
| 33.128205 | 114 | 0.594427 |
4a213e10d7d9efd93527dc216c5d4cac40bf2d01 | 1,914 | package com.yqwl.dao;
import com.yqwl.pojo.NewsTrends;
import java.util.List;
public interface NewsTrendsMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int insert(NewsTrends record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int insertSelective(NewsTrends record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
NewsTrends selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(NewsTrends record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int updateByPrimaryKeyWithBLOBs(NewsTrends record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_news_trends
*
* @mbggenerated
*/
int updateByPrimaryKey(NewsTrends record);
List<NewsTrends> showListNewsTrend();
Integer updateStatusById(Long newsId);
Integer updateFirstShowById(Long newsId);
List<NewsTrends> homePage();
List<NewsTrends> listByColumnProgramaId(int i);
List<NewsTrends> showFrontNewsTrend();
NewsTrends showNewsTrendById(Long id);
} | 24.857143 | 66 | 0.677638 |
c87084be61ae54e3cfaee8d667f3157bc192bf27 | 2,706 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
/**
*
* @author sanker
*/
public class EasySecure {
public static byte[] makeBytes(String s) {
try {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(byteOut);
dataOut.writeUTF(s);
return byteOut.toByteArray();
}
catch (IOException e) {
return null;
}
}
public static String convertBytetoStringofDigits(byte[] b)
{
BigInteger big = new BigInteger(1,b);
return big.toString(16);
}
public static byte[] convertStringofDigitstoByte(String s)
{
BigInteger big = new BigInteger(s,16);
return big.toByteArray();
}
public static String BytestoString(byte[] b) {
String s=null;
try {
ByteArrayInputStream byteIn = new ByteArrayInputStream(b);
DataInputStream dataIn = new DataInputStream(byteIn);
s=dataIn.readUTF();
}
catch (IOException e) {
}catch(Exception ex)
{
}
return s;
}
public static String encodeString(String s,String Algorithm)
{
String enc=null;
try{
MessageDigest md = MessageDigest.getInstance(Algorithm);
byte[] b=s.getBytes();
md.reset();
//md.update(b);
//encoding byte array
byte[] mdbytes = md.digest(b);
/*
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
buffer.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}*/
enc= EasySecure.convertBytetoStringofDigits(mdbytes);
//Hex.encodeHex(resultByte)
//enc=new String()
}catch(NoSuchAlgorithmException ex)
{
enc=null;
}catch(Exception ex)
{
enc=null;
}
return enc;
}
}
| 21.307087 | 92 | 0.556911 |
0dfd6ab5952790019a0c22be04adf7e14917191c | 18,204 | package com.egoveris.edt.web.pl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelArray;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import com.egoveris.edt.base.exception.NovedadException;
import com.egoveris.edt.base.model.eu.AplicacionDTO;
import com.egoveris.edt.base.model.eu.CategoriaDTO;
import com.egoveris.edt.base.model.eu.novedad.NovedadDTO;
import com.egoveris.edt.base.service.IAplicacionService;
import com.egoveris.edt.base.service.ICategoriaService;
import com.egoveris.edt.base.service.novedad.INovedadHelper;
import com.egoveris.edt.base.service.novedad.INovedadHistService;
import com.egoveris.edt.base.service.novedad.INovedadService;
import com.egoveris.edt.web.admin.pl.renderers.ApLayOut;
import com.egoveris.edt.web.common.BaseComposer;
import com.egoveris.shared.date.DateUtil;
import com.egoveris.sharedsecurity.base.model.ConstantesSesion;
public class NuevaNovedadComposer extends BaseComposer {
/**
*
*/
private static final long serialVersionUID = -6250261717036565696L;
private static Logger logger = LoggerFactory.getLogger(NuevaNovedadComposer.class);
private Textbox nombreTextbox;
private Datebox fechaInicioDatebox;
private Datebox fechaFinDatebox;
private List<NovedadDTO> novedades;
@Autowired
private List<ApLayOut> aplicacionesLayout;
private List<CategoriaDTO> categorias;
private List<AplicacionDTO> aplicaciones;
@Autowired
private ApLayOut aplicacionLayOut;
@Autowired
private Combobox cbx_categoria;
@Autowired
private Listbox cbx_aplicacion;
private NovedadDTO novedad;
private CategoriaDTO categoria;
private String estado;
@Autowired
private ICategoriaService categoriaService;
@Autowired
private INovedadService novedadService;
@Autowired
private IAplicacionService aplicacionService;
private INovedadHelper novedadHelper;
String usuario;
private String[] listaEstados;
private Boolean esAlta;
private AnnotateDataBinder binder;
@Autowired
private Window win_novedadNueva;
@Autowired
private Set<Listitem> selectedItems = new HashSet<>();
private INovedadHistService novedadHistService;
private Integer operacion;
@Override
@SuppressWarnings("unchecked")
public void doAfterCompose(Component c) throws Exception {
super.doAfterCompose(c);
binder = new AnnotateDataBinder(c);
this.categoriaService = (ICategoriaService) SpringUtil.getBean("categoriaService");
this.novedadService = (INovedadService) SpringUtil.getBean("novedadService");
this.aplicacionService = (IAplicacionService) SpringUtil.getBean("aplicacionesService");
novedadHistService = (INovedadHistService) SpringUtil.getBean("novedadHistService");
this.novedadHelper = (INovedadHelper) SpringUtil.getBean("novedadHelper");
this.novedades = (List<NovedadDTO>) Executions.getCurrent().getArg().get("novedades");
this.novedad = (NovedadDTO) Executions.getCurrent().getArg().get("novedad");
this.esAlta = (Boolean) Executions.getCurrent().getArg().get("alta");
loadComboModulo();
loadComboCategoria();
if (this.novedad != null) {
this.nombreTextbox.setValue(this.novedad.getNovedad());
this.fechaInicioDatebox.setValue(this.novedad.getFechaInicio());
this.fechaFinDatebox.setValue(this.novedad.getFechaFin());
this.novedades.remove(this.novedad);
categoria = this.novedad.getCategoria();
for (AplicacionDTO apiNovedad : novedad.getAplicaciones()) {
for (Iterator it = this.aplicacionesLayout.iterator(); it.hasNext();) {
ApLayOut ap = ((ApLayOut) it.next());
if (apiNovedad.getIdAplicacion() == ap.getIdAplicacion()) {
ap.setEsSeleccionado(true);
}
}
}
this.binder.loadComponent(cbx_aplicacion);
}
c.addEventListener(Events.ON_CHANGE, new NuevaNovedadComposerListener(this));
}
private void setearListaSeleccionados() {
for (Iterator it = this.cbx_aplicacion.getItems().iterator(); it.hasNext();) {
Listitem l = ((Listitem) it.next());
for (AplicacionDTO a : this.novedad.getAplicaciones()) {
if (l.getValue().equals(a.getIdAplicacion())) {
l.setSelected(true);
selectedItems.add(l);
}
}
}
binder.loadComponent(this.cbx_aplicacion);
}
public void onClick$refresh() throws InterruptedException {
setearListaSeleccionados();
}
public void onClick$guardar() throws InterruptedException {
try {
usuario = (String) Executions.getCurrent().getSession()
.getAttribute(ConstantesSesion.SESSION_USERNAME);
validarDatos();
NovedadDTO savedNovedad = this.novedadService.save(this.novedad);
this.novedades.add(savedNovedad);
HashMap<String, Object> hm = new HashMap<>();
hm.put("novedad", savedNovedad);
if (esAlta) {
hm.put("operacion", 0);
Messagebox.show(
Labels.getLabel("eu.configuracionNovedades.crearNovedad.alta",
new String[] { this.novedad.getNovedad() }),
Labels.getLabel("eu.general.information"), Messagebox.OK, Messagebox.INFORMATION);
} else {
hm.put("operacion", 1);
Messagebox.show(
Labels.getLabel("eu.configuracionNovedades.crearNovedad.modifica",
new String[] { this.novedad.getNovedad() }),
Labels.getLabel("eu.general.information"), Messagebox.OK, Messagebox.INFORMATION);
}
Events.sendEvent(Events.ON_CHANGE, this.self, hm);
novedadHelper.cachearListaNovedades();
this.closeAndNotify();
} catch (NovedadException e) {
logger.error(Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.validacion"), e);
Messagebox.show(e.getMessage(), "Error", Messagebox.OK, Messagebox.ERROR);
}
}
/**
* Cierra la ventana y notifica a la ventana padre para el refreco de la lista
*/
private void closeAndNotify() {
HashMap<String, Object> hm = new HashMap<>();
hm.put("novedades", this.novedades);
Events.sendEvent(Events.ON_NOTIFY, this.self.getParent(), hm);
this.self.detach();
}
private void validarDatos() throws NovedadException {
if (StringUtils.isEmpty(this.nombreTextbox.getValue())) {
throw new WrongValueException(nombreTextbox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.IngresarMotivo"));
}
if (this.cbx_categoria.getSelectedItem() == null) {
throw new WrongValueException(cbx_categoria,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.Categoria"));
}
Integer categoriaId = (Integer) this.cbx_categoria.getSelectedItem().getValue();
if (categoriaId == null) {
throw new WrongValueException(cbx_categoria,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.Categoria"));
} else {
categoria = categoriaService.getById(categoriaId);
}
Set<Listitem> selectItems = this.cbx_aplicacion.getSelectedItems();
if (selectItems.isEmpty()) {
throw new WrongValueException(cbx_aplicacion,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.Modulo"));
}
for (Listitem item : selectItems) {
try {
aplicacionesLayout.get((Integer) item.getIndex());
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new WrongValueException(cbx_aplicacion,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.Modulo"));
}
}
if (this.cbx_aplicacion.getSelectedItems() == null) {
throw new WrongValueException(cbx_aplicacion,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.Modulo"));
}
if (this.fechaInicioDatebox.getValue() == null) {
throw new WrongValueException(fechaInicioDatebox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.IngresarFecha"));
}
if (this.fechaFinDatebox.getValue() == null) {
throw new WrongValueException(fechaFinDatebox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.IngresarFin"));
}
if (this.fechaFinDatebox.getValue().compareTo(this.fechaInicioDatebox.getValue()) < 0) {
throw new WrongValueException(fechaFinDatebox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.FechasErrorInicio"));
}
if (DateUtil.getZeroTimeDate(this.fechaInicioDatebox.getValue())
.compareTo(DateUtil.getZeroTimeDate(new Date())) < 0) {
throw new WrongValueException(fechaInicioDatebox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.FechasErrorActual"));
}
if (DateUtil.getZeroTimeDate(this.fechaFinDatebox.getValue())
.compareTo(DateUtil.getZeroTimeDate(new Date())) < 0) {
throw new WrongValueException(fechaFinDatebox,
Labels.getLabel("eu.configuracionNovedades.crearNovedad.error.FechasErrorActual"));
}
this.armarNovedad();
}
private void armarNovedad() {
if (this.novedad == null) {
this.novedad = new NovedadDTO();
}
this.novedad.setFechaInicio(this.fechaInicioDatebox.getValue());
this.novedad.setFechaFin(this.fechaFinDatebox.getValue());
this.novedad.setNovedad(this.nombreTextbox.getValue());
this.novedad.setCategoria(categorias.get(this.cbx_categoria.getSelectedIndex()));
Set<AplicacionDTO> nuevaAplicaciones = new HashSet<>();
Set<Listitem> selectItems = this.cbx_aplicacion.getSelectedItems();
for (Listitem item : selectItems) {
ApLayOut aL = aplicacionesLayout.get((Integer) item.getIndex());
AplicacionDTO ap = aplicacionService.getAplicacionPorId(aL.getIdAplicacion());
nuevaAplicaciones.add(ap);
}
this.novedad.setAplicaciones(nuevaAplicaciones);
this.novedad.setUsuario(usuario);
boolean desde = this.novedad.getFechaInicio().before(new Date());
boolean hasta = this.novedad.getFechaFin().after(new Date());
if (desde && hasta) {
this.novedad.setEstado("ACTIVO");
} else {
this.novedad.setEstado("PENDIENTE");
}
}
public void onClick$cancelar() throws InterruptedException {
if (this.novedad != null) {
this.novedades.add(this.novedad);
}
Messagebox.show(Labels.getLabel("eu.nuevoFeriadoComposer.msgBox.datosSePerderan"),
Labels.getLabel("eu.adminSade.usuario.generales.confirmacion"),
Messagebox.YES | Messagebox.NO, Messagebox.QUESTION,
new org.zkoss.zk.ui.event.EventListener() {
@Override
public void onEvent(Event evt) throws InterruptedException {
switch (((Integer) evt.getData()).intValue()) {
case Messagebox.YES:
cerrar();
break;
case Messagebox.NO:
break;
}
}
});
}
private boolean validaModificacion() {
if (this.novedad == null) {
return false;
}
Integer categoriaIdOriginal = this.novedad.getCategoria().getId();
if (this.cbx_categoria.getSelectedItem() == null) {
return false;
} else {
Integer categoriaIdSelect = (Integer) this.cbx_categoria.getSelectedItem().getValue();
if (!categoriaIdSelect.equals(categoriaIdOriginal)) {
return true;
}
}
Set<Listitem> selectItems = this.cbx_aplicacion.getSelectedItems();
Set<AplicacionDTO> originales = this.novedad.getAplicaciones();
// Esta validacion se realiza para saber si se modifico o no la lista de
// aplicaciones
for (Listitem item : selectItems) {
boolean existe = false;
for (AplicacionDTO app : originales) {
Integer appSeleccionada = (Integer) item.getValue();
if (appSeleccionada.equals(app.getIdAplicacion())) {
existe = true;
}
}
if (!existe) {
return existe;
}
}
if (this.fechaInicioDatebox == null || this.fechaFinDatebox == null) {
return true;
}
try {
if (StringUtils.isEmpty(this.nombreTextbox.getValue())) {
return true;
} else {
if (!this.nombreTextbox.getValue().equals(this.novedad.getNovedad())) {
return true;
}
}
if (this.fechaInicioDatebox.getValue() == null
|| !this.fechaInicioDatebox.getValue().equals(this.novedad.getFechaInicio())) {
return true;
}
if (this.fechaFinDatebox.getValue() == null
|| !this.fechaFinDatebox.getValue().equals(this.novedad.getFechaFin())) {
return true;
}
} catch (WrongValueException ex) {
logger.error(ex.getMessage(), ex);
return true;
}
return false;
}
private void loadComboCategorias(final CategoriaDTO categoria) {
cbx_categoria.setModel(new ListModelArray(this.categoriaService.getAll()));
cbx_categoria.setItemRenderer(new ComboitemRenderer() {
@Override
public void render(Comboitem item, Object data, int arg2) throws Exception {
CategoriaDTO cat = (CategoriaDTO) data;
item.setLabel(cat.getCategoriaNombre());
item.setValue(cat.getId());
if (categoria != null && cat.getId().equals(categoria.getId())) {
cbx_categoria.setSelectedItem(item);
}
}
});
}
private void loadComboCategoria() {
setCategorias(this.categoriaService.getAll());
this.cbx_categoria.setModel(new ListModelArray(categorias));
this.binder.loadComponent(cbx_categoria);
}
private void loadComboModulo() {
aplicaciones = this.aplicacionService.getAll();
aplicacionesLayout = TransformerAplicacion.transformarAplicacionALayout(aplicaciones);
this.cbx_aplicacion.setModel(new ListModelArray(aplicacionesLayout));
this.binder.loadComponent(cbx_aplicacion);
}
private void cerrar() {
this.self.detach();
}
public NovedadDTO getNovedad() {
return novedad;
}
public void setNovedad(NovedadDTO novedad) {
this.novedad = novedad;
}
public CategoriaDTO getCategoria() {
return categoria;
}
public void setCategoria(CategoriaDTO categoria) {
this.categoria = categoria;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String[] getListaEstados() {
return listaEstados;
}
public void setListaEstados(String[] listaEstados) {
this.listaEstados = listaEstados;
}
public Listbox getCbx_aplicacion() {
return cbx_aplicacion;
}
public void setCbx_aplicacion(Listbox cbx_aplicacion) {
this.cbx_aplicacion = cbx_aplicacion;
}
public Combobox getCbx_categoria() {
return cbx_categoria;
}
public void setCbx_categoria(Combobox cbx_categoria) {
this.cbx_categoria = cbx_categoria;
}
public AnnotateDataBinder getBinder() {
return binder;
}
public void setBinder(AnnotateDataBinder binder) {
this.binder = binder;
}
public void setCategorias(List<CategoriaDTO> categorias) {
this.categorias = categorias;
}
public List<CategoriaDTO> getCategorias() {
return categorias;
}
public void setAplicaciones(List<AplicacionDTO> aplicaciones) {
this.aplicaciones = aplicaciones;
}
public List<AplicacionDTO> getAplicaciones() {
return aplicaciones;
}
public Set getSelectedItems() {
return selectedItems;
}
public void setSelectedItems(Set selectedItems) {
this.selectedItems = selectedItems;
}
public void setWin_novedadNueva(Window win_novedadNueva) {
this.win_novedadNueva = win_novedadNueva;
}
public Window getWin_novedadNueva() {
return win_novedadNueva;
}
public List<ApLayOut> getAplicacionesLayout() {
return aplicacionesLayout;
}
public void setAplicacionesLayout(List<ApLayOut> aplicacionesLayout) {
this.aplicacionesLayout = aplicacionesLayout;
}
public void setAplicacionLayOut(ApLayOut aplicacionLayOut) {
this.aplicacionLayOut = aplicacionLayOut;
}
public ApLayOut getAplicacionLayOut() {
return aplicacionLayOut;
}
final class NuevaNovedadComposerListener implements EventListener {
@SuppressWarnings("unused")
private NuevaNovedadComposer composer;
private INovedadHistService novedadHistService;
public NuevaNovedadComposerListener(NuevaNovedadComposer comp) {
this.composer = comp;
}
@Override
public void onEvent(Event event) throws Exception {
this.novedadHistService = (INovedadHistService) SpringUtil.getBean("novedadHistService");
if (event.getName().equals(Events.ON_CHANGE)) {
Map<String, Object> mapa = (Map<String, Object>) event.getData();
novedadHistService.guardarHistorico((NovedadDTO) mapa.get("novedad"),
(Integer) mapa.get("operacion"));
}
}
}
final static class TransformerAplicacion {
private static List<ApLayOut> transformarAplicacionALayout(List<AplicacionDTO> aplicaciones) {
List<ApLayOut> listOut = new ArrayList<>();
for (AplicacionDTO ap : aplicaciones) {
ApLayOut a = new ApLayOut();
a.setEsSeleccionado(false);
a.setIdAplicacion(ap.getIdAplicacion());
a.setNombreAplicacion(ap.getNombreAplicacion());
listOut.add(a);
}
return listOut;
}
}
} | 30.80203 | 98 | 0.702318 |
7f101cc3b98cd7c66c87c6ddf772ec5fca262ad0 | 631 | package model;
import java.util.ArrayList;
import java.util.List;
import activity.AnythingActivity;
import android.content.Context;
import android.widget.Button;
public class ModelUI {
private static ModelUI sModelUI;
private Context mContext;
private ArrayList<Button> mButtons;
private ModelUI(Context context){
mContext = context;
mButtons = new ArrayList<Button>();
}
public static ModelUI get(Context c){
sModelUI = new ModelUI(c);
return sModelUI;
}
public ArrayList<Button> getButtons() {
return mButtons;
}
public void setButtons(ArrayList<Button> Buttons) {
mButtons = Buttons;
}
}
| 16.179487 | 52 | 0.740095 |
b9629b2b78f9baa74ea309f5ced264e9d350bfc2 | 57,767 | package chat.rocket.android.api;
import android.content.Context;
import android.os.Build;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;
import bolts.Continuation;
import bolts.Task;
import chat.rocket.android.RocketChatCache;
import chat.rocket.android.ToastUtils;
import chat.rocket.android.helper.CheckSum;
import chat.rocket.android.helper.JsonHelper;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.log.RCLog;
import chat.rocket.android.service.ChatConnectivityManager;
import chat.rocket.android.video.model.VideoSendMsgModel;
import chat.rocket.android_ddp.DDPClient;
import chat.rocket.android_ddp.DDPClientCallback;
import chat.rocket.core.PublicSettingsConstants;
import chat.rocket.core.SyncState;
import chat.rocket.persistence.realm.RealmHelper;
import chat.rocket.persistence.realm.RealmStore;
import chat.rocket.persistence.realm.models.ddp.RealmAuth;
import chat.rocket.persistence.realm.models.ddp.RealmMessage;
import chat.rocket.persistence.realm.models.ddp.RealmOrgCompany;
import chat.rocket.persistence.realm.models.ddp.RealmPermission;
import chat.rocket.persistence.realm.models.ddp.RealmPublicSetting;
import chat.rocket.persistence.realm.models.ddp.RealmRoom;
import chat.rocket.persistence.realm.models.ddp.RealmRoomRole;
import chat.rocket.persistence.realm.models.ddp.RealmSpotlight;
import chat.rocket.persistence.realm.models.ddp.RealmSpotlightRoom;
import chat.rocket.persistence.realm.models.ddp.RealmSpotlightUser;
import chat.rocket.persistence.realm.models.ddp.RealmSubscription;
import chat.rocket.persistence.realm.models.ddp.RealmUserEntity;
import chat.rocket.persistence.realm.models.internal.MethodCall;
import chat.rocket.persistence.realm.models.internal.RealmSession;
import chat.rocket.persistence.realm.repositories.RealmLabels;
import hugo.weaving.DebugLog;
import io.realm.RealmQuery;
import okhttp3.HttpUrl;
/**
* Utility class for creating/handling MethodCall or RPC.
* <p>
* TODO: separate method into several manager classes (SubscriptionManager, MessageManager, ...).
*/
public class MethodCallHelper {
private static final String TAG = "MethodCallHelper";
protected static final long TIMEOUT_MS = 20000;
protected static final Continuation<String, Task<JSONObject>> CONVERT_TO_JSON_OBJECT =
task -> Task.forResult(new JSONObject(task.getResult()));
protected static final Continuation<String, Task<JSONArray>> CONVERT_TO_JSON_ARRAY =
task -> Task.forResult(new JSONArray(task.getResult()));
protected final Context context;
protected final RealmHelper realmHelper;
/**
* initialize with Context and hostname.
*/
public MethodCallHelper(Context context, String hostname) {
this.context = context.getApplicationContext();
this.realmHelper = RealmStore.getOrCreate(hostname);
}
/**
* initialize with RealmHelper and DDPClient.
*/
public MethodCallHelper(RealmHelper realmHelper) {
this.context = null;
this.realmHelper = realmHelper;
}
public MethodCallHelper(Context context, RealmHelper realmHelper) {
this.context = context.getApplicationContext();
this.realmHelper = realmHelper;
}
@DebugLog
private Task<String> executeMethodCall(String methodName, String param, long timeout) {
if (DDPClient.get() != null) {
return DDPClient.get().rpc(UUID.randomUUID().toString(), methodName, param, timeout)
.onSuccessTask(task -> Task.forResult(task.getResult().result))
.continueWithTask(task_ -> {
if (task_.isFaulted()) {
return Task.forError(task_.getError());
}
return Task.forResult(task_.getResult());
});
} else {
return MethodCall.execute(realmHelper, methodName, param, timeout)
.onSuccessTask(task -> {
ChatConnectivityManager.getInstance(context.getApplicationContext())
.keepAliveServer();
return task;
});
}
}
private Task<String> injectErrorHandler(Task<String> task) {
return task.continueWithTask(_task -> {
if (_task.isFaulted()) {
Exception exception = _task.getError();
if (exception instanceof MethodCall.Error || exception instanceof DDPClientCallback.RPC.Error) {
String errMessageJson;
if (exception instanceof DDPClientCallback.RPC.Error) {
errMessageJson = ((DDPClientCallback.RPC.Error) exception).error.toString();
} else {
errMessageJson = exception.getMessage();
}
if (TextUtils.isEmpty(errMessageJson)) {
return Task.forError(exception);
}
String errType = new JSONObject(errMessageJson).optString("error");
String errMessage = new JSONObject(errMessageJson).getString("message");
if (TwoStepAuthException.TYPE.equals(errType)) {
return Task.forError(new TwoStepAuthException(errMessage));
}
return Task.forError(new Exception(errMessage));
} else if (exception instanceof DDPClientCallback.RPC.Timeout) {
return Task.forError(new MethodCall.Timeout());
} else if (exception instanceof DDPClientCallback.Closed) {
return Task.forError(new Exception(exception.getMessage()));
} else {
return Task.forError(exception);
}
} else {
return _task;
}
});
}
protected final Task<String> call(String methodName, long timeout) {
return injectErrorHandler(executeMethodCall(methodName, null, timeout));
}
protected final Task<String> call(String methodName, long timeout, ParamBuilder paramBuilder) {
try {
final JSONArray params = paramBuilder.buildParam();
return injectErrorHandler(executeMethodCall(methodName,
params != null ? params.toString() : null, timeout));
} catch (JSONException exception) {
return Task.forError(exception);
}
}
/**
* Register RealmUser.
*/
public Task<String> registerUser(final String name, final String email,
final String password, final String confirmPassword) {
return call("registerUser", TIMEOUT_MS, () -> new JSONArray().put(new JSONObject()
.put("name", name)
.put("email", email)
.put("pass", password)
.put("confirm-pass", confirmPassword))); // nothing to do.
}
/**
* set current user's name.
*/
public Task<String> setUsername(final String username) {
return call("setUsername", TIMEOUT_MS, () -> new JSONArray().put(username));
}
public Task<Void> joinDefaultChannels() {
return call("joinDefaultChannels", TIMEOUT_MS)
.onSuccessTask(task -> Task.forResult(null));
}
public Task<Void> joinRoom(String roomId) {
return call("joinRoom", TIMEOUT_MS, () -> new JSONArray().put(roomId))
.onSuccessTask(task -> Task.forResult(null));
}
/**
* Login with username/email and password.
*/
public Task<Void> loginWithEmail(final String usernameOrEmail, final String password) {
return call("login", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
if (Patterns.EMAIL_ADDRESS.matcher(usernameOrEmail).matches()) {
param.put("user", new JSONObject().put("email", usernameOrEmail));
} else {
param.put("user", new JSONObject().put("username", usernameOrEmail));
}
param.put("password", new JSONObject()
.put("digest", CheckSum.sha256(password))
.put("algorithm", "sha-256"));
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(new Continuation<JSONObject, Task<String>>() {
@Override
public Task<String> then(Task<JSONObject> task) throws Exception {
JSONObject jsonObject = task.getResult();
return Task.forResult(jsonObject.getString("token"));
}
})
.onSuccessTask(this::saveToken);
}
public Task<Void> loginWithLdap(final String username, final String password) {
return call("login", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("ldap", true);
param.put("username", username);
param.put("ldapPass", password);
param.put("ldapOptions", new JSONObject());
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> Task.forResult(task.getResult().getString("token")))
.onSuccessTask(this::saveToken);
}
/**
* 威宁通登录
*
* @param activity
* @return
*/
public Task<Void> loginUser(Context activity, String sessionId) {
RCLog.d("loginUser sessionId="+sessionId);
return call("signupLogin", TIMEOUT_MS, () -> new JSONArray()
.put(new JSONObject()
.put("sessionId", sessionId)))
.onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(new Continuation<JSONObject, Task<String>>() {
@Override
public Task<String> then(Task<JSONObject> task) throws Exception {
JSONObject jsonObject = task.getResult();
RCLog.d("loginUser result: " + jsonObject.toString());
realmHelper.executeTransaction(realm -> {
realm.delete(RealmAuth.class);
realm.createOrUpdateObjectFromJson(RealmAuth.class, RealmAuth.customizeJson(task.getResult()));
return null;
});
RCLog.d("Main----保存sessionId");
return Task.forResult(jsonObject.getString("token"));
}
}).onSuccessTask(this::saveToken);
}
private Task<Void> saveToken(Task<String> task) {
// RocketChatCache.INSTANCE.setSessionToken(task.getResult());
return realmHelper.executeTransaction(realm ->
realm.createOrUpdateObjectFromJson(RealmSession.class, new JSONObject()
.put("sessionId", RealmSession.DEFAULT_ID)
.put("token", task.getResult())
.put("tokenVerified", true)
.put("error", JSONObject.NULL)
));
}
/**
* Login with OAuth.
*/
public Task<Void> loginWithOAuth(final String credentialToken,
final String credentialSecret) {
return call("login", TIMEOUT_MS, () -> new JSONArray().put(new JSONObject()
.put("oauth", new JSONObject()
.put("credentialToken", credentialToken)
.put("credentialSecret", credentialSecret))
)).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> Task.forResult(task.getResult().getString("token")))
.onSuccessTask(this::saveToken);
}
/**
* Login with token.
*/
public Task<Void> loginWithToken(final String token) {
RCLog.d("loginWithToken");
return call("login", TIMEOUT_MS, () -> new JSONArray().put(new JSONObject()
.put("resume", token)
)).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> Task.forResult(task.getResult().getString("token")))
.onSuccessTask(this::saveToken)
.continueWithTask(task -> {
if (task.isFaulted()) {
RealmSession.logError(realmHelper, task.getError());
}
return task;
});
}
public Task<Void> twoStepCodeLogin(final String usernameOrEmail, final String password,
final String twoStepCode) {
return call("login", TIMEOUT_MS, () -> {
JSONObject loginParam = new JSONObject();
if (Patterns.EMAIL_ADDRESS.matcher(usernameOrEmail).matches()) {
loginParam.put("user", new JSONObject().put("email", usernameOrEmail));
} else {
loginParam.put("user", new JSONObject().put("username", usernameOrEmail));
}
loginParam.put("password", new JSONObject()
.put("digest", CheckSum.sha256(password))
.put("algorithm", "sha-256"));
JSONObject twoStepParam = new JSONObject();
twoStepParam.put("login", loginParam);
twoStepParam.put("code", twoStepCode);
JSONObject param = new JSONObject();
param.put("totp", twoStepParam);
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> Task.forResult(task.getResult().getString("token")))
.onSuccessTask(this::saveToken);
}
/**
* Logout.
*/
public Task<Void> logout() {
return call("logout", TIMEOUT_MS).onSuccessTask(task -> {
if (task.isFaulted()) {
return Task.forError(task.getError());
}
return null;
});
}
/**
* request "room/get"
*/
public Task<Void> getRooms() {
return call("rooms/get", TIMEOUT_MS).onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
// RCLog.d("rooms/get->>"+ task.getResult());
JSONArray result = task.getResult();
for (int i = 0; i < result.length(); i++) {
if (TextUtils.isEmpty(result.get(i).toString())||result.get(i).toString().equals("{}")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
result.remove(i);
}else {
JsonHelper.getInstance().remove(result,i);
}
}else {
RealmRoom.customizeJson(result.getJSONObject(i));
}
}
return realmHelper.executeTransaction(realm -> {
if (result.length() == 0) {
return task;
}
realm.delete(RealmRoom.class);
realm.createOrUpdateAllFromJson(RealmRoom.class, result);
return task;
});
}).continueWithTask(task -> {
if (task.isFaulted()) {
// RCLog.e("rooms/get error="+task.getError());
}
return null;
});
}
/**
* request "subscriptions/get".
*/
public Task<Void> getRoomSubscriptions() {
return call("subscriptions/get", TIMEOUT_MS).onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
final JSONArray result = task.getResult();
try {
for (int i = 0; i < result.length(); i++) {
RealmSubscription.customizeJson(result.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
if (result.length() == 0) {
return null;
}
realm.delete(RealmSubscription.class);
// RCLog.d("->>>>>>>>>"+result);
realm.createOrUpdateAllFromJson(
RealmSubscription.class, result);
JSONObject openedRooms = RocketChatCache.INSTANCE.getOpenedRooms();
RealmQuery<RealmSubscription> query = realm.where(RealmSubscription.class);
Iterator<String> keys = openedRooms.keys();
while (keys.hasNext()) {
String rid = keys.next();
RealmSubscription realmSubscription = query.equalTo(RealmSubscription.ID, rid).findFirst();
if (realmSubscription == null) {
RocketChatCache.INSTANCE.removeOpenedRoom(rid);
} else {
loadMissedMessages(rid, realmSubscription.getLs())
.continueWithTask(task1 -> {
if (task1.isFaulted()) {
Exception error = task1.getError();
RCLog.e(error);
}
return null;
});
}
}
return null;
});
} catch (JSONException exception) {
return Task.forError(exception);
}
});
}
public Task<JSONArray> loadMissedMessages(final String roomId, final long timestamp) {
return call("loadMissedMessages", TIMEOUT_MS, () -> new JSONArray()
.put(roomId)
.put(timestamp > 0 ? new JSONObject().put("$date", timestamp) : JSONObject.NULL)
).onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
JSONArray result = task.getResult();
for (int i = 0; i < result.length(); i++) {
RealmMessage.customizeJson(result.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
if (timestamp == 0) {
realm.where(RealmMessage.class)
.equalTo("rid", roomId)
.equalTo("syncstate", SyncState.SYNCED)
.findAll().deleteAllFromRealm();
}
if (result.length() > 0) {
realm.createOrUpdateAllFromJson(RealmMessage.class, result);
}
return null;
}).onSuccessTask(_task -> Task.forResult(result));
});
}
/**
* Load messages for room.
*/
public Task<JSONArray> loadHistory(final String roomId, final long timestamp,
final int count, final long lastSeen) {
return call("loadHistory", TIMEOUT_MS, () -> new JSONArray()
.put(roomId)
.put(timestamp > 0 ? new JSONObject().put("$date", timestamp) : JSONObject.NULL)
.put(count)
.put(lastSeen > 0 ? new JSONObject().put("$date", lastSeen) : JSONObject.NULL)
).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> {
JSONObject result = task.getResult();
final JSONArray messages = result.getJSONArray("messages");
for (int i = 0; i < messages.length(); i++) {
RealmMessage.customizeJson(messages.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
// if (timestamp == 0) {
// realm.where(RealmMessage.class)
// .equalTo("rid", roomId)
// .equalTo("syncstate", SyncState.SYNCED)
// .findAll().deleteAllFromRealm();
// }
if (messages.length() > 0) {
realm.createOrUpdateAllFromJson(RealmMessage.class, messages);
}
return null;
}).onSuccessTask(_task -> Task.forResult(messages));
});
}
/**
* update user's status.
*/
public Task<Void> setUserStatus(final String status) {
return call("UserPresence:setDefaultStatus", TIMEOUT_MS, () -> new JSONArray().put(status))
.onSuccessTask(task -> Task.forResult(null));
}
public Task<Void> setUserPresence(final String status) {
return call("UserPresence:" + status, TIMEOUT_MS)
.onSuccessTask(task -> Task.forResult(null));
}
public Task<JSONObject> getUsersOfRoom(final String roomId, final boolean showAll) {
return call("getUsersOfRoom", TIMEOUT_MS, () -> new JSONArray().put(roomId).put(showAll))
.onSuccessTask(CONVERT_TO_JSON_OBJECT);
}
public Task<Void> createChannel(final String name, final boolean readOnly) {
return call("createChannel", TIMEOUT_MS, () -> new JSONArray()
.put(name)
.put(new JSONArray())
.put(readOnly))
.onSuccessTask(task -> Task.forResult(null));
}
public Task<Void> createPrivateGroup(final String name, final boolean readOnly) {
return call("createPrivateGroup", TIMEOUT_MS, () -> new JSONArray()
.put(name)
.put(new JSONArray())
.put(readOnly))
.onSuccessTask(task -> Task.forResult(null));
}
public Task<String> createDirectMessage(final String username) {
return call("createDirectMessage", TIMEOUT_MS, () -> new JSONArray().put(username))
.onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> Task.forResult(task.getResult().getString("rid")));
}
/**
* send message.
*/
public Task<String> sendMessage(String messageId, String roomId, String msg, long editedAt) {
try {
JSONObject messageJson = new JSONObject()
.put("_id", messageId)
.put("rid", roomId)
.put("msg", msg);
if (editedAt == 0) {
return sendMessage(messageJson);
} else {
return updateMessage(messageJson);
}
} catch (JSONException exception) {
return Task.forError(exception);
}
}
public Task<Void> deleteMessage(String messageID) {
try {
JSONObject messageJson = new JSONObject()
.put("_id", messageID);
return deleteMessage(messageJson);
} catch (JSONException exception) {
return Task.forError(exception);
}
}
/**
* Send message object.
*/
private Task<String> sendMessage(final JSONObject messageJson) {
return call("sendMessage", TIMEOUT_MS, () -> new JSONArray().put(messageJson))
.onSuccessTask(task -> Task.forResult(task.getResult()));
// .continueWithTask(new LogIfError());
}
private Task<String> updateMessage(final JSONObject messageJson) {
return call("updateMessage", TIMEOUT_MS, () -> new JSONArray().put(messageJson))
.onSuccessTask(task -> Task.forResult(task.getResult()));
}
private Task<Void> deleteMessage(final JSONObject messageJson) {
return call("deleteMessage", TIMEOUT_MS, () -> new JSONArray().put(messageJson))
.onSuccessTask(task -> Task.forResult(null));
}
/**
* mark all messages are read in the room.
*/
public Task<Void> readMessages(final String roomId) {
return call("readMessages", TIMEOUT_MS, () -> new JSONArray().put(roomId))
.onSuccessTask(task -> Task.forResult(null));
}
public Task<Void> getPublicSettings(String currentHostname) {
return call("public-settings/get", TIMEOUT_MS)
.onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
final JSONArray settings = task.getResult();
String siteUrl = null;
String siteName = null;
for (int i = 0; i < settings.length(); i++) {
JSONObject jsonObject = settings.getJSONObject(i);
RealmPublicSetting.customizeJson(jsonObject);
if (isPublicSetting(jsonObject, PublicSettingsConstants.General.SITE_URL)) {
siteUrl = jsonObject.getString(RealmPublicSetting.VALUE);
} else if (isPublicSetting(jsonObject, PublicSettingsConstants.General.SITE_NAME)) {
siteName = jsonObject.getString(RealmPublicSetting.VALUE);
}
}
if (siteName != null && siteUrl != null) {
HttpUrl httpSiteUrl = HttpUrl.parse(siteUrl);
if (httpSiteUrl != null) {
String host = httpSiteUrl.host();
RocketChatCache.INSTANCE.addSiteUrl(host, currentHostname);
RocketChatCache.INSTANCE.addSiteName(currentHostname, siteName);
}
}
return realmHelper.executeTransaction(realm -> {
realm.delete(RealmPublicSetting.class);
realm.createOrUpdateAllFromJson(RealmPublicSetting.class, settings);
return null;
});
});
}
private boolean isPublicSetting(JSONObject jsonObject, String id) {
return jsonObject.optString(RealmPublicSetting.ID).equalsIgnoreCase(id);
}
public Task<Void> getPermissions() {
return call("permissions/get", TIMEOUT_MS)
.onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
final JSONArray permissions = task.getResult();
for (int i = 0; i < permissions.length(); i++) {
RealmPermission.customizeJson(permissions.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
realm.delete(RealmPermission.class);
realm.createOrUpdateAllFromJson(RealmPermission.class, permissions);
return null;
});
});
}
public Task<Void> getRoomRoles(final String roomId) {
return call("getRoomRoles", TIMEOUT_MS, () -> new JSONArray().put(roomId))
.onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
final JSONArray roomRoles = task.getResult();
for (int i = 0; i < roomRoles.length(); i++) {
RealmRoomRole.customizeJson(roomRoles.getJSONObject(i));
}
return realmHelper.executeTransaction(realm -> {
realm.delete(RealmRoomRole.class);
realm.createOrUpdateAllFromJson(RealmRoomRole.class, roomRoles);
return null;
});
});
}
/**
* 删除点对点
*
* @param userId
* @param rid
* @return
*/
public Task<Void> hideRoomForMobile(String userId, String rid) {
return call("hideRoomForMobile", TIMEOUT_MS
, () -> new JSONArray()
.put(new JSONObject()
.put("userId", userId)
.put("rid", rid)))
.onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
task.getResult();
return null;
});
}
/**
* 创建点对点
*
* @param userName
* @return
*/
public Task<Void> createDirectMessageForMobile(String userName) {
return call("createDirectMessageForMobile", TIMEOUT_MS
, () -> new JSONArray()
.put(new JSONObject().put("username", userName)))
.onSuccessTask(task -> {
task.getResult();
return task;
})
.continueWithTask(task -> {
return null;
});
}
/**
* 获取体系数据
*
* @return
*/
public Task<String> labelsForMobile() {
return call("labelsForMobile", TIMEOUT_MS)
.onSuccessTask(CONVERT_TO_JSON_ARRAY)
.onSuccessTask(task -> {
final JSONArray result = task.getResult();
for (int i = 0; i < result.length(); i++) {
RealmLabels.customizeJson(result.getJSONObject(i));
}
realmHelper.executeTransaction(realm -> {
realm.delete(RealmLabels.class);
realm.createOrUpdateAllFromJson(RealmLabels.class, result);
return null;
});
return null;
});
}
/**
* 订阅数据
*
* @param userId
* @return
*/
public Task<Void> subscriptionForMobile(String userId) {
return call("subscriptionForMobile", TIMEOUT_MS, () ->
new JSONArray().put(new JSONObject().put("userId", userId)))
.onSuccessTask(task -> {
task.getResult();
return null;
}).continueWithTask(task -> {
if (task.isFaulted()) {
task.getError();
}
return null;
});
}
/**
* 获取频道数据
*
* @param userId
* @return
*/
public Task<Void> roomsForMobile(String userId) {
return call("roomsForMobile", TIMEOUT_MS, () ->
new JSONArray().put(new JSONObject().put("userId", userId)))
.onSuccessTask(task -> {
task.getResult();
return null;
}).continueWithTask(task -> {
if (task.isFaulted()) {
task.getError();
}
return null;
});
}
/**
* 获取频道类型
*
* @return
*/
public Task<Void> roomsTypesForMobile() {
return call("roomsTypesForMobile", TIMEOUT_MS)
.onSuccessTask(task -> {
task.getResult();
return null;
}).continueWithTask(task -> {
if (task.isFaulted()) {
task.getError();
}
return null;
});
}
/**
* 用户和房间搜索
*
* @param term
* @param userId
* @return
*/
public Task<Void> searchSpotlight(String term, String userId) {
return call("sideNavSearch", TIMEOUT_MS, () ->
new JSONArray()
.put(new JSONObject().put("userId", userId)
.put("text", term)))
.onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> {
JSONArray users = task.getResult().getJSONArray("users");
return realmHelper.executeTransaction(realm -> {
realm.delete(RealmSpotlightUser.class);
realm.createOrUpdateAllFromJson(RealmSpotlightUser.class,users);
; return null;
});
});
}
public Task<Void> searchSpotlightUsers(String term) {
return searchSpotlight(RealmSpotlightUser.class, "users", term);
}
public Task<Void> searchSpotlightRooms(String term) {
return searchSpotlight(RealmSpotlightRoom.class, "rooms", term);
}
public Task<Void> searchSpotlight(String term) {
return call("spotlight", TIMEOUT_MS, () ->
new JSONArray()
.put(term)
.put(JSONObject.NULL)
.put(new JSONObject().put("rooms", true).put("users", true))
).onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> {
String jsonString = null;
final JSONObject result = task.getResult();
JSONArray roomJsonArray = (JSONArray) result.get("rooms");
int roomTotal = roomJsonArray.length();
if (roomTotal > 0) {
for (int i = 0; i < roomTotal; ++i) {
RealmSpotlight.Companion.customizeRoomJSONObject(roomJsonArray.getJSONObject(i));
}
jsonString = roomJsonArray.toString();
}
JSONArray userJsonArray = (JSONArray) result.get("users");
int usersTotal = userJsonArray.length();
if (usersTotal > 0) {
for (int i = 0; i < usersTotal; ++i) {
RealmSpotlight.Companion.customizeUserJSONObject(userJsonArray.getJSONObject(i));
}
if (jsonString == null) {
jsonString = userJsonArray.toString();
} else {
jsonString = jsonString.replace("]", "") + "," + userJsonArray.toString().replace("[", "");
}
}
if (jsonString != null) {
String jsonStringResults = jsonString;
realmHelper.executeTransaction(realm -> {
realm.delete(RealmSpotlight.class);
realm.createOrUpdateAllFromJson(RealmSpotlight.class, jsonStringResults);
return null;
});
}
return null;
});
}
private Task<Void> searchSpotlight(Class clazz, String key, String term) {
return call("spotlight", TIMEOUT_MS, () -> new JSONArray()
.put(term)
.put(JSONObject.NULL)
.put(new JSONObject().put(key, true)))
.onSuccessTask(CONVERT_TO_JSON_OBJECT)
.onSuccessTask(task -> {
final JSONObject result = task.getResult();
if (!result.has(key)) {
return null;
}
Object items = result.get(key);
if (!(items instanceof JSONArray)) {
return null;
}
return realmHelper.executeTransaction(realm -> {
realm.delete(clazz);
realm.createOrUpdateAllFromJson(clazz, (JSONArray) items);
return null;
});
});
}
/**
* userId String 用户id 是
* name String 频道名称 是
* members Array 频道成员 是
* channel String 父级频道 此参数是频道数据里包含@userId+时间戳的字段 否
* label Object 企业体系 {“ id”:”xxxxx”,”name”:”xxxxx”} 否
* readOnly Bool 只读 否
*
* @return
*/
public Task<String> createWorkingGroupForMobile(String userId, String name, JSONArray list,
String channel, String tixiClass, boolean readOnly) {
return call("createWorkingGroupForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("userId", userId);
param.put("name", name);
param.put("members", list);
// param.put("channel", channel);
if (android.text.TextUtils.isEmpty(tixiClass)) {
// param.put("label", new JSONObject());
} else {
param.put("label", new JSONObject(tixiClass));
}
param.put("readonly", readOnly);
return new JSONArray().put(param);
});
}
/**
* 创建会议巢频道
* userId String 用户id 是
* name String 频道名称 是
* members Array 频道成员 是
* subMeetingType String 父级频道 text | audio | vide 是
* encrypt Boolean 加密 否
* readOnly Boolean 只读 否
* startDate Date 开始时间 是
* endDate Date 结束时间 是
* meetingSubject String 会议主题 否
*
* @return
*/
public Task<String> createMeetingGroupForMobile(String userId, String name, JSONArray str,JSONArray zhuchirenJsonArray,
Date startDate, Date endDate, String subMeetingType, boolean encrypt, boolean qiandao, String meetingSubject) {
return call("createMeetingGroupForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
JSONObject objStartDate = new JSONObject().put("$date", startDate);
JSONObject objEndDate = new JSONObject().put("$date", endDate);
param.put("userId", userId);
param.put("name", name);
param.put("host", zhuchirenJsonArray.toString().equals("[]")?"":zhuchirenJsonArray);
param.put("members", str);
param.put("subMeetingType", subMeetingType);
param.put("startDate", objStartDate);
param.put("endDate", objEndDate);
param.put("encrypt", encrypt);
param.put("readonly", false);
param.put("attendance", qiandao);
param.put("meetingSubject", meetingSubject);
return new JSONArray().put(param);
});
}
/**
* 创建组织巢频道
*
* @param userId
* @param name
* @param list
* @param channel
* @param tixiClass
* @param readOnly
* @return
*/
public Task<String> createPrivateGroupForMobile(String userId, String name, JSONArray list,
String channel, String tixiClass, boolean readOnly) {
return call("createPrivateGroupForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("userId", userId);
param.put("name", name);
param.put("members", list);
// param.put("channel", channel);
if (android.text.TextUtils.isEmpty(tixiClass)) {
// param.put("label", new JSONObject());
} else {
param.put("label", new JSONObject(tixiClass));
}
param.put("readonly", readOnly);
return new JSONArray().put(param);
});
}
public Task<String> userForCreateRoom(String type, String companyId, String[] filterUsernames) {
return call("userForCreateRoom", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
if(!TextUtils.isEmpty(type)) {
param.put("type", type);
}
if(!TextUtils.isEmpty(companyId)) {
param.put("companyId", companyId);
}
if(filterUsernames != null) {
JSONArray array = new JSONArray();
for (int i = 0; i < filterUsernames.length; i++) {
array.put(filterUsernames[i]);
}
param.put("filterUsernames", array);
}
return new JSONArray().put(param);
});
}
public Task<Void> userForCreateRoomToRealm(String type, String companyId) {
return call("userForCreateRoom", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("type", type);
param.put("companyId", companyId);
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_ARRAY).onSuccessTask((Task<JSONArray> task) -> {
JSONArray result = task.getResult();
if(result == null) {
return null;
}
/*您可以直接将 JSON 对象添加到 Realm 中,这些 JSON 对象可以是一个 String、一个 JSONObject 或者是一个
InputStream。Realm 会忽略 JSON 中存在但未定义在 Realm 模型类里的字段。单独对象可以通过
Realm.createObjectFromJson() 添加。对象列表可以通过 Realm.createAllFromJson() 添加。*/
for (int i = 0; i < result.length(); i++) {
RealmUserEntity.customizeJson(result.getJSONObject(i), type);
}
// List<RealmUserEntity> realmUserEntityAll = userEntityRepository.getRealmUserEntityAll(type, companyId);
realmHelper.executeTransaction(realm -> {
// if(realmUserEntityAll != null && realmUserEntityAll.size() > 0){
// realm.delete(RealmUserEntity.class);
// }
realm.createOrUpdateAllFromJson(RealmUserEntity.class, result);
return null;
}).continueWithTask(task1 -> {
if (task1.isFaulted() || task1.getError() != null) {
RCLog.e("userForCreateRoomToRealm: result=" + task1.getError());
}
return null;
});
return null;
});
}
public Task<JSONArray> userForCreateRoomShowDeptToRealm(String type, String name ,String companyId,boolean showDeptRole) {
return call("userForCreateRoom", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("type", type);
param.put("companyId", companyId);
param.put("name", name);
param.put("showDeptRole", showDeptRole);
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_ARRAY);
}
/**
* rid String 频道id 是
userId String 锁定,解锁用户id 是
block Boolean 锁定或解锁 是
* @return
*/
public Task<String> blockUserForMobile(String rid, String userId, boolean block) {
return call("blockUserForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
param.put("block", block);
return new JSONArray().put(param);
});
}
/**设置,解除群主 websocket method
* rid String 频道id
userId String 用户id
set Boolean 是否设置
*/
public Task<String> setOwner(String rid, String userId, boolean set) {
return call("setOwner", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
param.put("set", set);
return new JSONArray().put(param);
});
}
/**
* 设置,解除管理员
* rid String 频道id
userId String 用户id
set Boolean 是否设置
*/
public Task<String> setModerator(String rid, String userId, boolean set) {
return call("setModerator", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
param.put("set", set);
return new JSONArray().put(param);
});
}
/**
* 禁言、允许发言
* rid String 频道id
userId String 锁定,解锁用户id
username String 用户名
mute Boolean 是否禁言
*/
public Task<String> muteUser(String rid, String userId, String username, boolean mute) {
return call("muteUser", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
param.put("username", username);
param.put("mute", mute);
return new JSONArray().put(param);
});
}
/**
* 接口名称: modifyRoomInfo
接口说明: 修改频道信息
输入内容:
字段名 字段类型 字段名称
rid String 频道id
name String 频道名
topic String 频道主题
description String 频道描述
*/
public Task<String> modifyRoomInfo(String rid, String name) {
return call("modifyRoomInfo", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("name", name);
// param.put("description", description);
return new JSONArray().put(param);
});
}
public Task<String> modifyRoomInfo2(String rid, String topic) {
return call("modifyRoomInfo", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("topic", topic);
// param.put("description", description);
return new JSONArray().put(param);
});
}
/**
* rid String 频道id
username String 用户名
* @param rid
* @param username
* @return
*/
public Task<String> removeUser(String rid, String username) {
return call("removeUser", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("username", username);
return new JSONArray().put(param);
});
}
public Task<String> addMembers(String rid, JSONArray username) {
return call("addMembers", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("usernames", username);
return new JSONArray().put(param);
});
}
/**
* 签到
rid String 频道id
username String 用户名
date Dated 签到日期
*/
public void attendanceFromMobile(String rid, String username, Button btn_qiandao) {
call("attendanceFromMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
JSONObject objStartDate = new JSONObject().put("$date", new Date());
param.put("rid", rid);
param.put("username", username);
param.put("date", objStartDate);
return new JSONArray().put(param);
}).onSuccessTask(task -> {
return task;
}).continueWithTask(task -> {
if (task.isFaulted() || task.getError() != null) {
RCLog.e( "attendanceFromMobile: result=" + task.getError());
ToastUtils.showToast(task.getError()+"");
return null;
}else{
btn_qiandao.setVisibility(View.GONE);
ToastUtils.showToast("签到成功!");
}
return task;
}, Task.UI_THREAD_EXECUTOR);
}
/**
* 暂停/重启会议
* */
public Task<String> pauseOrRestartMeetting(String rid,String userId,boolean pauseOrRestart){
return call("pauseOrRestartMeeting", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
param.put("pauseOrRestart", pauseOrRestart);
return new JSONArray().put(param);
});
}
/**
* 获取组织架构(websocket method)
* type String 频道类型
sessionId String 会话Id
*/
public Task<Void> organizationForMobile(String type,String sessionId){
return call("organizationForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("type", type);
param.put("sessionId", sessionId);
return new JSONArray().put(param);
}).onSuccessTask(CONVERT_TO_JSON_OBJECT).onSuccessTask((Task<JSONObject> task) -> {
JSONObject result = task.getResult();
if(result.get("res") == null || !(result.get("res") instanceof JSONArray)) {
RCLog.e("result="+result);
return null;
}
JSONArray jsonArray = (JSONArray) result.get("res");
realmHelper.executeTransaction(realm -> {
realm.delete(RealmOrgCompany.class);
realm.createOrUpdateAllFromJson(RealmOrgCompany.class, jsonArray);
return null;
}).continueWithTask(task1 -> {
if (task1.isFaulted() || task1.getError() != null) {
RCLog.e( "organizationForMobile: result=" + task1.getError());
}
return null;
});
return null;
});
}
public Task<String> organizationUserForMobile(String type,String sessionId, String orgId){
return call("organizationUserForMobile", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("type", type);
param.put("sessionId", sessionId);
param.put("orgId", orgId);
return new JSONArray().put(param);
});
}
/**
* 结束会议
* */
public Task<String> forceEndMeeting(String rid,String userId){
return call("forceEndMeeting", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("userId", userId);
return new JSONArray().put(param);
});
}
/**
* 设置会议主持人
* */
public Task<String> setHost(String rid,String username){
return call("setHost", TIMEOUT_MS, () -> {
JSONObject param = new JSONObject();
param.put("rid", rid);
param.put("username", username);
return new JSONArray().put(param);
});
}
/**
*消息免打扰
* @param rid
* @param userId
* @param mnd
* @return
*/
public Task<String> roomMND(String rid,String userId,boolean mnd){
return call("roomMND",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("rid",rid);
param.put("userId",userId);
param.put("mnd",mnd);
return new JSONArray().put(param);
});
}
/**
* 群频道禁言
* @param rid
* @param readonly
* @return
*/
public Task<String> setReadonly(String rid,boolean readonly){
return call("setReadonly",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("rid",rid);
param.put("readonly",readonly);
return new JSONArray().put(param);
});
}
/**
* 删除或者退出
* @param rid
* @param username
* @param type
* @return
*/
public Task<String> deleteOrLeaveRoom(String rid,String username,int type){
return call("deleteOrLeaveRoom",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("rid",rid);
param.put("username",username);
param.put("type",type);
return new JSONArray().put(param);
});
}
/**
* setUserStatusForMobile(params)
userId, status,boolean
*/
public Task<String> setUserStatusForMobile(String userId,String status,boolean isPush){
return call("setUserStatusForMobile",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("userId",userId);
param.put("status",status);
param.put("boolean",isPush);// TODO 该接口需要调试
return new JSONArray().put(param);
});
}
/**
* {
"_id" : "4503a6584f9d4224993fcd17d4fdfd0a",
"token" : {
"gcm" : "a1d189278a194ae89b02cd6fc35a5bc6"
},
"appName" : "weiningPgy",
"userId" : "rdWH6n9vrwNkLFJGD",
}
*/
public Task<String> setUserPushTokenForMobile(String userId,String id,String gcmToken){
return call("setUserPushTokenForMobile",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("uuid",id);
param.put("userId",userId);
param.put("appName","weiningPgy");
JSONObject objStartDate = new JSONObject().put("gcm", gcmToken);
param.put("token", objStartDate);
return new JSONArray().put(param);
});
}
/**
*/
public Task<String> getFileClassify(String flag,String fileUrl,String fileName,String fileId,String userAccount){
return call("fileClassify",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("flag",flag);
param.put("fileUrl",fileUrl);
param.put("fileName",fileName);
param.put("fileId",fileId);//
param.put("userAccount",userAccount);
return new JSONArray().put(param);
});
}
/**
* userAccount String 会话id 是
name String 文件名 否 搜索时传
pageSize Int 当前页数 是 默认传20条
pageIndex Int 页码 是 第几页
*/
public Task<String> getFileClassifyList(String pageIndex,String pageSize,String name,String userAccount){
return call("classifyFileList",TIMEOUT_MS,()->{
JSONObject param=new JSONObject();
param.put("pageIndex",pageIndex);
param.put("pageSize",pageSize);
param.put("name",name);//
param.put("userAccount",userAccount);
return new JSONArray().put(param);
});
}
protected interface ParamBuilder {
JSONArray buildParam() throws JSONException;
}
public Task<Void> sendVideo(String url,
VideoSendMsgModel.MediaBean mediaBean,
String roomId,
VideoSendMsgModel.CalluserBean calluserBean,
String from, String warnmsg, String calltype, int av_type
) {
return call("stream-notify-user", TIMEOUT_MS, () ->
new JSONArray()
.put(url)
.put("false")
.put("call")
.put(new JSONObject()
.put("media",new JSONObject().put("video", mediaBean.isVideo()).put("audio", mediaBean.isAudio()))
.put("room", roomId)
.put("calluser",new JSONObject().put("username", calluserBean.getUsername()) .put("_id", calluserBean.get_id()))
.put("from", from)
.put("warnmsg", warnmsg)
.put("calltype", calltype)
.put("av_type", av_type)
.put("timestamp",System.currentTimeMillis())
)
).continueWithTask(task -> {
if (task.isFaulted()) {
Exception error = task.getError();
RCLog.d("come--------->>>>" + "error : " + error.toString());
} else {
String result = task.getResult();
}
return null;
}, Task.UI_THREAD_EXECUTOR);
}
public Task<Void> changeVideoOrAudioMsgStatusForMobile(String userId, String rid,
String status, String nType,
String time, String receiveUserId,
String mediaId) {
RCLog.d("come--------->>>>" + "changeVideoOrAudioMsgStatusForMobile:");
return call("changeVideoOrAudioMsgStatusForMobile", TIMEOUT_MS, () ->
new JSONArray().put(new JSONObject()
.put("userId", userId)
.put("rid", rid)
.put("status", status)
.put("nType", nType)
.put("time", time)
.put("receiveUserId", receiveUserId)
.put("mediaId", mediaId)
))
.continueWithTask(task -> {
if (task.isFaulted()) {
Exception error = task.getError();
RCLog.d("come--------->>>>" + "error : " + error.toString());
} else {
String result = null;
try {
result = task.getResult();
JSONObject jsonObject = new JSONObject(result);
/* if(ChatStatus.CANCEL.equals(jsonObject.getString("status"))){
TempFileUtils.getInstance()
.saveRecentVideoByMediaId(jsonObject.getString("mediaId"),jsonObject.getString("status"));
}*/
} catch (JSONException e) {
e.printStackTrace();
}
RCLog.d("come--------->>>>" + "changeVideoOrAudioMsgStatusForMobile result : " + result);
}
return null;
}, Task.UI_THREAD_EXECUTOR);
}
}
| 39.111036 | 144 | 0.523292 |
4a997dbbce956ac9635a8ec32e162c35ea85838c | 3,357 | package com.easypick.web.events.vo;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MovieDataVo {
private String shortDesc;
private String description;
private String thumbnail;
private String releaseDate;
private String tag;
private String cast;
private Integer movieId;
private String movieType;
private String certificate;
private String movieRate;
private String movieCode;
private String movieName;
private String languageName;
private Integer lang;
private List<GalleryDataVo> galleryData;
private List<CastDataVo> castData;
private List<VideoDataVo> videoData;
private List<ReviewDataVo> reviewData;
public List<ReviewDataVo> getReviewData() {
return reviewData;
}
public void setReviewData(List<ReviewDataVo> reviewData) {
this.reviewData = reviewData;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public Integer getMovieId() {
return movieId;
}
public void setMovieId(Integer movieId) {
this.movieId = movieId;
}
public String getMovieType() {
return movieType;
}
public void setMovieType(String movieType) {
this.movieType = movieType;
}
public String getCertificate() {
return certificate;
}
public void setCertificate(String certificate) {
this.certificate = certificate;
}
public String getMovieRate() {
return movieRate;
}
public void setMovieRate(String movieRate) {
this.movieRate = movieRate;
}
public String getMovieCode() {
return movieCode;
}
public void setMovieCode(String movieCode) {
this.movieCode = movieCode;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getLanguageName() {
return languageName;
}
public void setLanguageName(String languageName) {
this.languageName = languageName;
}
public Integer getLang() {
return lang;
}
public void setLang(Integer lang) {
this.lang = lang;
}
public List<GalleryDataVo> getGalleryData() {
return galleryData;
}
public void setGalleryData(List<GalleryDataVo> galleryData) {
this.galleryData = galleryData;
}
public List<CastDataVo> getCastData() {
return castData;
}
public void setCastData(List<CastDataVo> castData) {
this.castData = castData;
}
public List<VideoDataVo> getVideoData() {
return videoData;
}
public void setVideoData(List<VideoDataVo> videoData) {
this.videoData = videoData;
}
}
| 22.836735 | 63 | 0.70986 |
3b74f771993378e80e948c6415011194875ea7f7 | 1,633 | package org.batfish.representation.juniper;
import java.util.Collections;
import java.util.List;
import org.batfish.common.Warnings;
import org.batfish.common.util.CommonUtil;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.routing_policy.expr.InlineCommunitySet;
import org.batfish.datamodel.routing_policy.statement.SetCommunity;
import org.batfish.datamodel.routing_policy.statement.Statement;
public final class PsThenCommunitySet extends PsThen {
/** */
private static final long serialVersionUID = 1L;
private JuniperConfiguration _configuration;
private final String _name;
public PsThenCommunitySet(String name, JuniperConfiguration configuration) {
_name = name;
_configuration = configuration;
}
@Override
public void applyTo(
List<Statement> statements,
JuniperConfiguration juniperVendorConfiguration,
Configuration c,
Warnings warnings) {
CommunityList namedList = _configuration.getCommunityLists().get(_name);
if (namedList == null) {
warnings.redFlag("Reference to undefined community: \"" + _name + "\"");
} else {
org.batfish.datamodel.CommunityList list = c.getCommunityLists().get(_name);
String regex = list.getLines().get(0).getRegex();
// assuming this is a valid community list for setting, the regex value
// just retrieved should just be an explicit community
long community = CommonUtil.communityStringToLong(regex);
statements.add(new SetCommunity(new InlineCommunitySet(Collections.singleton(community))));
}
}
public String getName() {
return _name;
}
}
| 33.326531 | 97 | 0.749541 |
4cb693937ac0530605058e55c663b294f2e26e06 | 4,614 | package com.azhar.komik.fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.azhar.komik.R;
import com.azhar.komik.activities.ListGenreActivity;
import com.azhar.komik.adapter.AdapterGenre;
import com.azhar.komik.model.ModelGenre;
import com.azhar.komik.networking.ApiEndpoint;
import com.azhar.komik.utils.LayoutMarginDecoration;
import com.azhar.komik.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GenreFragment extends Fragment implements AdapterGenre.onSelectData {
private RecyclerView rvGenre;
private AdapterGenre adapterGenre;
private ProgressDialog progressDialog;
private LayoutMarginDecoration gridMargin;
private List<ModelGenre> modelGenre = new ArrayList<>();
public GenreFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_genre, container, false);
return rootView;
}
@Override
public void onViewCreated(@NonNull View rootView, @Nullable Bundle savedInstanceState) {
super.onViewCreated(rootView, savedInstanceState);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Mohon Tunggu");
progressDialog.setCancelable(false);
progressDialog.setMessage("Sedang menampilkan data");
rvGenre = rootView.findViewById(R.id.rvGenre);
rvGenre.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(),
3, RecyclerView.VERTICAL, false);
rvGenre.setLayoutManager(mLayoutManager);
gridMargin = new LayoutMarginDecoration(3, Tools.dp2px(getActivity(), 12));
rvGenre.addItemDecoration(gridMargin);
getGenre();
}
private void getGenre() {
progressDialog.show();
AndroidNetworking.get(ApiEndpoint.GENREURL)
.setPriority(Priority.HIGH)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
try {
progressDialog.dismiss();
JSONArray playerArray = response.getJSONArray("list_genre");
for (int i = 0; i < playerArray.length(); i++) {
JSONObject temp = playerArray.getJSONObject(i);
ModelGenre dataApi = new ModelGenre();
dataApi.setTitle(temp.getString("title"));
dataApi.setEndpoint(temp.getString("endpoint"));
modelGenre.add(dataApi);
showGenre();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Gagal menampilkan data!", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(ANError anError) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Tidak ada jaringan internet!", Toast.LENGTH_SHORT).show();
}
});
}
private void showGenre() {
adapterGenre = new AdapterGenre(getActivity(), modelGenre, this);
rvGenre.setAdapter(adapterGenre);
}
@Override
public void onSelected(ModelGenre modelGenre) {
Intent intent = new Intent(getActivity(), ListGenreActivity.class);
intent.putExtra("listGenre", modelGenre);
startActivity(intent);
}
}
| 38.773109 | 114 | 0.627221 |
c620b43558eb9c3d95aa4578d224a53a695a1629 | 896 | package com.intuit.karate.junit4.syntax;
import com.intuit.karate.Runner;
import java.util.Collections;
import org.junit.Test;
/**
*
* @author pthomas3
*/
public class SyntaxPerfRunner {
@Test
public void testPerf() {
System.setProperty("karate.env", "foo");
long startTime = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Runner.runFeature(getClass(), "syntax.feature", Collections.EMPTY_MAP, true);
}
long elapsedTime = System.currentTimeMillis() - startTime;
System.out.println("elapsed time: " + elapsedTime);
// 25.5 seconds for git 76c92bd
// 14.0 seconds after refactoring
// 11.0 seconds after second wave git 20445d5
// 9.0 seconds on new mac 6795ae8
}
public static void main(String[] args) {
new SyntaxPerfRunner().testPerf();
}
}
| 27.151515 | 89 | 0.620536 |
915c06bb33c4d10cef287178c54a30ed59c6f460 | 708 | package com.zhidiantech.orangesample.frametest.flowsence.morebs;
import com.zhidiantech.orangesample.frametest.base.IBaseView;
/**
* -----------------------------------------------------------------
* Copyright (C) 芝点科技 wen
* -----------------------------------------------------------------
* Create: 2019/1/3 下午12:54
* Changes (from 2019/1/3)
* -----------------------------------------------------------------
*/
public interface UploadPhotoContract {
interface IPresenter {
void uploadPhoto();
}
interface IView extends IBaseView{
void onUploadPhotoSuccess();
void onUploadPhotoError();
}
interface IModel{
void uploadPhotoFile();
}
}
| 24.413793 | 68 | 0.481638 |
e1e1c83c0f79e80fb3da109025d0921c2d212487 | 2,671 | package io.qt.example.splitapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Keep;
import android.view.View;
import android.view.View.OnSystemUiVisibilityChangeListener;
import org.qtproject.qt5.android.bindings.QtActivity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class AndroidQtActivity extends QtActivity {
// Activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
enterFullscreenMode();
initSystemUiVisibilityListener();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
enterFullscreenMode();
}
// Called from C++
@Keep // nativeCall
@SuppressWarnings("unused")
public byte[] nativeCallLoadRccResource(String resourceName) {
int resourceId = getResources().getIdentifier(resourceName, "raw", getPackageName());
if (resourceId == 0) {
return new byte[0];
}
InputStream inputStream = getResources().openRawResource(resourceId);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size;
byte[] buffer = new byte[1024];
try {
while ((size = inputStream.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
inputStream.close();
} catch (IOException exception) {
return new byte[0];
}
return outputStream.toByteArray();
}
// Private
private void initSystemUiVisibilityListener() {
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new OnSystemUiVisibilityChangeListener() {
@Override public void onSystemUiVisibilityChange(int visibility) {
if (visibility == 0) {
enterFullscreenMode();
}
}
}
);
}
}
private void enterFullscreenMode() {
if (Build.VERSION.SDK_INT >= 19) {
int uiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(uiVisibility);
}
}
}
| 29.351648 | 119 | 0.625608 |
fdd5cc062b40a623548ab73202764c1ca377cb02 | 1,279 | package org.luvx.message.mail;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.luvx.fund.util.MarkdownUtils;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.google.common.io.Files;
import lombok.SneakyThrows;
@ExtendWith(SpringExtension.class)
@SpringBootTest
class MailServiceTest {
@Resource
private MailService mailService;
@SneakyThrows
@Test
void sendSimpleMail() {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setSubject("title");
mail.setText("test test");
// mailService.sendSimpleMail(mail);
String path = "";
List<String> lines = Files.readLines(new File(path), StandardCharsets.UTF_8);
String md = lines.stream().collect(Collectors.joining("\n"));
String html = MarkdownUtils.markdown2Html1(md);
mail.setText(html);
mailService.sendHtmlMail(mail);
}
@Test
void sendHtmlMail() {
}
} | 27.212766 | 85 | 0.727131 |
113ebfa915536851dce2ec89d593e56f661c5dea | 8,009 | package com.jusenr.androidgithub.home.ui.activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jusenr.androidgithub.R;
import com.jusenr.androidgithub.base.PTActivity;
import com.jusenr.androidgithub.guidance.AboutUsActivity;
import com.jusenr.androidgithub.home.ui.fragment.MineFragment;
import com.jusenr.androidgithub.home.ui.fragment.MostStarFragment;
import com.jusenr.androidgithub.home.ui.fragment.TrendingContainerFragment;
import com.jusenr.androidgithub.user.ui.activity.SettingsActivity;
import com.jusenr.androidgithub.user.ui.activity.UserActivity;
import com.jusenr.androidgithub.utils.AccountHelper;
import com.jusenr.androidgithub.utils.Constants;
import com.jusenr.androidgithub.utils.SharePlatform;
import com.jusenr.androidlibrary.widgets.fresco.FrescoImageView;
import com.jusenr.androidlibrary.widgets.scrollview.PTSlidingMenu;
import com.jusenr.toolslibrary.utils.StringUtils;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Description:
* Copyright : Copyright (c) 2017
* Email : jusenr@163.com
* Author : Jusenr
* Date : 2017/09/30
* Time : 17:10
* Project :androidgithub.
*/
public class MainActivity extends PTActivity {
@BindView(R.id.ptslidemenu_layout)
PTSlidingMenu mPTSlideMenu;
@BindView(R.id.iv_user_icon)
FrescoImageView mIvUserIcon;
@BindView(R.id.tv_username)
TextView mTvUsername;
@BindView(R.id.account_view)
LinearLayout mAccountView;
@BindView(R.id.tv_history)
TextView mTvHistory;
@BindView(R.id.tv_share_app)
TextView mTvShareApp;
@BindView(R.id.tv_feedback)
TextView mTvFeedback;
@BindView(R.id.tv_settings)
TextView mTvSettings;
@BindView(R.id.tv_about_us)
TextView mTvAboutUs;
@BindView(R.id.tv_loginout)
TextView mTvLoginout;
@BindView(R.id.toolbar)
Toolbar mToolbar;
@BindView(R.id.fl_content)
FrameLayout mFlContent;
private FragmentManager mFragmentManager = getFragmentManager();
private Fragment mCurrentFragment;
private BottomBar mBottomBar;
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void onViewCreated(@Nullable Bundle savedInstanceState) {
mBottomBar = BottomBar.attach(this, savedInstanceState);
initViews();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mBottomBar.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
startActivity(new Intent(this, SearchActivity.class));
return true;
case android.R.id.home:
mPTSlideMenu.toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
mPTSlideMenu.requestLayout();
}
@Override
protected void onPause() {
super.onPause();
if (mPTSlideMenu.isOpen()) {
mPTSlideMenu.closeMenu();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
if (mPTSlideMenu.isOpen()) {
mPTSlideMenu.toggle(false);
return true;
}
return exit(2000);
}
return super.onKeyDown(keyCode, event);
}
@OnClick({R.id.account_view, R.id.tv_history, R.id.tv_share_app, R.id.tv_feedback, R.id.tv_settings, R.id.tv_about_us, R.id.tv_loginout})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.account_view:
Intent intent = new Intent(this, UserActivity.class);
mBundle.clear();
mBundle.putSerializable(Constants.BundleKey.BUNDLE_USER_NAME, AccountHelper.getNickname());
intent.putExtras(mBundle);
startActivity(intent);
break;
case R.id.tv_history:
break;
case R.id.tv_share_app:
SharePlatform.share(this);
break;
case R.id.tv_feedback:
break;
case R.id.tv_settings:
startActivity(new Intent(this, SettingsActivity.class));
break;
case R.id.tv_about_us:
startActivity(new Intent(this, AboutUsActivity.class));
break;
case R.id.tv_loginout:
AccountHelper.logout();
finish();
break;
}
}
private void initViews() {
mPTSlideMenu.requestDisallowInterceptTouchEvent(true);
mToolbar.setNavigationIcon(R.mipmap.menu);
setSupportActionBar(mToolbar);
mBottomBar.setItems(R.menu.bottombar_menu);
mBottomBar.setOnMenuTabClickListener(mTabClickListener);
String avatar = AccountHelper.getAvatar();
String nickname = AccountHelper.getNickname();
if (!StringUtils.isEmpty(avatar)) {
mIvUserIcon.setImageURL(avatar + ".png");
}
if (!StringUtils.isEmpty(nickname)) {
mTvUsername.setText(nickname);
}
}
private OnMenuTabClickListener mTabClickListener = new OnMenuTabClickListener() {
@Override
public void onMenuTabSelected(@IdRes int menuItemId) {
changeTitle(menuItemId);
switchMenu(getFragmentName(menuItemId));
}
@Override
public void onMenuTabReSelected(@IdRes int menuItemId) {
}
};
private void switchMenu(String fragmentName) {
Fragment fragment = mFragmentManager.findFragmentByTag(fragmentName);
if (fragment != null) {
if (fragment == mCurrentFragment) return;
mFragmentManager.beginTransaction().show(fragment).commit();
} else {
fragment = Fragment.instantiate(this, fragmentName);
mFragmentManager.beginTransaction().add(R.id.fl_content, fragment, fragmentName).commit();
}
if (mCurrentFragment != null) {
mFragmentManager.beginTransaction().hide(mCurrentFragment).commit();
}
mCurrentFragment = fragment;
}
private String getFragmentName(int menuId) {
switch (menuId) {
case R.id.menu_trending:
return TrendingContainerFragment.class.getName();
case R.id.menu_most_stars:
return MostStarFragment.class.getName();
case R.id.menu_account:
return MineFragment.class.getName();
default:
return null;
}
}
private void changeTitle(int menuId) {
switch (menuId) {
case R.id.menu_trending:
setTitle(R.string.menu_trending);
break;
case R.id.menu_most_stars:
setTitle(R.string.menu_most_star);
break;
case R.id.menu_account:
setTitle(R.string.menu_account);
break;
default:
break;
}
}
}
| 31.656126 | 141 | 0.645274 |
7aa4a415532b53cc016a441054c79719e20ad18a | 700 | package com.highjet.common.modules.wechat.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 消息父类
* @ClassName: BaseMessage
* @Description: TODO(消息父类)
* @author zhaojian.zheng
* @date 2019年6月21日 上午10:19:27
*
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseMessage {
//成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送
private String touser;
//部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
private String toparty;
//标签ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
private String toTag;
// 是 消息类型
private String msgtype;
// 是 企业应用的id,整型。可在应用的设置页面查看
private int agentid;
}
| 21.212121 | 66 | 0.731429 |
44191a23f6fea050fd9cd6bada4b90ea0d2e9573 | 383 | /*
* @author Anshul Saraf
*/
package kushina.repository;
import kushina.model.team.TeamDTO;
import kushina.model.team.TeamDoc;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TeamRepository extends MongoRepository<TeamDoc, String> {
TeamDTO findByNameEnglish(String name);
}
| 23.9375 | 74 | 0.81201 |
eaa3b652234fad31e3db5cccdbd6c3b0fc66570b | 377 | import org.jetbrains.annotations.Contract;4
class CompoundAssignmentSideEffect {
int k;
void m() {
pureCall(nonPureCall1(), nonPureCall2()).b &= true<caret>;
}
@Contract(pure = true)
X pureCall(int i, int j) {
return new X();
}
int nonPureCall1() {
return k;
}
int nonPureCall2() {
return k;
}
class X {
boolean b = false;
}
} | 13.962963 | 62 | 0.604775 |
451cefbd1b61c45ddb8d4e5f4bdd34d0ee621a76 | 2,423 | /*
Copyright 2008-2009 Christian Vest Hansen
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 net.nanopool;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Test;
/**
*
* @author cvh
*/
public class ConcurrentResizingTest extends NanoPoolTestBase {
@Test public void
mustBePossibleToGetConnectionWhilePoolIsBeingResized() throws Exception {
final int threadCount = 5;
pool = npds();
final NanoPoolDataSource fpool = pool;
final long stopTime = System.currentTimeMillis() + 200;
final AtomicReference<SQLException> sqleRef = new AtomicReference<SQLException>();
final CountDownLatch stopLatch = new CountDownLatch(threadCount);
Thread[] ths = new Thread[threadCount];
for (int i = 0; i < ths.length; i++) {
ths[i] = new Thread(new Runnable() {
public void run() {
Connection con = null;
while (System.currentTimeMillis() < stopTime) {
try {
con = fpool.getConnection();
} catch (SQLException sqle) {
sqle.printStackTrace();
sqleRef.set(sqle);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
stopLatch.countDown();
}
}, "TesterThread-" + (i + 1));
}
for (Thread th : ths) {
th.start();
}
CheapRandom rnd = new CheapRandom();
while (System.currentTimeMillis() < stopTime) {
fpool.resizePool(rnd.nextAbs(threadCount, threadCount * 3));
}
stopLatch.await();
SQLException sqle = sqleRef.get();
if (sqle != null) {
throw sqle;
}
}
}
| 29.91358 | 86 | 0.617416 |
85e43d2e0e23ede4bf62f01b78d08b6e2a64672f | 5,515 | package com.hk.goffer.ui.cview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import com.hk.goffer.R;
/**
* Created by hankang on 2015/9/26 19:17.
*/
/*
问题点: 1。关于footerView的添加时机,需要在adapter设置之前
2。因为每一次的动作都是依靠一对独立的Y值,因此当加载完成一次之后需要将Y值清零,这样也有利于滑动到底部自动加载
3. ListView是第二个孩子
4. onLayout只有在子元素为0时调用一次,其他方法下多次调用,而且只有在onLayout下才能正确得到子view,因此
为了保证在onLayout中做的初始化只执行一次,必须进行判空
*/
public class RefreshLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {
/**
* 子元素中的ListView
*/
private ListView mListView;
/**
* 用于显示下拉加载(加载更多)的View,作为ListView的footerView
*/
/**
* 记录手指的上滑还是下滑
*/
private int mStartY;
private int mEndY;
/**
* 是否下拉内容正在加载
*/
private boolean mIsLoading;
/**
* 防抖动的距离
*/
private int mTouchSlop;
private OnPullUpListener mPullUpListener;
private ViewGroup mFooterView;
private View tvLoadMore;
private View pbLoading;
private View tvLoadingTip;
public RefreshLayout(Context context) {
this(context, null);
}
public RefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mFooterView = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.refresh_footer, null, false);
tvLoadMore = mFooterView.findViewById(R.id.footer_more);
pbLoading = mFooterView.findViewById(R.id.footer_bar);
tvLoadingTip = mFooterView.findViewById(R.id.footer_tip); // 用于设置底部提示文字和进度条的可见性逻辑
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// 因为onLayout会调用多次,因此为了节省不必要的操作消耗,只有在mListView为null的时候才进行查找
// 这个问题是由于不了解onLayout的机制和addFooter的覆盖而引起的
if (mListView == null) { // 这个判断是否非常必要的,详细上面的描述
initListView();
}
}
/**
* 设置ListView,设置滑动到底部是自动加载
*/
private void initListView() {
if (getChildCount() > 0) {
View childView = getChildAt(0); // 强制必须是ListView,这里应该谨慎一点判断,因为默认有圆形的加载条,因此ListView是第二个孩子而不是肉眼砍刀的第一个孩子
if (!(childView instanceof ListView)) {
throw new ExceptionInInitializerError("The child must be listView");
}
mListView = (ListView) childView;
// ListView本身而言,addHeaderView和addFooter必须在setAdapter之前添加,否则会报错,这两种view不算在adapter内
setFooterViewVisibility(false);
mListView.addFooterView(mFooterView);
//设置自动滑动到底部的时候也进行加载
mListView.setOnScrollListener(this);
}
}
/**
* 设置底部的可见性
*
* @param visible
*/
private void setFooterViewVisibility(boolean visible) {
tvLoadMore.setVisibility(visible?INVISIBLE:VISIBLE);
pbLoading.setVisibility(visible?VISIBLE:INVISIBLE);
tvLoadingTip.setVisibility(visible?VISIBLE:INVISIBLE);
}
@Override
public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mStartY = (int) ev.getRawY(); // getRawY是获取屏幕中的坐标,get是Y获取View左上角为原点的坐标
break;
case MotionEvent.ACTION_MOVE:
mEndY = (int) ev.getRawY();
break;
case MotionEvent.ACTION_UP:
if (canLoad()) {
loadData();
}
break;
}
return super.dispatchTouchEvent(ev);
}
private void loadData() {
//处理动画,调用监听器来处理外部事件
if (mPullUpListener != null) {
setPullUpLoading(true); // 显示加载动画
mPullUpListener.onPullUp();
}
}
/**
* 设置一下加载的动画,或移除加载动画,可供外部调用停止加载动画
*/
public void setPullUpLoading(boolean isLoading) {
mIsLoading = isLoading;
if (isLoading) {
setFooterViewVisibility(true); // 结合ListView的Adapter,这里
} else {
setFooterViewVisibility(false); // 表示加载完成的时候手指触摸的位置Y一定要归0
mStartY = 0;
mEndY = 0;
}
}
/**
* 判断是否可以加载数据了
*
* @return d
*/
private boolean canLoad() {
// 底部+ 上滑+ 不在加载状态
return isPullUp() && isBottom() && !mIsLoading;
}
private boolean isBottom() {
return mListView != null && mListView.getLastVisiblePosition() == mListView.getCount() - 1;
}
private boolean isPullUp() {
return mTouchSlop != 0 && mStartY - mEndY > 2*mTouchSlop; // 1倍距离有点短
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// 滑动过程中来判断是否可以加载更多:上滑+底部
if (canLoad()) {
loadData();
}
}
public void setOnPullUpListener(OnPullUpListener listener) {
mPullUpListener = listener;
}
public interface OnPullUpListener {
void onPullUp();
}
}
| 27.167488 | 113 | 0.631913 |
48ee1e90ff775007b2cd8b5d8c892ecf6a454d07 | 1,104 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package AQSaga;
import javax.jms.JMSException;
/**
*
* @author pnavaney
*/
public interface Osaga {
public String beginSaga(String initiator_name) throws JMSException;
public String beginSaga(String initiator_name, int timeout) throws JMSException;
public String beginSaga(String initiator_name, int timeout, int version) throws JMSException;
public void rollbackSaga(String sagaId, String participant_name) throws JMSException;
public void rollbackSaga(String sagaId, String participant_name, boolean force) throws JMSException;
public void commitSaga(String sagaId, String participant_name, boolean force) throws JMSException;
public void commitSaga(String sagaId, String participant_name) throws JMSException;
public void forgetSaga(String sagaId);
public void leaveSaga(String sagaId);
public void afterSaga(String sagaId);
}
| 29.052632 | 104 | 0.749094 |
0598c52903bcd814a605adb3cb2260bf4d82960b | 2,391 | package teamEarth.homeSchoolHelper.configs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
return bCryptPasswordEncoder;
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
// all ^^^ is necessary boilerplate wiring
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.cors().disable()
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/about").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/newuser").permitAll()
.antMatchers("/css/*", "/graphics/*", "/js/*").permitAll() // and here for more info https://stackoverflow.com/questions/25368535/spring-security-does-not-allow-css-or-js-resources-to-be-loaded
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/myprofile") // the
// .failureUrl("/user")
.and()
.logout(); // this then creates a built-in default logout route at /logout.
}
} | 45.113208 | 210 | 0.684233 |
09ac9b77769db8b5428742f8b2c7a42c3ff54d3d | 1,822 | package com.song;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.song.saber.common.http.HttpUtil;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
/**
* Created by 001844 on 2018/5/5.
*/
public class QZoneTest {
public static int pos = 0;
public static int total = 425;
public static void main(String[] args) throws IOException {
File file = new File("qzone.txt");
String url = "https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6?uin=504252262&ftype=0&sort=0&replynum=100&callback=_preloadCallback&code_version=1&format=jsonp&need_private_comment=1&qzonetoken=37668506047b380a02f7c1b03857a4d3a0890084713830a7b8f822cc2eb7ae34c0b77527a9ffc704ef&g_tk=852835650&num=40";
while (total > 0) {
String posStr = "&pos=" + pos;
String url2 = url + posStr;
String str = HttpUtil.get(url2);
proc(str, file);
}
}
public static void proc(String str, File file) throws IOException {
int si = str.indexOf("(");
int ei = str.lastIndexOf(")");
String jsonStr = str.substring(si + 1, ei);
JSONObject jo = JSON.parseObject(jsonStr);
JSONArray jar = (JSONArray) jo.get("msglist");
pos += jar.size();
total = total - jar.size();
for (int i = 0; i < jar.size(); i++) {
JSONObject jsonObject = (JSONObject) jar.get(i);
String content = (String) jsonObject.get("content");
String createTime = (String) jsonObject.get("createTime");
String result = "#### " + createTime + "\r\n" + content + "\r\n";
FileUtils.write(file, result, "UTF-8", true);
}
}
}
| 35.72549 | 342 | 0.637212 |
3f0e2911309b7052535604ebf78a0b42e2216072 | 1,149 | package com.chutneytesting.environment.api.dto;
import static java.util.Collections.emptyList;
import static java.util.Optional.ofNullable;
import com.chutneytesting.environment.domain.Environment;
import java.util.List;
import java.util.stream.Collectors;
public class EnvironmentDto {
public String name;
public String description;
public List<TargetDto> targets;
public static EnvironmentDto from(Environment environment) {
EnvironmentDto environmentMetadataDto = new EnvironmentDto();
environmentMetadataDto.name = environment.name;
environmentMetadataDto.description = environment.description;
environmentMetadataDto.targets = environment.targets.stream().map(TargetDto::from).collect(Collectors.toList());
return environmentMetadataDto;
}
public Environment toEnvironment() {
return Environment.builder()
.withName(name)
.withDescription(description)
.withTargets(
ofNullable(targets).orElse(emptyList()).stream().map(t -> t.toTarget(name)).collect(Collectors.toSet())
)
.build();
}
}
| 33.794118 | 120 | 0.708442 |
76a5060037f6acca6b9969a6a92af471b4d48ac8 | 412 | /*
* Copyright 2020, Backblaze Inc. All Rights Reserved.
* License https://www.backblaze.com/using_b2_code.html
*/
package com.backblaze.b2.client.structures;
/**
* B2LegalHold provides constants for file lock legal hold
*/
public interface B2LegalHold {
/**
* Legal hold is on (enabled)
*/
String ON = "on";
/**
* Legal hold is off (disabled)
*/
String OFF = "off";
}
| 19.619048 | 58 | 0.633495 |
560d4640b2e3c074042552fc1ffbd3814f7eada8 | 6,973 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kuujo.vertigo.util;
import net.kuujo.vertigo.Context;
import net.kuujo.vertigo.component.ComponentContext;
import net.kuujo.vertigo.component.InstanceContext;
import net.kuujo.vertigo.io.IOContext;
import net.kuujo.vertigo.io.InputContext;
import net.kuujo.vertigo.io.OutputContext;
import net.kuujo.vertigo.io.port.InputPortContext;
import net.kuujo.vertigo.io.port.OutputPortContext;
import net.kuujo.vertigo.network.NetworkContext;
import net.kuujo.vertigo.util.serialization.SerializerFactory;
import io.vertx.core.json.JsonObject;
/**
* Context serialization helpers.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class Contexts {
/**
* Serializes a context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(Context<?> context) {
if (context instanceof NetworkContext) {
return serialize(NetworkContext.class.cast(context));
} else if (context instanceof ComponentContext) {
return serialize(ComponentContext.class.cast(context));
} else if (context instanceof InstanceContext) {
return serialize(InstanceContext.class.cast(context));
} else if (context instanceof IOContext) {
return serialize(IOContext.class.cast(context));
} else if (context instanceof InputPortContext) {
return serialize(InputPortContext.class.cast(context));
} else if (context instanceof OutputPortContext) {
return serialize(OutputPortContext.class.cast(context));
} else {
throw new UnsupportedOperationException("Cannot serialize " + context.getClass().getCanonicalName() + " type contexts");
}
}
/**
* Serializes a network context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(NetworkContext context) {
return serialize(context.uri(), context);
}
/**
* Serializes a component context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(ComponentContext<?> context) {
return serialize(context.uri(), context.network());
}
/**
* Serializes an instance context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(InstanceContext context) {
return serialize(context.uri(), context.component().network());
}
/**
* Serializes an I/O context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(IOContext<?> context) {
return serialize(context.uri(), context.instance().component().network());
}
/**
* Serializes an input port context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(InputPortContext context) {
return serialize(context.uri(), context.input().instance().component().network());
}
/**
* Serializes an output port context to JSON.
*
* @param context The context to serialize.
* @return The serialized context.
*/
public static JsonObject serialize(OutputPortContext context) {
return serialize(context.uri(), context.output().instance().component().network());
}
private static JsonObject serialize(String uri, NetworkContext context) {
return new JsonObject()
.putString("uri", uri)
.putObject("context", SerializerFactory.getSerializer(Context.class).serializeToObject(context));
}
/**
* Deserializes a context from JSON.
*
* @param context The serialized context.
* @return The deserialized context.
*/
public static <T extends Context<T>> T deserialize(JsonObject context) {
return deserialize(context.getString("uri"), context.getObject("context"));
}
@SuppressWarnings("unchecked")
private static <T extends Context<T>> T deserialize(String uri, JsonObject context) {
ContextUri curi = new ContextUri(uri);
NetworkContext network = SerializerFactory.getSerializer(Context.class).deserializeObject(context, NetworkContext.class);
if (!curi.getCluster().equals(network.cluster()) || !curi.getNetwork().equals(network.name())) {
throw new IllegalArgumentException("The given URI does not match the given context configuration");
}
if (curi.hasComponent()) {
ComponentContext<?> component = network.component(curi.getComponent());
if (component == null) {
throw new IllegalArgumentException("The URI component " + curi.getComponent() + " does not exist in the given network configuration");
}
if (curi.hasInstance()) {
InstanceContext instance = component.instance(curi.getInstance());
if (instance == null) {
throw new IllegalArgumentException("The URI instance " + curi.getInstance() + " does not exist in the given component configuration");
}
if (curi.hasEndpoint()) {
switch (curi.getEndpoint()) {
case ContextUri.ENDPOINT_IN:
InputContext input = instance.input();
if (curi.hasPort()) {
InputPortContext inPort = input.port(curi.getPort());
if (inPort == null) {
throw new IllegalArgumentException("The URI port " + curi.getPort() + " does not exist in the given input configuration");
}
return (T) inPort;
}
return (T) input;
case ContextUri.ENDPOINT_OUT:
OutputContext output = instance.output();
if (curi.hasPort()) {
OutputPortContext outPort = output.port(curi.getPort());
if (outPort == null) {
throw new IllegalArgumentException("The URI port " + curi.getPort() + " does not exist in the given output configuration");
}
return (T) outPort;
}
return (T) output;
default:
throw new IllegalArgumentException("The URI endpoint " + curi.getEndpoint() + " is not a valid endpoint type");
}
}
return (T) instance;
}
return (T) component;
}
return (T) network;
}
}
| 36.7 | 144 | 0.674172 |
eb99126cae050d69e0641d76c32c654bc1638387 | 591 | package br.com.renanfretta.pc.plataformacomunicacao.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Repository;
import br.com.renanfretta.pc.plataformacomunicacao.entities.FormatoMensagem;
@Repository
public interface FormatoMensagemRepository extends JpaRepository<FormatoMensagem, Long>, JpaSpecificationExecutor<FormatoMensagem>, QuerydslPredicateExecutor<FormatoMensagem> {
}
| 42.214286 | 176 | 0.876481 |
4d8ee5752ff0a4926b21a558a3ab41578485aaae | 171 | package net.alenzen.intelHex;
public class ValidationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 8737374532913228983L;
}
| 15.545455 | 67 | 0.754386 |
6650410e015163fd4186acc1ce2666b1389c1a21 | 6,716 | package breaker;
import iut.Audio;
import iut.Objet;
import iut.ObjetTouchable;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
/**
* Objet de soutient que le joueur peut rammasser au cours du jeu qui invoque un pokémon qui aide le joueur
* @author Islem Yahiaoui, Alan Gouvernet, Mouhouni Chakrina, Wout Heijnen, Ibrahim, Zouhairi
*/
public class Pokeball extends ObjetTouchable {
private Ennemi e;
private Joueur j;
private Joueur2 j2;
private int x;
private int y;
private GestionMap gestion;
private int pv;
public Pokeball(Ennemi source, int xx, int yy, GestionMap actualisation){
super(source.game(),"pokeball",xx ,yy);
gestion = actualisation;
j = gestion.getPlayer();
j2 = gestion.getPlayer2();
x = xx;
y = yy;
pv = 5;
}
/**
* Action : effet d'une collision entre l'objet et le paramètre
* gestion de l'IA
* grâce à une variable aléatoire, on détermine quelle pokemon va être contenu dans la pokeball
*/
public void effect(Objet o) {
if((o == j) || (o == j2 && o != null)){
if(!gestion.isPokeballActive()){
Random alea;
alea = new Random();
int aleatoire = alea.nextInt(1659);
aleatoire ++;
if(aleatoire >= 1 && aleatoire <= 190){
Fantominus fantominus = new Fantominus(game(), x, y, gestion);
game().add(fantominus);
}
if(aleatoire >= 191 && aleatoire <= 280){
Spectrum spectrum = new Spectrum(game(), x, y, gestion);
game().add(spectrum);
}
if(aleatoire >= 281 && aleatoire <= 325){
Ectoplasma ectoplasma = new Ectoplasma(game(), x, y, gestion);
game().add(ectoplasma);
}
if(aleatoire >= 326 && aleatoire <= 455){
Ptiravi ptiravi = new Ptiravi(game(), x, y, gestion);
game().add(ptiravi);
}
if(aleatoire >= 456 && aleatoire <= 480){
Leveinard leveinard = new Leveinard(game(), x, y, gestion);
game().add(leveinard);
}
if(aleatoire >= 481 && aleatoire <= 515){
Leuphorie leuphorie = new Leuphorie(game(), x, y, gestion);
game().add(leuphorie);
}
if(aleatoire >= 516 && aleatoire <= 770){
Miaouss miaouss = new Miaouss(game(), x, y, gestion);
game().add(miaouss);
}
if(aleatoire >= 771 && aleatoire <= 860){
Persian persian = new Persian(game(), x, y, gestion);
game().add(persian);
}
if(aleatoire >= 861 && aleatoire <= 920){
Electrode electrode = new Electrode(game(), x, y, gestion);
game().add(electrode);
}
if(aleatoire >= 921 && aleatoire <= 945){
Ronflex ronflex = new Ronflex(game(), x, y, gestion);
game().add(ronflex);
}
if(aleatoire >= 946 && aleatoire <= 948){
Sulfura sulfura = new Sulfura(game(), x, y, gestion);
game().add(sulfura);
}
if(aleatoire >= 949 && aleatoire <= 951){
Lugia lugia = new Lugia(game(), x, y, gestion);
game().add(lugia);
}
if(aleatoire >= 952 && aleatoire <= 1186){
Tarsal tarsal = new Tarsal(game(), x, y, gestion);
game().add(tarsal);
}
if(aleatoire >= 1187 && aleatoire <= 1306){
Kirlia kirlia = new Kirlia(game(), x, y, gestion);
game().add(kirlia);
}
if(aleatoire >= 1307 && aleatoire <= 1351){
Gardevoir gardevoir = new Gardevoir(game(), x, y, gestion);
game().add(gardevoir);
}
if(aleatoire >= 1352 && aleatoire <= 1354){
Terhal terhal = new Terhal(game(), x, y, gestion);
game().add(terhal);
}
if(aleatoire >= 1355 && aleatoire <= 1357){
Metang metang = new Metang(game(), x, y, gestion);
game().add(metang);
}
if(aleatoire >= 1358 && aleatoire <= 1360){
Metalosse metalosse = new Metalosse(game(), x, y, gestion);
game().add(metalosse);
}
if(aleatoire >= 1361 && aleatoire <= 1615){
Magicarpe magicarpe = new Magicarpe(game(), x, y, gestion);
game().add(magicarpe);
}
if(aleatoire >= 1616 && aleatoire <= 1660){
Leviator leviator = new Leviator(game(), x, y, gestion);
game().add(leviator);
}
aleatoire = alea.nextInt(100);
j.changeScore(aleatoire);
}
game().remove(this);
}
if(o.isEnnemy()){
pv --;
if(pv<=0){
game().remove(this);
}
}
}
/**
* @return true si l'objet est un "ami" du joueur
*/
public boolean isFriend() {
return true;
}
/**
* @return false si l'objet est un "ennemi" du joueur
*/
public boolean isEnnemy() {
return false;
}
/**
* Déplace l'objet
* @param dt le temps écoulé en millisecondes depuis le précédent déplacement
*/
public void move(long dt) {
if(dt>=10000){
game().remove(this);
}
if(estSorti()){
game().remove(this);
}
}
public void explosion(){
}
public void crier(){
}
public void tirer(){
}
/**
* indique si le tir est "à l'intérieur" de l'écran ou non
* @return true si le tir a quitté l'écran (par le bas)
*/
private boolean estSorti() {
return getTop()>game().height()-80 || getLeft()<80 || getTop()<80 || getRight()>game().getWidth()-80;
}
} | 35.914439 | 114 | 0.449821 |
b9a05d21fd905af975a0e7464e44f38402d86025 | 26,819 | /*
*
* Copyright 2004 Cordys R&D B.V.
*
* This file is part of the Cordys JMS Connector.
*
* 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.cordys.coe.ac.jmsconnector;
import com.cordys.coe.ac.jmsconnector.exceptions.JMSConnectorException;
import com.eibus.util.Base64;
import com.eibus.xml.nom.Node;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
/**
* DOCUMENTME
* .
*
* @author awisse
*/
public class JMSUtil
{
/**
* Appends extra parameters to a dynamic destination URL. The format of this URL is provider
* specific and probably not supported by all providers. Currently this method is hard-coded for
* WebSphere MQ.
*
* @param sPhysicalName Physical URL of the destination.
* @param dDest Dynamic JMSConnector destination.
* @param sParamString Extra parameters as configured in the connector configuration page.
*
* @return
*/
public static String appendDynamicDestinationParameters(String sPhysicalName, Destination dDest,
String sParamString)
{
if ((sParamString == null) || (sParamString.length() == 0))
{
return sPhysicalName;
}
// Parse them in to a hash map, so later we can do parameter merging.
Map<String, String> mParams = new HashMap<String, String>();
String[] saTmpArray = sParamString.split(",");
for (String sTmp : saTmpArray)
{
int iPos = sTmp.indexOf('=');
String sName;
String sValue;
if (iPos > 0)
{
sName = sTmp.substring(0, iPos).trim();
sValue = ((iPos < (sTmp.length() - 1)) ? sTmp.substring(iPos + 1).trim() : "");
}
else
{
sName = sTmp;
sValue = null;
}
mParams.put(sName, sValue);
}
// Discard the possible query part from the physical name.
int iPos = sPhysicalName.indexOf('?');
if (iPos >= 0)
{
sPhysicalName = sPhysicalName.substring(0, iPos);
}
StringBuilder sbRes = new StringBuilder(100);
boolean bFirst = true;
sbRes.append(sPhysicalName);
for (Map.Entry<String, String> eEntry : mParams.entrySet())
{
if (bFirst)
{
sbRes.append('?');
bFirst = false;
}
else
{
sbRes.append('&');
}
String sName = eEntry.getKey();
String sValue = eEntry.getValue();
sbRes.append(sName);
if (sValue != null)
{
sbRes.append('=');
sbRes.append(sValue);
}
}
return sbRes.toString();
}
/**
* DOCUMENTME.
*
* @param str DOCUMENTME
*
* @return DOCUMENTME
*/
public static byte[] base64decode(String str)
{
return Base64.decode(str.toCharArray());
}
/**
* DOCUMENTME.
*
* @param data DOCUMENTME
*
* @return DOCUMENTME
*/
public static String base64encode(byte[] data)
{
return new String(Base64.encode(data));
}
/**
* Finds the cause of an exception.
*
* @param t the exception to look for the cause
*
* @return the cause
*/
public static String findCause(Throwable t)
{
String msg = t.getMessage();
if (((msg == null) || "".equals(msg)) && (t.getCause() != null))
{
msg = findCause(t.getCause());
}
return msg;
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static Boolean getBooleanParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, Boolean defaultValue)
{
String value = getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
null);
if ((value == null) || (value.length() == 0))
{
return defaultValue;
}
if ("true".equals(value))
{
return true;
}
else if ("false".equals(value))
{
return false;
}
else
{
throw new IllegalArgumentException("Invalid value '" + value + "' for parameter: " +
nodeName);
}
}
/**
* Returns the identifier as used in this connector.
*
* @param uri The uri to look for
*
* @return
*/
public static String getDestinationIdentifier(String uri)
{
Destination dest = Destination.getDestination(uri);
if (dest == null)
{
return null;
}
return dest.getDestinationManager().getName() + "." + dest.getName();
}
/**
* Returns the internal (JMS) queue/topic identifier for a given destination, without any
* parameters.
*
* @param destination
*
* @return
*
* @throws JMSException
*/
public static String getDestinationURI(javax.jms.Destination destination)
throws JMSException
{
String destURI = "";
if (destination instanceof Queue)
{
destURI = ((Queue) destination).getQueueName();
}
else if (destination instanceof Topic)
{
destURI = ((Topic) destination).getTopicName();
}
if (destURI.indexOf("?") > -1) // remove all possible parameters...
{
destURI = destURI.substring(0, destURI.indexOf("?"));
}
return destURI;
}
/**
* Returns the JMSConnector name as well as the provider specific destination URL for the given
* JMS destination. The JMSConnector destination is a destination that is related to the given
* JMS destination (e.g. the receiving destination).
*
* @param dOrigConnectorDest Related JMSConnector destination.
* @param dDest JMS destination.
* @param bAddParameters If <code>true</code> dynamic destinations parameters are added
* to the physical name (provider URL).
*
* @return String array where [0] = JMSConnector name, [1] = JMS provider URL (null if the
* destination is known).
*
* @throws JMSException
*/
public static String[] getJmsDestinationNames(Destination dOrigConnectorDest,
javax.jms.Destination dDest,
boolean bAddParameters)
throws JMSException
{
String sProviderUrl = getDestinationURI(dDest);
String sConnectorName = getDestinationIdentifier(sProviderUrl);
if (sConnectorName != null)
{
return new String[] { sConnectorName, null };
}
// Unknown static destination. Just set it as a dynamic one.
Destination dUseDest = null;
if ((sProviderUrl != null) && (sProviderUrl.length() > 0))
{
// Destination physical name is known, so try to find a dynamic destination.
dUseDest = dOrigConnectorDest.getDestinationManager().getDynamicDestination();
}
if (dUseDest == null)
{
// No dynamic destination configured or the physical name was not known, so just
// use the default one. For triggers this is the destination to which the trigger is
// attached to.
dUseDest = dOrigConnectorDest;
}
sConnectorName = dUseDest.getDestinationManager().getName() + "." + dUseDest.getName();
if ((sProviderUrl != null) && (sProviderUrl.length() > 0) && bAddParameters)
{
sProviderUrl = appendDynamicDestinationParameters(sProviderUrl, dUseDest,
dUseDest
.getDynamicDestinationParameterString());
}
return new String[]
{
(sConnectorName != null) ? sConnectorName : "",
(sProviderUrl != null) ? sProviderUrl : ""
};
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static Long getLongParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, Long defaultValue)
{
String value = getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
null);
if ((value == null) || (value.length() == 0))
{
return defaultValue;
}
try
{
return Long.parseLong(value);
}
catch (RuntimeException e)
{
throw new IllegalArgumentException("Invalid value '" + value + "' for parameter: " +
nodeName);
}
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String nodeName,
String defaultValue)
{
return getParameter(request, implementation, nodeName, false, nodeName, defaultValue);
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param requestName DOCUMENTME
* @param implementationName DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String requestName,
String implementationName, String defaultValue)
{
return getParameter(request, implementation, requestName, false, implementationName,
defaultValue);
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, String defaultValue)
{
return getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
defaultValue);
}
/**
* Returns a parameter value from the implementation or the request itself, based on the
* implementation settings.
*
* @param request The request xml
* @param implementation The implementation xml
* @param requestName The parameter name in the request
* @param requestIsAttribute true if the parameter is specified in an attribute in the
* request
* @param implementationName The parameter name in the implementation
* @param defaultValue A default value
*
* @return the value from the request if the implementation states that it was overridable,
* else the value from the implementation and if that one is not found either, the
* default value
*/
public static String getParameter(int request, int implementation, String requestName,
boolean requestIsAttribute, String implementationName,
String defaultValue)
{
int impNode = Node.getElement(implementation, implementationName);
if ((impNode == 0) || "true".equals(Node.getAttribute(impNode, "overridable")))
{
String sRes;
if (requestIsAttribute)
{
sRes = Node.getAttribute(request, requestName, null);
}
else
{
sRes = Node.getDataElement(request, requestName, null);
}
if (sRes != null)
{
return sRes;
}
}
return Node.getDataWithDefault(impNode, defaultValue);
}
/**
* Returns a better stacktrace especially for JMSExceptions (contain a linked exception with
* more exception details).
*
* @param t the exception to get it from
*
* @return a string containing the stacktrace
*/
public static String getStackTrace(Throwable t)
{
if (t == null)
{
return "";
}
StringBuffer sb = new StringBuffer();
sb.append(t.getClass().getName());
sb.append(": ");
if (t.getMessage() != null)
{
sb.append(t.getMessage());
}
sb.append("\n");
if (t instanceof JMSException)
{
sb.append("Caused by: ");
sb.append(getStackTrace(((JMSException) t).getLinkedException()));
}
else if (t.getCause() != null)
{
sb.append("Caused by: ");
sb.append(getStackTrace(t.getCause()));
}
else
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
sb.append(sw.getBuffer());
}
return sb.toString();
}
/**
* Get the properties from the given xml.
*
* @param xml the xml to read the properties from
* @param nodeName the node name containing the property list
* @param properties the object to put the properties into
* @param canChange true if existing properties can be changed
*
* @throws JMSConnectorException
*/
public static void processProperties(int xml, String nodeName,
Hashtable<String, Object> properties, boolean canChange)
throws JMSConnectorException
{
int propNode = Node.getElement(xml, nodeName);
if (propNode != 0)
{
for (int cnode = Node.getFirstChild(propNode); cnode != 0;
cnode = Node.getNextSibling(cnode))
{
String key = Node.getAttribute(cnode, "name");
if (!canChange && properties.containsKey(key))
{
continue;
}
if ((key == null) || (key.length() == 0))
{
continue;
}
String type = Node.getAttribute(cnode, "type", null);
if ((type == null) || (type.length() == 0))
{
throw new JMSConnectorException("No type found for property '" + key + "'");
}
String value = Node.getData(cnode);
Object objValue;
if (type.equals("String"))
{
objValue = value;
}
else if (type.equals("Short"))
{
objValue = Short.valueOf(value);
}
else if (type.equals("Byte"))
{
objValue = Byte.valueOf(value);
}
else if (type.equals("Boolean"))
{
objValue = Boolean.valueOf(value);
}
else if (type.equals("Double"))
{
objValue = Double.valueOf(value);
}
else if (type.equals("Float"))
{
objValue = Float.valueOf(value);
}
else if (type.equals("Integer"))
{
objValue = Integer.valueOf(value);
}
else if (type.equals("Long"))
{
objValue = Long.valueOf(value);
}
else
{
throw new JMSConnectorException("Unknown type '" + type + "' for property '" +
key + "'");
}
properties.put(key, objValue);
}
}
}
/**
* Formats a a string so that it can be put into the log safely. Some characters seem to cause
* problem.
*
* @param oMessage Object to be formatted. Uses toString().
*
* @return Formattes string.
*/
public static String safeFormatLogMessage(Object oMessage)
{
return safeFormatLogMessage(oMessage.toString());
}
/**
* Formats a a string so that it can be put into the log safely. Some characters seem to cause
* problem.
*
* @param sMessage Log message to be formatted.
*
* @return Formattes string.
*/
public static String safeFormatLogMessage(String sMessage)
{
StringBuilder sbRes = new StringBuilder(sMessage.length() + 20);
int iLen = sMessage.length();
for (int i = 0; i < iLen; i++)
{
char ch = sMessage.charAt(i);
if ((ch < 9) || (ch == 11) || (ch == 12) || (ch > 127))
{
sbRes.append("[");
sbRes.append((int) ch);
sbRes.append("]");
}
else if ((ch == ']') && (i < (iLen - 2)) && (sMessage.charAt(i + 1) == ']') &&
(sMessage.charAt(i + 2) == '>'))
{
// Escape CDATA end marker.
sbRes.append("]] >");
i += 2;
}
else
{
sbRes.append(ch);
}
}
return sbRes.toString();
}
/**
* Creates a copy of the message, used to put a message into the error queue.
*
* @param inputMsg the message to copy
* @param session the session to use for the new message
*
* @return the copied message
*
* @throws JMSException
* @throws JMSConnectorException
*/
protected static Message getCopyOfMessageForSession(Message inputMsg, Session session)
throws JMSException, JMSConnectorException
{
Message outputMsg;
if (inputMsg instanceof BytesMessage)
{
outputMsg = session.createBytesMessage();
int len = (int) ((BytesMessage) inputMsg).getBodyLength();
byte[] msg = new byte[len];
((BytesMessage) inputMsg).readBytes(msg);
((BytesMessage) outputMsg).writeBytes(msg);
}
else if (inputMsg instanceof TextMessage)
{
outputMsg = session.createTextMessage();
((TextMessage) outputMsg).setText(((TextMessage) inputMsg).getText());
}
else if (inputMsg instanceof MapMessage)
{
outputMsg = session.createMapMessage();
Enumeration<?> mapNames = ((MapMessage) inputMsg).getMapNames();
while (mapNames.hasMoreElements())
{
String key = (String) mapNames.nextElement();
((MapMessage) outputMsg).setObject(key, ((MapMessage) inputMsg).getObject(key));
}
}
else if (inputMsg instanceof ObjectMessage)
{
outputMsg = session.createObjectMessage();
((ObjectMessage) outputMsg).setObject(((ObjectMessage) inputMsg).getObject());
}
else // StreamMessage is not implemented!!!
{
throw new JMSConnectorException("Unsupported message format: " +
inputMsg.getClass().getName());
}
if (inputMsg.getJMSMessageID() != null)
{
outputMsg.setJMSMessageID(inputMsg.getJMSMessageID());
}
if (inputMsg.getJMSCorrelationID() != null)
{
outputMsg.setJMSCorrelationID(inputMsg.getJMSCorrelationID());
}
if (inputMsg.getJMSReplyTo() != null)
{
outputMsg.setJMSReplyTo(inputMsg.getJMSReplyTo());
}
if (inputMsg.getJMSType() != null)
{
outputMsg.setJMSType(inputMsg.getJMSType());
}
outputMsg.setJMSDeliveryMode(inputMsg.getJMSDeliveryMode());
outputMsg.setJMSExpiration(inputMsg.getJMSExpiration());
outputMsg.setJMSPriority(inputMsg.getJMSPriority());
outputMsg.setJMSRedelivered(inputMsg.getJMSRedelivered());
outputMsg.setJMSTimestamp(inputMsg.getJMSTimestamp());
Enumeration<?> properties = inputMsg.getPropertyNames();
while (properties.hasMoreElements())
{
String key = (String) properties.nextElement();
if (key.startsWith("JMSX"))
{
continue;
}
outputMsg.setObjectProperty(key, inputMsg.getObjectProperty(key));
}
return outputMsg;
}
/**
* Convert a message to XML.
*
* @param dDest Destination the this message comes from.
* @param msg The message
* @param resultNode the xml node containing the xml representation
*
* @throws JMSException
*/
protected static void getInformationFromMessage(Destination dDest, Message msg, int resultNode)
throws JMSException
{
Node.createTextElement("messageid", msg.getJMSMessageID(), resultNode);
if (msg.getJMSCorrelationID() != null)
{
Node.createTextElement("correlationid", msg.getJMSCorrelationID(), resultNode);
}
if (msg.getJMSType() != null)
{
Node.createTextElement("jmstype", msg.getJMSType(), resultNode);
}
if (msg.getJMSReplyTo() != null)
{
String[] saNames = getJmsDestinationNames(dDest, msg.getJMSReplyTo(), true);
int xTmpNode;
xTmpNode = Node.createTextElement("reply2destination", saNames[0], resultNode);
if (saNames[1] != null)
{
// Unknown as a static destination. Just set it as a dynamic one.
Node.setAttribute(xTmpNode, Destination.DESTINATION_PHYSICALNAME_ATTRIB,
saNames[1]);
}
}
// Set the from destination too.
{
String[] saNames = getJmsDestinationNames(dDest, msg.getJMSDestination(), true);
int xTmpNode;
xTmpNode = Node.createTextElement("fromdestination", saNames[0], resultNode);
if (saNames[1] != null)
{
// Unknown as a static destination. Just set it as a dynamic one.
Node.setAttribute(xTmpNode, Destination.DESTINATION_PHYSICALNAME_ATTRIB,
saNames[1]);
}
}
Enumeration<?> properties = msg.getPropertyNames();
if (properties.hasMoreElements())
{
int propNode = Node.createElement("properties", resultNode);
while (properties.hasMoreElements())
{
String key = (String) properties.nextElement();
Object value = msg.getObjectProperty(key);
int cnode = Node.createTextElement("property", String.valueOf(value), propNode);
Node.setAttribute(cnode, "name", key);
if (value instanceof String)
{
Node.setAttribute(cnode, "type", "String");
}
else if (value instanceof Short)
{
Node.setAttribute(cnode, "type", "Short");
}
else if (value instanceof Byte)
{
Node.setAttribute(cnode, "type", "Byte");
}
else if (value instanceof Boolean)
{
Node.setAttribute(cnode, "type", "Boolean");
}
else if (value instanceof Double)
{
Node.setAttribute(cnode, "type", "Double");
}
else if (value instanceof Float)
{
Node.setAttribute(cnode, "type", "Float");
}
else if (value instanceof Integer)
{
Node.setAttribute(cnode, "type", "Integer");
}
else if (value instanceof Long)
{
Node.setAttribute(cnode, "type", "Long");
}
else
{
Node.setAttribute(cnode, "type", "Object");
}
}
}
}
}
| 31.965435 | 103 | 0.522689 |
66dee97656e98d698cf7f047025c43a7b468576e | 614 | package br.com.zup.desafiomercadolivre.desafiomercadolivre.repository;
import br.com.zup.desafiomercadolivre.desafiomercadolivre.models.Opiniao;
import br.com.zup.desafiomercadolivre.desafiomercadolivre.models.Pergunta;
import br.com.zup.desafiomercadolivre.desafiomercadolivre.models.Produto;
import br.com.zup.desafiomercadolivre.desafiomercadolivre.models.Usuario;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface PerguntaRepository extends JpaRepository<Pergunta,Long> {
List<Pergunta> findAllByProduto(Produto produto);
}
| 40.933333 | 74 | 0.855049 |
6af635d88ced18724e34a8bcf6aa189f71242731 | 1,206 | package com.bzh.floodserver.utils;
import java.io.Serializable;
public class JsonResult implements Serializable{
private static final long serialVersionUID = 4380426753651589809L;
public static final int SUCCESS = 0;
public static final int ERROR = 1;
private int state;
/** 错误消息 */
private String message;
/** 返回正确时候的数据 */
private Object data;
public JsonResult() {
}
public JsonResult(String error){
state = ERROR;
this.message = error;
}
public JsonResult(Object data){
state = SUCCESS;
this.data = data;
}
public JsonResult(Throwable e) {
state = ERROR;
message = e.getMessage();
}
public JsonResult(int state, Throwable e) {
this.state = state;
this.message = e.getMessage();
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "JsonResult [state=" + state + ", message=" + message + ", data=" + data + "]";
}
}
| 16.985915 | 88 | 0.674959 |
e9eae4b6e2d424a2786ea5616fdfb085b697ee39 | 54 | package TreeTraversal;
public class BreadthFirst {
}
| 10.8 | 27 | 0.796296 |
82132d8609a115a55f3fa368a924d5dd2a4509e5 | 364 | package z;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.util.TestUtil;
public class TestTest {
@Test
@Ignore
public void testId() throws InterruptedException {
Thread.sleep(1000000);
}
@AfterClass
public static void afterClassClearContext() {
TestUtil.clearAllStaticFieldsForUnitTest();
}
}
| 14 | 51 | 0.75 |
d108511a33969c107dc2950b26a73d5f0bbb27ce | 1,374 | package org.tickler.model.factories;
import org.tickler.exceptions.ProductionException;
import org.tickler.model.Tickle;
import java.util.Date;
/**
* Created by jasper on 14/10/18.
*/
public class SingleTickleFactory extends TickleFactory {
private String tickleName;
private Date tickleStartDate;
private Date tickleEndDate;
public SingleTickleFactory(String name, Date startDate, Date endDate) {
this.setTickleName(name);
this.setTickleStartDate(startDate);
this.setTickleEndDate(endDate);
}
public String getTickleName() {
return tickleName;
}
public Date getTickleStartDate() {
return tickleStartDate;
}
public Date getTickleEndDate() {
return tickleEndDate;
}
protected SingleTickleFactory setTickleName(String tickleName) {
this.tickleName = tickleName;
return this;
}
protected SingleTickleFactory setTickleStartDate(Date tickleStartDate) {
this.tickleStartDate = tickleStartDate;
return this;
}
protected SingleTickleFactory setTickleEndDate(Date tickleEndDate) {
this.tickleEndDate = tickleEndDate;
return this;
}
public Tickle produce() throws ProductionException {
Tickle result = new Tickle();
// TODO Implement - method visibility?
return result;
}
}
| 24.535714 | 76 | 0.689229 |
94ac335785fd9049d274313392a099186adae025 | 16,721 | /*
* Copyright (c) 2003-2006 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.scene;
import java.io.IOException;
import java.io.Serializable;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import com.jme.math.Vector3f;
import com.jme.renderer.Renderer;
import com.jme.scene.batch.TriangleBatch;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.util.export.InputCapsule;
import com.jme.util.export.JMEExporter;
import com.jme.util.export.JMEImporter;
import com.jme.util.export.OutputCapsule;
import com.jme.util.export.Savable;
import com.jme.util.geom.BufferUtils;
/**
* <code>Composite</code> defines a geometry mesh. This mesh defines a three
* dimensional object via a collection of points, colors, normals and textures.
* The points are referenced via a indices array. This array instructs the
* renderer the order in which to draw the points, with exact meaning of indices
* being defined by IndexRange collection. Index ranges are interpreted one
* after another, consuming their 'count' indices each time. Every range use
* same vertex data, so it is perfectly possible to reference already used
* indices from different kind of range.
*
* @author Artur Biesiadowski
*/
public class CompositeMesh extends TriMesh implements Serializable {
protected IndexRange[] ranges;
private int[] cachedTriangleIndices;
public CompositeMesh() {}
/**
* Constructor instantiates a new <code>CompositeMesh</code> object.
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
*/
public CompositeMesh(String name) {
super(name);
}
/**
* Constructor instantiates a new <code>CompositeMesh</code> object.
* Provided are the attributes that make up the mesh all attributes may be
* null, except for vertices,indices and ranges
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
* @param vertices
* the vertices of the geometry.
* @param normal
* the normals of the geometry.
* @param color
* the colors of the geometry.
* @param texture
* the texture coordinates of the mesh.
* @param indices
* the indices of the vertex array.
* @param ranges
* the list of index ranges to be used in rendering
*/
public CompositeMesh(String name, FloatBuffer vertices, FloatBuffer normal,
FloatBuffer color, FloatBuffer texture, IntBuffer indices,
IndexRange[] ranges) {
super(name);
this.reconstruct(vertices, normal, color, texture, indices, ranges);
LoggingSystem.getLogger().log(Level.INFO, "CompositeMesh created.");
}
/**
* Recreates the geometric information of this CompositeMesh from scratch.
* The index,vertex and ranges array must not be null, but the others may
* be.
*
* @param vertices
* the vertices of the geometry.
* @param normal
* the normals of the geometry.
* @param color
* the colors of the geometry.
* @param texture
* the texture coordinates of the mesh.
* @param indices
* the indices of the vertex array.
* @param ranges
* the list of index ranges to be used in rendering
*/
public void reconstruct(FloatBuffer vertices, FloatBuffer normal,
FloatBuffer color, FloatBuffer texture, IntBuffer indices,
IndexRange[] ranges) {
super.reconstruct(vertices, normal, color, texture, indices);
if (ranges == null) {
LoggingSystem.getLogger().log(Level.WARNING,
"Index ranges may not be null.");
throw new JmeException("Index ranges may not be null.");
}
this.ranges = ranges;
}
@Override
public int getType() {
return (SceneElement.GEOMETRY | SceneElement.TRIMESH | SceneElement.COMPOSITE_MESH);
}
/**
*
* @return currently set index ranges
*/
public IndexRange[] getIndexRanges() {
return ranges;
}
/**
* Sets new index ranges - be sure to match it with updates to indices array
* if needed
*
* @param ranges
*/
public void setIndexRanges(IndexRange[] ranges) {
this.ranges = ranges;
cachedTriangleIndices = null;
}
/**
* <code>draw</code> calls super to set the render state then passes
* itself to the renderer.
*
* @param r
* the renderer to display
*/
@Override
public void draw(Renderer r) {
if (!r.isProcessingQueue()) {
if (r.checkAndAdd(this))
return;
}
r.draw(this);
}
/**
* @return equivalent number of triangles - each quad counts as two
* triangles
*/
public int getTriangleQuantity() {
if (cachedTriangleIndices != null) {
return cachedTriangleIndices.length / 3;
}
int quantity = 0;
for (int i = 0; i < ranges.length; i++) {
quantity += ranges[i].getTriangleQuantityEquivalent();
}
return quantity;
}
/**
* Create index range representing free, unconnected triangles.
*
* @param count
* number of indexes to be put in this range
* @return new IndexRange for unconnected triangles
*/
public static IndexRange createTriangleRange(int count) {
if (count % 3 != 0) {
throw new IllegalArgumentException(
"Triangle range has to be multiple of 3 vertices");
}
return new IndexRange(IndexRange.TRIANGLES, count);
}
/**
* Create index range representing triangle strip
*
* @param count
* number of indexes to be put in this range
* @return new IndexRange for triangle strip
*/
public static IndexRange createTriangleStrip(int count) {
if (count < 3) {
throw new IllegalArgumentException(
"Triangle strip cannot be shorter than 3 vertices");
}
return new IndexRange(IndexRange.TRIANGLE_STRIP, count);
}
/**
* Create index range representing triangle fan
*
* @param count
* number of indexes to be put in this range
* @return new IndexRange for triangle fan
*/
public static IndexRange createTriangleFan(int count) {
if (count < 3) {
throw new IllegalArgumentException(
"Triangle fan cannot be shorter than 3 vertices");
}
return new IndexRange(IndexRange.TRIANGLE_FAN, count);
}
/**
* Create index range representing free, unconnected quads.
*
* @param count
* number of indexes to be put in this range
* @return new IndexRange for unconnected quads
*/
public static IndexRange createQuadRange(int count) {
if (count % 4 != 0) {
throw new IllegalArgumentException(
"Quad range has to be multiple of 4 vertices");
}
return new IndexRange(IndexRange.QUADS, count);
}
/**
* Create index range representing quad strip
*
* @param count
* number of indexes to be put in this range
* @return new IndexRange for quad strip
*/
public static IndexRange createQuadStrip(int count) {
if (count < 4) {
throw new IllegalArgumentException(
"Quad strip range cannot be shorter than 4 vertices");
}
if (count % 2 != 0) {
throw new IllegalArgumentException(
"Quad strip range has to be multiple of 2 vertices");
}
return new IndexRange(IndexRange.QUAD_STRIP, count);
}
/**
* Recreate view of this composite mesh as collection of triangles.
* Unconditionally updates cachedTriangleIndices field with new data.
*/
protected void recreateTriangleIndices() {
TriangleBatch batch = getBatch(0);
cachedTriangleIndices = new int[getTriangleQuantity() * 3];
int index = 0;
int ctIdx = 0;
for (int i = 0; i < ranges.length; i++) {
IndexRange rng = ranges[i];
switch (rng.getKind()) {
case CompositeMesh.IndexRange.TRIANGLES:
for (int ri = 0; ri < rng.getCount(); ri++) {
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(ri + index);
}
break;
case CompositeMesh.IndexRange.TRIANGLE_STRIP:
for (int ri = 2; ri < rng.getCount(); ri++) {
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + ri - 2);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + ri - 1);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + ri);
}
break;
case CompositeMesh.IndexRange.TRIANGLE_FAN:
for (int ri = 2; ri < rng.getCount(); ri++) {
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + ri - 1);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + ri);
}
break;
case CompositeMesh.IndexRange.QUADS:
for (int q = 0; q < rng.getCount(); q += 4) {
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q + 1);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q + 2);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q + 2);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q + 3);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q);
}
break;
case CompositeMesh.IndexRange.QUAD_STRIP:
for (int q = 2; q < rng.getCount(); q += 2) {
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q - 2);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q - 1);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q + 1);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q);
cachedTriangleIndices[ctIdx++] = batch.getIndexBuffer().get(index + q - 1);
}
break;
default:
throw new JmeException("Unknown index range type "
+ ranges[i].getKind());
}
index += rng.getCount();
}
}
/**
* Return this mesh object as triangles. Every 3 vertices returned compose
* single triangle. Vertices are returned by reference for efficiency, so it
* is required that they won't be modified by caller.
*
* @return view of current mesh as group of triangle vertices
*/
public Vector3f[] getMeshAsTrianglesVertices() {
if (cachedTriangleIndices == null) {
recreateTriangleIndices();
}
TriangleBatch batch = getBatch(0);
Vector3f[] vertex = BufferUtils.getVector3Array(batch.getVertexBuffer()); // FIXME: UGLY!
Vector3f[] triangleData = new Vector3f[cachedTriangleIndices.length];
for (int i = 0; i < triangleData.length; i++) {
triangleData[i] = vertex[cachedTriangleIndices[i]];
}
return triangleData;
}
/**
* Stores in the <code>storage</code> array the indices of triangle
* <code>i</code>. If <code>i</code> is an invalid index, or if
* <code>storage.length<3</code>, then nothing happens For composite
* mesh, this operation is more costly than for Trimesh.
*
* @param i
* The index of the triangle to get.
* @param storage
* The array that will hold the i's indexes.
*/
@Override
public void getTriangle(int i, int[] storage) {
int iOffset = i * 3;
if (cachedTriangleIndices == null) {
recreateTriangleIndices();
}
if (i < 0 || iOffset >= cachedTriangleIndices.length) {
return;
}
storage[0] = cachedTriangleIndices[iOffset + 0];
storage[1] = cachedTriangleIndices[iOffset + 1];
storage[2] = cachedTriangleIndices[iOffset + 2];
}
/**
* Stores in the <code>vertices</code> array the vertex values of triangle
* <code>i</code>. If <code>i</code> is an invalid triangle index,
* nothing happens.
*
* @param i
* @param vertices
*/
@Override
public void getTriangle(int i, Vector3f[] vertices) {
TriangleBatch batch = getBatch(0);
int iOffset = i * 3;
if (cachedTriangleIndices == null) {
recreateTriangleIndices();
}
if (i < 0 || iOffset >= cachedTriangleIndices.length) {
return;
}
for (int x = 0; x < 3; x++) {
vertices[x] = new Vector3f(); // we could reuse existing, but it may affect current users.
BufferUtils.populateFromBuffer(vertices[x], batch.getVertexBuffer(), cachedTriangleIndices[iOffset++]);
}
}
private static final long serialVersionUID = 1;
/**
* This class represents range of indexes to be interpreted in a way
* depending on 'kind' attribute. To create instances of this class, please
* check CompositeMesh static methods.
*/
public static class IndexRange implements java.io.Serializable, Savable {
public static final int TRIANGLES = 1;
public static final int TRIANGLE_STRIP = 2;
public static final int TRIANGLE_FAN = 3;
public static final int QUADS = 4;
public static final int QUAD_STRIP = 5;
private int kind;
private int count;
public IndexRange() {}
IndexRange(int aKind, int aCount) {
kind = aKind;
count = aCount;
}
public int getCount() {
return count;
}
public int getKind() {
return kind;
}
/**
* @return equivalent in triangles of elements drawn (1 quad counts as
* two triangles)
*/
public long getTriangleQuantityEquivalent() {
switch (kind) {
case TRIANGLES:
return count / 3;
case TRIANGLE_STRIP:
return count - 2;
case TRIANGLE_FAN:
return count - 2;
case QUADS:
return (count / 4) * 2;
case QUAD_STRIP:
return ((count - 2) / 2) * 2;
default:
throw new JmeException("Unknown kind of index range");
}
}
@Override
public String toString() {
return "IndexRange kind=" + KIND_NAMES[getKind()] + " count="
+ getCount();
}
private String[] KIND_NAMES = { null, "TRIANGLES", "TRIANGLE_STRIP",
"TRIANGLE_FAN", "QUADS", "QUAD_STRIP" };
private static final long serialVersionUID = 1;
@Override
public void write(JMEExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(kind, "kind", 0);
capsule.write(count, "count", 0);
}
@Override
public void read(JMEImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
kind = capsule.readInt("kind", 0);
count = capsule.readInt("count", 0);
}
@Override
public Class<? extends IndexRange> getClassTag() {
return this.getClass();
}
}
@Override
public void write(JMEExporter e) throws IOException {
super.write(e);
OutputCapsule capsule = e.getCapsule(this);
capsule.write(ranges, "ranges", null);
capsule.write(cachedTriangleIndices, "cachedTriangleIndices", null);
}
@Override
public void read(JMEImporter e) throws IOException {
super.read(e);
InputCapsule capsule = e.getCapsule(this);
Object[] savs = capsule.readSavableArray("ranges", null);
if(savs != null) {
ranges = new IndexRange[savs.length];
for(int i = 0; i < savs.length; i++) {
ranges[i] = (IndexRange)savs[i];
}
}
cachedTriangleIndices = capsule.readIntArray("cachedTriangleIndices", null);
}
}
| 31.728653 | 115 | 0.673524 |
5da93b147de40befe450cfa6d2e658149fecdaf0 | 2,612 | /*
* Copyright (C) 2019 AquariOS
*
* 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.
*
* Sets a sane color filter on a white drawable when system accent
* is white
*/
package com.aquarios.coralreef.helpers;
import android.app.ActivityManager;
import android.content.Context;
import android.content.om.IOverlayManager;
import android.content.om.OverlayInfo;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.android.settings.R;
public class WhiteAccentHelperImageView extends ImageView {
public WhiteAccentHelperImageView(final Context context) {
this(context, null);
}
public WhiteAccentHelperImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WhiteAccentHelperImageView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public WhiteAccentHelperImageView(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr,
int defStyleRes) {
if (isUsingWhiteAccent()) {
setColorFilter(
context.getResources().getColor(R.color.top_banner_icon_color_white_accent),
PorterDuff.Mode.SRC_ATOP);
}
}
private static boolean isUsingWhiteAccent() {
IOverlayManager om = IOverlayManager.Stub.asInterface(
ServiceManager.getService(Context.OVERLAY_SERVICE));
OverlayInfo themeInfo = null;
try {
themeInfo = om.getOverlayInfo("com.accents.white",
ActivityManager.getCurrentUser());
} catch (RemoteException e) {
e.printStackTrace();
}
return themeInfo != null && themeInfo.isEnabled();
}
}
| 33.922078 | 96 | 0.701761 |
64bdb648cf0a3590d258af890c056e160db5faf6 | 22,318 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.runtime.agent;
import io.fabric8.agent.download.DownloadManager;
import io.fabric8.agent.download.DownloadManagers;
import io.fabric8.agent.utils.AgentUtils;
import io.fabric8.api.Container;
import io.fabric8.api.ContainerRegistration;
import io.fabric8.api.FabricService;
import io.fabric8.api.Profile;
import io.fabric8.api.scr.AbstractComponent;
import io.fabric8.api.scr.ValidatingReference;
import io.fabric8.common.util.Closeables;
import io.fabric8.common.util.Strings;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.karaf.features.Feature;
import org.jboss.gravia.provision.Provisioner;
import org.jboss.gravia.provision.ResourceHandle;
import org.jboss.gravia.provision.ResourceInstaller;
import org.jboss.gravia.provision.spi.DefaultInstallerContext;
import org.jboss.gravia.resource.Capability;
import org.jboss.gravia.resource.ContentNamespace;
import org.jboss.gravia.resource.DefaultResourceBuilder;
import org.jboss.gravia.resource.IdentityNamespace;
import org.jboss.gravia.resource.ManifestBuilder;
import org.jboss.gravia.resource.MavenCoordinates;
import org.jboss.gravia.resource.Requirement;
import org.jboss.gravia.resource.Resource;
import org.jboss.gravia.resource.ResourceIdentity;
import org.jboss.gravia.runtime.WebAppContextListener;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.Asset;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.impl.base.asset.ZipFileEntryAsset;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@Component(name = "io.fabric8.runtime.agent.FabricAgent", label = "Fabric8 Runtime Agent", immediate = true, policy = ConfigurationPolicy.IGNORE, metatype = false)
public class FabricAgent extends AbstractComponent implements FabricAgentMXBean {
private static final Logger LOGGER = LoggerFactory.getLogger(FabricAgent.class);
private static final String SERVICE_COMPONENT = "Service-Component";
private static final String GENRATED_RESOURCE_IDENTITY = "io.fabric8.generated.fabric-profile";
private static final String GENRATED_MAVEN_COORDS = "mvn:io.fabric8.generated/fabric-profile/1.0.0/war";
private static final Pattern VALID_COMPONENT_PATH_PATTERN = Pattern.compile("[_a-zA-Z0-9\\-\\./]+");
@Reference(referenceInterface = MBeanServer.class)
private final ValidatingReference<MBeanServer> mbeanServer = new ValidatingReference<MBeanServer>();
@Reference(referenceInterface = Provisioner.class)
private final ValidatingReference<Provisioner> provisioner = new ValidatingReference<Provisioner>();
@Reference(referenceInterface = FabricService.class)
private final ValidatingReference<FabricService> fabricService = new ValidatingReference<FabricService>();
@Reference(referenceInterface = ContainerRegistration.class)
private final ValidatingReference<ContainerRegistration> containerRegistration = new ValidatingReference<ContainerRegistration>();
private final Runnable onConfigurationChange = new Runnable() {
@Override
public void run() {
submitUpdateJob();
}
};
private final ExecutorService executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("fabric8-agent"));
private final ExecutorService downloadExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("fabric8-agent-downloader"));
private ObjectName objectName;
private Map<ResourceIdentity, ResourceHandle> resourcehandleMap = new ConcurrentHashMap<ResourceIdentity, ResourceHandle>();
private ComponentContext componentContext;
@Activate
void activate(ComponentContext componentContext) {
this.componentContext = componentContext;
LOGGER.info("Activating");
fabricService.get().trackConfiguration(onConfigurationChange);
activateComponent();
submitUpdateJob();
try {
MBeanServer anMBeanServer = mbeanServer.get();
if (anMBeanServer != null) {
if (objectName == null) {
objectName = new ObjectName("io.fabric8:type=RuntimeAgent");
}
anMBeanServer.registerMBean(this, objectName);
} else {
LOGGER.warn("No MBeanServer");
}
} catch (Exception e) {
LOGGER.warn("Failed to register MBean " + objectName + ": " + e, e);
}
}
@Deactivate
void deactivate() {
if (objectName != null) {
try {
MBeanServer anMBeanServer = mbeanServer.get();
if (anMBeanServer != null) {
anMBeanServer.unregisterMBean(objectName);
}
} catch (Exception e) {
LOGGER.warn("Failed to unregister MBean " + objectName + ": " + e, e);
}
}
deactivateComponent();
fabricService.get().untrackConfiguration(onConfigurationChange);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
// Ignore
}
executor.shutdownNow();
}
private void submitUpdateJob() {
executor.submit(new Runnable() {
@Override
public void run() {
if (isValid()) {
try {
updateInternal();
} catch (Exception e) {
LOGGER.warn("Caught:" + e, e);
}
}
}
});
}
protected synchronized void updateInternal() {
Profile profile = null;
FabricService fabric = null;
Provisioner provisionService = null;
try {
fabric = fabricService.get();
Container container = fabric.getCurrentContainer();
profile = container.getOverlayProfile();
provisionService = provisioner.get();
} catch (Exception ex) {
LOGGER.debug("Failed to read container profile. This exception will be ignored..", ex);
return;
}
if (profile != null && fabric != null && provisionService != null) {
List<String> resources = null;
try {
Map<String, File> artifacts = downloadProfileArtifacts(fabric, profile);
populateExplodedWar(artifacts);
resources = updateProvisioning(artifacts, provisionService);
updateStatus(Container.PROVISION_SUCCESS, null, resources);
} catch (Throwable e) {
if (isValid()) {
LOGGER.warn("Exception updating provisioning: " + e, e);
updateStatus(Container.PROVISION_ERROR, e, resources);
} else {
LOGGER.debug("Exception updating provisioning: " + e, e);
}
}
}
}
protected void updateStatus(String status, Throwable result, List<String> resources) {
try {
FabricService fs = fabricService.get();
if (fs != null) {
Container container = fs.getCurrentContainer();
String e;
if (result == null) {
e = null;
} else {
StringWriter sw = new StringWriter();
result.printStackTrace(new PrintWriter(sw));
e = sw.toString();
}
if (resources != null) {
container.setProvisionList(resources);
}
container.setProvisionResult(status);
container.setProvisionException(e);
} else {
LOGGER.info("FabricService not available");
}
} catch (Throwable e) {
LOGGER.warn("Unable to set provisioning result");
}
}
protected Map<String, File> downloadProfileArtifacts(FabricService fabric, Profile profile) throws Exception {
updateStatus("downloading", null, null);
Set<String> bundles = new LinkedHashSet<String>();
Set<Feature> features = new LinkedHashSet<Feature>();
bundles.addAll(profile.getBundles());
DownloadManager downloadManager = DownloadManagers.createDownloadManager(fabric, downloadExecutor);
AgentUtils.addFeatures(features, fabric, downloadManager, profile);
//return AgentUtils.downloadProfileArtifacts(fabricService.get(), downloadManager, profile);
return AgentUtils.downloadBundles(downloadManager, features, bundles,
Collections.<String>emptySet());
}
protected void populateExplodedWar(Map<String, File> artifacts) throws IOException {
updateStatus("populating profile war", null, null);
ClassLoader original = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(FabricAgent.class.getClassLoader());
final WebArchive archive = ShrinkWrap.create(WebArchive.class, "profile.war");
final Set<String> components = new HashSet<String>();
for (Map.Entry<String, File> entry : artifacts.entrySet()) {
String name = entry.getKey();
File f = entry.getValue();
if (!isWar(name, f)) {
archive.addAsLibrary(f);
Manifest mf = readManifest(f);
if (mf.getMainAttributes().containsKey(new Attributes.Name(SERVICE_COMPONENT))) {
String serviceComponents = mf.getMainAttributes().getValue(SERVICE_COMPONENT);
for (String component : Strings.splitAndTrimAsList(serviceComponents, ",")) {
if (VALID_COMPONENT_PATH_PATTERN.matcher(component).matches()) {
archive.add(new ZipFileEntryAsset(new ZipFile(f, ZipFile.OPEN_READ), new ZipEntry(component)), component);
components.add(component);
}
}
}
}
}
archive.addClass(WebAppContextListener.class);
archive.addAsWebInfResource("web.xml");
archive.addAsWebResource("context.xml", "META-INF/context.xml");
archive.setManifest(new Asset() {
@Override
public InputStream openStream() {
return new ManifestBuilder()
.addIdentityCapability(GENRATED_RESOURCE_IDENTITY, "1.0.0")
.addManifestHeader(SERVICE_COMPONENT, Strings.join(components, ",")).openStream();
}
});
File profileWar = componentContext.getBundleContext().getDataFile("fabric-profile.war");
archive.as(ZipExporter.class).exportTo(profileWar, true);
artifacts.put(GENRATED_MAVEN_COORDS, profileWar);
} finally {
Thread.currentThread().setContextClassLoader(original);
}
updateStatus("populated profile war", null, null);
}
private static Manifest readManifest(File file) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
JarInputStream jis = new JarInputStream(fis);
return jis.getManifest();
} finally {
Closeables.closeQuitely(fis);
}
}
protected List<String> updateProvisioning(Map<String, File> artifacts, Provisioner provisionService) throws Exception {
ResourceInstaller resourceInstaller = provisionService.getResourceInstaller();
Map<ResourceIdentity, Resource> installedResources = getInstalledResources(provisionService);
Map<Requirement, Resource> requirements = new HashMap<Requirement, Resource>();
Set<Map.Entry<String, File>> entries = artifacts.entrySet();
List<Resource> resourcesToInstall = new ArrayList<Resource>();
List<String> resourceUrisInstalled = new ArrayList<String>();
updateStatus("installing", null, null);
for (Map.Entry<String, File> entry : entries) {
String name = entry.getKey();
File file = entry.getValue();
String coords = name;
int idx = coords.lastIndexOf(':');
if (idx > 0) {
coords = name.substring(idx + 1);
}
// lets switch to gravia's mvn coordinates
coords = coords.replace('/', ':');
MavenCoordinates mvnCoords = parse(coords);
URL url = file.toURI().toURL();
if (url == null) {
LOGGER.warn("Could not find URL for file " + file);
continue;
}
// TODO lets just detect wars for now for servlet engines - how do we decide on WildFly?
boolean isShared = !isWar(name, file);
Resource resource = findMavenResource(mvnCoords, url, isShared);
if (resource == null) {
LOGGER.warn("Could not find resource for " + mvnCoords + " and " + url);
} else {
ResourceIdentity identity = resource.getIdentity();
Resource oldResource = installedResources.remove(identity);
if (oldResource == null && !resourcehandleMap.containsKey(identity)) {
if (isShared) {
// TODO lest not deploy shared stuff for now since bundles throw an exception when trying to stop them
// which breaks the tests ;)
LOGGER.debug("TODO not installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity);
} else {
LOGGER.info("Installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity);
resourcesToInstall.add(resource);
resourceUrisInstalled.add(name);
}
}
}
}
for (Resource installedResource : installedResources.values()) {
ResourceIdentity identity = installedResource.getIdentity();
ResourceHandle resourceHandle = resourcehandleMap.get(identity);
if (resourceHandle == null) {
// TODO should not really happen when we can ask about the installed Resources
LOGGER.warn("TODO: Cannot uninstall " + installedResource + " as we have no handle!");
} else {
LOGGER.info("Uninstalling " + installedResource);
resourceHandle.uninstall();
resourcehandleMap.remove(identity);
LOGGER.info("Uninstalled " + installedResource);
}
}
if (resourcesToInstall.size() > 0) {
LOGGER.info("Installing " + resourcesToInstall.size() + " resource(s)");
Set<ResourceHandle> resourceHandles = new LinkedHashSet<>();
ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements);
for (Resource resource : resourcesToInstall) {
resourceHandles.add(resourceInstaller.installResource(context, resource));
}
LOGGER.info("Got " + resourceHandles.size() + " resource handle(s)");
for (ResourceHandle resourceHandle : resourceHandles) {
resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle);
}
}
return resourceUrisInstalled;
}
protected Map<ResourceIdentity, Resource> getInstalledResources(Provisioner provisionService) {
Map<ResourceIdentity, Resource> installedResources = new HashMap<ResourceIdentity, Resource>();
// lets add the handles we already know about
for (Map.Entry<ResourceIdentity, ResourceHandle> entry : resourcehandleMap.entrySet()) {
installedResources.put(entry.getKey(), entry.getValue().getResource());
}
try {
Iterator<Resource> resources = provisionService.getEnvironment().getResources();
while (resources.hasNext()) {
Resource resource = resources.next();
installedResources.put(resource.getIdentity(), resource);
}
} catch (Throwable e) {
LOGGER.warn("Ignoring error finding current resources: " + e, e);
}
return installedResources;
}
public Resource findMavenResource(MavenCoordinates mavenid, URL contentURL, boolean isShared) {
LOGGER.debug("Find maven providers for: {}", mavenid);
Resource result = null;
if (contentURL != null) {
DefaultResourceBuilder builder = new DefaultResourceBuilder();
Capability identCap = builder.addIdentityCapability(mavenid);
Capability ccap = builder.addCapability(ContentNamespace.CONTENT_NAMESPACE, null, null);
ccap.getAttributes().put(ContentNamespace.CAPABILITY_URL_ATTRIBUTE, contentURL);
if (isShared) {
identCap.getAttributes().put(IdentityNamespace.CAPABILITY_SHARED_ATTRIBUTE, "true");
} else {
// lets default to using just the artifact id for the context path
identCap.getAttributes().put("contextPath", mavenid.getArtifactId());
}
LOGGER.debug("Found maven resource: {}", result = builder.getResource());
}
return result;
}
private static boolean isWar(String name, File file) {
return name.startsWith("war:") || name.contains("/war/") ||
file.getName().toLowerCase().endsWith(".war");
}
//TODO: This needs to be fixed at gravia
private static MavenCoordinates parse(String coordinates) {
MavenCoordinates result;
String[] parts = coordinates.split(":");
if (parts.length == 3) {
result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null);
} else if (parts.length == 4) {
result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null);
} else if (parts.length == 5) {
result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]);
} else {
throw new IllegalArgumentException("Invalid coordinates: " + coordinates);
}
return result;
}
void bindMbeanServer(MBeanServer service) {
this.mbeanServer.bind(service);
}
void unbindMbeanServer(MBeanServer service) {
this.mbeanServer.unbind(service);
}
void bindProvisioner(Provisioner service) {
this.provisioner.bind(service);
}
void unbindProvisioner(Provisioner service) {
this.provisioner.unbind(service);
}
void bindFabricService(FabricService fabricService) {
this.fabricService.bind(fabricService);
}
void unbindFabricService(FabricService fabricService) {
this.fabricService.unbind(fabricService);
}
void bindContainerRegistration(ContainerRegistration service) {
this.containerRegistration.bind(service);
}
void unbindContainerRegistration(ContainerRegistration service) {
this.containerRegistration.unbind(service);
}
private static class NamedThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
NamedThreadFactory(String prefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = prefix + "-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}
| 43.420233 | 163 | 0.634824 |
7530a76b504fc886c9308ec257c1e53066645a72 | 954 | package com.eerussianguy.firmalife.render;
import net.minecraftforge.common.property.IUnlistedProperty;
import com.eerussianguy.firmalife.recipe.PlanterRecipe;
public class UnlistedCropProperty implements IUnlistedProperty<PlanterRecipe.PlantInfo>
{
public int ordinal;
public UnlistedCropProperty(int ordinal)
{
this.ordinal = ordinal;
}
@Override
public String getName()
{
return "UnlistedCropProperty" + ordinal;
}
@Override
public boolean isValid(PlanterRecipe.PlantInfo value)
{
return true;
}
@Override
public Class<PlanterRecipe.PlantInfo> getType()
{
return PlanterRecipe.PlantInfo.class;
}
@Override
public String valueToString(PlanterRecipe.PlantInfo value)
{
if (value.getRecipe().getRegistryName() == null) return "null";
return value.getRecipe().getRegistryName().toString() + "_" + value.getStage();
}
}
| 23.268293 | 87 | 0.689727 |
ed92f5b8bd2f33d93228ef6b9a54444536f32b97 | 16,024 | package dch.eclipse.p5Export;
import java.io.*;
import java.util.*;
import org.eclipse.debug.core.ILaunchConfiguration;
import com.sun.org.apache.xml.internal.serialize.LineSeparator;
import processing.app.Base;
import processing.app.Preferences;
import processing.core.PApplet;
import processing.core.PConstants;
public class P5ApplicationExport extends P5ExportType
{
private static final String CORE_JAR = "core.jar";
private static final String JAVAROOT = "$JAVAROOT/";
private static final String BAT_STRING = "@echo off\njava -Djava.ext.dirs=lib -Djava.library.path=lib ";
public P5ApplicationExport()
{
this.isApplet = false;
}
public File doExport(P5ExportBuilder builder, ILaunchConfiguration pConfiguration, File workDir, List createdFiles) throws Exception
{
Preferences.set("build.path", workDir.getAbsolutePath());
if (export(builder))
{
String[] platformConsts = { "windows", "macosx", "linux" }; // yuck
for (int i = 0; i < platformConsts.length; i++)
createdFiles.add(new File(workDir, "applications." + platformConsts[i]));
return workDir;
}
else
throw new P5ExportException("Unable to complete export");
}
protected boolean export(P5ExportBuilder builder) throws Exception
{
// System.err.println("P5ApplicationExport.export("+sketchFolder+","+javaSrc+","+mainClass+", CP=''"+sketchName+"hasMain= "+hasMain+") : \n\n"+classpath+"\n\n");
this.mainClass = builder.mainClass;
File sketchFolder = builder.workDir;
String sketchName = builder.sketchName;
String programText = builder.mainProgram;
String classpath = builder.projectClassPath;
File srcDir = new File(builder.srcPath);
for (int p = 0; p < PLATFORMS.length; p++)
{
int exportPlatform = PLATFORMS[p];
String folderName = getAppFolderName(exportPlatform);
// re-create the .application folder
File appFolder = new File(sketchFolder, folderName);
P5ExportUtils.deleteDir(appFolder);
appFolder.mkdirs();
// and the lib folder inside app
File jarFolder = new File(appFolder, "lib");
if (exportPlatform != PConstants.MACOSX && !jarFolder.exists())
jarFolder.mkdir();
// and the source folder inside app
addSourceDir(srcDir, appFolder);
String renderer = ""; // parse size/renderer
String[] params = parseSizeArgs(builder.mainProgram);
if (params != null && params.length == 3)
renderer = params[2];
// System.err.println("RENDERER: "+renderer);
File dotAppFolder = null;
if (exportPlatform == PConstants.MACOSX)
{
dotAppFolder = createMacBundle(sketchName, appFolder);
// set the jar folder to the mac-specific location
jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
appFolder = dotAppFolder; // reset the app folder to dotApp (??)
}
if (!jarFolder.exists())
jarFolder.mkdirs();
if (exportPlatform == PConstants.WINDOWS)
{
// File exe = new File(appFolder, sketchName + ".exe");
// Base.copyFile(new File("lib/export/application.exe"), exe);
// if (!exe.exists())
// P5ExportUtils.errorDialog(builder.shell, "Could not make windows .exe", null);
try
{
String data = BAT_STRING + "";
data += builder.mainClass;
File bat = new File(appFolder, sketchName + ".bat");
// if file doesnt exists, then create it
if (!bat.exists())
{
bat.createNewFile();
}
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(bat.getAbsolutePath(), true)));
out.println(data);
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (builder.hasMain)
programText = validateMain(programText);
else
return showMissingMainWarning(builder);
// determine whether to use one jar file or several
boolean separateJar = renderer.equals(OPENGL) || renderer.equals(GLGRAPHICS);
separateJar = true;
if (Preferences.getBoolean("export.applet.separate_jar_files")) {
//System.out.println("Fors");
separateJar = true;
}
// Write main zip (copy jars to lib if necessary) & return the classpath
Vector classpathList = null;
try
{
classpathList = createArchive(sketchName, mainClass, classpath, appFolder, jarFolder, separateJar, exportPlatform, separateJar);
}
catch (IOException e)
{
throw new P5ExportException(e);
}
StringBuffer exportClassPath = addJarList(exportPlatform, classpathList);
String cp = !separateJar ? sketchName + ".jar" : exportClassPath.toString();
if (exportPlatform == PConstants.MACOSX)
writePListFile(builder, sketchFolder, sketchName, appFolder, cp, separateJar);
else if (exportPlatform == PConstants.WINDOWS)
writeWinArgsFile(builder, appFolder, cp);
else
// Linux
writeShellScript(builder, sketchName, appFolder, separateJar, cp);
}
return true;
}
private boolean showMissingMainWarning(P5ExportBuilder builder)
{
String message = " A main() method is required for application exports:\n";
String code = " public static void main(String args[])\n {\n "
+ "PApplet.main(new String[] { " + mainClass + ".class.getName() "
+ "});\n }\n\n OR (for full-screen mode):\n\n public static void "
+ "main(String args[])\n {\n PApplet.main(new String[] { "
+ "\"--present\", " + mainClass + ".class.getName() });\n }";
P5ExportUtils.messageWithCode(builder.shell, message, code);
return false;
}
private String getAppFolderName(int exportPlatform) throws P5ExportException
{
String exportPlatformStr = "application.";
if (exportPlatform == PConstants.WINDOWS)
exportPlatformStr += "windows";
else if (exportPlatform == PConstants.MACOSX)
exportPlatformStr += "macosx";
else if (exportPlatform == PConstants.LINUX)
exportPlatformStr += "linux";
else
throw new P5ExportException("Unexpected OS type!");
return exportPlatformStr;
}
private void addSourceDir(File srcDir, File appFolder) throws IOException
{
File newSource = new File(appFolder, "source");
if (!newSource.exists())
newSource.mkdir();
File[] files = srcDir.listFiles();
Vector fileVector = new Vector();
fileVector.addAll(Arrays.asList(files));
// Add all the src files
while (!fileVector.isEmpty())
{
File file = (File) fileVector.remove(0);
if (file.isDirectory())
{
File[] tmp = file.listFiles();
fileVector.addAll(Arrays.asList(tmp));
}
else if (file.getName().endsWith(".java"))
{
File newFile = new File(newSource, file.getAbsolutePath().replace(srcDir.getAbsolutePath(), ""));
P5ExportUtils.writeFile(file, newFile);
}
}
}
// refactor this mess
private String validateMain(String programText) throws P5ExportException
{
// should we be in present-mode?
if (!presentMode && programText.indexOf("--present") > -1)
presentMode = true;
// check for --present if full-screen was specified
else if (presentMode && programText.indexOf("--present") < 0)
{
// ok, we need to add --present
System.err.println(getClass().getName() + " handling main(--present)");
String replaceStr = "new String[] { \"--present\", ";
if (!addStopButton) // hide stop button
replaceStr += "\"--hide-stop\", ";
// System.err.println("PGRM: "+programText);
String newText = programText.replaceFirst("new *String\\[ *\\] *\\{", replaceStr);
if (newText.equals(programText))
throw new P5ExportException("Unable to add'--present' flag: " + programText);
programText = newText;
}
// double-check that we fixed the problem
if (presentMode && programText.indexOf("--present") < 0)
{
String msg = "[WARN] Unable to set full-screen mode!\n" + programText + "\n";
System.err.println(msg);
}
return programText;
}
private File createMacBundle(String sketchName, File appFolder) throws IOException, FileNotFoundException
{
File dotAppFolder = new File(appFolder, sketchName + ".app");
String APP_SKELETON = "skeleton.app";
File dotAppSkeleton = new File("lib/export/" + APP_SKELETON);
Base.copyDir(dotAppSkeleton, dotAppFolder);
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// work on osx or *nix, but dies on windows
if (PApplet.platform == PConstants.WINDOWS)
{
File warningFile = new File(appFolder, "readme.txt");
writeWarningFile(dotAppFolder, stubName, warningFile);
}
else
{
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
return dotAppFolder;
}
private void writeShellScript(P5ExportBuilder builder, String sketchName, File appFolder, boolean separateJar, String cp) throws FileNotFoundException, IOException
{
File shellScript = new File(appFolder, sketchName);
PrintStream ps = new PrintStream(new FileOutputStream(shellScript));
ps.print("#!/bin/sh\n\n");
ps.print("APPDIR=$(dirname \"$0\")\n");
if (!separateJar) cp = "lib/" + cp;
ps.print("java " + builder.vmArgs + " -Djava.library.path="
+ "\"$APPDIR\" -cp \"" + cp + "\" " + mainClass + "\n");
System.out.println("java " + builder.vmArgs + " -Djava.library.path="
+ "\"$APPDIR\" -cp \"" + cp + "\" " + mainClass + "\n");
ps.flush();
ps.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but dies on windows, thus the readme file...
if (PApplet.platform != PConstants.WINDOWS)
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
private void writeWinArgsFile(P5ExportBuilder builder, File appFolder, String cp) throws FileNotFoundException
{
File argsFile = new File(appFolder + "/lib/args.txt");
PrintStream ps = new PrintStream(new FileOutputStream(argsFile));
if (builder.vmArgs != null && builder.vmArgs.length() > 0)
ps.print(builder.vmArgs);
ps.println();
ps.print(mainClass);
//if (progArgs != null && progArgs.length()>0) ps.print(progArgs);
ps.println();
ps.println(cp);
ps.flush();
ps.close();
}
private StringBuffer addJarList(int exportPlatform, Vector classpathList)
{
String jarList[] = new String[classpathList.size()];
// System.err.println("jarListVector: "+classpathList);
classpathList.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX)
{
for (int i = 0; i < jarList.length; i++)
{
if (i != 0)
exportClassPath.append(":");
exportClassPath.append(JAVAROOT + jarList[i]);
}
}
else if (exportPlatform == PConstants.WINDOWS)
{
for (int i = 0; i < jarList.length; i++)
{
if (i != 0)
exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
}
else
{
for (int i = 0; i < jarList.length; i++)
{
if (i != 0)
exportClassPath.append(":");
exportClassPath.append("$APPDIR/lib/" + jarList[i]);
}
}
return exportClassPath;
}
private void writePListFile(P5ExportBuilder builder, File sketchFolder, String sketchName, File appFolder, String cp, boolean separateJar) throws FileNotFoundException
{
if (!separateJar)
{
cp = JAVAROOT + cp; // hack
// if we are going to do this (Proc does), we need to
// make sure core.jar is copied into the resources folder
if (false && cp.indexOf(CORE_JAR) < 0)
{
cp += ":" + JAVAROOT + CORE_JAR;
System.out.println("[INFO] Added core.jar to classpath: " + cp);
}
}
// System.err.println("CLASSPATH="+cp);
String PLIST_TEMPLATE = "template.plist";
File plistTemplate = new File(sketchFolder, PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
plistTemplate = new File("lib/export/" + PLIST_TEMPLATE);
}
System.out.println(plistTemplate.getAbsolutePath());
File contentsDir = new File(appFolder, "Contents");
if (!contentsDir.exists())
contentsDir.mkdirs();
File plistFile = new File(contentsDir, "Info.plist");
PrintStream ps = new PrintStream(new FileOutputStream(plistFile));
// FULL_SCREEN SETTINGS
Preferences.setBoolean("export.application.fullscreen", presentMode);
Preferences.setBoolean("export.application.stop", addStopButton);
// ARCH SETTINGS
String arch = "<string>x86_64</string>";
// MEMORY SETTINGS (from builder.vmArgs)?
String vmArgs = "-Xms64m -Xmx1000m";
if (builder.vmArgs.length() > 0)
{
if (builder.vmArgs.contains("-Xmx"))
vmArgs = builder.vmArgs;
else
vmArgs += builder.vmArgs;
}
String[] lines = PApplet.loadStrings(plistTemplate);
System.out.println("pwd: "+System.getProperty("user.dir"));
System.out.println("plistTemplate: "+plistTemplate);
for (int i = 0; i < lines.length; i++)
{
String orig = lines[i];
//System.out.println(i+")"+lines[i]);
if (lines[i].indexOf("@@") != -1)
{
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@sketchName@@")) != -1)
{
sb.replace(index, index + "@@sketchName@@".length(), sketchName);
}
while ((index = sb.indexOf("@@sketch@@")) != -1)
{
sb.replace(index, index + "@@sketch@@".length(), mainClass);
}
while ((index = sb.indexOf("@@vmargs@@")) != -1)
{
sb.replace(index, index + "@@vmargs@@".length(), vmArgs);
}
while ((index = sb.indexOf("@@vmoptions@@")) != -1)
{
sb.replace(index, index + "@@vmoptions@@".length(), vmArgs);
}
while ((index = sb.indexOf("@@classpath@@")) != -1)
{
sb.replace(index, index + "@@classpath@@".length(), cp);
}
while ((index = sb.indexOf("@@lsarchitecturepriority@@")) != -1)
{
sb.replace(index, index + "@@lsarchitecturepriority@@".length(), arch);
}
while ((index = sb.indexOf("@@lsuipresentationmode@@")) != -1)
{
String pmode = "0";
if (presentMode || Preferences.getBoolean("export.application.fullscreen"))
pmode = "4";
sb.replace(index, index + "@@lsuipresentationmode@@".length(), pmode);
}
lines[i] = sb.toString();
}
if (!lines[i].equals(orig))
System.out.println(i+")"+lines[i]);
else
System.out.println(i+"***)"+lines[i]);
// explicit newlines to avoid Windows CRLF
ps.print(lines[i] + "\n");
}
ps.flush();
ps.close();
}
private void writeWarningFile(File dotAppFolder, String stubName, File warningFile) throws FileNotFoundException
{
PrintStream ps = new PrintStream(new FileOutputStream(warningFile));
ps.println("This application was created on Windows, which doesn't");
ps.println("properly support setting files as \"executable\",");
ps.println("a necessity for applications on Mac OS X.");
ps.println();
ps.println("To fix this, use the Terminal on Mac OS X, and from this");
ps.println("directory, type the following:");
ps.println();
ps.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
ps.flush();
ps.close();
}
}// end
| 34.093617 | 169 | 0.620819 |
ee0fe1eb377f6d4e9256257dc49465f219384ceb | 223 | /*
* Copyright (c) 2016 OmniFaces.org. All Rights Reserved.
*/
package org.omnifaces.serve.rest;
import org.omnifaces.serve.context.Context;
/**
* The REST context.
*/
public interface RestContext extends Context {
}
| 17.153846 | 57 | 0.726457 |
2778a86c818ab94243ed1d724a9435cd8e22d7e5 | 453 | package linkedlists.lockfree;
/**
* Parent Node class used for the Run-Time Type Identification (RTTI)
* version of Harris-Michael's variant in Java. This is the code used in:
*
* A Concurrency-Optimal List-Based Set. Gramoli, Kuznetsov, Ravi, Shang. 2015.
*
* @author Di Shang
*/
public interface NodeBase {
public int value();
public NodeBase next();
public boolean casNext(NodeBase old, NodeBase newN);
}
| 22.65 | 80 | 0.675497 |
eef41850e5e3d57e80c02640b056e291e441eb54 | 1,405 | package org.andengine.extension.multiplayer.protocol.adt.message.server;
import org.andengine.extension.multiplayer.protocol.adt.message.Message;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:20:38 - 02.03.2011
*/
public abstract class ServerMessage extends Message implements IServerMessage {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 33.452381 | 79 | 0.26548 |
51c7d0cfbabf6c50eae9c5b68948a321681167f6 | 2,167 | package com.salesforce.bazel.sdk.bep.event;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.junit.Test;
public class BEPBuildConfigurationEventTest {
private static final String configEvent = "{\n" + " \"id\": {\n"
+ " \"configuration\": { \"id\": \"63cc040ed2b86a512099924e698df6e0b9848625e6ca33d9556c5993dccbc2fb\" }\n"
+ " },\n" + " \"configuration\": {\n" + " \"mnemonic\": \"darwin-fastbuild\",\n"
+ " \"platformName\": \"darwin\",\n" + " \"cpu\": \"darwin\",\n" + " \"makeVariable\": {\n"
+ " \"COMPILATION_MODE\": \"fastbuild\",\n" + " \"TARGET_CPU\": \"darwin\",\n"
+ " \"GENDIR\": \"bazel-out/darwin-fastbuild/bin\",\n"
+ " \"BINDIR\": \"bazel-out/darwin-fastbuild/bin\"\n" + " }\n" + " }\n" + "}";
@Test
public void testConfigEventParse() throws Exception {
String rawEvent = configEvent;
int index = 5;
JSONObject jsonEvent = (JSONObject) new JSONParser().parse(rawEvent);
// ctor parses the event, otherwise throws, which is the primary validation here
BEPConfigurationEvent event = new BEPConfigurationEvent(rawEvent, index, jsonEvent);
assertFalse(event.isError());
assertFalse(event.isLastMessage());
assertFalse(event.isProcessed());
assertEquals("configuration", event.getEventType());
assertEquals("darwin-fastbuild", event.getMnemonic());
assertEquals("darwin", event.getPlatformName());
assertEquals("darwin", event.getCpu());
String value = event.getMakeVariables().get("COMPILATION_MODE");
assertEquals("fastbuild", value);
value = event.getMakeVariables().get("TARGET_CPU");
assertEquals("darwin", value);
value = event.getMakeVariables().get("GENDIR");
assertEquals("bazel-out/darwin-fastbuild/bin", value);
value = event.getMakeVariables().get("BINDIR");
assertEquals("bazel-out/darwin-fastbuild/bin", value);
}
}
| 45.145833 | 121 | 0.620674 |
0caa8609c55eb6c15acb07a9d75cf7e437ff75ea | 4,886 | /*
* Copyright 2007-2009 Hilbrand Bouwkamp, hs@bouwkamp.com
*
* 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.cobogw.gwt.user.client.impl;
import com.google.gwt.dom.client.Element;
/**
* Internet Explorer 6, 7 and 8 implementation of
* {@link org.cobogw.gwt.user.client.impl.CSSImpl}.
*/
public class CSSImplIE6 extends CSSImpl {
public final static float documentMode = documentMode();
// private final static float ieVersion = detectIEVersion();
// private final static boolean inQuiksMode = inQuirksMode();
// private final static boolean isTridentEngine = isTridentEngine();
/**
* Returns the version of Internet Explorer
*
* @return Version of Internet Explorer
*/
@SuppressWarnings("unused")
private static native float detectIEVersion() /*-{
var index = navigator.userAgent.indexOf("MSIE") + 5;
if (index == -1) return 6.0; // assume IE 6 in this case
return parseFloat(navigator.userAgent.substring(index));
}-*/;
public static native boolean inQuirksMode() /*-{
return $doc.compatMode == 'BackCompat';
}-*/;
//Trident is the IE 8 JavaScript Engine.
@SuppressWarnings("unused")
private static native boolean isTridentEngine() /*-{
return navigator.userAgent.indexOf("Trident") != -1;
}-*/;
/**
* From http://www.howtocreate.co.uk/emails/AlexeiWhite.html:
* The document.documentMode property gives the version mode it is operating
* in (currently 5, 7 or 8). This is a floating point number and will increase
* for new versions, perhaps 8.5 or 9 or 10.35 etc. It is a new property in IE
* 8, so you can use it to see if it is IE 8+ in IE 7 mode, but it will not be
* possible to use its existence to check for IE 9 operating in IE 8 mode. It
* would be more useful if there were some property like document.maximumMode
* so you could see if it is really version 9 in version 8 mode, but I guess
* we will have to wait and see what new stuff appears in IE 9.
*
* Note that this property is non-standard, so it will not exist at all in
* other browsers, and it is very important that you do not display silly
* messages in other browsers because it does now exist and is therefore
* smaller than 8.
*
* @return Returns the documentMode
* @see <a href="http://www.howtocreate.co.uk/emails/AlexeiWhite.html">http://www.howtocreate.co.uk/emails/AlexeiWhite.html</a>
*/
private static native float documentMode() /*-{
return $doc.documentMode || 5.0;
}-*/;
@Override
public String getFloatAttribute() {
return "styleFloat";
}
/**
* This method takes care of the browser specific implementation requirements
* for the property value 'inline-block' of the property 'display'.
*
* For Internet Explorer 8 running in IE8 Standards mode the inline-block
* problem has been fixed. For that version the method simply sets
* <code>display</code> to <code>inline-block</code>. To detect what mode of
* IE* is running the <code>document.documentMode</code> is queried. When
* running in Quirks Mode this is not set and only for IE8 and IE8
* Compatibility View when running in IE 8 Standards mode it return 8. These
* are also the only conditions in which we want the inline-block.
*
* @see <a href="http://www.brunildo.org/test/InlineBlockLayout.html">http://www.brunildo.org/test/InlineBlockLayout.html</a>
* @see <a href="http://www.tanfa.co.uk/archives/show.asp?var=300">http://www.tanfa.co.uk/archives/show.asp?var=300</a>
* @see <a href="http://www.brunildo.org/test/inline-block.html">http://www.brunildo.org/test/inline-block.html</a>
*
* @param element Element to set the display property inline-block on
*/
@Override
public void setInlineBlock(Element element) {
if (documentMode >= 8) {
element.getStyle().setProperty("display", "inline-block");
} else {
element.getStyle().setProperty("display", "inline");
element.getStyle().setProperty("zoom", "1");
}
}
@Override
public void setOpacity(Element e, float opacity) {
e.getStyle().setProperty("filter", "alpha(opacity=" + opacity*100 + ")");
}
@Override
public void setSelectable(Element e, boolean selectable) {
e.getStyle().setProperty("userSelect", selectable ? "" : "none");
e.setPropertyString("unselectable", selectable ? "" : "on");
}
}
| 40.716667 | 129 | 0.700982 |
0a84978e851ad11be2396e05fea1279bf390903a | 9,082 | // Copyright 2008 Google Inc.
//
// 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.gwtorm.jdbc;
import com.google.common.base.Preconditions;
import com.google.gwtorm.schema.ColumnModel;
import com.google.gwtorm.schema.RelationModel;
import com.google.gwtorm.schema.SchemaModel;
import com.google.gwtorm.schema.SequenceModel;
import com.google.gwtorm.schema.sql.SqlDialect;
import com.google.gwtorm.server.AbstractSchema;
import com.google.gwtorm.server.OrmConcurrencyException;
import com.google.gwtorm.server.OrmDuplicateKeyException;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.Schema;
import com.google.gwtorm.server.StatementExecutor;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
/** Internal base class for implementations of {@link Schema}. */
public abstract class JdbcSchema extends AbstractSchema {
private final Database<?> dbDef;
private Connection conn;
private OrmException transactionException;
protected JdbcSchema(final Database<?> d) throws OrmException {
dbDef = d;
conn = dbDef.newConnection();
}
public final Connection getConnection() {
return conn;
}
public final SqlDialect getDialect() {
return dbDef.getDialect();
}
@Override
public void commit() throws OrmException {
try {
if (isInTransaction()) {
if (transactionException != null) {
OrmException e = transactionException;
transactionException = null;
if (e instanceof OrmConcurrencyException) {
throw new OrmConcurrencyException(e.getMessage(), e);
} else if (e instanceof OrmDuplicateKeyException) {
throw new OrmDuplicateKeyException(e.getMessage(), e);
} else {
throw new OrmException(e.getMessage(), e);
}
}
conn.commit();
}
} catch (SQLException err) {
throw new OrmException("Cannot commit transaction", err);
} finally {
try {
conn.setAutoCommit(true);
} catch (SQLException err) {
throw new OrmException("Cannot set auto commit mode", err);
}
}
}
@Override
public void rollback() throws OrmException {
try {
if (!conn.getAutoCommit()) {
transactionException = null;
conn.rollback();
}
} catch (SQLException err) {
throw new OrmException("Cannot rollback transaction", err);
} finally {
try {
conn.setAutoCommit(true);
} catch (SQLException err) {
throw new OrmException("Cannot set auto commit mode", err);
}
}
}
@Override
public void updateSchema(final StatementExecutor e) throws OrmException {
try {
createSequences(e);
createRelations(e);
for (final RelationModel rel : dbDef.getSchemaModel().getRelations()) {
addColumns(e, rel);
}
} catch (SQLException err) {
throw new OrmException("Cannot update schema", err);
}
}
private void createSequences(final StatementExecutor e) throws OrmException, SQLException {
final SqlDialect dialect = dbDef.getDialect();
final SchemaModel model = dbDef.getSchemaModel();
Set<String> have = dialect.listSequences(getConnection());
for (final SequenceModel s : model.getSequences()) {
if (!have.contains(s.getSequenceName().toLowerCase())) {
e.execute(s.getCreateSequenceSql(dialect));
}
}
}
private void createRelations(final StatementExecutor e) throws SQLException, OrmException {
final SqlDialect dialect = dbDef.getDialect();
final SchemaModel model = dbDef.getSchemaModel();
Set<String> have = dialect.listTables(getConnection());
for (final RelationModel r : model.getRelations()) {
if (!have.contains(r.getRelationName().toLowerCase())) {
e.execute(r.getCreateTableSql(dialect));
}
}
}
private void addColumns(final StatementExecutor e, final RelationModel rel)
throws SQLException, OrmException {
final SqlDialect dialect = dbDef.getDialect();
Set<String> have =
dialect.listColumns( //
getConnection(), rel.getRelationName().toLowerCase());
for (final ColumnModel c : rel.getColumns()) {
if (!have.contains(c.getColumnName().toLowerCase())) {
dialect.addColumn(e, rel.getRelationName(), c);
}
}
}
public void renameTable(final StatementExecutor e, String from, String to) throws OrmException {
Preconditions.checkNotNull(e);
Preconditions.checkNotNull(from);
Preconditions.checkNotNull(to);
getDialect().renameTable(e, from, to);
}
public void renameField(final StatementExecutor e, String table, String from, String to)
throws OrmException {
final RelationModel rel = findRelationModel(table);
if (rel == null) {
throw new OrmException("Relation " + table + " not defined");
}
final ColumnModel col = rel.getField(to);
if (col == null) {
throw new OrmException("Relation " + table + " does not have " + to);
}
getDialect().renameColumn(e, table, from, col);
}
public void renameColumn(final StatementExecutor e, String table, String from, String to)
throws OrmException {
final RelationModel rel = findRelationModel(table);
if (rel == null) {
throw new OrmException("Relation " + table + " not defined");
}
final ColumnModel col = rel.getColumn(to);
if (col == null) {
throw new OrmException("Relation " + table + " does not have " + to);
}
getDialect().renameColumn(e, table, from, col);
}
private RelationModel findRelationModel(String table) {
for (final RelationModel rel : dbDef.getSchemaModel().getRelations()) {
if (table.equalsIgnoreCase(rel.getRelationName())) {
return rel;
}
}
return null;
}
@Override
public void pruneSchema(final StatementExecutor e) throws OrmException {
try {
pruneSequences(e);
pruneRelations(e);
for (final RelationModel rel : dbDef.getSchemaModel().getRelations()) {
pruneColumns(e, rel);
}
} catch (SQLException err) {
throw new OrmException("Schema prune failure", err);
}
}
private void pruneSequences(final StatementExecutor e) throws SQLException, OrmException {
final SqlDialect dialect = dbDef.getDialect();
final SchemaModel model = dbDef.getSchemaModel();
HashSet<String> want = new HashSet<>();
for (final SequenceModel s : model.getSequences()) {
want.add(s.getSequenceName().toLowerCase());
}
for (final String sequence : dialect.listSequences(getConnection())) {
if (!want.contains(sequence)) {
e.execute(dialect.getDropSequenceSql(sequence));
}
}
}
private void pruneRelations(final StatementExecutor e) throws SQLException, OrmException {
final SqlDialect dialect = dbDef.getDialect();
final SchemaModel model = dbDef.getSchemaModel();
HashSet<String> want = new HashSet<>();
for (final RelationModel r : model.getRelations()) {
want.add(r.getRelationName().toLowerCase());
}
for (final String table : dialect.listTables(getConnection())) {
if (!want.contains(table)) {
e.execute("DROP TABLE " + table);
}
}
}
private void pruneColumns(final StatementExecutor e, final RelationModel rel)
throws SQLException, OrmException {
final SqlDialect dialect = dbDef.getDialect();
HashSet<String> want = new HashSet<>();
for (final ColumnModel c : rel.getColumns()) {
want.add(c.getColumnName().toLowerCase());
}
for (String column :
dialect.listColumns( //
getConnection(), rel.getRelationName().toLowerCase())) {
if (!want.contains(column)) {
dialect.dropColumn(e, rel.getRelationName(), column);
}
}
}
@Override
protected long nextLong(final String poolName) throws OrmException {
return getDialect().nextLong(getConnection(), poolName);
}
@Override
public void close() {
transactionException = null;
if (conn != null) {
try {
conn.close();
} catch (SQLException err) {
// TODO Handle an exception while closing a connection
}
conn = null;
}
}
boolean isInTransaction() throws SQLException {
return !conn.getAutoCommit();
}
void setTransactionException(OrmException ex) {
// commit() needs a single cause, so just take the first.
if (transactionException == null) {
transactionException = Preconditions.checkNotNull(ex);
}
}
}
| 32.669065 | 98 | 0.67386 |
d60ebe0d31f1684be411b8f06d64450fce44023a | 428 | package pl.jakubz.simplehouse.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class LoginController {
public LoginController() {
}
@GetMapping("/loginForm")
public String showLogin(){
return "login";
}
@GetMapping("/denied")
public String accessDenied(){
return "access-denied";
}
}
| 19.454545 | 58 | 0.693925 |
506518dc4d80e01847914013ffea76238b6ae7da | 3,453 | package de.androbin.remote.http;
import de.androbin.remote.http.message.*;
import de.androbin.remote.http.message.Message.*;
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
public final class NetworkHelper {
private static final String IP_REGEX = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
private Thread senderThread;
private Thread receiverThread;
private volatile boolean running;
private Socket socket;
private BufferedWriter outputStream;
private BufferedReader inputStream;
private final BlockingQueue<Supplier<Request>> output;
private final BlockingQueue<Response> input;
public NetworkHelper() {
this.input = new LinkedBlockingQueue<>();
this.output = new LinkedBlockingQueue<>();
}
public static boolean checkAddress( final String ip, final int port ) {
return ip.matches( IP_REGEX ) && port >= 1024 && port < 49152;
}
public Response receive() {
try {
return input.take();
} catch ( final InterruptedException e ) {
return null;
}
}
public void runReceiver() {
while ( running ) {
final Response response;
try {
response = MessageDecoder.decodeResponse( inputStream );
} catch ( final IOException ignore ) {
running = false;
continue;
}
try {
input.put( response );
} catch ( final InterruptedException e ) {
running = false;
}
}
}
public void runSender() {
while ( running ) {
final Supplier<Request> request;
try {
request = output.take();
} catch ( final InterruptedException e ) {
continue;
}
try {
MessageEncoder.encodeRequest( request.get(), outputStream );
} catch ( final IOException e ) {
running = false;
}
}
}
public void send( final Supplier<Request> request ) {
try {
output.put( request );
} catch ( final InterruptedException ignore ) {
}
}
public Response sendAndReceive( final Lock lock, final Supplier<Request> request ) {
lock.lock();
send( request );
synchronized ( this ) {
lock.unlock();
return receive();
}
}
public boolean start( final String ip, final int port ) {
if ( running ) {
return true;
}
try {
socket = new Socket( ip, port );
outputStream = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
inputStream = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
} catch ( final IOException e ) {
return false;
}
running = true;
senderThread = new Thread( this::runSender, "NetworkHelper Sender" );
senderThread.setDaemon( true );
senderThread.start();
receiverThread = new Thread( this::runReceiver, "NetworkHelper Receiver" );
receiverThread.setDaemon( true );
receiverThread.start();
return true;
}
public boolean stop() {
if ( !running ) {
return true;
}
running = false;
senderThread.interrupt();
senderThread = null;
receiverThread.interrupt();
receiverThread = null;
try {
socket.close();
} catch ( final IOException e ) {
return false;
}
return true;
}
} | 23.979167 | 128 | 0.607877 |
f6484e6853529ddcf6a9bbbbd4b73d8f2cf90f3b | 8,646 | /*******************************************************************************
* * Copyright 2015 Impetus Infotech.
* *
* * 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.impetus.client.hbase.admin;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Row;
import org.apache.hadoop.hbase.filter.FilterList;
import com.impetus.kundera.db.RelationHolder;
import com.impetus.kundera.metadata.model.EntityMetadata;
/**
* The Interface DataHandler.
*
* @author Pragalbh Garg
*/
public interface DataHandler
{
/**
* Creates the table if does not exist.
*
* @param tableName
* the table name
* @param colFamily
* the col family
* @throws IOException
* Signals that an I/O exception has occurred.
*/
void createTableIfDoesNotExist(String tableName, String... colFamily) throws IOException;
// /**
// * Read data.
// *
// * @param tableName
// * the table name
// * @param clazz
// * the clazz
// * @param m
// * the m
// * @param rowKey
// * the row key
// * @param relatationNames
// * the relatation names
// * @param f
// * the f
// * @param colToOutput
// * the col to output
// * @return the list
// * @throws IOException
// * Signals that an I/O exception has occurred.
// */
// List readData(String tableName, Class clazz, EntityMetadata m, Object
// rowKey, List<String> relatationNames,
// FilterList f, List<Map<String, Object>> colToOutput) throws IOException;
/**
* Read data.
*
* @param tableName
* the table name
* @param m
* the m
* @param rowKey
* the row key
* @param startRow
* the start row
* @param endRow
* the end row
* @param columnsToOutput
* the columns to output
* @param filterList
* the filter list
* @return the list
* @throws IOException
* Signals that an I/O exception has occurred.
*/
List readData(String tableName, EntityMetadata m, final Object rowKey, byte[] startRow, byte[] endRow,
List<Map<String, Object>> columnsToOutput, FilterList filterList) throws IOException;
/**
* Read all.
*
* @param tableName
* the table name
* @param clazz
* the clazz
* @param m
* the m
* @param rowKeys
* the row keys
* @param relatationNames
* the relatation names
* @param columns
* the columns
* @return the list
* @throws IOException
* Signals that an I/O exception has occurred.
*/
List readAll(String tableName, Class clazz, EntityMetadata m, List<Object> rowKeys, List<String> relatationNames,
String... columns) throws IOException;
// /**
// * Read data by range.
// *
// * @param tableName
// * the table name
// * @param clazz
// * the clazz
// * @param m
// * the m
// * @param startRow
// * the start row
// * @param endRow
// * the end row
// * @param colToOutput
// * the col to output
// * @param f
// * the f
// * @return the list
// * @throws IOException
// * Signals that an I/O exception has occurred.
// */
// List readDataByRange(String tableName, Class clazz, EntityMetadata m,
// byte[] startRow, byte[] endRow,
// List<Map<String, Object>> colToOutput, FilterList f) throws IOException;
/**
* Write data.
*
* @param schemaName
* the schema name
* @param m
* the m
* @param entity
* the entity
* @param rowId
* the row id
* @param relations
* the relations
* @param showQuery
* the show query
* @throws IOException
* Signals that an I/O exception has occurred.
*/
void writeData(String schemaName, EntityMetadata m, Object entity, Object rowId, List<RelationHolder> relations,
boolean showQuery) throws IOException;
/**
* Write join table data.
*
* @param tableName
* the table name
* @param rowId
* the row id
* @param columns
* the columns
* @param columnFamilyName
* the column family name
* @throws IOException
* Signals that an I/O exception has occurred.
*/
void writeJoinTableData(String tableName, Object rowId, Map<String, Object> columns, String columnFamilyName)
throws IOException;
/**
* Gets the foreign keys from join table.
*
* @param <E>
* the element type
* @param schemaName
* the schema name
* @param joinTableName
* the join table name
* @param rowKey
* the row key
* @param inverseJoinColumnName
* the inverse join column name
* @return the foreign keys from join table
*/
<E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,
String inverseJoinColumnName);
/**
* Find parent entity from join table.
*
* @param <E>
* the element type
* @param parentMetadata
* the parent metadata
* @param joinTableName
* the join table name
* @param joinColumnName
* the join column name
* @param inverseJoinColumnName
* the inverse join column name
* @param childId
* the child id
* @return the list
*/
<E> List<E> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,
String joinColumnName, String inverseJoinColumnName, Object childId);
/**
* Shutdown.
*/
void shutdown();
/**
* Delete row.
*
* @param rowKey
* the row key
* @param colName
* the col name
* @param colFamily
* the col family
* @param tableName
* the table name
* @throws IOException
* Signals that an I/O exception has occurred.
*/
void deleteRow(Object rowKey, String colName, String colFamily, String tableName) throws IOException;
/**
* Scan rowy keys.
*
* @param filterList
* the filter list
* @param tableName
* the table name
* @param columnFamilyName
* the column family name
* @param columnName
* the column name
* @param rowKeyClazz
* the row key clazz
* @return the object[]
* @throws IOException
* Signals that an I/O exception has occurred.
*/
Object[] scanRowyKeys(FilterList filterList, String tableName, String columnFamilyName, String columnName,
Class rowKeyClazz) throws IOException;
/**
* Prepare put.
*
* @param hbaseRow
* the hbase row
* @return the put
*/
Put preparePut(HBaseRow hbaseRow);
/**
* Prepare delete.
*
* @param rowKey
* the row key
* @return the row
*/
Row prepareDelete(Object rowKey);
/**
* Batch process.
*
* @param batchData
* the batch data
*/
void batchProcess(Map<String, List<Row>> batchData);
}
| 30.020833 | 118 | 0.53331 |
45bde5534d5fa8f5c610f8fa110254009555f228 | 258 | package com.jacobmountain.resolvers.dto;
import lombok.Data;
import java.util.List;
@Data
public class FriendsConnection {
private Integer totalCount;
private List<FriendsEdge> edges;
private List<Character> friends;
private PageInfo pageInfo;
}
| 13.578947 | 40 | 0.782946 |
8c21037a8140924739fe28a4bc13ff12573ee7cb | 1,269 | package com.ThreadPool;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ThreadHistory3 {
private static final int threadNum = 100;
private static final Executor exec = Executors.newFixedThreadPool(threadNum);
public static void handleRequest(Socket socket) {
try {
InputStream is = socket.getInputStream();
byte[] buff = new byte[1024];
int len = is.read(buff);
if (len > 0) {
// 将读取出来的字节信息 转化成明文信息
String msg = new String(buff, 0, len);
System.out.println("客户端的请求信息:=======" + msg + "========");
// 解析出来uri
System.out.println("msg:=======" + msg + "========");
} else {
System.out.println("bad Request!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ServerSocket server;
try {
server = new ServerSocket(8080);
while (true) {
final Socket client = server.accept();
Runnable task = new Runnable() {
@Override
public void run() {
// 业务
handleRequest(client);
}
};
exec.execute(task);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 21.508475 | 78 | 0.635146 |
b5d68ec4c5710018ac353d1c36b995fb8e29116d | 5,607 | /*
* 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.custos.resource.secret.validator;
import org.apache.custos.core.services.commons.Validator;
import org.apache.custos.core.services.commons.exceptions.MissingParameterException;
import org.apache.custos.resource.secret.service.*;
/**
* This class validates the requests
*/
public class InputValidator implements Validator {
/**
* Input parameter validater
*
* @param methodName
* @param obj
* @return
*/
public void validate(String methodName, Object obj) {
switch (methodName) {
case "getAllResourceCredentialSummaries":
validateGetAllResourceCredentialSummaries(obj, methodName);
break;
case "addSSHCredential":
validateAddSSHCredential(obj, methodName);
break;
case "addPasswordCredential":
validateAddPasswordCredential(obj, methodName);
break;
case "addCertificateCredential":
validateAddCertificateCredential(obj, methodName);
break;
case "getPasswordCredential":
case "getCertificateCredential":
case "getSSHCredential":
case "deleteSSHCredential":
case "deletePWDCredential":
case "getResourceCredentialSummary":
validateGetResourceCredentialByToken(obj, methodName);
break;
default:
}
}
private boolean validateGetResourceCredentialByToken(Object obj, String methodName) {
if (obj instanceof GetResourceCredentialByTokenRequest) {
GetResourceCredentialByTokenRequest request = (GetResourceCredentialByTokenRequest) obj;
if (request.getTenantId() == 0) {
throw new MissingParameterException("TenantId should be set", null);
}
if (request.getToken() == null || request.getToken().equals("")) {
throw new MissingParameterException("Token should not be null", null);
}
} else {
throw new RuntimeException("Unexpected input type for method " + methodName);
}
return true;
}
private boolean validateGetAllResourceCredentialSummaries(Object obj, String methodName) {
if (obj instanceof GetResourceCredentialSummariesRequest) {
GetResourceCredentialByTokenRequest request = (GetResourceCredentialByTokenRequest) obj;
if (request.getTenantId() == 0) {
throw new MissingParameterException("TenantId should be set", null);
}
} else {
throw new RuntimeException("Unexpected input type for method " + methodName);
}
return true;
}
private boolean validateAddSSHCredential(Object obj, String methodName) {
if (obj instanceof SSHCredential) {
SSHCredential request = (SSHCredential) obj;
validateSecretMetadata(request.getMetadata());
} else {
throw new RuntimeException("Unexpected input type for method " + methodName);
}
return true;
}
private boolean validateAddPasswordCredential(Object obj, String methodName) {
if (obj instanceof PasswordCredential) {
PasswordCredential request = (PasswordCredential) obj;
validateSecretMetadata(request.getMetadata());
if (request.getPassword() == null || request.getPassword().trim().equals("")) {
throw new MissingParameterException("Password should not be null ", null);
}
} else {
throw new RuntimeException("Unexpected input type for method " + methodName);
}
return true;
}
private boolean validateAddCertificateCredential(Object obj, String methodName) {
if (obj instanceof CertificateCredential) {
CertificateCredential request = (CertificateCredential) obj;
validateSecretMetadata(request.getMetadata());
if (request.getX509Cert() == null || request.getX509Cert().trim().equals("")) {
throw new MissingParameterException("Certificate should not be null", null);
}
} else {
throw new RuntimeException("Unexpected input type for method " + methodName);
}
return true;
}
private boolean validateSecretMetadata(SecretMetadata metadata) {
if (metadata.getOwnerId() == null || metadata.getOwnerId().trim().equals("")) {
throw new MissingParameterException("OwnerId should not be null", null);
}
if (metadata.getTenantId() == 0) {
throw new MissingParameterException("TenantId should be set", null);
}
return true;
}
}
| 34.398773 | 100 | 0.64366 |
2e8a9df31612d0bc6ccbad2a5f0d0a983efcf131 | 13,079 | package org.contentmine.ami.tools;
import java.io.File;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.contentmine.ami.tools.AMIImageTool;
import org.junit.Test;
/** test cleaning.
*
* @author pm286
*
*/
public class AMIImageTest {
private static final String OLD_DEVTEST = "/Users/pm286/workspace/uclforest/devtest/";
private static final Logger LOG = Logger.getLogger(AMIImageTest.class);
static {
LOG.setLevel(Level.DEBUG);
}
@Test
public void testHelp() {
new AMIImageTool().runCommands("--help");
}
@Test
/**
*/
public void testFilterTrees() throws Exception {
String args =
// "-t /Users/pm286/workspace/uclforest/devtest/bowmann-perrottetal_2013"
// "-t /Users/pm286/workspace/uclforest/devtest/buzick_stone_2014_readalo"
// "-t /Users/pm286/workspace/uclforest/devtest/campbell_systematic_revie"
// "-t /Users/pm286/workspace/uclforest/devtest/case_systematic_review_ar"
"-t " + OLD_DEVTEST + "mcarthur_etal2012_cochran"
// "-t /Users/pm286/workspace/uclforest/devtest/puziocolby2013_co-operati"
// "-t /Users/pm286/workspace/uclforest/devtest/torgersonetal_2011dferepo"
// "-t /Users/pm286/workspace/uclforest/devtest/zhengetal_2016"
+ " --sharpen sharpen4"
+ " --threshold 180"
+ " --binarize GLOBAL_ENTROPY"
// + " --rotate 270"
+ " --priority SCALE"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
* mainly for visual inspection of results
*/
public void testBinarize() throws Exception {
String args =
// "-t /Users/pm286/workspace/uclforest/devtest/bowmann-perrottetal_2013"
// "-t /Users/pm286/workspace/uclforest/devtest/buzick_stone_2014_readalo"
// "-t /Users/pm286/workspace/uclforest/devtest/campbell_systematic_revie"
"-t /Users/pm286/workspace/uclforest/devtest/case_systematic_review_ar"
// "-t /Users/pm286/workspace/uclforest/devtest/mcarthur_etal2012_cochran"
// "-t /Users/pm286/workspace/uclforest/devtest/puziocolby2013_co-operati"
// "-t /Users/pm286/workspace/uclforest/devtest/torgersonetal_2011dferepo"
// "-t /Users/pm286/workspace/uclforest/devtest/zhengetal_2016"
// + " --sharpen sharpen4"
+ " --threshold 180"
+ " --binarize BLOCK_OTSU"
// + " --rotate 270"
+ " --priority SCALE"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
* mainly for visual inspection of results
*/
public void testBinarizeMethods() throws Exception {
String args = "-t /Users/pm286/workspace/uclforest/devtest/case_systematic_review_ar --binarize ";
String[] methods = {
"GLOBAL_MEAN",
"GLOBAL_ENTROPY",
"BLOCK_MIN_MAX",
"BLOCK_OTSU",
// "LOCAL_MEAN", // large spurius blocks
// "BLOCK_MEAN", // many large spurious blocks
// "LOCAL_GAUSSIAN", // spurious blocks
// "LOCAL_SAUVOLA", // stripes
// "LOCAL_NICK", // erosion
// "GLOBAL_OTSU", // spurious blocks
};
for (String method : methods) {
new AMIImageTool().runCommands(args + method);
}
}
@Test
/**
* mainly for visual inspection of results
*/
public void testBinarizeMethodsAll() throws Exception {
String[] names = {
"bowmann-perrottetal_2013",
"buzick_stone_2014_readalo",
"campbell_systematic_revie",
"case_systematic_review_ar",
"case-systematic-review-ju",
"cole_2014",
"davis2010_dissertation",
"donkerdeboerkostons2014_l",
"ergen_canagli_17_",
"fanetal_2017_meta_science",
"higginshallbaumfieldmosel",
"kunkel_2015",
"marulis_2010-300-35review",
"mcarthur_etal2012_cochran",
"puziocolby2013_co-operati",
"rui2009_meta_detracking",
"shenderovichetal_2016_pub",
"torgersonetal_2011dferepo",
"zhengetal_2016",
};
String[] methods = {
"GLOBAL_MEAN",
"GLOBAL_ENTROPY",
"BLOCK_MIN_MAX",
"BLOCK_OTSU",
};
for (String name : names) {
String tree = "-t /Users/pm286/workspace/uclforest/devtest/";
String treename = tree + name;
String args = treename + " --binarize ";
for (String method : methods) {
// new AMIImageTool().runCommands(args + method);
}
for (int threshold : new int[] {120, 140, 160, 180, 200, 220}) {
args = treename + " --monochrome --small --duplicate --sharpen sharpen4 --threshold "+threshold;
new AMIImageTool().runCommands(args);
}
}
}
/**
imageProcessor.setThreshold(180);
This is a poor subpixel image which need thresholding and sharpening
*/
@Test
public void testFilterProject() throws Exception {
String args =
"-p /Users/pm286/workspace/uclforest/devtest/"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
*/
public void testBinarizeTrees() throws Exception {
String args =
// "-t /Users/pm286/workspace/uclforest/devtest/bowmann-perrottetal_2013"
"-t /Users/pm286/workspace/uclforest/devtest/buzick_stone_2014_readalo"
// "-t /Users/pm286/workspace/uclforest/devtest/campbell_systematic_revie"
// "-t /Users/pm286/workspace/uclforest/devtest/mcarthur_etal2012_cochran"
// "-t /Users/pm286/workspace/uclforest/devtest/puziocolby2013_co-operati"
// "-t /Users/pm286/workspace/uclforest/devtest/torgersonetal_2011dferepo"
// "-t /Users/pm286/workspace/uclforest/devtest/zhengetal_2016"
// + " --binarize xLOCAL_MEAN"
+ " --threshold 180"
+ " --sharpen x"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
imageProcessor.setThreshold(180);
This is a poor subpixel image which need thresholding and sharpening
*/
public void testScale() throws Exception {
String args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --scalefactor 0.5"
+ " --maxwidth 100"
+ " --maxheight 100"
+ " --basename scale0_5";
new AMIImageTool().runCommands(args);
}
@Test
/**
* rotate by multiples of 90 degrees
*/
public void testRotate() throws Exception {
String args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --rotate 90"
+ " --basename rot90";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --rotate 180"
+ " --basename rot180";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --rotate 270"
+ " --basename rot270";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --rotate 0"
+ " --basename rot0";
new AMIImageTool().runCommands(args);
}
@Test
/**
imageProcessor.setThreshold(180);
This is a poor subpixel image which need thresholding and sharpening
*/
public void testThreshold() throws Exception {
String args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --basename noop";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 160"
+ " --basename thresh160";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 20"
+ " --basename thresh20"
;
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 30"
+ " --basename thresh30"
;
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 35"
+ " --basename thresh35"
;
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 40"
+ " --basename thresh40"
;
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 200"
// + " --thinning none"
// + " --binarize min_max"
+ " --basename threshold200";
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 220"
// + " --thinning none"
// + " --binarize min_max"
+ " --basename threshold220";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 225"
// + " --thinning none"
// + " --binarize min_max"
+ " --basename threshold225";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 230"
// + " --thinning none"
// + " --binarize min_max"
+ " --basename threshold230";
new AMIImageTool().runCommands(args);
args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --threshold 240"
// + " --thinning none"
// + " --binarize min_max"
+ " --basename threshold240";
new AMIImageTool().runCommands(args);
}
@Test
/**
*/
public void testBitmapForestPlotsSmall() throws Exception {
String args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --threshold 180"
// + " --thinning none"
+ " --binarize entropy"
;
new AMIImageTool().runCommands(args);
}
// @Test
// /**
// */
// public void testSharpen() throws Exception {
// String[] args = {
// "-p /Users/pm286/workspace/uclforest/forestplotssmall"
// + " --sharpen laplacian"
// };
// new AMIBitmapTool().runCommands(args);
// }
@Test
/**
*/
public void testSharpen() throws Exception {
String args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen sharpen4"
+ " --basename sharpen4"
;
new AMIImageTool().runCommands(args);
args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen sharpen8"
+ " --basename sharpen8"
;
new AMIImageTool().runCommands(args);
args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen laplacian"
+ " --basename laplacian"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
*/
public void testSharpenBoofcv() throws Exception {
String args =
"-t /Users/pm286/workspace/uclforest/forestplotssmall/cole"
+ " --sharpen sharpen4"
+ " --basename sharpen4mean"
// + " --binarize local_mean"
;
new AMIImageTool().runCommands(args);
args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen laplacian"
+ " --basename laplacian"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
*/
public void testSharpenThreshold1() throws Exception {
String args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen sharpen8"
+ " --basename sharpen8otsu"
+ " --binarize block_otsu"
;
new AMIImageTool().runCommands(args);
args =
"-p /Users/pm286/workspace/uclforest/forestplotssmall"
+ " --sharpen laplacian"
+ " --basename laplacian180"
+ " --threshold 180"
;
new AMIImageTool().runCommands(args);
}
@Test
/**
*
*/
public void testImageForestPlotsSmall() throws Exception {
String[] args = {
"-p", "/Users/pm286/workspace/uclforest/forestplotssmall",
"--monochrome", "true",
"--monochromedir", "monochrome",
"--minwidth", "100",
"--minheight", "100",
"--smalldir", "small",
"--duplicates", "true",
"--duplicatedir", "duplicates",
};
AMIImageTool amiImage = new AMIImageTool();
amiImage.runCommands(args);
}
@Test
/**
*
*/
public void testImagePanels() throws Exception {
// NYI
String userDir = System.getProperty("user.home");
File projectDir = new File(userDir, "projects/forestplots/spss");
String args =
"-p "+projectDir+
" --minwidth 100"+
" --minheight 100"+
" --monochrome monochrome"+
" --small small"+
" --duplicate duplicate"
;
AMIImageTool amiImage = new AMIImageTool();
amiImage.runCommands(args);
}
@Test
public void testAddBorders() {
String userDir = System.getProperty("user.home");
File projectDir = new File(userDir, "projects/forestplots/spss");
File treeDir = new File(projectDir, "PMC5502154");
String args =
"-t "+treeDir+
" --scalefactor 2.0"+
" --erodedilate" +
" --borders 10 "
;
AMIImageTool amiImage = new AMIImageTool();
amiImage.runCommands(args);
}
@Test
public void testImageBug() {
String userDir = System.getProperty("user.home");
File projectDir = new File(userDir, "projects/carnegiemellon");
File treeDir = new File(projectDir, "p2nax");
String args =
"-t "+treeDir
;
AMIImageTool amiImage = new AMIImageTool();
amiImage.runCommands(args);
}
@Test
public void testTemplate() {
String userDir = System.getProperty("user.home");
File projectDir = new File(userDir, "projects/carnegiemellon");
File treeDir = new File(projectDir, "p2nax");
String args =
"-t "+treeDir+
// " --template" +
" --help"
;
AMIImageTool amiImage = new AMIImageTool();
amiImage.runCommands(args);
}
}
| 27.768577 | 100 | 0.653108 |
edf58c0ad54ff22bb496c36cd52563c58c70397a | 27,227 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package BeanBagger;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import java.io.BufferedWriter;
import java.util.Set;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.management.*;
import javax.management.ObjectInstance;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.concurrent.TimeUnit;
/**
*
* @author s.ostenberg
*/
public class BeanBagger {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
private static final String CONNECTOR_ADDRESS_PROPERTY = "com.sun.management.jmxremote.localConnectorAddress";
public static VirtualMachineDescriptor TARGETDESCRIPTOR ;
static JMXConnector myJMXconnector = null;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
//Get the MBean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//register the MBean
BBConfig mBean = new BBConfig();
ObjectName name = new ObjectName("com.stiv.jmx:type=BBConfig");
mbs.registerMBean(mBean, name);
for(int x =0;x<args.length;x++)
{
String disarg = args[x];
switch(disarg)
{
case "-p":
if(x==args.length && !args[x+1].startsWith("-"))Usage();
mBean.setTargetJVM(args[x+1]);
x++;
break;
case "-pp" :
mBean.setprettyprint(true);
break;
case "-j":
mBean.setoutJSON(true);
if(args.length-1>x && !args[x+1].startsWith("-"))//If next item on line exists and is not an option
{
mBean.setJSONFile(args[x+1]);
x++;
}
break;
case "-b":
if(args.length-1>x && !args[x+1].startsWith("-"))
{
mBean.setTARGETBEAN(args[x+1]);
x++;
}
break;
case "-r":
mBean.setignoreunreadable(true);
break;
case "-q":
mBean.setconsoleout(false);
break;
case "-u":
mBean.setsuppresscomplex(true);
break;
case "-m":
mBean.setsupressSun(true);
break;
case "-x":
mBean.setExactMatchRequired(true);
break;
case "-log":
if(args.length-1>x && !args[x+1].startsWith("-"))//If next item on line exists and is not an option
{
mBean.setLogDir(args[x+1]);
try
{
File theDir = new File(mBean.getLogDir());
// if the directory does not exist, create it
if (!theDir.exists())
{
if(mBean.getconsoleout())System.out.println("creating directory: " + mBean.getLogDir());
theDir.mkdir();
}
}
catch(Exception ex)
{
System.out.println("Error creating directory: " + mBean.getLogDir());
System.exit(1);
}
// Write a readme file to the directory as a test
try{
String rmf = mBean.getLogDir() + "/BeanBaggerreadme.txt";
try (PrintWriter out = new PrintWriter(rmf)) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
out.println("Beanbagger started " + dateFormat.format(date) );
//consider adding options outlining the arguments started with.
out.close();
}
}
catch(Exception ex){
System.out.println("Error creating files in: " + mBean.getLogDir());
}
x++;
}
break;
case "-l":
mBean.setLoop(true);
if(args.length-1>x && !args[x+1].startsWith("-"))
{
try{
mBean.setLoopDelaySeconds(Integer.parseInt(args[x+1]));}
catch(Exception ex){
System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?");
Usage();
}
x++;
}
else{mBean.setLoopDelaySeconds(30); }
break;
case "-c":
mBean.setLoop(true);
if(args.length-1>x && !args[x+1].startsWith("-"))
{
try{
mBean.setIterations(Integer.parseInt(args[x+1]));}
catch(Exception ex){
System.out.println("You call " + args[x+1] + " an integer" +mBean.getInsult()+"?");
Usage();
}
x++;
}
else{mBean.setIterations(5);}
break;
default:
Usage();
}//End switch
}
//Variables have been set. We are done with intitial config
Boolean loopagain=false;
do { //Here we go, into da loop
try {
//The following code grabs a list of running VMs and sees if they match our target--------------------------------------
Map<String, VirtualMachine> result = new HashMap<>();
List<VirtualMachineDescriptor> list = VirtualMachine.list();
List<VirtualMachineDescriptor> MATCHINGLIST = new ArrayList<VirtualMachineDescriptor>();
Boolean gotit = false;
String listofjvs = "";
if(mBean.getconsoleout())System.out.println("Searching for matching VM instances");
for (VirtualMachineDescriptor vmd : list) {
String desc = vmd.toString();
try {
result.put(desc, VirtualMachine.attach(vmd));
String DN = vmd.displayName();
if (DN.contains(mBean.getTargetJVM()) || mBean.getTargetJVM().equalsIgnoreCase("*")) {
if (DN.equals("")) {
if(mBean.getconsoleout())System.out.println(" Skipping unnamed JVM");
} else if(!mBean.getTargetJVM().startsWith("BeanBagger") && DN.contains("BeanBagger")){
if(mBean.getconsoleout())System.out.println(" Skipping BeanBagger JVM"); }
else {
if(mBean.getconsoleout())System.out.println(" Matching JVM instance found: " + DN);
TARGETDESCRIPTOR = vmd;
gotit = true;
MATCHINGLIST.add(vmd);
}
} else {
listofjvs += DN + " \n";
}
} catch (IOException | AttachNotSupportedException e) {
}
}
if (!gotit)//If we dont find the instance.
{
System.out.println("No JVM Processes matching " + mBean.getTargetJVM() + " were found.");
System.out.println("Found instances: " + listofjvs);
System.exit(1);
}
System.out.println("");
///-------------If we get here, we have identified at least one instance matching our criteria
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
org.json.JSONObject Jinfrascan = new org.json.JSONObject();//Contains Hosts
org.json.JSONArray Hosts = new org.json.JSONArray();
org.json.JSONObject Host = new org.json.JSONObject();
org.json.JSONArray JVMs = new org.json.JSONArray();//JVMs on host
for (VirtualMachineDescriptor avmd : MATCHINGLIST) {
myJMXconnector = getLocalConnection(VirtualMachine.attach(avmd));// Connects to the process containing our beans
MBeanServerConnection myJMXConnection = myJMXconnector.getMBeanServerConnection(); //Connects to the MBean server for that process.
if(mBean.getconsoleout())System.out.println("Number of beans found in " +ANSI_CYAN+ avmd.displayName() + ANSI_RESET+ ": " + myJMXConnection.getMBeanCount());
String getDefaultDomain = myJMXConnection.getDefaultDomain();
String[] getDomains = myJMXConnection.getDomains();
Set<ObjectInstance> beans = myJMXConnection.queryMBeans(null, null);
org.json.JSONObject JVM = new org.json.JSONObject();
org.json.JSONArray JBeans = new org.json.JSONArray();
for (ObjectInstance instance : beans) {
String daclassname = instance.getClassName();
ObjectName oname = instance.getObjectName();
String BeanName = oname.getCanonicalName();
Hashtable<String,String> harry = oname.getKeyPropertyList();
if (mBean.getsupressSun() & (daclassname.startsWith("sun.") | daclassname.startsWith("com.sun."))) {
continue;
}
if (daclassname.contains(mBean.getTARGETBEAN()) || mBean.getTARGETBEAN().contentEquals("*")) {
MBeanAttributeInfo[] myAttributeArray = null;
org.json.JSONObject Beanboy = new org.json.JSONObject();
org.json.JSONArray BeanieButes = new org.json.JSONArray();
try {
MBeanInfo info = myJMXConnection.getMBeanInfo(instance.getObjectName());
myAttributeArray = info.getAttributes();
if(mBean.getconsoleout())System.out.println(" Processing bean: " +ANSI_GREEN+BeanName+ANSI_RESET);
} catch (UnsupportedOperationException | RuntimeMBeanException | IllegalStateException ex) {
if(mBean.getconsoleout())System.out.println(" Error processing bean: " + BeanName);
}
for (MBeanAttributeInfo thisAttributeInfo : myAttributeArray) {
String attvalue = "";
String myname = "";
String mytype = "";
String mydesc = "";
boolean myread = false;
boolean mywrite = false;
try {
myname = thisAttributeInfo.getName();
mydesc = thisAttributeInfo.getDescription();
mytype = thisAttributeInfo.getType();
myread = thisAttributeInfo.isReadable();
mywrite = thisAttributeInfo.isWritable();
if (myread) {
switch (mytype) {
case "String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "java.lang.String":
attvalue = (String) myJMXConnection.getAttribute(instance.getObjectName(), myname);
break;
case "boolean":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "int":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "long":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
case "double":
attvalue = myJMXConnection.getAttribute(instance.getObjectName(), myname).toString();
break;
default:
attvalue = "*-Unsupported: complex type-*";
break;
}//end switch
}//end if
else {
attvalue = "";
}
} catch (Exception ex) {
attvalue = "*-Exception: Unavailable-*";
}
//THis section is where we determine if we are going to record the value or not.
boolean dooutput = false;
if (!mBean.getsuppresscomplex()) {
dooutput = true;
} else {
try {
if (!attvalue.startsWith("*-") ) {
dooutput = true;
}
} catch (Exception ex)//For attributes with no values.
{
attvalue = "*-Unavailable-*";
if (!mBean.getsuppresscomplex())dooutput = true;
}
}
if (mBean.getignoreunreadable() && !myread) {
dooutput = false;
}
if (dooutput) {
org.json.JSONObject AtDatas = new org.json.JSONObject();// Create the list of attributes and values into an object.
AtDatas.put("Name", myname);
AtDatas.put("Type", mytype);
String attvaluecolor="";
if(attvalue == null)attvalue="*-NULL-*";
if(attvalue.startsWith("*-U")){
attvaluecolor=ANSI_PURPLE+attvalue+ANSI_RESET;}
else if(attvalue.startsWith("*-E")){
attvaluecolor=ANSI_RED+attvalue+ANSI_RESET;}
else attvaluecolor=attvalue;
if(attvalue.equals("")){
attvaluecolor=ANSI_YELLOW+"\"\""+ANSI_RESET;}
if (myread) {
AtDatas.put("Value", attvalue);
if(mBean.getconsoleout())System.out.println(" Name:" + myname + " Type:" + mytype + " Writeable:" + mywrite + " Readable:" + myread + " Value:" + attvaluecolor );
} else {
if(mBean.getconsoleout())System.out.println(" Name:" + myname + " Type:" + mytype + " Writeable:" + mywrite+ " Readable:" + myread );
AtDatas.put("Readable", myread);
}
AtDatas.put("Desc", mydesc);
if (mywrite) {
AtDatas.put("Writable", mywrite);
}
BeanieButes.put(AtDatas);
}
}//End processing Bean Attributes, add attributes to bean array.
Beanboy.put(BeanName, BeanieButes);//add attributes to the bean
JBeans.put(Beanboy);//add bean to VM
}//End if this bean was skipped.
}//End of process JVM instance beans
JVM.put(avmd.displayName(), JBeans);
JVMs.put(JVM);
}//End JVM iteration
java.net.InetAddress addr = java.net.InetAddress.getLocalHost();
String mename = addr.getHostName();
Host.put(mename, JVMs);
//add vms to host
Hosts.put(Host);
//add server(s) to infra
String time = String.valueOf(System.currentTimeMillis());
Jinfrascan.put(time, Hosts);
mBean.setLastJSON(Jinfrascan.toString());
// OK. How do I dump the JSON?
if (!mBean.getJSONFile().equals("")) {
try {
PrintWriter writer = new PrintWriter(mBean.getJSONFile(), "UTF-8");
if (mBean.getprettyprint()) {
writer.println(Jinfrascan.toString(4));
} else {
writer.println(Jinfrascan);
}
writer.close();
} catch (Exception ex) {
System.out.print("Error processing file!");
System.out.print(ex);
}
}
if(mBean.getoutJSON()){
System.out.println("JSON Output:");
if (mBean.getprettyprint()) {
System.out.print(Jinfrascan.toString(4));
} else {
System.out.print(Jinfrascan);
}
}
if(mBean.getDoLogging())
{
String rmf = mBean.getLogDir() + "/BeanBagger" + time + ".txt";
PrintWriter writer = new PrintWriter(rmf, "UTF-8");
if (mBean.getprettyprint()) {
writer.println(Jinfrascan.toString(4));
}
else {
writer.println(Jinfrascan);
}
writer.close();
}
} catch (Exception exception) {
System.out.println("Error:" + exception);
System.out.println(" " + exception);
//Error handling to come.
}
loopagain=false;
mBean.setIterationsCount(mBean.getIterationsCount() + 1);
if(mBean.getLoop())loopagain=true;
if( mBean.getIterations()>0 && mBean.getIterationsCount() < mBean.getIterations()){//If we are counting and havent reached limit
loopagain=true;
}
if( mBean.getIterations()>0 && mBean.getIterationsCount() >= mBean.getIterations()){//If we are counting and havent reached limit
loopagain=false;
}
if(!mBean.getLoop())loopagain=false; //If mBean says stop looping, stop it!
if(loopagain){
System.out.println("Sleeping " + mBean.getLoopDelaySeconds() + " seconds. This was run " + mBean.getIterationsCount());
for(int x=0; x<mBean.getLoopDelaySeconds();x++)
{
TimeUnit.SECONDS.sleep(1);
if(!mBean.getLoop()){
loopagain=false;
break;}
}
}
} while (loopagain);
System.out.println("");
System.out.println("Stiv's Beanbagger Finished: " + mBean.getIterationsCount() + " iterations.");
}
public static void Usage()
{
System.out.println("java -jar Beanbagger [-p {process}] [-b {bean}] -q -m [-j {filename}] -pp -q");
System.out.println(" -p {process}: VM Process Name or substring of process to try to connect to. Defaults to all");
System.out.println(" -b {bean}: Restrict data to just one bean. Default is all beans ");
System.out.println(" -j {optionalfilename}: Output results to single file in JSON format, or to console if no file specified.");
System.out.println(" File will be overwritten each pass.");
System.out.println(" -x :Requires exact match of VM Process Name");
System.out.println(" -u :Filter. Suppresses output of unsupported types or operations.");
System.out.println(" -m :Filter. Suppresses iteration of Sun beans (sun.* and com.sun.*");
System.out.println(" -r :Filter. Suppresses logging of unreadable attributes");
System.out.println(" -l {seconds} :Loop continously. After completion, the dump will rerun in x seconds, default is 30");
System.out.println(" -c {iterations} :Count number of times to run. -c with no options sets to 5. Automatically sets -l");
System.out.println(" -q :Quiet. Suppresses most console output.");
System.out.println(" -pp : Prettyprint JSON output" );
System.out.println(" -log {logdir} : Write each pass to a new file in logdir with epoch time in the filename." );
System.out.println("\nProcesses found:");
List<VirtualMachineDescriptor> list = VirtualMachine.list();
for (VirtualMachineDescriptor vmd: list)
{
if(vmd.displayName().equals(""))
{
System.out.println(" {Unamed Instance}");
}
else
{
System.out.println(" "+ vmd.displayName());
}
}
System.out.println("");
System.exit(1);
}
static JMXConnector getLocalConnection(VirtualMachine vm) throws Exception {
Properties props = vm.getAgentProperties();
String connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY);
if (connectorAddress == null) {
props = vm.getSystemProperties();
String home = props.getProperty("java.home");
String agent = home + File.separator + "lib" + File.separator + "management-agent.jar";
vm.loadAgent(agent);
props = vm.getAgentProperties();
connectorAddress = props.getProperty(CONNECTOR_ADDRESS_PROPERTY);
}
JMXServiceURL url = new JMXServiceURL(connectorAddress);
return JMXConnectorFactory.connect(url);
}
}
| 49.235081 | 214 | 0.426525 |
8503a02f385d4f86246122b1ffda572bf015eb59 | 3,329 | package com.xianzhi.integration.adapter.settings;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.xianzhi.integration.R;
import com.xianzhi.integration.bean.SecEditBean;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by TJTJL on 2017/7/24.
*
*/
public class SecEditAdapter extends BaseAdapter implements View.OnClickListener{
private List<SecEditBean.PageBean.ListBean> data = new ArrayList<>();
private Activity activity;
private SecEditListener listener;
int currentLevel = 0;
public SecEditAdapter(Activity activity, SecEditListener listener) {
this.activity = activity;
this.listener = listener;
}
public void addData(List<SecEditBean.PageBean.ListBean> data, int currentLevel) {
this.data.clear();
this.data.addAll(data);
this.currentLevel = currentLevel;
notifyDataSetChanged();
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
MyViewHolder holder = null;
if (convertView == null) {
view = View.inflate(activity, R.layout.item_securityedit, null);
holder = new MyViewHolder(view);
view.setTag(holder);
} else {
view = convertView;
holder = (MyViewHolder) view.getTag();
}
if (currentLevel == 0) {
holder.tvCategory.setText("风险类别: ");
} else if (currentLevel == 1) {
holder.tvCategory.setText("风险项点: ");
} else if (currentLevel == 2) {
holder.tvCategory.setText("工作标准: ");
}
holder.tvItem.setText(data.get(position).getName());
holder.tvRename.setTag(R.id.tag_security_id,data.get(position).getId());
holder.tvRename.setTag(R.id.tag_security_level,data.get(position).getLevel());
holder.tvRename.setTag(R.id.tag_security_pid,data.get(position).getPid());
holder.tvRename.setTag(R.id.tag_security_year,data.get(position).getYear());
holder.tvRename.setTag(R.id.tag_security_name,data.get(position).getName());
holder.tvDelete.setTag(R.id.tag_security_code,data.get(position).getCode());
holder.tvRename.setOnClickListener(this);
holder.tvDelete.setOnClickListener(this);
return view;
}
class MyViewHolder {
@BindView(R.id.tv_item)
TextView tvItem;
@BindView(R.id.tv_rename)
TextView tvRename;
@BindView(R.id.tv_delete)
TextView tvDelete;
@BindView(R.id.tv_category)
TextView tvCategory;
MyViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
/**
* 自定义接口,用于捕捉条目内控件的点击事件
*/
public interface SecEditListener{
public void click(View v);
}
@Override
public void onClick(View v) {
listener.click(v);
}
}
| 27.97479 | 86 | 0.644638 |
42e85781778d66277582c9afade8ecaa1379885e | 367 | package org.light4j.exception.relation;
import java.util.Date;
public class NullTest
{
public static void main(String[] args)
{
Date d = null;
try
{
System.out.println(d.after(new Date()));
}
catch (NullPointerException ne)
{
System.out.println("空指针异常");
}
catch(Exception e)
{
System.out.println("未知异常");
}
}
} | 15.956522 | 44 | 0.613079 |
d472440fa0a0f45ec43787b27eaaf4cacf1f9cf5 | 630 | package com.joindata.inf.common.support.idgen.component.sequence.impl;
import javax.annotation.Resource;
import com.joindata.inf.common.support.idgen.component.Sequence;
import com.joindata.inf.common.support.idgen.core.IdRangeFactory;
import lombok.Setter;
@Setter
public abstract class AbstractBaseSequence implements Sequence
{
@Resource(name = "idRangeFactory")
protected IdRangeFactory idRangeFactory;
protected String name;
protected long increase()
{
synchronized(this)
{
return idRangeFactory.getCurrentIdRange(name).next();
}
}
}
| 24.230769 | 71 | 0.706349 |
718a26bd7c46c25d13a6f4dfb82bee4e4e25b951 | 1,479 | // This file was generated by Mendix Studio Pro.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.
package businessbankmodule.actions;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
public class GenerateAccountNumber extends CustomJavaAction<java.lang.String>
{
private java.lang.String bankCode;
public GenerateAccountNumber(IContext context, java.lang.String bankCode)
{
super(context);
this.bankCode = bankCode;
}
@java.lang.Override
public java.lang.String executeAction() throws Exception
{
// BEGIN USER CODE
Long sum = 0L;
try {
sum = Long.parseLong(this.bankCode);
} catch (Exception e) {}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 13; i++) {
int num = (int)(Math.random()*10);
sum *=10;
sum += num;
sb.append(num);
}
double result = 98-sum * 100%97;
return this.bankCode + "-" + sb.toString() + "-" + (int)result;
// END USER CODE
}
/**
* Returns a string representation of this action
*/
@java.lang.Override
public java.lang.String toString()
{
return "GenerateAccountNumber";
}
// BEGIN EXTRA CODE
// END EXTRA CODE
}
| 25.947368 | 82 | 0.701826 |
59fb1574d51945957e86bdf9e2d97d5f20a7ab0c | 1,060 | package com.stubbornjava.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.CharSource;
public class Resources {
// {{start:asString}}
public static String asString(String resource) {
URL url = com.google.common.io.Resources.getResource(resource);
try {
return com.google.common.io.Resources.toString(url, Charsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
// {{end:asString}}
// {{start:asBufferedReader}}
public static BufferedReader asBufferedReader(String resource) {
URL url = com.google.common.io.Resources.getResource(resource);
try {
CharSource charSource = com.google.common.io.Resources.asCharSource(url, Charsets.UTF_8);
return charSource.openBufferedStream();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
// {{end:asBufferedReader}}
}
| 30.285714 | 101 | 0.659434 |
29be0804d07b2ed335591777a920ec00a3dc5c10 | 8,660 | package sk.upjs.ics.tennismanager;
import java.awt.Color;
public class TurnajForm extends javax.swing.JDialog {
private TurnajDao turnajDao = DaoFactory.INSTANCE.getTurnajDao();
private Turnaj turnaj;
public TurnajForm(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
public TurnajForm(java.awt.Frame parent, boolean modal, Turnaj turnaj) {
super(parent, modal);
initComponents();
if (turnaj != null) {
this.turnaj = turnaj;
nazovText.setText(turnaj.getNazov());
rokText.setText(Integer.valueOf(turnaj.getRok()).toString());
}
Color color = new Color(204, 255, 204);
this.getContentPane().setBackground(color);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
nazovText = new javax.swing.JTextField();
zrusitButton = new javax.swing.JButton();
okButton = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
rokText = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Pridať turnaj");
zrusitButton.setText("Zrušiť");
zrusitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zrusitButtonActionPerformed(evt);
}
});
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
jLabel2.setText("Rok:");
jLabel1.setText("Názov:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nazovText, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 13, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(rokText, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(zrusitButton)
.addGap(14, 14, 14))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(nazovText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(rokText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 69, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(okButton)
.addComponent(zrusitButton))
.addContainerGap())))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void zrusitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zrusitButtonActionPerformed
this.setVisible(false);
}//GEN-LAST:event_zrusitButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
if (turnaj == null) {
turnaj = new Turnaj();
turnaj.setNazov(nazovText.getText());
turnaj.setRok(Integer.parseInt(rokText.getText()));
turnajDao.pridat(turnaj);
} else {
turnaj.setNazov(nazovText.getText());
turnaj.setRok(Integer.parseInt(rokText.getText()));
turnajDao.upravit(turnaj);
}
this.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TurnajForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TurnajForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TurnajForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TurnajForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
TurnajForm dialog = new TurnajForm(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField nazovText;
private javax.swing.JButton okButton;
private javax.swing.JTextField rokText;
private javax.swing.JButton zrusitButton;
// End of variables declaration//GEN-END:variables
}
| 48.651685 | 169 | 0.627598 |
3bce44ab850787c5ff64b7380d09721ebe4c7ddd | 3,725 |
package com.leakyabstractions.result;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Tests for {@link LazyResult#flatMapFailure(Function)}.
*
* @author Guillermo Calvo
*/
@DisplayName("LazyResult flatMapFailure")
class LazyResult_flatMapFailure_Test {
private static final String SUCCESS = "SUCCESS";
private static final String FAILURE = "FAILURE";
@Test
void should_be_lazy() {
// Given
final Supplier<Result<String, String>> supplier = () -> fail("Should not happen");
final LazyResult<String, String> lazy = new LazyResult<>(supplier);
final Function<String, Result<String, String>> mapper = s -> fail("Should not happen");
// When
final Result<String, String> result = lazy.flatMapFailure(mapper);
// Then
assertThat(result).isInstanceOf(LazyResult.class);
}
@Test
void should_eventually_flat_map_when_needed() {
// Given
final Supplier<Result<String, String>> supplier = () -> new Failure<>(FAILURE);
final LazyResult<String, String> lazy = new LazyResult<>(supplier);
final Function<String, Result<String, String>> mapper = s -> new Success<>(SUCCESS);
// When
final String value = lazy.flatMapFailure(mapper).orElse(null);
// Then
assertThat(value).isSameAs(SUCCESS);
}
@Test
void should_not_be_lazy_if_already_supplied() {
// Given
final Supplier<Result<String, String>> supplier = () -> new Failure<>(FAILURE);
final LazyResult<String, String> lazy = new LazyResult<>(supplier);
final Result<String, String> another = new Failure<>("ANOTHER");
final Function<String, Result<String, String>> mapper = s -> another;
// When
final Optional<String> value = lazy.optionalFailure();
final Result<String, String> result = lazy.flatMapFailure(mapper);
// Then
assertThat(value).containsSame(FAILURE);
assertThat(result).isSameAs(another);
}
@Test
void obeys_monad_laws() {
// Given
final Result<Void, String> result = unit(FAILURE);
final Function<String, Result<Void, Integer>> fun1 = x -> unit(x.length());
final Function<Integer, Result<Void, String>> fun2 = x -> unit(x * 10 + "a");
// Then
// Left Identity Law
assertThat(resolve(bind(unit(FAILURE), fun1)))
.isEqualTo(resolve(fun1.apply(FAILURE)))
.isEqualTo(new Failure<>(7));
// Right Identity Law
assertThat(resolve(result))
.isEqualTo(resolve(bind(result, LazyResult_flatMapFailure_Test::unit)))
.isEqualTo(new Failure<>(FAILURE));
// Associativity Law
assertThat(resolve(bind(bind(result, fun1), fun2)))
.isEqualTo(resolve(bind(result, s -> fun2.apply(unwrap(fun1.apply(s))))))
.isEqualTo(new Failure<>("70a"));
}
private static <T> Result<Void, T> unit(T value) {
return new LazyResult<>(() -> new Failure<>(value));
}
private static <T, T2> Result<Void, T2> bind(Result<Void, T> result, Function<T, Result<Void, T2>> function) {
return result.flatMapFailure(function);
}
private static <T> T unwrap(Result<Void, T> result) {
return result.optionalFailure().get();
}
private static <T> Result<Void, T> resolve(Result<Void, T> result) {
return new Failure<>(unwrap(result));
}
}
| 36.881188 | 114 | 0.637047 |
8bfa55726db7aa78d1bb2a9b77cda6212235d82e | 640 | public class Experiment {
public Object function() {
int i = 1_0000_0000;
class A {
public Object function() {
int i = 1_0000_0000;
class A1 {
public Object function() {
return new A1();
}
public int k = 2_000;
}
return new A();
}
public int k = 2_000;
}
return new A();
}
public static void main(String[] args) {
Object retval = new Experiment().function();
System.out.println(retval);
}
}
| 25.6 | 52 | 0.421875 |
2e5c8f41ec7a05bc66ea8518eb82020ebb14326d | 458 | package com.atguigu.gulimall.coupon.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.coupon.entity.SpuBoundsEntity;
import java.util.Map;
/**
* 商品spu积分设置
*
* @author linfeng
* @email 951243590@qq.com
* @date 2021-06-05 15:48:39
*/
public interface SpuBoundsService extends IService<SpuBoundsEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| 21.809524 | 69 | 0.770742 |
ce82876cd87a2104b2a40f41854486ed7cb4db6d | 348 | package com.github.kubesys.vsphere.get;
import com.github.kubesys.vsphere.VsphereClientTest;
/**
* Unit test for simple App.
*/
public class GetResourcePoolTest extends VsphereClientTest {
public static void main(String[] args) throws Exception {
System.out.println(getClient().virtualMachinePools().getResourcePool("resgroup-17"));
}
}
| 23.2 | 87 | 0.767241 |
83a7d9b1575ad2bb61a09a2cd4785ef83dbfcea5 | 8,503 | /*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.ui.rest.model.artifacts.browse.treebrowser.nodes;
import com.google.common.collect.Lists;
import org.artifactory.api.context.ContextHelper;
import org.artifactory.api.repo.RepositoryService;
import org.artifactory.api.security.AuthorizationService;
import org.artifactory.descriptor.repo.LocalRepoAlphaComparator;
import org.artifactory.descriptor.repo.LocalRepoDescriptor;
import org.artifactory.descriptor.repo.RemoteRepoDescriptor;
import org.artifactory.descriptor.repo.RepoBaseDescriptor;
import org.artifactory.descriptor.repo.RepoDescriptor;
import org.artifactory.descriptor.repo.VirtualRepoDescriptor;
import org.artifactory.md.Properties;
import org.artifactory.rest.common.model.RestModel;
import org.artifactory.rest.common.service.ArtifactoryRestRequest;
import org.codehaus.jackson.annotate.JsonTypeName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* This is the root node of the tree browser. It contains all the repository nodes.
*
* @author Chen Keinan
*
*/
@JsonTypeName("root")
public class RootNode implements RestTreeNode {
@Override
public List<? extends INode> getChildren(AuthorizationService authService, boolean isCompact,
ArtifactoryRestRequest request) {
List<INode> repoNodes = new ArrayList<>();
//Add a tree node for each file repository and local cache repository
RepositoryService repositoryService = ContextHelper.get().getRepositoryService();
// get local repo descriptors
addLocalRepoNodes(repoNodes, repositoryService);
// add remote repo
addRemoteRepoNodes(repoNodes, repositoryService, request);
// add virtual repo
addVirtualRepoNodes(repoNodes, repositoryService, request);
return repoNodes;
}
/**
* add virtual repo nodes to repo list
* @param repoNodes - repository nodes list
* @param repositoryService - repository service
* @param request
*/
private void addVirtualRepoNodes(List<INode> repoNodes, RepositoryService repositoryService,
ArtifactoryRestRequest request) {
List<VirtualRepoDescriptor> virtualDescriptors = repositoryService.getVirtualRepoDescriptors();
removeNonPermissionRepositories(virtualDescriptors);
Collections.sort(virtualDescriptors, new RepoComparator());
repoNodes.addAll(getVirtualNodes(virtualDescriptors, request));
}
/**
* add remote repo nodes to repo list
* @param repoNodes - repository nodes list
* @param repositoryService - repository service
* @param request
*/
private void addRemoteRepoNodes(List<INode> repoNodes, RepositoryService repositoryService,
ArtifactoryRestRequest request) {
List<RemoteRepoDescriptor> remoteDescriptors = repositoryService.getRemoteRepoDescriptors();
removeNonPermissionRepositories(remoteDescriptors);
Collections.sort(remoteDescriptors, new RepoComparator());
repoNodes.addAll(getRemoteNodes(remoteDescriptors, request));
}
/**
* add local repo nodes to repo list
*
* @param repoNodes - repository nodes list
* @param repositoryService - repository service
*/
private void addLocalRepoNodes(List<INode> repoNodes, RepositoryService repositoryService) {
List<LocalRepoDescriptor> localRepos = repositoryService.getLocalAndCachedRepoDescriptors();
removeNonPermissionRepositories(localRepos);
Collections.sort(localRepos, new LocalRepoAlphaComparator());
repoNodes.addAll(getLocalNodes(localRepos));
}
/**
* get Root Node items
*
* @param repos - list of repositories
* @return - list of root node items
*/
private List<INode> getLocalNodes(List<LocalRepoDescriptor> repos) {
List<INode> items = Lists.newArrayListWithCapacity(repos.size());
repos.forEach(repo -> {
String repoType = repo.getKey().endsWith("-cache") ? "cached" : "local";
RepositoryNode itemNodes = new RepositoryNode(repo, repoType);
items.add(itemNodes);
});
return items;
}
/**
* get Root Node items
* @param repos - list of repositories
* @param request
* @return - list of root node items
*/
private List<INode> getRemoteNodes(List<RemoteRepoDescriptor> repos, ArtifactoryRestRequest request) {
List<INode> items = Lists.newArrayListWithCapacity(repos.size());
repos.forEach(repo -> {
if (repo.isListRemoteFolderItems()) {
String repoType = "remote";
VirtualRemoteRepositoryNode itemNodes = new VirtualRemoteRepositoryNode(repo, repoType, request);
items.add(itemNodes);
}
});
return items;
}
/**
* get Root Node items
*
* @param repos - list of repositories
* @param request
* @return - list of root node items
*/
private List<INode> getVirtualNodes(List<VirtualRepoDescriptor> repos, ArtifactoryRestRequest request) {
List<INode> items = Lists.newArrayListWithCapacity(repos.size());
repos.forEach(repo -> {
String repoType = "virtual";
VirtualRemoteRepositoryNode itemNodes = new VirtualRemoteRepositoryNode(repo, repoType, request);
items.add(itemNodes);
});
return items;
}
/**
* remove repositories which user not permit to access
*
* @param repositories
*/
private void removeNonPermissionRepositories(List<? extends RepoDescriptor> repositories) {
AuthorizationService authorizationService = ContextHelper.get().getAuthorizationService();
Iterator<? extends RepoDescriptor> repoDescriptors = repositories.iterator();
while (repoDescriptors.hasNext()) {
RepoDescriptor repoDescriptor = repoDescriptors.next();
if (!authorizationService.userHasPermissionsOnRepositoryRoot(repoDescriptor.getKey())) {
repoDescriptors.remove();
}
}
}
@Override
public List<RestModel> fetchItemTypeData(AuthorizationService authService, boolean isCompact,
Properties props, ArtifactoryRestRequest request) {
Collection<? extends RestTreeNode> items = getChildren(authService, isCompact, request);
List<RestModel> treeModel = new ArrayList<>();
items.forEach(item -> {
((INode) item).populateActions(authService);
// populate tabs
((INode) item).populateTabs(authService);
// update additional data
((INode) item).updateNodeData();
treeModel.add(item);
});
return treeModel;
}
private static class RepoComparator implements Comparator<RepoBaseDescriptor> {
@Override
public int compare(RepoBaseDescriptor descriptor1, RepoBaseDescriptor descriptor2) {
//Local repositories can be either ordinary or caches
if (descriptor1 instanceof LocalRepoDescriptor) {
boolean repo1IsCache = ((LocalRepoDescriptor) descriptor1).isCache();
boolean repo2IsCache = ((LocalRepoDescriptor) descriptor2).isCache();
//Cache repositories should appear in a higher priority
if (repo1IsCache && !repo2IsCache) {
return 1;
} else if (!repo1IsCache && repo2IsCache) {
return -1;
}
}
return descriptor1.getKey().compareTo(descriptor2.getKey());
}
}
} | 40.490476 | 113 | 0.686464 |
c037c343d0c00f12bc86cc251ec0b7ac0e7ba6d4 | 3,338 | /**
* Copyright 2016 William Van Woensel
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.
*
*
* @author wvw
*
*/
package wvw.utils.log;
import java.util.HashMap;
import java.util.Map;
public abstract class Logger {
public static final int INFO = 0;
public static final int DEBUG = 1;
public static final int EXP = 2;
private static int nextId = 0;
private static int defaultLvl = INFO;
private static int curLogLvl;
private static int defaultType;
private static Map<Integer, Logger> instances = new HashMap<Integer, Logger>();
private int loggerType;
static {
}
public static Logger getLogger() {
return getLogger(defaultType);
}
public static Logger getLogger(int loggerType) {
return instances.get(loggerType);
}
public static void setDefaultType(int loggerType) {
defaultType = loggerType;
}
public static void addInstance(int loggerType, Logger instance) {
instances.put(loggerType, instance);
}
public static void setLogLevel(int logLvl) {
curLogLvl = logLvl;
}
protected static int getUniqueLoggerTypeId() {
return nextId++;
}
public int getLoggerType() {
return loggerType;
}
protected Logger(int loggerType) {
this.loggerType = loggerType;
}
public void log() {
log(defaultLvl);
}
public void log(int logLvl) {
log("", logLvl);
}
public void log(Object msg) {
log(msg, defaultLvl);
}
public void log(Object msg, int logLvl) {
log(msg.toString(), logLvl);
}
public void log(Exception e) {
log(e, defaultLvl);
}
public void log(Exception e, int logLvl) {
log(excStr(e), logLvl);
}
public void log(String ID, String msg) {
log(ID, msg, defaultLvl);
}
public void log(String ID, String msg, int logLvl) {
log(ID + ": " + msg, logLvl);
}
public void log(Object obj, String msg) {
log(obj, msg, defaultLvl);
}
public void log(Object obj, String msg, int logLvl) {
log(objStr(obj) + ": " + msg, logLvl);
}
public void log(Object obj, Exception e) {
log(obj, e, defaultLvl);
}
public void log(Object obj, Exception e, int logLvl) {
log(objStr(obj) + " " + excStr(e), logLvl);
}
public void log(String msg, Exception e) {
log(msg + "; " + excStr(e), defaultLvl);
}
public void log(Object obj, String msg, Exception e) {
log(obj, msg, e, defaultLvl);
}
public void log(Object obj, String msg, Exception e, int logLvl) {
log(objStr(obj) + ": " + msg + "; " + excStr(e), logLvl);
}
public void log(String msg) {
log(msg, defaultLvl);
}
public void log(String msg, int logLvl) {
if (logLvl <= curLogLvl)
logString(msg);
}
private String objStr(Object obj) {
return "[" + obj.getClass().toString().substring(6) + "]";
}
private String excStr(Exception e) {
return "Exception: (" + e.getClass() + ") " + e.getMessage();
}
protected abstract void logString(String str);
}
| 21.261146 | 80 | 0.683044 |
ed5c508923e5ce2141946e5f3ae8a107fa4e418d | 3,404 | package com.applurk.plugin;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import android.net.Uri;
/*
shit hack
*/
import com.applurk.flashtaxidriver.R;
public class NotificationUtils {
private static final String TAG = NotificationUtils.class.getSimpleName();
private static NotificationUtils instance;
private static Context context;
private NotificationManager manager; // Системная утилита, упарляющая уведомлениями
private int lastId = 0; //постоянно увеличивающееся поле, уникальный номер каждого уведомления
private HashMap<Integer, Notification> notifications; //массив ключ-значение на все отображаемые пользователю уведомления
//приватный контструктор для Singleton
private NotificationUtils(Context context) {
this.context = context;
manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifications = new HashMap<Integer, Notification>();
}
/**
* Получение ссылки на синглтон
*/
public static NotificationUtils getInstance(Context context) {
if (instance == null) {
instance = new NotificationUtils(context);
} else {
instance.context = context;
}
return instance;
}
public int createInfoNotification(String title, String message, boolean isFree) {
Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
NotificationCompat.Builder nb = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.icon) //иконка уведомления
.setAutoCancel(true) //уведомление закроется по клику на него
.setTicker(message) //текст, который отобразится вверху статус-бара при создании уведомления
.setContentText(message) // Основной текст уведомления
.setContentIntent(PendingIntent.getActivity(context, -1, notificationIntent, PendingIntent.FLAG_ONE_SHOT))
.setWhen(System.currentTimeMillis()) //отображаемое время уведомления
.setContentTitle(title) //заголовок уведомления
.setDefaults(Notification.DEFAULT_VIBRATE) // звук, вибро и диодный индикатор выставляются по умолчанию
.setSound(Uri.parse("android.resource://"
+ context.getPackageName() + "/" + (isFree ? R.raw.free : R.raw.order)));
Notification notification = nb.build(); //генерируем уведомление
manager.notify(lastId, notification); // отображаем его пользователю.
notifications.put(lastId, notification); //теперь мы можем обращаться к нему по id
lastId = lastId++;
return lastId;
}
public int createOrderNotification(String addressFrom) {
String title = "Новый заказ";
return createInfoNotification(title, addressFrom, false);
}
public int createFreeOrderNotification(String addressFrom) {
String title = "Свободный эфир";
return createInfoNotification(title, addressFrom, true);
}
} | 39.581395 | 125 | 0.709753 |
b71785ff8a2a86924b24160353e7fd645fb2234b | 2,833 | package com.emc.rpsp.imageaccess.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import com.emc.rpsp.config.auditing.AuditConsts;
import com.emc.rpsp.config.auditing.annotations.RpspAuditObject;
import com.emc.rpsp.config.auditing.annotations.RpspAuditResult;
import com.emc.rpsp.config.auditing.annotations.RpspAuditSubject;
import com.emc.rpsp.config.auditing.annotations.RpspAudited;
import com.emc.rpsp.imageaccess.service.GroupSetImageAccessService;
import com.emc.rpsp.vmstructure.domain.CopySnapshot;
@Controller public class GroupSetImageAccessController {
@Autowired
private GroupSetImageAccessService groupSetImageAccessService;
@RequestMapping(value = "/group-sets/{groupSetId}/clusters/{clusterId}/image-access/enable", method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@RpspAudited(action=AuditConsts.ENABLE_DR_TEST)
@ResponseBody public @RpspAuditResult(AuditConsts.DR_TEST_RESULT) ResponseEntity<HttpStatus> enableSnapshotImageAccess(
@RpspAuditObject(AuditConsts.CLUSTER) @PathVariable("clusterId") Long clusterId, @RpspAuditSubject(AuditConsts.GS) @PathVariable("groupSetId") Long groupSetId,
@RequestBody Map<String, Long> params) {
CopySnapshot copySnapshot = new CopySnapshot();
copySnapshot.setId(params.get("snapshotId"));
copySnapshot.setOriginalClosingTimeStamp(params.get("timestamp"));
groupSetImageAccessService.enableImageAccessForGroupSetSubset(clusterId, groupSetId, copySnapshot);
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(value = "/group-sets/{groupSetId}/clusters/{clusterId}/image-access/disable", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
@RpspAudited(action=AuditConsts.DISABLE_DR_TEST)
@ResponseBody
public @RpspAuditResult(AuditConsts.DISABLE_DR_TEST_RESULT) ResponseEntity<HttpStatus> disableImageAccess(@RpspAuditObject(AuditConsts.CLUSTER) @PathVariable("clusterId") Long clusterId,
@RpspAuditSubject(AuditConsts.GS) @PathVariable("groupSetId") Long groupSetId) {
groupSetImageAccessService.disableImageAccessForGroupSetSubset(clusterId, groupSetId);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| 51.509091 | 190 | 0.810448 |
c7492d812d5625274ed1e9f9deec15eb689efe98 | 690 | package org.interledger.encoding.asn.codecs;
/**
* A base for codecs for primitive ASN.1 types.
*/
public abstract class AsnPrimitiveCodec<T> extends AsnObjectCodecBase<T> {
private final AsnSizeConstraint sizeConstraint;
public AsnPrimitiveCodec(AsnSizeConstraint sizeConstraint) {
this.sizeConstraint = sizeConstraint;
}
public AsnPrimitiveCodec(int fixedSizeConstraint) {
this.sizeConstraint = new AsnSizeConstraint(fixedSizeConstraint);
}
public AsnPrimitiveCodec(int minSize, int maxSize) {
this.sizeConstraint = new AsnSizeConstraint(minSize, maxSize);
}
public final AsnSizeConstraint getSizeConstraint() {
return this.sizeConstraint;
}
}
| 24.642857 | 74 | 0.769565 |
72987f2fcb292b897a886d3b545bd500175c32dd | 1,057 | package zzGeneradordeEncuentros;
import java.util.Vector;
public class Equipo {
private int NdeEquipo;
private Vector<Actividad> Va = new Vector<Actividad>();
private Vector<Equipo> Ve = new Vector<Equipo>();
private Vector<Integer> Hora = new Vector<Integer>();
public Equipo(int nde) {
NdeEquipo=nde;
}
public void IngresarEquipo(Equipo e) {
Ve.add(e);
}
public void IngresarActividad(Actividad a) {
Va.add(a);
}
public boolean ExisteEquipo(Equipo e) {
for(int i=0;i<Ve.size();i++)
if(e==Ve.get(i))
return true;
return false;
}
public boolean ExisteActividad(Actividad a) {
for(int i=0;i<Va.size();i++)
if(a==Va.get(i))
return true;
return false;
}
public int getNdeEquipo() {
return NdeEquipo;
}
public String toString() {
return NdeEquipo+"";
}
public void AgregarHora(int h) {
Hora.add(h);
}
public boolean ExisteHora(int h) {
for(int i=0;i<Hora.size();i++)
if(h==Hora.get(i))
return true;
return false;
}
}
| 18.54386 | 57 | 0.62157 |
e24768f48e55eb6e4e0fee795d96d50a64308af3 | 986 | package com.rustam.project.endpoint;
import com.google.inject.Inject;
import com.google.inject.servlet.RequestScoped;
import com.rustam.project.model.entity.Transfer;
import com.rustam.project.model.response.MessageResponse;
import com.rustam.project.service.TransferService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* Report on transfers
* Created by Rustam_Kadyrov on 25.06.2017.
*/
@RequestScoped
@Produces(MediaType.APPLICATION_JSON)
@Path("/transfer")
public class TransferEndpoint {
private final TransferService transferService;
@Inject
public TransferEndpoint(TransferService transferService) {
this.transferService = transferService;
}
/**
* Get all transfers
*
* @return
*/
@GET
public MessageResponse<List<Transfer>> getAllTransfers() {
return new MessageResponse<>(transferService.findAll());
}
}
| 23.47619 | 64 | 0.737323 |
440a79a91078ca898870f7fa59666fdb2c093b96 | 3,262 | /* Mazer5D: A Maze-Solving Game
Copyright (C) 2008-2013 Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.mazer5d.objects.abc;
import com.puttysoftware.mazer5d.Mazer5D;
import com.puttysoftware.mazer5d.abc.MazeObject;
import com.puttysoftware.mazer5d.assets.SoundGroup;
import com.puttysoftware.mazer5d.assets.SoundIndex;
import com.puttysoftware.mazer5d.editor.MazeEditor;
import com.puttysoftware.mazer5d.game.ObjectInventory;
import com.puttysoftware.mazer5d.gui.BagOStuff;
import com.puttysoftware.mazer5d.loaders.SoundPlayer;
import com.puttysoftware.mazer5d.utilities.Layers;
import com.puttysoftware.mazer5d.utilities.MazeObjects;
import com.puttysoftware.mazer5d.utilities.TypeConstants;
public abstract class GenericConditionalTeleport extends GenericTeleport {
// Fields
public static final int TRIGGER_SUN = 1;
public static final int TRIGGER_MOON = 2;
// Constructors
protected GenericConditionalTeleport() {
super();
this.addCustomCounters(this.getCustomFormat());
this.setSunMoon(GenericConditionalTeleport.TRIGGER_SUN);
this.setType(TypeConstants.TYPE_TELEPORT);
}
// Scriptability
@Override
public void postMoveAction(final boolean ie, final int dirX, final int dirY,
final ObjectInventory inv) {
final BagOStuff app = Mazer5D.getBagOStuff();
int testVal;
if (this.getSunMoon() == GenericConditionalTeleport.TRIGGER_SUN) {
testVal = inv.getItemCount(MazeObjects.SUN_STONE);
} else if (this
.getSunMoon() == GenericConditionalTeleport.TRIGGER_MOON) {
testVal = inv.getItemCount(MazeObjects.MOON_STONE);
} else {
testVal = 0;
}
if (testVal >= this.getTriggerValue()) {
app.getGameManager().updatePositionAbsolute(this
.getDestinationRow2(), this.getDestinationColumn2(), this
.getDestinationFloor2());
} else {
app.getGameManager().updatePositionAbsolute(this
.getDestinationRow(), this.getDestinationColumn(), this
.getDestinationFloor());
}
SoundPlayer.playSound(SoundIndex.TELEPORT, SoundGroup.GAME);
this.postMoveActionHook();
}
public void postMoveActionHook() {
// Do nothing
}
@Override
public abstract String getName();
@Override
public int getLayer() {
return Layers.OBJECT;
}
@Override
public void editorProbeHook() {
Mazer5D.getBagOStuff().showMessage(this.getName() + ": Trigger Value "
+ this.getTriggerValue());
}
@Override
public final MazeObject editorPropertiesHook() {
final MazeEditor me = Mazer5D.getBagOStuff().getEditor();
me.editConditionalTeleportDestination(this);
return this;
}
@Override
public boolean defersSetProperties() {
return true;
}
@Override
public int getCustomFormat() {
if (Mazer5D.getBagOStuff().getMazeManager().isMazeXML4Compatible()) {
return 7;
} else {
return 8;
}
}
}
| 32.949495 | 87 | 0.667382 |
95783b9090f200f6d9b9f6b9d7db7bda4b1773a6 | 6,899 | /*
* Copyright (C) 2019 Guilherme Maeda
*
* 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 ninja.abap.odatamock.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.olingo.odata2.annotation.processor.core.datasource.DataSource;
import org.apache.olingo.odata2.api.edm.EdmEntitySet;
import org.apache.olingo.odata2.api.edm.EdmEntityType;
import org.apache.olingo.odata2.api.edm.EdmException;
import org.apache.olingo.odata2.api.edm.EdmFunctionImport;
import org.apache.olingo.odata2.api.edm.EdmNavigationProperty;
import org.apache.olingo.odata2.api.edm.provider.EdmProvider;
import org.apache.olingo.odata2.api.exception.ODataApplicationException;
import org.apache.olingo.odata2.api.exception.ODataNotFoundException;
import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import ninja.abap.odatamock.event.FunctionImportHandler;
/**
* Implementation based on org.apache.olingo.odata2.annotation.processor.core.datasource.AnnotationInMemoryDs
*/
@RequiredArgsConstructor
public class MockDataSource implements DataSource {
protected final EdmProvider edmProvider;
protected final MockDataStore dataStore;
@Getter
protected final Map<String, FunctionImportHandler> functionImportHandlers = new HashMap<>();
@Override
public List<?> readData(EdmEntitySet entitySet)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
return dataStore.getEntitySet(entitySet.getName());
}
@Override
public Object readData(EdmEntitySet entitySet, Map<String, Object> keys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
return dataStore.getRecordByKey(entitySet.getName(), keys);
}
@Override
public Object readData(EdmFunctionImport function, Map<String, Object> parameters, Map<String, Object> keys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
FunctionImportHandler handler = functionImportHandlers.get(function.getName());
if (handler != null)
return handler.handle(function, parameters, keys);
else
throw new ODataNotImplementedException();
}
@Override
@SuppressWarnings("unchecked")
public Object readRelatedData(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
Map<String, Object> targetKeys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
// Single record access?
if (targetKeys != null && !targetKeys.isEmpty())
return dataStore.getRecordByKey(targetEntitySet.getName(), targetKeys);
// Entity Set navigation access
Map<String, Object> sourceEntry = (Map<String, Object>) sourceData;
String assocName = findNavigationPropertyName(sourceEntitySet, targetEntitySet);
return sourceEntry.get(assocName);
}
@Override
public BinaryData readBinaryData(EdmEntitySet entitySet, Object mediaLinkEntryData)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
throw new ODataNotImplementedException();
}
@Override
public Object newDataObject(EdmEntitySet entitySet)
throws ODataNotImplementedException, EdmException, ODataApplicationException {
return new HashMap<String, Object>();
}
@Override
public void writeBinaryData(EdmEntitySet entitySet, Object mediaLinkEntryData, BinaryData binaryData)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
throw new ODataNotImplementedException();
}
@Override
public void deleteData(EdmEntitySet entitySet, Map<String, Object> keys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
Map<String, Object> record = dataStore.getRecordByKey(entitySet.getName(), keys);
if (record == null)
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
dataStore.remove(entitySet.getName(), record);
}
@Override
@SuppressWarnings("unchecked")
public void createData(EdmEntitySet entitySet, Object data)
throws ODataNotImplementedException, EdmException, ODataApplicationException {
if (! (data instanceof Map))
throw new ODataApplicationException("Inserted record is of invalid type " +
data.getClass().getName(), Locale.getDefault());
dataStore.insert(entitySet.getName(), (Map<String, Object>) data);
}
@Override
public void deleteRelation(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
Map<String, Object> targetKeys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
throw new ODataNotImplementedException();
}
@Override
@SuppressWarnings("unchecked")
public void writeRelation(EdmEntitySet sourceEntitySet, Object sourceData, EdmEntitySet targetEntitySet,
Map<String, Object> targetKeys)
throws ODataNotImplementedException, ODataNotFoundException, EdmException, ODataApplicationException {
Map<String, Object> sourceEntry = (Map<String, Object>) sourceData;
String assocName = findNavigationPropertyName(sourceEntitySet, targetEntitySet);
List<Map<String, Object>> association = (List<Map<String, Object>>) sourceEntry.get(assocName);
if (association == null) {
association = new ArrayList<>();
sourceEntry.put(assocName, association);
}
association.add(targetKeys);
dataStore.put(sourceEntitySet.getName(), sourceEntry);
}
protected String findNavigationPropertyName(EdmEntitySet sourceEntitySet, EdmEntitySet targetEntitySet)
throws EdmException {
EdmEntityType sourceEntityType = sourceEntitySet.getEntityType();
EdmEntityType targetEntityType = targetEntitySet.getEntityType();
for (String propertyName : sourceEntityType.getNavigationPropertyNames()) {
EdmNavigationProperty navProp = (EdmNavigationProperty) sourceEntityType.getProperty(propertyName);
EdmEntityType navET1 = navProp.getRelationship().getEnd1().getEntityType();
EdmEntityType navET2 = navProp.getRelationship().getEnd2().getEntityType();
if (navET1 == targetEntityType || navET2 == targetEntityType)
return navProp.getName();
}
throw new EdmException(EdmException.NAVIGATIONPROPERTYNOTFOUND);
}
}
| 40.345029 | 109 | 0.80229 |
a5487013af8a8b4cf61165ff58b21b36e560db7b | 1,535 | /**
* Copyright 2011, Kevin Lindsey
* See LICENSE file for licensing information
*/
package com.kevlindev.pinconverter.switches;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.kevlindev.pinconverter.commands.ICommand;
import com.kevlindev.pinconverter.commands.TransformCommand;
/**
* TransformSwitch
*
* @author Kevin Lindsey
* @version 1.0
*/
public class TransformSwitch extends AbstractSwitch {
/*
* (non-Javadoc)
*
* @see com.kevlindev.papilio.ISwitch#createCommand()
*/
@Override
public ICommand createCommand() {
return new TransformCommand();
}
/*
* (non-Javadoc)
*
* @see com.kevlindev.papilio.ISwitch#getDescription()
*/
@Override
public String getDescription() {
return "Perform an FPGA pin name transformation using the current source and destination board types.";
}
/*
* (non-Javadoc)
*
* @see com.kevlindev.pinconverter.switches.ISwitch#getDisplayName()
*/
@Override
public String getDisplayName() {
return "Transform Board";
}
/*
* (non-Javadoc)
*
* @see com.kevlindev.papilio.ISwitch#getAliases()
*/
@Override
public List<String> getSwitchNames() {
List<String> aliases = new ArrayList<String>();
aliases.add("-t");
aliases.add("--transform");
return aliases;
}
/*
* (non-Javadoc)
*
* @see
* com.kevlindev.papilio.ISwitch#processArg(com.kevlindev.papilio.PinConverter
* , java.util.Iterator)
*/
@Override
public boolean processArg(Iterator<String> args) {
return true;
}
}
| 19.679487 | 105 | 0.701629 |
acfb43088898400ca80ea6691b848fc469958e50 | 580 | package org.jxls.examples;
import java.io.IOException;
import java.text.ParseException;
import org.junit.Test;
import org.jxls.JxlsTester;
import org.jxls.common.Context;
import org.jxls.entity.Department;
/**
* Two nested each commands demo
*/
public class TwoInnerLoopsDemo {
@Test
public void test() throws ParseException, IOException {
Context context = new Context();
context.putVar("departments", Department.createDepartments());
JxlsTester tester = JxlsTester.xls(getClass());
tester.processTemplate(context);
}
}
| 23.2 | 70 | 0.708621 |
7056f3afc3e9ccfd8d53a9e9cdf1c4d2e1983ce8 | 3,228 | /**************************************************************************/
/* Implementation of a simple semi-unification algorithm (Henglein 1993) */
/* Copyright (C) 2012. Michael Lienhardt */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; version 2 of the License. */
/* */
/* This program is distributed in the hope that it will be useful, but */
/* WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA */
/* 02110-1301 USA */
/* */
/**************************************************************************/
package deadlock.analyser.generation;
import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
import com.gzoumix.semisolver.constraint.SolvingErrorLoop;
import com.gzoumix.semisolver.constraint.Edge;
import com.gzoumix.semisolver.constraint.History;
import com.gzoumix.semisolver.constraint.HistoryPath;
import com.gzoumix.semisolver.constraint.Information;
public class ErrorLoop implements GenerationError {
class Inner { public Edge edge; public List<ErrorEdge> origin; public Inner(Edge e, List<ErrorEdge> o) { edge = e; origin = o; } }
private List<Inner> origin;
private Edge edge;
public ErrorLoop(SolvingErrorLoop loop) {
edge = loop.getEdge();
origin = new LinkedList<>();
List<ErrorEdge> o;
for(History h : loop.getHistory().getList()) {
o = new LinkedList<>();
for(Information info : h.getInformations()) { o.add(new ErrorEdge((ASTNodeInformation)info)); }
origin.add(new Inner(h.getEdge(), o));
}
}
public String getHelpMessage() {
String res = "*********************\n";
res = res + "* Cannot generate contract in presence of Recursive Structure\n";
res = res + "* Structure defined with the following edges:\n*****\n";
Iterator<Inner> itin = origin.iterator();
while(itin.hasNext()) {
Inner in = itin.next();
res = res + "* edge: " + in.edge.toString() + "\n***\n";
Iterator<ErrorEdge> it = in.origin.iterator();
while(it.hasNext()) {
res = res + it.next().getHelpMessage();
if(it.hasNext()) { res = res + "\n***\n"; } else { res = res + "\n"; }
}
if(itin.hasNext()) { res = res + "\n*****\n"; } else { res = res + "\n"; }
}
res = res + "*********************";
return res;
}
}
| 44.219178 | 132 | 0.527571 |
f7e59587e1b3f12ea475e9a3a3c25849e79337a8 | 1,481 | package com.tdxy.oauth.model.bo;
import java.util.Date;
public class ZFCookie {
private String stuNumber;
private String cookieHash;
private String cookiePrefix;
private String cookieValue;
private Date updateTime;
public ZFCookie() {
}
public ZFCookie(String stuNumber, String cookieHash, String cookiePrefix, String cookieValue) {
this.stuNumber = stuNumber;
this.cookieHash = cookieHash;
this.cookiePrefix = cookiePrefix;
this.cookieValue = cookieValue;
}
public String getCookieHash() {
return cookieHash;
}
public void setCookieHash(String cookieHash) {
this.cookieHash = cookieHash;
}
public String getStuNumber() {
return stuNumber;
}
public void setStuNumber(String stuNumber) {
this.stuNumber = stuNumber == null ? null : stuNumber.trim();
}
public String getCookiePrefix() {
return cookiePrefix;
}
public void setCookiePrefix(String cookiePrefix) {
this.cookiePrefix = cookiePrefix == null ? null : cookiePrefix.trim();
}
public String getCookieValue() {
return cookieValue;
}
public void setCookieValue(String cookieValue) {
this.cookieValue = cookieValue == null ? null : cookieValue.trim();
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
} | 22.784615 | 99 | 0.653612 |
f189799c960a94110eb5eed1599d18bb8ad3a321 | 3,664 | package com.okanciftci.cukatify.services.impl;
import com.okanciftci.cukatify.common.enums.RoleNames;
import com.okanciftci.cukatify.entities.mongo.Role;
import com.okanciftci.cukatify.entities.mongo.User;
import com.okanciftci.cukatify.exceptions.UsernameAlreadyExistsException;
import com.okanciftci.cukatify.persistence.mongo.RoleRepository;
import com.okanciftci.cukatify.persistence.mongo.UserRepository;
import com.okanciftci.cukatify.services.abstr.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private RoleService roleService;
public List<User> getUsers(){
return userRepository.findAll();
}
public User saveSpotifyUser(User user){
try{
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setActive(true);
return userRepository.save(user);
}catch(DuplicateKeyException e){
throw new UsernameAlreadyExistsException("This email is already exists.");
}
}
public User saveUser(User newUser){
try{
newUser.setPassword(passwordEncoder.encode(newUser.getPassword()));
Role role = roleService.getRoleByName(RoleNames.USER.name());
newUser.addRole(role);
newUser.setActive(true);
return userRepository.save(newUser);
}catch(DuplicateKeyException e){
throw new UsernameAlreadyExistsException("This email is already exists.");
}
}
public User getUser(String username){
try{
User user = userRepository.findByUsername(username);
user.setPassword("");
return user;
}catch (Exception e){
return null;
}
}
public boolean toggleUser(String username) {
User user = userRepository.findByUsername(username);
if(user != null){
user.setActive(!user.isActive());
userRepository.save(user);
}else{
throw new UsernameNotFoundException("Email not found.");
}
return true;
}
public boolean makeAdmin(String username) {
User user = userRepository.findByUsername(username);
if(user != null){
Role role = roleService.getRoleByName(RoleNames.ADMIN.name());
user.addRole(role);
userRepository.save(user);
}else{
throw new UsernameNotFoundException("Email not found.");
}
return true;
}
public boolean checkActive(String username){
User user = userRepository.findByUsername(username);
if(user != null){
return user.isActive();
}else{
throw new UsernameNotFoundException("Email not found.");
}
}
public User updateUser(User newUser){
try{
User updatedUser = userRepository.getById(newUser.getId().toString());
updatedUser.setFullName(newUser.getFullName());
updatedUser.setPassword(passwordEncoder.encode(newUser.getPassword()));
return userRepository.save(updatedUser);
}catch(Exception e){
throw new UsernameAlreadyExistsException("Exception");
}
}
}
| 29.312 | 86 | 0.664847 |
35cb366e29310924317447d5fbfccab5dcf48480 | 6,454 | /**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.test.framework.datafactorycommerce;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import org.apache.http.HttpStatus;
import org.joda.time.DateTime;
import com.mozu.api.ApiException;
import com.mozu.api.ApiContext;
import com.mozu.test.framework.core.TestFailException;
import com.mozu.api.resources.commerce.InStockNotificationSubscriptionResource;
/** <summary>
* Use the Customer In-Stock Notification Subscription resource to manage the subscriptions customer accounts use to send product notifications. This resource can send a notification when a product in a catalog returns to a site's active inventory after it is out of stock, or when a new product becomes available for the first time.
* </summary>
*/
public class InStockNotificationSubscriptionFactory
{
public static com.mozu.api.contracts.customer.InStockNotificationSubscriptionCollection getInStockNotificationSubscriptions(ApiContext apiContext, int expectedCode) throws Exception
{
return getInStockNotificationSubscriptions(apiContext, null, null, null, null, null, expectedCode);
}
public static com.mozu.api.contracts.customer.InStockNotificationSubscriptionCollection getInStockNotificationSubscriptions(ApiContext apiContext, Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.customer.InStockNotificationSubscriptionCollection returnObj = new com.mozu.api.contracts.customer.InStockNotificationSubscriptionCollection();
InStockNotificationSubscriptionResource resource = new InStockNotificationSubscriptionResource(apiContext);
try
{
returnObj = resource.getInStockNotificationSubscriptions( startIndex, pageSize, sortBy, filter, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.customer.InStockNotificationSubscription getInStockNotificationSubscription(ApiContext apiContext, Integer id, int expectedCode) throws Exception
{
return getInStockNotificationSubscription(apiContext, id, null, expectedCode);
}
public static com.mozu.api.contracts.customer.InStockNotificationSubscription getInStockNotificationSubscription(ApiContext apiContext, Integer id, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.customer.InStockNotificationSubscription returnObj = new com.mozu.api.contracts.customer.InStockNotificationSubscription();
InStockNotificationSubscriptionResource resource = new InStockNotificationSubscriptionResource(apiContext);
try
{
returnObj = resource.getInStockNotificationSubscription( id, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.customer.InStockNotificationSubscription addInStockNotificationSubscription(ApiContext apiContext, com.mozu.api.contracts.customer.InStockNotificationSubscription inStockNotificationSubscription, int expectedCode) throws Exception
{
return addInStockNotificationSubscription(apiContext, inStockNotificationSubscription, null, expectedCode);
}
public static com.mozu.api.contracts.customer.InStockNotificationSubscription addInStockNotificationSubscription(ApiContext apiContext, com.mozu.api.contracts.customer.InStockNotificationSubscription inStockNotificationSubscription, String responseFields, int expectedCode) throws Exception
{
com.mozu.api.contracts.customer.InStockNotificationSubscription returnObj = new com.mozu.api.contracts.customer.InStockNotificationSubscription();
InStockNotificationSubscriptionResource resource = new InStockNotificationSubscriptionResource(apiContext);
try
{
returnObj = resource.addInStockNotificationSubscription( inStockNotificationSubscription, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return null;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300) && !(expectedCode == HttpStatus.SC_NOT_FOUND && returnObj == null))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
return returnObj;
}
public static void deleteInStockNotificationSubscription(ApiContext apiContext, Integer id, int expectedCode) throws Exception
{
InStockNotificationSubscriptionResource resource = new InStockNotificationSubscriptionResource(apiContext);
try
{
resource.deleteInStockNotificationSubscription( id);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException("" + e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
else
return;
}
if(expectedCode != 304 && !(expectedCode >= 200 && expectedCode <= 300))
throw new TestFailException("304 or between 200 and 300", Thread.currentThread().getStackTrace()[2].getMethodName(), "" + expectedCode, "");
}
}
| 52.471545 | 334 | 0.768671 |
3ed5107e8bbf1648e70013fd2249a6f08938ac19 | 750 | package com.baeldung.datetime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;
public class UseDateTimeFormatter {
public String formatAsIsoDate(LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE);
}
public String formatCustom(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
public String formatWithStyleAndLocale(LocalDateTime localDateTime, FormatStyle formatStyle, Locale locale) {
return localDateTime.format(DateTimeFormatter.ofLocalizedDateTime(formatStyle)
.withLocale(locale));
}
}
| 34.090909 | 113 | 0.773333 |
f9918859bdf1c8a3d3df73fbc6664064ab47fa73 | 113 | package br.edu.ifrn.projetoifjics.app.enums;
public enum RoleEnum {
ROLE_ROOT, ROLE_ADM, ROLE_MOD, ROLE_USER
}
| 18.833333 | 44 | 0.787611 |
578f79ae63cf9331e3d938fcb67d70da6de3e22e | 3,705 | /*
* MIT License
*
* Copyright (C) 2020 The SimpleCloud authors
*
* 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 eu.thesimplecloud.mongoinstaller;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileEditor {
private File file;
private List<String> lines;
public FileEditor(File file) {
if (!file.exists()) {
File dir = new File(file, "..");
System.out.println();
dir.mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
this.file = file;
lines = new ArrayList<String>();
readFile(file.getAbsolutePath());
}
public List<String> getAllLines() {
return lines;
}
public String get(String name) {
for (String s : lines) {
String[] array = s.split("=");
if (array[0].equalsIgnoreCase(name)) {
return array[1];
}
}
return null;
}
public void write(String s) {
lines.add(s);
}
public String getLine(int i) {
if (i > lines.size() - 1)
return null;
return lines.get(i);
}
public void set(String name, String value) {
int line = -1;
for (int i = 0; i < lines.size(); i++) {
String s = lines.get(i);
String[] array = s.split("=");
if (array[0].equalsIgnoreCase(name)) {
line = i;
}
}
if (line != -1) {
lines.remove(line);
}
lines.add(name + "=" + value);
}
public void save() throws IOException {
BufferedWriter writer = null;
writer = new BufferedWriter(new FileWriter(file));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
writer.close();
}
private void readFile(String file) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
String str;
while ((str = in.readLine()) != null) {
lines.add(str);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void replaceLine(String line, String replace) {
for (int i = 0; i < lines.size(); i++) {
String s = lines.get(i);
if (s.equalsIgnoreCase(line)) {
lines.remove(i);
lines.set(i, replace);
return;
}
}
}
}
| 28.282443 | 114 | 0.565992 |
eac62d25adb1b6bd4d58494e7ef8fbf9e5292dfb | 699 | package fziviello.sharedpreferences;
/**
* Created by fziviello on 08/03/18.
*/
public class ModelUser {
int id;
String nome;
String cognome;
public ModelUser(int id, String nome, String cognome) {
this.id = id;
this.nome = nome;
this.cognome = cognome;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
}
| 15.886364 | 59 | 0.560801 |
2e4e461652093803fe0e367258ec9a1059034b76 | 41 | package assets.mmoverhaul.textures.block; | 41 | 41 | 0.878049 |
9fff626266bf81398e8e26458bcf9cdbef2ca6f7 | 851 | package org.batfish.representation.frr;
import java.io.Serializable;
/**
* Route map statement that calls another routemap.
*
* <p>Executed after any Set Actions have been carried out. If the route-map called returns deny
* then processing of the route-map finishes and the route is denied, regardless of the Matching
* Policy or the Exit Policy. If the called route-map returns permit, then Matching Policy and Exit
* Policy govern further behaviour, as normal.
*
* <p>See also <a href="http://docs.frrouting.org/en/latest/routemap.html#route-maps"></a>
*/
public class RouteMapCall implements Serializable {
private final String _routeMapName;
public RouteMapCall(String routeMapName) {
_routeMapName = routeMapName;
}
/** Name of the route map to call */
public String getRouteMapName() {
return _routeMapName;
}
}
| 31.518519 | 99 | 0.745006 |
10e6c00d2fb83f9e01325cd4fead48b0c7045f45 | 2,721 | package com.summerbrochtrup.myeats.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.summerbrochtrup.myeats.R;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mFindRestaurantsButton;
private Button mSavedRestaurantsButton;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindViews();
}
private void bindViews() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mFindRestaurantsButton = (Button) findViewById(R.id.findRestaurantsButton);
mSavedRestaurantsButton = (Button) findViewById(R.id.savedRestaurantsButton);
TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
toolbarTitle.setText(String.format(getResources().getString(R.string.welcome_toolbar_title),
FirebaseAuth.getInstance().getCurrentUser().getDisplayName()));
mFindRestaurantsButton.setOnClickListener(this);
mSavedRestaurantsButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
@Override
public void onClick(View v) {
if(v == mFindRestaurantsButton) {
Intent intent = new Intent(MainActivity.this, FindRestaurantListActivity.class);
startActivity(intent);
}
if (v == mSavedRestaurantsButton) {
Intent intent = new Intent(MainActivity.this, SavedRestaurantListActivity.class);
startActivity(intent);
}
}
}
| 34.884615 | 100 | 0.701948 |
385a4698a3ea81849ff35d92d73bbe2ee741bf39 | 48,289 | /*
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
* Copyright (c) 2017 AT&T Intellectual Property
* ===================================================================
* 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.
*
* ============LICENSE_END=============================================
* ====================================================================
*/
package org.onap.music.unittests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
//cjc import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
//cjc import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mindrot.jbcrypt.BCrypt;
//cjcimport org.mindrot.jbcrypt.BCrypt;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.music.datastore.MusicDataStore;
import org.onap.music.datastore.MusicDataStoreHandle;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.datastore.jsonobjects.JsonDelete;
import org.onap.music.datastore.jsonobjects.JsonInsert;
import org.onap.music.datastore.jsonobjects.JsonKeySpace;
//cjc import org.onap.music.datastore.jsonobjects.JsonKeySpace;
//import org.onap.music.datastore.jsonobjects.JsonOnboard;
import org.onap.music.datastore.jsonobjects.JsonSelect;
import org.onap.music.datastore.jsonobjects.JsonTable;
import org.onap.music.datastore.jsonobjects.JsonUpdate;
import org.onap.music.lockingservice.cassandra.CassaLockStore;
import org.onap.music.main.MusicCore;
import org.onap.music.main.MusicUtil;
//import org.onap.music.main.ResultType;
//import org.onap.music.rest.RestMusicAdminAPI;
import org.onap.music.rest.RestMusicDataAPI;
import org.onap.music.rest.RestMusicQAPI;
import org.springframework.test.util.ReflectionTestUtils;
import org.onap.music.rest.RestMusicLocksAPI;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.sun.jersey.core.util.Base64;
//import com.datastax.driver.core.DataType;
//import com.datastax.driver.core.ResultSet;
//import com.datastax.driver.core.Row;
import com.sun.jersey.core.util.MultivaluedMapImpl;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@RunWith(MockitoJUnitRunner.class)
public class TestRestMusicQAPI {
//RestMusicAdminAPI admin = new RestMusicAdminAPI();
RestMusicLocksAPI lock = new RestMusicLocksAPI();
RestMusicQAPI qData = new RestMusicQAPI();
static PreparedQueryObject testObject;
@Mock
static HttpServletResponse http;
@Mock
UriInfo info;
static String appName = "TestApp";
static String userId = "TestUser";
static String password = "TestPassword";
/*
static String appName = "com.att.ecomp.portal.demeter.aid";//"TestApp";
static String userId = "m00468@portal.ecomp.att.com";//"TestUser";
static String password = "happy123";//"TestPassword";
*/
static String authData = userId+":"+password;
static String wrongAuthData = userId+":"+"pass";
static String authorization = new String(Base64.encode(authData.getBytes()));
static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
static boolean isAAF = false;
static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
static String uuidS = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6";
static String keyspaceName = "testkscjc";
static String tableName = "employees";
static String xLatestVersion = "X-latestVersion";
static String onboardUUID = null;
static String lockId = null;
static String lockName = "testkscjc.employees.sample3";
static String majorV="3";
static String minorV="0";
static String patchV="1";
static String aid=null;
static JsonKeySpace kspObject=null;
static RestMusicDataAPI data = new RestMusicDataAPI();
static Response resp;
@BeforeClass
public static void init() throws Exception {
try {
ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle",
CassandraCQL.connectToEmbeddedCassandra());
MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle()));
// System.out.println("before class keysp");
//resp=data.createKeySpace(majorV,minorV,patchV,aid,appName,userId,password,kspObject,keyspaceName);
//System.out.println("after keyspace="+keyspaceName);
} catch (Exception e) {
System.out.println("before class exception ");
e.printStackTrace();
}
// admin keyspace and table
testObject = new PreparedQueryObject();
testObject.appendQueryString("CREATE KEYSPACE admin WITH REPLICATION = "
+ "{'class' : 'SimpleStrategy' , "
+ "'replication_factor': 1} AND DURABLE_WRITES = true");
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString(
"CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text,"
+ " application_name text, is_api boolean,"
+ " password text, username text,"
+ " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");");
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString(
"INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
MusicUtil.DEFAULTKEYSPACENAME));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString(
"INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
UUID.fromString("bbc66ccc-d857-4e90-b1e5-df98a3d40de6")));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
MusicUtil.DEFAULTKEYSPACENAME));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestApp1"));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestUser1"));
testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString(
"select uuid from admin.keyspace_master where application_name = ? allow filtering");
testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
ResultSet rs = MusicCore.get(testObject);
List<Row> rows = rs.all();
if (rows.size() > 0) {
System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid"));
}
JsonKeySpace jsonKeyspace = new JsonKeySpace();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, Object> replicationInfo = new HashMap<>();
consistencyInfo.put("type", "eventual");
replicationInfo.put("class", "SimpleStrategy");
replicationInfo.put("replication_factor", 1);
jsonKeyspace.setConsistencyInfo(consistencyInfo);
jsonKeyspace.setDurabilityOfWrites("true");
jsonKeyspace.setKeyspaceName(keyspaceName);
jsonKeyspace.setReplicationInfo(replicationInfo);
Response response = data.createKeySpace(majorV, minorV, patchV, null, authorization, appName,
jsonKeyspace, keyspaceName);
System.out.println("#######status is " + response.getStatus()+" keyspace="+keyspaceName);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("After class");
testObject = new PreparedQueryObject();
testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
MusicCore.eventualPut(testObject);
testObject = new PreparedQueryObject();
testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin");
MusicCore.eventualPut(testObject);
MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle");
if (mds != null)
mds.close();
}
/* @Test
public void Test1_createQ_good() throws Exception {
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setTableName(tableName);
jsonTable.setFields(fields);
jsonTable.setPartitionKey("emp_name");
jsonTable.setClusteringKey("uuid");
jsonTable.setClusteringOrder("uuid ASC");
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableName);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus());
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
}*/
@Test
public void Test1_createQ_FieldsEmpty() throws Exception {
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
/*
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name)");
*/
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name");
jsonTable.setTableName(tableName);
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableName);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("EmptyFields #######status is " + response.getStatus());
System.out.println("Entity" + response.getEntity());
assertNotEquals(200, response.getStatus());
}
/* @Test
public void Test1_createQ_Clustergood() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPartitionKey("emp_name");
jsonTable.setClusteringKey("emp_id");
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
}*/
/* @Test
public void Test1_createQ_ClusterOrderGood1() throws Exception {
String tableNameC="testcjcO";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name,emp_id)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setTableName(tableNameC);
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setFields(fields);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
} */
/* @Test
public void Test1_createQ_PartitionKeygood() throws Exception {
String tableNameP="testcjcP";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setTableName(tableNameP);
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setFields(fields);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameP);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameP);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
} */
@Test
public void Test1_createQ_PartitionKeybadclose() throws Exception {
String tableNameC="testcjcP1";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id))");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name,emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
//assertEquals(400, response.getStatus());
assertTrue(200 != response.getStatus());
}
/* @Test
public void Test1_createQ_ClusterOrderGood2() throws Exception {
String tableNameC="testcjcO1g";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name,emp_salary,emp_id)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name,emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC");
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
} */
/* @Test
public void Test1_createQ_ColPkeyoverridesPrimaryKeyGood() throws Exception {
String tableNameC="testcjcPr";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "((emp_name),emp_salary,emp_id)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name,emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC");
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
//assertTrue(200 != response.getStatus());
} */
@Test
public void Test1_createQ_ClusterOrderBad() throws Exception {
String tableNameC="testcjcO1b";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name,emp_id)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name,emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setClusteringOrder("emp_id DESCx");
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
// "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
@Test
public void Test3_createQ_0() throws Exception {
//duplicate testing ...
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name");
String tableNameDup=tableName+"X";
jsonTable.setTableName(tableNameDup);
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonTable, keyspaceName, tableNameDup);
System.out.println("#######status for 1st time " + response.getStatus());
System.out.println("Entity" + response.getEntity());
Response response0 = qData.createQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonTable, keyspaceName, tableNameDup);
// 400 is the duplicate status found in response
// Music 113 duplicate testing
//import static org.junit.Assert.assertNotEquals;
System.out.println("#######status for 2nd time " + response0.getStatus());
System.out.println("Entity" + response0.getEntity());
assertFalse("Duplicate table not created for "+tableNameDup, 200==response0.getStatus());
//assertEquals(400, response0.getStatus());
//assertNotEquals(200,response0.getStatus());
}
// Improper keyspace
@Ignore
@Test
public void Test3_createQ2() throws Exception {
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_salary", "varint");
fields.put("PRIMARY KEY", "(emp_name)");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPartitionKey("emp_name");
jsonTable.setTableName(tableName);
jsonTable.setClusteringKey("emp_salary");
jsonTable.setClusteringOrder("emp_salary DESC");
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonTable, "wrong", tableName);
System.out.println("#######status is " + response.getStatus());
System.out.println("Entity" + response.getEntity());
assertEquals(401, response.getStatus());
}
/* @Test
public void Test4_insertIntoQ() throws Exception {
JsonInsert jsonInsert = new JsonInsert();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, Object> values = new HashMap<>();
values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
values.put("emp_name", "testName");
values.put("emp_salary", 500);
consistencyInfo.put("type", "eventual");
jsonInsert.setConsistencyInfo(consistencyInfo);
jsonInsert.setKeyspaceName(keyspaceName);
jsonInsert.setTableName(tableName);
jsonInsert.setValues(values);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, jsonInsert, keyspaceName, tableName);
assertEquals(200, response.getStatus());
}*/
@Test
public void Test4_insertIntoQ_valuesEmpty() throws Exception {
JsonInsert jsonInsert = new JsonInsert();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, Object> values = new HashMap<>();
/*
values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
values.put("emp_name", "testName");
values.put("emp_salary", 500);
*/
consistencyInfo.put("type", "eventual");
jsonInsert.setConsistencyInfo(consistencyInfo);
jsonInsert.setKeyspaceName(keyspaceName);
jsonInsert.setTableName(tableName);
jsonInsert.setValues(values);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, jsonInsert, keyspaceName, tableName);
assertNotEquals(200, response.getStatus());
}
/* @Test
public void Test4_insertIntoQ2() throws Exception {
JsonInsert jsonInsert = new JsonInsert();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, Object> values = new HashMap<>();
values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
values.put("emp_name", "test1");
values.put("emp_salary", 1500);
consistencyInfo.put("type", "eventual");
jsonInsert.setConsistencyInfo(consistencyInfo);
jsonInsert.setKeyspaceName(keyspaceName);
jsonInsert.setTableName(tableName);
jsonInsert.setValues(values);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.insertIntoQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonInsert, keyspaceName, tableName);
assertEquals(200, response.getStatus());
}*/
/* @Test
public void Test5_updateQ() throws Exception {
JsonUpdate jsonUpdate = new JsonUpdate();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
Map<String, Object> values = new HashMap<>();
row.add("emp_name", "testName");
row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
values.put("emp_salary", "2500");
consistencyInfo.put("type", "atomic");
jsonUpdate.setConsistencyInfo(consistencyInfo);
jsonUpdate.setKeyspaceName(keyspaceName);
jsonUpdate.setTableName(tableName);
jsonUpdate.setValues(values);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
authorization, jsonUpdate, keyspaceName, tableName, info);
assertEquals(200, response.getStatus());
}*/
@Test
public void Test5_updateQEmptyValues() throws Exception {
JsonUpdate jsonUpdate = new JsonUpdate();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
Map<String, Object> values = new HashMap<>();
row.add("emp_name", "testName");
//values.put("emp_salary", 2500);
consistencyInfo.put("type", "atomic");
jsonUpdate.setConsistencyInfo(consistencyInfo);
jsonUpdate.setKeyspaceName(keyspaceName);
jsonUpdate.setTableName(tableName);
jsonUpdate.setValues(values);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
//Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
authorization, jsonUpdate, keyspaceName, tableName, info);
assertNotEquals(200, response.getStatus());
}
/* @Test
public void Test6_filterQ() throws Exception { //select
JsonSelect jsonSelect = new JsonSelect();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
row.add("emp_name", "testName");
row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
consistencyInfo.put("type", "atomic");
jsonSelect.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.filter(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, keyspaceName, tableName, info);
HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
HashMap<String, Object> result = map.get("result");
assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
}*/
/* @Test
public void Test6_peekQ() throws Exception { //select
JsonSelect jsonSelect = new JsonSelect();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
row.add("emp_name", "testName");
consistencyInfo.put("type", "atomic");
jsonSelect.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, keyspaceName, tableName, info);
HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
HashMap<String, Object> result = map.get("result");
if (result.isEmpty() ) assertTrue(true);
else assertFalse(false);
//assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
}*/
/*
@Test
public void Test6_peekQ_empty() throws Exception { //select
// row is not needed in thhis test
JsonSelect jsonSelect = new JsonSelect();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
row.add("emp_name", "testName");
consistencyInfo.put("type", "atomic");
jsonSelect.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
UriInfo infoe= mockUriInfo("/peek?");//empty queryParam: cause exception
// infoe.setQueryParameters("");
System.out.println("uriinfo="+infoe.getQueryParameters());
Mockito.when(infoe.getQueryParameters()).thenReturn(row);
Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, keyspaceName, tableName, infoe);
HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
HashMap<String, Object> result = map.get("result");
if (result.isEmpty() ) assertTrue(true);
else assertFalse(false);
//assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
}*/
/* @Test
public void Test6_deleteFromQ1() throws Exception {
JsonDelete jsonDelete = new JsonDelete();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
row.add("emp_name", "test1");
consistencyInfo.put("type", "atomic");
jsonDelete.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.deleteFromQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonDelete, keyspaceName, tableName, info);
assertEquals(200, response.getStatus());
}*/
// Values
@Test
@Ignore
public void Test6_deleteFromQ() throws Exception {
JsonDelete jsonDelete = new JsonDelete();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
consistencyInfo.put("type", "atomic");
jsonDelete.setConsistencyInfo(consistencyInfo);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.deleteFromQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonDelete, keyspaceName, tableName, info);
assertEquals(400, response.getStatus());
}
// delObj
@Test
public void Test6_deleteFromQ2() throws Exception {
JsonDelete jsonDelete = new JsonDelete();
Map<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
row.add("emp_name", "test1");
consistencyInfo.put("type", "atomic");
jsonDelete.setConsistencyInfo(consistencyInfo);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
//Mockito.when(info.getQueryParameters()).thenReturn(row);
Response response = qData.deleteFromQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
null, keyspaceName, tableName, info);
assertEquals(400, response.getStatus());
}
/*
@Test
public void Test7_dropQ() throws Exception {
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
consistencyInfo.put("type", "atomic");
jsonTable.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.dropQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
keyspaceName, tableName);
assertEquals(200, response.getStatus());
}*/
private UriInfo mockUriInfo(String urix) throws URISyntaxException {
String uri="http://localhost:8080/MUSIC/rest/v"+majorV+"/priorityq/keyspaces/"+keyspaceName+"/"+tableName+urix;
UriInfo uriInfo = Mockito.mock(UriInfo.class);
System.out.println("mock urix="+urix+" uri="+uri);
Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI(uri));
return uriInfo;
}
//Empty Fields
@Test
public void Test8_createQ_fields_empty() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPartitionKey("emp_name");
jsonTable.setClusteringKey("emp_id");
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Partition key null
@Test
public void Test8_createQ_partitionKey_empty() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setClusteringKey("emp_id");
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Clustering key null
@Test
public void Test8_createQ_ClusteringKey_empty() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPartitionKey("emp_name");
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Clustering Order null
@Test
public void Test8_createQ_ClusteringOrder_empty() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPartitionKey("emp_name");
jsonTable.setClusteringKey("emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Invalid primary key
@Test
public void Test8_createQ_primaryKey_invalid() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setPrimaryKey("(emp_name");
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setClusteringKey("emp_id");
jsonTable.setClusteringOrder("emp_id ASC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Primary key with no clustering key
@Test
public void Test8_createQ_primaryKey_with_empty_clusteringKey() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey("emp_name");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
jsonTable.setClusteringOrder("emp_id ASC");
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
//Primary key with no partition key
@Test
public void Test8_createQ_primaryKey_with_empty_partitionKey() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
fields.put("uuid", "text");
fields.put("emp_name", "text");
fields.put("emp_id", "text");
fields.put("emp_salary", "varint");
consistencyInfo.put("type", "eventual");
jsonTable.setConsistencyInfo(consistencyInfo);
jsonTable.setKeyspaceName(keyspaceName);
jsonTable.setPrimaryKey(" ");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
jsonTable.setClusteringOrder("emp_id ASC");
//Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(400, response.getStatus());
}
}
| 49.476434 | 123 | 0.647912 |
2ddc8bd073791420cf8ef0e47aa7495d453f57c1 | 851 | package com.vanniktech.emoji.<%= package %>.category;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import com.vanniktech.emoji.emoji.EmojiCategory;
import com.vanniktech.emoji.<%= package %>.R;
import com.vanniktech.emoji.<%= package %>.<%= name %>;
@SuppressWarnings("PMD.MethodReturnsInternalArray") public final class <%= category %>Category implements EmojiCategory {
private static final <%= name %>[] EMOJIS = CategoryUtils.concatAll(<%= chunks %>);
@Override @NonNull public <%= name %>[] getEmojis() {
return EMOJIS;
}
@Override @DrawableRes public int getIcon() {
return R.drawable.emoji_<%= package %>_category_<%= icon %>;
}
@Override @StringRes public int getCategoryName() {
return R.string.emoji_<%= package %>_category_<%= icon %>;
}
}
| 34.04 | 121 | 0.714454 |
250a7ccb68820a674a9c6fd18a38eac7cad30c52 | 2,186 | /*
* Copyright (C) 2016-2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package com.here.android.hello;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import android.os.Build;
import com.example.here.hello.BuildConfig;
import com.here.android.RobolectricApplication;
import java.util.ArrayList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@RunWith(RobolectricTestRunner.class)
@Config(
sdk = Build.VERSION_CODES.M,
application = RobolectricApplication.class,
constants = BuildConfig.class)
public class HelloWorldAttributesTest {
private final HelloWorldAttributes attributes = HelloWorldAttributes.createAttributes();
@Test
public void setGetBuiltInTypeAttribute() {
final long value = 42;
attributes.setBuiltInTypeAttribute(value);
long result = attributes.getBuiltInTypeAttribute();
assertEquals(value, result);
}
@Test
public void getReadonlyAttribute() {
final float value = 3.14f;
float result = attributes.getReadonlyAttribute();
assertEquals(value, result);
}
@Test
public void setGetStructAttribute() {
HelloWorldAttributes.ExampleStruct structValue =
new HelloWorldAttributes.ExampleStruct(2.71, new ArrayList<>());
attributes.setStructAttribute(structValue);
HelloWorldAttributes.ExampleStruct result = attributes.getStructAttribute();
assertNotNull(result);
assertEquals(structValue.value, result.value);
}
}
| 29.945205 | 90 | 0.76075 |
4e3ac187beff2f21f1988a12be9671efc7682829 | 1,473 | package io.ebean.enhance.entity;
import io.ebean.enhance.asm.AnnotationVisitor;
import io.ebean.enhance.asm.Attribute;
import io.ebean.enhance.asm.FieldVisitor;
import io.ebean.enhance.common.EnhanceConstants;
import static io.ebean.enhance.Transformer.EBEAN_ASM_VERSION;
/**
* Used to collect information about a field (specifically from field annotations).
*/
public class LocalFieldVisitor extends FieldVisitor implements EnhanceConstants {
private final FieldMeta fieldMeta;
/**
* Constructor used for entity class enhancement.
*
* @param fv the fieldVisitor used to write
* @param fieldMeta the fieldMeta data
*/
public LocalFieldVisitor(FieldVisitor fv, FieldMeta fieldMeta) {
super(EBEAN_ASM_VERSION, fv);
this.fieldMeta = fieldMeta;
}
/**
* Return the field name.
*/
public String getName() {
return fieldMeta.getFieldName();
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
fieldMeta.addAnnotationDesc(desc);
if (fv != null) {
if (!visible && desc.equals(L_JETBRAINS_NOTNULL)) {
fv.visitAnnotation(L_EBEAN_NOTNULL, true);
}
return fv.visitAnnotation(desc, visible);
} else {
return null;
}
}
@Override
public void visitAttribute(Attribute attr) {
if (fv != null) {
fv.visitAttribute(attr);
}
}
@Override
public void visitEnd() {
if (fv != null) {
fv.visitEnd();
}
}
}
| 23.380952 | 83 | 0.68907 |
e5a13d215925fd38c29d8e38526bee47bf22e8d0 | 249 | package black.libcore.io;
import top.niunaijun.blackreflection.annotation.BClassName;
import top.niunaijun.blackreflection.annotation.BStaticField;
@BClassName("libcore.io.Libcore")
public interface Libcore {
@BStaticField
Object os();
}
| 20.75 | 61 | 0.791165 |
6759a8e6a17443c0b16f9e408d1ee0279795a7ba | 651 | package com.yahoo.r4hu7.moviesdoughnut.data.local.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.yahoo.r4hu7.moviesdoughnut.data.remote.response.MovieExternalIdsResponse;
@Dao
public interface ExternalLinkDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(MovieExternalIdsResponse... externalIdsResponses);
@Query("SELECT * FROM _link WHERE id=:movieId")
LiveData<MovieExternalIdsResponse> getResponse(int movieId);
}
| 34.263158 | 84 | 0.814132 |
76236cbab7d18bc347148ad7200cf1b8f4e41f9b | 283 | package com.github.entropyfeng.simpleauth.config.anno;
import java.lang.annotation.*;
/**
* @author entropyfeng
* @date 2019/6/12 15:40
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PostAuth {
String value()default "";
}
| 18.866667 | 54 | 0.734982 |
31e44698fce504356e93247bb19daa5a13d431e2 | 5,580 | /*
* 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.lucene.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Methods for manipulating (sorting) collections. Sort methods work directly on the supplied lists
* and don't copy to/from arrays before/after. For medium size collections as used in the Lucene
* indexer that is much more efficient.
*
* @lucene.internal
*/
public final class CollectionUtil {
private CollectionUtil() {} // no instance
private static final class ListIntroSorter<T> extends IntroSorter {
T pivot;
final List<T> list;
final Comparator<? super T> comp;
ListIntroSorter(List<T> list, Comparator<? super T> comp) {
super();
if (!(list instanceof RandomAccess))
throw new IllegalArgumentException(
"CollectionUtil can only sort random access lists in-place.");
this.list = list;
this.comp = comp;
}
@Override
protected void setPivot(int i) {
pivot = list.get(i);
}
@Override
protected void swap(int i, int j) {
Collections.swap(list, i, j);
}
@Override
protected int compare(int i, int j) {
return comp.compare(list.get(i), list.get(j));
}
@Override
protected int comparePivot(int j) {
return comp.compare(pivot, list.get(j));
}
}
private static final class ListTimSorter<T> extends TimSorter {
final List<T> list;
final Comparator<? super T> comp;
final T[] tmp;
@SuppressWarnings("unchecked")
ListTimSorter(List<T> list, Comparator<? super T> comp, int maxTempSlots) {
super(maxTempSlots);
if (!(list instanceof RandomAccess))
throw new IllegalArgumentException(
"CollectionUtil can only sort random access lists in-place.");
this.list = list;
this.comp = comp;
if (maxTempSlots > 0) {
this.tmp = (T[]) new Object[maxTempSlots];
} else {
this.tmp = null;
}
}
@Override
protected void swap(int i, int j) {
Collections.swap(list, i, j);
}
@Override
protected void copy(int src, int dest) {
list.set(dest, list.get(src));
}
@Override
protected void save(int i, int len) {
for (int j = 0; j < len; ++j) {
tmp[j] = list.get(i + j);
}
}
@Override
protected void restore(int i, int j) {
list.set(j, tmp[i]);
}
@Override
protected int compare(int i, int j) {
return comp.compare(list.get(i), list.get(j));
}
@Override
protected int compareSaved(int i, int j) {
return comp.compare(tmp[i], list.get(j));
}
}
/**
* Sorts the given random access {@link List} using the {@link Comparator}. The list must
* implement {@link RandomAccess}. This method uses the intro sort algorithm, but falls back to
* insertion sort for small lists.
*
* @throws IllegalArgumentException if list is e.g. a linked list without random access.
*/
public static <T> void introSort(List<T> list, Comparator<? super T> comp) {
final int size = list.size();
if (size <= 1) return;
new ListIntroSorter<>(list, comp).sort(0, size);
}
/**
* Sorts the given random access {@link List} in natural order. The list must implement {@link
* RandomAccess}. This method uses the intro sort algorithm, but falls back to insertion sort for
* small lists.
*
* @throws IllegalArgumentException if list is e.g. a linked list without random access.
*/
public static <T extends Comparable<? super T>> void introSort(List<T> list) {
final int size = list.size();
if (size <= 1) return;
introSort(list, Comparator.naturalOrder());
}
// Tim sorts:
/**
* Sorts the given random access {@link List} using the {@link Comparator}. The list must
* implement {@link RandomAccess}. This method uses the Tim sort algorithm, but falls back to
* binary sort for small lists.
*
* @throws IllegalArgumentException if list is e.g. a linked list without random access.
*/
public static <T> void timSort(List<T> list, Comparator<? super T> comp) {
final int size = list.size();
if (size <= 1) return;
new ListTimSorter<>(list, comp, list.size() / 64).sort(0, size);
}
/**
* Sorts the given random access {@link List} in natural order. The list must implement {@link
* RandomAccess}. This method uses the Tim sort algorithm, but falls back to binary sort for small
* lists.
*
* @throws IllegalArgumentException if list is e.g. a linked list without random access.
*/
public static <T extends Comparable<? super T>> void timSort(List<T> list) {
final int size = list.size();
if (size <= 1) return;
timSort(list, Comparator.naturalOrder());
}
}
| 31.173184 | 100 | 0.659857 |
81b9b9f4cf4d7a8983f0ea3dc445ae86419093f6 | 1,112 | package fwcd.fructose.swing;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
* A viewable text component that
* is intended to provide helpful
* information.
*
* @author Fredrik
*
*/
public class HelpView implements Viewable {
private final JPanel view;
private final int padding = 20;
/**
* Constructs a new help view.
*
* @param text - The lines of text featured in this HelpView
*/
public HelpView(String... text) {
view = new JPanel();
view.setBorder(new EmptyBorder(padding, padding, padding, padding));
view.setBackground(Color.WHITE);
view.setLayout(new BoxLayout(view, BoxLayout.Y_AXIS));
view.setOpaque(true);
for (String line : text) {
view.add(new JLabel(" - " + line));
}
}
/**
* Displays a new dialog containing this
* HelpView.
*/
public void showAsDialog() {
JOptionPane.showMessageDialog(null, view, "Help", JOptionPane.PLAIN_MESSAGE);
}
@Override
public JPanel getComponent() {
return view;
}
}
| 20.981132 | 79 | 0.703237 |
312daaf8cbb1ddb9ac19e8b31940276b2967496a | 4,167 | package com.upseil.gdx.util;
import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.CharArray;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.IntMap.Entry;
import com.badlogic.gdx.utils.IntMap.Keys;
import com.badlogic.gdx.utils.IntSet;
import com.badlogic.gdx.utils.IntSet.IntSetIterator;
import com.badlogic.gdx.utils.ObjectSet;
import com.upseil.gdx.util.function.CharConsumer;
import com.upseil.gdx.util.function.FloatConsumer;
import com.upseil.gdx.util.function.IntObjectConsumer;
public class GDXCollections {
private GDXCollections() { }
// Primitive Arrays ---------------------------------------------------------------------------
public static void forEach(IntArray array, IntConsumer consumer) {
int[] data = array.items;
int size = array.size;
for (int i = 0; i < size; i++) {
consumer.accept(data[i]);
}
}
public static void forEach(FloatArray array, FloatConsumer consumer) {
float[] data = array.items;
int size = array.size;
for (int i = 0; i < size; i++) {
consumer.accept(data[i]);
}
}
public static void revertedForEach(FloatArray array, FloatConsumer consumer) {
float[] data = array.items;
for (int i = array.size - 1; i >= 0; i--) {
consumer.accept(data[i]);
}
}
public static void forEach(CharArray array, CharConsumer consumer) {
char[] data = array.items;
int size = array.size;
for (int i = 0; i < size; i++) {
consumer.accept(data[i]);
}
}
// Object Array ------------------------------------------------------------------------------
public static <T> void forEach(Array<T> array, Consumer<T> consumer) {
T[] data = array.items;
int size = array.size;
for (int i = 0; i < size; i++) {
consumer.accept(data[i]);
}
}
public static <T> void forEach(Array<T> array, IntObjectConsumer<T> consumer) {
T[] data = array.items;
int size = array.size;
for (int i = 0; i < size; i++) {
consumer.accept(i, data[i]);
}
}
// IntMap -------------------------------------------------------------------------------------
public static <T> void forEach(IntMap<T> intMap, IntObjectConsumer<T> consumer) {
for (Entry<T> entry : intMap.entries()) {
consumer.accept(entry.key, entry.value);
}
}
public static <T> void forEachValue(IntMap<T> intMap, Consumer<T> consumer) {
for (T value : intMap.values()) {
consumer.accept(value);
}
}
public static <T> void forEachKey(IntMap<T> intMap, IntConsumer consumer) {
Keys keys = intMap.keys();
while (keys.hasNext) {
consumer.accept(keys.next());
}
}
// IntSet -------------------------------------------------------------------------------------
public static void forEach(IntSet set, IntConsumer consumer) {
IntSetIterator iterator = set.iterator();
while (iterator.hasNext) {
consumer.accept(iterator.next());
}
}
// Generic Utilities --------------------------------------------------------------------------
public static boolean isEmpty(Iterable<?> iterable) {
if (iterable instanceof Collection) {
return ((Collection<?>) iterable).isEmpty();
}
return !iterable.iterator().hasNext();
}
// Empty Collections --------------------------------------------------------------------------
// TODO Add more empty collections
private static final ObjectSet<Object> EmptySet = new UnmodifiableObjectSet<>(new ObjectSet<Object>(0));
@SuppressWarnings("unchecked")
public static <T> ObjectSet<T> emptySet() {
return (ObjectSet<T>) EmptySet;
}
}
| 33.071429 | 108 | 0.535157 |
168705e9544bb3e97f5fb6e5f5003959e1f2c5c7 | 644 | package com.att.research.music.main;
public class WriteReturnType {
private ResultType result;
private String message;
public WriteReturnType(ResultType result, String message) {
super();
this.result = result;
this.message = message;
}
public ResultType getResultType() {
return result;
}
public String getTimingInfo() {
return timingInfo;
}
public void setTimingInfo(String timingInfo) {
this.timingInfo = timingInfo;
}
private String timingInfo;
public ResultType getResult() {
return result;
}
public String getMessage() {
return message;
}
public String toString(){
return result+" | "+message;
}
}
| 18.4 | 60 | 0.725155 |
d2357c891f25c6f5e2e541bc391e7bc4d60a4eb9 | 3,869 | package org.contest.scrapper;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
public class MetadataScrapper {
private static ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws IOException {
mapper.enable(SerializationFeature.INDENT_OUTPUT);
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultPrettyPrinter.Lf2SpacesIndenter.instance);
InputStream input = ReviewsScrapper.class.getResourceAsStream("/input.json");
List<Map<String, Object>> hotels = mapper.readValue(input, List.class);
FileWriter writer = new FileWriter("/Users/nicolae.popa/katea-chatbot/scraper/src/main/resources/metadata.json");
writer.append("[\n");
hotels.stream().map(MetadataScrapper::mapNewObject)
.forEach(m -> {
try {
String s = mapper.writer(prettyPrinter).writeValueAsString(m);
writer.append(s);
writer.append(",\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
});
writer.append("\n]");
writer.flush();
}
private static Map<String, Object> mapNewObject(Map<String, Object> map) {
try {
Document doc = Jsoup.connect(map.get("url").toString()).get();
// Document doc = Jsoup.connect("https://www.booking.com/hotel/fr/etap-paris-porte-de-montmartre.en-gb.html").get();
Map<String, Object> newMap = new LinkedHashMap<>(map);
newMap.put("venueType", getVenueType(doc));
newMap.put("zone", getZone(doc));
newMap.put("reviewCount", getReviewCount(doc));
newMap.put("facilities", getFacilities(doc));
newMap.put("lat-long", getLatLong(doc));
return newMap;
} catch (IOException e) {
return new HashMap<>();
}
}
private static String getVenueType(Document doc) {
try {
return doc.getElementsByClass("hp__hotel-type-badge").get(0).childNode(0).toString();
} catch (Exception e) {
return "Hotel";
}
}
private static String getZone(Document doc) {
String address = doc.getElementsByClass("hp_address_subtitle").get(0).childNode(0).toString();
int firstCommaIndex = address.indexOf(",");
String fromFirstComma = address.substring(firstCommaIndex + 1);
int secondCommaIndex = fromFirstComma.indexOf(",");
return fromFirstComma.substring(0, secondCommaIndex).trim();
}
private static int getReviewCount(Document doc) {
try {
String reviewValue = doc.getElementById("show_reviews_tab").childNodes().get(1).childNodes().get(2).toString();
String reviewAsString = reviewValue.replace("(", "").replace(")", "").replace(",", "").trim();
return Integer.parseInt(reviewAsString);
} catch (Exception e) {
return 123;
}
}
private static List<String> getFacilities(Document doc) {
Set<String> facilities = doc.getElementsByClass("important_facility").stream().map(e -> e.childNode(2).toString().trim()).collect(Collectors.toSet());
return new ArrayList<>(facilities);
}
private static String getLatLong(Document doc) {
return doc.getElementById("hotel_header").attr("data-atlas-latlng");
}
}
| 39.479592 | 158 | 0.636599 |
978e997fc9c040233189dfabb5aa8d3c664822a4 | 2,183 | package com.ilcarro.qa11;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CreateAccountTest extends TestBase {
//preconditions: user should be logged out
@BeforeMethod
public void ensurePreconditions() {
if (!isSignUpTabPresentInHeader()) {//sign up not present
logOut();
}
}
@Test
public void testSignUp() throws InterruptedException {
//wd.findElement(By.cssSelector("[href='/signup']")).click(); //click on SignUp Button
click(By.cssSelector("[href='/signup']"));
Assert.assertTrue(isElementPreswent(By.cssSelector("form.signup__fields")));
//fill registration form
//manuel@gmail.com
fillRegistraitionForm(new User()
.withFirstName("Manuel")
.withSecondName("Neuer")
.withEmail("manuel6@gmail.com")
.withPassword("Manuel12345"));
//wd.findElement(By.cssSelector("#check_policy")).click();
click(By.cssSelector("#check_policy"));
// Thread.sleep(2000);
//click Submit button
submitForm();
//check login form displayed
Assert.assertTrue(isLoginFormPresent());
// Assert.assertTrue(isElementPreswent(By.cssSelector(".Login_login__right_block__1niYm")));
}
@Test
public void testSignUpWithoutPassword() {
click(By.cssSelector("[href='/signup']"));
Assert.assertTrue(isElementPreswent(By.cssSelector("form.signup__fields")));
fillRegistraitionForm(new User()
.withFirstName("Manuel1")
.withSecondName("Neuer1")
.withEmail("manuel51@gmail.com"));
click(By.cssSelector("#check_policy"));
submitForm();
Assert.assertTrue(isLoginFormPresent());
}
public void fillRegistraitionForm(User user) {
type(By.name("first_name"), user.getFirstName());
type(By.name("second_name"), user.getSecondName());
type(By.name("email"), user.getEmail());
type(By.name("password"), user.getPassword());
}
}
| 30.319444 | 99 | 0.628493 |
574a7951e38af8dc7f4f07281bf7385ba61faa9c | 1,785 | /*
*
* Copyright 2008-2021 Kinotic and the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kinotic.continuum.internal.api.jsonSchema.converters.jdk;
import com.kinotic.continuum.api.jsonSchema.ArrayJsonSchema;
import com.kinotic.continuum.api.jsonSchema.JsonSchema;
import com.kinotic.continuum.internal.api.jsonSchema.converters.ConversionContext;
import com.kinotic.continuum.internal.api.jsonSchema.converters.GenericTypeJsonSchemaConverter;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Component;
/**
*
* Created by navid on 2019-07-01.
*/
@Component
public class ArrayJsonSchemaConverter implements GenericTypeJsonSchemaConverter {
@Override
public boolean supports(ResolvableType resolvableType) {
return resolvableType.isArray();
}
@Override
public JsonSchema convert(ResolvableType resolvableType,
ConversionContext conversionContext) {
ArrayJsonSchema ret = new ArrayJsonSchema();
ResolvableType componentType = resolvableType.getComponentType();
JsonSchema itemSchema = conversionContext.convertDependency(componentType);
ret.addItem(itemSchema);
return ret;
}
}
| 34.326923 | 95 | 0.755742 |
d5c0be2e1c5384b45755b1acfd4b93f24e25e4b8 | 2,031 | package cn.edu.nju.software.sda.plugin.function.info.impl.demo;
import cn.edu.nju.software.sda.core.domain.dto.InputData;
import cn.edu.nju.software.sda.core.domain.dto.ResultDto;
import cn.edu.nju.software.sda.core.domain.info.InfoSet;
import cn.edu.nju.software.sda.core.domain.info.PairRelation;
import cn.edu.nju.software.sda.core.domain.meta.FormDataType;
import cn.edu.nju.software.sda.core.domain.meta.MetaData;
import cn.edu.nju.software.sda.core.domain.meta.MetaFormDataItem;
import cn.edu.nju.software.sda.core.domain.meta.MetaInfoDataItem;
import cn.edu.nju.software.sda.core.domain.node.Node;
import cn.edu.nju.software.sda.core.domain.work.Work;
import cn.edu.nju.software.sda.core.utils.FileCompress;
import cn.edu.nju.software.sda.plugin.function.info.InfoCollection;
import cn.edu.nju.software.sda.plugin.function.info.impl.staticjava.ClassAdapter;
import cn.edu.nju.software.sda.plugin.function.info.impl.staticjava.JavaData;
import org.springframework.asm.ClassReader;
import java.io.*;
import java.util.ArrayList;
public class Demo extends InfoCollection {
@Override
public MetaData getMetaData() {
MetaData metaData = new MetaData();
metaData.addMetaDataItem(new MetaFormDataItem("String", FormDataType.STRING));
metaData.addMetaDataItem(new MetaFormDataItem("Time", FormDataType.TIMESTAMP));
metaData.addMetaDataItem(new MetaFormDataItem("File", FormDataType.FILE));
metaData.addMetaDataItem(new MetaInfoDataItem(Node.INFO_NAME_NODE));
metaData.addMetaDataItem(new MetaInfoDataItem(PairRelation.INFO_NAME_STATIC_CLASS_CALL_COUNT));
return metaData;
}
@Override
public ResultDto check(InputData inputData) {
return ResultDto.ok();
}
@Override
public InfoSet work(InputData inputData, Work work) {
return new InfoSet();
}
@Override
public String getName() {
return "sys_Demo";
}
@Override
public String getDesc() {
return "Just Demo. Collect nothing";
}
}
| 36.927273 | 103 | 0.750862 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.