text stringlengths 10 2.72M |
|---|
package com.smartsampa.busapi;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Created by ruan0408 on 12/04/2016.
*/
public abstract class Stop {
private Integer id;
private String name;
private String address;
private String reference;
private Double latitude;
private Double longitude;
public static Stop emptyStop() { return NullStop.getInstance(); }
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getAddress() {return address;}
public void setAddress(String address) { this.address = address; }
public String getReference() {return reference;}
public void setReference(String reference) { this.reference = reference; }
public Double getLatitude() { return latitude; }
public void setLatitude(Double latitude) { this.latitude = latitude; }
public Double getLongitude() { return longitude; }
public void setLongitude(Double longitude) { this.longitude = longitude; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Stop)) return false;
Stop that = (Stop) o;
return getId().equals(that.getId());
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + getId();
return result;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("id", getId())
.append("name", getName())
.append("address", getAddress())
.append("reference", getReference())
.append("latitude", getLatitude())
.append("longitude", getLongitude())
.toString();
}
}
|
package com.hhdb.csadmin.plugin.type_create.component;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicArrowButton;
import com.hhdb.csadmin.plugin.function.component.BaseDialogKey;
public class MulitCombobox extends JPanel {
private static final long serialVersionUID = -2248098799549252863L;
protected String[] values;
protected List<ActionListener> listeners = new ArrayList<ActionListener>();
protected JTextField editor;
protected String valueSperator;
final BaseDialogKey instance;
protected static final String DEFAULT_VALUE_SPERATOR = ",";
public MulitCombobox(String[] value) {
this(value, DEFAULT_VALUE_SPERATOR);
}
public void MulitCombobox_all(String[] value) {
this.repaint();
values = value;
}
public MulitCombobox(String[] value, String valueSperator) {
values = value;
this.valueSperator = valueSperator;
instance = new BaseDialogKey();
initComponent();
}
private void initComponent() {
instance.setData(values);
setLayout(new GridBagLayout());
this.repaint();
editor = new JTextField();
editor.setEditable(false);
editor.setBorder(null);
editor.setBackground(Color.WHITE);
JButton arrowButton = createArrowButton();
arrowButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
/**
* 设置已选择的字段
*
* @return
*/
if (instance.getBaseTable().isEditing()) {
instance.getBaseTable().getCellEditor().stopCellEditing();
}
int rows = instance.getBaseTable().getRowCount();
for (int i = 0; i < rows; i++) {
if (editor.getText().indexOf(instance.getBaseTable().getValueAt(i, 1).toString().trim()) > -1) {
instance.getBaseTable().setValueAt(true, i, 0);
} else {
instance.getBaseTable().setValueAt(false, i, 0);
}
}
instance.showDialog(e.getLocationOnScreen().x - 190, e.getLocationOnScreen().y + 12);
}
});
instance.getOkBtn().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
/**
* 获取已选择的字段
*
* @return
*/
int rows = instance.getBaseTable().getRowCount();
if (instance.getBaseTable().isEditing()) {
instance.getBaseTable().getCellEditor().stopCellEditing();
}
String result = "";
for (int i = 0; i < rows; i++) {
if (Boolean.parseBoolean(instance.getBaseTable().getValueAt(i, 0).toString())) {
result += instance.getBaseTable().getValueAt(i, 1).toString() + ",";
}
}
if (result.length() > 0) {
result = result.substring(0, result.length() - 1);
}
editor.setText(result);
instance.setVisible(false);
}
});
instance.getCancleBtn().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
instance.setVisible(false);
}
});
add(editor, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
add(arrowButton, new GridBagConstraints(1, 0, 0, 0, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE,
new Insets(0, 0, 0, 0), 0, 0));
}
public void setData(String[] vls) {
int rows = instance.getBaseTable().getRowCount();
for (int i = (rows - 1); i >= 0; i--) {
instance.getTablePanel().getTableDataModel().removeRow(i);
}
instance.setData(vls);
}
public void addActionListener(ActionListener listener) {
if (!listeners.contains(listener))
listeners.add(listener);
}
public void removeActionListener(ActionListener listener) {
if (listeners.contains(listener))
listeners.remove(listener);
}
protected void fireActionPerformed(ActionEvent e) {
for (ActionListener l : listeners) {
l.actionPerformed(e);
}
}
protected String getValues() {
return editor.getText();
}
public void setValues(String str) {
editor.setText(str);
}
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
}
protected JButton createArrowButton() {
JButton button = new BasicArrowButton(BasicArrowButton.SOUTH, UIManager.getColor("ComboBox.buttonBackground"),
UIManager.getColor("ComboBox.buttonShadow"), UIManager.getColor("ComboBox.buttonDarkShadow"),
UIManager.getColor("ComboBox.buttonHighlight"));
button.setName("ComboBox.arrowButton");
return button;
}
// private class MulitComboboxLayout implements LayoutManager {
//
// @Override
// public void addLayoutComponent(String name, Component comp) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void removeLayoutComponent(Component comp) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public Dimension preferredLayoutSize(Container parent) {
// return parent.getPreferredSize();
// }
//
// @Override
// public Dimension minimumLayoutSize(Container parent) {
// return parent.getMinimumSize();
// }
//
// @Override
// public void layoutContainer(Container parent) {
// int w = parent.getWidth();
// int h = parent.getHeight();
// Insets insets = parent.getInsets();
// h = h - insets.top - insets.bottom;
// }
// }
}
|
package com.ms.module.wechat.clear.activity.clear;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.provider.BaseNodeProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ms.module.wechat.clear.R;
import com.ms.module.wechat.clear.utils.ByteSizeToStringUnitUtils;
import org.jetbrains.annotations.NotNull;
public class UpChildProvider extends BaseNodeProvider {
@Override
public int getItemViewType() {
return 3;
}
@Override
public int getLayoutId() {
return R.layout.provider_wechat_clear_up_child;
}
@Override
public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) {
ImageView imageViewIcon = baseViewHolder.findView(R.id.imageViewIcon);
TextView textViewName = baseViewHolder.findView(R.id.textViewName);
TextView textViewSize = baseViewHolder.findView(R.id.textViewSize);
ImageView imageViewCheck = baseViewHolder.findView(R.id.imageViewCheck);
if (baseNode instanceof UpChildNode) {
UpChildNode upChildNode = (UpChildNode) baseNode;
textViewName.setText(upChildNode.getName());
Glide.with(getContext()).load(upChildNode.getIcon()).into(imageViewIcon);
textViewSize.setText(ByteSizeToStringUnitUtils.byteToStringUnit(upChildNode.getSize()));
imageViewCheck.setSelected(upChildNode.isCheck());
imageViewCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (upChildNode.isCheck()) {
upChildNode.setCheck(false);
imageViewCheck.setSelected(false);
} else {
upChildNode.setCheck(true);
imageViewCheck.setSelected(true);
}
getAdapter().notifyDataSetChanged();
}
});
}
}
}
|
package com.thepoofy.website_searcher;
import java.io.IOException;
import java.util.regex.Pattern;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import com.thepoofy.website_searcher.models.Job;
/**
* Executes Jobs issues by the JobManager
*
* @author wvanderhoef
*/
public class JobWorker implements Runnable {
private final JobManager jobs;
private final String sequence;
public JobWorker(JobManager jobManager, String sequence) {
this.jobs = jobManager;
this.sequence = sequence;
}
@Override
public void run() {
boolean isFinished = false;
// Not finished until a JobUnavailableException is thrown
while (!isFinished) {
try {
//request job from job pool
Job j = this.jobs.getNext();
// report back result
jobs.complete(j.getUuid(), processJob(j));
} catch (JobUnavailableException e) {
isFinished = true;
System.out.println("\tNo more jobs.");
}
}
System.out.println("\tworker exiting");
}
/**
* Process the job, returning a true or false.
*
* We could be more intelligent here and implement a retry strategy on HTTP errors.
*
* @param j
* @return
*/
private boolean processJob(Job j) {
try {
// get page contents
String pageContents = this.fetchUrl(j);
// RULE #1
// simple regex to check for a search term exists on the page
Pattern p = Pattern.compile(sequence, Pattern.CASE_INSENSITIVE);
return p.matcher(pageContents).find();
} catch (Exception e) {
e.printStackTrace(System.err);
}
return false;
}
/**
*
* @param j
* @return
* @throws IOException
*/
private String fetchUrl(Job j) throws IOException {
String uri = j.getMozData().getUrl();
ClientConfig config = new ClientConfig();
config.property(ClientProperties.CONNECT_TIMEOUT, 1000);
config.property(ClientProperties.READ_TIMEOUT, 1000);
Client client = ClientBuilder.newClient(config);
Response response = client
.target("http://" + uri)
.request()
.get();
System.out.println("URL: " + uri + "response: " + response.getStatus());
return resolveResponse(client, response, 0);
}
/**
* Return response, recursively follow redirects (3xx response codes) until either 5 redirects or we get a 2xx.
*
* Throw an IOException for 4xx and 5xx in addition to excessive redirects.
*
* @param client
* @param response
* @param redirectCount
* @return
* @throws IOException
*/
private String resolveResponse(Client client, Response response, int redirectCount) throws IOException {
if (response.getStatus() / 100 == 2) {
return response.readEntity(String.class);
} else if (response.getStatus() / 100 == 3 && redirectCount < 5) {
// follow up to 5 redirects
redirectCount++;
return resolveResponse(client, client.target(response.getLocation()).request().get(), redirectCount);
} else {
throw new IOException(response.getLocation() + " unavailable response: " + response.getStatus());
}
}
}
|
package sch.frog.calculator.compile.syntax;
import sch.frog.calculator.compile.semantic.result.IResult;
import sch.frog.calculator.compile.semantic.IExecuteContext;
import sch.frog.calculator.compile.semantic.exec.IExecutor;
/**
* abstract node, 提供一些公共的逻辑, 所有的node都应继承这个抽象类, 而不应该继承ISyntaxNode接口
*/
public abstract class AbstractSyntaxNode implements ISyntaxNode {
protected final IExecutor executor;
protected final String word;
protected final int priority;
protected int position = -1;
protected AbstractSyntaxNode(String word, int priority, IExecutor executor){
this.executor = executor;
this.word = word;
this.priority = priority;
}
@Override
public final String word(){
return this.word;
}
@Override
public final int priority(){
return this.priority;
}
@Override
public int position(){
return this.position;
}
@Override
public IResult execute(IExecuteContext context){
return this.executor.execute(this, context);
}
@Override
public String toString(){
return this.word;
}
}
|
package week3day1;
public class CompareStrings {
public static void main(String[] args) {
//Write a Java program to compare a given string to another string, ignoring case considerations.
//String 1="I am Learning Java"
//String 2="I am learning java?
//Explore with == operator
// equals
// equalsignorecase
String String1="I am Learning Java";
String String2="I am learning java?";
if(String1.equalsIgnoreCase(String2))
{
System.out.println("both Strings are equal");
}
else
System.out.println("both Strings are not equal ");
}
}
|
package com.sendit_app.sendit;
import java.io.File;
public class FileSystemItem {
private final String path;
private final String name;
private final String ext;
private final boolean isDir;
public FileSystemItem(String path) {
this.path = path;
File f = new File(path);
this.name = f.getName();
this.ext = "";//TODO
this.isDir = f.isDirectory();
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
public String getExt() {
return ext;
}
public boolean isDir() {
return isDir;
}
}
|
package Database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.sql.SQLException;
public class UserDAO {
private SQLiteDatabase database;
private Database dbHelper;
private String[] allColumns = {Database.COLUMN_ID, Database.COLUMN_NAME, Database.COLUMN_SCORE};
public UserDAO(Context context) {
dbHelper = new Database(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public UserObject createUser(String name, int score) {
ContentValues values = new ContentValues();
values.put(Database.COLUMN_NAME, name);
values.put(Database.COLUMN_SCORE, score);
long insertID = database.insert(Database.TABLE_USER, null, values);
Cursor cursor = database.query(Database.TABLE_USER, allColumns, Database.COLUMN_ID + " = " + insertID, null, null, null, null);
cursor.moveToFirst();
UserObject newUser = cursorToUser(cursor);
cursor.close();
return newUser;
}
private UserObject cursorToUser(Cursor cursor) {
return null;
}
}
|
/**
* This program simulates a battle between krogg and boss
*
* @author Muhammad Faizan Ali(100518916)
* @version 1.0
*/
public class Battle {
public static void main(String[] args) {
//variables for krogg stats
double kroggAttack = 38.5;
double kroggDefense = 20.0;
double kroggHP = 200;
//variables for boss stats
double bossAttack = 25;
double bossDefense = 12.5;
double bossHP = 200;
int round = 1; //current round
double damageDealt; //variable used to store damage dealt this round
// while loop runs as long as krogg and bosss both have more then 0 HP
while(kroggHP > 0 && bossHP > 0){
System.out.println("Round " + round);
//Calculate the damage dealt by krogg to boss and decrease boss health by that much
damageDealt = (kroggAttack - bossDefense);
bossHP -= damageDealt;
System.out.println("Krogg does "+ damageDealt +" points of damage to Boss");
//Calculate the damage dealt by boss to krogg and decrease krogg health by that much
damageDealt = (bossAttack - kroggDefense);
kroggHP -= damageDealt;
System.out.println("Boss does "+ damageDealt +" points of damage to Krogg");
System.out.println("Boss HP: " + bossHP);
System.out.println("Krogg HP: " + kroggHP);
System.out.println();
round++; //increase the value stored in the round variable by 1 in order to keep track of current round
}
//display msg based on if boss lost or if krogg lost
if(bossHP <= 0){
System.out.println("Boss Lost!");
}else{
System.out.println("Krogg Lost!");
}
}
}
|
package com.dora.web.rest;
import com.dora.DoraApp;
import com.dora.domain.ItensPedido;
import com.dora.domain.Produto;
import com.dora.repository.ItensPedidoRepository;
import com.dora.service.ItensPedidoService;
import com.dora.repository.search.ItensPedidoSearchRepository;
import com.dora.service.dto.ItensPedidoDTO;
import com.dora.service.mapper.ItensPedidoMapper;
import com.dora.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.math.BigDecimal;
import java.util.List;
import static com.dora.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the ItensPedidoResource REST controller.
*
* @see ItensPedidoResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DoraApp.class)
public class ItensPedidoResourceIntTest {
private static final BigDecimal DEFAULT_DESCONTO = new BigDecimal(1);
private static final BigDecimal UPDATED_DESCONTO = new BigDecimal(2);
@Autowired
private ItensPedidoRepository itensPedidoRepository;
@Autowired
private ItensPedidoMapper itensPedidoMapper;
@Autowired
private ItensPedidoService itensPedidoService;
@Autowired
private ItensPedidoSearchRepository itensPedidoSearchRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restItensPedidoMockMvc;
private ItensPedido itensPedido;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final ItensPedidoResource itensPedidoResource = new ItensPedidoResource(itensPedidoService);
this.restItensPedidoMockMvc = MockMvcBuilders.standaloneSetup(itensPedidoResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static ItensPedido createEntity(EntityManager em) {
ItensPedido itensPedido = new ItensPedido()
.desconto(DEFAULT_DESCONTO);
// Add required entity
Produto produto = ProdutoResourceIntTest.createEntity(em);
em.persist(produto);
em.flush();
itensPedido.setProduto(produto);
return itensPedido;
}
@Before
public void initTest() {
itensPedidoSearchRepository.deleteAll();
itensPedido = createEntity(em);
}
@Test
@Transactional
public void createItensPedido() throws Exception {
int databaseSizeBeforeCreate = itensPedidoRepository.findAll().size();
// Create the ItensPedido
ItensPedidoDTO itensPedidoDTO = itensPedidoMapper.toDto(itensPedido);
restItensPedidoMockMvc.perform(post("/api/itens-pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(itensPedidoDTO)))
.andExpect(status().isCreated());
// Validate the ItensPedido in the database
List<ItensPedido> itensPedidoList = itensPedidoRepository.findAll();
assertThat(itensPedidoList).hasSize(databaseSizeBeforeCreate + 1);
ItensPedido testItensPedido = itensPedidoList.get(itensPedidoList.size() - 1);
assertThat(testItensPedido.getDesconto()).isEqualTo(DEFAULT_DESCONTO);
// Validate the ItensPedido in Elasticsearch
ItensPedido itensPedidoEs = itensPedidoSearchRepository.findOne(testItensPedido.getId());
assertThat(itensPedidoEs).isEqualToComparingFieldByField(testItensPedido);
}
@Test
@Transactional
public void createItensPedidoWithExistingId() throws Exception {
int databaseSizeBeforeCreate = itensPedidoRepository.findAll().size();
// Create the ItensPedido with an existing ID
itensPedido.setId(1L);
ItensPedidoDTO itensPedidoDTO = itensPedidoMapper.toDto(itensPedido);
// An entity with an existing ID cannot be created, so this API call must fail
restItensPedidoMockMvc.perform(post("/api/itens-pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(itensPedidoDTO)))
.andExpect(status().isBadRequest());
// Validate the ItensPedido in the database
List<ItensPedido> itensPedidoList = itensPedidoRepository.findAll();
assertThat(itensPedidoList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllItensPedidos() throws Exception {
// Initialize the database
itensPedidoRepository.saveAndFlush(itensPedido);
// Get all the itensPedidoList
restItensPedidoMockMvc.perform(get("/api/itens-pedidos?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(itensPedido.getId().intValue())))
.andExpect(jsonPath("$.[*].desconto").value(hasItem(DEFAULT_DESCONTO.intValue())));
}
@Test
@Transactional
public void getItensPedido() throws Exception {
// Initialize the database
itensPedidoRepository.saveAndFlush(itensPedido);
// Get the itensPedido
restItensPedidoMockMvc.perform(get("/api/itens-pedidos/{id}", itensPedido.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(itensPedido.getId().intValue()))
.andExpect(jsonPath("$.desconto").value(DEFAULT_DESCONTO.intValue()));
}
@Test
@Transactional
public void getNonExistingItensPedido() throws Exception {
// Get the itensPedido
restItensPedidoMockMvc.perform(get("/api/itens-pedidos/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateItensPedido() throws Exception {
// Initialize the database
itensPedidoRepository.saveAndFlush(itensPedido);
itensPedidoSearchRepository.save(itensPedido);
int databaseSizeBeforeUpdate = itensPedidoRepository.findAll().size();
// Update the itensPedido
ItensPedido updatedItensPedido = itensPedidoRepository.findOne(itensPedido.getId());
updatedItensPedido
.desconto(UPDATED_DESCONTO);
ItensPedidoDTO itensPedidoDTO = itensPedidoMapper.toDto(updatedItensPedido);
restItensPedidoMockMvc.perform(put("/api/itens-pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(itensPedidoDTO)))
.andExpect(status().isOk());
// Validate the ItensPedido in the database
List<ItensPedido> itensPedidoList = itensPedidoRepository.findAll();
assertThat(itensPedidoList).hasSize(databaseSizeBeforeUpdate);
ItensPedido testItensPedido = itensPedidoList.get(itensPedidoList.size() - 1);
assertThat(testItensPedido.getDesconto()).isEqualTo(UPDATED_DESCONTO);
// Validate the ItensPedido in Elasticsearch
ItensPedido itensPedidoEs = itensPedidoSearchRepository.findOne(testItensPedido.getId());
assertThat(itensPedidoEs).isEqualToComparingFieldByField(testItensPedido);
}
@Test
@Transactional
public void updateNonExistingItensPedido() throws Exception {
int databaseSizeBeforeUpdate = itensPedidoRepository.findAll().size();
// Create the ItensPedido
ItensPedidoDTO itensPedidoDTO = itensPedidoMapper.toDto(itensPedido);
// If the entity doesn't have an ID, it will be created instead of just being updated
restItensPedidoMockMvc.perform(put("/api/itens-pedidos")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(itensPedidoDTO)))
.andExpect(status().isCreated());
// Validate the ItensPedido in the database
List<ItensPedido> itensPedidoList = itensPedidoRepository.findAll();
assertThat(itensPedidoList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteItensPedido() throws Exception {
// Initialize the database
itensPedidoRepository.saveAndFlush(itensPedido);
itensPedidoSearchRepository.save(itensPedido);
int databaseSizeBeforeDelete = itensPedidoRepository.findAll().size();
// Get the itensPedido
restItensPedidoMockMvc.perform(delete("/api/itens-pedidos/{id}", itensPedido.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate Elasticsearch is empty
boolean itensPedidoExistsInEs = itensPedidoSearchRepository.exists(itensPedido.getId());
assertThat(itensPedidoExistsInEs).isFalse();
// Validate the database is empty
List<ItensPedido> itensPedidoList = itensPedidoRepository.findAll();
assertThat(itensPedidoList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchItensPedido() throws Exception {
// Initialize the database
itensPedidoRepository.saveAndFlush(itensPedido);
itensPedidoSearchRepository.save(itensPedido);
// Search the itensPedido
restItensPedidoMockMvc.perform(get("/api/_search/itens-pedidos?query=id:" + itensPedido.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(itensPedido.getId().intValue())))
.andExpect(jsonPath("$.[*].desconto").value(hasItem(DEFAULT_DESCONTO.intValue())));
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(ItensPedido.class);
ItensPedido itensPedido1 = new ItensPedido();
itensPedido1.setId(1L);
ItensPedido itensPedido2 = new ItensPedido();
itensPedido2.setId(itensPedido1.getId());
assertThat(itensPedido1).isEqualTo(itensPedido2);
itensPedido2.setId(2L);
assertThat(itensPedido1).isNotEqualTo(itensPedido2);
itensPedido1.setId(null);
assertThat(itensPedido1).isNotEqualTo(itensPedido2);
}
@Test
@Transactional
public void dtoEqualsVerifier() throws Exception {
TestUtil.equalsVerifier(ItensPedidoDTO.class);
ItensPedidoDTO itensPedidoDTO1 = new ItensPedidoDTO();
itensPedidoDTO1.setId(1L);
ItensPedidoDTO itensPedidoDTO2 = new ItensPedidoDTO();
assertThat(itensPedidoDTO1).isNotEqualTo(itensPedidoDTO2);
itensPedidoDTO2.setId(itensPedidoDTO1.getId());
assertThat(itensPedidoDTO1).isEqualTo(itensPedidoDTO2);
itensPedidoDTO2.setId(2L);
assertThat(itensPedidoDTO1).isNotEqualTo(itensPedidoDTO2);
itensPedidoDTO1.setId(null);
assertThat(itensPedidoDTO1).isNotEqualTo(itensPedidoDTO2);
}
@Test
@Transactional
public void testEntityFromId() {
assertThat(itensPedidoMapper.fromId(42L).getId()).isEqualTo(42);
assertThat(itensPedidoMapper.fromId(null)).isNull();
}
}
|
package com.joalib.board.svc;
import com.joalib.DAO.DAO;
import com.joalib.DTO.BoardDTO;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class MyBoardViewService{
public ArrayList[] myBoardPost(String member_id) {
DAO dao = DAO.getinstance();
List list = dao.myBoardView(member_id); //내가 쓴 글정보
int postCount = 10; //글 10개씩 보이기
int count = 0;
int pageTotalCount = list.size() / postCount; //보여지는 페이지 수
if(list.size() % postCount != 0) //10개씩 나워서 나머지가 남으면,페이지수 한 장 추가
pageTotalCount++;
ArrayList[] totalPage = new ArrayList[pageTotalCount];
for(int i = 0; i < pageTotalCount; i++) {
ArrayList page = new ArrayList();
for(int j = 0; j < postCount; j++) {
page.add((BoardDTO)list.get(count));
if(count == (list.size()-1)) {
break;}
count++;
}
if(page == null) {
System.out.println("NULL error");
}else {
totalPage[i] = page;
}
}
return totalPage;
}
}
|
/*
* 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 library;
/**
*
* @author PhiLong
*/
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
public class SendingEmail extends javax.swing.JFrame {
/**
* Creates new form SendingEmail
*/
private Task task;
class Task extends SwingWorker<Void, Void> {
/**
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
// Initialize progress property.
setProgress(0);
while (progress < 100) {
// Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {
}
// Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
/**
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null); // turn off the wait cursor
taskOutput.append("Done!\n");
}
}
public SendingEmail() {
super("Sending Email");
initComponents();
setLocationRelativeTo(null);
startButton.setActionCommand("start");
// startButton.addActionListener(new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// startButton.setEnabled(false);
// setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// // Instances of javax.swing.SwingWorker are not reusuable, so
// // we create new instances as needed.
// task = new Task();
// task.addPropertyChangeListener(new PropertyChangeListener() {
// @Override
// public void propertyChange(PropertyChangeEvent evt) {
// if ("progress" == (evt.getPropertyName())) {
// int progress = (Integer) evt.getNewValue();
// progressBar.setValue(progress);
// taskOutput.append(String.format("Completed %d%% of task.\n", task.getProgress()));
// }
//// System.out.println("123");
// }
// });
// task.execute();
// }
// });
progressBar.setValue(0);
progressBar.setStringPainted(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
progressBar = new javax.swing.JProgressBar();
startButton = new javax.swing.JButton();
Button2 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
taskOutput = new javax.swing.JTextArea();
lb1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
formPropertyChange(evt);
}
});
startButton.setText("Send");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});
Button2.setText("Cancel");
Button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Button2ActionPerformed(evt);
}
});
taskOutput.setEditable(false);
taskOutput.setColumns(20);
taskOutput.setFont(new java.awt.Font("Arial", 2, 13)); // NOI18N
taskOutput.setRows(5);
taskOutput.setToolTipText("");
taskOutput.setMargin(new java.awt.Insets(5, 5, 5, 5));
jScrollPane1.setViewportView(taskOutput);
lb1.setText("SEND EMAIL");
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()
.addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(startButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Button2)
.addGap(31, 31, 31))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(122, 122, 122)
.addComponent(lb1)
.addContainerGap(119, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(lb1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(Button2))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void Button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button2ActionPerformed
this.dispose(); // TODO add your handling code here:
}//GEN-LAST:event_Button2ActionPerformed
private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange
}//GEN-LAST:event_formPropertyChange
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
}//GEN-LAST:event_startButtonActionPerformed
/**
* @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 {
UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SendingEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SendingEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SendingEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SendingEmail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new SendingEmail().setVisible(true);
}
});
}
public Task getTask() {
return task;
}
public JProgressBar getProgressBar() {
return progressBar;
}
public JButton getStartButton() {
return startButton;
}
public JTextArea getTaskOutput() {
return taskOutput;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Button2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lb1;
private javax.swing.JProgressBar progressBar;
private javax.swing.JButton startButton;
private javax.swing.JTextArea taskOutput;
// End of variables declaration//GEN-END:variables
}
|
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
// LightOffCommand는 리시버를 다른 메소드(off()메소드)하고 결합시킨다는 점을 제외하면 LightOnCommand하고 똑같은 식으로 작동
public void execute() {
light.off();
}
}
|
package persistance.dao;
import persistance.model.Team;
import java.util.List;
/**
* Created by tkachdan on 04-Dec-14.
*/
public interface TeamDAO {
public void saveTeam(Team team);
public Team getTeam(int id);
public List<Team> getAllTeams();
public void updateTeam(Team Team);
public void deleteTeam(int id);
public boolean isExists(Team team);
} |
package bis.project.controllers;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import bis.project.model.BankMessages;
import bis.project.services.BankMessagesServices;
import bis.project.services.CredentialsServices;
import bis.project.validators.BankMessagesValidator;
import bis.project.validators.ValidationException;
@RestController
public class BankMessagesController {
@Autowired
private BankMessagesServices services;
@Autowired
private CredentialsServices cServices;
@RequestMapping(value = "/api/messages",
method = RequestMethod.GET)
public ResponseEntity<Set<BankMessages>> getAllBankMessages(@RequestHeader(value="CsrfToken") String csrfToken,
@RequestHeader(value="AuthEmail") String authEmail,
@RequestHeader(value="BankId") Integer bankId,
@CookieValue("jwt") String jwt) {
boolean isAuthorized = false;
isAuthorized = cServices.isJWTAuthorized(jwt, csrfToken, authEmail, bankId, "GetAllBankMessages");
//boolean isAuthorized = cServices.isAuthorized(basicAuth, "GetAllBankMessages");
if(isAuthorized) {
Set<BankMessages> messages = services.getBankMessages();
return new ResponseEntity<Set<BankMessages>>(messages, HttpStatus.OK);
}
return new ResponseEntity<Set<BankMessages>>(HttpStatus.UNAUTHORIZED);
}
@RequestMapping(value = "/api/messages/{id}",
method = RequestMethod.GET)
public ResponseEntity<BankMessages> getBankMessage(@PathVariable("id") Integer id,
@RequestHeader(value="CsrfToken") String csrfToken,
@RequestHeader(value="AuthEmail") String authEmail,
@RequestHeader(value="BankId") Integer bankId,
@CookieValue("jwt") String jwt) {
boolean isAuthorized = false;
isAuthorized = cServices.isJWTAuthorized(jwt, csrfToken, authEmail, bankId, "GetBankMessage");
//boolean isAuthorized = cServices.isAuthorized(basicAuth, "GetBankMessage");
if(isAuthorized) {
BankMessages message = services.getBankMessage(id);
if(message != null) {
return new ResponseEntity<BankMessages>(message, HttpStatus.OK);
}
return new ResponseEntity<BankMessages>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<BankMessages>(HttpStatus.UNAUTHORIZED);
}
@RequestMapping(value = "/api/messages",
method = RequestMethod.POST)
public ResponseEntity<BankMessages> addBankMessage(@RequestBody BankMessages message,
@RequestHeader(value="CsrfToken") String csrfToken,
@RequestHeader(value="AuthEmail") String authEmail,
@RequestHeader(value="BankId") Integer bankId,
@CookieValue("jwt") String jwt) throws ValidationException {
boolean isAuthorized = false;
isAuthorized = cServices.isJWTAuthorized(jwt, csrfToken, authEmail, bankId, "AddBankMessage");
//boolean isAuthorized = cServices.isAuthorized(basicAuth, "AddBankMessage");
if(isAuthorized) {
BankMessagesValidator.Validate(message);
BankMessages m = services.addBankMessage(message);
return new ResponseEntity<BankMessages>(m, HttpStatus.OK);
}
return new ResponseEntity<BankMessages>(HttpStatus.UNAUTHORIZED);
}
//need to add check for this id
@RequestMapping(value = "/api/messages/{id}",
method = RequestMethod.PUT)
public ResponseEntity<BankMessages> updateBankMessage(@PathVariable("id") Integer id, @RequestBody BankMessages message,
@RequestHeader(value="CsrfToken") String csrfToken,
@RequestHeader(value="AuthEmail") String authEmail,
@RequestHeader(value="BankId") Integer bankId,
@CookieValue("jwt") String jwt) throws ValidationException {
boolean isAuthorized = false;
isAuthorized = cServices.isJWTAuthorized(jwt, csrfToken, authEmail, bankId, "UpdateBankMessage");
//boolean isAuthorized = cServices.isAuthorized(basicAuth, "UpdateBankMessage");
if(isAuthorized) {
BankMessagesValidator.Validate(message);
message.setId(id);
BankMessages m = services.updateBankMessage(message);
return new ResponseEntity<BankMessages>(m, HttpStatus.OK);
}
return new ResponseEntity<BankMessages>(HttpStatus.UNAUTHORIZED);
}
@RequestMapping(value = "/api/messages/{id}",
method = RequestMethod.DELETE)
public ResponseEntity<BankMessages> deleteBankMessage(@PathVariable("id") Integer id,
@RequestHeader(value="CsrfToken") String csrfToken,
@RequestHeader(value="AuthEmail") String authEmail,
@RequestHeader(value="BankId") Integer bankId,
@CookieValue("jwt") String jwt) {
boolean isAuthorized = false;
isAuthorized = cServices.isJWTAuthorized(jwt, csrfToken, authEmail, bankId, "DeleteBankMessage");
//boolean isAuthorized = cServices.isAuthorized(basicAuth, "DeleteBankMessage");
if(isAuthorized) {
services.deleteBankMessage(id);
return new ResponseEntity<BankMessages>(HttpStatus.OK);
}
return new ResponseEntity<BankMessages>(HttpStatus.UNAUTHORIZED);
}
}
|
package com.exam.connection_pool;
import com.exam.util.ExceptionalConsumer;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
@Log4j
public class ConnectionPool {
@Getter
private static ConnectionPool instance;
@Getter
private BlockingQueue<Connection> connectionQueue;
@Getter
private BlockingQueue<Connection> givenAwayConQueue;
private String driverName;
private String url;
private String user;
private String password;
private int poolSize;
private ConnectionPool(String pathToParams) {
try (FileInputStream fileInputStream = new FileInputStream(pathToParams);
BufferedInputStream stream = new BufferedInputStream(fileInputStream)) {
Properties dbProperties = new Properties();
dbProperties.load(stream);
this.driverName = dbProperties.getProperty("driver");
this.url = dbProperties.getProperty("url");
this.user = dbProperties.getProperty("user");
this.password = dbProperties.getProperty("password");
this.poolSize = Integer.parseInt(dbProperties.getProperty("poolSize"));
} catch (IOException e) {
log.error(e);
}
}
public static void create(String pathToParams) {
instance = new ConnectionPool(pathToParams);
}
public void initPoolData() throws ConnectionPoolException {
System.setProperty("file.encoding", "UTF-8");
try {
Class.forName(driverName);
givenAwayConQueue = new ArrayBlockingQueue<>(poolSize);
connectionQueue = new ArrayBlockingQueue<>(poolSize);
for (int i = 0; i < poolSize; i++) {
Connection connection = DriverManager.getConnection(url, user, password);
PooledConnection pooledConnection = new PooledConnection(connection);
connectionQueue.add(pooledConnection);
}
} catch (SQLException e) {
throw new ConnectionPoolException("SQLException in connection_pool", e);
} catch (ClassNotFoundException e) {
throw new ConnectionPoolException(
"Can't find database driver class", e);
}
}
public void dispose() {
clearConnectionQueue();
}
private void clearConnectionQueue() {
try {
closeConnectionsQueue(givenAwayConQueue);
closeConnectionsQueue(connectionQueue);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection takeConnection() throws ConnectionPoolException {
Connection connection;
try {
connection = connectionQueue.take();
givenAwayConQueue.add(connection);
} catch (InterruptedException e) {
throw new ConnectionPoolException(
"Error connecting to the data source.", e);
}
return connection;
}
@SneakyThrows
public int[] executeScript(String pathToScript) {
try (Connection connection = takeConnection();
Statement statement = connection.createStatement()) {
Arrays.stream(
Files.lines(Paths.get(pathToScript))
.collect(Collectors.joining())
.split(";"))
.forEachOrdered(ExceptionalConsumer.toUncheckedConsumer(statement::addBatch));
return statement.executeBatch();
}
}
private void closeConnectionsQueue(BlockingQueue<Connection> queue)
throws SQLException {
Connection connection;
while ((connection = queue.poll()) != null) {
if (!connection.getAutoCommit()) {
connection.commit();
}
((PooledConnection) connection).reallyClose();
}
}
} |
package jesk.desktopgui.item;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jesk.Jesk;
import jesk.desktopgui.MenuCircle;
import jesk.system.MouseButton;
import jesk.system.OperatingSystem;
import jesk.system.ShellFolder;
import jesk.util.Util;
public class ItemFile extends Item {
public static final int MAXCHARS = 16;
public static final int ICONSIZE = 32;
private File file;
public ItemFile() { }
public ItemFile(ItemSpace itemSpace, int x, int y, File file) {
super(x, y, itemSpace);
this.file = file;
}
public File file() {
return file;
}
public String getFilePath() {
return file.getAbsolutePath();
}
public void setFilePath(String filePath) {
this.file = new File(filePath);
}
public ShellFolder getShellFolder() {
return Jesk.getShellFolder(file);
}
@Override
public String getDescription() {
ShellFolder shellFolder = getShellFolder();
return shellFolder != null ? shellFolder.getDisplayName() : "";
}
@Override
public Image getIcon() {
ShellFolder shellFolder = getShellFolder();
return shellFolder != null ? shellFolder.getIcon(true) : null;
}
@Override
public int getWidth(Graphics2D g) {
String[] spl = Util.wrap(getDescription(), MAXCHARS).split("\n");
return Math.max(ICONSIZE * 4, Util.measureStringWidth(g, spl));
}
@Override
public int getHeight(Graphics2D g) {
g.setFont(new Font(Font.DIALOG, Font.PLAIN, 16));
String[] spl = Util.wrap(getDescription(), MAXCHARS).split("\n");
return 2 + ICONSIZE + 4 + Util.measureStringHeight(g, spl, 0) + 2;
}
@Override
public void update(Graphics2D g) {
if (file == null || !file.exists()) {
remove();
}
}
@Override
public void render(Graphics2D g) {
int x = getXOnScreen(), y = getYOnScreen();
int w = getWidth(g), h = getHeight(g);
Image icon = getIcon();
String[] spl = Util.wrap(getDescription(), MAXCHARS).split("\n");
if (itemspace().isSelected(this)) {
g.setColor(new Color(0x8822AAFF, true));
g.fillRoundRect(x - 2, y - 2, w + 4, h + 4, 3, 3);
g.setColor(new Color(0x44000000, true));
g.drawRoundRect(x - 2, y - 2, w + 4, h + 4, 3, 3);
g.setColor(new Color(0x66FFFFFF, true));
g.drawRoundRect(x - 1, y - 1, w + 2, h + 2, 3, 3);
}
g.setColor(new Color(0x44FFFFFF, true));
if (isMouseOver(g)) {
g.fillRoundRect(x - 2, y - 2, w + 4, h + 4, 3, 3);
Jesk.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
y += 2;
if (icon != null) {
g.drawImage(icon, x + (w - ICONSIZE)/2, y, ICONSIZE, ICONSIZE, null);
} else {
g.drawRect(x + (w - ICONSIZE)/2, y, ICONSIZE - 1, ICONSIZE - 1);
}
y += ICONSIZE + 4 + g.getFontMetrics().getAscent();
g.setFont(new Font(Font.DIALOG, Font.PLAIN, 16));
for (int i=0; i<spl.length; i++) {
String n = spl[i];
int rx = x + (w - g.getFontMetrics().stringWidth(n)) / 2;
g.setColor(new Color(0x33000000, true));
Rectangle2D bounds = g.getFontMetrics().getStringBounds(n, g);
g.fillRect((int) (rx + bounds.getX()), (int) (y + bounds.getY()), (int) bounds.getWidth(), (int) bounds.getHeight());
g.setColor(Color.WHITE);
g.drawString(n, rx, y);
y += bounds.getHeight();
}
}
@Override
public void onClick(Graphics2D g, MouseEvent event) {
MouseButton button = MouseButton.get(event, true);
if (button == MouseButton.LEFT) {
if (event.getClickCount() % 2 == 0) { // double click
OperatingSystem.launch(file);
} else {
boolean selected = itemspace().isSelected(this);
if (!event.isControlDown()) {
itemspace().setAllSelected(false);
}
itemspace().setSelected(this, !selected);
}
} else if (button == MouseButton.RIGHT) {
final ShellFolder shellFolder = getShellFolder();
if (shellFolder == null)
return;
ActionListener l = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String cmd = event.getActionCommand();
List<Item> selected = new ArrayList<>();
if (itemspace().getSelectionCount() > 0) {
selected.addAll(itemspace().selectedItems);
} else {
selected.add(ItemFile.this);
}
if (cmd.equals("open")) {
for (int i=0; i<selected.size(); i++) {
Item item = selected.get(i);
if (item instanceof ItemFile) {
OperatingSystem.launch(((ItemFile) item).file);
}
}
} else if (cmd.equals("edit")) {
for (int i=0; i<selected.size(); i++) {
Item item = selected.get(i);
if (item instanceof ItemFile) {
OperatingSystem.edit(((ItemFile) item).file);
}
}
} else if (cmd.equals("print")) {
for (int i=0; i<selected.size(); i++) {
Item item = selected.get(i);
if (item instanceof ItemFile) {
OperatingSystem.print(((ItemFile) item).file);
}
}
}
}
};
if (!itemspace().isSelected(this)) {
itemspace().setAllSelected(false);
itemspace().setSelected(this, true);
}
int numSel = itemspace().getSelectionCount();
Rectangle2D selBounds = itemspace().getSelectionBounds(g);
int x = (int) (numSel > 0 ? selBounds.getCenterX() : getXOnScreen() + getWidth(g)/2),
y = (int) (numSel > 0 ? selBounds.getCenterY() : getYOnScreen() + ICONSIZE/2);
MenuCircle menu = new MenuCircle(x, y, itemspace());
menu.add(new MenuCircle.Option("Open", 0.5, "open", l));
menu.add(new MenuCircle.Option("Edit", 0.25, "edit", l));
menu.add(new MenuCircle.Option("Print", 0.25, "print", l));
itemspace().openMenu(menu);
}
}
} |
package cpup.poke4j.ui;
public interface UI {
public abstract SplitUI splitH();
public abstract SplitUI splitV();
public abstract UI duplicate();
public abstract void startup();
public abstract void cleanup();
public abstract void replace(UI rep);
// Getters and Setters
public abstract PokeUI getPokeUI();
public abstract UI getParentUI();
} |
package dev.liambloom.softwareEngineering.chapter16;
import java.util.Collection;
import java.util.List;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Comparator;
import java.lang.reflect.Array;
import java.util.NoSuchElementException;
public abstract class AbstractLinkedList<E, N extends AbstractLinkedList<E, N>.Node> implements List<E> {
N head = null;
N tail = null;
int size = 0;
protected abstract class Node {
E data;
N next = null;
public Node(final E data) {
this.data = data;
}
}
protected abstract class AbstractListIterator implements ListIterator<E> {
N prev = null;
N next = head;
N lastReturned = null;
int index = 0;
boolean modOk = false;
public E next() {
if (next == null)
throw new NoSuchElementException();
else {
index++;
prev = next;
next = next.next;
modOk = true;
lastReturned = prev;
return prev.data;
}
}
public boolean hasNext() {
return next != null;
}
public int nextIndex() {
return index;
}
public boolean hasPrevious() {
return prev != null;
}
public int previousIndex() {
return index - 1;
}
public void set(E e) {
if (!modOk)
throw new IllegalStateException();
lastReturned.data = e;
}
}
public boolean add(final E e) {
listIterator(size).add(e);
return true;
}
public void add(final int index, final E e) {
listIterator(index).add(e);
}
public boolean addAll(Collection<? extends E> c) {
ListIterator<E> iter = listIterator(size);
for (E e : c)
iter.add(e);
return c.size() != 0;
}
public boolean addAll(final int index, final Collection<? extends E> c) {
if (c.size() == 0)
return false;
ListIterator<E> iter = listIterator(index);
for (E e : c)
iter.add(e);
return true;
}
@SuppressWarnings("unchecked")
public void addSorted(final E data) {
if (data instanceof Comparable)
addSorted(data, (Comparator<E>) Comparator.naturalOrder());
else
throw new ClassCastException();
}
public void addSorted(final E data, final Comparator<E> comparator) {
final ListIterator<E> iter = listIterator();
while (iter.hasNext()) {
if (comparator.compare(iter.next(), data) < 0) {
iter.previous();
break;
}
}
iter.add(data);
}
@SuppressWarnings("unused")
private void AddInOrder(final N node) {
addSorted(node.data);
}
public int size() {
return size;
}
public Iterator<E> iterator() {
return listIterator();
}
protected N getNode(final int i) {
if (i == 0)
return head;
else if (i + 1 == size)
return tail;
else if (i >= size || i < 0)
return null;
else {
N e = head;
for (int j = 0; j < i; j++)
e = e.next;
return e;
}
}
public void clear() {
head = null;
tail = null;
size = 0;
}
public boolean contains(Object o) {
for (E e : this) {
if (e.equals(o))
return true;
}
return false;
}
public boolean containsAll(Collection<?> c) {
for (Object e : c) {
if (!contains(e))
return false;
}
return true;
}
public boolean equals(final Object other) {
if (other instanceof List) {
List<?> o = (List<?>) other;
if (size == o.size()) {
Iterator<E> iterThis = iterator();
Iterator<?> iterOther = o.iterator();
while (iterThis.hasNext()) {
if (!iterThis.next().equals(iterOther.next()))
return false;
}
return true;
}
else
return false;
}
else
return false;
}
public E get(int i) {
return getNode(i).data;
}
public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
return hashCode;
}
public int indexOf(Object o) {
Iterator<E> iter = iterator();
for (int i = 0; iter.hasNext(); i++) {
if (iter.next().equals(o))
return i;
}
return -1;
}
public int lastIndexOf(Object o) {
final ListIterator<E> iter = listIterator(size);
for (int i = size - 1; iter.hasPrevious(); i--) {
if (iter.previous().equals(o))
return i;
}
return -1;
}
public boolean isEmpty() {
return size == 0;
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
public E set(int index, E element) {
N n = getNode(index);
E prev = n.data;
n.data = element;
return prev;
}
public E remove(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException();
Iterator<E> iter = iterator();
for (int i = 0; i < index; i++)
iter.next();
E r = iter.next();
iter.remove();
return r;
}
public boolean remove(Object o) {
Iterator<E> iter = iterator();
while (iter.hasNext()) {
if (o == null ? iter.next() == null : o.equals(iter.next())) {
iter.remove();
return true;
}
}
return false;
}
@SuppressWarnings("unused")
private void removeNode(N node) {
Iterator<E> iter = iterator();
while (iter.hasNext()) {
if (node.data == null ? iter.next() == null : node.data.equals(iter.next()))
iter.remove();
}
}
public boolean removeAll(final Collection<?> c) {
boolean changed = false;
Iterator<E> iter = iterator();
while (iter.hasNext()) {
if (c.contains(iter.next())) {
iter.remove();
changed = true;
}
}
return changed;
}
public boolean retainAll(final Collection<?> c) {
boolean changed = false;
Iterator<E> iter = iterator();
while (iter.hasNext()) {
if (!c.contains(iter.next())) {
iter.remove();
changed = true;
}
}
return changed;
}
public List<E> subList(int start, final int end) {
if (start < 0 || start > end || end > size)
throw new IndexOutOfBoundsException();
List<E> newList = new LinkedList<>();
for (Node e = getNode(start); start < end; start++) {
newList.add(e.data);
e = e.next;
}
return newList;
}
public Object[] toArray() {
return toArray(new Object[0]);
}
// A large portion of this method is taken from the original java code
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
N n = head;
Object[] r = a;
for (int i = 0; i < size; n = n.next)
r[i++] = n.data;
for (int i = size; i < a.length; i++)
r[i] = null;
return a;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append('[');
if (size > 0) {
Iterator<E> iter = iterator();
builder.append(iter.next().toString());
while (iter.hasNext())
builder.append(", " + iter.next().toString());
}
builder.append(']');
//System.out.println("String: " + builder.toString());
return builder.toString();
}
}
|
package org.minbox.framework.little.bee.core.jvm.option;
import org.minbox.framework.little.bee.core.jvm.AbstractJvmOption;
import org.minbox.framework.little.bee.core.jvm.JvmOptionType;
/**
* The "-client" jvm option
* <p>
* Use example:
* <pre>
* public static void main(String[] args){
* String client = JvmOptionFactory.getJvmOption(JvmClientOption.class, LittleBeeConstant.EMPTY_STRING).format();
* // -client
* System.out.println(client);
* }
* </pre>
*
* @author 恒宇少年
*/
public class JvmClientOption extends AbstractJvmOption {
private static final String JVM_CLIENT = "client";
@Override
public JvmOptionType getOptionType() {
return JvmOptionType.Standard;
}
@Override
public String getOptionName() {
return JVM_CLIENT;
}
}
|
package faker;
import model.Location;
import model.Temperature;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.UUID;
public class DataFaker {
/**
* Build a fake dataset
* @param size
* @return HashSet<Temperature> set of random temperatures
*/
public static HashSet<Temperature> getRandomTemperatureDataSet(int size) throws InterruptedException {
HashSet<Temperature> temperatures = new HashSet<Temperature>();
for (int i = 0; i<size; i++){
temperatures.add(getRandomTemperature());
Thread.sleep(1000);
}
return temperatures;
}
private static Temperature getRandomTemperature() {
Location [] locations = getAvailableLocations();
Location randomLocation = locations[getRandomNumber(0, locations.length-1)];
return new Temperature(UUID.randomUUID().toString(), new GregorianCalendar(), getRandomNumber(0, 45), randomLocation);
}
private static Location[] getAvailableLocations() {
Location princeton_nj = new Location("PRINCETON_NJ", 40.366633, 74.640832);
Location ithaca_ny = new Location("ITHACA_NY", 42.443087, 76.488707);
Location paris = new Location("PARIS", 48.866667, 2.333333);
Location newYork = new Location("NEW_YORK", 40.7127753, -74.0059728);
Location zurich = new Location("ZURICH", 47.3768866, 8.541694000000007);
Location [] locations = {princeton_nj, ithaca_ny, paris, newYork, zurich};
return locations;
}
private static int getRandomNumber(int min, int max){
return min + (int)(Math.random() * ((max - min) + 1));
}
}
|
package com.huy8895.dictionaryapi.config.aop;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Order(0)
public @interface RedisCache {
String value() default "";
String cacheName() default "";
int expire() default 1;
} |
package solid.pattern;
import shop.customers.Customer;
import shop.customers.Order;
import solid.templater.EmailMessageSendTemplater;
import solid.templater.RusMessageOrderTemplater;
import solid.templater.SMSMessageSendTemplater;
import solid.templater.api.IMessageOrderTemplater;
import solid.templater.api.IMessageSendTemplater;
public class MediatorMessangeSender {
public boolean send(Customer customer, Order order){
boolean managerSleep = true;
String number;
IMessageOrderTemplater messageOrderTemplater = new RusMessageOrderTemplater();
IMessageSendTemplater messageSendTemplater;
String text = messageOrderTemplater.getText(customer, order);
if (!managerSleep){
messageSendTemplater = new EmailMessageSendTemplater();
number = "Kuku.@mail.com";
}
else{
messageSendTemplater = new SMSMessageSendTemplater();
number = "+3759999999";
}
return messageSendTemplater.sendMessage(number, customer, order, text);
}
}
|
package mine.fan;
import mine.exceptions.AlreadyRunning;
import mine.exceptions.AlreadyStopped;
public class StartStopExceptionDecorator extends StartStopDevice {
private StartStopDevice instance;
private boolean isRunning;
public StartStopExceptionDecorator(StartStopDevice instance) {
this.instance = instance;
this.isRunning = false;
}
@Override
void start() throws AlreadyRunning {
if (isRunning) {
throw new AlreadyRunning();
}
this.instance.start();
this.isRunning = true;
}
@Override
void stop() throws AlreadyStopped {
if (!isRunning) {
throw new AlreadyStopped();
}
this.instance.stop();
this.isRunning = false;
}
}
|
package logicaJuego;
import java.io.Serializable;
public class Bloque extends Entidad implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
//tipos de bloques
private String tipoBloque;
private int id;
public Bloque(String tipo,int x, int y) {
super(x,y);
this.tipoBloque=tipo;
}
@Override
public String toString() {
return tipoBloque;
}
public String queTipo() {
return this.tipoBloque;
}
public void explotarPiedra() {
this.tipoBloque="transitable";
}
@Override
public boolean esBloque() {
return true;
}
@Override
public boolean esBomberman() {
return false;
}
@Override
public boolean esBomba() {
return false;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
} |
package com.icanit.app_v2.entity;
// default package
import java.util.HashSet;
import java.util.Set;
public class AppCommunity implements java.io.Serializable {
// Fields
public int longitudeE6,latitudeE6,flag;
public String commName,location,id,areaId;
} |
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class HomePage extends Util1 {
private By _registerbutton = By.linkText("Register");
private By _Computers = By.linkText("Computers");
private By _Electronics = By.linkText("Electronics");
private By _Searchinputbox = By.xpath("//input[@type=\"submit\"]");
private By _Facebook = By.linkText("Facebook");
private By _NewOnlineStore = By.linkText("New online store is open!");
private By _Currencyselect = By.xpath("//select[@id=\"customerCurrency\"]");
public void VerifyTextofHomePage() { //Assert homepage text
String expectedTitle = "Welcome to our store";
String actualText1 = getTextfromElement(By.xpath("//h2[text() ='Welcome to our store']"));
Assert.assertEquals(actualText1, expectedTitle);
}
public void clickregistration() {
clickElement(_registerbutton, 20);
} //click registration link
public void ClickonComputer() {
clickElement(_Computers, 20);
} // click computer link
public void ClickonElectronics() {
clickElement(_Electronics, 20);
} // click electronics link
public void clickonSearchButton() { clickElement(_Searchinputbox, 40); } // click search input box
public void alertMessage() { //Switch to alert message and get text from alert
driver.switchTo().alert().getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String alertMessage = driver.switchTo().alert().getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println(alertMessage);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void verifyTextofAlert() { // Assert text from alert message
String expectedTitle = "Please enter some search keyword"; //Expected alert message
String actualText1 = driver.switchTo().alert().getText(); //Actual alert message
Assert.assertEquals(actualText1, expectedTitle); //Assert actual and expected message
}
public void acceptAlert() {
driver.switchTo().alert().accept();
}// Method to click ok on alert
public void clickOnFaceBook() {
clickElement(_Facebook, 20);
} //Method to click on Facebbok link
public void clickOnNewonlineStore() { clickElement(_NewOnlineStore, 20); } //Method to click on New online store
public void Selectcurrency() { //Method to select currency from homepage
clickElement(_Currencyselect, 20); //click on currency button
Select currency = new Select(driver.findElement(_Currencyselect));//select Euro currency
currency.selectByVisibleText("Euro");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//Wait time 30 second
List<WebElement> ProductName = driver.findElements(By.className("prices"));
for (WebElement Product : ProductName) //For each loop for confirming currency symbol of four products
System.out.println(Product.getText().contains("")); // Print result of four products with Euro and prices
}
public void Assertcurrency () { //Method to assert currency and symbol
String expectedTitle = "€21.50";
String actualText1 = getTextfromElement(By.xpath("//span[text()='€21.50']"));
Assert.assertEquals(actualText1, expectedTitle);
}
}
|
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LogWriter {
public final static String path = "data/log.csv";
private BufferedWriter writer;
public LogWriter(){
}
public void write(int size, int seconds, Player player1, Player player2, boolean giveUp){
try{
File file = new File(path);
boolean error = false;
String out;
if (!file.exists()){
error = !file.createNewFile();
}
if (error){
throw new Exception(path + " file create failed.");
}
writer = new BufferedWriter(new FileWriter(file,true));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out = wrap(df.format(new Date())) + ",";
out += wrap(seconds+"") + ",";
out += wrap(size + "*" + size) + ",";
out += wrap(player1.getName()) + ",";
out += wrap(player2.getName()) + ",";
if (giveUp){
out += wrap("Human gave up.");
}
else {
out += wrap(player1.getGridsNumber() + " to " + player2.getGridsNumber());
}
writer.write(out);
writer.newLine();
writer.close();
}
catch (Exception e){
e.printStackTrace();
}
}
private String wrap(String content){
return "\"" + content + "\"";
}
}
|
package com.housesline.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.housesline.service.out.AppDirectorByGrlService;
/**
* 经理段app
* @author grl 2017-09-05
*
*/
@Controller
public class AppDirectorByGrlController {
@Autowired
private AppDirectorByGrlService appDirectorService;
@ResponseBody
@RequestMapping("/test")
public String testThisPro(){
return "hello world";
}
//获取详细接访数据(1.1)
@ResponseBody
@RequestMapping("/get_toDay_detail_Receive_data")
public String getToDayDetailedReceiveData(String proId,String startDate,String endDate){
Map map = appDirectorService.findToDayDetailedReceiveDataByTime(proId,startDate,endDate);
String mapStr = JSON.toJSONString(map);
return mapStr;
}
//获取详细成交数据(1.2.2)
@ResponseBody
@RequestMapping("/get_deal_data")
public String getDealDataData(String proId,String startDate,String endDate){
Map map = appDirectorService.findDealDataByTime(proId,startDate,endDate);
String mapStr = JSON.toJSONString(map);
return mapStr;
}
// 获取顾问状态数据(1.1.2)
@ResponseBody
@RequestMapping("/get_agent_status_data")
public Object getAgentStatusData(String proId,String startDate,String endDate,String agentId){
Map map = appDirectorService.findAgentStatusDataById(proId,startDate,endDate,agentId);
return map;
}
}
|
package ideablog.service.impl;
import ideablog.dao.IStatisticDao;
import ideablog.model.Statistic;
import ideablog.service.IStatisticService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("statisticService")
public class StatisticServiceImpl implements IStatisticService {
@Resource
private IStatisticDao statisticDao;
@Override
public Statistic selectStatisticByUserId(long userId) {
return this.statisticDao.selectStatisticByUserId(userId);
}
} |
package IteratorPattern;
import java.util.ArrayList;
import java.util.Iterator;
public class MenuByArrayList extends MenuComponent{
private ArrayList<MenuComponent> list;
private String name;
private String description;
public MenuByArrayList(String name,String description) {
super();
this.list = new ArrayList<MenuComponent>();
this.name = name;
this.description = description;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return description;
}
@Override
public void add(MenuComponent menuComponent) {
// TODO Auto-generated method stub
list.add(menuComponent);
}
@Override
public void remove(MenuComponent menuComponent) {
// TODO Auto-generated method stub
list.remove(menuComponent);
}
@Override
public MenuComponent getChild(int index) {
// TODO Auto-generated method stub
return list.get(index);
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println(name+"---"+description+"---");
Iterator<MenuComponent> iterator = list.iterator();
while (iterator.hasNext()) {
MenuComponent object = iterator.next();
object.print();
}
}
public Iterator<MenuComponent> createIterator() {
return list.iterator();
}
}
|
/*
SQL Schema Migration Toolkit
Copyright (C) 2015 Cédric Tabin
This file is part of ssmt, a tool used to maintain database schemas up-to-date.
The author can be contacted on http://www.astorm.ch/blog/index.php?contact
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 ch.astorm.ssmt.tools.sql;
import ch.astorm.ssmt.tools.sql.SQLToken.Type;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Creates {@code SQLToken} from an input. This class will only generate the tokens
* in order to make it easier for a parser to analyze. Note that this lexer is completely
* blind regarding the SQL syntax used.
*/
public class SQLLexer implements Iterator<SQLToken> {
private Reader reader;
private boolean readerOpen;
private SQLSyntax syntax;
private SQLToken nextToken;
private int currentIndex;
private int currentLine;
private int currentColumn;
private List<Integer> buffer;
private Map<String, Object> context;
/**
* Creates a new {@code SQLLexer} with the specified {@code reader} and {@code syntax}.
*/
public SQLLexer(Reader reader, SQLSyntax syntax) {
this.reader = reader;
this.readerOpen = true;
this.syntax = syntax;
this.currentIndex = -1;
this.currentLine = 1;
this.buffer = new ArrayList<>(8);
this.context = new HashMap<>();
}
/**
* Returns the current index of the char being parsed.
*/
public int getCurrentIndex() {
return currentIndex;
}
/**
* Returns the current line of the char being parsed.
*/
public int getCurrentLine() {
return currentLine;
}
/**
* Returns the current column of the char being parsed.
*/
public int getCurrentColumn() {
return currentColumn;
}
/**
* Returns the context of the lexer. This context can be used by the {@code SQLSyntax}
* handler to store data according to this lexer.
*/
public Map<String, Object> getContext() {
return context;
}
/**
* Peeks the next chars from the input without consuming them. This method is
* especially useful when some keywords are composed with multiple chars (ie multiline
* comments).
*
* @param nbChars The number of chars to peek.
* @return A String with is {@code nbChars} length. The return string can be shorter
* if the end of the stream is reached.
*/
public String peekNextChars(int nbChars) {
StringBuilder builder = new StringBuilder(nbChars);
int counter = 0;
while(counter<nbChars) {
if(counter<buffer.size()) { //read from the buffer
int c = buffer.get(counter);
builder.append((char)c);
} else if(readerOpen) { //read from the reader
try {
int c = reader.read();
if(c<0) {
reader.close();
readerOpen = false;
break;
}
buffer.add(c);
builder.append((char)c);
} catch(IOException ioe) {
throw new RuntimeException("Unable to read next char from the reader", ioe);
}
} else { //reader is closed
break;
}
++counter;
}
return builder.toString();
}
/**
* Peeks the next char from the input without consuming it.
*/
public int peekNextChar() {
if(!buffer.isEmpty()) {
return buffer.get(0);
}
if(!readerOpen) {
return -1;
}
try {
int c = reader.read();
if(c<0) {
reader.close();
readerOpen = false;
return c;
}
buffer.add(c);
return c;
} catch(IOException ioe) {
throw new RuntimeException("Unable to read next char from the reader", ioe);
}
}
/**
* Returns true if there is a token to read.
*/
@Override
public boolean hasNext() {
if(nextToken!=null) { return true; }
if(!readerOpen) { return false; }
strip();
int nextChar = peekNextChar();
if(nextChar<0) { return false; } //end of the stream reached
//handles a quoted literal
if(syntax.isQuoteStart(this)) {
char openingQuote = (char)nextChar();
//read until the escape ends
int indexStart = currentIndex+1;
int cline = currentLine;
int ccol = currentColumn+1;
StringBuilder builder = new StringBuilder(16);
boolean quoteClosed = syntax.isQuoteEnd(this, openingQuote, builder);
if(quoteClosed) {
nextChar(); //consumes the closing quote (or the escaper)
boolean escaped = syntax.isQuoteEscaped(this, openingQuote, builder);
if(escaped) { quoteClosed = false; }
}
while(!quoteClosed) {
int c = nextChar();
if(c<0) { throw new RuntimeException("Unexpected end of stream: quoted literal not closed"); }
builder.append((char)c);
quoteClosed = syntax.isQuoteEnd(this, openingQuote, builder);
if(quoteClosed) {
nextChar(); //consumes the closing quote (or the escaper)
boolean escaped = syntax.isQuoteEscaped(this, openingQuote, builder);
if(escaped) {
c = nextChar();
builder.append((char)c);
quoteClosed = false;
}
}
}
nextToken = new SQLToken(builder.toString(), Type.LITERAL, indexStart, currentIndex, cline, ccol);
return true;
}
//handles separators
if(syntax.isSeparator(this, null, false)) {
int c = nextChar();
nextToken = new SQLToken(""+(char)c, Type.SEPARATOR, currentIndex, currentIndex+1, currentLine, currentColumn);
return true;
}
//handles keywords
int c = nextChar();
int indexStart = currentIndex;
int cline = currentLine;
int ccol = currentColumn;
boolean isNumber = c>='0' && c<='9';
if(c=='-') { //handles negative numbers
int nc = peekNextChar();
isNumber = nc>='0' && c<='9';
}
StringBuilder builder = new StringBuilder(16);
builder.append((char)c);
int n = peekNextChar();
while(n>0 && !isWhite((char)n) && !syntax.isSeparator(this, builder, isNumber) && !syntax.isCommentStart(this)) {
c = nextChar();
builder.append((char)c);
n = peekNextChar();
}
nextToken = new SQLToken(builder.toString(), isNumber ? Type.LITERAL : Type.KEYWORD, indexStart, currentIndex+1, cline, ccol);
return true;
}
/**
* Returns the next {@code SQLToken} if any. If there is no more token, this
* method returns null.
*/
@Override
public SQLToken next() {
if(hasNext()) {
SQLToken r = nextToken;
nextToken = null;
return r;
}
return null;
}
/**
* Returns true if the specified char is a new line. This method returns true if
* {@code c} is either '\n' or '\r'.
*/
public boolean isNewLineChar(char c) {
return c=='\n' || c=='\r';
}
/**
* Returns true if the specified char is a white char. This method returns true
* if {@code c} is either '\n', '\r', '\t' or ' '.
*/
public boolean isWhite(char c) {
return isNewLineChar(c) || c==' ' || c=='\t';
}
/**
* Consumes the next char. This method will either consume the char from the buffer
* of from the input source if the buffer is empty. The current index and line will
* also be updated.
*/
private int nextChar() {
int nextChar;
if(!buffer.isEmpty()) {
nextChar = buffer.remove(0);
} else {
try {
if(!readerOpen) { return -1; }
nextChar = reader.read();
//end of the stream
if(nextChar<0) {
reader.close();
readerOpen = false;
return nextChar;
}
} catch(IOException ioe) {
throw new RuntimeException("Unable to read next SQL token (index="+currentIndex+", line="+currentLine+")", ioe);
}
}
++currentIndex;
if(isNewLineChar((char)nextChar)) {
++currentLine;
currentColumn = 0;
} else {
++currentColumn;
}
return nextChar;
}
private void strip() {
while(true) {
if(stripWhites()) { continue; }
if(stripComments()) { continue; }
break;
}
}
private boolean stripWhites() {
boolean r = false;
int c = peekNextChar();
while(c>=0 && isWhite((char)c)) {
nextChar();
c = peekNextChar();
r = true;
}
return r;
}
private boolean stripComments() {
boolean r = false;
if(syntax.isCommentStart(this)) {
r = true;
int c = nextChar();
StringBuilder builder = new StringBuilder(256);
builder.append((char)c);
while(c>=0 && !syntax.isCommentEnd(this, builder)) {
c = nextChar();
builder.append((char)c);
}
}
return r;
}
}
|
package upenn.cis550.groupf.client;
import java.util.List;
import upenn.cis550.groupf.shared.Content;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Image;
public class HotContentPanel extends VerticalPanel {
public HotContentPanel(List<Content> contents) {
setBorderWidth(3);
setSpacing(10);
Grid grid = new Grid(contents.size(), 1);
add(grid);
setCellHorizontalAlignment(grid, HasHorizontalAlignment.ALIGN_CENTER);
int rowNumber = 0;
for (Content content : contents) {
VerticalPanel panel = new VerticalPanel();
grid.setWidget(rowNumber, 0, panel);
panel.add(new ImageWidgetView(content));
++rowNumber;
}
}
}
|
package domain;
import java.io.Serializable;
import java.util.List;
import domain.interfaces.HasJSON;
import domain.interfaces.IsPostable;
public abstract class AbstractApiObject implements Serializable, HasJSON<AbstractApiObject>,
IsPostable
{
private static final long serialVersionUID = 2033325648556071101L;
private String id;
private Long revision;
private boolean deleted;
public AbstractApiObject(final ApiObjectBuilder builder)
{
super();
this.id = builder.id;
this.revision = builder.revision;
this.deleted = builder.deleted;
}
public static abstract class ApiObjectBuilder
{
private String id = null;
private boolean deleted;
private Long revision;
public ApiObjectBuilder revision(final Long value)
{
this.revision = value;
return this;
}
public ApiObjectBuilder id(final String value)
{
id = value;
return this;
}
public ApiObjectBuilder deleted(final boolean value)
{
deleted = value;
return this;
}
public abstract AbstractApiObject build();
}
@Override
public abstract int hashCode();
@Override
public abstract String toString();
public abstract void postList(final List<AbstractApiObject> list, final int limit);
public abstract DataType getType();
public String getId()
{
return id;
}
public void setId(final String id)
{
this.id = id;
}
public Long getRevision()
{
return revision;
}
public void setRevision(final Long revision)
{
this.revision = revision;
}
public boolean isDeleted()
{
return deleted;
}
public void setDeleted(final boolean deleted)
{
this.deleted = deleted;
}
}
|
package resources;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;
public class ExtendReports {
public static void main(String[] args) {
String path= System.getProperty("user.dir")+"\\extentreports5\\index.html";
ExtentSparkReporter reporter = new ExtentSparkReporter(path);
reporter.config().setDocumentTitle("Testing ");
reporter.config().setReportName("WebAutomation");
ExtentReports reports = new ExtentReports();
reports.attachReporter(reporter);
ExtentTest test=reports.createTest("sampleA");
ExtentTest node = test.createNode("MyFirstChildTest", "Node Description");
test.log(Status.PASS, "pass");
System.out.println("giiii");
test.log(Status.FAIL, "fail");
reports.flush();
test.addScreenCaptureFromBase64String("hi");
node.createNode("jgfjhg");
}
}
|
package com.git.cloud.resmgt.network.model.vo;
import com.git.cloud.common.model.base.BaseBO;
public class RmNwCclassFullVo extends BaseBO implements java.io.Serializable{
private static final long serialVersionUID = 6997663773772673432L;
private String cclassId;
private String platformId;
private String virtualTypeId;
private String hostTypeId;
private String useId;
private String bclassId;
private String useRelCode;
private String secureAreaId;
private String secureTierId;
private String cclassName;
private String subnetmask;
private String gateway;
private String vlanId;
private Long ipStart;
private Long ipEnd;
private Long aclassIp;
private Long bclassIp;
private Long cclassIp;
private Long ipTotalCnt;
private Long ipAvailCnt;
private String datacenterId;
private String convergeId;
private String isActive;
//
private String bclassName;//B段名称
private String datacenterName;//数据中心名称
private Long ipNum;//已使用IP数=vIpNum+hIpNum
private Long vIpNum;//虚拟机使用IP数
private Long hIpNum;//物理机使用IP数
private Long mIpNum;//管理
private Long pIpNum;//生产
private Long iLoIpNum;//ILO
private Long vmoIpNum;//VMO
private Long priIpNum;
private Long fsp1Num;
private Long fsp2Num;
/** default constructor */
public RmNwCclassFullVo() {
}
/** minimal constructor */
public RmNwCclassFullVo(String cclassId,String bclassId) {
this.cclassId = cclassId;
this.bclassId=bclassId;
}
/** full constructor */
public RmNwCclassFullVo(String cclassId, String platformId,
String virtualTypeId, String hostTypeId, String useId,
String bclassId, String useRelCode, String secureAreaId,
String secureTierId, String cclassName, String subnetmask,
String gateway, String vlanId, Long ipStart, Long ipEnd,
Long aclassIp, Long bclassIp, Long cclassIp, Long ipTotalCnt,
Long ipAvailCnt, String datacenterId, String convergeId,
String isActive, String bclassName, String datacenterName,
Long ipNum, Long vIpNum, Long hIpNum, Long mIpNum, Long pIpNum,
Long iLoIpNum, Long vmoIpNum, Long priIpNum, Long fsp1Num,
Long fsp2Num) {
super();
this.cclassId = cclassId;
this.platformId = platformId;
this.virtualTypeId = virtualTypeId;
this.hostTypeId = hostTypeId;
this.useId = useId;
this.bclassId = bclassId;
this.useRelCode = useRelCode;
this.secureAreaId = secureAreaId;
this.secureTierId = secureTierId;
this.cclassName = cclassName;
this.subnetmask = subnetmask;
this.gateway = gateway;
this.vlanId = vlanId;
this.ipStart = ipStart;
this.ipEnd = ipEnd;
this.aclassIp = aclassIp;
this.bclassIp = bclassIp;
this.cclassIp = cclassIp;
this.ipTotalCnt = ipTotalCnt;
this.ipAvailCnt = ipAvailCnt;
this.datacenterId = datacenterId;
this.convergeId = convergeId;
this.isActive = isActive;
this.bclassName = bclassName;
this.datacenterName = datacenterName;
this.ipNum = ipNum;
this.vIpNum = vIpNum;
this.hIpNum = hIpNum;
this.mIpNum = mIpNum;
this.pIpNum = pIpNum;
this.iLoIpNum = iLoIpNum;
this.vmoIpNum = vmoIpNum;
this.priIpNum = priIpNum;
this.fsp1Num = fsp1Num;
this.fsp2Num = fsp2Num;
}
// Property accessors
public String getDatacenterName() {
return datacenterName;
}
public void setDatacenterName(String datacenterName) {
this.datacenterName = datacenterName;
}
public String getCclassId() {
return cclassId;
}
public void setCclassId(String cclassId) {
this.cclassId = cclassId;
}
public String getPlatformId() {
return platformId;
}
public void setPlatformId(String platformId) {
this.platformId = platformId;
}
public String getVirtualTypeId() {
return virtualTypeId;
}
public void setVirtualTypeId(String virtualTypeId) {
this.virtualTypeId = virtualTypeId;
}
public String getHostTypeId() {
return hostTypeId;
}
public void setHostTypeId(String hostTypeId) {
this.hostTypeId = hostTypeId;
}
public String getUseId() {
return useId;
}
public void setUseId(String useId) {
this.useId = useId;
}
public String getBclassId() {
return bclassId;
}
public void setBclassId(String bclassId) {
this.bclassId = bclassId;
}
public String getUseRelCode() {
return useRelCode;
}
public void setUseRelCode(String useRelCode) {
this.useRelCode = useRelCode;
}
public String getSecureAreaId() {
return secureAreaId;
}
public void setSecureAreaId(String secureAreaId) {
this.secureAreaId = secureAreaId;
}
public String getSecureTierId() {
return secureTierId;
}
public void setSecureTierId(String secureTierId) {
this.secureTierId = secureTierId;
}
public String getCclassName() {
return cclassName;
}
public void setCclassName(String cclassName) {
this.cclassName = cclassName;
}
public String getSubnetmask() {
return subnetmask;
}
public void setSubnetmask(String subnetmask) {
this.subnetmask = subnetmask;
}
public String getGateway() {
return gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getVlanId() {
return vlanId;
}
public void setVlanId(String vlanId) {
this.vlanId = vlanId;
}
public Long getIpStart() {
return ipStart;
}
public void setIpStart(Long ipStart) {
this.ipStart = ipStart;
}
public Long getIpEnd() {
return ipEnd;
}
public void setIpEnd(Long ipEnd) {
this.ipEnd = ipEnd;
}
public Long getAclassIp() {
return aclassIp;
}
public void setAclassIp(Long aclassIp) {
this.aclassIp = aclassIp;
}
public Long getBclassIp() {
return bclassIp;
}
public void setBclassIp(Long bclassIp) {
this.bclassIp = bclassIp;
}
public Long getCclassIp() {
return cclassIp;
}
public void setCclassIp(Long cclassIp) {
this.cclassIp = cclassIp;
}
public Long getIpTotalCnt() {
return ipTotalCnt;
}
public void setIpTotalCnt(Long ipTotalCnt) {
this.ipTotalCnt = ipTotalCnt;
}
public Long getIpAvailCnt() {
return ipAvailCnt;
}
public void setIpAvailCnt(Long ipAvailCnt) {
this.ipAvailCnt = ipAvailCnt;
}
public String getDatacenterId() {
return datacenterId;
}
public void setDatacenterId(String datacenterId) {
this.datacenterId = datacenterId;
}
public String getConvergeId() {
return convergeId;
}
public void setConvergeId(String convergeId) {
this.convergeId = convergeId;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getBclassName() {
return bclassName;
}
public void setBclassName(String bclassName) {
this.bclassName = bclassName;
}
public Long getIpNum() {
return ipNum;
}
public void setIpNum(Long ipNum) {
this.ipNum = ipNum;
}
public Long getvIpNum() {
return vIpNum;
}
public void setvIpNum(Long vIpNum) {
this.vIpNum = vIpNum;
}
public Long gethIpNum() {
return hIpNum;
}
public void sethIpNum(Long hIpNum) {
this.hIpNum = hIpNum;
}
public Long getmIpNum() {
return mIpNum;
}
public void setmIpNum(Long mIpNum) {
this.mIpNum = mIpNum;
}
public Long getpIpNum() {
return pIpNum;
}
public void setpIpNum(Long pIpNum) {
this.pIpNum = pIpNum;
}
public Long getiLoIpNum() {
return iLoIpNum;
}
public void setiLoIpNum(Long iLoIpNum) {
this.iLoIpNum = iLoIpNum;
}
public Long getVmoIpNum() {
return vmoIpNum;
}
public void setVmoIpNum(Long vmoIpNum) {
this.vmoIpNum = vmoIpNum;
}
public Long getPriIpNum() {
return priIpNum;
}
public void setPriIpNum(Long priIpNum) {
this.priIpNum = priIpNum;
}
public Long getFsp1Num() {
return fsp1Num;
}
public void setFsp1Num(Long fsp1Num) {
this.fsp1Num = fsp1Num;
}
public Long getFsp2Num() {
return fsp2Num;
}
public void setFsp2Num(Long fsp2Num) {
this.fsp2Num = fsp2Num;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge;
/**
* <a href="http://oj.leetcode.com/problems/longest-palindromic-substring/">Longest Palindromic Substring</a>
* <p/>
* Copyright 2013 LeetCode
* <p/>
* <p/>
* Given a string S, find the longest palindromic substring in S. You may
* assume that the maximum length of S is 1000, and there exists one unique
* longest palindromic substring.
* <p/>
*
* @see <a href=" http://leetcode.com/2011/11/longest-palindromic-substring-part-i.html">Leetcode blog i</a>
* @see <a href=" http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html">Leetcode blog ii</a>
*/
public interface LongestPalindromicSubstring {
String longestPalindrome(String s);
}
|
/**
* @Author: Mahmoud Abdelrahman
* Authentication Exception class is where all AuthenticationException specifications are declared.
*/
package com.easylearn.easylearn.jwt.resource;
public class AuthenticationException extends RuntimeException {
public AuthenticationException(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.example.sypark9646.item02.service;
import com.example.sypark9646.item02.model.NutritionFactsBuilderPattern;
import com.example.sypark9646.item02.model.NutritionFactsConstructorPattern;
import com.example.sypark9646.item02.model.NutritionFactsJavaBeansPattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class NutritionFactsService {
public static boolean printConstructor() {
int random = (int) (Math.random() * 1000);
NutritionFactsConstructorPattern nutritionFacts = new NutritionFactsConstructorPattern(random, random, random, random, random, random);
return (nutritionFacts.getServingSize() == nutritionFacts.getServings() &&
nutritionFacts.getServingSize() == nutritionFacts.getCalories() &&
nutritionFacts.getServingSize() == nutritionFacts.getSodium() &&
nutritionFacts.getServingSize() == nutritionFacts.getFat() &&
nutritionFacts.getServingSize() == nutritionFacts.getCarbohydrate());
}
public static boolean printJavaBeans() {
NutritionFactsJavaBeansPattern nutritionFacts = NutritionFactsJavaBeansPattern.getInstance();
int random = (int) (Math.random() * 1000);
nutritionFacts.setServingSize(random);
nutritionFacts.setServings(random);
nutritionFacts.setCalories(random);
nutritionFacts.setSodium(random);
nutritionFacts.setFat(random);
nutritionFacts.setCarbohydrate(random);
return (nutritionFacts.getServingSize() == nutritionFacts.getServings() &&
nutritionFacts.getServingSize() == nutritionFacts.getCalories() &&
nutritionFacts.getServingSize() == nutritionFacts.getSodium() &&
nutritionFacts.getServingSize() == nutritionFacts.getFat() &&
nutritionFacts.getServingSize() == nutritionFacts.getCarbohydrate());
}
public static boolean printBuilder() {
int random = (int) (Math.random() * 1000);
NutritionFactsBuilderPattern nutritionFacts = new NutritionFactsBuilderPattern.Builder(random, random)
.setCalories(random)
.setSodium(random)
.setFat(random)
.setCarbohydrate(random)
.build();
return (nutritionFacts.getServingSize() == nutritionFacts.getServings() &&
nutritionFacts.getServingSize() == nutritionFacts.getCalories() &&
nutritionFacts.getServingSize() == nutritionFacts.getSodium() &&
nutritionFacts.getServingSize() == nutritionFacts.getFat() &&
nutritionFacts.getServingSize() == nutritionFacts.getCarbohydrate());
}
}
|
/*
* Copyright © 2018 huiyunetwork.com All Rights Reserved.
*
* 感谢您加入辉娱网络,不用多久,您就会升职加薪、当上总经理、出任CEO、迎娶白富美、从此走上人生巅峰
* 除非符合本公司的商业许可协议,否则不得使用或传播此源码,您可以下载许可协议文件:
*
* http://www.huiyunetwork.com/LICENSE
*
* 1、未经许可,任何公司及个人不得以任何方式或理由来修改、使用或传播此源码;
* 2、禁止在本源码或其他相关源码的基础上发展任何派生版本、修改版本或第三方版本;
* 3、无论你对源代码做出任何修改和优化,版权都归辉娱网络所有,我们将保留所有权利;
* 4、凡侵犯辉娱网络相关版权或著作权等知识产权者,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.game.dfa;
import xyz.noark.core.util.MapUtils;
import java.util.Map;
/**
* DFA相似度的文字管理类.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
public class DfaResembleManager {
/**
* 存放那些字母与数字相似的映射,只处理这些是打广告要用这些ID
*/
private static final Map<Integer, Integer> resembleMap = MapUtils.newHashMap(64);
static {
// 数字类型
addResembleWord('0', '⓪', '⓿', '〇', '零', '⁰', '₀');
addResembleWord('1', '①', '➀', '➊', '❶', '⓵', '⒈', '一', '⑴', '㈠', '㊀', '壹', '¹', '₁', 'Ⅰ');
addResembleWord('2', '②', '➁', '➋', '❷', '⓶', '⒉', '二', '⑵', '㈡', '㊁', '贰', '²', '₂', 'Ⅱ');
addResembleWord('3', '③', '➂', '➌', '❸', '⓷', '⒊', '三', '⑶', '㈢', '㊂', '叁', '³', '₃', 'Ⅲ');
addResembleWord('4', '④', '➃', '➍', '❹', '⓸', '⒋', '四', '⑷', '㈣', '㊃', '肆', '⁴', '₄', 'Ⅳ');
addResembleWord('5', '⑤', '➄', '➎', '❺', '⓹', '⒌', '五', '⑸', '㈤', '㊄', '伍', '⁵', '₅', 'Ⅴ');
addResembleWord('6', '⑥', '➅', '➏', '❻', '⓺', '⒍', '六', '⑹', '㈥', '㊅', '陆', '⁶', '₆', 'Ⅵ');
addResembleWord('7', '⑦', '➆', '➐', '❼', '⓻', '⒎', '七', '⑺', '㈦', '㊆', '柒', '⁷', '₇', 'Ⅶ');
addResembleWord('8', '⑧', '➇', '➑', '❽', '⓼', '⒏', '八', '⑻', '㈧', '㊇', '捌', '⁸', '₈', 'Ⅷ');
addResembleWord('9', '⑨', '➈', '➒', '❾', '⓽', '⒐', '九', '⑼', '㈨', '㊈', '玖', '⁹', '₉', 'Ⅸ');
// 字母类型
addResembleWord('a', 'Ⓐ', 'ⓐ', '⒜', 'ₐ');
addResembleWord('b', 'Ⓑ', 'ⓑ', '⒝');
addResembleWord('c', 'Ⓒ', 'ⓒ', '⒞');
addResembleWord('d', 'Ⓓ', 'ⓓ', '⒟');
addResembleWord('e', 'Ⓔ', 'ⓔ', '⒠', 'ₑ');
addResembleWord('f', 'Ⓕ', 'ⓕ', '⒡');
addResembleWord('g', 'Ⓖ', 'ⓖ', '⒢');
addResembleWord('h', 'Ⓗ', 'ⓗ', '⒣', 'ₕ');
addResembleWord('i', 'Ⓘ', 'ⓘ', '⒤');
addResembleWord('j', 'Ⓙ', 'ⓙ', '⒥');
addResembleWord('k', 'Ⓚ', 'ⓚ', '⒦', 'ₖ');
addResembleWord('l', 'Ⓛ', 'ⓛ', '⒧', 'ₗ');
addResembleWord('m', 'Ⓜ', 'ⓜ', '⒨', 'ₘ');
addResembleWord('n', 'Ⓝ', 'ⓝ', '⒩', 'ₙ');
addResembleWord('o', 'Ⓞ', 'ⓞ', '⒪', 'ₒ');
addResembleWord('p', 'Ⓟ', 'ⓟ', '⒫', 'ₚ');
addResembleWord('q', 'Ⓠ', 'ⓠ', '⒬');
addResembleWord('r', 'Ⓡ', 'ⓡ', '⒭');
addResembleWord('s', 'Ⓢ', 'ⓢ', '⒮', 'ₛ');
addResembleWord('t', 'Ⓣ', 'ⓣ', '⒯', 'ₜ');
addResembleWord('u', 'Ⓤ', 'ⓤ', '⒰');
addResembleWord('v', 'Ⓥ', 'ⓥ', '⒱');
addResembleWord('w', 'Ⓦ', 'ⓦ', '⒲');
addResembleWord('x', 'Ⓧ', 'ⓧ', '⒳', 'ₓ');
addResembleWord('y', 'Ⓨ', 'ⓨ', '⒴');
addResembleWord('z', 'Ⓩ', 'ⓩ', '⒵');
}
public static void addResembleWord(char src, char... resembleWordList) {
Integer srcValue = (int) src;
for (char key : resembleWordList) {
resembleMap.put((int) key, srcValue);
}
}
/**
* 获取相似的替换字符
*
* @param src 要替换的字符
* @return 返回此字符对应的原字符,如果没有则返回原本的字符
*/
public static int getResembleWord(int src) {
return resembleMap.getOrDefault(src, src);
}
public static void main(String[] args) {
char[] str1 = "ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ".toCharArray();
char[] str2 = "ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ".toCharArray();
char[] str3 = "⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵".toCharArray();
int index = 0;
for (int ii = 'a'; ii <= 'z'; ii++) {
System.out.print("addResembleWord('" + (char) ii + "'");
System.out.print(", '" + str1[index] + "'");
System.out.print(", '" + str2[index] + "'");
System.out.print(", '" + str3[index] + "'");
System.out.print(");");
System.out.println();
index++;
}
}
}
|
package com.cn.ouyjs.jvmTest;
/**
* @author ouyjs
* @date 2019/7/31 14:59
*/
public class SubTest extends ParentTest {
private static int B = A;
/*
静态变量和静态代码块运行顺序只和代码编写顺序有关.
为了符合思维,先声明再计算的方式 静态变量应该放在前面
*/
public static void main(String[] args) {
System.out.println(SubTest.B);
}
}
|
package cn.bdqn.stumanage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MgrSurveyServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MgrSurveyServiceApplication.class, args);
}
}
|
package thundercode.entrenamentFinal;
import java.io.IOException;
import java.util.ArrayList;
//https://github.com/sweed33/AceptaElReto/blob/master/470%20Montando%20Semaforos
public class SP09 {
static ArrayList<Character> a = new ArrayList<>();
static int can;
public static void main(String[] args) throws IOException {
int n = System.in.read();
int tot = 0;
while(n!=-1){
tot = 0;
a.clear();
can = 0;
while (n >= 65 && n <= 122) {
switch (n) {
case 82:
a.add('R');
can = 1;
break;
case 65:
a.add('A');
switch (can) {
case 2:
can = 0;
break;
case 1:
can = 2;
break;
default:
can = 0;
break;
}
break;
default:
a.add('V');
if (can == 2) {
can = 0;
tot++;
a.remove(a.size() - 1);
a.remove(a.size() - 1);
a.remove(a.size() - 1);
mirarAnteriores();
} else {
can = 0;
}
break;
}
n = System.in.read();
if (n == 13) {
System.in.read();
}
}
System.out.println(tot);
n = System.in.read();
};
}
private static void mirarAnteriores() {
if (a.size() >= 1) {
if (a.get(a.size() - 1) == 'R') {
can = 1;
}
}
if (a.size() >= 2) {
if (a.get(a.size() - 2) == 'R' && a.get(a.size() - 1) == 'A') {
can = 2;
}
}
}
}
/*import java.util.Scanner;
public class SP09 {
static final Scanner s = new Scanner(System.in);
public static void main(String[] args) {
int max, n, temp;
int n1, n2;
boolean valid;
while (s.hasNext()) {
max = s.nextInt();
n = s.nextInt();
valid = true;
temp = 0;
n1 = s.nextInt();
for (int i = 1; i < n; i++) {
n2 = s.nextInt();
if (n2 > n1) {
temp += Math.abs(n1 - n2);
} else temp = 0;
if (temp > max) {
valid = false; s.nextLine();
break;
}
n1 = n2;
}
System.out.println( (valid) ? "APTA" : "NO APTA" );
}
}
}*/ |
package com.youma;
/**
* A Camel Application
*
* @author czq
*/
public class MainApp {
/**
* A main() so we can easily run these routing rules in our IDE
*/
public static void main(String... args) throws Exception {
Circle c = new Circle(1);
c.new Draw().drawSahpe();
System.out.println("Unique ID: " + c.generateUniqueKey());
Animal animal = new Cat();
Animal animal1 = new Dog();
Cat cat = null;
System.out.println(String.format("是%s",animal instanceof Animal));
if (animal instanceof Animal) {
cat = (Cat) animal;
}
animal.run();
animal1.run();
System.out.println(Animal.name);
System.out.println(cat.name);
// Main main = new Main();
// main.addRouteBuilder(new MyRouteBuilder());
// main.run(args);
}
}
|
package ALIXAR.U5_HERENCIA.T1.A3;
import ALIXAR.U5_HERENCIA.T1.A1.horas;
public class HoraExacta extends horas {
// Atributos
public int segundos;
// Metodos
public HoraExacta (int hora, int minutos, int segundos) {
super(hora, minutos);
this.segundos=0;
setSegundos(segundos);
}
public void setSegundos(int segundos) {
if (segundos >= 0 && segundos <= 59) {
this.segundos=segundos;
}
}
@Override
public void inc() {
segundos++;
if (segundos > 59) {
segundos = 0;
super.inc();
}
}
@Override
public String toString() {
String reloj = "";
String cadena=String.valueOf(hora);
String cadena2=String.valueOf(minutos);
String cadena3=String.valueOf(segundos);
reloj = cadena;
reloj += ":" + cadena2;
reloj += ":" + cadena3;
return reloj;
}
} |
package com.example.parstagram;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class LaunchScreen extends AppCompatActivity {
private static int SPLASH_TIME = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_screen);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(LaunchScreen.this, LoginActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME);
//Reference : https://medium.com/@shishirthedev/the-right-way-to-implement-a-splash-screen-in-android-acae0e52949a
}
} |
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.authn.remote;
import pl.edu.icm.unity.server.authn.SandboxAuthnContext;
/**
* Stores full information on the remote sandboxed authentication.
* Either {@link RemotelyAuthenticatedContext} is
* provided (successful authN) or exception with unprocessed {@link RemotelyAuthenticatedInput}.
* The most of the information is in authnContext, which is enriched with logs and potential error.
* User should be careful when using the authnResult. It may happen that many of the
* fields are not initialized in case of authentication failure.
*
* @author K. Benedyczak
*/
public class RemoteSandboxAuthnContext implements SandboxAuthnContext
{
private RemotelyAuthenticatedContext authnContext;
private Exception authnException;
private String logs;
public RemoteSandboxAuthnContext(RemotelyAuthenticatedContext authnResult, String logs)
{
this.authnContext = authnResult;
this.logs = logs;
}
public RemoteSandboxAuthnContext(Exception authnException, String logs,
RemotelyAuthenticatedInput input)
{
this.authnException = authnException;
this.logs = logs;
if (input != null)
{
authnContext = new RemotelyAuthenticatedContext(input.getIdpName(), null);
authnContext.setAuthnInput(input);
}
}
public RemotelyAuthenticatedContext getAuthnContext()
{
return authnContext;
}
public Exception getAuthnException()
{
return authnException;
}
public String getLogs()
{
return logs;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.stomp;
import org.junit.jupiter.api.Disabled;
import org.springframework.messaging.tcp.TcpOperations;
import org.springframework.messaging.tcp.reactor.ReactorNetty2TcpClient;
/**
* Integration tests for {@link StompBrokerRelayMessageHandler} running against
* ActiveMQ with {@link ReactorNetty2TcpClient}.
*
* @author Rossen Stoyanchev
*/
@Disabled("gh-29287 :: Disabled because they fail too frequently")
public class ReactorNetty2StompBrokerRelayIntegrationTests extends AbstractStompBrokerRelayIntegrationTests {
@Override
protected TcpOperations<byte[]> initTcpClient(int port) {
return new ReactorNetty2TcpClient<>("127.0.0.1", port, new StompTcpMessageCodec());
}
}
|
package com.movietime.oauth2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import java.util.Collection;
/**
* Created by Attila on 2015-05-06.
* Indicates a class can process a specific Authentication implementation.
*/
@Component
public class MyUserAuthenticationProvider implements AuthenticationProvider {
@Autowired
private MyAuthenticationProxy myAuthenticationProxy;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
boolean result = myAuthenticationProxy.isValidUser(
authentication.getPrincipal().toString(), authentication.getCredentials().toString());
if (result) {
MyUserDetails userDetails = myAuthenticationProxy.detailsOfUser(authentication.getPrincipal().toString());
Collection<? extends GrantedAuthority> grantedAuthorities = userDetails.getAuthorities();
MyUserAuthenticationToken auth = new MyUserAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(), grantedAuthorities);
return auth;
} else {
throw new BadCredentialsException("Bad user credentials.");
}
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
|
package com.esum.framework.security.auth;
public class HTTPAuthInfo {
private String authInfoId = null;
private String id = null;
private String password = null;
private boolean useVirtualID = false;
private String privatePKIAlias = null;
private String partnerPKIAlias = null;
public HTTPAuthInfo(String authInfoId, String id, String password) {
this.authInfoId = authInfoId;
this.id = id;
this.password = password;
}
public HTTPAuthInfo(String authInfoId, String id, String privatePKIAlias, String partnerPKIAlias) {
this.authInfoId = authInfoId;
this.id = id;
this.useVirtualID = true;
this.privatePKIAlias = privatePKIAlias;
this.partnerPKIAlias = partnerPKIAlias;
}
public String getAuthInfoId() {
return authInfoId;
}
public void setAuthInfoId(String authInfoId) {
this.authInfoId = authInfoId;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getPartnerPKIAlias() {
return partnerPKIAlias;
}
public void setPartnerPKIAlias(String partnerPKIAlias) {
this.partnerPKIAlias = partnerPKIAlias;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrivatePKIAlias() {
return privatePKIAlias;
}
public void setPrivatePKIAlias(String privatePKIAlias) {
this.privatePKIAlias = privatePKIAlias;
}
/**
* KCAC.TS.SIVID - (http://www.kisa.or.kr)
*
* @return boolean
*/
public boolean isUseVirtualID() {
return this.useVirtualID;
}
/**
* KCAC.TS.SIVID - (http://www.kisa.or.kr)
*
* @param useVirtualID
*/
public void setUseVirtualID(boolean useVirtualID) {
this.useVirtualID = useVirtualID;
}
}
|
/*
* 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 DAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import util.ConexaoBD;
/**
*
* @author azm
*/
public class SurveyDAO
{
private Connection conexao;
public SurveyDAO () throws ClassNotFoundException , SQLException
{
this.conexao = new ConexaoBD ().getConnectio ();
}
public void updateTotalSurvey (int votes) throws SQLException
{
String sql = "UPDATE surveyResults SET votes = votes + 1 WHERE survey_pk " + votes;
try (PreparedStatement pst = conexao.prepareStatement (sql))
{
pst.executeUpdate ();
pst.close ();
}
}
public int listTotalSurvey () throws SQLException
{
String sql = "SELECT SUM(votes) FROM surveyResults";
int total = 0;
try (PreparedStatement pst = conexao.prepareStatement (sql))
{
ResultSet rs = pst.executeQuery ();
rs.next ();
return total = rs.getInt (1);
}
}
public int[] listResultsSurvey () throws SQLException
{
int totalSurvey = listTotalSurvey ();
int votes = 0, count = 0;
int resultSurvey[] = null;
String sql = "SELECT surveyOption, votes, survey_pk FROM surveyResults ORDER BY survey_pk";
try (PreparedStatement pst = conexao.prepareStatement (sql))
{
ResultSet rs = pst.executeQuery ();
while (rs.next ())
{
rs.getString (1);
votes = rs.getInt (2);
resultSurvey[count] = votes / totalSurvey * 100;
count++;
}
return resultSurvey;
}
}
}
|
package com.wangcheng.lambda;
/**
* 只要满足FunctionalInterface的条件,即使没有@FunctionalInterface注解,编译器会自动将其作为函数式接口FunctionalInterface
*
* @author WangCheng
* create in 2020-06-23 14:31
*/
@FunctionalInterface
public interface FunctionalInterfaceTest {
void test();
}
|
package com.android.abhishek.wirelessdisplay;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
public class ChooseActionAct extends AppCompatActivity {
LinearLayout linearLayout;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_action);
Button type = findViewById(R.id.keyPad);
Button pattern = findViewById(R.id.pattern);
linearLayout = findViewById(R.id.chooseLayout);
progressBar = findViewById(R.id.progressBar);
type.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ChooseActionAct.this,"Please Wait ...",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ChooseActionAct.this,HomePage.class);
intent.putExtra("EXTRA",1);
startActivity(intent);
}
});
pattern.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ChooseActionAct.this,"Please Wait ...",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ChooseActionAct.this,HomePage.class);
intent.putExtra("EXTRA",2);
startActivity(intent);
}
});
}
}
|
package com.ihoment.photo.editor;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
import com.adobe.creativesdk.aviary.utils.AdobeImageEditorIntentConfigurationValidator;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
static final String TAG = MainActivity.class.getName();
static final int REQUEST_CODE_FOR_EDIT = 1;
// static final String BASE_DIR = "/storage/emulated/0/baidu/flyflow/downloads";
static final String BASE_DIR = "/storage/emulated/0";
private ImageView editBeforeImg;
private ImageView editAfterImg;
private List<String> imgS;
private List<String> imgFileS;
private ArrayList<String> data_list;
private Uri uri;
private File output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*检测修改是否有效*/
if (BuildConfig.DEBUG) {
try {
AdobeImageEditorIntentConfigurationValidator.validateConfiguration(this);
} catch (Throwable e) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(e.getMessage()).show();
}
}
/*启动服务;提高加载图片到编辑页面到效率*/
Intent cdsIntent = AdobeImageIntent.createCdsInitIntent(getBaseContext(), "CDS");
startService(cdsIntent);
editBeforeImg = (ImageView) findViewById(R.id.edit_before_img);
editAfterImg = (ImageView) findViewById(R.id.edit_after_img);
// findImgUrl();
initSpinner();
}
private void initSpinner() {
Spinner spinner = (Spinner) findViewById(R.id.img_choose);
data_list = initData();
//适配器
ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
//设置样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
private ArrayList<String> initData() {
ArrayList<String> data = new ArrayList<>();
File dir = new File(BASE_DIR);
if (dir.exists() && dir.isDirectory()) {
String[] list = dir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String nameIgnoreCase = name.toLowerCase();
return nameIgnoreCase.endsWith(".jpg") || nameIgnoreCase.endsWith(".jpeg") || nameIgnoreCase.endsWith(".png");
}
});
List<String> asList = Arrays.asList(list);
data.addAll(asList);
}
return data;
}
private void findImgUrl() {
imgS = new ArrayList<>();
imgFileS = new ArrayList<>();
Cursor query = null;
try {
query = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (query == null) {
Log.w(TAG, "query==null");
return;
}
while (query.moveToNext()) {
String name = query.getString(query.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
byte[] data = query.getBlob(query.getColumnIndex(MediaStore.Images.Media.DATA));
String fileName = new String(data, 0, data.length - 1);
// Log.w(TAG, "imgName = " + name);
Log.w(TAG, "imgFileName = " + fileName);
imgS.add(name);
imgFileS.add(fileName);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (query != null)
query.close();
}
}
public void btnClick(View view) {
// if (imgS.isEmpty() || imgFileS.isEmpty()) return;
// String imgName = imgS.get(0);
// Uri uri = Uri.parse("content://media/external/images/media/" + imgName);
// String imgFileName = imgFileS.get(0);
// String imgFileName = "/storage/emulated/0/DCIM/Camera/IMG_20170402_143853.jpg";
// String imgFileName = "/storage/emulated/0/baidu/flyflow/downloads/1493807499407.jpg";
// Uri uri = Uri.parse("file://" + imgFileName);
// Log.w(TAG, "uri = " + uri);
// editBeforeImg.setImageURI(uri);
if (uri == null) {
Toast.makeText(this, "未选中编辑的图片", Toast.LENGTH_SHORT).show();
return;
}
startEditAC(uri);
}
private void startEditAC(Uri uri) {
File outDir = new File(Environment.getExternalStorageDirectory(), "AdobeEditorImgDir");
if ((outDir.exists() && outDir.isDirectory()) || outDir.mkdirs()) {
output = new File(outDir, UUID.randomUUID().toString() + ".png");
Intent build = new AdobeImageIntent.Builder(this)
.setData(uri)
.withOutputFormat(Bitmap.CompressFormat.PNG)
.withOutput(output)
// .withToolList(new ToolsFactory.Tools[]{SHARPNESS})
.build();
startActivityForResult(build, REQUEST_CODE_FOR_EDIT);
} else {
Toast.makeText(this, "OutDir is not exists!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.w(TAG, "requestCode = " + requestCode + " ;resultCode =" + resultCode);
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_FOR_EDIT) {
Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
Log.w(TAG, "editedImageUri = " + editedImageUri);
// editAfterImg.setImageURI(editedImageUri);
editAfterImg.setImageURI(Uri.fromFile(output));
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String file = "file://" + BASE_DIR + "/" + data_list.get(position);
Log.w(TAG, "ImgFile = " + file);
uri = Uri.parse(file);
editBeforeImg.setImageURI(uri);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
String file = "file://" + BASE_DIR + "/" + data_list.get(0);
Log.w(TAG, "ImgFile = " + file);
uri = Uri.parse(file);
editBeforeImg.setImageURI(uri);
}
}
|
package de.varylab.discreteconformal.unwrapper.quasiisothermic;
import static de.jtem.halfedge.util.HalfEdgeUtils.isBoundaryVertex;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan;
import static java.lang.Math.log;
import static java.lang.Math.sin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.jreality.math.Matrix;
import de.jreality.math.MatrixBuilder;
import de.jreality.math.Rn;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Node;
import de.jtem.halfedge.Vertex;
import de.jtem.halfedge.util.HalfEdgeUtils;
import de.jtem.halfedgetools.adapter.AbstractAdapter;
import de.jtem.halfedgetools.adapter.Adapter;
import de.jtem.halfedgetools.adapter.AdapterSet;
import de.jtem.halfedgetools.adapter.type.CurvatureFieldMax;
import de.jtem.halfedgetools.adapter.type.CurvatureFieldMin;
import de.jtem.halfedgetools.adapter.type.Normal;
import de.jtem.halfedgetools.adapter.type.Position;
import de.jtem.halfedgetools.adapter.type.TexturePosition;
import de.jtem.halfedgetools.adapter.type.generic.BaryCenter4d;
import de.jtem.halfedgetools.adapter.type.generic.EdgeVector;
import de.jtem.halfedgetools.adapter.type.generic.TexturePosition4d;
import de.jtem.halfedgetools.algorithm.topology.TopologyAlgorithms;
import de.jtem.halfedgetools.functional.Functional;
import de.jtem.halfedgetools.plugin.algorithm.vectorfield.EdgeVectorFieldMaxAdapter;
import de.jtem.jpetsc.InsertMode;
import de.jtem.jpetsc.KSP;
import de.jtem.jpetsc.Mat;
import de.jtem.jpetsc.MatStructure;
import de.jtem.jpetsc.PETSc;
import de.jtem.jpetsc.Vec;
import de.jtem.jtao.Tao;
import de.varylab.discreteconformal.heds.CoEdge;
import de.varylab.discreteconformal.heds.CoHDS;
import de.varylab.discreteconformal.heds.CoVertex;
import de.varylab.discreteconformal.heds.adapter.types.OppositeAngle;
import de.varylab.discreteconformal.unwrapper.ConesUtility;
public class QuasiisothermicUtility {
static {
Tao.Initialize();
}
@OppositeAngle
public static class OppositeAnglesAdapter <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> extends AbstractAdapter<Double> {
private Map<E, Double>
angleMap = new HashMap<E, Double>();
public OppositeAnglesAdapter(Map<E, Double> betaMap) {
super(Double.class, true, true);
this.angleMap = betaMap;
}
@SuppressWarnings("unlikely-arg-type")
@Override
public <
VV extends Vertex<VV, EE, FF>,
EE extends Edge<VV, EE, FF>,
FF extends Face<VV, EE, FF>
> Double getE(EE e, AdapterSet a) {
if (!angleMap.containsKey(e)) {
return 0.0;
}
return angleMap.get(e);
}
@SuppressWarnings("unchecked")
@Override
public <
VV extends Vertex<VV, EE, FF>,
EE extends Edge<VV, EE, FF>,
FF extends Face<VV, EE, FF>
> void setE(EE e, Double value, AdapterSet a) {
angleMap.put((E)e, value);
}
@Override
public <N extends Node<?, ?, ?>> boolean canAccept(Class<N> nodeClass) {
return CoEdge.class.isAssignableFrom(nodeClass);
}
}
/**
* Calculate the angle between the edges that belong to alpha1 and alpha2.
* @param alpha1
* @param alpha2
* @param alpha3
* @return
*/
public static double calculateBeta(double alpha1, double alpha2, double alpha3) {
alpha1 = QuasiisothermicUtility.normalizeAngle(alpha1);
alpha2 = QuasiisothermicUtility.normalizeAngle(alpha2);
alpha3 = QuasiisothermicUtility.normalizeAngle(alpha3);
double beta = abs(alpha2 - alpha1);
if ((alpha3 > alpha2 && alpha3 > alpha1) || (alpha3 < alpha2 && alpha3 < alpha1)) {
return beta;
} else {
return PI - beta;
}
}
public static double normalizeAngle(double a) {
a %= PI;
if (a > PI/2) {
return a - PI;
} else if (a < -PI/2) {
return PI + a;
} else {
return a;
}
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> void subdivideFaceSingularities(HDS hds, Map<E, Double> alpha, AdapterSet a) {
Set<F> faces = new HashSet<F>(hds.getFaces());
for (F f : faces) {
double index = getSingularityIndexF(f, alpha, a);
if (Math.abs(index) < 0.25) continue;
// calulate alpha rotations for edges
Map<E, Double> alphaRot = new HashMap<E, Double>();
for (E e : HalfEdgeUtils.boundaryEdges(f)) {
double ar = alphaRotationE(e, alpha, a);
alphaRot.put(e, ar);
}
// subdivide and interpolate according to the transport
double[] p = a.getD(BaryCenter4d.class, f);
System.out.print("subdividing face " + f);
V v = TopologyAlgorithms.splitFace(f);
System.out.println("with index " + index + " -> " + v);
a.set(Position.class, v, p);
for (E e : HalfEdgeUtils.incomingEdges(v)) {
E ep = e.getPreviousEdge();
double ar = alphaRot.get(ep);
double a1 = alpha.get(e.getPreviousEdge());
double newAlpha = a1 + ar/2;
alpha.put(e, newAlpha);
alpha.put(e.getOppositeEdge(), newAlpha);
}
}
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double getSingularityIndexF(F f, Map<E, Double> alpha, AdapterSet a) {
return Math.round(2 * alphaRotationF(f, alpha, a) / (2.0 * Math.PI)) / 2.0;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double getSingularityIndexV(V v, Map<E, Double> alpha, AdapterSet a) {
return Math.round(2 * alphaRotationV(v, alpha, a) / (2.0 * Math.PI)) / 2.0;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> int getSingularityIndexFromAdapterSet(F f, AdapterSet a) {
return (int)(Math.round(2 * alphaRotationFromAdapterSet(f, a) / (2.0 * Math.PI)) / 2.0);
}
/**
* Returns the angle between v1 and v2 in the range ]-pi/2, pi/2].
* Where the sign is the sign of the determinant |N v1 v2|.
* @param v1
* @param v2
* @param N
* @return
*/
public static double getSignedAngle(double[] N, double[] v1, double[] v2) {
double[][] T = {N, v1, v2};
double sign = Math.signum(Rn.determinant(T));
double alpha = Rn.euclideanAngle(v1, v2);
if (alpha > PI/2) {
alpha = -(PI - alpha);
}
return sign * alpha;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<E, Integer> createSolverEdgeIndexMap(HDS hds, boolean excludeBoundary) {
Map<E, Integer> result = new HashMap<E, Integer>();
Integer i = 0;
for (E e : hds.getPositiveEdges()) {
if (((isBoundaryVertex(e.getStartVertex()) ||
isBoundaryVertex(e.getTargetVertex())) && excludeBoundary)
) {
result.put(e, -1);
result.put(e.getOppositeEdge(), -1);
} else {
result.put(e, i);
result.put(e.getOppositeEdge(), i);
i++;
}
}
return result;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<V, Integer> createSolverVertexIndexMap(HDS hds) {
Map<V, Integer> result = new HashMap<V, Integer>();
Integer i = 0;
for (V v : hds.getVertices()) {
if (isBoundaryVertex(v)) {
result.put(v, -1);
} else {
result.put(v, i);
i++;
}
}
return result;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> double calculateAngleSumFromAlphas(V v, Map<E, Double> alphaMap) {
double sum = 0.0;
for (E e : HalfEdgeUtils.incomingEdges(v)) {
sum += QuasiisothermicUtility.getOppositeBeta(e.getPreviousEdge(), alphaMap);
}
return sum;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> double calculateAngleSumFromBetas(V v, Map<E, Double> betaMap) {
double sum = 0.0;
for (E e : HalfEdgeUtils.incomingEdges(v)) {
if (e.getLeftFace() == null) {
continue;
}
sum += betaMap.get(e.getPreviousEdge());
}
return sum;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> int[] getPETScNonZeros(HDS hds, Functional<V, E, F> fun){
int [][] sparseStucture = fun.getNonZeroPattern(hds);
int [] nnz = new int[sparseStucture.length];
for(int i = 0; i < nnz.length; i++){
nnz[i] = sparseStucture[i].length;
}
return nnz;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<E, Double> calculateBetasFromAlphas(HDS hds, Map<E, Double> alphaMap) {
Map<E, Double> betaMap = new HashMap<E, Double>();
for (E e : hds.getEdges()) {
if (e.getLeftFace() != null) {
double a1 = alphaMap.get(e);
double a2 = alphaMap.get(e.getNextEdge());
double a3 = alphaMap.get(e.getPreviousEdge());
double beta = angleOrientation(a2,a3,a1)*calculateBeta(a2, a3, a1);
betaMap.put(e, beta);
}
}
return betaMap;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> void checkTriangleAngles(HDS hds, Map<E, Double> betaMap) {
double EPS = 1E-5;
for (F f : hds.getFaces()) {
double sum = 0.0;
for (E e : HalfEdgeUtils.boundaryEdges(f)) {
double beta = betaMap.get(e);
if (beta < 0) {
throw new RuntimeException("Negative angle at edge " + e + ": " + beta);
}
sum += beta;
}
if (Math.abs(sum - PI) > EPS) {
throw new RuntimeException("Angle sum at " + f + ": " + sum);
}
}
for (V v : hds.getVertices()) {
if (HalfEdgeUtils.isBoundaryVertex(v)) {
continue;
}
double sum = 0.0;
for (E e : HalfEdgeUtils.incomingEdges(v)) {
double beta = betaMap.get(e.getPreviousEdge());
sum += beta;
}
if (Math.abs(sum - 2*PI) > EPS) {
throw new RuntimeException("Angle sum at " + v + ": " + sum);
}
}
}
/**
* invokes the Delaunay flip algorithm on hds and modifies the angles in betaMap
* accordingly. The local Delaunay condition is derived from the opposite angles
* of an edge.
* @param hds
* @param betaMap
*/
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> void createDelaunayAngleSystem(HDS hds, Map<E, Double> betaMap) {
OppositeAnglesAdapter<V, E, F> anglesAdapter = new OppositeAnglesAdapter<V, E, F>(betaMap);
AdapterSet a = new AdapterSet(anglesAdapter);
QuasiisothermicDelaunay.constructDelaunay(hds, a);
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<E, Double> calculateThetasFromBetas(HDS hds, Map<E, Double> betaMap) {
Map<E, Double> thetas = new HashMap<E, Double>();
for (E e : hds.getPositiveEdges()) {
double theta = PI;
if (e.getRightFace() != null) {
double betaRight = betaMap.get(e.getOppositeEdge());
theta -= betaRight;
}
if (e.getLeftFace() != null) {
double betaLeft = betaMap.get(e);
theta -= betaLeft;
}
thetas.put(e, theta);
thetas.put(e.getOppositeEdge(), theta);
}
return thetas;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<F, Double> calculatePhisFromBetas(HDS hds, Map<E, Double> betaMap) {
Map<F, Double> phiMap = new HashMap<F, Double>();
for (F f : hds.getFaces()) {
phiMap.put(f, 2*PI);
}
return phiMap;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> double getOppositeBeta(E e, Map<E, Double> alphaMap) {
Double eA = alphaMap.get(e);
if (eA == null) {
eA = alphaMap.get(e.getOppositeEdge());
}
Double eNextA = alphaMap.get(e.getNextEdge());
if (eNextA == null) {
eNextA = alphaMap.get(e.getOppositeEdge().getNextEdge());
}
Double ePrevA = alphaMap.get(e.getPreviousEdge());
if (ePrevA == null) {
ePrevA = alphaMap.get(e.getOppositeEdge().getPreviousEdge());
}
return calculateBeta(eNextA, ePrevA, eA);
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> void layoutEars(HDS hds, Map<E, Double> alphaMap) {
// List<E> earEdges = findEarsEdge(hds);
// for (E ear : earEdges) {
// E base = ear.getPreviousEdge();
// V v = ear.getTargetVertex();
// double[] p2 = base.getTargetVertex().T;
// double[] p1 = base.getStartVertex().T;
// double lBase = Pn.distanceBetween(p2, p1, Pn.EUCLIDEAN);
// double lNew = getEdgeLength(ear, lBase, alphaMap);
//
// }
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> void alignLayout(HDS hds, Map<E, Double> alphaMap, AdapterSet a) {
List<E> b = HalfEdgeUtils.boundaryEdges(hds);
List<E> earEdges = findEarsEdge(hds);
for (E e : earEdges) {
b.remove(e);
b.remove(e.getNextEdge());
}
E refEdge = hds.getEdge(0);
if (b.size() != 0) {
refEdge = b.get(0);
}
double alpha = alphaMap.get(refEdge);
double[] s = a.getD(TexturePosition4d.class, refEdge.getStartVertex());
double[] t = a.getD(TexturePosition4d.class, refEdge.getTargetVertex());
double angle = atan((s[1] - t[1]) / (s[0] - t[0]));
double difAngle = alpha - angle;
MatrixBuilder mb = MatrixBuilder.euclidean();
mb.rotate(difAngle, new double[] {0,0,1});
Matrix T = mb.getMatrix();
for (V v : hds.getVertices()) {
double[] vt = a.getD(TexturePosition4d.class, v);
T.transformVector(vt);
a.set(TexturePosition.class, v, vt);
}
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> List<E> findEarsEdge(HDS hds){
ArrayList<E> result = new ArrayList<E>();
for (E e : hds.getEdges()){
if (!HalfEdgeUtils.isInteriorEdge(e) && e.getLeftFace() == null) {
if (e.getRightFace() == e.getNextEdge().getRightFace()) {
result.add(e);
}
}
}
return result;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> double getEdgeLength(E e, double prevEdgeLength, Map<E, Double> alphaMap) {
double ea = getOppositeBeta(e, alphaMap);
double prevAngle = getOppositeBeta(e.getPreviousEdge(), alphaMap);
return prevEdgeLength * sin(ea) / sin(prevAngle);
}
/**
* Cuts from cone points (beta sum != 2PI) to the boundary of a mesh
* @param hds
* @param betaMap
*/
public static void cutConesToBoundary(CoHDS hds, Map<CoEdge, Double> betaMap) {
Set<CoVertex> innerVerts = new HashSet<CoVertex>(hds.getVertices());
innerVerts.removeAll(HalfEdgeUtils.boundaryVertices(hds));
for (CoVertex v : innerVerts) {
double sum = calculateAngleSumFromBetas(v, betaMap);
if (abs(abs(sum) - 2*PI) > Math.PI/4) {
System.out.println("angle sum " + sum);
int index = (int)Math.round(sum / PI);
v.setTheta(index * PI);
if((index % 2) != 0) {
System.out.println("singularity: " + v + ", " + index + " pi");
}
} else {
v.setTheta(2 * PI);
}
}
ConesUtility.cutMesh(hds);
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<E, Double> calculateAlphasFromCurvature(AdapterSet a, HDS hds) {
Map<E, Double> alphaMap = new HashMap<E, Double>();
for(E e : hds.getEdges()) {
double[] N = a.getD(Normal.class, e);
double[] Kmin = a.getD(CurvatureFieldMin.class, e);
double[] E = a.getD(EdgeVector.class, e);
try {
double ae = getSignedAngle(N, Kmin, E);
alphaMap.put(e, ae);
alphaMap.put(e.getOppositeEdge(), ae);
} catch (Exception e2) {
System.out.println("check");
}
}
return alphaMap;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double calculateAlpha(E e, AdapterSet a) {
double[] N = a.getD(Normal.class, e);
double[] Kmin = a.getD(CurvatureFieldMax.class, e);
double[] E = a.getD(EdgeVector.class, e);
return QuasiisothermicUtility.getSignedAngle(N, Kmin, E);
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<F, Double> calculateOrientationFromAlphas(HDS hds, Map<E, Double> alphaMap) {
Map<F, Double> orientationMap = new HashMap<F, Double>(hds.numFaces());
for(F f : hds.getFaces()) {
E e = f.getBoundaryEdge();
double orientation = angleOrientation(
alphaMap.get(e),
alphaMap.get(e.getNextEdge()),
alphaMap.get(e.getPreviousEdge())
);
orientationMap.put(f, orientation);
}
return orientationMap;
}
public static double angleOrientation(double alpha1, double alpha2, double alpha3) {
return (
((alpha1 < alpha2) && (alpha2 < alpha3)) ||
((alpha2 < alpha3) && (alpha3 < alpha1)) ||
((alpha3 < alpha1) && (alpha1 < alpha2))
)? -1.0 : 1.0;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaOrientationFromAdapterSet(F f, AdapterSet a) {
E e = f.getBoundaryEdge();
double alpha1 = calculateAlpha(e,a);
double alpha2 = calculateAlpha(e.getNextEdge(),a);
double alpha3 = calculateAlpha(e.getPreviousEdge(),a);
return angleOrientation(alpha1, alpha2, alpha3);
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationFromAdapterSet(F f, AdapterSet a) {
E se = f.getBoundaryEdge();
E e = se;
double rotation = 0.0;
do {
rotation += alphaRotationFromAdapterSet(e,a);
e = e.getNextEdge();
} while(e != se);
return rotation;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationFromAdapterSet(V v, AdapterSet a) {
E se = v.getIncomingEdge();
E e = se;
double rotation = 0.0;
do {
rotation += alphaRotationFromAdapterSet(e,a);
e = e.getNextEdge().getOppositeEdge();
} while(e != se);
return rotation;
}
private static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationFromAdapterSet(E e, AdapterSet a) {
double alpha1 = calculateAlpha(e,a);
double[] edge1 = a.getD(EdgeVector.class,e);
double alpha2 = calculateAlpha(e.getNextEdge(),a);
double[] edge2 = a.getD(EdgeVector.class,e.getNextEdge());
double gamma = Rn.euclideanAngle(edge1, edge2);
double rotation = normalizeAngle(gamma + alpha1 -alpha2 - Math.PI);
return rotation;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationF(F f, Map<E, Double> alpha, AdapterSet a) {
E se = f.getBoundaryEdge();
E e = se;
double rotation = 0.0;
do {
rotation += alphaRotationE(e, alpha, a);
e = e.getNextEdge();
} while(e != se);
return rotation;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationV(V v, Map<E, Double> alpha, AdapterSet a) {
E se = v.getIncomingEdge();
E e = se;
double rotation = 0.0;
do {
rotation += alphaRotationE(e, alpha, a);
e = e.getNextEdge().getOppositeEdge();
} while(e != se);
return rotation;
}
private static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> double alphaRotationE(E e, Map<E, Double> alpha, AdapterSet a) {
double alpha1 = alpha.get(e);
double[] edge1 = a.getD(EdgeVector.class,e);
double alpha2 = alpha.get(e.getNextEdge());
double[] edge2 = a.getD(EdgeVector.class,e.getNextEdge());
double gamma = Rn.euclideanAngle(edge1, edge2);
double rotation = normalizeAngle(gamma + alpha1 -alpha2 - Math.PI);
return rotation;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<V, Double> calculateQuasiconformalFactors(HDS hds, Map<E, Double> edgeLengths, Map<E, Double> texLengths) {
Map<E, Integer> eIndexMap = createSolverEdgeIndexMap(hds, false);
int m = hds.numEdges() / 2;
Vec u = new Vec(m);
Vec l = new Vec(m);
Mat A = Mat.createSeqAIJ(m, m, 2, null);
for (E e : hds.getPositiveEdges()) {
int eIndex = eIndexMap.get(e);
int i = e.getStartVertex().getIndex();
int j = e.getTargetVertex().getIndex();
double l1 = 2*log(edgeLengths.get(e));
double l2 = 2*log(texLengths.get(e));
l.setValue(eIndex, l2 - l1, InsertMode.INSERT_VALUES);
A.setValue(eIndex, i, 1.0, InsertMode.INSERT_VALUES);
A.setValue(eIndex, j, 1.0, InsertMode.INSERT_VALUES);
}
A.assemble();
KSP ksp = KSP.create();
ksp.setOptionsPrefix("qcf_");
PETSc.optionsSetValue("-qcf_ksp_type", "lsqr");
ksp.setFromOptions();
// ksp.setTolerances(1E-8, PETSc.PETSC_DEFAULT, PETSc.PETSC_DEFAULT, 25);
ksp.setOperators(A, A, MatStructure.SAME_NONZERO_PATTERN);
ksp.solve(l, u);
System.out.println("ksp residual: " + ksp.getResidualNorm());
Map<V, Double> result = new HashMap<V, Double>();
for (V v : hds.getVertices()) {
double ui = u.getValue(v.getIndex());
result.put(v, ui);
}
return result;
}
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Adapter<double[]> createAlphaField(HDS hds, Map<E, Double> alpha, AdapterSet a, String name) {
Map<E, double[]> vMap = new HashMap<E, double[]>();
for (E e : hds.getPositiveEdges()) {
if (!alpha.containsKey(e)) continue;
double al = alpha.get(e);
double[] ev = a.getD(EdgeVector.class, e);
Rn.normalize(ev, ev);
double[] n = a.getD(Normal.class, e);
double[] vp = Rn.crossProduct(null, ev, n);
Rn.times(ev, Math.cos(al), ev);
Rn.times(vp, Math.sin(al), vp);
double[] vec = Rn.add(null, ev, vp);
vMap.put(e, vec);
vMap.put(e.getOppositeEdge(), vec);
}
EdgeVectorFieldMaxAdapter aMax = new EdgeVectorFieldMaxAdapter(vMap, name);
return aMax;
}
}
|
package dbutil;
import entities.Comments;
import entities.Goods;
import entities.Users;
import java.sql.*;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import static java.lang.Integer.parseInt;
import static java.lang.Integer.valueOf;
public class DBUtil {
private Connection connection;
public DBUtil() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc", "root", "1234");
} catch (Exception e) {
e.printStackTrace();
}
}
public void addUser(String email, String password, String name, String surname, int age) {
try {
Statement st = connection.createStatement();
st.executeUpdate("INSERT INTO users (email, sha1(password), name, surname, age) " +
"VALUES (\"" + email + "\",\"" + password + "\",\"" + name + "\",\"" + surname + "\"," + age + ")");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<Users> listUsers() {
ArrayList<Users> usersList = new ArrayList();
try {
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT id, email, password, name, surname, age FROM users ORDER BY id ASC");
while (result.next()) {
int id = result.getInt("id");
String email = result.getString("email");
String password = result.getString("password");
String name = result.getString("name");
String surname = result.getString("surname");
int age = result.getInt("age");
Users u = new Users(id, email, password, name, surname, age);
usersList.add(u);
}
st.close();
} catch (Exception e) {
e.printStackTrace();
}
return usersList;
}
public void deleteUser(String idUser) {
try {
Statement st = connection.createStatement();
st.executeUpdate("DELETE FROM users WHERE id = \"" + idUser + "\"");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Users getUserById(int id) {
Users getUser = null;
for (Users x : listUsers()) {
if (id == x.getId()) {
getUser = x;
}
}
return getUser;
}
public void updateUser(String email, String password, String name, String surname, int age, String id) {
try {
Statement st = connection.createStatement();
st.executeUpdate("UPDATE users SET email=\"" + email + "\", password=(\"" + password + "\"),name=\"" + name + "\",surname=\"" + surname + "\",age=" + age + " WHERE id = \"" + id + "\"");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Users getUserByEmailAndPassword(String email, String password) {
Users u = null;
try {
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT id, email, password, name, surname, age FROM users WHERE email=\"" + email + "\" AND password=(\"" + password + "\") LIMIT 1");
if (result.next()) {
int id = result.getInt("id");
String emailUser = result.getString("email");
String passwordUser = result.getString("password");
String name = result.getString("name");
String surname = result.getString("surname");
int age = result.getInt("age");
u = new Users(id, emailUser, passwordUser, name, surname, age);
System.out.println("Пользователь проверен!");
}
st.close();
} catch (Exception e) {
e.printStackTrace();
}
return u;
}
public ArrayList<Goods> showMyGoods(Users u) {
int get_id_user = u.getId();
ArrayList<Goods> listGoods = new ArrayList<Goods>();
try {
PreparedStatement preparedStatement = null;
preparedStatement = connection.prepareStatement("SELECT * FROM goods WHERE id_user = ? ORDER BY id DESC ");
preparedStatement.setInt(1, get_id_user);
ResultSet result = preparedStatement.executeQuery();
while (result.next()) {
int id = result.getInt("id");
int id_user = result.getInt("id_user");
int published = result.getInt("published");
String date = result.getString("date");
String time = result.getString("time");
int view_count = result.getInt("view_count");
int price = result.getInt("price");
String description = result.getString("description");
String photo = result.getString("photo");
String title = result.getString("title");
int category = result.getInt("category");
Goods g = new Goods(id, id_user, published, date, time, view_count, price, description, photo, title, category);
listGoods.add(g);
}
preparedStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
return listGoods;
}
public void deleteGoodsById(String idGoods) {
try {
Statement st = connection.createStatement();
st.executeUpdate("DELETE FROM goods WHERE id = \"" + idGoods + "\"");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleteCommentsById(String idComments) {
try {
Statement st = connection.createStatement();
st.executeUpdate("DELETE FROM comments WHERE id = \"" + idComments + "\"");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Goods getGoodsById(String idG) {
Goods goods = null;
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM goods WHERE id= \"" + idG + "\" ");
while (resultSet.next()) {
int id = resultSet.getInt("id");
int idUser = resultSet.getInt("id_user");
int published = resultSet.getInt("published");
String date = resultSet.getString("date");
String time = resultSet.getString("time");
int viewCount = resultSet.getInt("view_count");
int price = resultSet.getInt("price");
String description = resultSet.getString("description");
String photo = resultSet.getString("photo");
String title = resultSet.getString("title");
int category = resultSet.getInt("category");
goods = new Goods(id, idUser, published, date, time, viewCount, price, description, photo, title, category);
}
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return goods;
}
public boolean emailAlreadyExist(String email) {
boolean exist = false;
try {
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT email FROM users");
while (resultSet.next()) {
if (email.equals(resultSet.getString("email"))) {
exist = true;
break;
} else {
exist = false;
}
}
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return exist;
}
public ArrayList<Goods> getGoodsByParam(String search, String category) {
ArrayList<Goods> goodsList = new ArrayList<Goods>();
Goods goods = null;
if (category == null) category = "0";
if (search == null) search = "";
try {
Statement statement = connection.createStatement();
String queryAll = null;
boolean x = category.equals("0");
if (search != null && x != true) {
queryAll = "SELECT * FROM goods WHERE published='1' AND category=\"" + category + "\" AND \n" +
"(LOWER(title) LIKE LOWER(\"%" + search + "%\") OR LOWER(description) LIKE LOWER(\"%" + search + "%\"))";
} else if (category.equals("0")) {
queryAll = "SELECT * FROM goods WHERE published='1' AND \n" +
"(LOWER(title) LIKE LOWER(\"%" + search + "%\") OR LOWER(description) LIKE LOWER(\"%" + search + "%\"))";
} else {
queryAll = "SELECT * FROM goods WHERE published='1' AND category=\"" + category + "\"";
}
ResultSet resultSet = statement.executeQuery(queryAll);
while (resultSet.next()) {
int id = resultSet.getInt("id");
int idUser = resultSet.getInt("id_user");
int published = resultSet.getInt("published");
String date = resultSet.getString("date");
String time = resultSet.getString("time");
int viewCount = resultSet.getInt("view_count");
int price = resultSet.getInt("price");
String description = resultSet.getString("description");
String photo = resultSet.getString("photo");
String title = resultSet.getString("title");
int category1 = resultSet.getInt("category");
goods = new Goods(id, idUser, published, date, time, viewCount, price, description, photo, title, category1);
goodsList.add(goods);
}
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return goodsList;
}
public void updatePassword(String id, String password) {
try {
Statement st = connection.createStatement();
st.executeUpdate("UPDATE users SET password=(\"" + password + "\") WHERE id=\"" + id + "\"");
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean checkCurrentPassword(String id1, int password) {
boolean x = false;
try {
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT password FROM users WHERE id=\"" + id1 + "\" AND password=(\"" + password + "\") LIMIT 1");
if (result.next()) {
int pass = result.getInt("password");
if (password==pass) {
x = true;
} else {
x = false;
}
}
st.close();
} catch (Exception e) {
e.printStackTrace();
}
return x;
}
public void addNewGoods(Goods goods) {
int id_user = goods.getId_user();
int published = goods.getPublished();
String date = goods.getDate();
String time = goods.getTime();
int price = goods.getPrice();
String description = goods.getDescription();
String photo = goods.getPhoto();
String title = goods.getTitle();
int category = goods.getCategory();
try {
PreparedStatement ps = null;
ps = connection.prepareStatement("INSERT INTO goods " +
"(id_user, published, date, time, price, description, photo, title, category) " +
"VALUES (?,?,?,?,?,?,?,?,?)");
ps.setInt(1, id_user);
ps.setInt(2, published);
ps.setString(3, date);
ps.setString(4, time);
ps.setInt(5, price);
ps.setString(6, description);
ps.setString(7, photo);
ps.setString(8, title);
ps.setInt(9, category);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNewComment(Comments comments) {
Long idGoods = comments.getId_goods();
Long idUser = comments.getId_user();
String title = comments.getTitle();
String content = comments.getContent();
String userName = comments.getUserName();
String userSurname = comments.getUserSurname();
String date = comments.getPostDate();
String time = comments.getPostTime();
try {
PreparedStatement ps = null;
ps = connection.prepareStatement("INSERT INTO comments" +
"(id_goods,id_user, title, content, date, time, user_name, user_surname) " +
"VALUES (?,?,?,?,?,?,?,?)");
ps.setInt(1, Math.toIntExact(idGoods));
ps.setInt(2, Math.toIntExact(idUser));
ps.setString(3, title);
ps.setString(4, content);
ps.setString(5, date);
ps.setString(6, time);
ps.setString(7, userName);
ps.setString(8, userSurname);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Goods showGoodsById(String idUser) {
Goods g = null;
try {
PreparedStatement preparedStatement = null;
preparedStatement = connection.prepareStatement("SELECT * FROM goods WHERE id = ? LIMIT 1");
preparedStatement.setInt(1, Integer.parseInt(idUser));
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
int id = result.getInt("id");
int id_user = result.getInt("id_user");
int published = result.getInt("published");
String date = result.getString("date");
int view_count = result.getInt("view_count");
String time = result.getString("time");
int price = result.getInt("price");
String description = result.getString("description");
String photo = result.getString("photo");
String title = result.getString("title");
int category = result.getInt("category");
g = new Goods(id, id_user, published, date, time, view_count, price, description, photo, title, category);
}
preparedStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
return g;
}
public ArrayList<Comments> commentsList(String idGoods) {
ArrayList<Comments> list = new ArrayList<Comments>();
Comments c = null;
try {
PreparedStatement preparedStatement = null;
preparedStatement = connection.prepareStatement("SELECT * FROM comments WHERE id_goods = ?");
preparedStatement.setInt(1, Integer.parseInt(idGoods));
ResultSet result = preparedStatement.executeQuery();
while (result.next()) {
Long id = result.getLong("id");
Long id_goods = result.getLong("id_goods");
Long id_user = result.getLong("id_user");
String title = result.getString("title");
String content = result.getString("content");
String postDate = result.getString("date");
String postTime = result.getString("time");
String userName = result.getString("user_name");
String userSurname = result.getString("user_surname");
c = new Comments(id, id_goods, id_user, title, content, postDate, postTime, userName, userSurname);
list.add(c);
}
preparedStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
private static DateFormatSymbols myDateFormatSymbols = new DateFormatSymbols() {
@Override
public String[] getMonths() {
return new String[]{"января", "февраля", "марта", "апреля", "мая", "июня",
"июля", "августа", "сентября", "октября", "ноября", "декабря"};
}
};
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AopInvocationException;
import org.springframework.aop.RawTargetAccess;
import org.springframework.aop.TargetSource;
import org.springframework.aop.support.AopUtils;
import org.springframework.core.DecoratingProxy;
import org.springframework.core.KotlinDetector;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* JDK-based {@link AopProxy} implementation for the Spring AOP framework,
* based on JDK {@link java.lang.reflect.Proxy dynamic proxies}.
*
* <p>Creates a dynamic proxy, implementing the interfaces exposed by
* the AopProxy. Dynamic proxies <i>cannot</i> be used to proxy methods
* defined in classes, rather than interfaces.
*
* <p>Objects of this type should be obtained through proxy factories,
* configured by an {@link AdvisedSupport} class. This class is internal
* to Spring's AOP framework and need not be used directly by client code.
*
* <p>Proxies created using this class will be thread-safe if the
* underlying (target) class is thread-safe.
*
* <p>Proxies are serializable so long as all Advisors (including Advices
* and Pointcuts) and the TargetSource are serializable.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @author Dave Syer
* @author Sergey Tsypanov
* @author Sebastien Deleuze
* @see java.lang.reflect.Proxy
* @see AdvisedSupport
* @see ProxyFactory
*/
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
/** use serialVersionUID from Spring 1.2 for interoperability. */
private static final long serialVersionUID = 5531744639992436476L;
/*
* NOTE: We could avoid the code duplication between this class and the CGLIB
* proxies by refactoring "invoke" into a template method. However, this approach
* adds at least 10% performance overhead versus a copy-paste solution, so we sacrifice
* elegance for performance (we have a good test suite to ensure that the different
* proxies behave the same :-)).
* This way, we can also more easily take advantage of minor optimizations in each class.
*/
/** We use a static Log to avoid serialization issues. */
private static final Log logger = LogFactory.getLog(JdkDynamicAopProxy.class);
private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow";
/** Config used to configure this proxy. */
private final AdvisedSupport advised;
private final Class<?>[] proxiedInterfaces;
/**
* Is the {@link #equals} method defined on the proxied interfaces?
*/
private boolean equalsDefined;
/**
* Is the {@link #hashCode} method defined on the proxied interfaces?
*/
private boolean hashCodeDefined;
/**
* Construct a new JdkDynamicAopProxy for the given AOP configuration.
* @param config the AOP configuration as AdvisedSupport object
* @throws AopConfigException if the config is invalid. We try to throw an informative
* exception in this case, rather than let a mysterious failure happen later.
*/
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
Assert.notNull(config, "AdvisedSupport must not be null");
this.advised = config;
this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
@Override
public Object getProxy() {
return getProxy(ClassUtils.getDefaultClassLoader());
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
return Proxy.newProxyInstance(determineClassLoader(classLoader), this.proxiedInterfaces, this);
}
@SuppressWarnings("deprecation")
@Override
public Class<?> getProxyClass(@Nullable ClassLoader classLoader) {
return Proxy.getProxyClass(determineClassLoader(classLoader), this.proxiedInterfaces);
}
/**
* Determine whether the JDK bootstrap or platform loader has been suggested ->
* use higher-level loader which can see Spring infrastructure classes instead.
*/
private ClassLoader determineClassLoader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
// JDK bootstrap loader -> use spring-aop ClassLoader instead.
return getClass().getClassLoader();
}
if (classLoader.getParent() == null) {
// Potentially the JDK platform loader on JDK 9+
ClassLoader aopClassLoader = getClass().getClassLoader();
ClassLoader aopParent = aopClassLoader.getParent();
while (aopParent != null) {
if (classLoader == aopParent) {
// Suggested ClassLoader is ancestor of spring-aop ClassLoader
// -> use spring-aop ClassLoader itself instead.
return aopClassLoader;
}
aopParent = aopParent.getParent();
}
}
// Regular case: use suggested ClassLoader as-is.
return classLoader;
}
/**
* Finds any {@link #equals} or {@link #hashCode} method that may be defined
* on the supplied set of interfaces.
* @param proxiedInterfaces the interfaces to introspect
*/
private void findDefinedEqualsAndHashCodeMethods(Class<?>[] proxiedInterfaces) {
for (Class<?> proxiedInterface : proxiedInterfaces) {
Method[] methods = proxiedInterface.getDeclaredMethods();
for (Method method : methods) {
if (AopUtils.isEqualsMethod(method)) {
this.equalsDefined = true;
}
if (AopUtils.isHashCodeMethod(method)) {
this.hashCodeDefined = true;
}
if (this.equalsDefined && this.hashCodeDefined) {
return;
}
}
}
}
/**
* Implementation of {@code InvocationHandler.invoke}.
* <p>Callers will see exactly the exception thrown by the target,
* unless a hook method throws an exception.
*/
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// Get the interception chain for this method.
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fall back on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
if (chain.isEmpty()) {
// We can skip creating a MethodInvocation: just invoke the target directly
// Note that the final invoker must be an InvokerInterceptor so we know it does
// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
if (KotlinDetector.isSuspendingFunction(method)) {
return COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName()) ?
CoroutinesUtils.asFlow(retVal) : CoroutinesUtils.awaitSingleOrNull(retVal, args[args.length - 1]);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
/**
* Equality means interfaces, advisors and TargetSource are equal.
* <p>The compared object may be a JdkDynamicAopProxy instance itself
* or a dynamic proxy wrapping a JdkDynamicAopProxy instance.
*/
@Override
public boolean equals(@Nullable Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
JdkDynamicAopProxy otherProxy;
if (other instanceof JdkDynamicAopProxy jdkDynamicAopProxy) {
otherProxy = jdkDynamicAopProxy;
}
else if (Proxy.isProxyClass(other.getClass())) {
InvocationHandler ih = Proxy.getInvocationHandler(other);
if (!(ih instanceof JdkDynamicAopProxy jdkDynamicAopProxy)) {
return false;
}
otherProxy = jdkDynamicAopProxy;
}
else {
// Not a valid comparison...
return false;
}
// If we get here, otherProxy is the other AopProxy.
return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised);
}
/**
* Proxy uses the hash code of the TargetSource.
*/
@Override
public int hashCode() {
return JdkDynamicAopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode();
}
}
|
/*
* Copyright 2015 Arie Timmerman
*/
package com.passbird.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Base64;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.InvalidCipherTextException;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.digests.ShortenedDigest;
import org.spongycastle.crypto.engines.AESEngine;
import org.spongycastle.crypto.generators.KDF2BytesGenerator;
import org.spongycastle.crypto.kems.RSAKeyEncapsulation;
import org.spongycastle.crypto.modes.CBCBlockCipher;
import org.spongycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.spongycastle.crypto.params.AsymmetricKeyParameter;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.params.ParametersWithIV;
import org.spongycastle.crypto.util.PrivateKeyFactory;
import org.spongycastle.crypto.util.PublicKeyFactory;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import com.passbird.activity.MainActivity;
/**
* Utils class
*/
public class Utils {
private static final String PROPERTY_PRIVATE_KEY = "private_key";
private static final String PROPERTY_PUBLIC_KEY = "public_key";
public static final String PROPERTY_REG_ID = "registration_id";
public static final String PROPERTY_APP_VERSION = "appVersion";
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId != null && registrationId.isEmpty()) {
Log.i("main", "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i("main", "App version changed.");
return "";
}
return registrationId;
}
/**
* @return Application's {@code SharedPreferences}.
*/
public static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}
public static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
public static KeyPair generateKeyPair(){
KeyPair keys = null;
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = new SecureRandom();
keyGen.initialize(2048, random);
keys = keyGen.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return keys;
}
public static void storeKeyPair(Context context, KeyPair keys){
final SharedPreferences prefs = Utils.getGCMPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Utils.PROPERTY_PRIVATE_KEY, Base64.encodeToString(keys.getPrivate().getEncoded(), Base64.DEFAULT));
editor.putString(Utils.PROPERTY_PUBLIC_KEY, Base64.encodeToString(keys.getPublic().getEncoded(), Base64.DEFAULT));
editor.apply();
}
public static String decrypt(JSONObject jsonObject, String privateKeyString){
return decrypt(jsonObject,getPrivateKey(privateKeyString));
}
@SuppressWarnings("WeakerAccess")
public static String decrypt(JSONObject jsonObject, AsymmetricKeyParameter privateKey){
try {
byte[] encapsulation = Base64.decode(jsonObject.getString("encapsulation"),Base64.DEFAULT);
byte[] iv = Base64.decode(jsonObject.getString("iv"),Base64.DEFAULT);
byte[] ciphertext = Base64.decode(jsonObject.getString("ciphertext"), Base64.DEFAULT);
KDF2BytesGenerator kdf = new KDF2BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20));
SecureRandom secureRandom = new SecureRandom();
RSAKeyEncapsulation rsaKeyEncapsulation = new RSAKeyEncapsulation(kdf, secureRandom);
rsaKeyEncapsulation.init(privateKey);
//initializes the cipher
CBCBlockCipher cipher = new CBCBlockCipher(new AESEngine());
//padded with PKCS7Padding
PaddedBufferedBlockCipher paddedCipher = new PaddedBufferedBlockCipher(cipher);
KeyParameter keyParameter = (KeyParameter) rsaKeyEncapsulation.decrypt(encapsulation,32);
CipherParameters ivAndKey = new ParametersWithIV(keyParameter, iv);
paddedCipher.reset();
paddedCipher.init(false, ivAndKey);
byte[] buf = new byte[paddedCipher.getOutputSize(ciphertext.length)];
int len = paddedCipher.processBytes(ciphertext, 0, ciphertext.length, buf, 0);
len += paddedCipher.doFinal(buf, len);
// remove padding
byte[] out2 = new byte[len];
System.arraycopy(buf, 0, out2, 0, len);
return new String(out2);
} catch (JSONException | InvalidCipherTextException e) {
e.printStackTrace();
}
return "";
}
private static AsymmetricKeyParameter getPrivateKey(String privateKeyString){
AsymmetricKeyParameter privateKey = null;
privateKeyString = privateKeyString.replaceAll("(-+BEGIN RSA PRIVATE KEY-+\\r?\\n|-+END RSA PRIVATE KEY-+\\r?\\n?)", "");
try {
privateKey = PrivateKeyFactory.createKey(Base64.decode(privateKeyString, Base64.DEFAULT));
} catch (IOException e) {
e.printStackTrace();
}
return privateKey;
}
public static AsymmetricKeyParameter getPublicKey(String publicKeyString){
Logger.log("publicKeyString",publicKeyString);
AsymmetricKeyParameter publicKey = null;
publicKeyString = publicKeyString.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");
try {
publicKey = PublicKeyFactory.createKey(Base64.decode(publicKeyString, Base64.DEFAULT));
} catch (IOException e) {
Logger.log("fout",e.getMessage());
e.printStackTrace();
}
Logger.log("return","return");
return publicKey;
}
public static JSONObject encrypt(JSONObject plain, String publicKeyString){
return encrypt(plain,getPublicKey(publicKeyString));
}
public static JSONObject encrypt(JSONObject plain, AsymmetricKeyParameter publicKey){
JSONObject result = new JSONObject();
//encapsulates the encrypted symetric key using the public key
KDF2BytesGenerator kdf = new KDF2BytesGenerator(new ShortenedDigest(new SHA256Digest(), 20));
SecureRandom secureRandom = new SecureRandom();
RSAKeyEncapsulation rsaKeyEncapsulation = new RSAKeyEncapsulation(kdf, secureRandom);
byte[] out = new byte[256];
rsaKeyEncapsulation.init(publicKey);
//store the encrypted key in "out" and return the unencrypted key in keyParameter
KeyParameter keyParameter = (KeyParameter)rsaKeyEncapsulation.encrypt(out,32);
Logger.log("encryption key", Base64.encodeToString(keyParameter.getKey(), Base64.DEFAULT));
//initializes the cipher
CBCBlockCipher cipher = new CBCBlockCipher(new AESEngine());
//padded with PKCS7Padding
PaddedBufferedBlockCipher paddedCipher = new PaddedBufferedBlockCipher(cipher);
Logger.log("blocksize: ",String.valueOf(cipher.getBlockSize()));
//generates the iv
byte[] ivBytes = new byte[cipher.getBlockSize()];
secureRandom.nextBytes(ivBytes);
CipherParameters ivAndKey = new ParametersWithIV(keyParameter, ivBytes);
paddedCipher.reset();
paddedCipher.init(true, ivAndKey);
try {
byte[] dataToEncrypt = plain.toString().getBytes();
byte[] encryptedData=new byte[paddedCipher.getOutputSize(dataToEncrypt.length)];
int numberOfEncryptedBytes = paddedCipher.processBytes(dataToEncrypt,0,dataToEncrypt.length,encryptedData,0);
numberOfEncryptedBytes += paddedCipher.doFinal(encryptedData, numberOfEncryptedBytes);
byte[] out2 = new byte[numberOfEncryptedBytes];
System.arraycopy(encryptedData, 0, out2, 0, numberOfEncryptedBytes);
Logger.log("In buffer", String.valueOf(dataToEncrypt.length));
Logger.log("zonder buffer",String.valueOf(out2.length));
result.put("ciphertext",Base64.encodeToString(out2,Base64.DEFAULT));
result.put("iv",Base64.encodeToString(ivBytes,Base64.DEFAULT));
result.put("encapsulation",Base64.encodeToString(out,Base64.DEFAULT));
} catch (Exception e) {
Logger.log("Fout",e.getMessage());
e.printStackTrace();
}
return result;
}
public static String jsonObjectGetString(JSONObject jsonObject, String key){
String result = null;
try {
result = jsonObject!=null?jsonObject.getString(key):"";
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
public static JSONObject jsonObjectGetJSONObject(JSONObject jsonObject, @SuppressWarnings("SameParameterValue") String key){
JSONObject result = new JSONObject();
try {
result = jsonObject!=null?jsonObject.getJSONObject("message"):new JSONObject();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
public static JSONObject getJSONObject(String jsonString){
JSONObject result = new JSONObject();
try {
result = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
|
package com.tibco.as.util.convert.impl;
import com.tibco.as.util.convert.ConverterFactory;
import com.tibco.as.util.convert.IConverter;
public class DynamicConverter implements IConverter {
private ConverterFactory factory;
private Class<?> to;
public DynamicConverter(ConverterFactory factory, Class<?> to) {
this.factory = factory;
this.to = to;
}
@Override
public Object convert(Object source) {
Class<?> from = source.getClass();
IConverter converter = factory.getConverter(from, to);
if (converter == null) {
return null;
}
return converter.convert(source);
}
} |
/**
* @file XListViewHeader.java
* @create Apr 18, 2012 5:22:27 PM
* @author Maxwin
* @description XListView's header
*/
package walke.base.widget.xlist;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import walke.base.R;
public class XListHeader extends LinearLayout {
private static final String TAG = "XListViewHeader";
private LinearLayout mContainer;
private DrawRing mDrawRing;
private int mState = STATE_NORMAL;
public final static int STATE_NORMAL = 0;
public final static int STATE_READY = 1;
public final static int STATE_REFRESHING = 2;
private TextView mTextView;
private boolean isNormal=true;
public XListHeader(Context context) {
super(context);
initView(context);
}
public XListHeader(Context context, boolean isNormal) {
super(context);
this.isNormal=isNormal;
initView(context);
}
/**
* @param context
* @param attrs
*/
public XListHeader(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public DrawRing getDrawRing() {
return mDrawRing;
}
public void setDrawRing(DrawRing drawRing) {
mDrawRing = drawRing;
}
private void initView(Context context) {
// 初始情况,设置下拉刷新view高度为0
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0);
if (isNormal) {
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.xlist_header, null);
mDrawRing = (DrawRing)mContainer.findViewById(R.id.xlist_header_progressbar);
mTextView = (TextView)mContainer.findViewById(R.id.xlist_header_text);
}else {
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.xlist_header2, null);
mDrawRing = (DrawRing)mContainer.findViewById(R.id.xlist_header_progressbar2);
mTextView = (TextView)mContainer.findViewById(R.id.xlist_header_text2);
}
addView(mContainer, lp);
setGravity(Gravity.BOTTOM);
}
public void setState(int state) {
if (state == mState) return ;
/*if (state == STATE_REFRESHING) {// 显示进度
mTextView.setText(R.string.xlistview_header_hint_loading);
mDrawRing.setVisibility(View.VISIBLE);
} else { // 显示箭头图片
mDrawRing.setVisibility(View.VISIBLE);
}*/
switch(state){
case STATE_NORMAL://下拉刷新
mTextView.setText("下拉刷新");
mDrawRing.setProgress(0);
mDrawRing.stopRotate();
break;
case STATE_READY:
if (mState != STATE_READY) {//---松开刷新
//mDrawRing.startRotate(5);
mTextView.setText("松开刷新");
}
break;
case STATE_REFRESHING://正在加载...
mDrawRing.startRotate(12);
mTextView.setText("正在刷新");
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public void setTopMargin(int height) {
if (height < 0) return ;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContainer.getLayoutParams();
lp.bottomMargin = -height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getHeight();
}
}
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.contrib.mqtt.impl;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttPersistable;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A variant of {@link MemoryPersistence} which uses
* {@link ConcurrentMap} instead of {@link Hashtable}.
*/
public class ConcurrentMemoryPersistence implements MqttClientPersistence {
private final ConcurrentMap<String, MqttPersistable> data = new ConcurrentHashMap<>();
@Override
public void open(String clientId, String serverURI) {
}
@Override
public void close() {
}
@Override
public void put(String key, MqttPersistable persistable) {
data.put(key, persistable);
}
@Override
public MqttPersistable get(String key) {
return data.get(key);
}
@Override
public void remove(String key) {
data.remove(key);
}
@Override
public Enumeration<String> keys() {
return Collections.enumeration(data.keySet());
}
@Override
public void clear() {
data.clear();
}
@Override
public boolean containsKey(String key) {
return data.containsKey(key);
}
}
|
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.tenant.resource.manager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
import org.wso2.carbon.event.stream.core.EventStreamConfiguration;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
import org.wso2.carbon.identity.configuration.mgt.core.constant.ConfigurationConstants;
import org.wso2.carbon.identity.configuration.mgt.core.exception.ConfigurationManagementException;
import org.wso2.carbon.identity.configuration.mgt.core.model.Resource;
import org.wso2.carbon.identity.configuration.mgt.core.model.ResourceFile;
import org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants;
import org.wso2.carbon.identity.tenant.resource.manager.exception.TenantResourceManagementException;
import org.wso2.carbon.identity.tenant.resource.manager.internal.TenantResourceManagerDataHolder;
import org.wso2.carbon.identity.tenant.resource.manager.util.ResourceUtils;
import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
import java.util.List;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_ADDING_EVENT_PUBLISHER_CONFIGURATION;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_STREAM_CONFIGURATION;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_TENANT_SPECIFIC_PUBLISHER_FILES;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.PUBLISHER;
import static org.wso2.carbon.identity.tenant.resource.manager.util.ResourceUtils.populateMessageWithData;
/**
* Axis2Observer for generating tenant wise publisher configurations.
*/
public class TenantAwareAxis2ConfigurationContextObserver extends AbstractAxis2ConfigurationContextObserver {
private static final Log log = LogFactory.getLog(TenantAwareAxis2ConfigurationContextObserver.class);
/**
* Add the tenant wise publisher and stream Configuration in tenant loading.
*
* @param tenantId tenant ID.
*/
@Override
public void creatingConfigurationContext(int tenantId) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
log.info("Loading configuration context for tenant domain: " + tenantDomain);
loadEventStreamAndPublisherConfigurations(tenantId);
}
/**
* This method loads event stream and publisher configurations for a specific tenant.
*
* @param tenantId tenant id.
*/
private void loadEventStreamAndPublisherConfigurations(int tenantId) {
List<EventPublisherConfiguration> activeEventPublisherConfigurations;
List<EventStreamConfiguration> eventStreamConfigurationList;
try {
ResourceUtils.startSuperTenantFlow();
activeEventPublisherConfigurations = ResourceUtils.getSuperTenantEventPublisherConfigurations();
eventStreamConfigurationList = getSuperTenantEventStreamConfigurations();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
try {
ResourceUtils.startTenantFlow(tenantId);
loadTenantEventStreams(eventStreamConfigurationList);
loadTenantPublisherConfigurationFromConfigStore();
if (activeEventPublisherConfigurations != null) {
ResourceUtils.loadTenantPublisherConfigurationFromSuperTenantConfig(activeEventPublisherConfigurations);
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* This method loads publisher configurations tenant wise by fetching them from configuration store.
*/
private void loadTenantPublisherConfigurationFromConfigStore() {
try {
List<Resource> resourcesByTypePublisher = TenantResourceManagerDataHolder.getInstance()
.getConfigurationManager().getResourcesByType(PUBLISHER).getResources();
for (Resource resource : resourcesByTypePublisher) {
if (!resource.getFiles().isEmpty()) {
ResourceFile tenantSpecificPublisherFile = resource.getFiles().get(0);
if (tenantSpecificPublisherFile != null) {
if (log.isDebugEnabled()) {
log.debug("File for publisher name: " + tenantSpecificPublisherFile.getName()
+ " is available in the configuration store.");
}
TenantResourceManagerDataHolder.getInstance().getResourceManager()
.addEventPublisherConfiguration(tenantSpecificPublisherFile);
}
}
}
} catch (ConfigurationManagementException e) {
if (e.getErrorCode()
.equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_FEATURE_NOT_ENABLED.getCode())) {
log.warn("Configuration store is disabled. Super tenant configuration will be used for the tenant "
+ "domain: " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
} else if (e.getErrorCode()
.equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_RESOURCES_DOES_NOT_EXISTS.getCode())) {
log.warn("Configuration store does not contain any resources under resource type publisher. Super "
+ "tenant configurations will be used for the tenant domain: " + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain());
} else if (e.getErrorCode()
.equals(ConfigurationConstants.ErrorMessages.ERROR_CODE_RESOURCE_TYPE_DOES_NOT_EXISTS.getCode())) {
log.warn("Configuration store does not contain publisher resource type. Super "
+ "tenant configurations will be used for the tenant domain: " + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain());
} else {
log.error(populateMessageWithData(ERROR_CODE_ERROR_WHEN_FETCHING_TENANT_SPECIFIC_PUBLISHER_FILES,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
} catch (TenantResourceManagementException e) {
log.error(populateMessageWithData(ERROR_CODE_ERROR_WHEN_ADDING_EVENT_PUBLISHER_CONFIGURATION,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
}
/**
* This method returns super tenant event stream configurations.
*
* @return list of event stream configurations.
*/
private List<EventStreamConfiguration> getSuperTenantEventStreamConfigurations() {
List<EventStreamConfiguration> eventStreamConfigurationList = null;
try {
eventStreamConfigurationList = TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
.getAllEventStreamConfigurations();
} catch (EventStreamConfigurationException e) {
log.error(populateMessageWithData(
TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_SUPER_TENANT_EVENT_STREAM_CONFIGURATION,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
return eventStreamConfigurationList;
}
/**
* This method loads event stream configurations tenant wise by using super tenant publisher configurations.
*
* @param eventStreamConfigurationList list of active super tenant stream configurations.
*/
private void loadTenantEventStreams(List<EventStreamConfiguration> eventStreamConfigurationList) {
if (eventStreamConfigurationList != null) {
for (EventStreamConfiguration eventStreamConfiguration : eventStreamConfigurationList) {
if (TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
.getEventStreamConfiguration(eventStreamConfiguration.getStreamDefinition().getStreamId())
== null) {
try {
TenantResourceManagerDataHolder.getInstance().getCarbonEventStreamService()
.addEventStreamConfig(eventStreamConfiguration);
} catch (EventStreamConfigurationException e) {
log.error(populateMessageWithData(
ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_STREAM_CONFIGURATION,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
}
}
}
}
}
|
package io.github.cottonmc.libcd.impl;
import net.minecraft.class_1799;
import net.minecraft.class_1856;
import net.minecraft.class_2960;
import net.minecraft.class_3972;
public interface CuttingRecipeFactoryInvoker<T extends class_3972> {
T libcd$create(class_2960 id, String group, class_1856 input, class_1799 output);
}
|
package br.com.filemanager.web.utils;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class FormChild {
private FacesContext facesContext;
private FacesMessage facesMessage;
public void addMsgError(String msg, String detail) {
facesContext = FacesContext.getCurrentInstance();
facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detail != null? detail : "");
facesContext.addMessage(null, facesMessage);
}
}
|
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
public class VM {
private int pc = 0;
private Pattern cmmdPattern;
List<Command> program;
Map<String, Integer> myProgram;
private int count;
private int loopPC;
private int numInstructionsExecuted;
public VM(){
numInstructionsExecuted = 0;
program = new ArrayList<Command>();
myProgram = new HashMap<String, Integer>();
}
public void add(String cmmd){
Command cmd = new Command(cmmd, pc++);
program.add(cmd);
System.out.println(cmd);
//System.out.println(pc);
}
public void compile(String fileName){
String line = null;
try{
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null){
Command cmd = new Command(line, pc++);
program.add(cmd);
}
bufferedReader.close();
}
catch(FileNotFoundException ex){
System.out.println("File" + fileName + "not found");
}
catch(IOException ex){
System.out.println("Error reading" + fileName);
}
}
public void execute(Command cmmd) throws Exception{
numInstructionsExecuted++;
if(cmmd.getOP().equals("load")){
int val;
if(cmmd.getArg2().matches("[0-9]+")){
val = Integer.valueOf(cmmd.getArg2());
}
else{
String variable = cmmd.getArg2();
//val = Integer.parseInt(cmmd.getArg2());
val = myProgram.get(variable);
}
//load x, 10
//if myprogram doesnt contain key, initialize it
if(!myProgram.containsKey(cmmd.getArg1())){
myProgram.put(cmmd.getArg1(), val);
}
else{
myProgram.replace(cmmd.getArg1(), val);
}
}
else if(cmmd.getOP().equals("inc")){
int value;
String key = cmmd.getArg1();
value = myProgram.get(key);
value = value + 1;
myProgram.replace(key, value);
}
else if(cmmd.getOP().equals("goto")){
pc = cmmd.getTarget()-1;
}
else if(cmmd.getOP().equals("loop")){
/*//loopPC = pc;
//System.out.println("loopPC:" + loopPC);
//System.out.println("loop PC:" + loopPC);
count = myProgram.get(cmmd.getArg1());
if(count <= 0){
pc = cmmd.getTarget() + 1;
} else {
cmmd.setCount(count);
}**/
String arg1 = cmmd.getArg1();
int count;
if(arg1.matches("\\d+")){
count = Integer.parseInt(arg1);
}
else{
Integer integer = myProgram.get(cmmd.getArg1());
if(integer == null){
myProgram.put(arg1, 0);
count = 0;
}
else{
count = integer.intValue();
}
}
if(count <= 0){
pc = cmmd.getTarget() + 1;
}
else{
cmmd.setCount(count);
}
}
else if(cmmd.getOP().equals("end")){
Command myLoop = program.get(cmmd.getTarget()-1);
myLoop.decCount();
int count = myLoop.getCount();
if(count > 0){
pc = cmmd.getTarget();
}
//count--;
//if(count > 0){
// pc = loopPC;
//}
}
else{
throw new Exception("unrecognized opcode");
}
}
public void run() throws Exception {
resolveLabels();
pc = 0;
while(pc < program.size()) {
execute(program.get(pc++));
}
}
private void resolveLabels() {
Stack<Command> loopStack = new Stack<Command>();
Map<String, Integer> targets = new HashMap<String, Integer>();
// pass 1
for(Command cmmd: program) {
if(cmmd.getLabel() != null){
targets.put(cmmd.getLabel(), cmmd.getpc());
}
if(cmmd.getOP().equals("loop")){
loopStack.push(cmmd);
}
if(cmmd.getOP().equals("end")){
Command loop = loopStack.pop();
loop.setTarget(cmmd.getpc());
cmmd.setTarget(loop.getpc());
}
}
// pass 2
for(Command cmmd: program) {
if(cmmd.getOP().equals("goto")){
String labelInMap = cmmd.getArg1();
if(targets.containsKey(labelInMap)){
int pcOfLabel = targets.get(labelInMap);
cmmd.setTarget(pcOfLabel);
}
}
}
//System.out.println(targets);
}
public String toString(){
return "pc= " + pc + "\n" + "vars= " + myProgram + "\n" +
"Number of Instructions Executed: " + numInstructionsExecuted;
}
}
|
package br.com.zup.kafka.consumer;
import java.util.regex.Pattern;
public class TestConfigs {
public static final String KAFKA_BOOTSTRAP_SERVERS = "localhost:9092";
public static final String KAFKA_DEFAULT_GROUP_ID = "zup_kafka_group_1";
public static final Pattern KAFKA_DEFAULT_TOPIC_PATTERN = Pattern.compile("zup_kafka(.)*");
public static final int KAFKA_DEFAULT_CONSUMER_POOL_SIZE = 1;
}
|
package com.zxt.compplatform.authority.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import com.opensymphony.xwork2.ActionSupport;
import com.zxt.compplatform.authority.entity.FieldGrant;
import com.zxt.compplatform.authority.service.FieldGrantService;
public class FieldGrantAction extends ActionSupport{
/**
* 字段授权 操作业务逻辑实体 SET注入 GUOWEIXIN
*/
private FieldGrantService fieldGrantService;
public void setFieldGrantService(FieldGrantService fieldGrantService) {
this.fieldGrantService = fieldGrantService;
}
/**
* 执行添加操作
*
*/
public String addFieldGrant() {
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
String fieldString = req.getParameter("fieldString");
String tableNameStr=req.getParameter("tableName");
try {
//得到角色ID。如果没有,不操作:
String roleId=req.getParameter("roleId");
if(roleId!=null && !"".equals(tableNameStr)){
//得到ID后,先将该角色ID的值删除后,再进行保存.该删除方法 根据角色ID
fieldGrantService.deleteFieldGrant(new Long(roleId));
String[] arrayTableName=tableNameStr.split(",");//得到表的名称
String subStrFieldStr="";//截取字符串了
for(int i=0;i<arrayTableName.length;i++){
if(i==0)
subStrFieldStr=fieldString.substring(0,fieldString.lastIndexOf(arrayTableName[i]));//截取字符串,从最后的截取过来。
else{
int first=fieldString.lastIndexOf(arrayTableName[i-1])+arrayTableName[i-1].length();
int index=fieldString.indexOf(arrayTableName[i])-first;
int result=fieldString.indexOf(arrayTableName[i])-index;
subStrFieldStr=fieldString.substring(result,fieldString.lastIndexOf(arrayTableName[i]));//截取字符串,从最后的截取过来。
}
String[] arrayFieldStr= subStrFieldStr.split(arrayTableName[i]);
//System.out.println(arrayFieldStr.length);//测试数据 输出 该表字段个数
int flagLength=0;
for(int j=0;j<arrayFieldStr.length;j++){
//System.out.println(arrayFieldStr[j]+"~~~"+arrayTableName[i]);//测试数据 输出字段名+表名
FieldGrant fieldGrant=new FieldGrant();
Long l=System.currentTimeMillis();
fieldGrant.setId(l.toString());
fieldGrant.setRid(new Long(roleId));//角色ID
fieldGrant.setTablename(arrayTableName[i]);
fieldGrant.setFieldname(arrayFieldStr[j]);//字段名称
//执行添加操作
fieldGrantService.addFieldGrant(fieldGrant);
//执行更新操作
try{
fieldGrantService.update_service(new Long(roleId));
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
//res.getWriter().write("success");
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 字段授权 LIST页面
*/
public String list(){
HttpServletResponse res = ServletActionContext.getResponse();
HttpServletRequest req = ServletActionContext.getRequest();
/*
* 根据传过来的角色ID。进行查询
*/
String roleId=req.getParameter("roleId");
req.setAttribute("roleId",roleId);
if(roleId==null){
return "list";
}
/**
* 得到存储的数据ID列表
* 得到其角色所属的 字段名和表名
*/
List listRoleId=fieldGrantService.getAllByRid(new Long(roleId));
if(listRoleId!=null && listRoleId.size()>0){
Map map1 = new HashMap();
if (listRoleId == null) {
listRoleId = new ArrayList();
}
map1.put("resultListColumnJson",listRoleId);
String dataJson1 = JSONObject.fromObject(map1).toString();
req.setAttribute("formJson",dataJson1);
}else{
req.setAttribute("resultListColumnJson","");
}
/**
* 根据角色ID,得到其所属表名称
* select tableName from T_FIELD_GRANT where rid=2 group by tableName
* 如果flag==0时,则让其查所有表名称。rid不起作用。如果是其它,flag不起作用
*/
List listTableName=fieldGrantService.getTableNameByRid(new Long(roleId),1);
String tableNameSplit="";
if(listTableName!=null && listTableName.size()>0){
for(int i=0;i<listTableName.size();i++){
FieldGrant fieldGrant=(FieldGrant)listTableName.get(i);
tableNameSplit+=fieldGrant.getTablename()+",";
}
req.setAttribute("tableNameSplit", tableNameSplit);
}
return "list";
}
/**
* 根据 角色RID,删除该角色所有操作
* @param id
*/
public String deleteFieldGrant(){
fieldGrantService.deleteFieldGrant(new Long(1));
return "toList";
}
}
|
package tr.com.indbilisim;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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.io.PrintWriter;
import java.sql.*;
import java.util.List;
/**
* Created by brhanmeYdn on 20/07/2017.
*/
public class LoginServlet extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
/* PrintWriter outs=response.getWriter();
String userid = request.getParameter("user");
String pwd = request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/todo99",
"brhanmeYdn", "123456");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from login where username='" + userid + "' and pass='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("todo.jsp");
} else {
outs.print("Unsucessfuly");
response.sendRedirect("login.jsp");
}*/
PrintWriter out=response.getWriter();
String user=request.getParameter("user");
String pass=request.getParameter("pass");
ServletContext context=getServletContext();
Connection con=UserDao.getConnection();
try {
PreparedStatement ps=con.prepareStatement
("SELECT *FROM login WHERE username=? and pass=?");
ps.setString(1,user);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
if(rs.next())
{;
response.sendRedirect("todo");
}
else {
out.print("You are wrong!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package MachineLearningAnalyse;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class AttributeResults {
public static void main(String args[]) throws IOException{
int start = 0;
int end = 4;
for(int i = 0; i<=34; i++){
ArrayList<String> subjects = new ArrayList<String>();
subjects.add("home_exit_diff");
subjects.add("tsukin_time_diff");
subjects.add("office_enter_diff");
subjects.add("office_time_diff");
subjects.add("office_exit_diff");
subjects.add("kitaku_time_diff");
subjects.add("home_return_diff");
for(String subject: subjects){
File in = new File("/home/c-tyabe/Data/MLResults_rain9/"+subject+"_ML_lineforeach.csv");
File out = new File("/home/c-tyabe/Data/MLResults_rain9/sosei/"+subject+"_ML_lineforeach_elements_"+String.valueOf(start+5*i)+"_"+String.valueOf(end+5*i)+".csv");
makeMap(in,out,String.valueOf(start+5*i),String.valueOf(end+5*i));
}
}
}
public static HashMap<String,ArrayList<String>> makeMap(File in, File out, String start, String end) throws IOException{
HashMap<String,ArrayList<String>> res = new HashMap<String,ArrayList<String>>();
BufferedReader br = new BufferedReader(new FileReader(in));
BufferedWriter bw = new BufferedWriter(new FileWriter(out));
String line = null;
while((line=br.readLine())!= null){
String[] tokens = line.split(" ");
String val = tokens[0];
for(String ele : tokens){
if(ele.split(":").length==2){
String elenum = ele.split(":")[0];
if(!elenum.equals("")){
if((Integer.valueOf(elenum)<=Integer.valueOf(end))&&(Integer.valueOf(elenum)>=Integer.valueOf(start))){
if(res.containsKey(elenum)){
res.get(elenum).add(val);
}
else{
ArrayList<String> list = new ArrayList<String>();
list.add(val);
res.put(elenum, list);
}
}
}
}
}
}
br.close();
for(String num : res.keySet()){
for(String val : res.get(num)){
bw.write(num + "," + val);
bw.newLine();
}
}
bw.close();
return res;
}
// public static void soukancheck(HashMap<String,ArrayList<String>> map){
// int elenum = 4;
//
// }
}
|
import static org.junit.Assert.*;
import org.junit.Test;
public class PostItTest {
@Test
public void testPostIt() {
String taskName = "Finir projet de CLean Architecture";
AppTime dateTime = new AppTime("2020-03-14 15:33");
PostIt postIt = new PostIt(taskName, dateTime);
assertEquals(postIt.getTaskName(), taskName);
assertTrue(dateTime.getDateTime().isEqual(postIt.getCreationDate().getDateTime()));
assertEquals(postIt.getState(), TaskState.TODO);
}
} |
import java.util.ArrayDeque;
public class TestaArray {
public static void main(String[] args) {
int[] arrayDeIdades = new int[5];
arrayDeIdades[0]=25;
arrayDeIdades[1]=35;
arrayDeIdades[2]=15;
arrayDeIdades[3]=45;
arrayDeIdades[4]=12;
for (int i = 0; i < arrayDeIdades.length; i++) {
System.out.println(i);
System.out.println("Nessa posição tem o valor "+arrayDeIdades[i]);
}
//Foreach
for(int i:arrayDeIdades){
System.out.println(i);
}
}
}
|
package com.daydvr.store.presenter.game;
/*
* Copyright (C) 2017 3ivr. All rights reserved.
*
* @author: Jason(Liu ZhiCheng)
* @mail : jason@3ivr.cn
* @date : 2017/12/29 11:00
*/
import android.content.Context;
import com.daydvr.store.base.IBasePresenter;
import com.daydvr.store.base.IBaseView;
import com.daydvr.store.bean.GameBean;
import java.util.ArrayList;
import java.util.List;
public class GameDetailContract {
public interface View extends IBaseView<Presenter> {
<T> void showGameDetailPic(List<T> beans);
void showGameDetail(GameBean gameBean);
Context getContext();
void jumpToGameDetail(android.view.View view, ArrayList<CharSequence> data, int position);
}
public interface Presenter extends IBasePresenter {
void initUtils();
void loadGameDetail(int apkId);
void loadGameDetailPic();
void startDownload();
void pauseDownload();
void installGame();
void openGame();
}
}
|
package ru.job4j.models;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
/**
* Класс BrandTest тестирует класс Brand.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 2019-05-30
* @since 2018-05-14
*/
public class BrandTest {
/**
* Кузов.
*/
private Brand brand;
/**
* Действия перед тестом.
*/
@Before
public void beforeTest() {
this.brand = new Brand(1L, "Ford", new Founder(1L, "Ford", "Henry"));
}
/**
* Тестирует public boolean equals(Object obj).
*/
@Test
public void testEquals() {
Brand expected = new Brand(1L, "Ford", new Founder(1L, "Ford", "Henry"));
assertEquals(expected, this.brand);
}
/**
* Тестирует public boolean equals(Object obj).
* 2 ссылки на один объект.
*/
@Test
public void testEquals2refsOfOneObject() {
Brand obj = this.brand;
assertEquals(obj, this.brand);
}
/**
* Тестирует public boolean equals(Object obj).
* Сравнение с null.
*/
@Test
public void testEqualsWithNull() {
Brand brand = null;
assertFalse(this.brand.equals(brand));
}
/**
* Тестирует public boolean equals(Object obj).
* Сравнение объектов разных классов.
*/
@Test
public void testEqualsWithDifferentClasses() {
assertFalse(this.brand.equals(""));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные id.
*/
@Test
public void testEqualsDifferentIds() {
Brand expected = new Brand(0L, "Ford", new Founder(1L, "Ford", "Henry"));
assertFalse(expected.equals(this.brand));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные name.
*/
@Test
public void testEqualsDifferentNames() {
Brand expected = new Brand(1L, "Chevrolet", new Founder(1L, "Ford", "Henry"));
assertFalse(expected.equals(this.brand));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные name.
*/
@Test
public void testEqualsDifferentFounders() {
Brand expected = new Brand(1L, "Ford", new Founder(1L, "Chevrolet", "Louis"));
assertFalse(expected.equals(this.brand));
}
/**
* Тестирует public int hashCode().
*/
@Test
public void testHashCode() {
int expected = Objects.hash(new Founder(1L, "Ford", "Henry"), 1L, "Ford");
int actual = this.brand.hashCode();
assertEquals(expected, actual);
}
/**
* Тестирует public String toString().
*/
@Test
public void testToString() {
Brand brand = new Brand();
brand.setId(1L);
brand.setName("Ford");
brand.setFounder(new Founder(1L, "Ford", "Henry"));
assertEquals("Brand[id: 1, name: Ford, founder: Founder[id: 1, nameLast: Ford, name: Henry]]", brand.toString());
}
} |
import java.util.Scanner;
class apples{
public static void main(String args[]){
int age;
age = 7;
switch (age){
case 1:System.out.println("You can crawl");
break;
case 2:System.out.println("You can talk");
break;
case 3:System.out.println("You can get in trouble");
break;
default:System.out.println("I don't know how old you are");
break;
}
}
}
|
package org.androidpn.server.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.zhku.my21days.base.AbstractExample;
/**
* <p>系统名称: <b>NETARK-通用网管平台V1.0</b></p>
* <p>公司: 中通服软件科技有限公司</p>
* <p>表名称:apn_user</p>
* <p>域对象:User.java</p>
* <p>SQL映射文件:org.androidpn.server.model.apn_user_SqlMap.xml</p>
* @see org.androidpn.server.model.User
* @see org.androidpn.server.dao.UserDAO
* @author 戈亮锋
* @Create On:2014-03-05 10:26:34
*/
public class UserExample extends AbstractExample {
protected String orderByClause;
protected List<Criteria> oredCriteria;
public UserExample() {
oredCriteria = new ArrayList<Criteria>();
}
protected UserExample(UserExample example) {
this.orderByClause = example.orderByClause;
this.oredCriteria = example.oredCriteria;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
}
public String getTableName() {
return "apn_user";
}
/**
* 对应关联的表名为: apn_user
*/
public static class Criteria {
protected List<String> criteriaWithoutValue;
protected List<Map<String, Object>> criteriaWithSingleValue;
protected List<Map<String, Object>> criteriaWithListValue;
protected List<Map<String, Object>> criteriaWithBetweenValue;
protected Criteria() {
super();
criteriaWithoutValue = new ArrayList<String>();
criteriaWithSingleValue = new ArrayList<Map<String, Object>>();
criteriaWithListValue = new ArrayList<Map<String, Object>>();
criteriaWithBetweenValue = new ArrayList<Map<String, Object>>();
}
public boolean isValid() {
return criteriaWithoutValue.size() > 0
|| criteriaWithSingleValue.size() > 0
|| criteriaWithListValue.size() > 0
|| criteriaWithBetweenValue.size() > 0;
}
public List<String> getCriteriaWithoutValue() {
return criteriaWithoutValue;
}
public List<Map<String, Object>> getCriteriaWithSingleValue() {
return criteriaWithSingleValue;
}
public List<Map<String, Object>> getCriteriaWithListValue() {
return criteriaWithListValue;
}
public List<Map<String, Object>> getCriteriaWithBetweenValue() {
return criteriaWithBetweenValue;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteriaWithoutValue.add(condition);
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("condition", condition);
map.put("value", value);
criteriaWithSingleValue.add(map);
}
protected void addCriterion(String condition, List<? extends Object> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("condition", condition);
map.put("values", values);
criteriaWithListValue.add(map);
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
List<Object> list = new ArrayList<Object>();
list.add(value1);
list.add(value2);
Map<String, Object> map = new HashMap<String, Object>();
map.put("condition", condition);
map.put("values", list);
criteriaWithBetweenValue.add(map);
}
protected void addCriterionForJDBCDate(String condition, Date value, String property) {
addCriterion(condition, new java.sql.Date(value.getTime()), property);
}
protected void addCriterionForJDBCDate(String condition, List<Date> values, String property) {
if (values == null || values.size() == 0) {
throw new RuntimeException("Value list for " + property + " cannot be null or empty");
}
List<java.sql.Date> dateList = new ArrayList<java.sql.Date>();
Iterator<Date> iter = values.iterator();
while (iter.hasNext()) {
dateList.add(new java.sql.Date(iter.next().getTime()));
}
addCriterion(condition, dateList, property);
}
protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property);
}
public Criteria andUserIdIsNull() {
addCriterion("id is null");
return this;
}
public Criteria andUserIdIsNotNull() {
addCriterion("id is not null");
return this;
}
public Criteria andUserIdEqualTo(Integer value) {
addCriterion("id =", value, "userId");
return this;
}
public Criteria andUserIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "userId");
return this;
}
public Criteria andUserIdGreaterThan(Integer value) {
addCriterion("id >", value, "userId");
return this;
}
public Criteria andUserIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "userId");
return this;
}
public Criteria andUserIdLessThan(Integer value) {
addCriterion("id <", value, "userId");
return this;
}
public Criteria andUserIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "userId");
return this;
}
public Criteria andUserIdIn(List<Integer> values) {
addCriterion("id in", values, "userId");
return this;
}
public Criteria andUserIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "userId");
return this;
}
public Criteria andUserIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "userId");
return this;
}
public Criteria andUserIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "userId");
return this;
}
public Criteria andUserNameIsNull() {
addCriterion("username is null");
return this;
}
public Criteria andUserNameIsNotNull() {
addCriterion("username is not null");
return this;
}
public Criteria andUserNameEqualTo(String value) {
addCriterion("username =", value, "userName");
return this;
}
public Criteria andUserNameNotEqualTo(String value) {
addCriterion("username <>", value, "userName");
return this;
}
public Criteria andUserNameGreaterThan(String value) {
addCriterion("username >", value, "userName");
return this;
}
public Criteria andUserNameGreaterThanOrEqualTo(String value) {
addCriterion("username >=", value, "userName");
return this;
}
public Criteria andUserNameLessThan(String value) {
addCriterion("username <", value, "userName");
return this;
}
public Criteria andUserNameLessThanOrEqualTo(String value) {
addCriterion("username <=", value, "userName");
return this;
}
public Criteria andUserNameLike(String value) {
addCriterion("username like", value, "userName");
return this;
}
public Criteria andUserNameNotLike(String value) {
addCriterion("username not like", value, "userName");
return this;
}
public Criteria andUserNameIn(List<String> values) {
addCriterion("username in", values, "userName");
return this;
}
public Criteria andUserNameNotIn(List<String> values) {
addCriterion("username not in", values, "userName");
return this;
}
public Criteria andUserNameBetween(String value1, String value2) {
addCriterion("username between", value1, value2, "userName");
return this;
}
public Criteria andUserNameNotBetween(String value1, String value2) {
addCriterion("username not between", value1, value2, "userName");
return this;
}
public Criteria andPasswordIsNull() {
addCriterion("password is null");
return this;
}
public Criteria andPasswordIsNotNull() {
addCriterion("password is not null");
return this;
}
public Criteria andPasswordEqualTo(String value) {
addCriterion("password =", value, "password");
return this;
}
public Criteria andPasswordNotEqualTo(String value) {
addCriterion("password <>", value, "password");
return this;
}
public Criteria andPasswordGreaterThan(String value) {
addCriterion("password >", value, "password");
return this;
}
public Criteria andPasswordGreaterThanOrEqualTo(String value) {
addCriterion("password >=", value, "password");
return this;
}
public Criteria andPasswordLessThan(String value) {
addCriterion("password <", value, "password");
return this;
}
public Criteria andPasswordLessThanOrEqualTo(String value) {
addCriterion("password <=", value, "password");
return this;
}
public Criteria andPasswordLike(String value) {
addCriterion("password like", value, "password");
return this;
}
public Criteria andPasswordNotLike(String value) {
addCriterion("password not like", value, "password");
return this;
}
public Criteria andPasswordIn(List<String> values) {
addCriterion("password in", values, "password");
return this;
}
public Criteria andPasswordNotIn(List<String> values) {
addCriterion("password not in", values, "password");
return this;
}
public Criteria andPasswordBetween(String value1, String value2) {
addCriterion("password between", value1, value2, "password");
return this;
}
public Criteria andPasswordNotBetween(String value1, String value2) {
addCriterion("password not between", value1, value2, "password");
return this;
}
public Criteria andEmaliIsNull() {
addCriterion("email is null");
return this;
}
public Criteria andEmaliIsNotNull() {
addCriterion("email is not null");
return this;
}
public Criteria andEmaliEqualTo(String value) {
addCriterion("email =", value, "emali");
return this;
}
public Criteria andEmaliNotEqualTo(String value) {
addCriterion("email <>", value, "emali");
return this;
}
public Criteria andEmaliGreaterThan(String value) {
addCriterion("email >", value, "emali");
return this;
}
public Criteria andEmaliGreaterThanOrEqualTo(String value) {
addCriterion("email >=", value, "emali");
return this;
}
public Criteria andEmaliLessThan(String value) {
addCriterion("email <", value, "emali");
return this;
}
public Criteria andEmaliLessThanOrEqualTo(String value) {
addCriterion("email <=", value, "emali");
return this;
}
public Criteria andEmaliLike(String value) {
addCriterion("email like", value, "emali");
return this;
}
public Criteria andEmaliNotLike(String value) {
addCriterion("email not like", value, "emali");
return this;
}
public Criteria andEmaliIn(List<String> values) {
addCriterion("email in", values, "emali");
return this;
}
public Criteria andEmaliNotIn(List<String> values) {
addCriterion("email not in", values, "emali");
return this;
}
public Criteria andEmaliBetween(String value1, String value2) {
addCriterion("email between", value1, value2, "emali");
return this;
}
public Criteria andEmaliNotBetween(String value1, String value2) {
addCriterion("email not between", value1, value2, "emali");
return this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return this;
}
public Criteria andOnlineIsNull() {
addCriterion("online is null");
return this;
}
public Criteria andOnlineIsNotNull() {
addCriterion("online is not null");
return this;
}
public Criteria andOnlineEqualTo(Boolean value) {
addCriterion("online =", value, "online");
return this;
}
public Criteria andOnlineNotEqualTo(Boolean value) {
addCriterion("online <>", value, "online");
return this;
}
public Criteria andOnlineGreaterThan(Boolean value) {
addCriterion("online >", value, "online");
return this;
}
public Criteria andOnlineGreaterThanOrEqualTo(Boolean value) {
addCriterion("online >=", value, "online");
return this;
}
public Criteria andOnlineLessThan(Boolean value) {
addCriterion("online <", value, "online");
return this;
}
public Criteria andOnlineLessThanOrEqualTo(Boolean value) {
addCriterion("online <=", value, "online");
return this;
}
public Criteria andOnlineIn(List<Boolean> values) {
addCriterion("online in", values, "online");
return this;
}
public Criteria andOnlineNotIn(List<Boolean> values) {
addCriterion("online not in", values, "online");
return this;
}
public Criteria andOnlineBetween(Boolean value1, Boolean value2) {
addCriterion("online between", value1, value2, "online");
return this;
}
public Criteria andOnlineNotBetween(Boolean value1, Boolean value2) {
addCriterion("online not between", value1, value2, "online");
return this;
}
public Criteria andCreatedDateIsNull() {
addCriterion("created_date is null");
return this;
}
public Criteria andCreatedDateIsNotNull() {
addCriterion("created_date is not null");
return this;
}
public Criteria andCreatedDateEqualTo(Date value) {
addCriterionForJDBCDate("created_date =", value, "createdDate");
return this;
}
public Criteria andCreatedDateNotEqualTo(Date value) {
addCriterionForJDBCDate("created_date <>", value, "createdDate");
return this;
}
public Criteria andCreatedDateGreaterThan(Date value) {
addCriterionForJDBCDate("created_date >", value, "createdDate");
return this;
}
public Criteria andCreatedDateGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("created_date >=", value, "createdDate");
return this;
}
public Criteria andCreatedDateLessThan(Date value) {
addCriterionForJDBCDate("created_date <", value, "createdDate");
return this;
}
public Criteria andCreatedDateLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("created_date <=", value, "createdDate");
return this;
}
public Criteria andCreatedDateIn(List<Date> values) {
addCriterionForJDBCDate("created_date in", values, "createdDate");
return this;
}
public Criteria andCreatedDateNotIn(List<Date> values) {
addCriterionForJDBCDate("created_date not in", values, "createdDate");
return this;
}
public Criteria andCreatedDateBetween(Date value1, Date value2) {
addCriterionForJDBCDate("created_date between", value1, value2, "createdDate");
return this;
}
public Criteria andCreatedDateNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("created_date not between", value1, value2, "createdDate");
return this;
}
public Criteria andUpdatedDateIsNull() {
addCriterion("updated_date is null");
return this;
}
public Criteria andUpdatedDateIsNotNull() {
addCriterion("updated_date is not null");
return this;
}
public Criteria andUpdatedDateEqualTo(Date value) {
addCriterionForJDBCDate("updated_date =", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateNotEqualTo(Date value) {
addCriterionForJDBCDate("updated_date <>", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateGreaterThan(Date value) {
addCriterionForJDBCDate("updated_date >", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateGreaterThanOrEqualTo(Date value) {
addCriterionForJDBCDate("updated_date >=", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateLessThan(Date value) {
addCriterionForJDBCDate("updated_date <", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateLessThanOrEqualTo(Date value) {
addCriterionForJDBCDate("updated_date <=", value, "updatedDate");
return this;
}
public Criteria andUpdatedDateIn(List<Date> values) {
addCriterionForJDBCDate("updated_date in", values, "updatedDate");
return this;
}
public Criteria andUpdatedDateNotIn(List<Date> values) {
addCriterionForJDBCDate("updated_date not in", values, "updatedDate");
return this;
}
public Criteria andUpdatedDateBetween(Date value1, Date value2) {
addCriterionForJDBCDate("updated_date between", value1, value2, "updatedDate");
return this;
}
public Criteria andUpdatedDateNotBetween(Date value1, Date value2) {
addCriterionForJDBCDate("updated_date not between", value1, value2, "updatedDate");
return this;
}
}
} |
package com.zheng.thread.masterworker;
import java.util.Optional;
/**
* 进行立方运算
*
* @Author zhenglian
* @Date 2018/6/25 21:01
*/
public class PowerWorker extends Worker {
@Override
protected Object handle(Object obj) {
if (!Optional.ofNullable(obj).isPresent()) {
return null;
}
Integer num = Integer.parseInt(obj + "");
return num * num * num;
}
}
|
/*
* 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 model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
*
* @author Spike
*/
public class AuthorDao implements AuthorDaoStrategy {
private DbStrategy db;
private String driverClassName;
private String url;
private String userName;
private String password;
public AuthorDao(DbStrategy db, String driverClass, String url, String userName, String password) {
this.db = db;
this.driverClassName = driverClass;
this.url = url;
this.userName = userName;
this.password = password;
}
@Override
public List<Author> getAllAuthors() throws Exception {
db.openConnection(driverClassName, url, userName, password);
List<Author> records = new ArrayList<>();
List<Map<String,Object>> rawData = db.findAllRecords("author", 500);
for(Map rawRec : rawData) {
Author author = new Author();
Object obj = rawRec.get("author_id");
author.setAuthorId(Integer.parseInt(obj.toString()));
String name = rawRec.get("author_name") == null ? "" : rawRec.get("author_name").toString();
author.setAuthorName(name);
obj = rawRec.get("date_added");
Date dateAdded = (obj == null) ? new Date() : (Date)rawRec.get("date_added");
author.setDateAdded(dateAdded);
records.add(author);
}
db.closeConnection();
return records;
}
@Override
public void addAuthor(String name, Date date) throws Exception {
db.openConnection(driverClassName, url, userName, password);
ArrayList columns = new ArrayList();
columns.add("author_name");
columns.add("date_added");
ArrayList values = new ArrayList();
values.add(name);
values.add(date);
db.createRecord("author", columns, values);
db.closeConnection();
}
@Override
public void updateAuthor(Object key, String columnName, Object newObject) throws Exception {
db.openConnection(driverClassName, url, userName, password);
db.updateRecordByPrimaryKey("author", columnName, newObject, "author_id", key);
db.closeConnection();
}
@Override
public void deleteAuthor(Object key) throws Exception {
db.openConnection(driverClassName, url, userName, password);
db.deleteRecordByPK("author", "author_id", (int) key);
db.closeConnection();
}
}
|
/*
* 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 dictionary;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author listya
*/
public class SaveableDictionary {
private Map<String,String> dicts;
private String file;
public SaveableDictionary(String file) {
this.file = file;
this.dicts = new HashMap<>();
}
public SaveableDictionary() {
this.dicts = new HashMap<>();
}
public boolean load() {
try (Scanner scan = new Scanner(Paths.get(this.file))) {
String word;
String translate;
String[] arrays;
String read;
while (scan.hasNextLine()) {
read = scan.nextLine();
arrays = read.split(":");
word = arrays[0];
translate = arrays[1];
this.dicts.put(word,translate);
}
return true;
} catch (NullPointerException | IOException e) {
System.out.println("File doesn't exist");
return false;
}
}
public void add(String words, String translation) {
if (!this.dicts.containsKey(words)) {
this.dicts.put(words, translation);
}
}
public String translate(String word) {
Set<String> keys = this.dicts.keySet();
if(this.dicts.containsKey(word)) {
return this.dicts.get(word);
} else if (this.dicts.containsValue(word)) {
for (String letters : keys) {
if(this.dicts.get(letters).equals(word)) {
return letters;
}
}
}
return null;
}
public void delete(String word) {
String translation = translate(word);
this.dicts.remove(word);
this.dicts.remove(translation);
}
public boolean save() {
try {
try (PrintWriter writer = new PrintWriter(this.file)) {
for (Map.Entry<String,String> dict : this.dicts.entrySet()) {
writer.println(dict.getKey() + ":" + dict.getValue());
}
return true;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found");
return false;
}
}
}
|
package objetos.aeronaves.enemigos;
import java.util.ArrayList;
import movimiento.Posicion;
import objetos.aeronaves.FabricaAeronaves;
import ar.uba.fi.algo3.titiritero.ObjetoVivo;
/*
* Clase que modela un grupo de cazas enemigos.
* La cantidad de cazas en el grupo se setea cambiando cantidadCazas.
*/
public class GrupoCaza implements ObjetoVivo {
private ArrayList<Caza> cazas;
private final int cantidadCazas = 3;
public GrupoCaza() {
/* Se a�ade 1 por defecto */
this.cazas.add(FabricaAeronaves.crearCaza());
for (int i = 1; i < this.cantidadCazas; i++) {
this.cazas.add(FabricaAeronaves.crearCaza());
}
}
public GrupoCaza(Posicion posicion) {
this();
ubicarGrupo(posicion);
}
public GrupoCaza(int x, int y) {
this(new Posicion(x, y));
}
@Override
public void vivir() {
for (Caza caza : this.cazas) {
caza.vivir();
}
}
/*
* Ubica al grupo en forma de V, el primero en la posicion dada y el resto
* detras de el en formacion.
*/
public void ubicarGrupo(Posicion posicionLider) {
Caza lider = this.cazas.get(0);
lider.setPosicion(posicionLider);
Caza caza;
for (int i = 1; i < this.cantidadCazas; i++) {
caza = this.cazas.get(i);
int x = lider.getPosicion().getEnX();
int y = lider.getPosicion().getEnY();
if (i % 2 == 0) {
/* Los pares se ubican a la derecha */
x += 2 * i;
y -= 2 * i;
} else {
/* Los impares a la izquierda */
x -= 2 * (i + 1);
y -= 2 * (i + 1);
}
caza.setPosicion(new Posicion(x, y));
}
}
}
|
package com.project.services.distributionstrategies;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import com.project.entities.Order;
import com.project.entities.OrderStatus;
import com.project.entities.User;
//take the courier found in the same city as the order, with the least orders
//that were not yet delivered
public class LeastOrdersinCityStrategy implements DistributionStrategy {
@Override
public User selectCourier(Order order, List<User> couriers) {
return couriers.stream().filter(x -> x.getAddress().getCity().equals(order.getAddress().getCity()))
.sorted(Comparator.comparing((User x) -> x.getCourierOrders().stream()
.filter(y -> y.getStatus().equals(OrderStatus.PROCESSING)).collect(Collectors.toList()).size(),
Comparator.reverseOrder()))
.findFirst().orElse(null);
}
}
|
package com.xys.car.controller;
import com.xys.car.entity.Brand;
import com.xys.car.entity.RootEntity;
import com.xys.car.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author zxm
* @since 2020-12-04
*/
@RestController
@RequestMapping("/brand/")
public class BrandController {
@Autowired
private IBrandService iBrandService;
@PostMapping("selectBrand")
private RootEntity selectBrand(@RequestBody Brand brand){
return iBrandService.selectBrand(brand);
}
@PostMapping("updateBrand")
private RootEntity updateBrand(@RequestBody Brand brand){
return iBrandService.updateBrand(brand);
}
@PostMapping("deleteBrand")
private RootEntity deleteBrand(@RequestBody Brand brand){
return iBrandService.deleteBrand(brand);
}
@PostMapping("insertBrand")
private RootEntity insertBrand(@RequestBody Brand brand){
return iBrandService.insertBrand(brand);
}
}
|
package com.union.express.web.freightrates.service;
import com.union.express.commons.query.BaseJpaService;
import com.union.express.web.freightrates.dao.ValueAddedServiceRepository;
import com.union.express.web.freightrates.model.ValueAddedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by Administrator on 2016/11/18 0018.
* 增值服务
*/
@Service
@Transactional
public class ValueAddedServiceService extends BaseJpaService<ValueAddedService, ValueAddedServiceRepository> {
@Autowired
ValueAddedServiceRepository valueAddedServiceRepository;
public void updateById( String id,int code,String value){
valueAddedServiceRepository.updatebyid(id,code,value) ;
}
}
|
package com.bwie.juan_mao.jingdong_kanglijuan;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.ImageView;
import com.bwie.juan_mao.jingdong_kanglijuan.base.BaseActivity;
import com.bwie.juan_mao.jingdong_kanglijuan.base.BasePresenter;
import com.bwie.juan_mao.jingdong_kanglijuan.fragment.CartFragment;
import com.bwie.juan_mao.jingdong_kanglijuan.fragment.ClassifyFragment;
import com.bwie.juan_mao.jingdong_kanglijuan.fragment.FindFragment;
import com.bwie.juan_mao.jingdong_kanglijuan.fragment.HomeFragment;
import com.bwie.juan_mao.jingdong_kanglijuan.fragment.MineFragment;
import butterknife.BindView;
import butterknife.OnClick;
public class HomeActivity extends BaseActivity {
@BindView(R.id.txt_home)
ImageView txtHome;
@BindView(R.id.txt_classify)
ImageView txtClassify;
@BindView(R.id.txt_find)
ImageView txtFind;
@BindView(R.id.txt_shop)
ImageView txtShop;
@BindView(R.id.txt_mine)
ImageView txtMine;
private HomeFragment homeFrag;
private ClassifyFragment classifyFrag;
private CartFragment cartFrag;
private MineFragment mineFrag;
private FindFragment findFrag;
private FragmentManager manager;
@Override
protected void initData() {
homeFrag = new HomeFragment();
classifyFrag = new ClassifyFragment();
cartFrag = new CartFragment();
mineFrag = new MineFragment();
findFrag = new FindFragment();
manager = getSupportFragmentManager();
manager.beginTransaction()
.replace(R.id.content, homeFrag)
.commit();
}
@Override
protected BasePresenter providePresenter() {
return null;
}
@Override
protected int provideLayoutId() {
return R.layout.activity_home;
}
@Override
public Context getContext() {
return this;
}
@OnClick({R.id.txt_home, R.id.txt_classify, R.id.txt_find, R.id.txt_shop, R.id.txt_mine})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.txt_home:
manager.beginTransaction()
.replace(R.id.content, homeFrag)
.commit();
changeBackground(0);
break;
case R.id.txt_classify:
manager.beginTransaction()
.replace(R.id.content, classifyFrag)
.commit();
changeBackground(1);
break;
case R.id.txt_find:
manager.beginTransaction()
.replace(R.id.content, findFrag)
.commit();
changeBackground(2);
break;
case R.id.txt_shop:
manager.beginTransaction()
.replace(R.id.content, cartFrag)
.commit();
changeBackground(3);
break;
case R.id.txt_mine:
manager.beginTransaction()
.replace(R.id.content, mineFrag)
.commit();
changeBackground(4);
break;
}
}
private void changeBackground(int index) {
txtHome.setImageResource(index == 0 ? R.drawable.ac1 : R.drawable.ac0);
txtClassify.setImageResource(index == 1 ? R.drawable.abx : R.drawable.abw);
txtFind.setImageResource(index == 2 ? R.drawable.abz : R.drawable.aby);
txtShop.setImageResource(index == 3 ? R.drawable.abv : R.drawable.abu);
txtMine.setImageResource(index == 4 ? R.drawable.ac3 : R.drawable.ac2);
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import org.jooq.types.UInteger;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.WikiArticleforobjectRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class WikiArticleforobject extends TableImpl<WikiArticleforobjectRecord> {
private static final long serialVersionUID = 1917384708;
/**
* The reference instance of <code>bitnami_edx.wiki_articleforobject</code>
*/
public static final WikiArticleforobject WIKI_ARTICLEFOROBJECT = new WikiArticleforobject();
/**
* The class holding records for this type
*/
@Override
public Class<WikiArticleforobjectRecord> getRecordType() {
return WikiArticleforobjectRecord.class;
}
/**
* The column <code>bitnami_edx.wiki_articleforobject.id</code>.
*/
public final TableField<WikiArticleforobjectRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.wiki_articleforobject.object_id</code>.
*/
public final TableField<WikiArticleforobjectRecord, UInteger> OBJECT_ID = createField("object_id", org.jooq.impl.SQLDataType.INTEGERUNSIGNED.nullable(false), this, "");
/**
* The column <code>bitnami_edx.wiki_articleforobject.is_mptt</code>.
*/
public final TableField<WikiArticleforobjectRecord, Byte> IS_MPTT = createField("is_mptt", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "");
/**
* The column <code>bitnami_edx.wiki_articleforobject.article_id</code>.
*/
public final TableField<WikiArticleforobjectRecord, Integer> ARTICLE_ID = createField("article_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.wiki_articleforobject.content_type_id</code>.
*/
public final TableField<WikiArticleforobjectRecord, Integer> CONTENT_TYPE_ID = createField("content_type_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>bitnami_edx.wiki_articleforobject</code> table reference
*/
public WikiArticleforobject() {
this("wiki_articleforobject", null);
}
/**
* Create an aliased <code>bitnami_edx.wiki_articleforobject</code> table reference
*/
public WikiArticleforobject(String alias) {
this(alias, WIKI_ARTICLEFOROBJECT);
}
private WikiArticleforobject(String alias, Table<WikiArticleforobjectRecord> aliased) {
this(alias, aliased, null);
}
private WikiArticleforobject(String alias, Table<WikiArticleforobjectRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<WikiArticleforobjectRecord, Integer> getIdentity() {
return Keys.IDENTITY_WIKI_ARTICLEFOROBJECT;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<WikiArticleforobjectRecord> getPrimaryKey() {
return Keys.KEY_WIKI_ARTICLEFOROBJECT_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<WikiArticleforobjectRecord>> getKeys() {
return Arrays.<UniqueKey<WikiArticleforobjectRecord>>asList(Keys.KEY_WIKI_ARTICLEFOROBJECT_PRIMARY, Keys.KEY_WIKI_ARTICLEFOROBJECT_WIKI_ARTICLEFOROBJECT_CONTENT_TYPE_ID_27C4CCE189B3BCAB_UNIQ);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<WikiArticleforobjectRecord, ?>> getReferences() {
return Arrays.<ForeignKey<WikiArticleforobjectRecord, ?>>asList(Keys.WIKI_ARTICLEFOROBJ_ARTICLE_ID_6EFFCFADF020E71_FK_WIKI_ARTICLE_ID, Keys.WIKI__CONTENT_TYPE_ID_6A39C68B7A20C3C4_FK_DJANGO_CONTENT_TYPE_ID);
}
/**
* {@inheritDoc}
*/
@Override
public WikiArticleforobject as(String alias) {
return new WikiArticleforobject(alias, this);
}
/**
* Rename this table
*/
public WikiArticleforobject rename(String name) {
return new WikiArticleforobject(name, null);
}
}
|
package com.datalinks.restwsexample.services;
import static org.junit.Assert.*;
import javax.ws.rs.core.MediaType;
import org.junit.Test;
import com.sun.jersey.api.client.Client;
public class HelloWorldServiceTest {
private static String TST_URL = "http://localhost:9090/RestWSExample/rest/hello/chris";
@Test
public void testGetMsg() {
String serviceResponse = Client.create().resource(TST_URL).accept(MediaType.TEXT_PLAIN).get(String.class);
String expectedResponse = "Jersey responds with: hello chris";
assertTrue("Expected Value: "+expectedResponse+" actual value: "+serviceResponse, serviceResponse.equals(expectedResponse));
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Arrays;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* A simple key as returned from the {@link SimpleKeyGenerator}.
*
* @author Phillip Webb
* @author Juergen Hoeller
* @since 4.0
* @see SimpleKeyGenerator
*/
@SuppressWarnings("serial")
public class SimpleKey implements Serializable {
/**
* An empty key.
*/
public static final SimpleKey EMPTY = new SimpleKey();
private final Object[] params;
// Effectively final, just re-calculated on deserialization
private transient int hashCode;
/**
* Create a new {@link SimpleKey} instance.
* @param elements the elements of the key
*/
public SimpleKey(Object... elements) {
Assert.notNull(elements, "Elements must not be null");
this.params = elements.clone();
// Pre-calculate hashCode field
this.hashCode = Arrays.deepHashCode(this.params);
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof SimpleKey that && Arrays.deepEquals(this.params, that.params)));
}
@Override
public final int hashCode() {
// Expose pre-calculated hashCode field
return this.hashCode;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + Arrays.deepToString(this.params);
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
// Re-calculate hashCode field on deserialization
this.hashCode = Arrays.deepHashCode(this.params);
}
}
|
package mockito;
import java.util.ArrayList;
import java.util.List;
public class MockIns {
public List<String> getList(String name, int age) {
// do something code
return new ArrayList<>();
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.connector.intellij.bamboo;
import com.atlassian.connector.commons.api.ConnectionCfg;
import com.atlassian.theplugin.commons.bamboo.BambooBuildInfo;
import com.atlassian.theplugin.commons.bamboo.BambooServerData;
import com.atlassian.theplugin.commons.bamboo.BuildStatus;
import com.atlassian.theplugin.commons.cfg.BambooServerCfg;
import com.atlassian.theplugin.commons.cfg.ServerIdImpl;
import com.atlassian.theplugin.commons.cfg.UserCfg;
import com.atlassian.theplugin.commons.configuration.BambooConfigurationBean;
import com.atlassian.theplugin.commons.configuration.BambooTooltipOption;
import com.atlassian.theplugin.commons.configuration.PluginConfigurationBean;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import static org.easymock.EasyMock.createStrictMock;
/**
* @author Jacek Jaroczynski
*/
public class BambooStatusListenerOnlyMyBuildsTest extends TestCase {
private BambooStatusDisplay displayMock;
private BambooStatusTooltipListener tooltipListener;
private static final String DEFAULT_PLAN_KEY = "PL-DEF";
private static final String DEFAULT_BUILD_NAME = "Build";
private static final String DEFAULT_PROJECT_NAME = "Project";
private static final String DEFAULT_ERROR_MESSAGE = "Error message";
private static final HashSet<String> COMMITERS = new HashSet<String>(Arrays.asList("jjaroczynski", "unknown"));
private static final String LOGGED_USER_JJ = "jjaroczynski";
private static final String LOGGED_USER_US = "user";
private static final String LOGGED_USER_UN = "unknown";
private PluginConfigurationBean conf;
private BambooConfigurationBean bean;
@Override
protected void setUp() throws Exception {
super.setUp();
displayMock = createStrictMock(BambooStatusDisplay.class);
conf = new PluginConfigurationBean();
bean = new BambooConfigurationBean();
conf.setBambooConfigurationData(bean);
bean.setBambooTooltipOption(BambooTooltipOption.ALL_FAULIRES_AND_FIRST_SUCCESS);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
displayMock = null;
tooltipListener = null;
}
public void testOnlyMyOn() {
bean.setOnlyMyBuilds(true);
tooltipListener = new BambooStatusTooltipListener(displayMock, conf);
BambooBuildAdapter buildOK_JJ = generateBuildInfo(BuildStatus.SUCCESS, 1, LOGGED_USER_JJ);
BambooBuildAdapter buildFail_JJ = generateBuildInfo(BuildStatus.FAILURE, 2, LOGGED_USER_JJ);
BambooBuildAdapter buildFail_US = generateBuildInfo(BuildStatus.FAILURE, 3, LOGGED_USER_US);
BambooBuildAdapter buildOK_US = generateBuildInfo(BuildStatus.SUCCESS, 4, LOGGED_USER_US);
BambooBuildAdapter buildFail_UN = generateBuildInfo(BuildStatus.FAILURE, 5, LOGGED_USER_UN);
BambooBuildAdapter buildOK_UN = generateBuildInfo(BuildStatus.SUCCESS, 6, LOGGED_USER_UN);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), EasyMock.isA(BambooPopupInfo.class));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_JJ), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_JJ), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_US), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_UN), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_UN), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_US), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_US), null);
}
public void testOnlyMyOff() {
bean.setOnlyMyBuilds(false);
tooltipListener = new BambooStatusTooltipListener(displayMock, conf);
BambooBuildAdapter buildOK_JJ = generateBuildInfo(BuildStatus.SUCCESS, 1, LOGGED_USER_JJ);
BambooBuildAdapter buildFail_JJ = generateBuildInfo(BuildStatus.FAILURE, 2, LOGGED_USER_JJ);
BambooBuildAdapter buildFail_US = generateBuildInfo(BuildStatus.FAILURE, 3, LOGGED_USER_US);
BambooBuildAdapter buildOK_US = generateBuildInfo(BuildStatus.SUCCESS, 4, LOGGED_USER_US);
BambooBuildAdapter buildFail_UN = generateBuildInfo(BuildStatus.FAILURE, 5, LOGGED_USER_UN);
BambooBuildAdapter buildOK_UN = generateBuildInfo(BuildStatus.SUCCESS, 6, LOGGED_USER_UN);
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.FAILURE), EasyMock.isA(BambooPopupInfo.class));
displayMock.updateBambooStatus(EasyMock.eq(BuildStatus.SUCCESS), EasyMock.isA(BambooPopupInfo.class));
EasyMock.replay(displayMock);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_JJ), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_JJ), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_US), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_UN), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_UN), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildFail_US), null);
tooltipListener.updateBuildStatuses(Arrays.asList(buildOK_US), null);
}
public static BambooBuildAdapter generateBuildInfo(BuildStatus status, int buildNumber, String loggedUser) {
BambooBuildInfo.Builder builder =
new BambooBuildInfo.Builder(DEFAULT_PLAN_KEY, DEFAULT_BUILD_NAME,
new ConnectionCfg("name", "", loggedUser, ""),
DEFAULT_PROJECT_NAME, buildNumber, status).enabled(true).commiters(COMMITERS);
switch (status) {
case UNKNOWN:
builder.errorMessage(DEFAULT_ERROR_MESSAGE);
break;
case SUCCESS:
builder.startTime(new Date());
break;
case FAILURE:
builder.startTime(new Date());
break;
}
return new BambooBuildAdapter(builder.build(), new BambooServerData(new BambooServerCfg(true, "mybamboo",
new ServerIdImpl()), new UserCfg("", "")));
}
}
|
package com.naruto.demo.dao;
import java.util.List;
import com.naruto.demo.model.Student;
public interface StudentDao {
public void add(final Student student);
public void edit(final Student student);
public void delete(final Student student);
public Student getStudent(final int studentId);
public List<Student> getAllStudents();
}
|
package com.example.daraz_application.Prevalent;
import com.example.daraz_application.Model.Users;
public class Prevalent {
// From this class we will be working on the forget password
// Remember me
// Type of features
// This package is created to get the current user who are using the app
private static Users currentOnlineUser;
// The below code is written to store the user phone i.e. the unqiue key to use this app contains all information of the user
public static final String UserPhoneKey = "UserPhone";
public static final String UserPasswordKey = "UserPassword";
}
|
package org.sky.sys.model;
public class SysArea {
private String id;
private String name;
private String pid;
private String disorder;
private String procode;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getDisorder() {
return disorder;
}
public void setDisorder(String disorder) {
this.disorder = disorder;
}
public String getProcode() {
return procode;
}
public void setProcode(String procode) {
this.procode = procode;
}
} |
package com._520it.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
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 com._520it.service.ProductService;
import net.sf.json.JSONArray;
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//接收数据
String pname = request.getParameter("word");
//传递数据和请求
ProductService service =new ProductService();
List<Object> pnameList = service.search(pname);
//解决中文乱码
response.setContentType("text/html;charset=utf-8");
//
JSONArray pnames = JSONArray.fromObject(pnameList);
String pString = pnames.toString();
System.out.println(pString);
response.getWriter().write(pString);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
} |
package am.bizis.stspr.po;
import am.bizis.stspr.IC;
import am.bizis.stspr.IPodnik;
import am.bizis.stspr.OsobaTyp;
import am.bizis.stspr.fo.Adresa;
public class Podnik implements IPodnik {
public Podnik() {
// TODO Auto-generated constructor stub
}
@Override
public IC getIC() {
// TODO Auto-generated method stub
return null;
}
@Override
public long getDIC() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getJmeno() {
// TODO Auto-generated method stub
return null;
}
@Override
public OsobaTyp getTyp() {
return OsobaTyp.PO;
}
@Override
public String getEmail() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getTelefon() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getFax() {
return 0;
}
@Override
public Adresa getAdresa() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.nfet.icare.pojo;
//延保上门套餐数量
public class WarrantyCount {
private String name;
private int value;
private String payAmts;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getPayAmts() {
return payAmts;
}
public void setPayAmts(String payAmts) {
this.payAmts = payAmts;
}
}
|
package com.kc.springmicroservice.employeeservice.exception;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import com.kc.springmicroservice.employeeservice.EmployeeNotFoundException;
@RestControllerAdvice
public class RestExceptionHandler {
private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RestExceptionHandler.class);
@ExceptionHandler(BindException.class)
public ResponseEntity<ExceptionResponse> handleBindException(BindException ex, WebRequest webRequest) {
logger.error("Entered Bind violation");
StringBuilder errorMessage = new StringBuilder();
ex.getAllErrors().forEach(error -> errorMessage.append(error.getDefaultMessage()+"."));
return new ResponseEntity<ExceptionResponse>(ExceptionResponse.builder().timeStamp(new Date()).message(errorMessage.toString()).uri(webRequest.getDescription(false)).build(), HttpStatus.BAD_REQUEST);
}
public ResponseEntity<ExceptionResponse> handleEmployeeNotFoundException(EmployeeNotFoundException ex,
WebRequest webRequest) {
logger.error("Entered EmployeeNotFoundException");
return new ResponseEntity<ExceptionResponse>(
ExceptionResponse.builder().timeStamp(new Date()).message(ex.getMessage())
.details(webRequest.getDescription(false)).uri(webRequest.getDescription(false)).build(),
HttpStatus.BAD_REQUEST);
}
}
|
package com.stanislavmachel.shop.services;
import com.stanislavmachel.shop.api.v1.mappers.CustomerMapper;
import com.stanislavmachel.shop.api.v1.model.CustomerDto;
import com.stanislavmachel.shop.domain.Customer;
import com.stanislavmachel.shop.repositories.CustomerRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
public class CustomerServiceImplTest {
private static final String API_V1_CUSTOMERS_URL = "/api/v1/customers/";
@Mock
CustomerRepository customerRepository;
private CustomerService customerService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
customerService = new CustomerServiceImpl(customerRepository, CustomerMapper.INSTANCE);
}
@Test
public void getAll() {
List<Customer> customers = Arrays.asList(new Customer(), new Customer(), new Customer());
when(customerRepository.findAll()).thenReturn(customers);
assertEquals(3, customerService.getAll().size());
}
@Test
public void getCustomerById() {
UUID id = UUID.randomUUID();
String firstName = "John";
String lastName = "Snow";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName(firstName);
customer.setLastName(lastName);
when(customerRepository.findById(id)).thenReturn(Optional.of(customer));
CustomerDto customerDto = customerService.getById(id);
assertNotNull(customerDto);
assertEquals(firstName, customerDto.getFirstName());
assertEquals(lastName, customerDto.getLastName());
assertEquals(API_V1_CUSTOMERS_URL + id, customerDto.getUrl());
}
@Test
public void create() {
UUID id = UUID.randomUUID();
String firstName = "John";
String lastName = "Snow";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName(firstName);
customer.setLastName(lastName);
CustomerDto customerDtoToCreate = new CustomerDto();
customerDtoToCreate.setFirstName(firstName);
customerDtoToCreate.setLastName(lastName);
when(customerRepository.save(any(Customer.class))).thenReturn(customer);
CustomerDto createdCustomerDto = customerService.create(customerDtoToCreate);
assertEquals(firstName, createdCustomerDto.getFirstName());
assertEquals(lastName, createdCustomerDto.getLastName());
assertEquals(API_V1_CUSTOMERS_URL + id, createdCustomerDto.getUrl());
}
private void fakeCustomers() {
UUID customer1Id = UUID.randomUUID();
Customer customer1 = new Customer();
customer1.setId(customer1Id);
customer1.setFirstName("John");
customer1.setLastName("Snow");
UUID customer2Id = UUID.randomUUID();
Customer customer2 = new Customer();
customer2.setId(customer2Id);
customer2.setFirstName("Arya");
customer2.setLastName("Stark");
UUID customer3Id = UUID.randomUUID();
Customer customer3 = new Customer();
customer3.setId(customer3Id);
customer3.setFirstName("Tyrion");
customer3.setLastName("Lannister");
}
@Test
public void updateExistingCustomer() {
UUID id = UUID.randomUUID();
String newFirsName = "NewFirsName";
String newLastName = "NewLastName";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName("OldFirsName");
customer.setLastName("OldLastName");
when(customerRepository.findById(id)).thenReturn(Optional.of(customer));
Customer updatedCustomer = new Customer();
updatedCustomer.setId(id);
updatedCustomer.setFirstName(newFirsName);
updatedCustomer.setLastName(newLastName);
when(customerRepository.save(any(Customer.class))).thenReturn(updatedCustomer);
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstName(newFirsName);
customerDto.setLastName(newLastName);
CustomerDto updatedCustomerDto = customerService.update(id, customerDto);
assertEquals(newFirsName, updatedCustomerDto.getFirstName());
assertEquals(newLastName, updatedCustomerDto.getLastName());
assertEquals(API_V1_CUSTOMERS_URL + id, updatedCustomerDto.getUrl());
}
@Test(expected = ResourceNotFoundException.class)
public void updateIfCustomerNotExist() {
when(customerRepository.findById(any(UUID.class))).thenReturn(Optional.empty());
customerService.update(UUID.randomUUID(), new CustomerDto());
}
@Test
public void patchWhenOnlyFirstNameUpdated() {
UUID id = UUID.randomUUID();
String oldFirsName = "Old firstname";
String oldLastName = "Old lastname";
String newFirstName = "New firstname";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName(oldFirsName);
customer.setLastName(oldLastName);
when(customerRepository.findById(argThat(argument -> argument.equals(id)))).thenReturn(Optional.of(customer));
Customer updatedCustomer = new Customer();
updatedCustomer.setId(id);
updatedCustomer.setFirstName(newFirstName);
updatedCustomer.setLastName(oldLastName);
when(customerRepository.save(
argThat(argument ->
argument.getId().equals(updatedCustomer.getId()) &&
argument.getFirstName().equals(updatedCustomer.getFirstName()) &&
argument.getLastName().equals(updatedCustomer.getLastName())))).thenReturn(updatedCustomer);
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstName(newFirstName);
customerDto.setLastName(oldLastName);
CustomerDto newCustomerDto = customerService.patch(id, customerDto);
assertEquals(newFirstName, newCustomerDto.getFirstName());
assertEquals(oldLastName, newCustomerDto.getLastName());
}
@Test
public void patchIfOnlyLastnameUpdated() {
UUID id = UUID.randomUUID();
String oldFirsName = "Old firstname";
String oldLastName = "Old lastname";
String newLastName = "New lastname";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName(oldFirsName);
customer.setLastName(oldLastName);
when(customerRepository.findById(argThat(argument -> argument.equals(id)))).thenReturn(Optional.of(customer));
Customer updatedCustomer = new Customer();
updatedCustomer.setId(id);
updatedCustomer.setFirstName(oldFirsName);
updatedCustomer.setLastName(newLastName);
when(customerRepository.save(
argThat(argument ->
argument.getId().equals(updatedCustomer.getId()) &&
argument.getFirstName().equals(updatedCustomer.getFirstName()) &&
argument.getLastName().equals(updatedCustomer.getLastName())))).thenReturn(updatedCustomer);
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstName(oldFirsName);
customerDto.setLastName(newLastName);
CustomerDto newCustomerDto = customerService.patch(id, customerDto);
assertEquals(oldFirsName, newCustomerDto.getFirstName());
assertEquals(newLastName, newCustomerDto.getLastName());
}
@Test
public void patchIfFirstnameAndLastnameUpdated() {
UUID id = UUID.randomUUID();
String oldFirsName = "Old firstname";
String oldLastName = "Old lastname";
String newFirstName = "New firstname";
String newLastName = "New lastname";
Customer customer = new Customer();
customer.setId(id);
customer.setFirstName(oldFirsName);
customer.setLastName(oldLastName);
when(customerRepository.findById(argThat(argument -> argument.equals(id)))).thenReturn(Optional.of(customer));
Customer updatedCustomer = new Customer();
updatedCustomer.setId(id);
updatedCustomer.setFirstName(newFirstName);
updatedCustomer.setLastName(newLastName);
when(customerRepository.save(
argThat(argument ->
argument.getId().equals(updatedCustomer.getId()) &&
argument.getFirstName().equals(updatedCustomer.getFirstName()) &&
argument.getLastName().equals(updatedCustomer.getLastName())))).thenReturn(updatedCustomer);
CustomerDto customerDto = new CustomerDto();
customerDto.setFirstName(newFirstName);
customerDto.setLastName(newLastName);
CustomerDto newCustomerDto = customerService.patch(id, customerDto);
assertEquals(newFirstName, newCustomerDto.getFirstName());
assertEquals(newLastName, newCustomerDto.getLastName());
}
@Test
public void deleteById() {
customerService.deleteById(UUID.randomUUID());
verify(customerRepository, times(1)).deleteById(any(UUID.class));
}
} |
/*
* Dados dois vetores A e B de mesma dimensão, fazer um programa que calcule e
* imprima o produto de cada elemento de A pelo correspondente elemento de B.
* O resultado deve ser armazenado em um vetor C.
*/
package Lista4;
import AP03_04.Exercico7;
import java.util.Scanner;
public class Exercicio9 {
static Scanner input = new Scanner (System.in);
static int[] produtoVetores(int []vetorA, int []vetorB, int tamanho){
int []vetorC=Exercicio1.vetor(tamanho);
for(int i=0;i<tamanho;i++){
vetorC[i]=vetorA[i] * vetorB[i];
}
return vetorC;
}
public static void main(String[] args) {
System.out.print("tamanho vetor: ");
int tamanho=Exercicio1.entrada();
int []vetorA=Exercicio1.vetor(tamanho);
int []vetorB=Exercicio1.vetor(tamanho);
System.out.println("Vetor A");
vetorA=Exercicio1.populaVetor(vetorA);
System.out.println("Vetor B");
vetorB=Exercicio1.populaVetor(vetorB);
int []vetorC=produtoVetores(vetorA, vetorB, tamanho);
Exercicio1.imprimirVetor(vetorC);
}
}
|
package com.netcracker.app.domain.tariffs.services;
import com.netcracker.app.domain.tariffs.repositories.TariffRepository;
import com.netcracker.app.domain.tariffs.entities.Tariff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public abstract class AbstractTariffService<E extends Tariff> implements TariffService<E> {
}
|
package com.cninnovatel.ev.db;
import com.cninnovatel.ev.db.DaoSession;
import de.greenrobot.dao.DaoException;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
* Entity mapped to table "MEETING_USER_".
*/
public class MeetingUser_ {
private Long id;
private Long meetingId;
private Long userId;
/** Used to resolve relations */
private transient DaoSession daoSession;
/** Used for active entity operations. */
private transient MeetingUser_Dao myDao;
private RestUser_ user;
private Long user__resolvedKey;
private RestMeeting_ meeting;
private Long meeting__resolvedKey;
public MeetingUser_() {
}
public MeetingUser_(Long id) {
this.id = id;
}
public MeetingUser_(Long id, Long meetingId, Long userId) {
this.id = id;
this.meetingId = meetingId;
this.userId = userId;
}
/** called by internal mechanisms, do not call yourself. */
public void __setDaoSession(DaoSession daoSession) {
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getMeetingUser_Dao() : null;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMeetingId() {
return meetingId;
}
public void setMeetingId(Long meetingId) {
this.meetingId = meetingId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
/** To-one relationship, resolved on first access. */
public RestUser_ getUser() {
Long __key = this.userId;
if (user__resolvedKey == null || !user__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
RestUser_Dao targetDao = daoSession.getRestUser_Dao();
RestUser_ userNew = targetDao.load(__key);
synchronized (this) {
user = userNew;
user__resolvedKey = __key;
}
}
return user;
}
public void setUser(RestUser_ user) {
synchronized (this) {
this.user = user;
userId = user == null ? null : user.getId();
user__resolvedKey = userId;
}
}
/** To-one relationship, resolved on first access. */
public RestMeeting_ getMeeting() {
Long __key = this.meetingId;
if (meeting__resolvedKey == null || !meeting__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
RestMeeting_Dao targetDao = daoSession.getRestMeeting_Dao();
RestMeeting_ meetingNew = targetDao.load(__key);
synchronized (this) {
meeting = meetingNew;
meeting__resolvedKey = __key;
}
}
return meeting;
}
public void setMeeting(RestMeeting_ meeting) {
synchronized (this) {
this.meeting = meeting;
meetingId = meeting == null ? null : meeting.getId();
meeting__resolvedKey = meetingId;
}
}
/** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
public void delete() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.delete(this);
}
/** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
public void update() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.update(this);
}
/** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
public void refresh() {
if (myDao == null) {
throw new DaoException("Entity is detached from DAO context");
}
myDao.refresh(this);
}
}
|
package kr.co.ca;
import java.util.List;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import kr.co.dao.BoardDAO;
import kr.co.dao.ReplyDAO;
import kr.co.domain.BoardVO;
import kr.co.domain.ReplyVO;
import kr.co.domain.SearchCriteria;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"file:src/main/webapp/WEB-INF/spring/**/*.xml"})
public class ReplyDAOTest {
@Inject
private ReplyDAO dao;
@Test
public void testinsert() {
// TODO Auto-generated method stub
/*
* Integer rno = createRno();
*
* if(rno == null) { rno = 1; } else { rno++; }
*
* vo.setRno(rno);
*
* session.insert(NS+".insert", vo);
*/
ReplyVO vo = new ReplyVO(1, 156, "성공?", "나야나", null, null);
dao.insert(vo);
}
@Test
public void testlist() {
List<ReplyVO>list = dao.list(156);
for(ReplyVO vo : list) {
System.out.println(vo);
}
}
@Test
public void testupdate() {
ReplyVO vo = new ReplyVO(1, 156, "성공?", "나야나", null, null);
dao.update(vo);
}
@Test
public void testdelete() {
int rno = 17;
dao.delete(rno);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.