blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
980aadf769d038e9af1650e7264d4fda9da5e548 | dc1dbb7e5a4b95bf44170d2f51fd08b3814f2ac9 | /data_defect4j/preprossed_method_corpus/Math/82/org/apache/commons/math/complex/ComplexFormat_getAvailableLocales_121.java | 0139cf7d7696148a741405d3aa36e89e7ad0f645 | [] | no_license | hvdthong/NetML | dca6cf4d34c5799b400d718e0a6cd2e0b167297d | 9bb103da21327912e5a29cbf9be9ff4d058731a5 | refs/heads/master | 2021-06-30T15:03:52.618255 | 2020-10-07T01:58:48 | 2020-10-07T01:58:48 | 150,383,588 | 1 | 1 | null | 2018-09-26T07:08:45 | 2018-09-26T07:08:44 | null | UTF-8 | Java | false | false | 777 | java |
org apach common math complex
format complex number cartesian format 'i'
replac 'j' number format real
imaginari part configur
author apach softwar foundat
version revis date
complex format complexformat composit format compositeformat
set local complex format
set link number format numberformat set
complex format local
local local getavailablelocal
number format numberformat local getavailablelocal
| [
"hvdthong@gmail.com"
] | hvdthong@gmail.com |
a399c8efd18141a56ab4f7246df819c7e656d949 | 98ce1ef6d0dabbdc787147c1f5f3debcdf09d015 | /BackEnd.java | 1594869dec62ce477be2478363cc6b5d9ad419e4 | [] | no_license | quintesc/Duva-Bakery | 62500bf656b72557b0e30241b3ce2dedbae9d7e5 | bbf3f7f84414011af066240a3bcfc5ce22d806eb | refs/heads/main | 2023-09-05T05:03:48.367968 | 2021-11-15T02:29:29 | 2021-11-15T02:29:29 | 428,094,248 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,503 | java | import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.function.*;
import java.util.NoSuchElementException;
/**
* Interfaces front end with the hashtables where data is stored
* @author Andres Quintanal Escandon
*/
public class BackEnd {
// key is client firstName + " " + lastName, value is client
private static HashTableMap<String, Client> clients = new HashTableMap<>();
// key is order number, value is order
// i know i could just use an array but I wanna feel cool ok?
private static HashTableMap<Integer, Order> orders = new HashTableMap<>();
/**
* Main, calls the main menu and the save/load operations
*/
public static void main(String[] args) {
Order.nextOrderNumber = 0;
load("data.txt");
FrontEnd.mainMenu(); // goes to front end, and only returns when user quits
save("data.txt");
}
/**
* Reads all orders and clients from text file, and loads it into the hash tables upon startup
* @param filename The file to load data from
*/
private static void load(String filename) {
try {
File data = new File(filename);
Scanner input = new Scanner(data);
// load clients from text file to hash table
String currLine;
Client currClient;
while (input.hasNextLine()) {
currLine = input.nextLine();
if (currLine.equals("ORDERS")) break; // leaves loop when gets to orders
currClient = new Client(currLine);
clients.put(currClient.getName(), currClient);
}
// load orders from text file to hash table
Order currOrder;
while (input.hasNextLine()) {
currLine = input.nextLine();
currOrder = new Order(currLine);
orders.put(currOrder.getNumber(), currOrder);
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("A load file does not exist. Creating new load file");
// will create a new file when saving
}
}
/**
* Saves all the Clients and Orders from hash table to a text file when the user quits the program
* @param filename the file to save data in
*/
private static void save(String filename) {
try {
File data = new File(filename);
PrintWriter out = new PrintWriter(data);
// save clients
ArrayList<Client> storedClients = clients.getAll();
for (Client c : storedClients) {
out.println(c.toLoadString());
}
// save orders
ArrayList<Order> storedOrders = orders.getAll();
out.println("ORDERS");
for (Order o : storedOrders) {
out.println(o.toLoadString());
}
out.close();
System.out.println("Data saved successfully");
} catch (FileNotFoundException e) {
System.out.println("Trouble saving. Changes made in this session will be lost");
}
}
/**
* Finds data from multiple orders, specified by FrontEnd
* @param tester tests an order
* @param action does an action with an order and the array list
* @return ArrayList<T> an ArrayList with the data retrieved
*/
protected static <T> ArrayList<T> findOrders(Predicate<Order> tester,
BiConsumer<Order, ArrayList<T>> action) {
int i = 0;
Order order;
ArrayList<T> list = new ArrayList<T>();
try {
while (true) { // will finish when i overtakes # of orders, then exit through exception
order = orders.get(i);
if (tester.test(order)) {
action.accept(order, list);
}
i++;
}
} catch (NoSuchElementException e) {} // will always happen, do nothing
return list;
}
/**
* Gets a client given their name.
* @param name the name of the client, represented as firstName + " " + lastName
* @return Client, the client with the given name
*/
protected static Client getClient(String name) {
return clients.get(name);
}
/**
* Gets an order given its number
* @param orderNumber the number of the order we're looking for
* @return the order we were looking for
*/
protected static Order getOrder(int orderNumber) {
return orders.get(orderNumber);
}
/**
* Adds a new client to the hash table
*/
protected static void addClient(String name, Client client) {
clients.put(name, client);
}
/**
* Adds a new order to the hash table
*/
protected static void addOrder(Order order) {
orders.put(order.getNumber(), order);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fbbdf86ff9045a63f135830197c79bb08ddc20ca | 73b763f0f16008356d797b74dd436d5ea192e7c3 | /3 semester/Laboratory works/Aplet_KWork/TextMove.java | 7b4e2b6a68084174e755edf608a141ebb2b81f87 | [] | no_license | ViktarDunayeu/BSU_FAMCS_Java | cbb5ba540bdbc208d3899a4e5f11594aa158d7b7 | e2aa564882125da6003bd2871d431ec853dcb882 | refs/heads/main | 2023-06-22T06:30:49.376887 | 2020-10-15T11:41:28 | 2020-10-15T11:41:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,312 | java | /*
* 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 lab10;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.awt.*;
import javax.swing.*;
public class TextMove implements ActionListener{
private JTextField tf;
private JTextArea ta;
TextMove(JTextField tf, JTextArea ta){
this.tf=tf;
this.ta=ta;
}
public void actionPerformed(ActionEvent ae){
ta.append(tf.getText()+"\n");
}
}
class MyNote extends JFrame{
MyNote(String title){
super(title);
Container c = getContentPane();
JTextField tf = new JTextField("", 50);
c.add(tf,BorderLayout.NORTH);
JTextArea ta = new JTextArea();
ta.setEditable(false);
c.add(ta);
JPanel p = new JPanel();
c.add(p,BorderLayout.SOUTH);
JButton b = new JButton("OK GO: ");
p.add(b);
tf.addActionListener(new TextMove(tf,ta));
b.addActionListener(new TextMove(tf,ta));
setSize(300,200);
setVisible(true);
}
}
| [
"rulit.ivan@yandex.ru"
] | rulit.ivan@yandex.ru |
17c31992ce2be15bdcd93318d13c57daff1705b4 | 75484aeed789b170359575a3082b95c06c35c095 | /logon/src/main/java/com/aliyun/ayland/ui/adapter/ATConvenientKitchenRVAdapter.java | 2656ed78c4a909328223a59f023d17e9ec0a202b | [] | no_license | 584393321/aite_longguang | abc1ed64bfd0d33c3638fb31c3777af054c2d8f5 | 97aade9d29a903a648c2cc4993a94d60d7b05820 | refs/heads/main | 2023-04-07T02:32:24.649736 | 2021-04-09T09:44:38 | 2021-04-09T09:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,917 | java | package com.aliyun.ayland.ui.adapter;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.aliyun.ayland.base.autolayout.util.ATAutoUtils;
import com.aliyun.ayland.data.ATKitchenProjectBean.TimeBean;
import com.aliyun.ayland.interfaces.ATOnRVItemClickListener;
import com.anthouse.xuhui.R;
import java.util.ArrayList;
import java.util.List;
public class ATConvenientKitchenRVAdapter extends RecyclerView.Adapter {
private Activity mContext;
private List<TimeBean> list = new ArrayList<>();
private int selected_position = -1;
public ATConvenientKitchenRVAdapter(Activity context) {
mContext = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.at_item_rv_kitchen, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.setData(position);
}
@Override
public int getItemCount() {
return list.size();
}
public void setLists(List<TimeBean> list) {
this.list.clear();
this.list.addAll(list);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout mRlContent;
private TextView tvName, tvTime, tvPrice;
private ViewHolder(View itemView) {
super(itemView);
ATAutoUtils.autoSize(itemView);
mRlContent = itemView.findViewById(R.id.rl_content);
tvName = itemView.findViewById(R.id.tv_name);
tvTime = itemView.findViewById(R.id.tv_time);
tvPrice = itemView.findViewById(R.id.tv_price);
}
public void setData(int position) {
tvName.setText(list.get(position).getItemName());
tvTime.setText(list.get(position).getItemTime());
tvPrice.setText(String.format(mContext.getString(R.string.at_price_), list.get(position).getItemPrice()));
if (list.get(position).getUseStatus() != -1)
if (position == selected_position) {
tvName.setTextColor(mContext.getResources().getColor(R.color._EBB080));
tvTime.setTextColor(mContext.getResources().getColor(R.color._EBB080));
tvPrice.setTextColor(mContext.getResources().getColor(R.color._EBB080));
} else {
tvName.setTextColor(mContext.getResources().getColor(R.color._666666));
tvTime.setTextColor(mContext.getResources().getColor(R.color._666666));
tvPrice.setTextColor(mContext.getResources().getColor(R.color._666666));
}
else {
tvName.setTextColor(mContext.getResources().getColor(R.color._CCCCCC));
tvTime.setTextColor(mContext.getResources().getColor(R.color._CCCCCC));
tvPrice.setTextColor(mContext.getResources().getColor(R.color._CCCCCC));
}
mRlContent.setOnClickListener(view -> {
if (list.get(position).getUseStatus() == -1)
return;
selected_position = position;
notifyDataSetChanged();
mOnItemClickListener.onItemClick(view, position);
});
}
}
private ATOnRVItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(ATOnRVItemClickListener listener) {
this.mOnItemClickListener = listener;
}
}
| [
"584393321@qq.com"
] | 584393321@qq.com |
196612636be0bab0ae17b49af519c60e5c70a110 | 94d8c81f5c85243d965a6d46f689e451cc305353 | /spring.practice/src/main/java/com/spring/mvc/demo/StudentControlller.java | c9af1b53e47213a9c0c3ce4022dc107140b7a232 | [
"MIT"
] | permissive | shubhamchopra3/spring-learning | f314d382c39168c7855341067de9fb7a7f6ca02a | f25f5138cfb5ed76d7d8837ad1bc537a4e929e0b | refs/heads/master | 2023-01-14T13:09:19.755212 | 2020-11-18T09:24:38 | 2020-11-18T09:24:38 | 313,876,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 824 | java | package com.spring.mvc.demo;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/student")
public class StudentControlller {
@RequestMapping("/showForm")
public String showForm(Model model) {
Student s = new Student("shubham","chopra");
model.addAttribute("student",s);
return "studentForm";
}
@RequestMapping("/processForm")
public String processForm(@Valid @ModelAttribute("student") Student student, BindingResult result) {
if(result.hasErrors())
return "studentForm";
return "student-confirmation";
}
}
| [
"shubamchopra553@gmail.com"
] | shubamchopra553@gmail.com |
0c970fd71824883390f7549ef1027940a23a6a0d | 134d3373331565d373288428ba5c8f6ed7de8a96 | /app/src/main/java/com/example/grusha/aawify/PapersFragment.java | 82eef1f3ce01c08ed0b6afa98bd5da1fc8ec1c09 | [] | no_license | grusha02/Awarify | 37cb39ad2cc63c8a4405506164871bc389005205 | 58402e866f58b7e81d183e4829442d992af77f57 | refs/heads/master | 2021-09-04T22:36:26.372779 | 2018-01-22T19:39:49 | 2018-01-22T19:39:49 | 107,501,371 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,068 | java | package com.example.grusha.aawify;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class PapersFragment extends Fragment {
public NamesAdapter adapt;
public ArrayList<Names> names;
public ListView list;
public PapersFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.activity_papername,container,false);
names = new ArrayList<Names>();
names.add(new Names("Times Of India"));
names.add(new Names("Hindustan Times"));
names.add(new Names("India Today"));
adapt = new NamesAdapter(getActivity(), names);
list = (ListView) rootview.findViewById(R.id.list);
list.setAdapter(adapt);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent firstIntent = new Intent(getActivity(), Timesmix.class);
startActivity(firstIntent);
break;
case 1:
Intent secondIntent = new Intent(getActivity(), Hindustanmix.class);
startActivity(secondIntent);
break;
case 2:
Intent thirdIntent = new Intent(getActivity(), Indiamix.class);
startActivity(thirdIntent);
break;
}
}
});
return rootview;
}
}
| [
"grushabhalla@gmail.com"
] | grushabhalla@gmail.com |
3e05f5e752a379fd1a07c3db62e76fb362af0249 | 982e9d5a0eba05880f36eae62ed98a5641bb76ba | /bodegaControl/src/main/java/com/uisrael/bodegaControl/vista/DetalleView.java | d06d72dd0448360c6dca435fa2089cff55fd8064 | [
"MIT"
] | permissive | Lordcreos/controlBodega | 79640c92ea87caa6d780927715b4e822afb25c91 | 0611b9103614ee17e8444df2f66e6b77786db912 | refs/heads/main | 2023-03-03T07:41:22.730597 | 2021-02-14T22:04:13 | 2021-02-14T22:04:13 | 338,911,538 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,899 | java | package com.uisrael.bodegaControl.vista;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import com.uisrael.bodegaControl.controlador.DetalleControlador;
import com.uisrael.bodegaControl.controlador.EquipoControlador;
import com.uisrael.bodegaControl.controlador.ServicioControlador;
import com.uisrael.bodegaControl.controlador.impl.DetalleControladorImpl;
import com.uisrael.bodegaControl.controlador.impl.EquipoControladorImpl;
import com.uisrael.bodegaControl.controlador.impl.ServicioControladorImpl;
import com.uisrael.bodegaControl.modelo.entidades.Detalle;
import com.uisrael.bodegaControl.modelo.entidades.Equipo;
import com.uisrael.bodegaControl.modelo.entidades.Servicio;
@ManagedBean
@ViewScoped
public class DetalleView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idDetalle;
private int idEquipo;
private int idServicio;
private Detalle nuevoDetalle;
private Servicio nuevoServicio;
private Equipo nuevoEquipo;
private DetalleControlador detalleControlador;
private EquipoControlador equipoControlador;
private ServicioControlador servicioControlador;
private List<Detalle>listarDetalle;
private List<Equipo>listarEquipo;
private List<Servicio>listarServicio;
public DetalleView() {
}
@PostConstruct
public void init() {
nuevoEquipo = new Equipo();
nuevoServicio = new Servicio();
detalleControlador = new DetalleControladorImpl();
equipoControlador = new EquipoControladorImpl();
servicioControlador = new ServicioControladorImpl();
listarDetalle = new ArrayList<Detalle>();
listarDetalle();
listarEquipo();
listarServicio();
}
public void insertarDetalle() {
try {
nuevoDetalle = new Detalle();
nuevoDetalle.setFkEquipo(nuevoEquipo);
nuevoDetalle.setFkServicio(nuevoServicio);
detalleControlador.insertarDetalle(nuevoDetalle);
listarDetalle();
listarEquipo();
listarServicio();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage
(FacesMessage.SEVERITY_INFO,"Info","Dato Ingresado Correctamente"));
} catch (Exception e) {
// TODO: handle exception
System.out.println("Insertado"+ e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage
(FacesMessage.SEVERITY_ERROR, "Info","Error al Insertar Dato"));
}
}
public void listarDetalle() {
listarDetalle = detalleControlador.listarDetalle();
}
public void listarEquipo() {
listarEquipo = equipoControlador.listarEquipo();
}
public void listarServicio() {
listarServicio = servicioControlador.listarServicio();
}
public Detalle getNuevoDetalle() {
return nuevoDetalle;
}
public void setNuevoDetalle(Detalle nuevoDetalle) {
this.nuevoDetalle = nuevoDetalle;
}
public Servicio getNuevoServicio() {
return nuevoServicio;
}
public void setNuevoServicio(Servicio nuevoServicio) {
this.nuevoServicio = nuevoServicio;
}
public Equipo getNuevoEquipo() {
return nuevoEquipo;
}
public void setNuevoEquipo(Equipo nuevoEquipo) {
this.nuevoEquipo = nuevoEquipo;
}
public DetalleControlador getDetalleControlador() {
return detalleControlador;
}
public void setDetalleControlador(DetalleControlador detalleControlador) {
this.detalleControlador = detalleControlador;
}
public List<Detalle> getListarDetalle() {
return listarDetalle;
}
public void setListarDetalle(List<Detalle> listarDetalle) {
this.listarDetalle = listarDetalle;
}
public List<Equipo> getListarEquipo() {
return listarEquipo;
}
public void setListarEquipo(List<Equipo> listarEquipo) {
this.listarEquipo = listarEquipo;
}
public EquipoControlador getEquipoControlador() {
return equipoControlador;
}
public void setEquipoControlador(EquipoControlador equipoControlador) {
this.equipoControlador = equipoControlador;
}
public List<Servicio> getListarServicio() {
return listarServicio;
}
public void setListarServicio(List<Servicio> listarServicio) {
this.listarServicio = listarServicio;
}
public ServicioControlador getServicioControlador() {
return servicioControlador;
}
public void setServicioControlador(ServicioControlador servicioControlador) {
this.servicioControlador = servicioControlador;
}
public int getIdDetalle() {
return idDetalle;
}
public void setIdDetalle(int idDetalle) {
this.idDetalle = idDetalle;
}
public int getIdServicio() {
return idServicio;
}
public void setIdServicio(int idServicio) {
this.idServicio = idServicio;
}
public int getIdEquipo() {
return idEquipo;
}
public void setIdEquipo(int idEquipo) {
this.idEquipo = idEquipo;
}
}
| [
"leonardosanchez4h@hotmail.com"
] | leonardosanchez4h@hotmail.com |
cae21f8a4a012a9793e64d1fe90f18690031fd1a | 439e9f919595de65ae8a7c147c702eae2039a5aa | /ilsvitalsign_be/src/main/java/com/example/ilsvitalsign_be/entity/ObservationEntity.java | 4e201d0975b2f607d74120d70c061a5b50321d24 | [] | no_license | prathwish/ilsvitalsigns | 7d57e0aa0436514f519d7f589d086f33803ae3c4 | d8625186b0b3b698b2169d438b67a89548e0888d | refs/heads/master | 2020-05-05T11:50:08.260614 | 2019-04-08T11:27:16 | 2019-04-08T11:27:16 | 180,005,672 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,959 | java | package com.example.ilsvitalsign_be.entity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "OBSERVATION")
public class ObservationEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "OBSERVATION_ID")
private Integer observationId;
@Column(name = "CATEGORY", length = 128)
private String category;
@Column(name = "SUBCATEGORY_TYPE", length = 128)
private String subCategoryType;
@Column(name = "SUBCATEGORY_CODE", length = 128)
private String subCategoryCode;
@Column(name = "CDRID", length = 128)
private String cdrId;
@Column(name = "EFFECTIVEDATE_TIME", length = 128)
private String effectiveDateTime;
@JoinColumns({ @JoinColumn(name = "PATIENT_ID", referencedColumnName = "PATIENT_ID"),
@JoinColumn(name = "SOURCE_ID", referencedColumnName = "SOURCE_ID") })
@ManyToOne(cascade = CascadeType.ALL)
private SourcePatientEntity sourcePatientEntity;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "observationEntity", fetch = FetchType.EAGER)
private List<ObservationValueEntity> observationValueEntity = new ArrayList<>();
public Integer getObservationId() {
return observationId;
}
public void setObservationId(Integer observationId) {
this.observationId = observationId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getSubCategoryType() {
return subCategoryType;
}
public void setSubCategoryType(String subCategoryType) {
this.subCategoryType = subCategoryType;
}
public String getSubCategoryCode() {
return subCategoryCode;
}
public void setSubCategoryCode(String subCategoryCode) {
this.subCategoryCode = subCategoryCode;
}
public String getCdrId() {
return cdrId;
}
public void setCdrId(String cdrId) {
this.cdrId = cdrId;
}
public String getEffectiveDateTime() {
return effectiveDateTime;
}
public void setEffectiveDateTime(String effectiveDateTime) {
this.effectiveDateTime = effectiveDateTime;
}
public SourcePatientEntity getSourcePatientEntity() {
return sourcePatientEntity;
}
public void setSourcePatientEntity(SourcePatientEntity sourcePatientEntity) {
this.sourcePatientEntity = sourcePatientEntity;
}
public List<ObservationValueEntity> getObservationValueEntity() {
return observationValueEntity;
}
public void setObservationValueEntity(List<ObservationValueEntity> observationValueEntity) {
this.observationValueEntity = observationValueEntity;
}
}
| [
"Prathwish.Hegde@philips.com"
] | Prathwish.Hegde@philips.com |
7ba32629a2255a97521fc7072c09181864b7b0a0 | 7cacec9594e65e52e953085bcd7f873164568495 | /src/com/irandoo/xhep/base/json/JRecvMsg.java | 2b2b6eea4780cbe200e88c02d6592514511ba23b | [] | no_license | louluxi/wawa | 401d48c5126aea9ac61bb9909194b935d4bb3a86 | 65a9ec6458112471b14b48651c98bc037ad745b8 | refs/heads/master | 2021-05-01T17:50:01.227030 | 2018-02-10T08:22:36 | 2018-02-10T08:22:36 | 120,994,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,298 | java | package com.irandoo.xhep.base.json;
import java.sql.Timestamp;
import java.util.Date;
import com.irandoo.base.json.RandooJsonBean;
public class JRecvMsg extends RandooJsonBean{
@Override
public JRecvMsg createBean() {
// TODO Auto-generated method stub
return new JRecvMsg();
}
public Long getRecvId() {
return (Long)get("recvId");
}
public void setRecvId(Long recvId) {
set("recvId",recvId);
}
public long getSendId() {
return (Long)get("sendId");
}
public void setSendId(long sendId) {
set("sendId",sendId);
}
// public String getSendUser() {
// return (String)get("sendUser");
// }
//
// public void setSendUser(String sendUser) {
// set("sendUser",sendUser);
// }
public String getFrom() {
return (String)get("from");
}
public void setFrom(String from) {
set("from",from);
}
public Timestamp getSendTime() {
return (Timestamp)get("sendTime");
}
public void setSendTime(Timestamp sendTime) {
set("sendTime",sendTime);
}
public String getTitle() {
return (String)get("title");
}
public void setTitle(String title) {
set("title",title);
}
public String getContent() {
return (String)get("content");
}
public void setContent(String content) {
set("content",content);
}
}
| [
"nuoxin@DESKTOP-159N79I"
] | nuoxin@DESKTOP-159N79I |
d4f73967dc7453bb2563a1927dbcb71fbdf525cb | a4f3b3e9fe4d8ef1c58962a7dc91213485dee066 | /src/main/java/com/zeus/LinkedList/ConvertSortLinkListToBinarySearchTree_109.java | d9d42b30229c928e420be054280287aabe3564ec | [
"Apache-2.0"
] | permissive | hustman/leetcode | 0a2b2d8c0a1b8f702a13dafdc0f607f0a600457a | e7633907ecbc0bd1f387f6602aa44dce3ff2717f | refs/heads/master | 2022-12-28T14:16:34.664617 | 2019-05-29T16:24:14 | 2019-05-29T16:24:14 | 103,494,983 | 1 | 0 | Apache-2.0 | 2020-10-13T02:15:03 | 2017-09-14T06:32:33 | Java | UTF-8 | Java | false | false | 1,313 | java | package com.zeus.LinkedList;
/**
* @author xuxingbo
* @Date 2018/5/27
*
* 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
* 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
*/
public class ConvertSortLinkListToBinarySearchTree_109 {
public TreeNode sortedListToBST(ListNode head) {
return sortedListToBST(head, null);
}
/**
* 在链表中,通过定义两个快慢指针,可以迅速的将链表划分为两个部分
* 然后对两个部分进行递归处理即可
*/
public TreeNode sortedListToBST(ListNode head, ListNode tail){
if(head == tail){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast != tail && fast.next != tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode treeHead = new TreeNode(slow.val);
treeHead.left = sortedListToBST(head, slow);
treeHead.right = sortedListToBST(slow.next, tail);
return treeHead;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
| [
"xuxingbo@hust.edu.cn"
] | xuxingbo@hust.edu.cn |
9733cc003b3d84faab2bbf6ebeaf5c37cea90385 | fe9fc7316474bd0b433195830ce1a4f9c9d5f4a9 | /src/main/java/lt/lb/longestpath/genetic/impl/GraphAgentMaker.java | 5e9652c0cdbfcfdce09c9614de666a4cb35558f3 | [] | no_license | laim0nas100/LongestPath | 2ba5b837bd74adcfc69f6494b23325cf19a3dd68 | 7f4d34e13205480d7b64139654affef747364bc2 | refs/heads/master | 2021-06-26T06:56:14.807668 | 2019-12-30T10:30:59 | 2019-12-30T10:30:59 | 151,693,655 | 0 | 0 | null | 2020-10-13T09:56:54 | 2018-10-05T08:43:57 | Java | UTF-8 | Java | false | false | 1,654 | java | /*
* 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 lt.lb.longestpath.genetic.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lt.lb.commons.Log;
import lt.lb.commons.graphtheory.GLink;
import lt.lb.commons.graphtheory.Orgraph;
import lt.lb.commons.graphtheory.paths.PathGenerator;
import lt.lb.commons.misc.rng.RandomDistribution;
import lt.lb.longestpath.API;
import lt.lb.longestpath.genetic.GraphAgent;
import lt.lb.neurevol.evolution.NEAT.interfaces.AgentMaker;
/**
*
* @author laim0nas100
*/
public class GraphAgentMaker implements AgentMaker<GraphAgent> {
public int population = 100;
public Orgraph gr;
public RandomDistribution rnd;
public GraphAgentMaker(Orgraph g, RandomDistribution rnd, int population) {
this.rnd = rnd;
gr = g;
this.population = population;
}
@Override
public Collection<GraphAgent> initializeGeneration() {
ArrayList<GraphAgent> list = new ArrayList<>();
for (int i = 0; i < population; i++) {
List<GLink> path = PathGenerator.generateLongPathBidirectional(gr, rnd.pickRandom(gr.nodes.keySet()), PathGenerator.nodeDegreeDistributed(rnd,false));
GraphAgent agent = new GraphAgent(API.getNodesIDs(path), gr);
list.add(agent);
Log.print("is valid?", API.isPathValid(gr, agent.path), agent);
agent.computeFitness();
}
return list;
}
}
| [
"aciukadsiunciate@gmail.com"
] | aciukadsiunciate@gmail.com |
89138f61bbead6303b1623ea68dac1514007fd10 | 81d6c282e0cf778bcd38fc6ddcaa4fc5e6e38f43 | /app/src/main/java/in/z/smsreceivereaddemo/MainActivity.java | f9a4f93f6d3e1f85a31d471aca2988f390f2d7b7 | [] | no_license | mzaifquraishi/SmsReceiveReadDemo | d374a18c4e4455774708bd79f9a6d6b4f8b4253d | 0ec40828ad162308d1a0a065789e25f655659cd9 | refs/heads/master | 2023-03-07T19:14:45.147696 | 2021-02-24T18:44:47 | 2021-02-24T18:44:47 | 342,000,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,276 | java | package in.z.smsreceivereaddemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Telephony;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText txt;
SmsListener smsListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = findViewById(R.id.txt_otp);
if (!isSmsPermissionGranted()) {
requestReadAndSendSmsPermission();
} else {
smsListener = new SmsListener();
registerReceiver(smsListener, new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION));
smsListener.setListener(new SmsListener.Listener() {
@Override
public void onTextReceived(String text) {
txt.setText(text);
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
});
}
}
public boolean isSmsPermissionGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
}
/**
* Request runtime SMS permission
*/
private void requestReadAndSendSmsPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_SMS)) {
smsListener = new SmsListener();
registerReceiver(smsListener, new IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION));
smsListener.setListener(new SmsListener.Listener() {
@Override
public void onTextReceived(String text) {
txt.setText(text);
Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
}
});
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, 1);
}
} | [
"mzaifquraishi@gmail.com"
] | mzaifquraishi@gmail.com |
91cbfe1c4628db08175ebe982ec042f9d9a594df | f393bdd43c5e54916409a536f74eb9de46921fdb | /app/src/main/java/com/java/wangguanghan/newsmodel/NewsBean.java | eed4c02391f6159c28b96b01db80d3e74ff4dafc | [] | no_license | anyezhiya368/SummerSemester_JavaAndroid | 8191a63e297187b968959398173578879a23364c | 536369b45f54da990ec76a9771a0efee568fea6c | refs/heads/master | 2023-07-23T22:11:34.989505 | 2021-09-09T07:15:36 | 2021-09-09T07:15:36 | 401,201,198 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,453 | java | package com.java.wangguanghan.newsmodel;
import java.util.ArrayList;
import java.util.List;
public class NewsBean {
private String image = "";
private String publishTime;
private String video;
private String title;
private String url;
private String publisher;
private String category;
private String content;
private List<String> imagelist = new ArrayList<>();
public NewsBean(){}
public NewsBean(String image, String publishTime, String video, String title, String url, String publisher
, String content)
{
this.image = image;
this.publishTime = publishTime;
this.video = video;
this.title = title;
this.url = url;
this.publisher = publisher;
this.content = content;
}
public NewsBean(NewsBeanPlanB newsBeanPlanB){
this.imagelist = newsBeanPlanB.getImage();
this.publishTime = newsBeanPlanB.getPublishTime();
this.video = newsBeanPlanB.getVideo();
this.title = newsBeanPlanB.getTitle();
this.url = newsBeanPlanB.getUrl();
this.publisher = newsBeanPlanB.getPublisher();
this.content = newsBeanPlanB.getContent();
StringBuffer buffer = new StringBuffer();
buffer.append('[');
if(imagelist.size() != 0){
for (String imagestring:
this.imagelist) {
buffer.append(imagestring);
buffer.append(',');
buffer.append(' ');
}buffer.deleteCharAt(buffer.length() - 1);
buffer.deleteCharAt(buffer.length() - 1);
buffer.append(']');
this.image = buffer.toString();
}else{
buffer.append(']');
this.image = buffer.toString();
}
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisherstring) {
this.publisher = publisherstring;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String titlestring) {
this.title = titlestring;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(String publishTimestring) {
this.publishTime = publishTimestring;
}
public String getImageString(){return image;}
public List<String> getImage() {
if(imagelist.size() != 0)
return imagelist;
//Log.e("TAG", image);
List<String> resultlist = new ArrayList<>();
resultlist.clear();
if (image.equals("[]") || image.equals(""))
{
return resultlist;
}
else {
StringBuffer result = new StringBuffer(1000);
result.append(image);
result.delete(0, 1);
// 得到第一个逗号的位置
while (true) {
int i = 0;
char cur = result.charAt(i);
while ((cur != ',') && (cur != ']')) {
i++;
cur = result.charAt(i);
}
if (result.charAt(i) != ']') {
if(result.charAt(i - 1) != 'f') {
String temp = result.substring(0, i);
resultlist.add(temp);
result.delete(0, i + 2);
}else{
result.delete(0, i + 2);
}
}else{
if(result.charAt(i - 1) != 'f'){
String temp = result.substring(0, i);
resultlist.add(temp);
return resultlist;
}else
return resultlist;
}
}
}
}
public void setImage(String imagestring) {
this.image = imagestring;
}
}
| [
"Snob021123@163.com"
] | Snob021123@163.com |
badcdd88c0af0ccba545d7e31253d1710cb22804 | c18796c240d2d432232c077e460bd495e11060b9 | /src/BackRrack/CombinationSum.java | a8c7ce937373d3cadf6967ac688815dbdea67993 | [] | no_license | fengfan1994/offer | 8bc8bef3b1d5c88b6d5c88bf5eeaa8650d59b8cc | 64464cfd01406e86f5b0dfb70638a82fa1784a9e | refs/heads/master | 2022-06-22T10:32:58.453571 | 2020-08-23T03:08:20 | 2020-08-23T03:08:20 | 202,362,633 | 0 | 0 | null | 2022-06-21T04:02:32 | 2019-08-14T14:03:56 | Java | UTF-8 | Java | false | false | 1,512 | java | package BackRrack;
import java.util.ArrayList;
import java.util.Arrays;
public class CombinationSum {
ArrayList<ArrayList<Integer>> lists1=new ArrayList<>();
public ArrayList<ArrayList<Integer>> getResult1(int n,int k){
ArrayList<Integer> list=new ArrayList<>();
backtracking(n,k,1,list);
return lists1;
}
public void backtracking(int n,int k,int start,ArrayList<Integer> list){
if(k<0){
return;
}
if(k==0){
lists1.add(new ArrayList<Integer>(list));
}else{
for(int i=start;i<=n;i++){
list.add(i);
backtracking(n,k-1,i+1,list);
list.remove(list.size()-1);
}
}
}
ArrayList<ArrayList<Integer>> lists2=new ArrayList<>();
public ArrayList<ArrayList<Integer>> getResult2(int[] candidates,int target){
Arrays.sort(candidates);
ArrayList<Integer> list=new ArrayList<>();
backtracking1(candidates,target,0,list);
return lists2;
}
public void backtracking1(int[] candidates,int k,int start,ArrayList<Integer> list){
if(k<0){
return;
}
if(k==0){
lists2.add(new ArrayList<Integer>( list));
}else{
for(int i=start;i<candidates.length;i++){
list.add(candidates[i]);
backtracking1(candidates,k-candidates[i],i,list);
list.remove(list.size()-1);
}
}
}
}
| [
"15071148197@163.com"
] | 15071148197@163.com |
00fc6eb8b77cbe0ffc6f1cb0bcdf02a79cb819c0 | e729cc7c1f3ed04d6fe7407bdfe3aa295f5c83ba | /myblog/src/main/java/com/example/myblog/WebMvcConfig.java | 337d6293244886738556cfb0fe2f7759dbab125e | [] | no_license | weifengkkk/myblog | db7b8b878bd4299676bf5fde86997b07e8f9e873 | b61514bdd88f288c64f9259b0c7fa80a8cc8a67c | refs/heads/main | 2023-03-26T09:39:13.624733 | 2021-03-26T09:51:57 | 2021-03-26T09:51:57 | 347,927,248 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 674 | java | package com.example.myblog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);
public void addResourceHandlers(ResourceHandlerRegistry registry){
logger.info("add resourceHandlers");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
| [
"2360484952@qq.com"
] | 2360484952@qq.com |
33a6f66214f558f388efd7a8177d0915d38145e9 | f662526b79170f8eeee8a78840dd454b1ea8048c | /bqp.java | f4fe1f6ec9c279ab41d494e102e891bacdee57d0 | [] | no_license | jason920612/Minecraft | 5d3cd1eb90726efda60a61e8ff9e057059f9a484 | 5bd5fb4dac36e23a2c16576118da15c4890a2dff | refs/heads/master | 2023-01-12T17:04:25.208957 | 2020-11-26T08:51:21 | 2020-11-26T08:51:21 | 316,170,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 243 | java | /* */
/* */ public interface bqp
/* */ {
/* 4 */ public static final brz e = new brz();
/* */ }
/* Location: F:\dw\server.jar!\bqp.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | [
"jasonya2206@gmail.com"
] | jasonya2206@gmail.com |
9d54736068ba658b5068743c45d87bc1cfa81598 | 12de6c39b18d9f84cb3e493d68a823b1ec78fdd3 | /java/com/zmy/service/impl/UserAwardMapServiceImpl.java | cba67d19425634c134f67c0b25fe62b12ac59968 | [] | no_license | lion-yu/o2o | 60f6156d17b62f4888f1c8e6a6edfe173e109615 | 480e68fced673906d32c982676f7691a752ce18d | refs/heads/master | 2021-04-23T19:37:31.353795 | 2020-03-25T13:38:17 | 2020-03-25T13:38:17 | 249,984,349 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,173 | java | package com.zmy.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zmy.dao.IUserAwardMapDao;
import com.zmy.dao.IUserShopMapDao;
import com.zmy.dto.UserAwardMapExecution;
import com.zmy.entity.UserAwardMap;
import com.zmy.entity.UserShopMap;
import com.zmy.enums.UserAwardMapStateEnum;
import com.zmy.exceptions.UserAwardMapOperationException;
import com.zmy.service.IUserAwardMapService;
import com.zmy.util.PageCalculator;
/**
* @author 作者:张哥哥
* @version 创建时间:2019年5月24日下午6:21:11 Class Description:
*/
@Service
public class UserAwardMapServiceImpl implements IUserAwardMapService {
@Autowired
private IUserAwardMapDao userAwardDao;
@Autowired
private IUserShopMapDao userShopMapDao;
@Override
public UserAwardMapExecution listUserAwardMap(UserAwardMap userAwardConditon, Integer pageIndex, Integer pageSize) {
if (userAwardConditon != null && pageIndex != null && pageSize != null) {
int beginIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
List<UserAwardMap> userAwardMapList = userAwardDao.queryUserMapList(userAwardConditon, beginIndex,
pageSize);
int count = userAwardDao.queryUserAwardMapCount(userAwardConditon);
UserAwardMapExecution ue = new UserAwardMapExecution();
ue.setCount(count);
ue.setUserAwardMapList(userAwardMapList);
return ue;
} else {
return null;
}
}
@Override
public UserAwardMap getUserAwardMapById(long userAwardMapId) {
return null;
}
@Override
public UserAwardMapExecution addUserAwardMap(UserAwardMap userAwardMap) {
if (userAwardMap != null && userAwardMap.getUser() != null && userAwardMap.getUser().getUserId() != null
&& userAwardMap.getShop() != null && userAwardMap.getShop().getShopId() != null) {
userAwardMap.setCreateTime(new Date());
userAwardMap.setUsedStatus(0);
try {
int effectedNum = 0;
// 若该积分需要消耗积分,则将tb_user_shop_map对应的积分抵扣
if (userAwardMap.getPoint() != null && userAwardMap.getPoint() > 0) {
UserShopMap userShopMap = userShopMapDao.queryUserShopMap(userAwardMap.getUser().getUserId(),
userAwardMap.getShop().getShopId());
userShopMap.setPoint(userShopMap.getPoint() - userAwardMap.getPoint());
effectedNum = userShopMapDao.updateUserShopMapPoint(userShopMap);
if (effectedNum <= 0) {
throw new UserAwardMapOperationException("更新积分信息失败");
}
}
// 插入礼品兑换信息
effectedNum = userAwardDao.insertUserAwardMap(userAwardMap);
if (effectedNum <= 0) {
throw new UserAwardMapOperationException("领取失败");
}
return new UserAwardMapExecution(UserAwardMapStateEnum.SUCCESS);
} catch (Exception e) {
throw new UserAwardMapOperationException("领取失败:" + e.toString());
}
} else {
return new UserAwardMapExecution(UserAwardMapStateEnum.NULL_AWARD_INFO);
}
}
@Override
public Integer modify(UserAwardMap userAwardMapCondition) {
return userAwardDao.updateUserAwardMap(userAwardMapCondition);
}
}
| [
"promeryu@foxmail.com"
] | promeryu@foxmail.com |
9217db1de17cedab4bab9ad7632ddd1700afea73 | d16021da0344ab91473244efbf0f625a70656c2e | /app/src/main/java/fragments/FragmentSignUp.java | d9819da56083f017ec89ed319fbc2286cab5bbb6 | [] | no_license | LuiguiBalarezo/MinerCoin | 057097198df952fc7d814f55b53222a0b53a7453 | 4a50527886556db3056ded732913e338dc3c20f9 | refs/heads/master | 2021-06-12T06:55:00.166828 | 2017-01-07T18:20:21 | 2017-01-07T18:20:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,669 | java | package fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.toquescript.www.minercoin.R;
import baseclass.BaseFragment;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FragmentSignUp.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentSignUp#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentSignUp extends BaseFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FragmentSignUp() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FragmentForgotPassword.
*/
// TODO: Rename and change types and number of parameters
public static FragmentSignUp newInstance(String param1, String param2) {
FragmentSignUp fragment = new FragmentSignUp();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_signup, container, false);
}
// // TODO: Rename method, update argument and hook method into UI event
// public void onButtonPressed(Uri uri) {
// if (mListener != null) {
// mListener.onFragmentInteraction(uri);
// }
// }
@Override
public void onAttach(Context context) {
super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// // mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
}
@Override
public void onDetach() {
super.onDetach();
// mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| [
"luiguibalarezo@gmail.com"
] | luiguibalarezo@gmail.com |
42b8a213b753fd402eadad7f7d7bc03784014655 | 76ff07c82b5cf6d1f86714036b066792fb42520a | /src/ru/geekbrains/adapter/Main.java | 7f0a74fda2272fcdf559ad4dbcc67ad9b38acbcb | [] | no_license | Pro100proff/lesson-4 | e5c7df95d99288c9041dbe37435c2d7389a0f3cd | c2d9d859123b181ab981df8b36bac58e736ab291 | refs/heads/master | 2023-08-17T16:41:33.825524 | 2021-10-02T11:36:45 | 2021-10-02T11:36:45 | 318,619,946 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 536 | java | package ru.geekbrains.adapter;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Human> humans = new LinkedList<>();
humans.add(new Women("Анастасия"));
humans.add(new Women("Анна"));
Monkey monkey = new Monkey("Monkey");
humans.add(new MonkeyToHumanAnotherAdapter(monkey));
humans.forEach(Human::speak);
System.out.println("----------------");
humans.forEach(Human::work);
}
}
| [
"pro100proff@mail.ru"
] | pro100proff@mail.ru |
a44d68ad2165e9aa2ad6f8dee4b94c1eebf50da0 | d0eff1f6a34b8358c784cc85ffc7195b74a3528b | /app/src/main/java/study/java/concurrency/in/practice/c6/domain/TravelCompany.java | 2715e6008274a7bba1ec58abee5a0b40bce2dd0b | [] | no_license | kji6252/study-java-concurrency-in-practice | 50469cd4278be9def5748b2088417bf86c34e4cc | e86b150a057f4391433f038dacfdf5eaa089f985 | refs/heads/master | 2023-08-15T17:09:27.392919 | 2021-10-21T04:08:39 | 2021-10-21T04:08:39 | 414,846,343 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 174 | java | package study.java.concurrency.in.practice.c6.domain;
public class TravelCompany {
public TravelQuote solicitQuote(TravelInfo travelInfo) {
return null;
}
}
| [
"kji6252@gmail.com"
] | kji6252@gmail.com |
5b78e4f72308e364f2a2fb1aa157c9c32f6360da | 3d9d31b1df1210087857653eb756cb43f426d2e1 | /src/Porta.java | 374792df6f21303cc57847ae652f0267a60171ce | [] | no_license | Matheusagostinho/ExerciciosDeFixacao | 69f5a23d363d78925276106ad20b9d41294ef17e | 55137c71fe10fffc5437bfbedaa938553e69e8b1 | refs/heads/master | 2020-07-17T05:48:44.532850 | 2019-09-03T00:54:30 | 2019-09-03T00:54:30 | 205,959,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 501 | java |
/**
*
* @author Matheus Agostinhho
*/
public class Porta {
//Atributos
boolean aberta;
String cor;
//Dimensão em metros
double dimensaoX;
double dimensaoY;
double dimensaoZ;
//Métodos
void abre(){
this.aberta = true;
}
void fecha(){
this.aberta = false;
}
void pinta(String cor) {
this.cor = cor;
}
boolean estaAberta(){
return aberta;
}
}
| [
"henrique.matheus28@gmail.com"
] | henrique.matheus28@gmail.com |
124127cb82c15c4a450c8e9f3eb427d78dd96fe9 | b4c1a212ac9bc45720622d9e6fd94a95323f5ba6 | /sts_workspace/design0219/src/com/oracle/test/Test.java | bf57641ddfa4a350824c8cd6e2da95f7fe8bb3a8 | [] | no_license | GeeK-lhy/myWorkSpaces | 7e46147aa8d20df3755eac7527331862180d4857 | 14910630a5babe7981a1af1eab967296cd6d3cb6 | refs/heads/master | 2022-12-04T14:20:09.422982 | 2020-08-25T09:40:25 | 2020-08-25T09:40:25 | 290,168,416 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 217 | java | package com.oracle.test;
import com.oracle.decorator.*;
public class Test {
public static void main(String[] args) {
Component w=new BackGroundDecorator(new ScrollDecorator(new Window()));
w.display();
}
}
| [
"185568360@qq.com"
] | 185568360@qq.com |
b4069c78c466f0e5906fcbd35c0b346cd43eb926 | cf900a815d97727f2f0227fd9a200ae6eec807be | /xml_assignment/StringUtils.java | 1a406494f8a3fc4128b5d967c89d7e2d29538d01 | [
"MIT"
] | permissive | stahlechris/resume | 1be047fc9a2ddb96db35bf886951b2e7897c8544 | 634474423ae409e35fe2be01ea0b9c9a5e415ba5 | refs/heads/master | 2021-01-20T19:53:35.551856 | 2017-09-22T22:04:04 | 2017-09-22T22:04:04 | 64,684,471 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | //***************************************************************************
// File: CountriesApp.Java
//
// Student: Chris Stahle
//
// Assignment: Program # 3
//
// Course Name: Java Programming I
//
// Course Number: COSC 2050 - 01
//
// Due: November 15, 2016
//
// Description: This program maintains a list of customers
// It reads and writes to a file.
//***************************************************************************
package xml_assignment;
public class StringUtils
{
public static String addSpaces(String s, int length)
{
if (s.length() < length)
{
StringBuilder sb = new StringBuilder(s);
while(sb.length() < length)
{
sb.append(" ");
}
return sb.toString();
}
else
{
return s.substring(0, length);
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
d23f0a35c33db0246a2f40a4ba53b6aa129ed40a | dba87418d2286ce141d81deb947305a0eaf9824f | /sources/com/google/android/material/progressindicator/CircularDrawingDelegate.java | 61d0bcf102a08e8bd27f9a4eac1503c13130040e | [] | no_license | Sluckson/copyOavct | 1f73f47ce94bb08df44f2ba9f698f2e8589b5cf6 | d20597e14411e8607d1d6e93b632d0cd2e8af8cb | refs/heads/main | 2023-03-09T12:14:38.824373 | 2021-02-26T01:38:16 | 2021-02-26T01:38:16 | 341,292,450 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,723 | java | package com.google.android.material.progressindicator;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import androidx.annotation.ColorInt;
import androidx.annotation.FloatRange;
import androidx.annotation.NonNull;
import com.google.android.material.color.MaterialColors;
final class CircularDrawingDelegate extends DrawingDelegate<CircularProgressIndicatorSpec> {
private float adjustedRadius;
private int arcDirectionFactor = 1;
private float displayedCornerRadius;
private float displayedTrackThickness;
public CircularDrawingDelegate(@NonNull CircularProgressIndicatorSpec circularProgressIndicatorSpec) {
super(circularProgressIndicatorSpec);
}
public int getPreferredWidth() {
return getSize();
}
public int getPreferredHeight() {
return getSize();
}
public void adjustCanvas(@NonNull Canvas canvas, @FloatRange(from = 0.0d, mo651to = 1.0d) float f) {
float f2 = (((float) ((CircularProgressIndicatorSpec) this.spec).indicatorSize) / 2.0f) + ((float) ((CircularProgressIndicatorSpec) this.spec).indicatorInset);
canvas.translate(f2, f2);
canvas.rotate(-90.0f);
float f3 = -f2;
canvas.clipRect(f3, f3, f2, f2);
this.arcDirectionFactor = ((CircularProgressIndicatorSpec) this.spec).indicatorDirection == 0 ? 1 : -1;
this.displayedTrackThickness = ((float) ((CircularProgressIndicatorSpec) this.spec).trackThickness) * f;
this.displayedCornerRadius = ((float) ((CircularProgressIndicatorSpec) this.spec).trackCornerRadius) * f;
this.adjustedRadius = ((float) (((CircularProgressIndicatorSpec) this.spec).indicatorSize - ((CircularProgressIndicatorSpec) this.spec).trackThickness)) / 2.0f;
if ((this.drawable.isShowing() && ((CircularProgressIndicatorSpec) this.spec).showAnimationBehavior == 2) || (this.drawable.isHiding() && ((CircularProgressIndicatorSpec) this.spec).hideAnimationBehavior == 1)) {
this.adjustedRadius += ((1.0f - f) * ((float) ((CircularProgressIndicatorSpec) this.spec).trackThickness)) / 2.0f;
} else if ((this.drawable.isShowing() && ((CircularProgressIndicatorSpec) this.spec).showAnimationBehavior == 1) || (this.drawable.isHiding() && ((CircularProgressIndicatorSpec) this.spec).hideAnimationBehavior == 2)) {
this.adjustedRadius -= ((1.0f - f) * ((float) ((CircularProgressIndicatorSpec) this.spec).trackThickness)) / 2.0f;
}
}
/* access modifiers changed from: package-private */
public void fillIndicator(@NonNull Canvas canvas, @NonNull Paint paint, @FloatRange(from = 0.0d, mo651to = 1.0d) float f, @FloatRange(from = 0.0d, mo651to = 1.0d) float f2, @ColorInt int i) {
Paint paint2 = paint;
if (f != f2) {
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.BUTT);
paint.setAntiAlias(true);
paint.setColor(i);
paint.setStrokeWidth(this.displayedTrackThickness);
int i2 = this.arcDirectionFactor;
float f3 = f * 360.0f * ((float) i2);
float f4 = (f2 >= f ? f2 - f : (f2 + 1.0f) - f) * 360.0f * ((float) i2);
float f5 = this.adjustedRadius;
canvas.drawArc(new RectF(-f5, -f5, f5, f5), f3, f4, false, paint);
if (this.displayedCornerRadius > 0.0f && Math.abs(f4) < 360.0f) {
paint.setStyle(Paint.Style.FILL);
float f6 = this.displayedCornerRadius;
RectF rectF = new RectF(-f6, -f6, f6, f6);
Canvas canvas2 = canvas;
Paint paint3 = paint;
RectF rectF2 = rectF;
drawRoundedEnd(canvas2, paint3, this.displayedTrackThickness, this.displayedCornerRadius, f3, true, rectF2);
drawRoundedEnd(canvas2, paint3, this.displayedTrackThickness, this.displayedCornerRadius, f3 + f4, false, rectF2);
}
}
}
/* access modifiers changed from: package-private */
public void fillTrack(@NonNull Canvas canvas, @NonNull Paint paint) {
int compositeARGBWithAlpha = MaterialColors.compositeARGBWithAlpha(((CircularProgressIndicatorSpec) this.spec).trackColor, this.drawable.getAlpha());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.BUTT);
paint.setAntiAlias(true);
paint.setColor(compositeARGBWithAlpha);
paint.setStrokeWidth(this.displayedTrackThickness);
float f = this.adjustedRadius;
canvas.drawArc(new RectF(-f, -f, f, f), 0.0f, 360.0f, false, paint);
}
private int getSize() {
return ((CircularProgressIndicatorSpec) this.spec).indicatorSize + (((CircularProgressIndicatorSpec) this.spec).indicatorInset * 2);
}
private void drawRoundedEnd(Canvas canvas, Paint paint, float f, float f2, float f3, boolean z, RectF rectF) {
Canvas canvas2 = canvas;
float f4 = z ? -1.0f : 1.0f;
canvas.save();
canvas.rotate(f3);
float f5 = f / 2.0f;
float f6 = f4 * f2;
Paint paint2 = paint;
canvas.drawRect((this.adjustedRadius - f5) + f2, Math.min(0.0f, ((float) this.arcDirectionFactor) * f6), (this.adjustedRadius + f5) - f2, Math.max(0.0f, f6 * ((float) this.arcDirectionFactor)), paint2);
canvas.translate((this.adjustedRadius - f5) + f2, 0.0f);
RectF rectF2 = rectF;
canvas.drawArc(rectF2, 180.0f, (-f4) * 90.0f * ((float) this.arcDirectionFactor), true, paint2);
canvas.translate(f - (f2 * 2.0f), 0.0f);
canvas.drawArc(rectF2, 0.0f, f4 * 90.0f * ((float) this.arcDirectionFactor), true, paint2);
canvas.restore();
}
}
| [
"lucksonsurprice94@gmail.com"
] | lucksonsurprice94@gmail.com |
b7647af90d661d4e27a5d27f67015ba6c84da252 | ff2e69ff97126cff6a64a30dc613b3e7df672a9b | /java_01/src/day16/Book.java | 176a2535edbd6ddded1bbdbbce5ae6cd8ba3c20b | [] | no_license | aydma/bit_java | 42b3ccf80ce485755a65d9adedb3a2ae2eff2755 | d584ee086eb77dfa23e3b0b9c3db6500d6230e63 | refs/heads/master | 2020-07-03T10:56:11.000576 | 2019-09-20T08:44:34 | 2019-09-20T08:44:34 | 201,861,779 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,674 | java | package day16;
import day17.PriceException;
public class Book {
private String title;
private int price;
public Book() { }
public Book(String title, int price) throws PriceException {
this.title = title;
setPrice(price); //RuntimeException이면 throws Exception안해도 에러안남
// try {
// setPrice(price);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPrice() {
return price;
}
public void setPrice(int price) throws PriceException { //무슨오류가 나는지 이름만 보고 알수있게함 -> 사용자정의예외 > PriceException클래스를 만들어줌
if (price < 0)
throw new PriceException(/* "음수는 안돼" */); // 여기서 메세지 안넘기고 생성자에 설정해줌
this.price = price;
}
@Override
public String toString() {
return "Book [title=" + title + ", price=" + price + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + price;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (price != other.price)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
| [
"user@DESKTOP-V882PTR"
] | user@DESKTOP-V882PTR |
edd2d45eb33ccf8bd3bdec39d0e04e1d8f6d6bfc | 0ad80e9d3c00b5198573ee0bc3a95e2e8a7e6437 | /src/main/java/com/quiz/entity/Answer.java | 09fe98f5ea0a05e25b7e009e4e523270d9cd422a | [] | no_license | vg-madt/quiz-services | 6a33784df0c3e6b71f1cd586392d7adaebcaf8ae | 1425ac95bcbe2efce88d334c82ef0d69bea1061d | refs/heads/main | 2023-03-06T04:36:26.408680 | 2021-02-04T21:29:50 | 2021-02-04T21:29:50 | 336,086,802 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | package com.quiz.entity;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
@Data
public class Answer implements Serializable {
private static final long serialVersionUID = 1L;
private String answer;
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a0ca2b541619b5373745dc8a39c88f1ae0455af1 | fd7384a518016b3efcf44fece2075c308619005f | /LogisticManageSystem/Client/src/main/java/edu/nju/lms/presentation/mouseListener/ChangeChoosedListListener.java | 2554a24523c5f15e8e122fb496d72162ef9b9c09 | [] | no_license | niansong1996/LogisticsSystem | b38be33a1f05a8800b462f223b716c2d9e792890 | e2db50ed21bd6fecdbf4354afac62d9be58056a2 | refs/heads/master | 2021-01-16T19:34:05.522436 | 2017-02-24T06:47:53 | 2017-02-24T06:47:53 | 42,798,544 | 6 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,136 | java | package edu.nju.lms.presentation.mouseListener;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import edu.nju.lms.VO.ListVO;
import edu.nju.lms.businessLogicService.impl.list.ListController;
import edu.nju.lms.data.ResultMessage;
import edu.nju.lms.presentation.UIController.UIController;
import edu.nju.lms.presentation.components.MyCheckBox;
import edu.nju.lms.presentation.components.MyDialog;
import edu.nju.lms.presentation.components.table.ListTable;
import edu.nju.lms.presentation.components.table.MyTableLabel;
/**
* @author tj
* @date 2015年12月5日
*/
public abstract class ChangeChoosedListListener extends ButtonListener {
protected ListController control;
protected ListTable table;
public ChangeChoosedListListener(ArrayList<Component> units, UIController controller, Component button) {
super(units, controller, button);
this.control = controller.getListController();
this.table = (ListTable) units.get(0);
}
@Override
public void mouseReleased(MouseEvent e) {
ArrayList<MyTableLabel> data = table.getDataList();
if (data.isEmpty()) {
return;
}
ResultMessage result = null;
for (int i = 0; i < data.size(); i++) {
MyTableLabel label = data.get(i);
MyCheckBox check = (MyCheckBox) label.getComponent(0);
if (check.isSelected()) {
ListVO vo = createVO(label);
result = control.changeList(vo, vo.getType());
if (result.isSuccess()) {
table.my_remove(i);
i--;
}
// 把之前双击显示的单据具体信息从界面上去掉
LabelListener listener = (LabelListener) label.getMouseListeners()[0];
if (listener != null) {
Component area = listener.getArea();
if (area != null) {
area.setVisible(false);
controller.getFrame().getPanel().repaint();
}
}
}
}
if (result.isSuccess()) {
new MyDialog("审批通过!", true,controller);
} else {
new MyDialog(result.getErrorMessage(), true,controller);
}
}
/**
* 返回修改审批状态后的{@link ListVO}
*
* @param label
* @return
*/
public abstract ListVO createVO(MyTableLabel label);
}
| [
"457391179@qq.com"
] | 457391179@qq.com |
8d9e9d38b52e8991bd3aeba3af86eb2640a12983 | 5ca3901b424539c2cf0d3dda52d8d7ba2ed91773 | /src_procyon/com/google/common/collect/ArrayTable$ArrayMap$1.java | 9ebe2e19eb9bca12163e2d0341fca853968a88bb | [] | no_license | fjh658/bindiff | c98c9c24b0d904be852182ecbf4f81926ce67fb4 | 2a31859b4638404cdc915d7ed6be19937d762743 | refs/heads/master | 2021-01-20T06:43:12.134977 | 2016-06-29T17:09:03 | 2016-06-29T17:09:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 434 | java | package com.google.common.collect;
import java.util.*;
class ArrayTable$ArrayMap$1 extends AbstractIndexedListIterator
{
final /* synthetic */ ArrayTable$ArrayMap this$0;
ArrayTable$ArrayMap$1(final ArrayTable$ArrayMap this$0, final int n) {
this.this$0 = this$0;
super(n);
}
@Override
protected Map.Entry get(final int n) {
return new ArrayTable$ArrayMap$1$1(this, n);
}
}
| [
"manouchehri@riseup.net"
] | manouchehri@riseup.net |
f87b3df63d3218ef529cb13fa9b0ba3d565f4b66 | 01017028508fc8c3ac733603f4215f1022b7b30f | /us/mattmarion/pyxeconomy/profile/Profile.java | c7b1983e56cb0c8c7615649225d5a0fa115e81b8 | [] | no_license | matthewmarion/PyxEconomy | 106df75ff339f5ef66be0e08e3db65e1c293e5f6 | d143a3a8feee10311a47a4df28e6e715f7832e46 | refs/heads/master | 2021-03-27T10:56:01.193362 | 2018-05-26T07:35:03 | 2018-05-26T07:35:03 | 110,752,444 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,209 | java | package us.mattmarion.pyxeconomy.profile;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.entity.Player;
import us.mattmarion.pyxeconomy.PyxEconomy;
public class Profile {
private static Set<Profile> profiles = new HashSet<>();
private UUID uuid;
private Player player;
private double balance;
private double multiplier;
private int killstreak;
public Profile(UUID uuid, Player player) {
this.uuid = uuid;
this.player = player;
profiles.add(this);
}
public Profile(Player player) {
this(player.getUniqueId(), player);
}
public static Profile getByUUID(UUID uuid) {
for (Profile profile : profiles) {
if (profile.getUUID().equals(uuid)) {
return profile;
}
}
return null;
}
public static Profile getByPlayer(Player player) {
return getByUUID(player.getUniqueId());
}
public void load() {
this.balance = PyxEconomy.data.getDouble(uuid + ".balance");
this.killstreak = PyxEconomy.data.getInt(uuid + ".killstreak");
}
public void save() {
PyxEconomy.data.set(uuid + ".name", player.getName());
PyxEconomy.data.set(uuid + ".balance", balance);
PyxEconomy.data.set(uuid + ".killstreak", killstreak);
try {
PyxEconomy.data.save(PyxEconomy.dataf);
} catch (IOException e) {
e.printStackTrace();
}
}
public UUID getUUID() {
return uuid;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void addBalance(double balance) {
this.balance += balance;
}
public void removeBalance(double amount) {
this.balance -= amount;
}
public Player getPlayer() {
return player;
}
public double getMultiplier() {
return multiplier;
}
public void setMultiplier(double multiplier) {
this.multiplier = multiplier;
}
public int getKillstreak() {
return killstreak;
}
public void setKillstreak(int killstreak) {
this.killstreak = killstreak;
}
public static Set<Profile> getProfiles() {
return profiles;
}
}
| [
"matthewjmarion29@gmail.com"
] | matthewjmarion29@gmail.com |
e01e08796ef2c853f652a8a0cae289dcec20a584 | 72ffb245bedeb93c9a671ca0422feaced5f26b74 | /src/main/java/redis/clients/jedis/JedisPool.java | 71fce90b3523ca46470019260a9b120afbc6da75 | [] | no_license | HJKCC/jedis-study | 93553ad9029bba24ccef32797d2b0e97fc6ae67f | 09c50b85c4c5856c3f8f2773b803541353465985 | refs/heads/master | 2020-04-07T23:54:26.647581 | 2018-12-07T15:33:14 | 2018-12-07T15:33:14 | 156,940,156 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,335 | java | package redis.clients.jedis;
import java.net.URI;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.util.JedisURIHelper;
/**
* Jedis线程池,默认使用0号数据库
*/
public class JedisPool extends JedisPoolAbstract {
public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT);
}
public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port);
}
public JedisPool(final String host) {
URI uri = URI.create(host);
if (JedisURIHelper.isValid(uri)) {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null), new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host,
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null), new GenericObjectPoolConfig());
}
}
public JedisPool(final String host, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
URI uri = URI.create(host);
if (JedisURIHelper.isValid(uri)) {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory, sslParameters,
hostnameVerifier), new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host,
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null, false, null, null, null), new GenericObjectPoolConfig());
}
}
public JedisPool(final URI uri) {
this(new GenericObjectPoolConfig(), uri);
}
public JedisPool(final URI uri, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, hostnameVerifier);
}
public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig(), uri, timeout);
}
public JedisPool(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final boolean ssl) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final boolean ssl) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout) {
this(poolConfig, host, port, timeout, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout, final boolean ssl) {
this(poolConfig, host, port, timeout, null, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, null, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database) {
this(poolConfig, host, port, timeout, password, database, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final boolean ssl) {
this(poolConfig, host, port, timeout, password, database, null, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, password, database, null, ssl, sslSocketFactory,
sslParameters, hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName,
final boolean ssl) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName,
final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password,
database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier));
}
public JedisPool(final GenericObjectPoolConfig poolConfig) {
this(poolConfig, Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final String host, final int port, final boolean ssl) {
this(new GenericObjectPoolConfig(), host, port, ssl);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName) {
super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password,
database, clientName));
}
public JedisPool(final String host, final int port, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig(), host, port, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName, final boolean ssl) {
this(poolConfig, host, port, connectionTimeout, soTimeout, password, database, clientName, ssl,
null, null, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) {
this(poolConfig, uri, timeout, timeout);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout, final int soTimeout) {
super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null));
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null, sslSocketFactory,
sslParameters, hostnameVerifier));
}
@Override
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
@Override
protected void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
@Override
protected void returnResource(final Jedis resource) {
if (resource != null) {
try {
resource.resetState();
returnResourceObject(resource);
} catch (Exception e) {
returnBrokenResource(resource);
throw new JedisException("Resource is returned to the pool as broken", e);
}
}
}
}
| [
"chencheng0816@gmail.com"
] | chencheng0816@gmail.com |
0df148f256b1c37b892662b5f55567ca4079091c | 4b9c7c940461efaa871da3e31c69584be16ffdc6 | /app/src/test/java/com/rkv/voiceassistantforvisuallyimpaired/ExampleUnitTest.java | db10d7335208adb0e78c6cb024440e3238c2908b | [] | no_license | satyamraj18/VoiceAssistant | e0b4d00d9c28a923345f5070b7f595c0ffc775b6 | be035d68aee8467929b93f2c075aee2a23c626ea | refs/heads/master | 2020-05-17T19:21:35.851146 | 2019-04-28T13:50:19 | 2019-04-28T13:50:19 | 183,913,274 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 419 | java | package com.rkv.voiceassistantforvisuallyimpaired;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"talk2satyam.raj@gmail.com"
] | talk2satyam.raj@gmail.com |
a944aedc237edf38f0e93e3ca63b896d39e4d9b2 | 206d15befecdfb67a93c61c935c2d5ae7f6a79e9 | /team1_videoplay_v2.0/src/team1/videoplay/user/servlet/UserStatusModifyServlet.java | d031ed14cb85f42fc5833b4c39b62ca41164b9df | [] | no_license | MarkChege/micandroid | 2e4d2884929548a814aa0a7715727c84dc4dcdab | 0b0a6dee39cf7e258b6f54e1103dcac8dbe1c419 | refs/heads/master | 2021-01-10T19:15:34.994670 | 2013-05-16T05:56:21 | 2013-05-16T05:56:21 | 34,704,029 | 0 | 1 | null | null | null | null | WINDOWS-1252 | Java | false | false | 1,163 | java | package team1.videoplay.user.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import team1.videoplay.user.model.User;
import team1.videoplay.user.service.impl.UserServiceImpl;
public class UserStatusModifyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int userID = Integer.parseInt(request.getParameter("id"));
int tag = Integer.parseInt(request.getParameter("tag"));
User user = UserServiceImpl.getInstance().getUser(userID);
if(tag==0){
//¶³½á
user.setUserStatus(1);
UserServiceImpl.getInstance().updateUserStatus(user);
}else {
user.setUserStatus(0);
UserServiceImpl.getInstance().updateUserStatus(user);
}
response.sendRedirect("manage/memberManage.jsp");
}
}
| [
"zoopnin@29cfa68c-37ae-8048-bc30-ccda835e92b1"
] | zoopnin@29cfa68c-37ae-8048-bc30-ccda835e92b1 |
24403cd79bb89a0e73f1a373b1ffaef0caad2fdc | 75806aade25df0b6f65095415f3b80bf8f3b0958 | /src/main/java/request/FormatResult.java | 5eda0e0c693339fd8ed523ecc615f45afcffeb86 | [] | no_license | jswalker808/cvsFormatter | 78b66b42f6d05fac0302f8353948e34fc2da06a3 | c122549955749a1734c58900e37b5f979d99b034 | refs/heads/master | 2020-08-29T03:12:27.587969 | 2019-10-28T04:09:47 | 2019-10-28T04:09:47 | 217,906,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 386 | java | package request;
public class FormatResult {
private String formattedString;
public FormatResult(String formattedString) {
this.formattedString = formattedString;
}
public String getFormattedString() {
return formattedString;
}
public void setFormattedString(String formattedString) {
this.formattedString = formattedString;
}
}
| [
"jamesswalker808@gmail.com"
] | jamesswalker808@gmail.com |
33e53139d210f195cc5496771b868561bd290fd2 | 7d9f97dc1c3a7e33b792b488015b5cfdd87d80c0 | /test/jp/itacademy/samples/gae/controller/memcache/employee/List2ControllerTest.java | a5217c111bdfdfe552cdc5a0ffd06fb155dda2d3 | [] | no_license | itacademy/gae-samples | fc66b1bf8b72a4a017dc15dc423a6189de966cf4 | 43a068843d5c69fda27471c6484635cfe6dc3834 | refs/heads/master | 2016-09-06T14:49:05.407903 | 2013-01-18T19:52:16 | 2013-01-18T19:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 630 | java | package jp.itacademy.samples.gae.controller.memcache.employee;
import org.slim3.tester.ControllerTestCase;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class List2ControllerTest extends ControllerTestCase {
@Test
public void run() throws Exception {
tester.start("/memcache/employee/list2");
List2Controller controller = tester.getController();
assertThat(controller, is(notNullValue()));
assertThat(tester.isRedirect(), is(false));
assertThat(tester.getDestinationPath(), is(nullValue()));
}
}
| [
"fanban.xiaofan@gmail.com"
] | fanban.xiaofan@gmail.com |
e3b90533004e29cc10ced939a1833fccc9718c99 | 0d60c67c2f1135c75b42de90a6e5f8c96543ff42 | /app/src/main/java/pl/mrucznik/gwint/controller/activities/IGameController.java | 771bdcf2d7321a58b337e589c33f095a5e4b6280 | [] | no_license | Mrucznik/Gwint | f6059c1aa605c6afce14c1297e8024f02017ded9 | 423a0d46a480c1eb9c4ee1b2c63515b70e71b37b | refs/heads/master | 2021-01-19T08:37:49.891124 | 2020-10-05T23:03:07 | 2020-10-05T23:03:07 | 74,205,171 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 693 | java | package pl.mrucznik.gwint.controller.activities;
import android.widget.Toast;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
import pl.mrucznik.gwint.model.Game;
import pl.mrucznik.gwint.model.Player;
import pl.mrucznik.gwint.model.cards.AttackRow;
import pl.mrucznik.gwint.model.cards.GwentCard;
/**
* Created by Mrucznik on 09.09.2017.
*/
public interface IGameController {
void startGame();
void showRowMenu(Consumer<AttackRow> callback);
void updatePoints(Map<Player, Map<AttackRow, Integer>> points);
void sendMessage(String message);
void updatePlayer(Player player);
void onNextRound();
void onGameEnds();
}
| [
"mrucznix@gmail.com"
] | mrucznix@gmail.com |
b238a9c893742b5bde41bb791722e172284585d6 | c89da0067f3de3ff509f4a56b21b55cccca349f9 | /team_vv/src/main/java/java2/application_target_list/console_ui/actions/AddTargetUIAction.java | 0fa7070dcfa993e70b4e3955081cd4dcb18bc431 | [] | no_license | Marxjava/java2_thursday_online_2020_autumn | 7827628d40c10a00a14991791f4b01f2eaddc3f2 | f86709f6b8b8d9f020a6495a348528885efc366d | refs/heads/master | 2023-02-04T02:42:56.611839 | 2020-12-25T19:33:27 | 2020-12-25T19:33:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,417 | java | package java2.application_target_list.console_ui.actions;
import java2.application_target_list.core.requests.AddTargetRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java2.application_target_list.console_ui.UIAction;
import java2.application_target_list.core.responses.AddTargetResponse;
import java2.application_target_list.core.responses.CoreError;
import java2.application_target_list.core.services.AddTargetService;
import java.util.Scanner;
@Component
public class AddTargetUIAction implements UIAction {
@Autowired private AddTargetService addTargetService;
private final Scanner scr = new Scanner(System.in);
@Override
public void execute() {
while (true){
String targetName = getNameFromUser();
String targetDescription = getDescriptionFromUser();
Integer targetDeadline = getDeadlineFromUser();
AddTargetRequest request = createRequest(targetName,targetDescription,targetDeadline);
AddTargetResponse response = createResponse(request);
if (response.hasErrors()) {
printResponseErrors(response);
} else {
printResponseResultMessage();
break;
}
}
}
private void printResponseResultMessage(){
System.out.println("----------");
System.out.println("Your target was added to list.");
System.out.println("----------");
}
private void printResponseErrors(AddTargetResponse response){
response.getErrorList().forEach(System.out::println);
}
private AddTargetResponse createResponse(AddTargetRequest request){
return addTargetService.execute(request);
}
private AddTargetRequest createRequest(String targetName, String targetDescription, Integer targetDeadline){
return new AddTargetRequest(targetName,targetDescription,targetDeadline);
}
private String getNameFromUser(){
System.out.print("Enter target name: ");
return scr.nextLine();
}
private String getDescriptionFromUser(){
System.out.print("Enter target description: ");
return scr.nextLine();
}
private Integer getDeadlineFromUser(){
System.out.print("Enter target deadline(days): ");
return Integer.parseInt(scr.nextLine());
}
}
| [
"vadims.vladisevs@gmail.com"
] | vadims.vladisevs@gmail.com |
2211e15af2b0146a69d7efe7d93ffe658901b34c | c77625eb0f823ee38f1e5e275e2a09959f4ca810 | /src/com/learning/Basics/AccessSpecifiers/Plant.java | f1601fe608959f72c5cc7a239df4d5e280689013 | [] | no_license | sahithipeddi/learning | 4f79d4748a6dee0f7b47dca8c16f08f7fb0c2040 | 16ed36838c9e618e2762d6a7d7e774ccf9931fef | refs/heads/master | 2023-03-01T01:27:04.579109 | 2021-02-09T23:09:42 | 2021-02-09T23:09:42 | 337,556,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 392 | java | package com.learning.Basics.AccessSpecifiers;
public class Plant {
// Bad practice
public String name;
// Acceptable practise -- as long as it's final
public final static int SEQNUM=8;
private String type;
protected String size;
int height;
public Plant(){
this.name = "I'm freddie";
type = "plant";
//
this.size = "medium";
}
}
| [
"speddi@apple.com"
] | speddi@apple.com |
72b703f18cb2e34167da4a492b739b40aacf689f | 27e1bb8c8836a84914636e820979ddf7ad11dc4f | /src/main/java/com/github/xtralife/leetcode/problems/p301/remove_invalid_parentheses/Solution.java | 0ac64a7d578b338f42b0efe689ea1aa1936fd7da | [] | no_license | xtralife/leetcode | 1ec656a301b77fb592e309de1b793c63cff3be86 | de80a96ff9ae520d5aec7b900ec905526e1c58c7 | refs/heads/master | 2023-04-13T05:00:59.898251 | 2021-04-11T17:41:03 | 2021-04-11T17:41:03 | 294,781,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,849 | java | package com.github.xtralife.leetcode.problems.p301.remove_invalid_parentheses;
import java.util.*;
public class Solution {
private final Set<String> validExpressions = new HashSet<>();
public List<String> removeInvalidParentheses(String s) {
validExpressions.clear();
int left = 0;
int right = 0;
for (char ch : s.toCharArray()) {
if (ch == '(') {
left++;
}
if (ch == ')') {
if (left > 0) {
left--;
} else {
right++;
}
}
}
recurse(s, 0, 0, 0, left, right, new StringBuilder());
return new ArrayList<>(validExpressions);
}
private void recurse(String s, int index, int leftCount, int rightCount, int leftRem, int rightRem, StringBuilder expr) {
if (index == s.length()) {
if (leftRem == 0 && rightRem == 0) {
validExpressions.add(expr.toString());
}
return;
}
char ch = s.charAt(index);
if (ch == '(' && leftRem > 0) {
recurse(s, index + 1, leftCount, rightCount, leftRem - 1, rightRem, expr);
}
if (ch == ')' && rightRem > 0) {
recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem - 1, expr);
}
expr.append(ch);
if (ch == '(') {
recurse(s, index + 1, leftCount + 1, rightCount, leftRem, rightRem, expr);
}
if (ch == ')' && leftCount > rightCount) {
recurse(s, index + 1, leftCount, rightCount + 1, leftRem, rightRem, expr);
}
if (ch != '(' && ch != ')') {
recurse(s, index + 1, leftCount, rightCount, leftRem, rightRem, expr);
}
expr.deleteCharAt(expr.length() - 1);
}
}
| [
"anatolii.tsaruk@ticketmaster.com"
] | anatolii.tsaruk@ticketmaster.com |
912cf1ded31110e39ac35ded6c458310d528127a | 16c414980c4f703f3530c062468aa9cde086109e | /app/src/main/java/com/liji/as/pictureselect/adapter/PhotoRecyclerViewAdapter.java | 146b9ec54fd59cf3438b6cf3907136b142e0117b | [] | no_license | snowleopard668/WeiChaoLeopard-TakePhoto-master | f0566cdbd4cff8ba594eaa9fd803cc8752d25e37 | 3e55356afcbc834218ac56f24cafef1b76ac5533 | refs/heads/master | 2021-08-08T10:42:51.424391 | 2017-11-10T06:18:43 | 2017-11-10T06:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,993 | java | package com.liji.as.pictureselect.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.liji.as.pictureselect.R;
import com.liji.as.pictureselect.activity.MainActivity;
import com.liji.as.pictureselect.activity.photo.PreviewPhotoActivity;
import com.liji.as.pictureselect.utils.XCallbackListener;
import java.util.ArrayList;
import java.util.List;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.galleryfinal.widget.GFImageView;
/**
* Created by liji on 2016/5/13.
*/
public class PhotoRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
/**
* 一行最多显示的图片数量
*/
public static final int NUM_ITEM = 6;
private Context mContext;
private LayoutInflater mInflater;
private List<PhotoInfo> mPhotoInfoList;
/**
* 底部添加图片view
*/
private final int ITEM_FOOTER = 0;
/**
* 内容区域,显示图片
*/
private final int ITEM_CONTENT = 1;
XCallbackListener mXCallbackListener;
FragmentManager fragmentManager;
public PhotoRecyclerViewAdapter(Context mContext, FragmentManager fragmentManager, List<PhotoInfo> mPhotoInfoList, XCallbackListener mXCallbackListener) {
this.mContext = mContext;
this.fragmentManager=fragmentManager;
this.mPhotoInfoList = mPhotoInfoList;
mInflater = LayoutInflater.from(mContext);
this.mXCallbackListener = mXCallbackListener;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ITEM_FOOTER) {
return new FootViewHolder(mInflater.inflate(R.layout.item_photo_add, parent, false));
} else {
return new ContentViewHolder(mInflater.inflate(R.layout.item_adapter_photo_list, parent, false));
}
}
@Override
public int getItemViewType(int position) {
if (getDatas().size() <= NUM_ITEM) {
if (getDatas().size() == 0) {//没有数据,显示添加按钮
return ITEM_FOOTER;
} else {
if (position == getDatas().size()) {//在范围内最后一个显示添加按钮,其余显示数据
return ITEM_FOOTER;
} else {
return ITEM_CONTENT;
}
}
} else {
return ITEM_CONTENT;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ContentViewHolder) {//显示图片数据
String path = "";
PhotoInfo photoInfo = getDatas().get(position);
if (photoInfo != null) {
path = photoInfo.getPhotoPath();
}
((ContentViewHolder) holder).mIvPhoto.setImageResource(cn.finalteam.galleryfinal.R.drawable.ic_gf_default_photo);
((ContentViewHolder) holder).mIvDelete.setImageResource(GalleryFinal.getGalleryTheme().getIconDelete());
Drawable defaultDrawable = mContext.getResources().getDrawable(cn.finalteam.galleryfinal.R.drawable.ic_gf_default_photo);
GalleryFinal.getCoreConfig().getImageLoader().displayImage((Activity) mContext, path, ((ContentViewHolder) holder).mIvPhoto, defaultDrawable, 100, 100);
((ContentViewHolder) holder).mIvDelete.setVisibility(View.VISIBLE);
((ContentViewHolder) holder).mIvDelete.setOnClickListener(new OnDeletePhotoClickListener(position, mXCallbackListener));
//查看预览图
((ContentViewHolder) holder).mIvPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, PreviewPhotoActivity.class);
intent.putExtra(PreviewPhotoActivity.PHOTO_LIST, (ArrayList) getDatas());
intent.putExtra(PreviewPhotoActivity.PHOTO_INDEX, position);
mContext.startActivity(intent);
}
});
} else if (holder instanceof FootViewHolder) {//显示添加按钮
// if (position == getDatas().size() && position == NUM_ITEM) {
// ((FootViewHolder) holder).mImageAdd.setVisibility(View.GONE);
// } else {
// ((FootViewHolder) holder).mImageAdd.setVisibility(View.VISIBLE);
((FootViewHolder) holder).mImageAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity) mContext).openChoiceDialog(mContext,fragmentManager);
}
});
// }
}
}
//包含一个添加按钮
@Override
public int getItemCount() {
int num = mPhotoInfoList.size();
int total = 0;
if (num < NUM_ITEM) {
total = ++num;
} else {
total = num;
}
return total;
}
//底部ViewHolder
public static class FootViewHolder extends RecyclerView.ViewHolder {
ImageView mImageAdd;
public FootViewHolder(View footView) {
super(footView);
mImageAdd = (ImageView) itemView.findViewById(R.id.imageviewadd);
}
}
//内容viewHolder
public static class ContentViewHolder extends RecyclerView.ViewHolder {
GFImageView mIvPhoto;
ImageView mIvDelete;
public ContentViewHolder(View itemView) {
super(itemView);
mIvPhoto = (GFImageView) itemView.findViewById(R.id.iv_photo);
mIvDelete = (ImageView) itemView.findViewById(R.id.iv_delete);
}
}
/**
* 返回列表数据
*
* @return
*/
public List<PhotoInfo> getDatas() {
return this.mPhotoInfoList;
}
//图片删除操作
private class OnDeletePhotoClickListener implements View.OnClickListener {
private int position;
private XCallbackListener mXCallbackListener;
public OnDeletePhotoClickListener(int position, XCallbackListener mXCallbackListener) {
this.position = position;
this.mXCallbackListener = mXCallbackListener;
}
@Override
public void onClick(View view) {
PhotoInfo photoInfo = null;
try {
photoInfo = getDatas().remove(position);
mXCallbackListener.call(position);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
}
}
| [
"weichao@example.com"
] | weichao@example.com |
b0eaa3831fa0da0bde3c4065fca6713ed1729e02 | cd7c753f835d1817f01dc9b861b17cc35cb932e5 | /ConsumirApiRest/app/src/main/java/com/example/consumirapirest/InsumosFragment.java | f408947bd3ef48cb6d7a074398b4726a5b95e554 | [] | no_license | Dukecero/altoqueapi | c7b75542cf514a67a2cc897fb5776440e975df31 | d6b1c84f08326e9559b488b13cf7a076faaf88ed | refs/heads/master | 2022-12-12T14:12:51.203484 | 2020-01-16T23:01:25 | 2020-01-16T23:01:25 | 234,426,984 | 0 | 0 | null | 2022-12-11T20:51:39 | 2020-01-16T22:50:32 | HTML | UTF-8 | Java | false | false | 6,427 | java | package com.example.consumirapirest;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.consumirapirest.adapters.ListaAdapter;
import com.example.consumirapirest.interfaces.JsonPlaceHolderApi;
import com.example.consumirapirest.model.Insumo;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link InsumosFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link InsumosFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class InsumosFragment extends Fragment {
RecyclerView recyclerview;
Button btnVerCarro;
private ArrayList<Insumo> listInsumo = new ArrayList<>();
private ArrayList<Insumo> carroCompras = new ArrayList<>();
private ListaAdapter lAdapter;
View vista;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public InsumosFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment InsumosFragment.
*/
// TODO: Rename and change types and number of parameters
public static InsumosFragment newInstance(String param1, String param2) {
InsumosFragment fragment = new InsumosFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
vista = inflater.inflate(R.layout.fragment_insumos, container, false);
btnVerCarro = vista.findViewById(R.id.btnVerCarro);
recyclerview = vista.findViewById(R.id.recyclerViewInsumo);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
getPosts();
return vista;
}
private void getPosts(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.217:3030/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Insumo>> call = jsonPlaceHolderApi.getPost();
call.enqueue(new Callback<List<Insumo>>() {
@Override
public void onResponse(Call<List<Insumo>> call, Response<List<Insumo>> response) {
if(!response.isSuccessful()){
//// mJsonTxtView.setText("Codigo:"+response.code());
Toast.makeText(getContext(),"Exitoso", Toast.LENGTH_SHORT);
return;
}
List<Insumo> postsList = response.body();
listInsumo.clear();
for(Insumo posts: postsList){
String numero = posts.getIns_codigo();
String nombre = posts.getIns_nombre();
String precio = posts.getIns_pre_uni();
String categoria = posts.getCat_nombre();
String image = posts.getIns_imagen();
listInsumo.add(new Insumo(numero,nombre,precio,categoria,image));
}
lAdapter = new ListaAdapter(getContext(),btnVerCarro,listInsumo,carroCompras);
recyclerview.setAdapter(lAdapter);
}
@Override
public void onFailure(Call<List<Insumo>> call, Throwable t) {
// mJsonTxtView.setText(t.getMessage());
Toast.makeText(getContext(),"Fallo", Toast.LENGTH_SHORT);
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| [
"SteveAguilar@gmail.com"
] | SteveAguilar@gmail.com |
20229bff3722aa2bb5844e10e9e3e034f4f7261a | 1cf57a9686b6db8fe81f50669a7a289724994504 | /ManchesterCoding/src/physical_network/MyTwistedWirePair.java | a5225b157eef8decabd74ad61f235816da64cdf0 | [] | no_license | derng/ManchesterCoding | b5e6dad2313c98899fde68b1e7a8a4ea0a3182a8 | 3af8934d30a0d3bb4b1779c025999de3b7af6b4a | refs/heads/master | 2020-04-04T03:45:50.949679 | 2013-11-17T21:19:34 | 2013-11-17T21:19:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,504 | java | /*
* (c) K.Bryson, Dept. of Computer Science, UCL (2013)
*/
package physical_network;
/**
*
* %%%%%%%%%%%%%%%% YOU NEED TO IMPLEMENT THIS %%%%%%%%%%%%%%%%%%
*
* Concrete implementation of the Twisted Wire Pair.
*
* This implementation will simply ADD TOGETHER all current voltages set
* by different devices attached to the wire.
*
* Thus you may have "Network Card A" device setting voltages to transfer bits
* across the wire and at the same time a "Thermal Noise" device which
* is setting random voltages on the wire. These voltages should then
* be added together so that getVoltage() returns the sum of voltages
* at any particular time.
*
* Similarly any number of network cards may be attached to the wire and
* each be setting voltages ... the wire should add all these voltages together.
*
* @author K. Bryson
*/
class MyTwistedWirePair implements TwistedWirePair {
private double signal1V, signal2V, noiseV;
public MyTwistedWirePair () {
this.signal1V = 0;
this.signal2V = 0;
this.noiseV = 0;
}
public synchronized void setVoltage(String device, double voltage) {
if (device.equals("Network Card A")) {
this.signal1V = voltage;
} else if (device.equals("Network Card B")) {
this.signal2V = voltage;
} else if (device.equals("Thermal Noise")) {
this.noiseV = voltage;
}
}
public synchronized double getVoltage(String device) {
return this.signal1V + this.signal2V + this.noiseV;
}
}
| [
"derngy@gmail.com"
] | derngy@gmail.com |
9b297460fb56a24d70cd0aa0d8aa70be8f672821 | 6378473772ba75153d24ce3907317455555a5273 | /src/pos/advancedTickect/first/At1NextBtn.java | bca335cfa527d020c95d8bad9d91a662fd5f10c2 | [] | no_license | kes0421/POS | fd087a658cbdbeaf5d6fea21a4895a1108b735d3 | 36844bc3f6f2a58cd60f2741661cca7d4c94a529 | refs/heads/master | 2023-07-23T23:02:25.111106 | 2021-08-04T06:45:34 | 2021-08-04T06:45:34 | 389,265,454 | 1 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 409 | java | package pos.advancedTickect.first;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class At1NextBtn extends JButton{
public At1NextBtn(JFrame at1F, JLabel at1L3) {
super("Next");
setFont(new Font("±¼¸²", Font.BOLD, 40));
setBackground(Color.white);
addActionListener(new At1NextBtnAct(at1F, at1L3));
}
}
| [
"82787408+dhshffnfn123@users.noreply.github.com"
] | 82787408+dhshffnfn123@users.noreply.github.com |
9c4e1d78040a315a2f6d195086bae7f2551e4160 | d476bc92c4489ff5b613512b71751574473ccccd | /src/test/java/AdminLinks.java | d438471a6d24bf430a4cd6275d9d2dd778d8a0b3 | [
"Apache-2.0"
] | permissive | MarvinKRK/selenium-test-repository | 21969d3d61d24d3ac70935ca588e29ffc5af98dc | dd99161a8c0b2c22c81eb3c18a88f4b46d99038e | refs/heads/master | 2021-08-23T03:27:47.001913 | 2017-12-02T22:27:52 | 2017-12-02T22:27:52 | 109,267,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,040 | java | import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated;
public class AdminLinks {
private WebDriver driver;
private WebDriverWait wait;
@BeforeTest
public void setUp() {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 5);
}
@Test()
public void adminLinks() {
driver.get("http://localhost/litecart/admin/");
driver.findElement(By.name("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin");
driver.findElement(By.name("login")).click();
wait.until(visibilityOfElementLocated(By.className("fa-sign-out")));
List<WebElement> links = driver.findElements(By.cssSelector("ul#box-apps-menu > li"));
for (int i = 1; i <= links.size(); ++i) {
driver.findElement(By.cssSelector("ul#box-apps-menu > li:nth-child(" + i + ")")).click();
List<WebElement> links2 = driver.findElements(By.cssSelector("ul#box-apps-menu > li:nth-child(" + i + ") li"));
if (links2.size() > 0) {
for (int j = 1; j <= links2.size(); ++j) {
driver.findElement(By.cssSelector("ul#box-apps-menu > li:nth-child(" + i + ") li:nth-child(" + j + ")")).click();
wait.until(visibilityOfElementLocated(By.tagName("h1")));
}
} else {
wait.until(visibilityOfElementLocated(By.tagName("h1")));
}
}
}
@AfterTest
public void tearDown() {
driver.quit();
}
}
| [
"maciek4@gmail.com"
] | maciek4@gmail.com |
2cb699fd93db9c25537b8a7137884f43cae620d6 | f8d042e9f6170d8e1b9930bed87d42b0ff89f14e | /Code/MyShanghai/src/Shanghai20/model/StdBoardManager.java | 9900cb305aad98bd9eda92487b47a0f1635b239f | [] | no_license | relhanred/majhong | bff862ce5c2f08dd81992a63a93f7d14fc0999f3 | ebd2ddf3f587360d039cef4a92ab4dc2a48446f6 | refs/heads/main | 2023-06-28T12:46:02.672736 | 2021-07-25T22:52:55 | 2021-07-25T22:52:55 | 389,454,719 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,209 | java | package Shanghai20.model;
import java.util.Iterator;
import java.util.LinkedList;
import Shanghai20.util.Contract;
import Shanghai20.util.Triplet;
public class StdBoardManager implements BoardManager {
public StdBoardManager() {
}
/**
* Retourne sous forme d'une liste de Triplet tous les voisins à gauche et à droite du Triplet {triple} dans la liste {L}
* @pre
* L != null
*/
public LinkedList<Triplet> getAllCoordAround(LinkedList<Triplet> L, int maxX, int maxY, Triplet triple) {
Contract.checkCondition(L != null);
LinkedList<Triplet> coordAround = new LinkedList<Triplet>();
int x = triple.getFirst();
int y = triple.getSecond();
int s = triple.getThird();
if (x >= 2) {
coordAround.add(new Triplet(x - 2, y, s));
if (y < maxY - 2) {
coordAround.add(new Triplet(x - 2, y + 1, s));
}
}
if (y > 0 && x < maxX - 2 ) {
coordAround.add(new Triplet(x + 2, y - 1, s));
}
if (y > 0 && x >= 2) {
coordAround.add(new Triplet(x - 2, y - 1, s));
}
if (x < maxX - 2) {
coordAround.add(new Triplet(x + 2, y , s));
if (y < maxY - 2) {
coordAround.add(new Triplet(x + 2, y + 1, s));
}
}
Iterator<Triplet> iteCoord = coordAround.iterator();
while (iteCoord.hasNext()) {
Triplet t = iteCoord.next();
if(!t.contains(L)) {
iteCoord.remove();
}
}
return coordAround;
}
/**
* Retourne sous forme d'une liste de Triplet tous les voisins en haut du Triplet {triple} contenu dans la liste {L}
* si le boolean {b} est à true
*
* @pre
* L != null
*/
public LinkedList<Triplet> getAllNeighborsAbove(LinkedList<Triplet> L, Triplet triple, int maxX, int maxY, boolean b) {
Contract.checkCondition(L != null);
Contract.checkCondition(triple != null);
int s = triple.getThird();
LinkedList<Triplet> coordAbove = new LinkedList<Triplet>();
if (b == true) {
s = s - 1;
}else {
s = s + 1;
}
int x = triple.getFirst();
int y = triple.getSecond();
coordAbove.add(new Triplet(x, y, s));
if (x < maxX - 2) {
coordAbove.add(new Triplet(x + 1, y, s));
if (y > 0) {
coordAbove.add(new Triplet(x, y + 1, s));
}
if (y < maxY - 1) {
coordAbove.add(new Triplet(x + 1, y + 1, s));
}
}
if (x > 0 && y > 0) {
coordAbove.add(new Triplet(x - 1, y - 1, s));
}
if (x > 0) {
coordAbove.add(new Triplet(x - 1, y, s));
if (y < maxY) {
coordAbove.add(new Triplet(x - 1, y + 1, s));
}
}
if (y > 0) {
coordAbove.add(new Triplet(x, y - 1, s));
if (x < maxX - 2) {
coordAbove.add(new Triplet(x + 1, y - 1, s));
}
}
Iterator<Triplet> iteCoord = coordAbove.iterator();
while (iteCoord.hasNext()) {
Triplet tri = iteCoord.next();
if(!tri.contains(L)) {
iteCoord.remove();
}
}
return coordAbove;
}
/**
* Retourne sous forme d'une liste de Triplet tous les voisins en bas du Triplet {triple} dans la liste {L}
* @pre
* L != null
* triple != null;
*/
public LinkedList<Triplet> getAllNeighborsBelow(LinkedList<Triplet> L, Triplet triple, int maxX, int maxY) {
Contract.checkCondition(L != null);
Contract.checkCondition(triple != null);
return getAllNeighborsAbove(L, triple, maxX, maxY, false);
}
/**
* Supprime toutes les tuiles de {L} situé sur la même ligne que c (sauf les voisins direct) et les ajoutes dans {L2}
* @pre
* L != null
* L2 != null
* c != null
*/
public void removeLigne(LinkedList<Triplet> L,LinkedList<Triplet> L2, Triplet c, int maxX, int maxY) {
Contract.checkCondition(c != null);
Contract.checkCondition(L != null);
Contract.checkCondition(L2 != null);
LinkedList<Triplet> coordAround = new LinkedList<Triplet>();
int x = c.getFirst();
int y = c.getSecond();
int z = c.getThird();
int n = 0;
boolean b = true;
x = x - 2;
Triplet triple = new Triplet(x,y,z);
while(b) {
Triplet c0 = new Triplet(x - 2, y - 1, z);
Triplet c1 = new Triplet(x - 2, y, z);
Triplet c2 = new Triplet(x - 2, y + 1, z);
if (x >= 2 && c1.contains(L) && triple.contains(L)) {
coordAround.add(c1);
++n;
}
if (y < maxY - 2 && c2.contains(L) && triple.contains(L)) {
coordAround.add(c2);
++n;
}
if (y > 0 && x >= 2 && c0.contains(L) && triple.contains(L)) {
coordAround.add(c0);
++n;
}
if (n == 0) {
b = false;
}
n = 0;
x = x - 2;
}
x = c.getFirst();
y = c.getSecond();
n = 0;
b = true;
x = x + 2;
triple = new Triplet(x,y,z);
while(b) {
Triplet c3 = new Triplet(x + 2, y - 1, z);
Triplet c4 = new Triplet(x + 2, y, z);
Triplet c5 = new Triplet(x + 2, y + 1, z);
if (y > 0 && x < maxX - 2 && c3.contains(L) && triple.contains(L)) {
coordAround.add(c3);
++n;
}
if (x < maxX - 2 && c4.contains(L) && triple.contains(L)) {
coordAround.add(c4);
++n;
}
if ((y < maxY - 2) && c5.contains(L) && triple.contains(L)) {
coordAround.add(c5);
++n;
}
if (n == 0) {
b = false;
}
n = 0;
x = x + 2;
}
Iterator<Triplet> iterator = coordAround.iterator();
while(iterator.hasNext()) {
Triplet crd = iterator.next();
if (crd.contains(L)) {
L2.add(crd);
L.remove(crd);
}
}
}
}
| [
"relhanti@gmail.com"
] | relhanti@gmail.com |
a97a8338ff7aee90bb8368a0a76754116cbffa36 | 80c8fd1f7f66424bc69730aa48e08a1325db16ff | /app/src/main/java/projects/shahabgt/com/myuniversity/ViewPost.java | 0b7ea8272a4d3484c16b645b0d21052682bd3dc9 | [
"MIT"
] | permissive | ShahabGT/MyUniversity | 8e50625dc1904ccbfef7dc2a92f71192940169a9 | 15246bf912bd375c1426af6159a81b4e38d95317 | refs/heads/master | 2020-03-20T20:26:28.251026 | 2018-06-25T07:04:05 | 2018-06-25T07:04:05 | 137,687,813 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,364 | java | package projects.shahabgt.com.myuniversity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baoyz.widget.PullRefreshLayout;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.marcohc.toasteroid.Toasteroid;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import projects.shahabgt.com.myuniversity.adapters.ViewpostAdapter;
import projects.shahabgt.com.myuniversity.classes.BackgroundTask;
public class ViewPost extends AppCompatActivity {
RecyclerView recyclerView;
public static ViewpostAdapter adapter;
ImageView back;
RecyclerView.LayoutManager layoutManager;
LinearLayout linearLayout,errorlayout,loadinglayout;
TextView toolbar_text;
PullRefreshLayout pullRefreshLayout;
SimpleDraweeView loadingimg,nointernet;
MaterialSearchView searchView;
MenuItem item;
public static int mstate, fstate;
Toolbar toolbar;
FrameLayout toolbarcontainer;
FloatingActionButton fab1,fab2,fab3;
FloatingActionMenu fab;
int ws2;
Bundle bundle;
SharedPreferences sp;
String person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fresco.initialize(ViewPost.this);
setContentView(R.layout.activity_view_post);
toolbarcontainer = findViewById(R.id.toolbar_container);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar_text = findViewById(R.id.toolbar_text);
bundle = getIntent().getExtras();
sp= getApplicationContext().getSharedPreferences("logininfo",0);
person= sp.getString("id","");
fab = findViewById(R.id.fab_menu);
fab.setMenuButtonColorNormal(Color.parseColor("#1d4054"));
fab.setMenuButtonColorPressed(Color.parseColor("#1d4054"));
fab1 = findViewById(R.id.fab_item1);
fab2 = findViewById(R.id.fab_item2);
fab3 = findViewById(R.id.fab_item3);
fab2.setEnabled(false);
fab3.setEnabled(false);
fab1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialDialog.Builder(ViewPost.this)
.title("Select Subject")
.items(R.array.subjectall)
.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
fab1.setLabelText(text.toString());
fab2.setLabelText("Select Department");
fab2.setEnabled(true);
fab3.setLabelText("Select SubDepartment");
fab3.setEnabled(false);
return true;
}
})
.show();
}
});
fab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialDialog.Builder(ViewPost.this)
.title("Select Department")
.items(R.array.catagoryall)
.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
fab3.setLabelText("Select SubDepartment");
ws2 = which;
if(which==0){
adapter.filter(fab1.getLabelText(),"all","all");
fab3.setLabelText("all");
fab3.setEnabled(false);
}else{
fab3.setEnabled(true);
}
fab2.setLabelText(text.toString());
return true;
}
})
.show();
}
});
fab3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MaterialDialog.Builder materialDialog = new MaterialDialog.Builder(ViewPost.this);
materialDialog.title("Select SubDepartment");
materialDialog.itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
fab3.setLabelText(text.toString());
adapter.filter(fab1.getLabelText(),fab2.getLabelText(),fab3.getLabelText());
return true;
}
});
switch (ws2){
case 0:
fab3.setLabelText("all");
break;
case 1:
materialDialog.items(R.array.catagory0all);
break;
case 2:
materialDialog.items(R.array.catagory1all);
break;
case 3:
materialDialog.items(R.array.catagory2all);
break;
case 4:
materialDialog.items(R.array.catagory3all);
break;
case 5:
materialDialog.items(R.array.catagory4all);
break;
}
materialDialog.show();
}
});
recyclerView= findViewById(R.id.viewpost_recylcer);
linearLayout = findViewById(R.id.viewpost_layout);
errorlayout = findViewById(R.id.viewpost_error);
pullRefreshLayout = findViewById(R.id.viewpost_swipeRefreshLayout);
layoutManager=new LinearLayoutManager(this);
loadinglayout = findViewById(R.id.viewpost_loadinglayout);
loadingimg = findViewById(R.id.viewpost_loadingimg);
Uri loadinguri= Uri.parse("asset:///loading.gif");
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setUri(loadinguri)
.setAutoPlayAnimations(true)
.build();
loadingimg.setController(controller);
loadinglayout.setVisibility(View.VISIBLE);
nointernet = findViewById(R.id.viewpost_nointernet);
Uri noinnetneturi= Uri.parse("asset:///nointernet.gif");
DraweeController controller2 = Fresco.newDraweeControllerBuilder()
.setUri(noinnetneturi)
.setAutoPlayAnimations(true)
.build();
nointernet.setController(controller2);
back = findViewById(R.id.toolbar_btn);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewPost.this.finish();
}
});
searchView = findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
adapter.search(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.search(newText);
return true;
}
});
String what = bundle.getString("what");
if(what.equals("viewpost")) {
fstate=1;
invalidateOptionsMenu();
toolbar_text.setText("Posts");
pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (checknet()) {
fab1.setLabelText("Select Subject");
fab1.setEnabled(true);
fab2.setLabelText("Select Department");
fab2.setEnabled(false);
fab3.setLabelText("Select SubDepartment");
fab3.setEnabled(false);
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getposts",getResources().getString(R.string.url)+"getposts.php");
} else {
loadinglayout.setVisibility(View.VISIBLE);
snackError();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}
});
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getposts",getResources().getString(R.string.url)+"getposts.php");
} else {
snackError();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}else if (what.equals("viewfav")){
fstate=0;
invalidateOptionsMenu();
toolbar_text.setText("My Favorites");
pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getfavposts",person);
} else {
loadinglayout.setVisibility(View.VISIBLE);
snackError2();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}
});
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getfavposts",person);
} else {
snackError2();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}else if (what.equals("myposts")){
mstate=0;
invalidateOptionsMenu();
fab.setVisibility(View.INVISIBLE);
fab.setEnabled(false);
toolbar_text.setText("My Posts");
pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getmyposts",person);
} else {
loadinglayout.setVisibility(View.VISIBLE);
snackError3();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}
});
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getmyposts",person);
} else {
snackError3();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
}
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy){
super.onScrolled(recyclerView, dx, dy);
if (dy >0) {
if (fab.isShown()) {
fab.hideMenuButton(true);
}
}
else if (dy <0) {
fab.showMenuButton(true);
}
}
});
}
@Override
protected void onResume() {
searchView.closeSearch();
fab.close(true);
super.onResume();
}
@Override
public void onBackPressed() {
if(errorlayout.getVisibility() == View.VISIBLE)
{
ViewPost.this.finish();
}
else if(searchView.isSearchOpen()) {
searchView.closeSearch();
}else if(fab.isOpened()){
fab.close(true);
}else {
ViewPost.this.finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_toolbar, menu);
item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
if(mstate==0)
{
menu.getItem(0).setVisible(false);
menu.getItem(1).setVisible(false);
}
else if(fstate==0)
{ menu.getItem(0).setVisible(true);
menu.getItem(1).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_hot:
if (checknet()) {
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 1);
backgroundTask.execute("getposts",getResources().getString(R.string.url)+"gethotposts.php");
} else {
loadinglayout.setVisibility(View.VISIBLE);
snackError();
Toasteroid.show(ViewPost.this, "Check Your Internet Connection", Toasteroid.STYLES.ERROR);
}
break;
}
return super.onOptionsItemSelected(item);
}
private boolean checknet(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
return activeInfo != null && activeInfo.isConnected();
}
private void snackError(){
mstate=0;
invalidateOptionsMenu();
loadinglayout.setVisibility(View.GONE);
errorlayout.setVisibility(View.VISIBLE);
Snackbar snackbar = Snackbar
.make(linearLayout, "Something Bad Happend", Snackbar.LENGTH_INDEFINITE)
.setAction("Try Again", new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checknet()) {
loadinglayout.setVisibility(View.VISIBLE);
errorlayout.setVisibility(View.GONE);
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getposts",getResources().getString(R.string.url)+"getposts.php");
}else {
snackError();
}
}
});
snackbar.show();
}
private void snackError2(){
mstate=0;
invalidateOptionsMenu();
loadinglayout.setVisibility(View.GONE);
errorlayout.setVisibility(View.VISIBLE);
Snackbar snackbar = Snackbar
.make(linearLayout, "Something Bad Happend", Snackbar.LENGTH_INDEFINITE)
.setAction("Try Again", new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checknet()) {
loadinglayout.setVisibility(View.VISIBLE);
errorlayout.setVisibility(View.GONE);
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getfavposts",person);
}else {
snackError();
}
}
});
snackbar.show();
}
private void snackError3(){
mstate=0;
invalidateOptionsMenu();
loadinglayout.setVisibility(View.GONE);
errorlayout.setVisibility(View.VISIBLE);
Snackbar snackbar = Snackbar
.make(linearLayout, "Something Bad Happend", Snackbar.LENGTH_INDEFINITE)
.setAction("Try Again", new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checknet()) {
loadinglayout.setVisibility(View.VISIBLE);
errorlayout.setVisibility(View.GONE);
BackgroundTask backgroundTask = new BackgroundTask(ViewPost.this, 0);
backgroundTask.execute("getmyposts",person);
}else {
snackError();
}
}
});
snackbar.show();
}
}
| [
"azimishahab@yahoo.com"
] | azimishahab@yahoo.com |
3adb91f8fd172757a45cce10a478646098b5dc86 | 2e9b1b549844b6248f8fb0097232caf64c80d11e | /src/main/java/edu/uiowa/slis/GRIDRDF/Other/OtherHasRelatedIterator.java | 38860ec0303b7c983243fa04f918f01f7133eb3b | [] | no_license | eichmann/GRIDRDFTagLib | 0a88019f73db08f7dfcefef04b8f5de8b58576b4 | caf3c049fa824f41bfe4ebf2882e75328b565ab2 | refs/heads/master | 2020-03-19T03:42:21.192207 | 2017-08-15T20:39:26 | 2017-08-15T20:39:26 | 135,754,427 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,688 | java | package edu.uiowa.slis.GRIDRDF.Other;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import java.util.Hashtable;
@SuppressWarnings("serial")
public class OtherHasRelatedIterator extends edu.uiowa.slis.GRIDRDF.TagLibSupport {
static OtherHasRelatedIterator currentInstance = null;
private static final Log log = LogFactory.getLog(OtherHasRelatedIterator.class);
static boolean firstInstance = false;
static boolean lastInstance = false;
String subjectURI = null;
String type = null;
String hasRelated = null;
ResultSet rs = null;
Hashtable<String,String> classFilter = null;
public int doStartTag() throws JspException {
currentInstance = this;
try {
Other theOther = (Other) findAncestorWithClass(this, Other.class);
if (theOther != null) {
subjectURI = theOther.getSubjectURI();
}
if (theOther == null && subjectURI == null) {
throw new JspException("subject URI generation currently not supported");
}
rs = getResultSet(prefix+"SELECT ?s ?t where {"
+" <" + subjectURI + "> <http://www.grid.ac/ontology/hasRelated> ?s . "
+" OPTIONAL { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?t } ."
+" FILTER NOT EXISTS {"
+" ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?subtype ."
+" ?subtype <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?t ."
+" filter ( ?subtype != ?t )"
+" }"
+"} ");
while(rs.hasNext()) {
QuerySolution sol = rs.nextSolution();
hasRelated = sol.get("?s").toString();
type = sol.get("?t") == null ? null : getLocalName(sol.get("?t").toString());
// if (type == null)
// continue;
if (classFilter == null || (classFilter != null && type != null && classFilter.containsKey(type))) {
log.info("instance: " + hasRelated + " type: " + type);
firstInstance = true;
lastInstance = ! rs.hasNext();
return EVAL_BODY_INCLUDE;
}
}
} catch (Exception e) {
log.error("Exception raised in OtherHasRelatedIterator doStartTag", e);
clearServiceState();
freeConnection();
throw new JspTagException("Exception raised in OtherHasRelatedIterator doStartTag");
}
return SKIP_BODY;
}
public int doAfterBody() throws JspException {
try {
while(rs.hasNext()) {
QuerySolution sol = rs.nextSolution();
hasRelated = sol.get("?s").toString();
type = sol.get("?t") == null ? null : getLocalName(sol.get("?t").toString());
// if (type == null)
// continue;
if (classFilter == null || (classFilter != null && type != null && classFilter.containsKey(type))) {
log.info("instance: " + hasRelated + " type: " + type);
firstInstance = false;
lastInstance = ! rs.hasNext();
return EVAL_BODY_AGAIN;
}
}
} catch (Exception e) {
log.error("Exception raised in OtherHasRelatedIterator doAfterBody", e);
clearServiceState();
freeConnection();
throw new JspTagException("Exception raised in OtherHasRelatedIterator doAfterBody");
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
currentInstance = null;
try {
// do processing
} catch (Exception e) {
log.error("Exception raised in OtherHasRelated doEndTag", e);
throw new JspTagException("Exception raised in OtherHasRelated doEndTag");
} finally {
clearServiceState();
freeConnection();
}
return super.doEndTag();
}
private void clearServiceState() {
subjectURI = null;
type = null;
hasRelated = null;
classFilter = null;
}
public void setType(String theType) {
type = theType;
}
public String getType() {
return type;
}
public void setHasRelated(String theHasRelated) {
hasRelated = theHasRelated;
}
public String getHasRelated() {
return hasRelated;
}
public static void setFirstInstance(Boolean theFirstInstance) {
firstInstance = theFirstInstance;
}
public static Boolean getFirstInstance() {
return firstInstance;
}
public static void setLastInstance(Boolean theLastInstance) {
lastInstance = theLastInstance;
}
public static Boolean getLastInstance() {
return lastInstance;
}
public void setClassFilter(String filterString) {
String[] classFilterArray = filterString.split(" ");
this.classFilter = new Hashtable<String, String>();
for (String filterClass : classFilterArray) {
log.info("adding filterClass " + filterClass + " to OtherHasRelatedIterator");
classFilter.put(filterClass, "");
}
}
public String getClassFilter() {
return classFilter.toString();
}
}
| [
"david-eichmann@uiowa.edu"
] | david-eichmann@uiowa.edu |
ff67a0b2e62d1a4989ab32c01bcc37a2c8741dec | 097acf45654e6c8ce107e6c1574c525d335c4092 | /ExerciciosJava/Exercicio55.java | 6cd1325e5c5c940d26933e4818924167bbedd14c | [] | no_license | jv-paltanin/java-basico | b74fac0e6a930de6a632eb8ffb342036a20ac4bb | af098a960f45355e2c20a443c7e5f02675f39919 | refs/heads/main | 2023-03-20T14:46:19.446279 | 2021-03-11T19:38:42 | 2021-03-11T19:38:42 | 346,815,483 | 2 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,106 | java | package exercicios;
import javax.swing.JOptionPane;
/**
* Programa para ler nome de 2 times e nº de gols de cada e mostrar o vencedor
*
* @author João Victor
* @since 09/02/2021
*/
public class Exercicio55 {
/*
* Método principal para executar a classe
*/
public static void main(String[] args) {
// declarando as variáveis
String time1, time2;
int gol1, gol2;
String msg = "";
// recebendo informação do usuário
time1 = JOptionPane.showInputDialog("Informe o nome do time da casa");
gol1 = Integer.parseInt(JOptionPane.showInputDialog("Gols da casa"));
time2 = JOptionPane.showInputDialog("Informe o nome do time vistante");
gol2 = Integer.parseInt(JOptionPane.showInputDialog("Gols do visitante"));
// verificando se houvve empate
if (gol1 == gol2) {
msg = "EMPATE";
} else if (gol1 > gol2) { // verificando se gol1 > gol2
msg = time1 + " é o Vencedor";
} else {
msg = time2 + " é o Vencedor";
}
// mostra na tela se houve empate ou mostra o vencedor
JOptionPane.showMessageDialog(null, msg);
}
} | [
"noreply@github.com"
] | noreply@github.com |
8398b408881151ad88f2cdfa7852a7f44f00981d | e2ef3ebf823681866c57bd43d6d00c700f10666e | /javafx-demos/src/main/java/com/ezest/javafx/demogallery/TodaysDateWiget.java | 024e97509afcf85de9a556238cf8702659dedf7a | [] | no_license | agbenn/javafx-demos | 3c24eed5f2b52092c30e8a778ccdcd2111ddf598 | 4302739a6156b066c0c4bf46867bd9f0dfc10923 | refs/heads/master | 2021-05-31T04:53:58.248369 | 2013-12-06T13:00:14 | 2013-12-06T13:00:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,739 | java | package com.ezest.javafx.demogallery;
import java.util.Calendar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Light.Distant;
import javafx.scene.effect.Lighting;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author Lawrence PremKumar
*/
public class TodaysDateWiget extends Application {
final double WIDTH = 150.0;
final double HEIGHT = 150.0;
public static void main(String[] args) {
Application.launch(TodaysDateWiget.class, args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
Group root = new Group();
Scene scene = new Scene(root, 300, 250, Color.LIGHTGREEN);
primaryStage.setScene(scene);
Button btn = new Button();
btn.setLayoutX(100);
btn.setLayoutY(80);
btn.setText("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Stage st = new Stage(StageStyle.UNDECORATED);
Group group = new Group();
Scene s = new Scene(group ,WIDTH+3,HEIGHT+5);
s.setFill(null);
group.getChildren().addAll(getToDayControl());
st.setScene(s);
st.show();
}
});
btn.fire();
root.getChildren().add(btn);
primaryStage.show();
primaryStage.close();
}
public Group getToDayControl(){
String[] months = {"Jan", "Feb","Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov","Dec"};
Calendar cal = Calendar.getInstance();
Group ctrl = new Group();
Rectangle rect = new Rectangle();
rect.setWidth(WIDTH);
rect.setHeight(HEIGHT);
rect.setArcHeight(10.0);
rect.setArcWidth(10.0);
Rectangle headerRect = new Rectangle();
headerRect.setWidth(WIDTH);
headerRect.setHeight(30);
headerRect.setArcHeight(10.0);
headerRect.setArcWidth(10.0);
Stop[] stops = new Stop[] { new Stop(0, Color.color(0.31, 0.31, 0.31, 0.443)), new Stop(1, Color.color(0, 0, 0, 0.737))};
LinearGradient lg = new LinearGradient( 0.482, -0.017, 0.518, 1.017, true, CycleMethod.REFLECT, stops);
headerRect.setFill(lg);
Rectangle footerRect = new Rectangle();
footerRect.setY(headerRect.getBoundsInLocal().getHeight() -4);
footerRect.setWidth(WIDTH);
footerRect.setHeight(125);
footerRect.setFill(Color.color(0.51, 0.671, 0.992));
final Text currentMon = new Text(months[(cal.get(Calendar.MONTH) )]);
currentMon.setFont(Font.font("null", FontWeight.BOLD, 24));
currentMon.setTranslateX((footerRect.getBoundsInLocal().getWidth() - currentMon.getBoundsInLocal().getWidth())/2.0);
currentMon.setTranslateY(23);
currentMon.setFill(Color.WHITE);
final Text currentDate = new Text(Integer.toString(cal.get(Calendar.DATE)));
currentDate.setFont(new Font(100.0));
currentDate.setTranslateX((footerRect.getBoundsInLocal().getWidth() - currentDate.getBoundsInLocal().getWidth())/2.0);
currentDate.setTranslateY(120);
currentDate.setFill(Color.WHITE);
ctrl.getChildren().addAll(rect, headerRect, footerRect , currentMon,currentDate);
DropShadow ds = new DropShadow();
ds.setOffsetY(3.0);
ds.setOffsetX(3.0);
ds.setColor(Color.GRAY);
ctrl.setEffect(ds);
return ctrl;
}
} | [
"saipradeep.dandem@gmail.com"
] | saipradeep.dandem@gmail.com |
1f73696c6f223a0b2e4166326c9c88905f3a6ab0 | 9c2c329e09f68097247e9af3ba010acb1d9e9fdd | /src/main/java/tn/esprit/spring/entity/Feedback.java | 98877f96e727d6d9c4e03c8e0fc914fd39819d85 | [] | no_license | samehsboui/kindergarten | 3aae0af1f273c3b773fc4efee663b480c891c070 | e6a4741526fc300f01385f493a957c3767a09992 | refs/heads/master | 2023-04-04T08:37:04.242979 | 2021-04-11T10:31:08 | 2021-04-11T10:31:08 | 351,576,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,784 | java | package tn.esprit.spring.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "T_Feedback")
public class Feedback implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Feedback_Id")
private long id;
@Column(name="Message_Date")
@Temporal(TemporalType.DATE)
private Date date;
@Column(name="note_ambiance")
private int note_ambiance;
@Column(name="note_emplacement")
private int note_emplacement;
@Column(name="note_organisation")
private int note_organisation;
@Column(name="note_objectifsEvent")
private int note_objectifsEvent;
@Column(name="note_experience")
private int note_experience;
// @ManyToOne
// @JoinColumn(name = "Event_id")
// private Events events;
public Feedback(Date date, int note_ambiance, int note_emplacement, int note_organisation, int note_objectifsEvent,
int note_experience) {
super();
this.date = date;
this.note_ambiance = note_ambiance;
this.note_emplacement = note_emplacement;
this.note_organisation = note_organisation;
this.note_objectifsEvent = note_objectifsEvent;
this.note_experience = note_experience;
// this.events = events;
}
public Feedback() {
super();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getNote_ambiance() {
return note_ambiance;
}
public void setNote_ambiance(int note_ambiance) {
this.note_ambiance = note_ambiance;
}
public int getNote_emplacement() {
return note_emplacement;
}
public void setNote_emplacement(int note_emplacement) {
this.note_emplacement = note_emplacement;
}
public int getNote_organisation() {
return note_organisation;
}
public void setNote_organisation(int note_organisation) {
this.note_organisation = note_organisation;
}
public int getNote_objectifsEvent() {
return note_objectifsEvent;
}
public void setNote_objectifsEvent(int note_objectifsEvent) {
this.note_objectifsEvent = note_objectifsEvent;
}
public int getNote_experience() {
return note_experience;
}
public void setNote_experience(int note_experience) {
this.note_experience = note_experience;
}
// public Events getEvents() {
// return events;
// }
//
// public void setEvents(Events events) {
// this.events = events;
// }
}
| [
"samehsboui.enicar@gmail.com"
] | samehsboui.enicar@gmail.com |
32503e17841d3631133f862f9136548c22984c46 | 79dd5a5b8130738f0ea3270c3339702c38ee4a1a | /src/com/itheima/quiz/Main.java | 28a8cc13ec5f867187d2ff80d5c3f0be9fa84db2 | [] | no_license | chancelau/quize | 28f23236c0ec5a1367afb08296a1be1898168be4 | b46a48f79e6aaa14d00d0b23df168c87a8720267 | refs/heads/master | 2020-05-23T19:28:03.248801 | 2019-05-22T23:26:04 | 2019-05-22T23:26:04 | 186,912,604 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,371 | java | package com.itheima.quiz;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.net.URL;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
URL location = getClass().getResource("/uiXml/main_ui.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
Parent root = fxmlLoader.load();
Controller controller = fxmlLoader.<Controller>getController();
//Parent root = FXMLLoader.load(getClass().getResource("main_ui.fxml"));
primaryStage.setTitle("知识竞赛");
primaryStage.setScene(new Scene(root, 800, 500));
primaryStage.setResizable(false);
primaryStage.show();
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
System.out.print("监听到窗口关闭");
System.exit(0);
}
});
}
}
| [
"chancelau@hotmail.com"
] | chancelau@hotmail.com |
97e438470ed3697375b85d1ee3422523ec6c7db3 | 3cb3d9f00ed5d4b12892f877354eef2398d3ad5e | /sms-sender/src/main/java/com/zuma/smssender/enums/error/ZhuWangSubmitErrorEnum.java | 963ed81bd2c3eec5d2bdd97f4bfef34bef69e836 | [] | no_license | BrightStarry/unifiedlogincloud | 4f631407b349dc5adf1353ddc32026b299dacb5d | d18066389bac7dfce7111635a2eaa2bbfdc03f09 | refs/heads/master | 2021-09-22T10:06:52.239762 | 2021-09-11T03:09:00 | 2021-09-11T03:09:00 | 110,092,022 | 1 | 4 | null | null | null | null | UTF-8 | Java | false | false | 956 | java | package com.zuma.smssender.enums.error;
import com.zuma.smssender.enums.CodeEnum;
import lombok.Getter;
/**
* author:ZhengXing
* datetime:2017/11/23 0023 17:49
* 筑望
*/
@Getter
public enum ZhuWangSubmitErrorEnum implements CodeEnum<Integer> {
SUCCESS(0, "正确"),
A(1, "消息结构错误"),
B(2, "命令字错误"),
C(3, "消息序号重复"),
D(4, "消息长度错误"),
E(5, "资费代码错误"),
F(6, "超过最大信息长度"),
G(7, "业务代码错误"),
H(8, "流量控制错误"),
I(9, "本网关不负责此计费号码"),
J(10, "Src_ID错"),
K(11, "Msg_src错"),
L(12, "计费地址错"),
M(13, "目的地址错"),
UNCONNECT(51, "尚未建立连接"),
OTHER_ERROR(9, "其他错误"),
;
private Integer code;
private String message;
ZhuWangSubmitErrorEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
| [
"970389745@qq.com"
] | 970389745@qq.com |
0f96ce41271271288fc9a842ae3a45726e0f9051 | 0cc4482029c48a0d7dda2b49058bd2d3d15dc312 | /src/main/java/br/org/generation/blogpessoal/configuration/SwaggerConfig.java | e59c175fc41873aa019ee7ebcac9391c921e9b9b | [] | no_license | RenanMoreira92/BlogPessoal- | 47db50f8a14777f78f8cc1f2c256a0912c89dc45 | 41578d9627b694e98dff8dc77d1a8e8d14b6b8cf | refs/heads/main | 2023-09-03T01:26:21.246526 | 2021-11-18T22:20:33 | 2021-11-18T22:20:33 | 429,594,434 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,503 | java |
package br.org.generation.blogpessoal.configuration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors
.basePackage("br.org.generation.blogpessoal.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(metadata())
.useDefaultResponseMessages(false)
.globalResponses(HttpMethod.GET, responseMessage())
.globalResponses(HttpMethod.POST, responseMessage())
.globalResponses(HttpMethod.PUT, responseMessage())
.globalResponses(HttpMethod.DELETE, responseMessage());
}
public static ApiInfo metadata() {
return new ApiInfoBuilder()
.title("API - Blog Pessoal")
.description("Projeto API Spring - Blog Pessoal")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/RenanMoreira92")
.contact(contact())
.build();
}
private static Contact contact() {
return new Contact("Renan Moreira",
"https://github.com/RenanMoreira92",
"renan.s.7@hotmail.com");
}
private static List<Response> responseMessage() {
return new ArrayList<Response>() {
private static final long serialVersionUID = 1L;
{
add(new ResponseBuilder().code("200").description("Sucesso!").build());
add(new ResponseBuilder().code("201").description("Criado!").build());
add(new ResponseBuilder().code("400").description("Erro na requisição!").build());
add(new ResponseBuilder().code("401").description("Não Autorizado!").build());
add(new ResponseBuilder().code("403").description("Proibido!").build());
add(new ResponseBuilder().code("404").description("Não Encontrado!").build());
add(new ResponseBuilder().code("500").description("Erro!").build());
}
};
}
} | [
"renan.s.7@hotmail.com"
] | renan.s.7@hotmail.com |
39255926eb251b39a03f4b30cbbda32f04781579 | ecb8bfc59bd1d31bc58f0663f16e5e7fd668811d | /src/main/java/com/projeto/digitalinnovation/citiesapi/distances/service/EarthRadius.java | 6e0b7a0a2f2d1bf8827b8c2ec018c94fda255228 | [] | no_license | brmelo/cities-api | b4569dadbc676e171e306ddcd032086ea07d52a7 | e62036d345a373f0b79f79e1a65b2ddab6e421c5 | refs/heads/main | 2023-04-25T09:54:54.870763 | 2021-05-16T23:32:39 | 2021-05-16T23:32:39 | 368,004,082 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 483 | java | package com.projeto.digitalinnovation.citiesapi.distances.service;
public enum EarthRadius {
METERS("m", 6378168),
KILOMETERS("km", 6378.168f),
MILES("mi", 3958.747716f);
private final String unit;
private final float value;
EarthRadius(final String unit, final float value) {
this.unit = unit;
this.value = value;
}
public float getValue() {
return value;
}
public String getUnit() {
return unit;
}
}
| [
"allysson_brunno@yahoo.com.br"
] | allysson_brunno@yahoo.com.br |
18eeb1db9802170ca9f377a266b2a3e513b0ca50 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i62561.java | e0d5f16a18071081ca2d5061c83bcf548d309176 | [] | no_license | vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711400 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 69 | java | package number_of_direct_superinterfaces;
public interface i62561 {} | [
"vincentlee.dolbydigital@yahoo.com"
] | vincentlee.dolbydigital@yahoo.com |
35f49dcb6228b02cf65b76fd593004058decc0b8 | 87451f23a873abaaa61198d94d367420c21fc8ec | /.metadata/.plugins/org.eclipse.core.resources/.history/1a/b01d6557667800151819b1db8d9b9d08 | 19fb79b2bd038f7c33806e3a257f04827d650c1c | [] | no_license | diegolms/MyQuimica | 96408dfa3862814f45be22f585167cd91243700f | bd928b73fc3e6115df42053aebdfc53410ecddf4 | refs/heads/master | 2021-01-19T18:11:22.765109 | 2015-10-22T02:49:50 | 2015-10-22T02:49:50 | 6,653,281 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,306 | package br.com.myquimica.database;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.myquimica.core.Constants;
import br.com.myquimica.models.Jogador;
import br.com.myquimica.models.MyQuimicaLog;
public class MyQuimicaDatabaseAdapter {
private static final String JOGADOR = "jogador";
private static final String LOG = "log";
private static final String PERFIL = "perfil";
private SQLiteDatabase database;
private MyQuimicaDatabaseHelper dbHelper;
private Context context;
public MyQuimicaDatabaseAdapter(Context context) {
this.context = context;
}
public MyQuimicaDatabaseAdapter open() throws SQLException {
dbHelper = new MyQuimicaDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public List<Jogador> buscarListaJogadores() {
Cursor cursor = database.query(JOGADOR,
new String[] { "id", "nome", "pontos"},null,null, null, null, null);
if (cursor.moveToFirst()) {
List<Jogador> jogadores = new ArrayList<Jogador>();
do {
Jogador jogador = new Jogador(
cursor.getInt(0), //id
cursor.getString(1),//nome
cursor.getInt(2));//pontos,
jogadores.add(jogador);
} while (cursor.moveToNext());
cursor.close();
return jogadores;
}
if (cursor != null)
cursor.close();
return null;
}
public long criarJogador(Jogador j){
try{
if(j.getId() != 0){
return atualizarJogador(j);
}
ContentValues values = new ContentValues();
values.put("nome", j.getNome());
values.put("pontos", j.getPontos());
return database.insert(JOGADOR, null, values);
}catch(Exception e){
Log.e(Constants.TAG, e.getMessage(), e);
}
return -1;
}
public long atualizarJogador(Jogador j) {
try {
ContentValues values = new ContentValues();
values.put("id", j.getId());
values.put("nome", j.getNome());
values.put("pontos", j.getPontos());
return database.update(JOGADOR, values, "id = " + j.getId(), null);
} catch (SQLiteConstraintException e) {
return -1;
}
}
public long gravarLog(MyQuimicaLog log){
try{
ContentValues values = new ContentValues();
values.put("jogador_id", log.getJogador_id().getId());
values.put("log", log.getLog());
return database.insert(LOG, null, values);
}catch(Exception e){
Log.e(Constants.TAG, e.getMessage(), e);
}
return -1;
}
public long salvarPerfil(List<String> resultPerfil, long jogador_id){
try{
ContentValues values = new ContentValues();
values.put("jogador_id", jogador_id);
values.put("ati_ref", resultPerfil.get(0));
values.put("sen_int", resultPerfil.get(1));
values.put("vis_ver", resultPerfil.get(2));
values.put("seq_glo", resultPerfil.get(3));
return database.insert(PERFIL, null, values);
}catch(Exception e){
Log.e(Constants.TAG, e.getMessage(), e);
}
return -1;
}
}
| [
"diego.lopes@dce.ufpb.br"
] | diego.lopes@dce.ufpb.br | |
7b22477ce7feb52d5baa68ca01c2abf87ae7f951 | 364e79821c571744c3d634f418f7b7585d7baf5a | /src/simulacion/models/Paciente.java | 3cf2f1dc91fe5d4bcc0c159f823dac42ad7333fe | [] | no_license | fabricio6969/Trabajo-Interciclo-Simulacion | d17bf5c641d178332064ca8a6671d637f4ccb471 | e6b1a789cb32e268529662d6b782faa7620c5cfc | refs/heads/main | 2023-02-09T22:33:11.993884 | 2020-12-23T22:55:16 | 2020-12-23T22:55:16 | 321,233,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,742 | java | package ec.edu.ups.simulacion.models;
import co.paralleluniverse.fibers.SuspendExecution;
import desmoj.core.simulator.Model;
import desmoj.core.simulator.SimProcess;
import desmoj.core.simulator.TimeInstant;
import desmoj.core.simulator.TimeSpan;
import java.util.Random;
// representa entidades con un ciclo de vida activo propio
public class Paciente extends SimProcess {
private Hospital modelo;
private int id;
public Paciente(Model model, String s, int id, boolean b) {
super(model, s, b);
this.id = id;
modelo = (Hospital) model;
}
///Pasiva un SimProcess durante el período de tiempo muestreado de la distribución proporcionada al método
@Override
public void lifeCycle() throws SuspendExecution {
sendTraceNote("El paciente: "+this.id+ "llega al hospital");
if(modelo.realizarTest()){
if(modelo.disponibilidadCamas()) {
modelo.asignarCama();
sendTraceNote("El paciente: "+this.id+ "se le asigna una cama");
hold(new TimeSpan(modelo.estancias.sample()));
modelo.liberarCama();
if(modelo.colaPacientes.length() > 0) {
Paciente paciente = (Paciente) modelo.colaPacientes.first();
modelo.colaPacientes.remove(paciente);
paciente.activateAfter(this);
}
//passivate();
delay(10);
if (validarEstado()) {
modelo.sanos.add(1);
sendTraceNote("El paciente: "+this.id+ " es dado de alta");
} else {
sendTraceNote("El paciente: "+this.id+ " entra en etapa de neumonia");
if (modelo.disponibilidadRespiradores()) {
modelo.asignarRespirador();
sendTraceNote("Al paciente: "+this.id+ " se le asigna un respirador");
//passivate();
delay(10);
modelo.liberarRespirador();
if (validarEstadoFinal()) {
sendTraceNote("Al paciente: "+this.id+ " se cura y se va");
modelo.sanos.add(1);
} else {
sendTraceNote("Al paciente: "+this.id+ " no se cura y muere");
modelo.fallecidos.add(1);
}
} else {
sendTraceNote("El paciente: "+this.id+ " muere por falta de respiradores");
modelo.fallecidos.add(1);
}
modelo.liberarRespirador();
}
} else {
modelo.colaPacientes.insert(this);
passivate();
}
}
}
private void delay(long tiempo){
try {
sendTraceNote("Han pasado n dias y se reevaluara al paciente "+this.id);
Thread.sleep(tiempo);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private boolean validarEstado() {
Random rnd = new Random();
int probabilidad = ((int)(rnd.nextDouble() * 10 + 0));
if (probabilidad >= 4) {
return true;
} else {
return false;
}
}
private boolean validarEstadoFinal() {
Random rnd = new Random();
int probabilidad = ((int)(rnd.nextDouble() * 10 + 0));
if (probabilidad >= 6) {
return true;
} else {
return false;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
fddf1626dafe5bf53d0bde05d54af9a1d94cf41e | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/15/15_cbbf915d37c0430c9320199d5962893b5fbe9f34/FXDNavigatorNode/15_cbbf915d37c0430c9320199d5962893b5fbe9f34_FXDNavigatorNode_s.java | b58cc1b2525fcacac2e661f26fad9d1fff65ae02 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 29,484 | java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.javafx.fxd.composer.navigator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.netbeans.modules.editor.structure.api.DocumentElement;
import org.netbeans.modules.editor.structure.api.DocumentElementEvent;
import org.netbeans.modules.editor.structure.api.DocumentElementListener;
import org.netbeans.modules.javafx.fxd.composer.model.FXDFileModel;
/**
* TreeNodeAdapter is an implementation of j.s.t.TreeNode encapsulating a DocumentElement
* instance and listening on its changes.
*
* @author Marek Fukala
* @author Pavel Benes
*/
final class FXDNavigatorNode implements TreeNode, DocumentElementListener {
private final FXDNavigatorTree m_nodeTree;
private final DocumentElement m_de;
private final TreeNode m_parent;
private byte m_nodeVisibility;
private List<FXDNavigatorNode> m_children = null; //a list of non-content nodes
//if the node itself contains an error
private boolean m_containsError = false;
//if one of its descendants contains an error
private int m_childrenErrorCount = 0;
FXDNavigatorNode(DocumentElement de, FXDNavigatorTree nodeTree, TreeNode parent, byte nodeVisibility) {
m_de = de;
m_nodeTree = nodeTree;
m_parent = parent;
m_nodeVisibility = nodeVisibility;
}
public java.util.Enumeration<FXDNavigatorNode> children() {
checkChildrenAdapters();
return Collections.enumeration(m_children);
}
public boolean getAllowsChildren() {
return true;
}
public TreeNode getChildAt(int param) {
checkChildrenAdapters();
return (TreeNode)m_children.get(param);
}
public int getChildCount() {
checkChildrenAdapters();
return m_children.size();
}
public int getIndex(TreeNode treeNode) {
checkChildrenAdapters();
return m_children.indexOf(treeNode);
}
public TreeNode getParent() {
return m_parent;
}
public boolean isLeaf() {
return getChildCount() == 0;
}
public DocumentElement getDocumentElement() {
assert m_de != null;
return m_de;
}
public byte getNodeVisibility() {
return m_nodeVisibility;
}
FXDNavigatorNode findNode(DocumentElement docElem) {
FXDNavigatorNode node = null;
if (m_de.equals(docElem)) {
node = this;
} else if (m_children != null) {
for (int i = m_children.size() - 1; i >= 0; i--) {
if ( (node=(m_children.get(i)).findNode(docElem)) != null) {
break;
}
}
}
return node;
}
FXDNavigatorNode getChildByElemenent( DocumentElement de) {
checkChildrenAdapters();
if (m_children != null) {
for (FXDNavigatorNode child : m_children) {
if (child.getDocumentElement() == de) {
return child;
}
}
}
return null;
}
TreePath getNodePath() {
int depth = 0;
TreeNode node = this;
do {
node = node.getParent();
depth++;
} while( node != null);
TreeNode [] nodes = new TreeNode[depth];
node = this;
for (int i = nodes.length - 1; i >= 0; i--) {
nodes[i] = node;
node = node.getParent();
}
return new TreePath(nodes);
}
private FXDNavigatorNode getChildTreeNode(DocumentElement de) {
int index;
if ((index=getChildTreeNodeIndex(de)) != -1) {
return m_children.get(index);
}
return null;
}
private int getChildTreeNodeIndex(DocumentElement de) {
checkChildrenAdapters();
int childNum = m_children.size();
for (int i = 0; i < childNum; i++) {
FXDNavigatorNode node = m_children.get(i);
if(node.getDocumentElement().equals(de)) {
return i;
}
}
return -1;
}
public boolean containsError() {
checkChildrenAdapters();
return m_containsError;
}
//returns a number of ancestors with error
public int getChildrenErrorCount() {
checkChildrenAdapters();
return m_childrenErrorCount;
}
@Override
public String toString() {
return getText(false);
}
public String getText(boolean html) {
if(FXDNavigatorTree.isTreeElement(m_de)) {
/*
String contentText = "";
String documentText = getDocumentContent();
if(NavigatorContent.showContent) {
contentText = documentText.length() > TEXT_MAX_LEN ? documentText.substring(0,TEXT_MAX_LEN) + "..." : documentText;
}*/
StringBuilder text = new StringBuilder();
text.append(html ? "<html>" : ""); //NOI18N
if (html) {
if (m_containsError) {
text.append("<font color=FF0000><b>"); //NOI18N
} else if (m_nodeVisibility == FXDNavigatorTree.VISIBILITY_UNDIRECT) {
text.append("<font color=888888>"); //NOI18N
}
}
String name = getDocumentElement().getName();
if ( "root".equals(name)) { // NOI18N
name = (String) getDocumentElement().getDocument().getProperty("entry_name");
if ( name == null) {
name = "FXD"; // NOI18N
}
}
String id = (String) getDocumentElement().getAttributes().getAttribute("id"); //NOI18N
if (id != null /*&& !id.startsWith(JSONObject.INJECTED_ID_PREFIX)*/) {
int len = id.length();
if ( id.charAt(0) == '"' && len >=2 && id.charAt(len-1) == '"') { // NOI18N
//strip the enclosing parentheses
for (int i = 1; i < len - 1; i++) {
text.append( id.charAt(i));
}
} else {
text.append(id);
}
text.append(':');
}
text.append(name);
if (html) {
if (m_containsError) {
text.append("</b></font>"); //NOI18N
} else if (m_nodeVisibility == FXDNavigatorTree.VISIBILITY_UNDIRECT) {
text.append("</font>"); //NOI18N
}
}
text.append(html ? "<font color=888888>" : ""); //NOI18N
String attribsVisibleText;
if ( FXDNavigatorTree.showAttributes) {
attribsVisibleText = getAttribsText(ATTRIBS_MAX_LEN);
} else {
attribsVisibleText = ""; //NOI18N
}
if(attribsVisibleText.trim().length() > 0) {
text.append(" "); //NOI18N
text.append(attribsVisibleText);
}
text.append(html ? "</font>" : ""); //NOI18N
/*
if(contentText.trim().length() > 0) {
text.append(" (");
text.append(HTMLTextEncoder.encodeHTMLText(contentText));
text.append(")");
}
*/
text.append(html ? "</html>" : ""); //NOI18N
return text.toString();
} /*else if(de.getType().equals(XML_PI)) {
//PI text
String documentText = getPIText();
documentText = documentText.length() > TEXT_MAX_LEN ? documentText.substring(0,TEXT_MAX_LEN) + "..." : documentText;
return documentText;
} else if(de.getType().equals(XML_DOCTYPE)) {
//limit the text length
String documentText = getDoctypeText();
String visibleText = documentText.length() > TEXT_MAX_LEN ? documentText.substring(0,TEXT_MAX_LEN) + "..." : documentText;
return visibleText;
} else if(de.getType().equals(XML_CDATA)) {
//limit the text length
String documentText = getCDATAText();
String visibleText = documentText.length() > TEXT_MAX_LEN ? documentText.substring(0,TEXT_MAX_LEN) + "..." : documentText;
return visibleText;
}*/
return m_de.getName() + " [unknown content]"; //NOI18N
}
public String getToolTipText() {
return getAttribsText( Integer.MAX_VALUE);
/*
if(de.getType().equals(XML_TAG)
|| de.getType().equals(XML_EMPTY_TAG)) {
return getAttribsText();
} else if(de.getType().equals(XML_PI)) {
return getPIText();
} else if(de.getType().equals(XML_DOCTYPE)) {
return getDoctypeText();
} else if(de.getType().equals(XML_CDATA)) {
return getCDATAText();
}
return ""; */
}
/*
private String getPIText() {
String documentText = null;
try {
documentText = m_de.getDocumentModel().getDocument().getText(de.getStartOffset(), de.getEndOffset() - de.getStartOffset());
//cut the leading PI name and the <?
int index = "<?".length() + de.getName().length();
if(index > (documentText.length() - 1)) index = documentText.length() - 1;
if(documentText.length() > 0) documentText = documentText.substring(index, documentText.length() - 1).trim();
}catch(BadLocationException e) {
return "???";
}
return documentText;
}
private String getDoctypeText() {
String documentText = "???";
try {
documentText = de.getDocumentModel().getDocument().getText(de.getStartOffset(), de.getEndOffset() - de.getStartOffset());
//cut the leading PI name and the <?
if(documentText.length() > 0) documentText = documentText.substring("<!DOCTYPE ".length() + de.getName().length(), documentText.length() - 1).trim();
}catch(BadLocationException e) {
return "???";
}
return documentText;
}
private String getCDATAText() {
String documentText = "???";
try {
documentText = de.getDocumentModel().getDocument().getText(de.getStartOffset(), de.getEndOffset() - de.getStartOffset());
//cut the leading PI name and the <?
if(documentText.length() > 0) documentText = documentText.substring("<![CDATA[".length(), documentText.length() - "]]>".length()).trim();
}catch(BadLocationException e) {
return "???";
}
return documentText;
}
*/
public void childrenReordered(DocumentElementEvent ce) {
//notify treemodel - do that in event dispath thread
m_nodeTree.getTreeModel().nodeStructureChanged(FXDNavigatorNode.this);
}
protected String getAttribsText(final int maxSize) {
final StringBuilder sb = new StringBuilder();
FXDFileModel.visitAttributes(getDocumentElement(), new FXDFileModel.ElementAttrVisitor() {
public boolean visitAttribute(String attrName, String attrValue) {
sb.append(attrName);
sb.append("="); //NOI18N
sb.append(attrValue);
sb.append(", "); //NOI18N
return sb.length() < maxSize;
}
}, true);
int len = sb.length();
if ( len > maxSize) {
sb.setLength(maxSize);
sb.append( "..."); //NOI18N
} else {
sb.setLength(Math.max(len-2, 0));
}
return sb.toString();
}
public void elementAdded(DocumentElementEvent e) {
final DocumentElement ade = e.getChangedChild();
if(debug) System.out.println(">>> +EVENT called on " + hashCode() + " - " + m_de + ": element " + ade + " is going to be added"); //NOI18N
if (FXDNavigatorTree.isTreeElement(ade)) {
byte visibility = m_nodeTree.checkVisibility(ade, true);
//add the element only when there isn't such one
int index = getChildTreeNodeIndex(ade);
if(index == -1) {
if (visibility != FXDNavigatorTree.VISIBILITY_NO) {
int insertIndex = getVisibleChildIndex(ade);
//check whether the insert index doesn't go beyond the actual children length (which states an error)
if( insertIndex < 0 || m_children.size() < insertIndex /*||
children.size() + 1 /* it doesn't contain the currently added element != getDocumentElement().getElementCount()*/) {
//error => try to recover by refreshing the current node
//debugError(e);
//notify treemodel
m_nodeTree.getTreeModel().nodeStructureChanged(this);
} else {
FXDNavigatorNode tn = new FXDNavigatorNode(ade, m_nodeTree, this, visibility);
m_children.add(insertIndex, tn);
final int tnIndex = getIndex(tn);
m_nodeTree.getTreeModel().nodesWereInserted(this, new int[]{tnIndex});
if(debug)System.out.println("<<<EVENT finished (node " + tn + " added)"); //NOI18N
}
//TODO Maybe add
/*
final String id = m_nodeTree.getSelectedId();
if ( id != null &&
m_nodeTree.isSelectionEmpty() &&
id.equals(FXDFileModel.getIdAttribute(ade))) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
m_nodeTree.selectNode(id, ade);
}
});
}*/
}
} else {
if (visibility == FXDNavigatorTree.VISIBILITY_NO) {
Object removedNode = m_children.remove(index);
m_nodeTree.getTreeModel().nodesWereRemoved(this, new int[] {index}, new Object[] {removedNode});
}
}
} else if ( FXDFileModel.isError(ade)) {
markNodeAsError(this);
}
//fix: if a new nodes are added into the root element (set as invisible), the navigator
//window is empty. So we need to always expand the root element when adding something into
if(m_de.equals(m_de.getDocumentModel().getRootElement())) {
//expand path
m_nodeTree.expandPath(new TreePath(this));
}
}
/*
private void debugError(DocumentElementEvent e) {
StringBuffer sb = new StringBuffer();
sb.append("An inconsistency between XML navigator and XML DocumentModel occured when adding a new element in the XML DocumentModel! Please report the problem and add following debug messages to the issue along with the XML document you are editing."); //NOI18N
sb.append("Debug for Node " + this + ":\n"); //NOI18N
sb.append("Children of current node:\n"); //NOI18N
Iterator itr = m_children.iterator();
while(itr.hasNext()) {
FXDNavigatorNode tna = (FXDNavigatorNode)itr.next();
sb.append(tna.toString());
sb.append("\n"); //NOI18N
}
sb.append("\nChildren of DocumentElement (" + getDocumentElement() + ") wrapped by the current node:\n"); //NOI18N
Iterator currChildrenItr = getDocumentElement().getChildren().iterator();
while(itr.hasNext()) {
DocumentElement de = (DocumentElement)itr.next();
sb.append(de.toString());
sb.append("\n"); //NOI18N
}
sb.append("------------"); //NOI18N
ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, sb.toString());
}
*/
private void markNodeAsError(final FXDNavigatorNode tna) {
tna.m_containsError = true;
//mark all its ancestors as "childrenContainsError"
FXDNavigatorNode parent = tna;
m_nodeTree.getTreeModel().nodeChanged(tna);
while((parent = (FXDNavigatorNode)parent.getParent()) != null) {
if(parent.getParent() != null) parent.m_childrenErrorCount++; //do not fire for root element
m_nodeTree.getTreeModel().nodeChanged(parent);
}
}
private int getVisibleChildIndex(DocumentElement de) {
int index = 0;
Iterator children = getDocumentElement().getChildren().iterator();
while(children.hasNext()) {
DocumentElement child = (DocumentElement)children.next();
if(child.equals(de)) return index;
if ( FXDNavigatorTree.isTreeElement(child)) {
index++;
}
/*
//skip text and error tokens
if(!child.getType().equals(XML_CONTENT)
&& !child.getType().equals(XML_ERROR)
&& !child.getType().equals(XML_COMMENT)) index++; */
}
return -1;
}
public void elementRemoved(DocumentElementEvent e) {
DocumentElement rde = e.getChangedChild();
if(debug) System.out.println(">>> -EVENT on " + hashCode() + " - " + m_de + ": element " + rde + " is going to be removed "); //NOI18N
if (FXDNavigatorTree.isTreeElement(rde)) {
if(debug) System.out.println(">>> removing tag element"); //NOI18N
final FXDNavigatorNode tn = getChildTreeNode(rde);
final int tnIndex = getIndex(tn);
if(tn != null) {
m_children.remove(tn);
//notify treemodel - do that in event dispath thread
m_nodeTree.getTreeModel().nodesWereRemoved(FXDNavigatorNode.this, new int[]{tnIndex}, new Object[]{tn});
} else if(debug) System.out.println("Warning: TreeNode for removed element doesn't exist!!!"); //NOI18N
} else if ( FXDFileModel.isError(rde)) {
unmarkNodeAsError(this);
}
if(debug) System.out.println("<<<EVENT finished (node removed)"); //NOI18N
}
private void unmarkNodeAsError(final FXDNavigatorNode tna) {
//handle error element
tna.m_containsError = false;
//unmark all its ancestors as "childrenContainsError"
FXDNavigatorNode parent = tna;
m_nodeTree.getTreeModel().nodeChanged(tna);
while((parent = (FXDNavigatorNode)parent.getParent()) != null) {
if(parent.getParent() != null) parent.m_childrenErrorCount--; //do not fire for root element
m_nodeTree.getTreeModel().nodeChanged(parent);
}
}
public void attributesChanged(DocumentElementEvent e) {
if(debug)System.out.println("Attributes of treenode " + this + " has changed."); //NOI18N
m_nodeTree.getTreeModel().nodeChanged(FXDNavigatorNode.this);
}
public void contentChanged(DocumentElementEvent e) {
if(debug) System.out.println("treenode " + this + " changed."); //NOI18N
m_nodeTree.getTreeModel().nodeChanged(FXDNavigatorNode.this);
}
public synchronized void refresh() {
if (m_children != null) {
List<DocumentElement> childElems = m_de.getChildren();
int elemNum = childElems.size();
int childNum = m_children.size();
boolean [] processed = new boolean[elemNum];
FXDNavigatorNode [] removedChildren = new FXDNavigatorNode[childNum];
int removedNum = 0;
int processedElemNum = 0;
// skip the elements that are not represented by navigator node
for (int j = 0; j < elemNum; j++) {
if (!FXDNavigatorTree.isTreeElement( childElems.get(j))) {
processedElemNum++;
processed[j] = true;
}
}
for( int i = childNum - 1; i >= 0; i--) {
FXDNavigatorNode childNode = m_children.get(i);
for (int j = 0; j < elemNum; j++) {
if (!processed[j]) {
DocumentElement childElem = childElems.get(j);
if ( childNode.m_de.equals(childElem)) {
byte visibility = m_nodeTree.checkVisibility(childElem, true);
if (visibility == FXDNavigatorTree.VISIBILITY_NO) {
m_children.remove(i);
removedChildren[i] = childNode;
removedNum++;
} else {
if (childNode.m_nodeVisibility != visibility) {
childNode.m_nodeVisibility = visibility;
}
childNode.refresh();
}
processedElemNum++;
processed[j] = true;
break;
}
}
}
}
// check if some nodes become invisible
if (removedNum > 0) {
int [] childIndices = new int[removedNum];
Object [] childrenArr = new Object[removedNum];
for (int j = 0, k = 0; j < childNum; j++) {
if (removedChildren[j] != null) {
childrenArr[k] = removedChildren[j];
childIndices[k++] = j;
}
}
m_nodeTree.getTreeModel().nodesWereRemoved(this, childIndices, childrenArr);
childNum -= removedNum;
}
assert childNum == m_children.size();
// check is some nodes become visible
if ( processedElemNum < elemNum) {
int childIndex = 0;
int elemIndex = 0;
int [] childIndices = new int[elemNum - processedElemNum];
int addedNum = 0;
main_loop : while( childIndex < childNum || elemIndex < elemNum) {
DocumentElement childNodeElem;
if (childIndex < childNum) {
childNodeElem = (m_children.get(childIndex)).m_de;
} else {
childNodeElem = null;
}
while(elemIndex < elemNum) {
DocumentElement childElem = m_de.getElement(elemIndex);
if (childElem.equals(childNodeElem)) {
childIndex++;
elemIndex++;
continue main_loop;
} else {
if ( !processed[elemIndex]) {
byte visibility = m_nodeTree.checkVisibility(childElem, true);
if (visibility != FXDNavigatorTree.VISIBILITY_NO) {
FXDNavigatorNode newChild = new FXDNavigatorNode(childElem, m_nodeTree, this, visibility);
m_children.add(childIndex, newChild);
childIndices[addedNum++] = childIndex;
childIndex++;
childNum++;
}
}
elemIndex++;
}
}
}
if (addedNum > 0) {
if (addedNum < childIndices.length) {
int [] t = childIndices;
childIndices = new int[addedNum];
System.arraycopy(t, 0, childIndices, 0, addedNum);
}
m_nodeTree.getTreeModel().nodesWereInserted(this, childIndices);
}
}
}
}
private synchronized void checkChildrenAdapters() {
if(m_children == null) {
//attach myself to the document element as a listener
m_de.addDocumentElementListener(this);
//lazyloading children for node
m_children = new ArrayList<FXDNavigatorNode>();
Iterator i = m_de.getChildren().iterator();
//boolean textElementAdded = false;
while(i.hasNext()) {
DocumentElement chde = (DocumentElement)i.next();
if (FXDNavigatorTree.isTreeElement(chde)) {
byte visibility = m_nodeTree.checkVisibility(chde, true);
//add the adapter only when there isn't any
int index = getChildTreeNodeIndex(chde);
if(index == -1) {
if (visibility != FXDNavigatorTree.VISIBILITY_NO) {
FXDNavigatorNode tna = new FXDNavigatorNode(chde, m_nodeTree, this, visibility);
m_children.add(tna);
}
} else {
if (visibility == FXDNavigatorTree.VISIBILITY_NO) {
m_children.remove(index);
}
}
} else if ( FXDFileModel.isError(chde)) {
markNodeAsError(this);
}
}
}
}
private static final boolean debug = Boolean.getBoolean("org.netbeans.modules.xml.text.structure.debug"); //NOI18N
private static final int ATTRIBS_MAX_LEN = 100;
//private static final int TEXT_MAX_LEN = ATTRIBS_MAX_LEN;
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
13f53d022cb5455983bbec71f8323c9977acbf2d | fb020d652243703f8ca2d0573a45dc7b58c70918 | /opencore/library/web/org.opengoss.web.lib/freemarker/freemarker/template/TemplateDateModel.java | 34607af64f704ca19706916e0f8eea05c7678b1b | [] | no_license | jorgediz/opengoss | 75213055b71dea9fe9d5d6367c4939f0d4e6371e | 161e53c890fcbd8eb0233cb8e7a7d11d430682b5 | refs/heads/master | 2021-01-10T09:59:11.407228 | 2007-06-19T07:40:39 | 2007-06-19T07:40:39 | 49,879,066 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,401 | java | /*
* Copyright (c) 2003 The Visigoth Software Society. All rights
* reserved.
*
* 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 end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Visigoth Software Society (http://www.visigoths.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
* project contributors may be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact visigoths@visigoths.org.
*
* 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
* nor may "FreeMarker" or "Visigoth" appear in their names
* without prior written permission of the Visigoth Software Society.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Visigoth Software Society. For more
* information on the Visigoth Software Society, please see
* http://www.visigoths.org/
*/
package freemarker.template;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Date values in a template data model must implement this interface.
* Contrary to Java, FreeMarker actually distinguishes values that represent
* only a time, only a date, or a combined date and time. All three are
* represented using this single interface, however there's a method that
*
* @author Attila Szegedi
*
* @version $Id: TemplateDateModel.java,v 1.10 2004/03/13 13:05:09 ddekany Exp $
*/
public interface TemplateDateModel extends TemplateModel
{
/**
* It is not known whether the date model represents a time-only,
* a date-only, or a datetime value.
*/
public static final int UNKNOWN = 0;
/**
* The date model represents a time-only value.
*/
public static final int TIME = 1;
/**
* The date model represents a date-only value.
*/
public static final int DATE = 2;
/**
* The date model represents a datetime value.
*/
public static final int DATETIME = 3;
public static final List TYPE_NAMES =
Collections.unmodifiableList(
Arrays.asList(
new String[] {
"UNKNOWN", "TIME", "DATE", "DATETIME"
}));
/**
* Returns the date value. The return value must not be null.
* @return the {@link Date} instance associated with this date model.
*/
public Date getAsDate() throws TemplateModelException;
/**
* Returns the type of the date. It can be any of <tt>TIME</tt>,
* <tt>DATE</tt>, or <tt>DATETIME</tt>.
*/
public int getDateType();
}
| [
"ery.lee@776b2eea-cf25-0410-9cbb-0f43d99736f6"
] | ery.lee@776b2eea-cf25-0410-9cbb-0f43d99736f6 |
97f7d53a5ebea60ce47a5e30a447ef55b220147a | c77fdaae357eb8a131a114c21c6d5ecf5c04d49f | /jiabian-platform/src/main/java/com/jiabian/control/dada/ConfigSeriesController.java | f47deac1469702ff8f93fe5118525fa047fbcd40 | [] | no_license | RenYongliang/jiabian-parent | 9b6af4e2d84d597f733cd7c0f99af5f80a608411 | 1df2425633446ffd4ae16670e69d46d119ff237d | refs/heads/master | 2020-03-25T15:06:50.398611 | 2018-08-13T16:46:07 | 2018-08-13T16:46:16 | 143,867,728 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,817 | java | package com.jiabian.control.dada;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jiabian.base.PagesModel;
import com.jiabian.base.control.BaseController;
import com.jiabian.dada.IDadaService;
import com.jiabian.dada.request.ConfigSeriesReq;
import com.jiabian.dada.response.ConfigSeriesRes;
import com.jiabian.util.Result;
@Controller
@RequestMapping("/series")
public class ConfigSeriesController extends BaseController<ConfigSeriesReq, ConfigSeriesRes> {
@Autowired
private IDadaService iDadaService;
/**
* 后台查询车型
* @param map
* @param configSeriesReq
* @return
*/
@RequestMapping("/seriesList")
public String selectSeries(ModelMap map, ConfigSeriesReq configSeriesReq) {
PagesModel<ConfigSeriesReq, ConfigSeriesRes> pagesModel = new PagesModel<>(configSeriesReq);
this.setPagesToModel(pagesModel, configSeriesReq);
pagesModel.setOrderBy("id asc");
iDadaService.selectSeries(pagesModel);
map.put("pagesModel", pagesModel);
return "dada/series/select";
}
/**
* 删除
* @param id
* @return
*/
@RequestMapping("/deleteSeriesById")
@ResponseBody
public Result<Boolean> deleteSeriesById(@RequestParam("id") Integer id) {
Result<Boolean> res = new Result<>();
String message;
Integer result = iDadaService.deleteSeries(id);
if(result > 0) {
message = "操作成功!";
res.setData(true);
}else {
message = "操作失败!";
res.setData(false);
}
res.setDesc(message);
return res;
}
/**
* 批量删除
* @param idList
* @return
*/
@RequestMapping("/delBatchSeries/{idList}")
@ResponseBody
public Result<Boolean> delBatchSeries(@PathVariable("idList") String idList) {
Result<Boolean> res = new Result<>();
String message;
List<Integer> ids = new ArrayList<>();
if(!idList.contains("-")) {
ids.add(Integer.parseInt(idList));
}else {
String[] idStrs = idList.split("-");
for(String s : idStrs) {
ids.add(Integer.parseInt(s));
}
}
Integer result = iDadaService.delBatchSeries(ids);
if(result > 0) {
message = "操作成功!";
res.setData(true);
}else {
message = "操作失败!";
res.setData(false);
}
res.setDesc(message);
return res;
}
/**
* 条件查询
* @param condition
* @return
*/
@RequestMapping("/selectSeriesByCondition")
@ResponseBody
public PagesModel<ConfigSeriesReq, ConfigSeriesRes> selectSeriesByCondition(@RequestParam("condition") String condition) {
PagesModel<ConfigSeriesReq, ConfigSeriesRes> pagesModel = new PagesModel<>();
pagesModel.setOrderBy("id asc");
iDadaService.selectSeriesByCondition(condition, pagesModel);
return pagesModel;
}
/**
* 添加跳转页
*/
@RequestMapping("/toInsert")
public String toInsert() {
return "dada/series/insert";
}
/**
* 新增品牌
* @param configSeriesReq
* @return
*/
@RequestMapping("/insertSeries")
@ResponseBody
public Result<Boolean> insertBrand(ConfigSeriesReq configSeriesReq) {
Result<Boolean> res = new Result<>();
String message;
Integer result = iDadaService.insertSeries(configSeriesReq);
if(result > 0) {
message = "操作成功!";
res.setData(true);
}else {
message = "操作失败!";
res.setData(false);
}
res.setDesc(message);
return res;
}
}
| [
"1017632646@qq.com"
] | 1017632646@qq.com |
7f81bc777502319003f2f59f93f9c6d4158fd272 | c3bd770413d64dd6fee3a64d505f9c4f64b379a2 | /2019/CentroMedicoPrivado/src/gui/MainWindow.java | fa211a715e9709a96b66ca7a51c5ed905e485e78 | [] | no_license | RaulG89/CPM-1 | 797533d02ac8d93f6d1d338e8a09608e28f0aa20 | 33c367b878650c3d925187d1320eefc9bc3f636c | refs/heads/master | 2020-12-03T20:22:45.690174 | 2019-11-27T10:50:12 | 2019-11-27T10:50:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,541 | java | package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import logic.DataBase;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JPanel pnButtons;
private JButton btnNext;
private JButton btnBack;
private JPanel pnLogin;
private JButton btnLogin;
private DataBase database;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
database = new DataBase();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 721, 433);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(getPanel(), BorderLayout.CENTER);
contentPane.add(getPnButtons(), BorderLayout.SOUTH);
contentPane.add(getPnLogin(), BorderLayout.NORTH);
}
private JPanel getPanel() {
if (panel == null) {
panel = new JPanel();
}
return panel;
}
private JPanel getPnButtons() {
if (pnButtons == null) {
pnButtons = new JPanel();
FlowLayout flowLayout = (FlowLayout) pnButtons.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
pnButtons.add(getBtnNext());
pnButtons.add(getBtnBack());
}
return pnButtons;
}
private JButton getBtnNext() {
if (btnNext == null) {
btnNext = new JButton("Next");
}
return btnNext;
}
private JButton getBtnBack() {
if (btnBack == null) {
btnBack = new JButton("Back");
}
return btnBack;
}
private JPanel getPnLogin() {
if (pnLogin == null) {
pnLogin = new JPanel();
FlowLayout flowLayout = (FlowLayout) pnLogin.getLayout();
flowLayout.setAlignment(FlowLayout.RIGHT);
pnLogin.add(getBtnLogin());
}
return pnLogin;
}
private JButton getBtnLogin() {
if (btnLogin == null) {
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
}
return btnLogin;
}
}
| [
"ivangonzalezmahagamage@gmail.com"
] | ivangonzalezmahagamage@gmail.com |
3575349f2316a1afba8f3ba99ea10633ab52dec3 | 7ed6ee76240a3ce8542e8d65f0900c392d81553c | /src/main/java/com/casper/usercrud/entity/User.java | 06180bd8348ffffa63710e7729e5050a1b2d9ab7 | [] | no_license | Casper133/User-CRUD | 8f6dd6902d51cbf8f8fa81f05516f6d39e98d221 | d48444254163366e08325c168be49eee9a6b35e7 | refs/heads/master | 2023-02-20T15:43:08.028106 | 2021-01-23T17:18:02 | 2021-01-24T08:24:28 | 258,706,297 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | package com.casper.usercrud.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "users")
public class User {
@Id
@Column(name = "id", updatable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String username;
private String password;
}
| [
"133casper@gmail.com"
] | 133casper@gmail.com |
621d3191da3964ca2265c41c0bb63c6772f53fea | 3abd77888f87b9a874ee9964593e60e01a9e20fb | /sim/EJS/Ejs/src/org/colos/ejs/library/resources/ejs_res_es_ES.java | 85955caa50b8f2fa3c8d9c4024c9492db2dea0d1 | [
"MIT"
] | permissive | joakimbits/Quflow-and-Perfeco-tools | 7149dec3226c939cff10e8dbb6603fd4e936add0 | 70af4320ead955d22183cd78616c129a730a9d9c | refs/heads/master | 2021-01-17T14:02:08.396445 | 2019-07-12T10:08:07 | 2019-07-12T10:08:07 | 1,663,824 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package org.colos.ejs.library.resources;
import java.io.IOException;
/**
* ES Spanish resource loader for OSP display class. Resource strings are obtained from superclass.
* @author Francisco Esquembre
*/
public class ejs_res_es_ES extends ejs_res_es {
/**
* Constructor ejs_res_es_ES
* @throws IOException
*/
public ejs_res_es_ES() throws IOException {
super();
}
}
| [
"joakimbits@gmail.com"
] | joakimbits@gmail.com |
5ce1efd4ca5c5a38096afbbdfed5745e97ed0dc2 | c7d73554f48587acfe0e2a49968d65bc8dd0a914 | /app/src/main/java/com/zz/temperaturemonitor/view/TempCircleView.java | 1ea4f123855160d031c21bbe1d5a162a961dfb6b | [] | no_license | LeeVanie/TemperatureMonitor | 86c39339417d0c1fb25a61e50e0d9312892fbe64 | a5c5d3214d2f67ed10583ba00c9de0c284f25ff7 | refs/heads/master | 2020-04-16T17:56:42.348198 | 2019-01-15T06:33:49 | 2019-01-15T06:33:49 | 165,796,363 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,909 | java | package com.zz.temperaturemonitor.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.zz.temperaturemonitor.utils.DisplayUtil;
public class TempCircleView extends View {
private Paint linePaint;
private Paint circlePaint;
private Paint textPaint;//刻度值
private Paint centerTextPaint;//中间的温度值
private Paint indicatorPaint;//指示器
private RectF mRectF;
private int defaultValue;
int mCenter = 0;// 圆的半径
int mRadius = 0;
private SweepGradient mSweepGradient,mSweepGradient2;
private int scanDegree = 0;//最高温度和最低温度扫描角度
private int currentScanDegree=0;//当前温度扫过的角度
private boolean isCanMove;
private GetDegreeInterface mGetDegreeInterface;
int minDegrees = 0;//最低温度
int maxDegree=0;//最高温度
int currentDegree=0;//当前温度
public boolean flag=false;
int screenWidth,screenHeight;
private float scaleX, scaleY;
public TempCircleView(Context context) {
super(context);
initPaint();
}
public TempCircleView(Context context, AttributeSet attrs) {
super(context, attrs);
screenWidth= DisplayUtil.getScreenWidth(context);
screenHeight=DisplayUtil.getScreenHeight(context);
scaleX = screenHeight / 540;
scaleY = screenHeight / 960;
Log.e("My----->", "2 "+screenWidth+" "+screenHeight);
initPaint();
}
private void initPaint() {
linePaint = new Paint();
linePaint.setColor(Color.CYAN);
linePaint.setStyle(Style.FILL);
linePaint.setAntiAlias(true);
linePaint.setStrokeWidth(1.0f);
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setAntiAlias(true);
textPaint.setTextSize(30 * scaleY);
centerTextPaint = new Paint();
centerTextPaint.setColor(Color.BLUE);
centerTextPaint.setTextAlign(Paint.Align.CENTER);
centerTextPaint.setAntiAlias(true);
centerTextPaint.setTextSize(50 * scaleY);
circlePaint = new Paint();
circlePaint.setColor(Color.WHITE);
circlePaint.setAntiAlias(true);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeCap(Cap.ROUND);//实现末端圆弧
circlePaint.setStrokeWidth(60.0f * scaleY);
// 着色的共有270度,这里设置了12个颜色均分360度s
int[] colors = { 0xFFD52B2B, 0xFFf70101, 0xFFFFFFFF, 0xFFFFFFFF,
0xFF6AE2FD, 0xFF8CD0E5, 0xFFA3CBCB, 0xFFD1C299, 0xFFE5BD7D,
0xFFAA5555, 0xFFBB4444, 0xFFC43C3C };
mCenter = (int) ((screenWidth - 100) / 2);
mRadius = (int) ((screenWidth - 300) / 2 / scaleX * scaleY) ;
// 渐变色
mSweepGradient = new SweepGradient(mCenter, mCenter, colors, null);
// 构建圆的外切矩形
mRectF = new RectF(mCenter - mRadius + 25, mCenter - mRadius - 30, mCenter
+ mRadius + 25, mCenter + mRadius - 30);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO 自动生成的方法存根
super.onDraw(canvas);
circlePaint.setShader(null);
canvas.drawArc(mRectF, 135, 270, false, circlePaint);
Log.e("scan--1-->", scanDegree+"");
//重新赋值了,所以手指滑动没有显示
scanDegree=(getMaxDegree()-getMinDegree())*3;
// 设置画笔渐变色
circlePaint.setShader(mSweepGradient);
canvas.drawArc(mRectF, 135+(getMinDegree()-10)*9, (float) scanDegree, false, circlePaint);
currentScanDegree=(getCurrentDegree()-10)*3;
canvas.drawText((currentScanDegree/9+10)+"℃", mCenter + 25, mCenter - 20, centerTextPaint);
// x代表文字的x轴距离圆心x轴的距离 因为刚好是45度,所以文字x轴值和y值相等
int x = 0;
// 三角形的斜边
int c = mRadius + 60 / 2 + 20;// 20代表这个字距离圆外边的距离
// 因为是每45度写一次文字,故根据到圆心的位置,利用三角形的公式,可以算出文字的坐标值
x = (int) Math.sqrt((c * c / 2));
// if (getMinDegree() == 0) {
// minDegrees = 10;
// }
canvas.drawText("10", mCenter - x + 25 * scaleY, mCenter + x - 20 * scaleY, textPaint);
canvas.drawText("15", mCenter - c + 25 * scaleY, mCenter - 20 * scaleY,
textPaint);
canvas.drawText("20", mCenter - x + 25 * scaleY, mCenter - x - 20 * scaleY,
textPaint);
canvas.drawText("25", mCenter + 25 * scaleY, mCenter - c - 20 * scaleY,
textPaint);
canvas.drawText( "30", mCenter + x + 25 * scaleY, mCenter - x - 20 * scaleY,
textPaint);
canvas.drawText( "35", mCenter + c + 25 * scaleY, mCenter - 20 * scaleY,
textPaint);
canvas.drawText( "40", mCenter + x + 25 * scaleY, mCenter + x - 25 * scaleY,
textPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO 自动生成的方法存根
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
isCanMove = true;
break;
case MotionEvent.ACTION_MOVE:
float x = event.getX();
float y = event.getY();
float StartX = event.getX();
float StartY = event.getY();
// 判断当前手指距离圆心的距离 如果大于mCenter代表在圆心的右侧
if (x > mCenter) {
x = x - mCenter;
} else {
x = mCenter - x;
}
if (y > mCenter) {
y = y - mCenter;
} else {
y = mCenter - y;
}
// 判断当前手指是否在圆环上的(30+10多加了10个像素)
if ((mRadius + 40) < Math.sqrt(x * x + y * y)
|| Math.sqrt(x * x + y * y) < (mRadius - 40)) {
Log.e("cmos---->", "终止滑动");
isCanMove = false;
return false;
}
float cosValue = x / (float) Math.sqrt(x * x + y * y);
// 根据cosValue求角度值
double acos = Math.acos(cosValue);// 弧度值
acos = Math.toDegrees(acos);// 角度值
if (StartX > mCenter && StartY < mCenter) {
acos = 360 - acos;// 第一象限
Log.e("象限---->", "第一象限");
} else if (StartX < mCenter && StartY < mCenter) {
acos = 180 + acos;// 第二象限
Log.e("象限---->", "第二象限");
} else if (StartX < mCenter && StartY > mCenter) {
acos = 180 - acos;// 第三象限
Log.e("象限---->", "第三象限");
} else {
// acos=acos;
Log.e("象限---->", "第四象限");
}
Log.e("旋转的角度---->", acos + "");
scanDegree = (int) acos;
if (scanDegree >= 135 && scanDegree < 360) {
scanDegree = scanDegree - 135;
int actualDegree = (int) (scanDegree / 9);
if (mGetDegreeInterface != null) {
mGetDegreeInterface.getActualDegree(actualDegree
+ minDegrees);
}
} else if (scanDegree <= 45) {
scanDegree = (int) (180 + 45 + acos);
int actualDegree = (int) (scanDegree / 9);
if (mGetDegreeInterface != null) {
mGetDegreeInterface.getActualDegree(actualDegree
+ minDegrees);
}
} else {
return false;
}
postInvalidate();
return true;
}
return true;
}
/**
* 设置最低温度
*
* @param degree
*/
public void setMinDegree(int degree) {
this.minDegrees = degree;
}
public int getMinDegree() {
return minDegrees;
}
/**
* 获取当前温度值接口
*
*/
public interface GetDegreeInterface {
void getActualDegree(int degree);
}
public void setGetDegreeInterface(GetDegreeInterface arg) {
this.mGetDegreeInterface = arg;
}
/**
* 设置最高温度值
*/
public void setMaxDegree(int degree){
this.maxDegree=degree;
}
public int getMaxDegree() {
return maxDegree;
}
/**
* 设置当前温度
* @param currentDegree
*/
public void setCurrentDegree(int currentDegree) {
this.currentDegree = currentDegree;
}
public int getCurrentDegree() {
return currentDegree;
}
// 因为自定义的空间的高度设置的是wrap_content,所以我们必须要重写onMeasure方法去测量高度,否则布局界面看不到
// 其他控件(被覆盖)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
//setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
/**
* 测量宽度
*
* @param widthMeasureSpec
* @return
*/
private int measureWidth(int widthMeasureSpec) {
int mode = MeasureSpec.getMode(widthMeasureSpec);
int size = MeasureSpec.getSize(widthMeasureSpec);
// 默认宽高;
defaultValue=screenWidth;
switch (mode) {
case MeasureSpec.AT_MOST:
// 最大值模式 当控件的layout_Width或layout_height属性指定为wrap_content时
Log.e("cmos---->", "size " + size + " screenWidth " + screenWidth);
size = Math.min(defaultValue, size);
break;
case MeasureSpec.EXACTLY:
// 精确值模式
// 当控件的android:layout_width=”100dp”或android:layout_height=”match_parent”时
break;
default:
size = defaultValue;
break;
}
defaultValue = size;
return size;
}
/**
* 测量高度
*
* @param heightMeasureSpec
* @return
*/
private int measureHeight(int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
int size = MeasureSpec.getSize(heightMeasureSpec);
switch (mode) {
case MeasureSpec.AT_MOST:
// 最大值模式 当控件的layout_Width或layout_height属性指定为wrap_content时
Log.e("cmos---->", "size " + size + " screenHeight " + screenHeight);
size = Math.min(screenHeight/2, size);
break;
case MeasureSpec.EXACTLY:
// 精确值模式
// 当控件的android:layout_width=”100dp”或android:layout_height=”match_parent”时
break;
default:
size = defaultValue;
break;
}
return size;
}
}
| [
"942629585@qq.com"
] | 942629585@qq.com |
8a6ef406a61cb96a01636bcc61267ff2f55888c0 | 2cbc36842d997f3597da98b14096dc0ed11d35bb | /src/main/java/br/jpe/tdl/web/rest/AccountResource.java | aae505632c7f1a6b916fbbdafbcae2acffb61d46 | [] | no_license | joaovperin/app-todolist | 4ebbff721cc54ccc475ebce315b151820130d245 | 9f9d5a4ccd68eeefb243f6f7b73003dfe9873a50 | refs/heads/main | 2023-08-05T09:25:12.408549 | 2021-09-17T02:02:25 | 2021-09-17T02:02:25 | 407,250,293 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,696 | java | package br.jpe.tdl.web.rest;
import br.jpe.tdl.domain.User;
import br.jpe.tdl.repository.UserRepository;
import br.jpe.tdl.security.SecurityUtils;
import br.jpe.tdl.service.MailService;
import br.jpe.tdl.service.UserService;
import br.jpe.tdl.service.dto.AdminUserDTO;
import br.jpe.tdl.service.dto.PasswordChangeDTO;
import br.jpe.tdl.web.rest.errors.*;
import br.jpe.tdl.web.rest.vm.KeyAndPasswordVM;
import br.jpe.tdl.web.rest.vm.ManagedUserVM;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private static class AccountResourceException extends RuntimeException {
private AccountResourceException(String message) {
super(message);
}
}
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
private final UserRepository userRepository;
private final UserService userService;
private final MailService mailService;
public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) {
this.userRepository = userRepository;
this.userService = userService;
this.mailService = mailService;
}
/**
* {@code POST /register} : register the user.
*
* @param managedUserVM the managed user View Model.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
*/
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
if (isPasswordLengthInvalid(managedUserVM.getPassword())) {
throw new InvalidPasswordException();
}
User user = userService.registerUser(managedUserVM, managedUserVM.getPassword());
mailService.sendActivationEmail(user);
}
/**
* {@code GET /activate} : activate the registered user.
*
* @param key the activation key.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated.
*/
@GetMapping("/activate")
public void activateAccount(@RequestParam(value = "key") String key) {
Optional<User> user = userService.activateRegistration(key);
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this activation key");
}
}
/**
* {@code GET /authenticate} : check if the user is authenticated, and return its login.
*
* @param request the HTTP request.
* @return the login if the user is authenticated.
*/
@GetMapping("/authenticate")
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
/**
* {@code GET /account} : get the current user.
*
* @return the current user.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned.
*/
@GetMapping("/account")
public AdminUserDTO getAccount() {
return userService
.getUserWithAuthorities()
.map(AdminUserDTO::new)
.orElseThrow(() -> new AccountResourceException("User could not be found"));
}
/**
* {@code POST /account} : update the current user information.
*
* @param userDTO the current user information.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found.
*/
@PostMapping("/account")
public void saveAccount(@Valid @RequestBody AdminUserDTO userDTO) {
String userLogin = SecurityUtils
.getCurrentUserLogin()
.orElseThrow(() -> new AccountResourceException("Current user login not found"));
Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) {
throw new EmailAlreadyUsedException();
}
Optional<User> user = userRepository.findOneByLogin(userLogin);
if (!user.isPresent()) {
throw new AccountResourceException("User could not be found");
}
userService.updateUser(
userDTO.getFirstName(),
userDTO.getLastName(),
userDTO.getEmail(),
userDTO.getLangKey(),
userDTO.getImageUrl()
);
}
/**
* {@code POST /account/change-password} : changes the current user's password.
*
* @param passwordChangeDto current and new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect.
*/
@PostMapping(path = "/account/change-password")
public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) {
if (isPasswordLengthInvalid(passwordChangeDto.getNewPassword())) {
throw new InvalidPasswordException();
}
userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword());
}
/**
* {@code POST /account/reset-password/init} : Send an email to reset the password of the user.
*
* @param mail the mail of the user.
*/
@PostMapping(path = "/account/reset-password/init")
public void requestPasswordReset(@RequestBody String mail) {
Optional<User> user = userService.requestPasswordReset(mail);
if (user.isPresent()) {
mailService.sendPasswordResetMail(user.get());
} else {
// Pretend the request has been successful to prevent checking which emails really exist
// but log that an invalid attempt has been made
log.warn("Password reset requested for non existing mail");
}
}
/**
* {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
*
* @param keyAndPassword the generated key and the new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset.
*/
@PostMapping(path = "/account/reset-password/finish")
public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {
if (isPasswordLengthInvalid(keyAndPassword.getNewPassword())) {
throw new InvalidPasswordException();
}
Optional<User> user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey());
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this reset key");
}
}
private static boolean isPasswordLengthInvalid(String password) {
return (
StringUtils.isEmpty(password) ||
password.length() < ManagedUserVM.PASSWORD_MIN_LENGTH ||
password.length() > ManagedUserVM.PASSWORD_MAX_LENGTH
);
}
}
| [
"joaovperin@live.com"
] | joaovperin@live.com |
e9098f37fa301d4a6b84683d79613d585ea9434d | 58a30a35f0edf0582e133ae1e1c4882752a6a767 | /src/leetcode/string/RomanToInt_13.java | 3a993484f917cd2563c9012e45f8f198c92155a6 | [] | no_license | fatezy/arithmetic | 08c74905060ff0c612f1c3c38da2ff65751c02ae | 6a201e4ff380369e2b21d12a9098ce2b0eb75627 | refs/heads/master | 2021-01-19T02:02:44.085110 | 2020-05-05T13:38:59 | 2020-05-05T13:38:59 | 54,632,979 | 5 | 0 | null | 2020-10-13T12:20:44 | 2016-03-24T10:14:46 | Java | UTF-8 | Java | false | false | 1,195 | java | package leetcode.string;
import java.util.HashMap;
/**
* author: 张亚飞
* time:2016/4/26 22:12
*/
//Given a roman numeral, convert it to an integer.
//
// Input is guaranteed to be within the range from 1 to 3999.
public class RomanToInt_13 {
public int romanToInt(String s) {
HashMap<String, Integer> table = new HashMap<>();
table.put("I",1);
table.put("IV",4);
table.put("V",5);
table.put("IX",9);
table.put("X",10);
table.put("XL",40);
table.put("L",50);
table.put("XC",90);
table.put("C",100);
table.put("CD",400);
table.put("D",500);
table.put("CM",900);
table.put("M",1000);
int result = 0;
int len = s.length();
for (int i = 0; i <len ; i++) {
if (i+1<len){
String ss = s.charAt(i)+""+s.charAt(i+1);
if (table.containsKey(ss)){
result+=table.get(ss);
i=i+1;
continue;
}
}
String ss = s.charAt(i)+"";
result+=table.get(ss);
}
return result;
}
}
| [
"1104199203@qq.com"
] | 1104199203@qq.com |
8598e9c46b0ed4d22e3e04b2b4be4320cbc43f4a | c7aa8bda2f31a516b1c2d336df202b99273445aa | /src/main/java/com/ruo/model/LogWithBLOBs.java | 8344ccb21c96abc95a8d8dd2b61569ae46785439 | [] | no_license | li-ll/SSM-RABC | e78e3047aef818134b781efa0ba7a1b09c7f9571 | ef35144c9ed1fb4534635d17041d1de695037fe1 | refs/heads/master | 2023-03-31T00:02:48.966351 | 2021-03-16T10:03:35 | 2021-03-16T10:03:35 | 313,296,951 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 498 | java | package com.ruo.model;
public class LogWithBLOBs extends Log {
private String oldValue;
private String newValue;
public String getOldValue() {
return oldValue;
}
public void setOldValue(String oldValue) {
this.oldValue = oldValue == null ? null : oldValue.trim();
}
public String getNewValue() {
return newValue;
}
public void setNewValue(String newValue) {
this.newValue = newValue == null ? null : newValue.trim();
}
} | [
"2209288672@qq.com"
] | 2209288672@qq.com |
437c4015d7aba2c529def1275c7ddecf193a5375 | f07ebfdfc6120e6080ccdc9a17bff028942e8558 | /Spring-Boot-Ant-Web/src/spring/boot/ant/models/Greeting.java | 124787d8d07c822a47ef6f66d93d02476062787e | [] | no_license | aleksandarbosancic/spring-boot-ant | 65888ecb4e5066835e5639607737e429d5e11771 | ac56d8d8254caf554175a1d1095af80b4f66a766 | refs/heads/master | 2021-01-20T03:17:12.084319 | 2017-04-27T16:27:36 | 2017-04-27T16:27:36 | 89,520,063 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 261 | java | package spring.boot.ant.models;
public class Greeting {
private String content;
public Greeting() {
}
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
| [
"aco.bosancic@gmail.com"
] | aco.bosancic@gmail.com |
b1ee8280c457fb0387b8dc53809aa5507c5141b5 | 5f44dbd9a71dd55fb586e6d53f9903fb262a9f50 | /src/main/java/ru/netology/domain/CommentsInfo.java | ae5e6d200c323b659f8deed0cfb16891e6021e58 | [] | no_license | AlexeySuchkov/QA-Vk | 6f789a3c18142e546daef09e5506c115928728b3 | 2f0e61a340a4b2d1396f3baca9d67f31767a1450 | refs/heads/master | 2022-05-26T20:46:24.066740 | 2020-05-01T16:12:20 | 2020-05-01T16:12:20 | 258,038,742 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 238 | java | package ru.netology.domain;
public class CommentsInfo {
private int count;
private int canPost;
private int groupsCanPost;
private boolean canClose;
private boolean canOpen;
// + get/set на все поля
}
| [
"alexey.suchkov@gmail.com"
] | alexey.suchkov@gmail.com |
0ce376207790da30e75480294d7b3ee0f98c09f9 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project31/src/test/java/org/gradle/test/performance31_1/Test31_62.java | 3effea3754d2a15b53fdc6e740099a2187f2bf19 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 289 | java | package org.gradle.test.performance31_1;
import static org.junit.Assert.*;
public class Test31_62 {
private final Production31_62 production = new Production31_62("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
04596331df0fbb080dbd7efe3581005574d5d21d | bbfa56cfc81b7145553de55829ca92f3a97fce87 | /plugins/org.eclipse.jqvt/src-gen/org/eclipse/jqvt/parser/antlr/JQVTParser.java | 489e28ef0a679bad2db4c704162c78a1550993b3 | [] | no_license | patins1/raas4emf | 9e24517d786a1225344a97344777f717a568fdbe | 33395d018bc7ad17a0576033779dbdf70fa8f090 | refs/heads/master | 2021-08-16T00:27:12.859374 | 2021-07-30T13:01:48 | 2021-07-30T13:01:48 | 87,889,951 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,070 | java | /*
* generated by Xtext
*/
package org.eclipse.jqvt.parser.antlr;
import com.google.inject.Inject;
import org.eclipse.xtext.parser.antlr.XtextTokenStream;
import org.eclipse.jqvt.services.JQVTGrammarAccess;
public class JQVTParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser {
@Inject
private JQVTGrammarAccess grammarAccess;
@Override
protected void setInitialHiddenTokens(XtextTokenStream tokenStream) {
tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT");
}
@Override
protected org.eclipse.jqvt.parser.antlr.internal.InternalJQVTParser createParser(XtextTokenStream stream) {
return new org.eclipse.jqvt.parser.antlr.internal.InternalJQVTParser(stream, getGrammarAccess());
}
@Override
protected String getDefaultRuleName() {
return "PackageDeclaration";
}
public JQVTGrammarAccess getGrammarAccess() {
return this.grammarAccess;
}
public void setGrammarAccess(JQVTGrammarAccess grammarAccess) {
this.grammarAccess = grammarAccess;
}
}
| [
"patins@f81cfaeb-dc96-476f-bd6d-b0d16e38694e"
] | patins@f81cfaeb-dc96-476f-bd6d-b0d16e38694e |
b8b164fddd9bea34da9776c58618cd12c3185132 | d2fd3495fbc3053a869b4202382c00e2b381ca26 | /app/src/main/java/com/rogmax/amirjaber/taskrogmax22/models/Pet.java | cc3f111ea22696b9bb91128290a05d89c90e53e4 | [] | no_license | amirjaber-rogmax/TaskRogmax2.2 | 5e1d2ec75d1274f0049a9f049008744b90f21d9e | 4e234c44e92d9e0d8829c486aab9a7ba668c4437 | refs/heads/master | 2021-07-13T14:29:18.153548 | 2017-10-18T11:31:53 | 2017-10-18T11:31:53 | 105,039,244 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 960 | java | package com.rogmax.amirjaber.taskrogmax22.models;
/**
* Created by Amir Jaber on 9/27/2017.
*/
public class Pet {
private String type, subtype, name;
private int id;
public Pet(int id, String type, String subtype, String name) {
this.id = id;
this.type = type;
this.subtype = subtype;
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubtype() {
return subtype;
}
public void setSubtype(String subtype) {
this.subtype = subtype;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return this.name;
}
}
| [
"amir.jaber@rogmax.com"
] | amir.jaber@rogmax.com |
c8647d4a3e522921185f461a7eb5b0552a7592a7 | 4d6e125bb4e1a1f72c97a1be095086faad53b560 | /src/main/java/com/zmlProjects/express/service/Kuaidi100ServiceImpl.java | 97894226f37b3a9b87c8adf0c0d124de1138f5a7 | [] | no_license | ccc012zx/express | 871304b6a82c96b23f26d9667a7101fccf10b377 | d6c77ede23137229ca95b9f90f99d274723b41aa | refs/heads/master | 2021-09-06T15:23:02.696276 | 2018-02-08T00:57:57 | 2018-02-08T00:57:57 | 115,842,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,979 | java | package com.zmlProjects.express.service;
import com.alibaba.fastjson.JSON;
import com.zmlProjects.express.bean.KuaidiBean;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
@Service("kuaidi100Service")
public class Kuaidi100ServiceImpl implements Kuaidi100Service {
public KuaidiBean queryOneExpress(String com, String number) {
KuaidiBean kuaidiBean = null;//返回参数
String key = "29833628d495d7a5";//快递100的密钥
String urlStr = "http://api.kuaidi100.com/api?id=" + key + "&com=" + com + "&nu=" + number + "&show=0&muti=1&order=desc";
URL url = null;
try {
url = new URL(urlStr);
URLConnection con = url.openConnection();
con.setAllowUserInteraction(false);
InputStream urlStream = url.openStream();
String type = con.guessContentTypeFromStream(urlStream);
String charSet = null;
if (type == null)
type = con.getContentType();
if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/json") < 0)
return null;
if (type.indexOf("charset=") > 0)
charSet = type.substring(type.indexOf("charset=") + 8);
byte b[] = new byte[10000];
int numRead = urlStream.read(b);
String content = new String(b, 0, numRead);
while (numRead != -1) {
numRead = urlStream.read(b);
if (numRead != -1) {
// String newContent = new String(b, 0, numRead);
String newContent = new String(b, 0, numRead, charSet);
content += newContent;
}
}
//System.err.println(content);
kuaidiBean = JSON.parseObject(content, KuaidiBean.class);
urlStream.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return kuaidiBean;
}
// private static String getState(String state) {
// Map<String, String> map = new HashMap<String, String>();
// map.put("0", "在途,即货物处于运输过程中");
// map.put("1", "揽件,货物已由快递公司揽收并且产生了第一条跟踪信息");
// map.put("2", "疑难,货物寄送过程出了问题");
// map.put("3", "签收,收件人已签收");
// map.put("4", "退签,即货物由于用户拒签、超区等原因退回,而且发件人已经签收");
// map.put("5", "派件,即快递正在进行同城派件");
// map.put("6", "退回,货物正处于退回发件人的途中");
//
// return map.get(state);
// }
public boolean queryOneState(KuaidiBean kuaidiBean) {
StringBuffer sb = new StringBuffer();
// sb.append("快递单号:").append(number).append(",当前快递单状态:").append(this.getState(kuaidiBean.getState()));
// 快递单当前的状态 :
// 0:在途,即货物处于运输过程中;
// 1:揽件,货物已由快递公司揽收并且产生了第一条跟踪信息;
// 2:疑难,货物寄送过程出了问题;
// 3:签收,收件人已签收;
// 4:退签,即货物由于用户拒签、超区等原因退回,而且发件人已经签收;
// 5:派件,即快递正在进行同城派件;
// 6:退回,货物正处于退回发件人的途中;
if (null != kuaidiBean && !"3".equals(kuaidiBean.getState())) {
return false;//快递还没有签收
}
return true;
}
}
| [
"javac.m.z@gmail.com"
] | javac.m.z@gmail.com |
bbad86612dc68e496c763d3febbb89e74f664139 | 725c1a112b8517277c7474d0b9b90d3a349ac81d | /AlgoritmosOrdenacao/SelectionSort.java | faf8526b83775d68f37cc4a133b0daab873e1d59 | [] | no_license | niverton-felipe/p3 | 008604105f8a2826f8282fa70ff363c9de2f9cc5 | 49f1114a8e6d1f5925d337e3a81b5a9543c86e5b | refs/heads/main | 2023-07-17T16:46:23.670442 | 2021-09-02T23:24:46 | 2021-09-02T23:24:46 | 360,340,658 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 767 | java | package p3.AlgoritmosOrdenacao;
public class SelectionSort {
public static void main(String[] args) {
int[] vector = {5,10,4,3,8,9,15,11};
int ordenados = 0;
for(int i = 0; i < vector.length; i++){
int indexMaior = 0;
for(int j = 1; j < vector.length - ordenados; j++){
if(vector[j] > vector[indexMaior]){
indexMaior = j;
}
}
int temp = vector[vector.length - 1 - ordenados];
vector[vector.length - 1 - ordenados] = vector[indexMaior];
vector[indexMaior] = temp;
ordenados++;
}
for(int i = 0; i < vector.length; i++){
System.out.print(vector[i] + " ");
}
}
}
| [
"nivertonfelipe355@gmail.com"
] | nivertonfelipe355@gmail.com |
379b848dae156709e2851fe52daa173621622f09 | 813a748b5340fd6dbc52e7cd689ae001d7b4b23d | /src/test/java/com/ynov/demo/web/rest/errors/ExceptionTranslatorTestController.java | 64ff77f2f9de2838f38afab9aa4e36209f8c0e51 | [] | no_license | keffa98/jhdemo | a8907499cd6c5dce05091f6245fe0495c63b6793 | 36b432ceb33debc05f30cc61d461435ca3b972cc | refs/heads/master | 2023-02-20T11:43:37.023661 | 2021-01-22T09:18:04 | 2021-01-22T09:18:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,086 | java | package com.ynov.demo.web.rest.errors;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@RestController
@RequestMapping("/api/exception-translator-test")
public class ExceptionTranslatorTestController {
@GetMapping("/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {
}
@GetMapping("/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart String part) {
}
@GetMapping("/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam String param) {
}
@GetMapping("/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/response-status")
public void exceptionWithResponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/internal-server-error")
public void internalServerError() {
throw new RuntimeException();
}
public static class TestDTO {
@NotNull
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
@SuppressWarnings("serial")
public static class TestResponseStatusException extends RuntimeException {
}
}
| [
"j.bilong@gmail.com"
] | j.bilong@gmail.com |
b62e4e0b0c270d45b9554de0089727e2617d5f24 | 8696bb507242bef6d984c9fa87a44e170dac6449 | /Java/BTK-Akademi-Java-ileri/1-SpringIntro/src/springIntro/MySqlCustomerDal.java | 22ac78ee1aaf654ae7d692a216929272ac84c78e | [] | no_license | ismailartun00/Tutorials | 1abe1adb07248f0948b8c04a222a60501779fc3d | f588e814fa9ebc735d7cf309e0206046e3bc2858 | refs/heads/main | 2023-05-08T07:28:04.715607 | 2021-05-22T17:10:19 | 2021-05-22T17:10:19 | 358,101,009 | 2 | 0 | null | null | null | null | WINDOWS-1258 | Java | false | false | 447 | java | package springIntro;
public class MySqlCustomerDal implements ICustomerDal {
String connectionString;
public String getConnectionString() {
return connectionString;
}
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
@Override
public void add() {
System.out.println("Connection String : " + this.connectionString);
System.out.println("My Sql Veritabanưna Eklendi.");
}
}
| [
"ismailartun00@gmail.com"
] | ismailartun00@gmail.com |
2c71b3098428dda8ebab3d34ef111ea7002ead5b | 40ee7656ecf2d446600dde9bcdc522d10af11752 | /src/main/java/com/harsen/app/utils/annotation/AnnotationUtils.java | 28ee9e83d0a9700288ad146af694f2f7cc5f4b4e | [] | no_license | HarsenLin/console-utils | c0fadaa3b66dd646d35b4e48e48c0df6cab3faf9 | aa172c1f07fb1c2e6ad36dab3ed760c0fbc0d36f | refs/heads/master | 2021-01-19T08:55:45.990614 | 2017-04-09T10:02:08 | 2017-04-09T10:02:08 | 87,698,794 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,077 | java | package com.harsen.app.utils.annotation;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 工具类
* Created by HarsenLin on 2016/6/5.
*/
public class AnnotationUtils {
/**
* 获取可执行命令方法
* @param clz 所属类
* @return List
*/
public static List<Method> getCommand(Class clz){
List<Method> retList = new ArrayList<Method>();
for(Method m : clz.getMethods()){
if(null != m.getAnnotation(Command.class)){
retList.add(m);
}
}
return retList;
}
/**
* 获取组件
* @param packageName 组件所在包
* @param recursive 是否查询子包
* @return Map
*/
public static Map<String, Class> getControl(String packageName, boolean recursive) {
//第一个class类的集合
Map<String, Class> classes = new HashMap<String, Class>();
//获取包的名字 并进行替换
String packageDirName = packageName.replace('.', '/');
//定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
//循环迭代下去
while (dirs.hasMoreElements()) {
//获取下一个元素
URL url = dirs.nextElement();
//得到协议的名称
String protocol = url.getProtocol();
//如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
//获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
//以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
//如果是jar包文件
//定义一个JarFile
JarFile jar;
try {
//获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
//从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
//同样的进行循环迭代
while (entries.hasMoreElements()) {
//获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
//如果是以/开头的
if (name.charAt(0) == '/') {
//获取后面的字符串
name = name.substring(1);
}
//如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
//如果以"/"结尾 是一个包
if (idx != -1) {
//获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
}
//如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
//如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
//去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
//添加到classes
addControl(packageName + '.' + className, classes);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName 包名
* @param packagePath 包路径
* @param recursive 是否加载子目录
* @param classes 类集合
*/
private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Map<String, Class> classes) {
//获取此包的目录 建立一个File
File dir = new File(packagePath);
//如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) return;
//如果存在 就获取包下的所有文件 包括目录
File[] dirFiles = dir.listFiles(new FileFilter() {
//自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
//循环所有文件
for (File file : dirFiles) {
//如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
} else {
//如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
//添加到集合中去
if ("".equals(packageName)) {
addControl(className, classes);
} else {
addControl(packageName + '.' + className, classes);
}
}
}
}
private static void addControl(String clzName, Map<String, Class> classes){
try {
Class clz = Class.forName(clzName);
if(null != clz.getAnnotation(Control.class)){
classes.put(clzName, clz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| [
"linhs@coreware.com.cn"
] | linhs@coreware.com.cn |
6b849aca27b231f163ce9b277b6f555c21620db1 | cb44cc2f34faefe31c7617059f2a0963edc87388 | /gwt-ol3-client/src/test/java/ol/PixelTest.java | d4903f3c21654aed0ccabd37288d0436b1e1f2d3 | [
"Apache-2.0"
] | permissive | TDesjardins/gwt-ol | 0e2ae272caa3fc33fe574ec83f33dfe670edc6a0 | 7ff86018585c7a1ad064c5e666c1f867efa0361f | refs/heads/main | 2023-08-11T19:50:38.301076 | 2023-08-08T15:49:53 | 2023-08-08T15:49:53 | 24,293,015 | 29 | 16 | Apache-2.0 | 2023-04-12T15:52:42 | 2014-09-21T14:25:45 | Java | UTF-8 | Java | false | false | 1,404 | java | /*******************************************************************************
* Copyright 2014, 2017 gwt-ol3
*
* 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 ol;
/**
* Test for {@link ol.Pixel}.
*
* @author Tino Desjardins
*
*/
public class PixelTest extends GwtOLBaseTestCase {
public void testPixel() {
injectUrlAndTest(() -> {
Pixel pixel = new Pixel(100, 50);
assertNotNull(pixel);
assertEquals(100, pixel.getX());
assertEquals(50, pixel.getY());
Pixel clonedPixel = pixel.cloneObject();
assertNotNull(clonedPixel);
assertEquals(pixel.getX(), clonedPixel.getX());
assertEquals(pixel.getY(), clonedPixel.getY());
});
}
}
| [
"tino.desjardins@arcor.de"
] | tino.desjardins@arcor.de |
730a24fa6230ed78e3d8ea1f11a40c066d093abb | d17398f207e752e7b4976348e7c66e8e0439da83 | /src/models/tasks/orders/CollectOrder.java | 6f3ac73df3f884f374c00d892f83813e46d2eb7c | [
"MIT"
] | permissive | MorS25/Hive_backend | 84e47ffb929f3c5d76e335727108f8a8a90d4897 | 9ad591b0247bbecfa4700791f25078f5602eb8d6 | refs/heads/master | 2022-02-05T10:16:16.651596 | 2019-07-09T22:36:00 | 2019-07-09T22:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,447 | java | package models.tasks.orders;
import models.facilities.Gate;
import models.facilities.Rack;
import models.items.Item;
import models.tasks.Task;
import models.warehouses.Warehouse;
import utils.Utility;
import java.util.HashMap;
import java.util.Map;
/**
* This {@code CollectOrder} class represents an order of collect type in our Hive Warehousing System.
* <p>
* A collect order is an {@link Order} used to collect a set of {@link Item Items}
* from the {@link Rack Racks} of the {@link Warehouse} and deliver them to a specified {@link Gate}.
*
* @see Task
* @see Item
* @see Gate
* @see Rack
* @see Order
* @see RefillOrder
*/
public class CollectOrder extends Order {
/**
* Constructs a new {@code CollectOrder} object.
*
* @param id the id of the {@code Order}.
* @param gate the delivery {@code Gate} of the {@code Order}.
*/
public CollectOrder(int id, Gate gate) {
super(id, gate);
}
/**
* Plans the set of items to reserve for the favor of this {@code Order}
* by the given {@code Task}.
*
* @param task the {@code Task} responsible for carrying out the reservation.
*/
@Override
protected void planItemsToReserve(Task task) {
Map<Item, Integer> items = new HashMap<>();
Rack rack = task.getRack();
for (var pair : pendingItems.entrySet()) {
Item item = pair.getKey();
int neededQuantity = pair.getValue();
int availableQuantity = rack.get(item);
int plannedQuantity = Math.min(neededQuantity, availableQuantity);
if (plannedQuantity != 0) {
items.put(item, plannedQuantity);
}
}
reservedItems.put(task, items);
}
/**
* Returns a string representation of this {@code Order}.
* In general, the toString method returns a string that "textually represents" this object.
*
* @return a string representation of this {@code Order}.
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CollectOrder: {");
builder.append(" id: ").append(id).append(",");
builder.append(" gate_id: ").append(deliveryGate.getId()).append(",");
builder.append(" items: ").append(Utility.stringifyItemQuantities(pendingItems));
builder.append(" }");
return builder.toString();
}
}
| [
"omar_bazaraa@hotmail.com"
] | omar_bazaraa@hotmail.com |
ed26e0a73e196b27268de7f1ec4b6e42c0293fbd | fee3bb5d92cebb4356b138473cc61f64fb0182b6 | /com.stud.titas.sandbox/src/main/java/dkpro/similarity/experiments/sts2013baseline/util/StopwordFilter.java | 0d27a3007bed20c3b299f5f115688b13839cef85 | [
"Apache-2.0"
] | permissive | TitasNandi/Summer_Project | 1f188749f3b1d1746827ef35f4fb5651754c663b | 7b3e1afb3b7c261dfb2d414993293a4c7ce1f9b5 | refs/heads/master | 2016-09-14T05:34:41.559942 | 2016-05-10T12:40:51 | 2016-05-10T12:40:51 | 58,363,757 | 2 | 0 | null | 2016-05-09T09:30:45 | 2016-05-09T09:12:41 | null | UTF-8 | Java | false | false | 5,615 | java | /*******************************************************************************
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl-3.0.txt
******************************************************************************/
package dkpro.similarity.experiments.sts2013baseline.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.apache.uima.resource.ResourceInitializationException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
public class StopwordFilter
extends JCasAnnotator_ImplBase
{
public static final String PARAM_STOPWORD_LIST = "StopwordList";
@ConfigurationParameter(name = PARAM_STOPWORD_LIST, mandatory = true)
private String stopwordList;
public static final String PARAM_ANNOTATION_TYPE_NAME = "AnnotationType";
@ConfigurationParameter(name = PARAM_ANNOTATION_TYPE_NAME, defaultValue = "de.tudarmstadt.ukp.dkpro.core.type.Token")
private String annotationTypeName;
public static final String PARAM_STRING_REPRESENTATION_METHOD_NAME = "StringRepresentationMethodName";
@ConfigurationParameter(name = PARAM_STRING_REPRESENTATION_METHOD_NAME, defaultValue = "getCoveredText")
private String stringRepresentationMethodName;
private Class<? extends Annotation> annotationType;
private Set<String> stopwords;
@SuppressWarnings("unchecked")
@Override
public void initialize(UimaContext context)
throws ResourceInitializationException
{
super.initialize(context);
try {
annotationType = (Class<? extends Annotation>) Class.forName(annotationTypeName);
}
catch (ClassNotFoundException e) {
throw new ResourceInitializationException(e);
}
PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver();
Resource res = r.getResource(stopwordList);
InputStream s;
try {
s = res.getInputStream();
}
catch (IOException e) {
throw new ResourceInitializationException(e);
}
loadStopwords(s);
}
@Override
public void process(JCas jcas)
throws AnalysisEngineProcessException
{
List<Annotation> itemsToRemove = new ArrayList<Annotation>();
// Check all annotations if they are stopwords
for (Annotation annotation : JCasUtil.select(jcas, annotationType)) {
try {
String word = (String) annotation.getClass()
.getMethod(stringRepresentationMethodName, new Class[] {})
.invoke(annotation, new Object[] {});
if (isStopword(word)) {
itemsToRemove.add(annotation);
}
}
catch (IllegalArgumentException e) {
throw new AnalysisEngineProcessException(e);
}
catch (SecurityException e) {
throw new AnalysisEngineProcessException(e);
}
catch (IllegalAccessException e) {
throw new AnalysisEngineProcessException(e);
}
catch (InvocationTargetException e) {
throw new AnalysisEngineProcessException(e);
}
catch (NoSuchMethodException e) {
throw new AnalysisEngineProcessException(e);
}
}
// Remove all stopwords from index
for (Annotation a : itemsToRemove) {
a.removeFromIndexes();
}
}
private boolean isStopword(String item)
{
assert item.length() > 0;
// item is in the stopword list
try {
if (stopwords.contains(item.toLowerCase())) {
return true;
}
}
catch (NullPointerException e) {
// Ignore this token
return true;
}
// does not start with a letter
if (!firstCharacterIsLetter(item)) {
return true;
}
return false;
}
private boolean firstCharacterIsLetter(String item)
{
if (item.matches("^[A-Za-z].+")) {
return true;
}
else {
return false;
}
}
private void loadStopwords(InputStream is)
throws ResourceInitializationException
{
stopwords = new HashSet<String>();
try {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = br.readLine()) != null) {
stopwords.add(line);
}
}
catch (IOException e) {
throw new ResourceInitializationException(e);
}
}
}
| [
"titas.nandi01@gmail.com"
] | titas.nandi01@gmail.com |
262cccedc59599577b894d048067b4a615fd2c5e | e2307b5abcc3d91ba98c82fa8d8a7108133ac8b3 | /aws-java-sdk-kendra/src/main/java/com/amazonaws/services/kendra/model/transform/IndexConfigurationSummaryJsonUnmarshaller.java | dad6618f04411e03737bd3254319794397e640d4 | [
"Apache-2.0"
] | permissive | fangwentong/aws-sdk-java | d87f9be8120643766dee5e086beb01fe8d733d76 | 92eb162a81e9c1b78d07a430c5a290519d7e7335 | refs/heads/master | 2022-07-26T11:29:40.748429 | 2020-05-09T18:57:29 | 2020-05-09T18:57:29 | 262,482,398 | 0 | 0 | Apache-2.0 | 2020-05-09T03:40:19 | 2020-05-09T03:40:18 | null | UTF-8 | Java | false | false | 3,864 | java | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.kendra.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kendra.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* IndexConfigurationSummary JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class IndexConfigurationSummaryJsonUnmarshaller implements Unmarshaller<IndexConfigurationSummary, JsonUnmarshallerContext> {
public IndexConfigurationSummary unmarshall(JsonUnmarshallerContext context) throws Exception {
IndexConfigurationSummary indexConfigurationSummary = new IndexConfigurationSummary();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
indexConfigurationSummary.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Id", targetDepth)) {
context.nextToken();
indexConfigurationSummary.setId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreatedAt", targetDepth)) {
context.nextToken();
indexConfigurationSummary.setCreatedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("UpdatedAt", targetDepth)) {
context.nextToken();
indexConfigurationSummary.setUpdatedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
indexConfigurationSummary.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return indexConfigurationSummary;
}
private static IndexConfigurationSummaryJsonUnmarshaller instance;
public static IndexConfigurationSummaryJsonUnmarshaller getInstance() {
if (instance == null)
instance = new IndexConfigurationSummaryJsonUnmarshaller();
return instance;
}
}
| [
""
] | |
8e6c4d5f3c9131173c43c91164910f88ca792200 | 4431b9d049c31082ffcf24178cfac918129937a3 | /nowcoder/AlgorithmCode/03String/Problem_03_ReverseSentence.java | 2bf7bc3d17ae7dbac8b8d03fc2fb0fef817f1410 | [] | no_license | doug65535/madDougAlgorithm | 170f76121b317a8a81435afa55e05b71331f1f40 | f33a46228a17c555ef9e1e0f705d67a3c65ad37c | refs/heads/master | 2023-08-15T12:38:50.838576 | 2021-10-12T19:45:14 | 2021-10-12T19:45:14 | 416,475,069 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 774 | java | package String;
/**
* 句子逆序,“i love you”处理后变成 “you love i”
* */
public class Problem_03_ReverseSentence {
public static String reverseSentence(String A, int n) {
StringBuilder bulider = new StringBuilder();
//切分字符串
String[] split = A.split(" ");
//将字符串倒序拼接
for (int i = split.length - 1; i >= 0; i--) {
bulider.append(split[i] + " ");
}
return bulider.substring(0, bulider.length() - 1).toString();
}
public static void main(String args[]) {
String str1 = "i love you";
int len = str1.length();
String res = null;
res = reverseSentence(str1, len);
System.out.println("The res is:" + res);
}
}
| [
"doug65535@gmail.com"
] | doug65535@gmail.com |
314e875c453386489c01ef88d6bdddacb6b1cd14 | 4863c358eaa76cee995992758ccf11b5f0ae651e | /src/minecraft/biomesoplenty/items/ItemBOPPickaxe.java | dfeb6a7c187a55a8c6e7da2fe87c1fc0bce2ffed | [] | no_license | psychoma/BiomesOPlenty | f3eba89fa026e441b48bd919edf701cad414361f | 4512618d84eb59de870278e88b2f195b5670b794 | refs/heads/master | 2021-01-15T19:39:25.399718 | 2013-05-14T14:40:05 | 2013-05-14T14:40:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package biomesoplenty.items;
import biomesoplenty.BiomesOPlenty;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.item.EnumToolMaterial;
import net.minecraft.item.ItemPickaxe;
public class ItemBOPPickaxe extends ItemPickaxe
{
public int TextureID = 0;
public ItemBOPPickaxe(int par1, EnumToolMaterial par2, int texture)
{
super(par1, par2);
TextureID = texture;
setCreativeTab(BiomesOPlenty.tabBiomesOPlenty);
}
public void registerIcons(IconRegister iconRegister)
{
if(TextureID==0){ itemIcon = iconRegister.registerIcon("BiomesOPlenty:mudpickaxe"); }
else if(TextureID==1){ itemIcon = iconRegister.registerIcon("BiomesOPlenty:amethystpickaxe"); }
else { itemIcon = iconRegister.registerIcon("BiomesOPlenty:mudball"); }
}
}
| [
"a.dubbz@hotmail.com"
] | a.dubbz@hotmail.com |
31e745680e883881fe1b43e575a804f8e469db36 | 0cbe2ff9245f9b255b1d9830a93fe8feb6128371 | /src/cormenbooksolutions/HeapSortUsingMinHeap.java | 59c5d01ea3d6db78fe7a8e27a5b37850c313b547 | [] | no_license | ShwetiMahajan/IntroductionToAlgorithmsSolutions | b275155e3936ae4a0480205c55c635859567231d | 2a14b7b23cd3aa04157e160a3d33bbac0da28e58 | refs/heads/master | 2021-05-09T11:04:39.031719 | 2018-02-02T16:47:56 | 2018-02-02T16:47:56 | 118,982,795 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 116 | java | package cormenbooksolutions;
/**
* Created by shwetimahajan on 12/4/17.
*/
public class HeapSortUsingMinHeap {
}
| [
"shwetimahajan@ucrwpa2-5-10-25-51-90.wnet.ucr.edu"
] | shwetimahajan@ucrwpa2-5-10-25-51-90.wnet.ucr.edu |
bb8047dff2909c2a56c08b148b6a8baedce77f64 | 641f1d44b5c02a013817af60c23ba41c6423f6ce | /20210226/katas/starter-code/U1M2L5Katas/src/main/java/com/company/Buzzer.java | 9cca15db6812f4f855f6c0f8510afdf2dcf4cec7 | [] | no_license | xitraisia/Daniele_Tenga_JavaS1 | b0fc7e54995c6463bacbf700e6518ac73b3fc594 | 6b9c712bc1f84158f1df26fa396b64041a4e772b | refs/heads/main | 2023-05-05T16:42:19.833144 | 2021-05-21T19:25:45 | 2021-05-21T19:25:45 | 339,541,718 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 175 | java | package com.company;
import com.company.interfaces.Alarm;
public class Buzzer implements Alarm{
public void sound() {
System.out.println("Alarm!!!!!");
}
}
| [
"cookiie@Danieles-Air-2.attlocal.net"
] | cookiie@Danieles-Air-2.attlocal.net |
8a002a13e3db42d9df506301a724780b4873ff6c | 0a4bfaad90a8939a897ae770a9209a3947511b40 | /Watson/src/main/java/com/hadleym/watson/index/DocumentIndexer.java | 6ce42c66cdc5741fc8370cf282558c4a81f3ab7c | [] | no_license | hadleym/Watson | 5d3ac6ff3bf17eb64b9bb22254b06b09f42f8ccc | 0ac53ab290486746fbeccf32adaf2dceb2414b02 | refs/heads/master | 2021-01-19T21:33:56.349742 | 2017-05-09T19:33:03 | 2017-05-09T19:33:03 | 88,667,027 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,200 | java | package com.hadleym.watson.index;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import com.hadleym.watson.Constants;
/*
* This class provides the functionality of indexing
* a given directory of files into another directory
* using a given analyzer.
*/
public class DocumentIndexer {
File srcDir, destDir;
Analyzer analyzer;
IndexWriter indexWriter;
BufferedReader br;
public DocumentIndexer(File srcDir, File destDir, Analyzer analyzer) {
this.srcDir = srcDir;
this.destDir = destDir;
this.analyzer = analyzer;
}
// index the files in the given directory with a
// simpleFSDirectory
public void indexAllFiles() {
try {
Directory directory = new SimpleFSDirectory(destDir.toPath());
this.indexWriter = new IndexWriter(directory, new IndexWriterConfig(analyzer));
int total = srcDir.listFiles().length;
int count = 1;
for (File srcFile : srcDir.listFiles()) {
System.out.print(count++ + " of " + total + ", ");
indexFile(srcFile, destDir, indexWriter);
}
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
// index a single file into the destination directory and the given
// indexWriter.
public void indexFile(File srcFile, File destDir, IndexWriter indexWriter) throws IOException {
Reader reader = new FileReader(srcFile);
BufferedReader br = new BufferedReader(reader);
// assumes that the first line of a text document is a subject
String line = br.readLine();
Document document = new Document();
addTextField(document, Constants.FIELD_CATEGORY, line);
addTextField(document, Constants.FIELD_CONTENTS, line);
// read through each line until EOF is reached.
for (line = br.readLine(); line != null; line = br.readLine()) {
if (!isCategory(line)) {
if (Constants.DEBUG) {
System.out.print("Adding to contents--> ");
System.out.println(line);
}
document.add(new TextField(Constants.FIELD_CONTENTS, line, Field.Store.YES));
} else {
indexWriter.addDocument(document);
document = new Document();
addTextField(document, Constants.FIELD_CATEGORY, line);
addTextField(document, Constants.FIELD_CONTENTS, line);
}
}
br.close();
System.out.println(srcFile.getName() + " finished");
}
// add a single line to the given field of a lucene document.
public void addTextField(Document document, String field, String line) {
if (Constants.DEBUG) {
System.out.println("New Category: " + line);
}
document.add(new TextField(field, line, Field.Store.YES));
}
// categories are determined by having '[[' as the first
// two characters.
public static boolean isCategory(String line) {
return (line.length() > 2 && line.charAt(0) == '[' && line.charAt(1) == '[');
}
}
| [
"hadleym@email.arizona.edu"
] | hadleym@email.arizona.edu |
8dac53822d2e313f8b0c1e4641faf852e0e649fa | 5991ad88a5dcbc1deb1b118c6ab272948cb0c33d | /core/src/test/java/org/dkf/jed2k/test/SessionTest.java | 9245ea0d9410df2ed8c5d84c1158f8bbfceee64e | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | riverfor/jed2k | 4e7e5847e09810c7f6112e41f883be737e219912 | 1a66bceea6bcaad810de1ac3c332398f6e1c91bd | refs/heads/master | 2021-01-20T13:42:37.795722 | 2017-05-06T09:53:16 | 2017-05-06T09:53:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,560 | java | package org.dkf.jed2k.test;
import org.dkf.jed2k.Session;
import org.dkf.jed2k.SessionTrial;
import org.dkf.jed2k.Settings;
import org.dkf.jed2k.TransferHandle;
import org.dkf.jed2k.exception.JED2KException;
import org.dkf.jed2k.protocol.Endpoint;
import org.dkf.jed2k.protocol.Hash;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.LinkedList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by inkpot on 24.08.2016.
*/
public class SessionTest {
private Session session;
private Settings settings;
@Before
public void setupSession() {
settings = new Settings();
settings.listenPort = -1;
session = new SessionTrial(settings, new LinkedList<Endpoint>());
}
@Test
public void testTransferHandle() throws JED2KException, InterruptedException {
session.start();
TransferHandle handle = session.addTransfer(Hash.EMULE, 1000L, new File("xxx"));
assertTrue(handle.isValid());
TransferHandle handle2 = session.addTransfer(Hash.EMULE, 1002L, new File("yyy"));
assertEquals(1, session.getTransfers().size());
assertEquals(handle, handle2);
assertEquals(1000L, handle2.getSize());
assertEquals("xxx", handle2.getFile().getName());
assertTrue(handle2.getPeersInfo().isEmpty());
session.removeTransfer(handle.getHash(), true);
session.abort();
session.join();
assertEquals(0, session.getTransfers().size());
}
}
| [
"dkfsoft@gmail.com"
] | dkfsoft@gmail.com |
d35d24fa4691217ee357d4e6322b5f15157cb980 | 4901f839469449b46e7d844bb21c3f8e7ee0f367 | /LibraryJ2EE5.0/LibraryWebProject/src/com/ibm/library/ejb/PatronEJBLocal.java | 624496981342aac0a8f7cf794ef97be26c0b59a7 | [] | no_license | BegBang/library | e86a3364ed90b1d67cd9c1e17a68e1a7c80073ee | 7566f47b1e631b9413485f3603de2dfe8818600e | refs/heads/master | 2021-01-13T01:36:08.555306 | 2012-06-03T11:08:37 | 2012-06-03T11:08:37 | 3,603,223 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 557 | java | package com.ibm.library.ejb;
import javax.ejb.Local;
import javax.persistence.EntityExistsException;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.RollbackException;
import com.ibm.library.Patron;
@Local
public interface PatronEJBLocal {
public void add(Patron p) throws EntityExistsException, RollbackException, IllegalStateException;
public Patron findByEmail(String email) throws NoResultException, IllegalArgumentException, IllegalStateException, NonUniqueResultException;
}
| [
"begbang@gmail.com"
] | begbang@gmail.com |
be699b488a55ebbbb4b16306d737bfdefd1c76c8 | 87f3ec89b0738a0ff6a777a63f6535671b38f308 | /java/src/main/java/com/sebuilder/interpreter/Aspect.java | 6588066615084f4eda62b6b69f021a97cbbc4933 | [
"Apache-2.0"
] | permissive | y-onodera/SeInterpreter-Java | 48904252e7f0b9b554d7d2526a932c2867666697 | 6b2c91d5fb4d4178eefe439ad5d42ec5b9b6eb2a | refs/heads/master | 2023-09-01T13:36:31.741073 | 2023-08-27T04:11:30 | 2023-08-27T04:11:30 | 129,473,376 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,432 | java | package com.sebuilder.interpreter;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public record Aspect(Iterable<Interceptor> interceptors) implements Iterable<Interceptor> {
public static Aspect from(final Stream<Interceptor> interceptors) {
return new Aspect(interceptors.collect(Collectors.toList()));
}
public Aspect() {
this(new ArrayList<>());
}
public Aspect(final Iterable<Interceptor> interceptors) {
final ArrayList<Interceptor> src = new ArrayList<>();
interceptors.forEach(src::add);
this.interceptors = src;
}
public Builder builder() {
return new Builder(this.interceptors);
}
public Advice advice(final TestRun testRun, final Step step, final InputData vars) {
return new Advice(this.getStream()
.filter(interceptor -> interceptor.isPointcut(testRun, step, vars))
.toList());
}
public Stream<Interceptor> getStream() {
return this.toStream(this.interceptors);
}
@Override
@Nonnull
public Iterator<Interceptor> iterator() {
return this.interceptors.iterator();
}
public Aspect filter(final Predicate<Interceptor> condition) {
return from(this.getStream().filter(condition));
}
public Aspect materialize(final InputData shareInput) {
return from(this.getStream().flatMap(it -> it.materialize(shareInput)));
}
public Aspect takeOverChain(final boolean newValue) {
return from(this.getStream().map(it -> it.takeOverChain(newValue)));
}
public Aspect replace(final Interceptor currentValue, final Interceptor newValue) {
return from(this.getStream().map(it -> it.equals(currentValue) ? newValue : it));
}
public Aspect remove(final Interceptor removeItem) {
return from(this.getStream().filter(it -> !it.equals(removeItem)));
}
public record Advice(List<Interceptor> advices) {
public boolean invokeBefore(final TestRun testRun) {
for (final Interceptor interceptor : this.advices) {
if (!interceptor.invokeBefore(testRun)) {
return false;
}
}
return true;
}
public boolean invokeAfter(final TestRun testRun) {
for (final Interceptor interceptor : this.advices) {
if (!interceptor.invokeAfter(testRun)) {
return false;
}
}
return true;
}
public void invokeFailure(final TestRun testRun) {
for (final Interceptor interceptor : this.advices) {
if (!interceptor.invokeFailure(testRun)) {
return;
}
}
}
}
private Stream<Interceptor> toStream(final Iterable<Interceptor> materialize) {
return StreamSupport.stream(materialize.spliterator(), false);
}
public static class Builder {
private LinkedHashSet<Interceptor> interceptors;
public Builder(final Iterable<Interceptor> interceptors) {
this.interceptors = new LinkedHashSet<>();
interceptors.forEach(this.interceptors::add);
}
public Builder add(final Supplier<Interceptor> interceptorSupplier) {
this.interceptors.add(interceptorSupplier.get());
return this;
}
public Builder add(final Interceptor interceptor) {
this.interceptors.add(interceptor);
return this;
}
public Builder add(final Iterable<Interceptor> interceptor) {
interceptor.forEach(this.interceptors::add);
return this;
}
public Builder insert(final Iterable<Interceptor> other) {
final LinkedHashSet<Interceptor> newInterceptors = new LinkedHashSet<>();
other.forEach(newInterceptors::add);
newInterceptors.addAll(this.interceptors);
this.interceptors = newInterceptors;
return this;
}
public Aspect build() {
return new Aspect(this.interceptors);
}
}
} | [
"yutaonodera0304@gmail.com"
] | yutaonodera0304@gmail.com |
67463cf910a5997aee22aaaa5f0862a3f96b3586 | 9837c2ffbec5a409e6636155906b444b22350622 | /src/utils/Cell.java | 28415de511c75c18b91958bbde95fe4bf8fc8e76 | [] | no_license | AI-Ant-Feng/tetris_test | a46c59a5b1a2db1fc7f3db0f6c2cb515097afb41 | 6bf84c73f8efb2b6a9a8ba417ed6dd7bf21849a3 | refs/heads/master | 2023-03-04T11:57:12.153016 | 2021-02-03T01:36:31 | 2021-02-03T01:36:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 788 | java | package utils;
import java.awt.*;
public class Cell {
public static void drawCell(Graphics graphics, int px, int py, Color color){
graphics.setColor(color);
graphics.fillRect(
px,
py,
Constant.CELL_WIDTH,
Constant.CELL_HEIGHT);
graphics.setColor(Constant.COLOR_WHITE);
graphics.drawRect(
px,
py,
Constant.CELL_WIDTH - 1,
Constant.CELL_HEIGHT - 1);
}
public static void drawGrid(Graphics graphics, int px, int py, Color color){
graphics.setColor(color);
graphics.drawRect(
px,
py,
Constant.CELL_WIDTH,
Constant.CELL_HEIGHT);
}
}
| [
"fj_whlt@163.com"
] | fj_whlt@163.com |
d17d68b77bb400d608264c406deb7f1bc2aee23a | 86405eafa26f6a185f2143fbe0c910f855427600 | /src/server/RegisterServer.java | a3daecaec720e73d7c5af58c911122f573150e99 | [] | no_license | crazyhmc/MiniQQ | a4e26b604ace197d91e23355b4fd1f4656ae89c8 | fd2dbebcb19980e5f2640f3b096e52bf73de9e78 | refs/heads/master | 2021-01-24T17:01:11.938275 | 2017-06-19T11:25:30 | 2017-06-19T11:25:30 | 89,556,846 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 3,415 | java | package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import db.DBconnection;
import objects.User;
public class RegisterServer {
private ServerSocket server;
private Socket socket;
private Connection con;
private PreparedStatement state;
private ResultSet res;
public RegisterServer(Connection con) {
try {
server = new ServerSocket(8890);
} catch (IOException e) {
e.printStackTrace();
}
this.con = con;
}
public void serve() {
while(true) {
try {
socket = server.accept();
} catch (IOException e) {
e.printStackTrace();
}
if(socket != null) {
new Thread(new RegisterServe(socket)).start();
}
}
}
public void close() {
}
public static void main(String[] args) {
}
private class RegisterServe implements Runnable {
private Socket s;
private ObjectInputStream ois;
private ObjectOutputStream oop;
public RegisterServe(Socket s) {
this.s = s;
}
@Override
public void run() {
String username = null;
String password = null;
String nick = null;
String sex = null;
User u = null;
// 保证对数据库的操作不会被打断
synchronized (con) {
try {
ois = new ObjectInputStream(s.getInputStream());
oop = new ObjectOutputStream(s.getOutputStream());
username = ois.readUTF();
System.out.println(username);
state = con.prepareStatement("select*from user where username = ?");
state.setString(1, username);
res = state.executeQuery();
if (!res.next()) {
oop.writeUTF("没毛病");
oop.flush();
u = (User)ois.readObject();
username = u.getUserName();
password = u.getPassword();
nick = u.getNick();
sex = u.getSex();
state = con.prepareStatement("insert into user(username,password,nickname,sex) values(?,?,?,?)");
state.setString(1, username);
state.setString(2, password);
state.setString(3, nick);
state.setString(4, sex);
if(!state.execute()){
oop.writeUTF("注册成功");
oop.flush();
}
else {
oop.writeUTF("注册失败");
oop.flush();
}
} else {
oop.writeUTF("用户名已存在");
oop.flush();
}
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (res != null) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
res = null;
}
if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
state = null;
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
ois = null;
}
if (oop != null) {
try {
oop.close();
} catch (IOException e) {
e.printStackTrace();
}
oop = null;
}
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
s = null;
}
}
}
}
}
}
| [
"2394002693@qq.com"
] | 2394002693@qq.com |
2d8808f51548495c47f349983cd5875eaccf776e | cd83f67406c18d5b14e3bca12e6803b05d425039 | /app/src/main/java/com/ccs/utils/Utils.java | 77f7e4d06a2eb9fec2d635e546544b1615904bfb | [] | no_license | lllllsun/CcsNew | c0ecbd6702070b784b9ab8f0617535deda460ae8 | 093c713ec3a48f7b75e59146819ab67ce0e6908a | refs/heads/master | 2021-01-20T03:57:07.920921 | 2017-05-01T15:26:22 | 2017-05-01T15:26:22 | 89,610,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | package com.ccs.utils;
import java.util.ArrayList;
/**
* Created by DangH on 2017/4/28.
*/
public class Utils {
public static Utils getThis() {
return new Utils();
}
}
| [
"dang.hy@outlook.com"
] | dang.hy@outlook.com |
055f6a33d775da1ee92b4d146b3dfa7f7793db8a | aed9c187ea4b9971ed73077c3e98ebd0262d60b6 | /004 Development/001 Implementation/e-TrustEx/etrustex-dao/src/test/java/eu/europa/ec/etrustex/dao/MessageDAOTest.java | ab97ea5b5d9e29f94020da15321b465986107482 | [] | no_license | fassifehrim/Open-e-TrustEx | fb2414344bf2c888be17c00260831c5971e3e91a | 6518dc9ac12ce698413836cd8693da5b12216a72 | refs/heads/master | 2020-08-08T00:09:58.017625 | 2019-03-04T12:18:22 | 2019-03-04T12:18:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 36,823 | java | package eu.europa.ec.etrustex.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import eu.europa.ec.etrustex.dao.dto.MessageQueryDTO;
import eu.europa.ec.etrustex.dao.dto.RetrieveMessagesForQueryRequestDTO;
import eu.europa.ec.etrustex.dao.util.DispatchEnum;
import eu.europa.ec.etrustex.domain.InterchangeAgreement;
import eu.europa.ec.etrustex.domain.Message;
import eu.europa.ec.etrustex.domain.MessageBinary;
import eu.europa.ec.etrustex.domain.Party;
import eu.europa.ec.etrustex.domain.Profile;
import eu.europa.ec.etrustex.domain.Transaction;
import eu.europa.ec.etrustex.domain.admin.BusinessDomain;
import eu.europa.ec.etrustex.domain.query.QueryResult;
import eu.europa.ec.etrustex.domain.routing.JMSEndpoint;
import eu.europa.ec.etrustex.domain.routing.MessageRouting;
import eu.europa.ec.etrustex.domain.util.EntityAccessInfo;
import eu.europa.ec.etrustex.domain.util.MessagesListVO;
import eu.europa.ec.etrustex.types.DataExtractionTypes;
import eu.europa.ec.etrustex.types.SortFieldTypeCode;
public class MessageDAOTest extends AbstractEtrustExTest {
@Autowired private IMessageDAO msgDao;
@Autowired private IPartyDAO partyDao;
@Autowired private ITransactionDAO transactionDao;
@Autowired private IInterchangeAgreementDAO icaDao;
@Autowired private IBusinessDomainDAO bdDao;
@Autowired private IQueryResultDAO qrDao;
@Autowired private IMessageRoutingDAO mrDao;
@Autowired private IEndpointDAO epDao;
private static final String STATUS_CODE_RECEIVED = "RECEIVED";
private static final String STATUS_CODE_ERROR = "ERROR";
private static final String DOCUMENT_TYPE_CODE = "TDTC";
private static final String DOCUMENT_ID = "DOCUMENT_ID_1";
private static final String CORRELATION_ID = "CORRELATION_ID_1";
private static final String USER_ID = "USER_U_TEST";
private static final String BUSINESS_DOCUMENT = "B_DOCUMENT_UTEST";
private static final String CREATION_USER = "user";
private static final int MAX_RESULTS = 20;
private Date startDate;
private Date endDate;
private Message message1;
private Party partySender;
private Party partyReceiver;
private Transaction transaction1;
private BusinessDomain bd1;
@Before
public void setupTests(){
startDate = new Date(System.currentTimeMillis() - (1 * 60 * 60 * 1000));
endDate = new Date(System.currentTimeMillis());
bd1 = new BusinessDomain();
bd1.setName("BD1");
bd1.setResponseSignatureRequired(Boolean.TRUE);
bdDao.create(bd1);
partySender = new Party();
partySender.setName("UTEST_PARTY_S");
partySender.setBusinessDomain(bd1);
partySender = partyDao.create(partySender);
partyReceiver = new Party();
partyReceiver.setName("UTEST_PARTY_R");
partyReceiver = partyDao.create(partyReceiver);
transaction1 = new Transaction();
transaction1.setName("UTEST_TRANSACTION");
transaction1 = transactionDao.create(transaction1);
message1 = msgDao.create(buildMessage(DOCUMENT_ID, STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate));
}
@Test(expected=DataIntegrityViolationException.class)
public void testCreateMessageDataIntegrityException(){
Message m = new Message();
msgDao.createMessage(m);
Assert.fail("Exception Not Caught");
}
@Test
public void testCreateMessage(){
Message m = buildMessage("MY_MESSAGE", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
msgDao.createMessage(m);
Assert.assertNotNull(m.getId());
}
@Test
public void testRetrieveMessage4Params(){
Message m = msgDao.retrieveMessage(DOCUMENT_ID,DOCUMENT_TYPE_CODE,partySender.getId(),partyReceiver.getId());
Assert.assertNotNull(m.getId());
m = msgDao.retrieveMessage(DOCUMENT_ID,"Fake",partySender.getId(),partyReceiver.getId());
Assert.assertNull(m);
}
@Test
public void testFindMessagesByDocumentId(){
String uuid = UUID.randomUUID().toString();
msgDao.create(buildMessage(uuid, STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate));
Assert.assertEquals(1, msgDao.findMessagesByDocumentId(uuid));
}
@Test
public void testRetrieveMessages6Params(){
Set<String> statesToExclude = new HashSet<String>();
statesToExclude.add("RECEIVED");
List<Message> list = msgDao.retrieveMessages(DOCUMENT_ID, DOCUMENT_TYPE_CODE, partySender.getId(), null, Boolean.FALSE, null);
Assert.assertEquals(1, list.size());
Assert.assertNotNull(list.get(0).getId());
list = msgDao.retrieveMessages(DOCUMENT_ID, DOCUMENT_TYPE_CODE, null, partyReceiver.getId(), Boolean.FALSE, null);
Assert.assertEquals(1, list.size());
Assert.assertNotNull(list.get(0).getId());
list = msgDao.retrieveMessages(DOCUMENT_ID, DOCUMENT_TYPE_CODE, null, partySender.getId(), Boolean.TRUE, null);
Assert.assertEquals(1, list.size());
Assert.assertNotNull(list.get(0).getId());
list = msgDao.retrieveMessages(DOCUMENT_ID, DOCUMENT_TYPE_CODE, partyReceiver.getId(), partySender.getId(), Boolean.TRUE, statesToExclude);
Assert.assertEquals(0, list.size());
list = msgDao.retrieveMessages(DOCUMENT_ID+"_FAKE", DOCUMENT_TYPE_CODE, null, partyReceiver.getId(), Boolean.TRUE, null);
Assert.assertEquals(0, list.size());
}
@Test
public void testRetrieveMsgWithEproFilterAppResponseNoParent(){
MessageQueryDTO mq = new MessageQueryDTO();
mq.setReceiverPartyId(partySender.getId());
mq.setTransactions(new HashSet<Transaction>());
mq.setRetrievedInd(Boolean.FALSE);
mq.setFetchParents(Boolean.TRUE);
mq.setInboxServiceFilter(Boolean.TRUE);
mq.setMaxResult(20);
Message message301 = buildMessage("DOC_301_WithoutParent", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
message301.setMessageDocumentTypeCode("301");
message301 = msgDao.create(message301);
List<Message> inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Parent is null so a the doc should be returned", 1, inbox.size());
message301.setMessageDocumentTypeCode("501");
message301 = msgDao.update(message301);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("SHouldn't be filtered out", 1, inbox.size());
}
@Test
public void testRetrieveMsgWithEproFilteAppResponseWithParent(){
List<Message> inbox;
Set<Transaction> transactions = new HashSet<Transaction>();
Transaction transaction2 = new Transaction();
transaction2.setName("UTEST_TRANSACTION_2");
transaction2 = transactionDao.create(transaction2);
transactions.add(transaction2);
Transaction transaction3 = new Transaction();
transaction3.setName("UTEST_TRANSACTION_3");
transaction3 = transactionDao.create(transaction3);
MessageQueryDTO mq = new MessageQueryDTO();
mq.setReceiverPartyId(partySender.getId());
mq.setTransactions(transactions);
mq.setRetrievedInd(Boolean.FALSE);
mq.setFetchParents(Boolean.TRUE);
mq.setInboxServiceFilter(Boolean.TRUE);
mq.setMaxResult(20);
Message parentOfMessage301 = buildMessage("DOC_301_Parent", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
parentOfMessage301.setTransaction(transaction3);
parentOfMessage301 = msgDao.create(parentOfMessage301);
Message message301 = buildMessage("DOC_301", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
message301.setMessageDocumentTypeCode("301");
message301.setTransaction(transaction2);
message301.getParentMessages().add(parentOfMessage301);
message301 = msgDao.create(message301);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Should not return a result because the TX-2 should be filtered out", 0, inbox.size());
transactions.add(transaction3);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Should return a result because the parent is part of the Transactions", 1, inbox.size());
message301.setMessageDocumentTypeCode("916");
msgDao.update(message301);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Attached Document should work as well", 1, inbox.size());
}
@Test
public void testRetrieveMsgWithEproFilterAttachement(){
List<Message> inbox;
Set<Transaction> transactions = new HashSet<Transaction>();
Transaction transaction2 = new Transaction();
transaction2.setName("UTEST_TRANSACTION_2");
transaction2 = transactionDao.create(transaction2);
transactions.add(transaction2);
Transaction transaction3 = new Transaction();
transaction3.setName("UTEST_TRANSACTION_3");
transaction3 = transactionDao.create(transaction3);
//transactions.add(transaction3);
MessageQueryDTO mq = new MessageQueryDTO();
mq.setReceiverPartyId(partySender.getId());
mq.setTransactions(transactions);
mq.setRetrievedInd(Boolean.FALSE);
mq.setFetchParents(Boolean.TRUE);
mq.setInboxServiceFilter(Boolean.TRUE);
mq.setMaxResult(20);
Message grandParent916 = buildMessage("DOC_916_GrandParent", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
grandParent916.setTransaction(transaction3);
grandParent916 = msgDao.create(grandParent916);
Message parent916 = buildMessage("DOC_916_Parent", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
parent916.setMessageDocumentTypeCode("916");
parent916.getParentMessages().add(grandParent916);
parent916 = msgDao.create(parent916);
Message message916 = buildMessage("DOC_916", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
message916.setMessageDocumentTypeCode("916");
message916.setTransaction(transaction2);
message916.getParentMessages().add(parent916);
message916 = msgDao.create(message916);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Filtering by transaction", 0, inbox.size());
transactions.add(transaction3);
inbox = msgDao.retrieveMessages(mq);
Assert.assertEquals("Filtering by transaction - Should return 1 result", 1, inbox.size());
}
@Test
public void testRetrieveMessages14ParamsFilteredRead_NoParent(){
List<Message> list;
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, partySender.getId()));
Assert.assertEquals("Only the main message should be returned", 1, list.size());
}
@Test
public void testRetrieveMessages14ParamsFilteredRead_WrongParent(){
List<Message> list;
Message parent = buildMessage(DOCUMENT_ID+"P3", STATUS_CODE_RECEIVED, partySender, partySender, partySender, CORRELATION_ID, false, endDate);
message1.addParentMessage(parent);
parent.addChildMessage(message1);
msgDao.create(parent);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, partyReceiver.getId()));
Assert.assertEquals("With Filtering disabled it should return 1 result", 1, list.size());
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, partyReceiver.getId()));
Assert.assertEquals("With wrong parent should return a result", 1, list.size());
}
@Test
public void testRetrieveMessages14ParamsFilteredRead_RightSenderAndIssuer(){
List<Message> list;
Message parent = buildMessage(DOCUMENT_ID+"P2", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
message1.addParentMessage(parent);
parent.addChildMessage(message1);
msgDao.create(parent);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, partyReceiver.getId()));
Assert.assertEquals("With Filtering disabled it should return one result", 1, list.size());
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE,partyReceiver.getId()));
Assert.assertEquals("With Filtering enabled we need to have 1 result as we have a valid parent", 1, list.size());
}
@Test
public void testRetrieveMessages14ParamsFilteredRead_RightSenderWrongIssuer(){
List<Message> list;
Message parent1 = buildMessage(DOCUMENT_ID+"P1", STATUS_CODE_RECEIVED, partyReceiver, partySender, partySender, CORRELATION_ID, false, endDate);
message1.addParentMessage(parent1);
parent1.addChildMessage(message1);
msgDao.create(parent1);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, partyReceiver.getId()));
Assert.assertEquals("With Filtering disabled it should return one result", 1, list.size());
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), null, null, null, null, 20, null, null, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, partyReceiver.getId()));
Assert.assertEquals("With Filtering enabled no message should be returned, wrong Issuer", 0, list.size());
}
@Test
public void testRetrieveMessages14Params(){
List<Message> list;
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), null, new HashSet<>(Arrays.asList(transaction1)), 20, DOCUMENT_ID, DOCUMENT_TYPE_CODE, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("Only the main message should be returned", 1, list.size());
Message parentM = buildMessage("Parent_Msg", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
parentM = msgDao.create(parentM);
message1.setParentMessages(new HashSet<>(Arrays.asList(parentM)));
message1.addMessageBinary(new MessageBinary());
message1 = msgDao.update(message1);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), null, new HashSet<>(Arrays.asList(transaction1)), 20, DOCUMENT_ID, DOCUMENT_TYPE_CODE, null, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("1 result returned after fetching the binaries & parents", 1, list.size());
message1.setRetrieveIndicator(Boolean.TRUE);
message1 = msgDao.update(message1);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), null, new HashSet<>(Arrays.asList(transaction1)), 20, DOCUMENT_ID, DOCUMENT_TYPE_CODE, Boolean.FALSE, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("Retrieve Indicator should filter out the reult", 0, list.size());
Message errorM = buildMessage("Error_Msg", STATUS_CODE_ERROR, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
errorM = msgDao.create(errorM);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), null, new HashSet<>(Arrays.asList(transaction1)), 20, null, DOCUMENT_TYPE_CODE, null, Boolean.TRUE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("Error Message is filtered out", 1, list.size());
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), null, new HashSet<>(Arrays.asList(transaction1)), 20, null, DOCUMENT_TYPE_CODE, null, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, null));
Assert.assertEquals("Main & Error Message should be retrieved", 2, list.size());
Profile p = new Profile();
p.setName("P1");
InterchangeAgreement ica = new InterchangeAgreement();
ica.setProfile(p);
ica = icaDao.create(ica);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), ica.getId(), new HashSet<>(Arrays.asList(transaction1)), 20, null, DOCUMENT_TYPE_CODE, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("No message related to the new ICA", 0, list.size());
message1.setAgreement(ica);
message1 = msgDao.update(message1);
list = msgDao.retrieveMessages(new MessageQueryDTO(partyReceiver.getId(), partySender.getId(), partySender.getId(), ica.getId(), new HashSet<>(Arrays.asList(transaction1)), 20, null, DOCUMENT_TYPE_CODE, null, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, null));
Assert.assertEquals("Should return 1 result linked to the new ICA", 1, list.size());
}
/**
* no parents, no binaries, messages in error included
*/
@Test
public void testRetrieveMessagesForQueryRequest(){
Set<Long> senderSet = new HashSet<Long>(Arrays.asList(partySender.getId()));
Set<Long> receiverSet = new HashSet<Long>(Arrays.asList(partyReceiver.getId()));
// START OF TEST 1
//chiricr: issuerPartyId, documentId and hasParent were removed from the method signature because the code calling the method was never sending a non-null parameter
RetrieveMessagesForQueryRequestDTO queryDTO = new RetrieveMessagesForQueryRequestDTO.Builder()
.setReceiverPartyIds(receiverSet)
.setSenderPartyIds(senderSet)
.setTransactions(new HashSet<>(Arrays.asList(transaction1)))
.setDocumentTypeCodes(new HashSet<>(Arrays.asList(DOCUMENT_TYPE_CODE)))
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setMaxResult(MAX_RESULTS)
.setFetchParents(false)
.setFetchBinaries(false)
.setIsSenderAlsoReceiver(false)
.setFilterOutMessagesInError(true)
.build();
List<Message> list = msgDao.retrieveMessagesForQueryRequest(queryDTO);
Assert.assertEquals("Should return 1 result", 1, list.size());
// END OF TEST 1
// START OF TEST 2
Message errorM = buildMessage("Error_Msg", STATUS_CODE_ERROR, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
errorM = msgDao.create(errorM);
queryDTO = new RetrieveMessagesForQueryRequestDTO.Builder()
.setReceiverPartyIds(receiverSet)
.setSenderPartyIds(senderSet)
.setTransactions(new HashSet<>(Arrays.asList(transaction1)))
.setDocumentTypeCodes(new HashSet<>(Arrays.asList(DOCUMENT_TYPE_CODE)))
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setMaxResult(MAX_RESULTS)
.setFetchParents(false)
.setFetchBinaries(false)
.setIsSenderAlsoReceiver(false)
.setFilterOutMessagesInError(false)
.build();
list = msgDao.retrieveMessagesForQueryRequest(queryDTO);
Assert.assertEquals("Should return 1 result + 1 Error", 2, list.size());
// END OF TEST 2
// START OF TEST 3
Message parentM = buildMessage("Parent_Msg", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION_ID, false, endDate);
parentM = msgDao.create(parentM);
message1.setParentMessages(new HashSet<>(Arrays.asList(parentM)));
message1.addMessageBinary(new MessageBinary());
message1.setRetrieveIndicator(Boolean.TRUE);
message1 = msgDao.update(message1);
queryDTO = new RetrieveMessagesForQueryRequestDTO.Builder()
.setReceiverPartyIds(receiverSet)
.setSenderPartyIds(senderSet)
.setTransactions(new HashSet<>(Arrays.asList(transaction1)))
.setDocumentTypeCodes(new HashSet<>(Arrays.asList(DOCUMENT_TYPE_CODE)))
.setRetrievedInd(true)
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setMaxResult(MAX_RESULTS)
.setFetchParents(true)
.setFetchBinaries(true)
.setIsSenderAlsoReceiver(false)
.setFilterOutMessagesInError(false)
.build();
list = msgDao.retrieveMessagesForQueryRequest(queryDTO);
Assert.assertEquals("Should return 1 result after adding parent & message Binary", 1, list.size());
// END OF TEST 3
// START OF TEST 4
//TODO Is this realistic?
Message senderReceiver = buildMessage("senderReceiver", STATUS_CODE_RECEIVED, partySender, partySender, partySender, CORRELATION_ID, false, endDate);
senderReceiver = msgDao.create(senderReceiver);
queryDTO = new RetrieveMessagesForQueryRequestDTO.Builder()
.setSenderPartyIds(senderSet)
.setTransactions(new HashSet<>(Arrays.asList(transaction1)))
.setDocumentTypeCodes(new HashSet<>(Arrays.asList(DOCUMENT_TYPE_CODE)))
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setMaxResult(MAX_RESULTS)
.setFetchParents(false)
.setFetchBinaries(false)
.setIsSenderAlsoReceiver(true)
.setFilterOutMessagesInError(true)
.build();
list = msgDao.retrieveMessagesForQueryRequest(queryDTO);
//ETRUSTEX-3859 by removing the parameter hasParents, which was never used aside from the unit tests, this test now returns 2 records instead of 1
Assert.assertEquals("Should return 2 results: SenderReceiver and Parent_Msg", 2, list.size());
// END OF TEST 4
// START OF TEST 5
queryDTO = new RetrieveMessagesForQueryRequestDTO.Builder()
.setReceiverPartyIds(receiverSet)
.setSenderPartyIds(senderSet)
.setTransactions(new HashSet<>(Arrays.asList(transaction1)))
.setDocumentTypeCodes(new HashSet<>(Arrays.asList(DOCUMENT_TYPE_CODE)))
.setRetrievedInd(true)
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setFetchParents(true)
.setFetchBinaries(true)
.setIsSenderAlsoReceiver(false)
.setFilterOutMessagesInError(false)
.build();
list = msgDao.retrieveMessagesForQueryRequest(queryDTO);
Assert.assertEquals("Should return 1 result ", 1, list.size());
// END OF TEST 5
}
@Test
public void testGetStatusCodes(){
int scCount = msgDao.getStatusCodes().size();
String SC = "FAKE_SC";
msgDao.create(buildMessage("01", SC, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate));
List<String> sc2 = msgDao.getStatusCodes();
Assert.assertEquals("There should be 1 new Status Code", 1 ,sc2.size()-scCount);
boolean newStatusFound = false;
for (String string : sc2) {
if(SC.equals(string)){
newStatusFound = true;
}
}
if(!newStatusFound){
Assert.fail("New Status Code Not Returned");
}
}
@Test
public void testGetDocumentTypeCodes(){
boolean newDTCFound = false;
for (String string : msgDao.getDocumentTypeCodes()) {
if(DOCUMENT_TYPE_CODE.equals(string)){
newDTCFound = true;
}
}
if(!newDTCFound){
Assert.fail("New Document Type Code Not Returned");
}
}
@Test
public void testFindMessagesByTransaction(){
msgDao.create(buildMessage("01", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate));
Assert.assertEquals("Should return 2 ", 2,msgDao.findMessagesByTransaction(transaction1.getId()));
Transaction transaction2 = new Transaction();
transaction2.setName("UTEST_TRANSACTION_2");
transaction2 = transactionDao.create(transaction2);
Assert.assertEquals("Should return 0", 0,msgDao.findMessagesByTransaction(transaction2.getId()));
}
@Test
public void testRetrieveOrphans(){
List<Message> list;
Transaction transaction2 = new Transaction();
transaction2.setName("UTEST_TRANSACTION2");
transaction2 = transactionDao.create(transaction2);
Transaction transaction3 = new Transaction();
transaction3.setName("UTEST_TRANSACTION3");
transaction3 = transactionDao.create(transaction3);
Message message2 = buildMessage("Message2", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
msgDao.create(message2);
Message message3 = buildMessage("Message3", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
message3.setTransaction(transaction2);
msgDao.create(message3);
list = msgDao.retrieveOrphans(bd1, transaction1, startDate, endDate);
Assert.assertEquals("Should return 2", 2, list.size());
list = msgDao.retrieveOrphans(bd1, null, startDate, endDate);
Assert.assertEquals("Should return 3 as TX is not taken into account", 3, list.size());
message1.getChildMessages().add(message2);
message2.addParentMessage(message1);
msgDao.update(message1);
list = msgDao.retrieveOrphans(bd1, transaction1, startDate, endDate);
Assert.assertEquals("Should only return the parent", 1, list.size());
Assert.assertEquals("Should only return the parent", message1.getId(), list.get(0).getId());
list = msgDao.retrieveOrphans(bd1, null, startDate, endDate);
Assert.assertEquals("Should return message1 & 3", 2, list.size());
BusinessDomain bd2 = new BusinessDomain();
bd2.setName("BD2");
bd2.setResponseSignatureRequired(Boolean.TRUE);
bd2 = bdDao.create(bd2);
list = msgDao.retrieveOrphans(bd2, transaction1, startDate, endDate);
Assert.assertEquals("Should return 0 as bd2 is not related to any message", 0, list.size());
}
@Test
public void testRetrieveLeaves(){
List<Message> list;
list = msgDao.retrieveLeaves(bd1, transaction1, startDate, endDate, null);
Assert.assertEquals("One message available for this transaction", 1, list.size());
Assert.assertEquals(message1.getId(), list.get(0).getId());
Message message2 = buildMessage("Message2", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION_ID, false, endDate);
message2.addParentMessage(message1);
msgDao.create(message2);
list = msgDao.retrieveLeaves(bd1, transaction1, startDate, endDate, null);
Assert.assertEquals("One leave available for this transaction", 1, list.size());
Assert.assertEquals(message2.getId(), list.get(0).getId());
Transaction transaction2 = new Transaction();
transaction2.setName("UTEST_TRANSACTION2");
transaction2 = transactionDao.create(transaction2);
message2.setTransaction(transaction2);
msgDao.update(message2);
list = msgDao.retrieveLeaves(bd1, transaction1, startDate, endDate, new HashSet<Transaction>(Arrays.asList(transaction2)));
Assert.assertEquals("Parent SHould be returned", 1, list.size());
Assert.assertEquals(message1.getId(), list.get(0).getId());
}
@Test
public void testRetrieveMessagesJustice(){
MessagesListVO listVO;
Set<Long> senderSet = new HashSet<Long>(Arrays.asList(partySender.getId()));
Set<Long> receiverSet = new HashSet<Long>(Arrays.asList(partyReceiver.getId()));
Set<Transaction> tx1Set = new HashSet<Transaction>(Arrays.asList(transaction1));
Set<String> dtcSet = new HashSet<String>(Arrays.asList(DOCUMENT_TYPE_CODE));
message1.getAdditionalInfo().addAll(buildQR(USER_ID, BUSINESS_DOCUMENT, "Title",message1));
message1.setRetrieveIndicator(Boolean.TRUE);
msgDao.update(message1);
RetrieveMessagesForQueryRequestDTO.Builder queryDTOBuilder = new RetrieveMessagesForQueryRequestDTO.Builder()
.setReceiverPartyIds(receiverSet)
.setSenderPartyIds(senderSet)
.setTransactions(tx1Set)
.setDocumentTypeCodes(dtcSet)
.setRetrievedInd(true)
.setStartDate(startDate)
.setEndDate(endDate)
.setCorrelationId(CORRELATION_ID)
.setMaxResult(MAX_RESULTS)
.setFetchParents(false)
.setFetchBinaries(false)
.setIsSenderAlsoReceiver(false)
.setUserId(USER_ID)
.setBusinessDocumentTypes(new HashSet<String>(Arrays.asList(BUSINESS_DOCUMENT)))
.setPaginationFrom(BigDecimal.valueOf(0))
.setPaginationTo(BigDecimal.valueOf(1))
.setSortField(SortFieldTypeCode.TITLE)
.setFilterOutMessagesInError(true);
RetrieveMessagesForQueryRequestDTO queryDTO = queryDTOBuilder.build();
listVO = msgDao.retrieveMessagesJustice(queryDTO);
Assert.assertEquals(1, listVO.getMessages().size());
queryDTOBuilder.setFilterOutMessagesInError(false);
queryDTO = queryDTOBuilder.build();
listVO = msgDao.retrieveMessagesJustice(queryDTO);
Assert.assertEquals(1, listVO.getMessages().size());
}
@Test
public void testRetrieveMessagesJusticeSorting(){
String USER = "gradmin1";
String CORRELATION1 = "Corr1";
String CORRELATION2 = "Corr2";
//START of TEST 1
Set<Long> senderSet = new HashSet<Long>(Arrays.asList(partySender.getId()));
RetrieveMessagesForQueryRequestDTO.Builder queryDTOBuilder = new RetrieveMessagesForQueryRequestDTO.Builder()
.setSenderPartyIds(senderSet)
.setDocumentTypeCodes(new HashSet<String>())
.setRetrievedInd(true)
.setMaxResult(1000)
.setFetchParents(true)
.setFetchBinaries(false)
.setIsSenderAlsoReceiver(false)
.setUserId(USER)
.setBusinessDocumentTypes(new HashSet<String>())
.setPaginationFrom(BigDecimal.valueOf(0))
.setPaginationTo(BigDecimal.valueOf(10))
.setSortField(SortFieldTypeCode.SUBMISSION_DATE)
.setFilterOutMessagesInError(false);
RetrieveMessagesForQueryRequestDTO queryDTO = queryDTOBuilder.build();
MessagesListVO listVO = msgDao.retrieveMessagesJustice(queryDTO);
Assert.assertEquals(0, listVO.getSize().longValue());
//END of TEST 1
//START of TEST 2
Message tempM;
Date issueDate;
//First Conversation
issueDate = new GregorianCalendar(2003, 01, 01).getTime();
tempM = msgDao.create(buildMessage(DOCUMENT_ID+"-FormA-01", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION1, true, issueDate));
tempM.getAdditionalInfo().addAll(buildQR(USER, BUSINESS_DOCUMENT, "Title 1",tempM));
tempM = msgDao.update(tempM);
issueDate = new GregorianCalendar(2013, 01, 01).getTime();
tempM = msgDao.create(buildMessage(DOCUMENT_ID+"-FormB-01", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION1, false, issueDate));
tempM.setIssueDate(issueDate);
tempM.getAdditionalInfo().addAll(buildQR(USER, BUSINESS_DOCUMENT, "Title 1",tempM));
tempM = msgDao.update(tempM);
//Second Conversation
issueDate = new GregorianCalendar(2004, 01, 01).getTime();
tempM = msgDao.create(buildMessage(DOCUMENT_ID+"-FormA-02", STATUS_CODE_RECEIVED, partySender, partyReceiver, partySender, CORRELATION2, true, issueDate));
tempM.getAdditionalInfo().addAll(buildQR(USER, BUSINESS_DOCUMENT, "Title 2",tempM));
tempM = msgDao.update(tempM);
issueDate = new GregorianCalendar(2010, 01, 01).getTime();
tempM = msgDao.create(buildMessage(DOCUMENT_ID+"-FormB-02", STATUS_CODE_RECEIVED, partyReceiver, partySender, partyReceiver, CORRELATION2, false,issueDate));
tempM.getAdditionalInfo().addAll(buildQR(USER, BUSINESS_DOCUMENT, "Title 2",tempM));
tempM = msgDao.update(tempM);
queryDTOBuilder.setRetrievedInd(null);
queryDTO = queryDTOBuilder.build();
listVO = msgDao.retrieveMessagesJustice(queryDTO);
Assert.assertEquals(2, listVO.getSize().longValue());
//END of TEST 2
}
@Test
public void testFindMessagesByCriteria(){
List<Message> list;
Profile p = new Profile();
p.setName("P1");
InterchangeAgreement ica = new InterchangeAgreement();
ica.setProfile(p);
ica = icaDao.create(ica);
p= ica.getProfile();
flush();
JMSEndpoint ep = new JMSEndpoint();
ep.setDestinationJndiName("D");
ep.setIsSupportingReplyTo(false);
ep.setIsActive(true);
ep.setProfile(p);
ep = (JMSEndpoint)epDao.create(ep);
flush();
message1.setAgreement(ica);
msgDao.update(message1);
Message messageExample = new Message();
messageExample.getAccessInfo().setCreationId(CREATION_USER);;
messageExample.setSender(partySender);
messageExample.setIssuer(partySender);
messageExample.setCorrelationId(CORRELATION_ID);
messageExample.setDocumentId(DOCUMENT_ID);
messageExample.setMessageDocumentTypeCode(DOCUMENT_TYPE_CODE);
messageExample.setRetrieveIndicator(Boolean.FALSE);
messageExample.setReceiver(partyReceiver);
messageExample.setTransaction(transaction1);
messageExample.setStatusCode(STATUS_CODE_RECEIVED);
messageExample.setAgreement(ica);
list = msgDao.findMessagesByCriteria(messageExample, startDate, endDate, 0, 20, Arrays.asList(bd1.getId()), null);
Assert.assertEquals(1, list.size());
MessageRouting mr1 = new MessageRouting();
mr1.setMessage(message1);
mr1.setProcessed(Boolean.TRUE);
mr1.setEndpoint(ep);
mrDao.create(mr1);
list = msgDao.findMessagesByCriteria(messageExample, startDate, endDate, 0, 20, Arrays.asList(bd1.getId()), DispatchEnum.YES);
Assert.assertEquals(1, list.size());
MessageRouting mr2 = new MessageRouting();
mr2.setMessage(message1);
mr2.setProcessed(Boolean.FALSE);
mr2.setEndpoint(ep);
mrDao.create(mr2);
list = msgDao.findMessagesByCriteria(messageExample, startDate, endDate, 0, 20, Arrays.asList(bd1.getId()), DispatchEnum.PARTIAL);
Assert.assertEquals(1, list.size());
}
@Test
public void testCountMessagesByCriteria(){
Profile p = new Profile();
p.setName("P1");
InterchangeAgreement ica = new InterchangeAgreement();
ica.setProfile(p);
ica = icaDao.create(ica);
p= ica.getProfile();
flush();
JMSEndpoint ep = new JMSEndpoint();
ep.setDestinationJndiName("D");
ep.setIsSupportingReplyTo(false);
ep.setIsActive(true);
ep.setProfile(p);
ep = (JMSEndpoint)epDao.create(ep);
flush();
message1.setAgreement(ica);
msgDao.update(message1);
Message messageExample = new Message();
messageExample.getAccessInfo().setCreationId(CREATION_USER);;
messageExample.setSender(partySender);
messageExample.setIssuer(partySender);
messageExample.setCorrelationId(CORRELATION_ID);
messageExample.setDocumentId(DOCUMENT_ID);
messageExample.setMessageDocumentTypeCode(DOCUMENT_TYPE_CODE);
messageExample.setRetrieveIndicator(Boolean.FALSE);
messageExample.setReceiver(partyReceiver);
messageExample.setTransaction(transaction1);
messageExample.setStatusCode(STATUS_CODE_RECEIVED);
messageExample.setAgreement(ica);
Assert.assertEquals(1, msgDao.countMessagesByCriteria(messageExample, startDate, endDate, Arrays.asList(bd1.getId()), null));
MessageRouting mr1 = new MessageRouting();
mr1.setMessage(message1);
mr1.setProcessed(Boolean.TRUE);
mr1.setEndpoint(ep);
mrDao.create(mr1);
Assert.assertEquals(1, msgDao.countMessagesByCriteria(messageExample, startDate, endDate, Arrays.asList(bd1.getId()), DispatchEnum.YES));
MessageRouting mr2 = new MessageRouting();
mr2.setMessage(message1);
mr2.setProcessed(Boolean.FALSE);
mr2.setEndpoint(ep);
mrDao.create(mr2);
Assert.assertEquals(1, msgDao.countMessagesByCriteria(messageExample, startDate, endDate, Arrays.asList(bd1.getId()), DispatchEnum.PARTIAL));
}
private Message buildMessage(String docId, String statusCode, Party sender, Party receiver, Party issuer, String corrId, Boolean retIndicator, Date issueDate){
EntityAccessInfo eai = new EntityAccessInfo();
eai.setCreationDate(endDate);
eai.setCreationId(CREATION_USER);
eai.setModificationDate(endDate);
Message m = new Message();
m.setAccessInfo(eai);
m.setDocumentId(docId);
m.setStatusCode(statusCode);
m.setMessageDocumentTypeCode(DOCUMENT_TYPE_CODE);
m.setTransaction(transaction1);
m.setSender(sender);
m.setIssuer(issuer);
m.setReceiver(receiver);
m.setReceptionDate(endDate);
m.setIssueDate(issueDate);
m.setCorrelationId(corrId);
m.setRetrieveIndicator(retIndicator);
return m;
}
private List<QueryResult> buildQR(String user, String bd, String title, Message message){
List<QueryResult> list = new ArrayList<QueryResult>();
QueryResult qr_user = new QueryResult();
qr_user.setKey(DataExtractionTypes.JMS_USER_ID.name());
qr_user.setValue(user);
qr_user.setMessage(message);
qr_user = qrDao.create(qr_user);
list.add(qr_user);
QueryResult qr_bd = new QueryResult();
qr_bd.setKey(DataExtractionTypes.JMS_BUSINESS_DOC_TYPE.name());
qr_bd.setValue(BUSINESS_DOCUMENT);
qr_bd.setMessage(message);
qr_bd = qrDao.create(qr_bd);
list.add(qr_bd);
QueryResult qr_title = new QueryResult();
qr_title.setKey(DataExtractionTypes.JMS_TITLE.name());
qr_title.setValue(title);
qr_title.setMessage(message);
qr_bd = qrDao.create(qr_title);
list.add(qr_title);
return list;
}
}
| [
"cdchiriac@gmail.com"
] | cdchiriac@gmail.com |
e447344720622fd7ee509dea8627c5e8edf629a7 | f1c8c72d5527cce4d5356480a402bc6ffd207e14 | /src/main/java/com/cnaude/purpleirc/IRCListeners/ConnectListener.java | 0aaba1e707d5eedf2f33653faf03c1b7ffa73d89 | [
"BSD-3-Clause"
] | permissive | cnaude/PurpleIRC-forge-1.12.2 | 4faa8fe7c3854f4f5ade35f0fcf79a517ed8e01d | 5969add7e7db4953b8e9ce10d8122573172a8333 | refs/heads/master | 2022-08-15T22:50:55.810128 | 2020-05-24T17:16:56 | 2020-05-24T17:16:56 | 124,798,575 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,475 | java | /*
* Copyright (C) 2014 cnaude
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.cnaude.purpleirc.IRCListeners;
import com.cnaude.purpleirc.PurpleBot;
import com.cnaude.purpleirc.PurpleIRC;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.ConnectEvent;
/**
*
* @author cnaude
*/
public class ConnectListener extends ListenerAdapter {
PurpleIRC plugin;
PurpleBot ircBot;
/**
*
* @param plugin
* @param ircBot
*/
public ConnectListener(PurpleIRC plugin, PurpleBot ircBot) {
this.plugin = plugin;
this.ircBot = ircBot;
}
/**
*
* @param event
*/
@Override
public void onConnect(ConnectEvent event) {
plugin.logDebug("ON CONNECT 0");
PircBotX bot = event.getBot();
plugin.logDebug("ON CONNECT 1");
if (bot.getUserBot().getNick().isEmpty()) {
plugin.logDebug("ON CONNECT 2");
plugin.logDebug("Connected but bot nick is blank!");
plugin.logDebug("ON CONNECT 3");
} else {
plugin.logDebug("ON CONNECT 4");
ircBot.broadcastIRCConnect(ircBot.botNick);
plugin.logDebug("ON CONNECT 5");
if (ircBot.sendRawMessageOnConnect) {
plugin.logDebug("ON CONNECT 6");
plugin.logDebug("Sending raw message to server");
plugin.logDebug("ON CONNECT 7");
ircBot.asyncRawlineNow(ircBot.rawMessage);
plugin.logDebug("ON CONNECT 8");
}
}
plugin.logDebug("ON CONNECT 9");
ircBot.setConnected(true);
plugin.logDebug("ON CONNECT 10");
ircBot.autoJoinChannels();
plugin.logDebug("ON CONNECT 11");
}
}
| [
"chris.naude.0@gmail.com"
] | chris.naude.0@gmail.com |
a17aa141cff01d7e05574a26ce1b0e768ca3af47 | 4291cc6e7d856e779e48418d9f7aedea06cabb58 | /src/main/java/info/kmdb/config/AsyncConfiguration.java | f72081e85b55508d4cba1fe257c96adf8d1573d9 | [] | no_license | kaloneh/jhipster-ionic | 77c21fb3586e5f3a916ff18db69d400b48d62285 | ccd8b8166af981ac5b7544bebf90473bc5685c8a | refs/heads/master | 2022-12-21T21:24:41.589045 | 2021-01-06T01:55:51 | 2021-01-06T01:55:51 | 205,726,476 | 0 | 0 | null | 2022-12-16T05:03:20 | 2019-09-01T20:04:47 | Java | UTF-8 | Java | false | false | 1,993 | java | package info.kmdb.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
| [
"jhipster-bot@jhipster.tech"
] | jhipster-bot@jhipster.tech |
f2c51c8466b062f66e278fcf960130625a3f14e4 | edc6693ada84d2392bf6c1ac24097ab8b5a9d040 | /checker-framework/checkers/jdk/nullness/src/java/lang/Float.java | aaf0257e82d332beaf89832bb0ccc097e4cc115a | [] | no_license | he-actlab/r2.code | e544a60ba6eb90a94023d09843574b23725a5c14 | b212d1e8fe90b87b5529bf01eb142d7b54c7325b | refs/heads/master | 2023-03-30T10:48:43.476138 | 2016-02-15T15:58:54 | 2016-02-15T15:58:54 | 354,711,273 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,917 | java | package java.lang;
import checkers.nullness.quals.*;
@checkers.quals.DefaultQualifier("checkers.nullness.quals.NonNull")
public final class Float extends Number implements Comparable<Float> {
private static final long serialVersionUID = 0;
public final static float POSITIVE_INFINITY = 0;
public final static float NEGATIVE_INFINITY = 0;
public final static float NaN = 0;
public final static float MAX_VALUE = 0;
public final static float MIN_NORMAL = 0;
public final static float MIN_VALUE = 0;
public final static int MAX_EXPONENT = 0;
public final static int MIN_EXPONENT = 0;
public final static int SIZE = 32;
public final static Class<Float> TYPE;
public static String toString(float a1) { throw new RuntimeException("skeleton method"); }
public static String toHexString(float a1) { throw new RuntimeException("skeleton method"); }
public static Float valueOf(String a1) throws NumberFormatException { throw new RuntimeException("skeleton method"); }
public static Float valueOf(float a1) { throw new RuntimeException("skeleton method"); }
public static float parseFloat(String a1) throws NumberFormatException { throw new RuntimeException("skeleton method"); }
public static boolean isNaN(float a1) { throw new RuntimeException("skeleton method"); }
public static boolean isInfinite(float a1) { throw new RuntimeException("skeleton method"); }
public Float(float a1) { throw new RuntimeException("skeleton method"); }
public Float(double a1) { throw new RuntimeException("skeleton method"); }
public Float(String a1) throws NumberFormatException { throw new RuntimeException("skeleton method"); }
public boolean isNaN() { throw new RuntimeException("skeleton method"); }
public boolean isInfinite() { throw new RuntimeException("skeleton method"); }
public String toString() { throw new RuntimeException("skeleton method"); }
public byte byteValue() { throw new RuntimeException("skeleton method"); }
public short shortValue() { throw new RuntimeException("skeleton method"); }
public int intValue() { throw new RuntimeException("skeleton method"); }
public long longValue() { throw new RuntimeException("skeleton method"); }
public float floatValue() { throw new RuntimeException("skeleton method"); }
public double doubleValue() { throw new RuntimeException("skeleton method"); }
public int hashCode() { throw new RuntimeException("skeleton method"); }
public boolean equals(@Nullable Object a1) { throw new RuntimeException("skeleton method"); }
public static int floatToIntBits(float a1) { throw new RuntimeException("skeleton method"); }
public int compareTo(Float a1) { throw new RuntimeException("skeleton method"); }
public static int compare(float a1, float a2) { throw new RuntimeException("skeleton method"); }
public static native float intBitsToFloat(int a1);
public static native int floatToRawIntBits(float a1);
}
| [
"jspark@gatech.edu"
] | jspark@gatech.edu |
d6440fdba9df247213482774e46a08573cd27fe5 | 96aca7618ec96a483f1dc9cc2a358779e4d4861d | /Birll-Academy-master/ProjetoBirl/src/academia/config/AppWebConfiguration.java | 3b1a8bd2caf9d87e5c5aa255d4a2d1c7776c19c4 | [] | no_license | JoaoAraujo98/Birll-Academy | db89dc2b99dc9c57fbd622b3f5d00683ad1e7877 | 02b3d9e3fc42f0cbe1fbd5528140ed9b5e96128a | refs/heads/master | 2021-09-07T22:53:40.010965 | 2018-03-02T13:51:50 | 2018-03-02T13:51:50 | 117,880,463 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package academia.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import academia.controller.HomeController;
@EnableWebMvc
@ComponentScan (basePackageClasses={HomeController.class})
public class AppWebConfiguration {
@Bean
public InternalResourceViewResolver internalResourceViewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
c494e9bf9489e8963c5d2cebb0e7d312f17b60e0 | f303007792d221c1264700632818f805f4cde852 | /String_Assignment/src/Reverse_sentence.java | cbc543a1a6cbb5ddffa236f2d2a0b179c0b99dd9 | [] | no_license | yeshpreet/Eclipse-Workspace | 4085157821bdd55693f413bcb74bc8d963688e80 | 5bb0e446dcaf8d6b674226219b6552a43bfb38e3 | refs/heads/master | 2021-07-09T15:48:25.969169 | 2019-08-29T04:25:48 | 2019-08-29T04:25:48 | 205,078,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 467 | java | import java.util.Scanner;
public class Reverse_sentence {
public static void main(String[] args) {
Scanner scn= new Scanner(System.in);
System.out.println("Enter any String: ");
String str= scn.nextLine();
String[] words = str.split(" ");
String Revstr="";
for (int i = words.length-1; i >= 0; i--)
{
Revstr = Revstr + words[i] + " ";
}
System.out.println("You Entered String: "+str);
System.out.println("Reversed String is: "+Revstr);
}
}
| [
"yeshpreet@gmail.com"
] | yeshpreet@gmail.com |
a8bdf5ca3903f751d4a8000a0de3cea9ef118519 | 95cfe2239c8fce0cec91d76e0a82f59a9efc4cb8 | /sourceCode/CommonsLangMutGenerator/java.lang.StringIndexOutOfBoundsException/15761_lang/mut/StringUtils.java | 9ce9ad11d6869f893738fd5db3f5934de3cc2b88 | [] | no_license | Djack1010/BUG_DB | 28eff24aece45ed379b49893176383d9260501e7 | a4b6e4460a664ce64a474bfd7da635aa7ff62041 | refs/heads/master | 2022-04-09T01:58:29.736794 | 2020-03-13T14:15:11 | 2020-03-13T14:15:11 | 141,260,015 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 319,237 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* <p>Operations on {@link java.lang.String} that are
* {@code null} safe.</p>
*
* <ul>
* <li><b>IsEmpty/IsBlank</b>
* - checks if a String contains text</li>
* <li><b>Trim/Strip</b>
* - removes leading and trailing whitespace</li>
* <li><b>Equals</b>
* - compares two strings null-safe</li>
* <li><b>startsWith</b>
* - check if a String starts with a prefix null-safe</li>
* <li><b>endsWith</b>
* - check if a String ends with a suffix null-safe</li>
* <li><b>IndexOf/LastIndexOf/Contains</b>
* - null-safe index-of checks
* <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b>
* - index-of any of a set of Strings</li>
* <li><b>ContainsOnly/ContainsNone/ContainsAny</b>
* - does String contains only/none/any of these characters</li>
* <li><b>Substring/Left/Right/Mid</b>
* - null-safe substring extractions</li>
* <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b>
* - substring extraction relative to other strings</li>
* <li><b>Split/Join</b>
* - splits a String into an array of substrings and vice versa</li>
* <li><b>Remove/Delete</b>
* - removes part of a String</li>
* <li><b>Replace/Overlay</b>
* - Searches a String and replaces one String with another</li>
* <li><b>Chomp/Chop</b>
* - removes the last part of a String</li>
* <li><b>AppendIfMissing</b>
* - appends a suffix to the end of the String if not present</li>
* <li><b>PrependIfMissing</b>
* - prepends a prefix to the start of the String if not present</li>
* <li><b>LeftPad/RightPad/Center/Repeat</b>
* - pads a String</li>
* <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b>
* - changes the case of a String</li>
* <li><b>CountMatches</b>
* - counts the number of occurrences of one String in another</li>
* <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b>
* - checks the characters in a String</li>
* <li><b>DefaultString</b>
* - protects against a null input String</li>
* <li><b>Reverse/ReverseDelimited</b>
* - reverses a String</li>
* <li><b>Abbreviate</b>
* - abbreviates a string using ellipsis</li>
* <li><b>Difference</b>
* - compares Strings and reports on their differences</li>
* <li><b>LevenshteinDistance</b>
* - the number of changes needed to change one String into another</li>
* </ul>
*
* <p>The {@code StringUtils} class defines certain words related to
* String handling.</p>
*
* <ul>
* <li>null - {@code null}</li>
* <li>empty - a zero-length string ({@code ""})</li>
* <li>space - the space character ({@code ' '}, char 32)</li>
* <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li>
* <li>trim - the characters <= 32 as in {@link String#trim()}</li>
* </ul>
*
* <p>{@code StringUtils} handles {@code null} input Strings quietly.
* That is to say that a {@code null} input will return {@code null}.
* Where a {@code boolean} or {@code int} is being returned
* details vary by method.</p>
*
* <p>A side effect of the {@code null} handling is that a
* {@code NullPointerException} should be considered a bug in
* {@code StringUtils}.</p>
*
* <p>Methods in this class give sample code to explain their operation.
* The symbol {@code *} is used to indicate any input including {@code null}.</p>
*
* <p>#ThreadSafe#</p>
* @see java.lang.String
* @since 1.0
* @version $Id: StringUtils.java 1648067 2014-12-27 16:45:42Z britter $
*/
//@Immutable
public class StringUtils {
// Performance testing notes (JDK 1.4, Jul03, scolebourne)
// Whitespace:
// Character.isWhitespace() is faster than WHITESPACE.indexOf()
// where WHITESPACE is a string of all whitespace characters
//
// Character access:
// String.charAt(n) versus toCharArray(), then array[n]
// String.charAt(n) is about 15% worse for a 10K string
// They are about equal for a length 50 string
// String.charAt(n) is about 4 times better for a length 3 string
// String.charAt(n) is best bet overall
//
// Append:
// String.concat about twice as fast as StringBuffer.append
// (not sure who tested this)
/**
* A String for a space character.
*
* @since 3.2
*/
public static final String SPACE = " ";
/**
* The empty String {@code ""}.
* @since 2.0
*/
public static final String EMPTY = "";
/**
* A String for linefeed LF ("\n").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String LF = "\n";
/**
* A String for carriage return CR ("\r").
*
* @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 3.2
*/
public static final String CR = "\r";
/**
* Represents a failed index search.
* @since 2.1
*/
public static final int INDEX_NOT_FOUND = -1;
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>{@code StringUtils} instances should NOT be constructed in
* standard programming. Instead, the class should be used as
* {@code StringUtils.trim(" foo ");}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public StringUtils() {
super();
}
// Empty checks
//-----------------------------------------------------------------------
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
* @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is not empty ("") and not null.</p>
*
* <pre>
* StringUtils.isNotEmpty(null) = false
* StringUtils.isNotEmpty("") = false
* StringUtils.isNotEmpty(" ") = true
* StringUtils.isNotEmpty("bob") = true
* StringUtils.isNotEmpty(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is not empty and not null
* @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
*/
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
/**
* <p>Checks if any one of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isAnyEmpty(null) = true
* StringUtils.isAnyEmpty(null, "foo") = true
* StringUtils.isAnyEmpty("", "bar") = true
* StringUtils.isAnyEmpty("bob", "") = true
* StringUtils.isAnyEmpty(" bob ", null) = true
* StringUtils.isAnyEmpty(" ", "bar") = false
* StringUtils.isAnyEmpty("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isAnyEmpty(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css){
if (isEmpty(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if none of the CharSequences are empty ("") or null.</p>
*
* <pre>
* StringUtils.isNoneEmpty(null) = false
* StringUtils.isNoneEmpty(null, "foo") = false
* StringUtils.isNoneEmpty("", "bar") = false
* StringUtils.isNoneEmpty("bob", "") = false
* StringUtils.isNoneEmpty(" bob ", null) = false
* StringUtils.isNoneEmpty(" ", "bar") = true
* StringUtils.isNoneEmpty("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are empty or null
* @since 3.2
*/
public static boolean isNoneEmpty(final CharSequence... css) {
return !isAnyEmpty(css);
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
/**
* <p>Checks if any one of the CharSequences are blank ("") or null and not whitespace only..</p>
*
* <pre>
* StringUtils.isAnyBlank(null) = true
* StringUtils.isAnyBlank(null, "foo") = true
* StringUtils.isAnyBlank(null, null) = true
* StringUtils.isAnyBlank("", "bar") = true
* StringUtils.isAnyBlank("bob", "") = true
* StringUtils.isAnyBlank(" bob ", null) = true
* StringUtils.isAnyBlank(" ", "bar") = true
* StringUtils.isAnyBlank("foo", "bar") = false
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if any of the CharSequences are blank or null or whitespace only
* @since 3.2
*/
public static boolean isAnyBlank(final CharSequence... css) {
if (ArrayUtils.isEmpty(css)) {
return true;
}
for (final CharSequence cs : css){
if (isBlank(cs)) {
return true;
}
}
return false;
}
/**
* <p>Checks if none of the CharSequences are blank ("") or null and whitespace only..</p>
*
* <pre>
* StringUtils.isNoneBlank(null) = false
* StringUtils.isNoneBlank(null, "foo") = false
* StringUtils.isNoneBlank(null, null) = false
* StringUtils.isNoneBlank("", "bar") = false
* StringUtils.isNoneBlank("bob", "") = false
* StringUtils.isNoneBlank(" bob ", null) = false
* StringUtils.isNoneBlank(" ", "bar") = false
* StringUtils.isNoneBlank("foo", "bar") = true
* </pre>
*
* @param css the CharSequences to check, may be null or empty
* @return {@code true} if none of the CharSequences are blank or null or whitespace only
* @since 3.2
*/
public static boolean isNoneBlank(final CharSequence... css) {
return !isAnyBlank(css);
}
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String, handling {@code null} by returning
* {@code null}.</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #strip(String)}.</p>
*
* <p>To trim your choice of characters, use the
* {@link #strip(String, String)} methods.</p>
*
* <pre>
* StringUtils.trim(null) = null
* StringUtils.trim("") = ""
* StringUtils.trim(" ") = ""
* StringUtils.trim("abc") = "abc"
* StringUtils.trim(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed string, {@code null} if null String input
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToNull(String)}.</p>
*
* <pre>
* StringUtils.trimToNull(null) = null
* StringUtils.trimToNull("") = null
* StringUtils.trimToNull(" ") = null
* StringUtils.trimToNull("abc") = "abc"
* StringUtils.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String,
* {@code null} if only chars <= 32, empty or null String input
* @since 2.0
*/
public static String trimToNull(final String str) {
final String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim or if it is {@code null}.
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.
* To strip whitespace use {@link #stripToEmpty(String)}.</p>
*
* <pre>
* StringUtils.trimToEmpty(null) = ""
* StringUtils.trimToEmpty("") = ""
* StringUtils.trimToEmpty(" ") = ""
* StringUtils.trimToEmpty("abc") = "abc"
* StringUtils.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str the String to be trimmed, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String trimToEmpty(final String str) {
return str == null ? EMPTY : str.trim();
}
// Stripping
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of a String.</p>
*
* <p>This is similar to {@link #trim(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.strip(null) = null
* StringUtils.strip("") = ""
* StringUtils.strip(" ") = ""
* StringUtils.strip("abc") = "abc"
* StringUtils.strip(" abc") = "abc"
* StringUtils.strip("abc ") = "abc"
* StringUtils.strip(" abc ") = "abc"
* StringUtils.strip(" ab c ") = "ab c"
* </pre>
*
* @param str the String to remove whitespace from, may be null
* @return the stripped String, {@code null} if null String input
*/
public static String strip(final String str) {
return strip(str, null);
}
/**
* <p>Strips whitespace from the start and end of a String returning
* {@code null} if the String is empty ("") after the strip.</p>
*
* <p>This is similar to {@link #trimToNull(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToNull(null) = null
* StringUtils.stripToNull("") = null
* StringUtils.stripToNull(" ") = null
* StringUtils.stripToNull("abc") = "abc"
* StringUtils.stripToNull(" abc") = "abc"
* StringUtils.stripToNull("abc ") = "abc"
* StringUtils.stripToNull(" abc ") = "abc"
* StringUtils.stripToNull(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the stripped String,
* {@code null} if whitespace, empty or null String input
* @since 2.0
*/
public static String stripToNull(String str) {
if (str == null) {
return null;
}
str = strip(str, null);
return str.isEmpty() ? null : str;
}
/**
* <p>Strips whitespace from the start and end of a String returning
* an empty String if {@code null} input.</p>
*
* <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripToEmpty(null) = ""
* StringUtils.stripToEmpty("") = ""
* StringUtils.stripToEmpty(" ") = ""
* StringUtils.stripToEmpty("abc") = "abc"
* StringUtils.stripToEmpty(" abc") = "abc"
* StringUtils.stripToEmpty("abc ") = "abc"
* StringUtils.stripToEmpty(" abc ") = "abc"
* StringUtils.stripToEmpty(" ab c ") = "ab c"
* </pre>
*
* @param str the String to be stripped, may be null
* @return the trimmed String, or an empty String if {@code null} input
* @since 2.0
*/
public static String stripToEmpty(final String str) {
return str == null ? EMPTY : strip(str, null);
}
/**
* <p>Strips any of a set of characters from the start and end of a String.
* This is similar to {@link String#trim()} but allows the characters
* to be stripped to be controlled.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.
* Alternatively use {@link #strip(String)}.</p>
*
* <pre>
* StringUtils.strip(null, *) = null
* StringUtils.strip("", *) = ""
* StringUtils.strip("abc", null) = "abc"
* StringUtils.strip(" abc", null) = "abc"
* StringUtils.strip("abc ", null) = "abc"
* StringUtils.strip(" abc ", null) = "abc"
* StringUtils.strip(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String strip(String str, final String stripChars) {
if (isEmpty(str)) {
return str;
}
str = stripStart(str, stripChars);
return stripEnd(str, stripChars);
}
/**
* <p>Strips any of a set of characters from the start of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripStart(null, *) = null
* StringUtils.stripStart("", *) = ""
* StringUtils.stripStart("abc", "") = "abc"
* StringUtils.stripStart("abc", null) = "abc"
* StringUtils.stripStart(" abc", null) = "abc"
* StringUtils.stripStart("abc ", null) = "abc "
* StringUtils.stripStart(" abc ", null) = "abc "
* StringUtils.stripStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripStart(final String str, final String stripChars) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
int start = 0;
if (stripChars == null) {
while (start != strLen && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) {
start++;
}
}
return str.substring(start);
}
/**
* <p>Strips any of a set of characters from the end of a String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* An empty string ("") input returns the empty string.</p>
*
* <p>If the stripChars String is {@code null}, whitespace is
* stripped as defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripEnd(null, *) = null
* StringUtils.stripEnd("", *) = ""
* StringUtils.stripEnd("abc", "") = "abc"
* StringUtils.stripEnd("abc", null) = "abc"
* StringUtils.stripEnd(" abc", null) = " abc"
* StringUtils.stripEnd("abc ", null) = "abc"
* StringUtils.stripEnd(" abc ", null) = " abc"
* StringUtils.stripEnd(" abcyx", "xyz") = " abc"
* StringUtils.stripEnd("120.00", ".0") = "12"
* </pre>
*
* @param str the String to remove characters from, may be null
* @param stripChars the set of characters to remove, null treated as whitespace
* @return the stripped String, {@code null} if null String input
*/
public static String stripEnd(final String str, final String stripChars) {
int end;
if (str == null || (end = str.length()) == 0) {
return str;
}
if (stripChars == null) {
while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.isEmpty()) {
return str;
} else {
while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) {
end--;
}
}
return str.substring(0, end);
}
// StripAll
//-----------------------------------------------------------------------
/**
* <p>Strips whitespace from the start and end of every String in an array.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.</p>
*
* <pre>
* StringUtils.stripAll(null) = null
* StringUtils.stripAll([]) = []
* StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null]) = ["abc", null]
* </pre>
*
* @param strs the array to remove whitespace from, may be null
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String... strs) {
return stripAll(strs, null);
}
/**
* <p>Strips any of a set of characters from the start and end of every
* String in an array.</p>
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>A new array is returned each time, except for length zero.
* A {@code null} array will return {@code null}.
* An empty array will return itself.
* A {@code null} array entry will be ignored.
* A {@code null} stripChars will strip whitespace as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.stripAll(null, *) = null
* StringUtils.stripAll([], *) = []
* StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"]
* StringUtils.stripAll(["abc ", null], null) = ["abc", null]
* StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null]
* StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null]
* </pre>
*
* @param strs the array to remove characters from, may be null
* @param stripChars the characters to remove, null treated as whitespace
* @return the stripped Strings, {@code null} if null array input
*/
public static String[] stripAll(final String[] strs, final String stripChars) {
int strsLen;
if (strs == null || (strsLen = strs.length) == 0) {
return strs;
}
final String[] newArr = new String[strsLen];
for (int i = 0; i < strsLen; i++) {
newArr[i] = strip(strs[i], stripChars);
}
return newArr;
}
/**
* <p>Removes diacritics (~= accents) from a string. The case will not be altered.</p>
* <p>For instance, 'à' will be replaced by 'a'.</p>
* <p>Note that ligatures will be left as is.</p>
*
* <pre>
* StringUtils.stripAccents(null) = null
* StringUtils.stripAccents("") = ""
* StringUtils.stripAccents("control") = "control"
* StringUtils.stripAccents("éclair") = "eclair"
* </pre>
*
* @param input String to be stripped
* @return input text with diacritics removed
*
* @since 3.0
*/
// See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907).
public static String stripAccents(final String input) {
if(input == null) {
return null;
}
final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$
final String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD);
// Note that this doesn't correctly remove ligatures...
return pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$
}
// Equals
//-----------------------------------------------------------------------
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @see Object#equals(Object)
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
*/
public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
}
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters, ignoring case.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered equal. Comparison is case insensitive.</p>
*
* <pre>
* StringUtils.equalsIgnoreCase(null, null) = true
* StringUtils.equalsIgnoreCase(null, "abc") = false
* StringUtils.equalsIgnoreCase("abc", null) = false
* StringUtils.equalsIgnoreCase("abc", "abc") = true
* StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param str1 the first CharSequence, may be null
* @param str2 the second CharSequence, may be null
* @return {@code true} if the CharSequence are equal, case insensitive, or
* both {@code null}
* @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) {
if (str1 == null || str2 == null) {
return str1 == str2;
} else if (str1 == str2) {
return true;
} else if (str1.length() != str2.length()) {
return false;
} else {
return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length());
}
}
// IndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(int, int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf("", *) = -1
* StringUtils.indexOf("aabaabaa", 'a') = 0
* StringUtils.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return the first index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int)
*/
public static int indexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0);
}
/**
* <p>Finds the first index within a CharSequence from a start position,
* handling {@code null}.
* This method uses {@link String#indexOf(int, int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code (INDEX_NOT_FOUND) -1}.
* A negative start position is treated as zero.
* A start position greater than the string length returns {@code -1}.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf("", *, *) = -1
* StringUtils.indexOf("aabaabaa", 'b', 0) = 2
* StringUtils.indexOf("aabaabaa", 'b', 3) = 5
* StringUtils.indexOf("aabaabaa", 'b', 9) = -1
* StringUtils.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position, negative treated as zero
* @return the first index of the search character (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int)
*/
public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchChar, startPos);
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOf(null, *) = -1
* StringUtils.indexOf(*, null) = -1
* StringUtils.indexOf("", "") = 0
* StringUtils.indexOf("", *) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a") = 0
* StringUtils.indexOf("aabaabaa", "b") = 2
* StringUtils.indexOf("aabaabaa", "ab") = 1
* StringUtils.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0);
}
/**
* <p>Finds the first index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOf(null, *, *) = -1
* StringUtils.indexOf(*, null, *) = -1
* StringUtils.indexOf("", "", 0) = 0
* StringUtils.indexOf("", *, 0) = -1 (except when * = "")
* StringUtils.indexOf("aabaabaa", "a", 0) = 0
* StringUtils.indexOf("aabaabaa", "b", 0) = 2
* StringUtils.indexOf("aabaabaa", "ab", 0) = 1
* StringUtils.indexOf("aabaabaa", "b", 3) = 5
* StringUtils.indexOf("aabaabaa", "b", 9) = -1
* StringUtils.indexOf("aabaabaa", "b", -1) = 2
* StringUtils.indexOf("aabaabaa", "", 2) = 2
* StringUtils.indexOf("abc", "", 9) = 3
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int)
*/
public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.indexOf(seq, searchSeq, startPos);
}
/**
* <p>Finds the n-th index within a CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.ordinalIndexOf(null, *, *) = -1
* StringUtils.ordinalIndexOf(*, null, *) = -1
* StringUtils.ordinalIndexOf("", "", *) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2
* StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
* StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
* StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0
* StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0
* </pre>
*
* <p>Note that 'head(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(0, lastOrdinalIndexOf(str, "\n", n))
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.1
* @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int)
*/
public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, false);
}
/**
* <p>Finds the n-th index within a String, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th {@code searchStr} to find
* @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf()
* @return the n-th index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
*/
// Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int)
private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) {
if (str == null || searchStr == null || ordinal <= 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return lastIndex ? str.length() : 0;
}
int found = 0;
int index = lastIndex ? str.length() : INDEX_NOT_FOUND;
do {
if (lastIndex) {
index = CharSequenceUtils.lastIndexOf(str, searchStr, index - searchStr.length());
} else {
index = CharSequenceUtils.indexOf(str, searchStr, index + searchStr.length());
}
if (index < 0) {
return index;
}
found++;
} while (found < ordinal);
return index;
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *) = -1
* StringUtils.indexOfIgnoreCase(*, null) = -1
* StringUtils.indexOfIgnoreCase("", "") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "a") = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "b") = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/**
* <p>Case in-sensitive find of the first index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position is treated as zero.
* An empty ("") search CharSequence always matches.
* A start position greater than the string length only matches
* an empty search CharSequence.</p>
*
* <pre>
* StringUtils.indexOfIgnoreCase(null, *, *) = -1
* StringUtils.indexOfIgnoreCase(*, null, *) = -1
* StringUtils.indexOfIgnoreCase("", "", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3) = 5
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9) = -1
* StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
* StringUtils.indexOfIgnoreCase("aabaabaa", "", 2) = 2
* StringUtils.indexOfIgnoreCase("abc", "", 9) = 3
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the first index of the search CharSequence (always ≥ startPos),
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos < 0) {
startPos = 0;
}
final int endLimit = str.length() - searchStr.length() + 1;
if (startPos > endLimit) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i < endLimit; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// LastIndexOf
//-----------------------------------------------------------------------
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf("", *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a') = 7
* StringUtils.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return the last index of the search character,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int)
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length());
}
/**
* <p>Finds the last index within a CharSequence from a start position,
* handling {@code null}.
* This method uses {@link String#lastIndexOf(int, int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf("", *, *) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @param startPos the start position
* @return the last index of the search character (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int)
*/
public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) {
if (isEmpty(seq)) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos);
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOf(null, *) = -1
* StringUtils.lastIndexOf(*, null) = -1
* StringUtils.lastIndexOf("", "") = 0
* StringUtils.lastIndexOf("aabaabaa", "a") = 7
* StringUtils.lastIndexOf("aabaabaa", "b") = 5
* StringUtils.lastIndexOf("aabaabaa", "ab") = 4
* StringUtils.lastIndexOf("aabaabaa", "") = 8
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return the last index of the search String,
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length());
}
/**
* <p>Finds the n-th last index within a String, handling {@code null}.
* This method uses {@link String#lastIndexOf(String)}.</p>
*
* <p>A {@code null} String will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastOrdinalIndexOf(null, *, *) = -1
* StringUtils.lastOrdinalIndexOf(*, null, *) = -1
* StringUtils.lastOrdinalIndexOf("", "", *) = 0
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7
* StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5
* StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
* StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8
* StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8
* </pre>
*
* <p>Note that 'tail(CharSequence str, int n)' may be implemented as: </p>
*
* <pre>
* str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param ordinal the n-th last {@code searchStr} to find
* @return the n-th last index of the search CharSequence,
* {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int)
*/
public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) {
return ordinalIndexOf(str, searchStr, ordinal, true);
}
/**
* <p>Finds the last index within a CharSequence, handling {@code null}.
* This method uses {@link String#lastIndexOf(String, int)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOf(null, *, *) = -1
* StringUtils.lastIndexOf(*, null, *) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 1) = -1
* StringUtils.lastIndexOf("aabaabaa", "b", 2) = 2
* StringUtils.lastIndexOf("aabaabaa", "ba", 2) = -1
* StringUtils.lastIndexOf("aabaabaa", "ba", 2) = 2
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @param startPos the start position, negative treated as zero
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int)
*/
public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) {
if (seq == null || searchSeq == null) {
return INDEX_NOT_FOUND;
}
return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos);
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.</p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A") = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B") = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return the first index of the search CharSequence,
* -1 if no match or {@code null} string input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
return lastIndexOfIgnoreCase(str, searchStr, str.length());
}
/**
* <p>Case in-sensitive find of the last index within a CharSequence
* from the specified position.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A negative start position returns {@code -1}.
* An empty ("") search CharSequence always matches unless the start position is negative.
* A start position greater than the string length searches the whole string.
* The search starts at the startPos and works backwards; matches starting after the start
* position are ignored.
* </p>
*
* <pre>
* StringUtils.lastIndexOfIgnoreCase(null, *, *) = -1
* StringUtils.lastIndexOfIgnoreCase(*, null, *) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8) = 7
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9) = 5
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0) = 0
* StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @param startPos the start position
* @return the last index of the search CharSequence (always ≤ startPos),
* -1 if no match or {@code null} input
* @since 2.5
* @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int)
*/
public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) {
if (str == null || searchStr == null) {
return INDEX_NOT_FOUND;
}
if (startPos > str.length() - searchStr.length()) {
startPos = str.length() - searchStr.length();
}
if (startPos < 0) {
return INDEX_NOT_FOUND;
}
if (searchStr.length() == 0) {
return startPos;
}
for (int i = startPos; i >= 0; i--) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) {
return i;
}
}
return INDEX_NOT_FOUND;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Checks if CharSequence contains a search character, handling {@code null}.
* This method uses {@link String#indexOf(int)} if possible.</p>
*
* <p>A {@code null} or empty ("") CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains("", *) = false
* StringUtils.contains("abc", 'a') = true
* StringUtils.contains("abc", 'z') = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChar the character to find
* @return true if the CharSequence contains the search character,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int)
*/
public static boolean contains(final CharSequence seq, final int searchChar) {
if (isEmpty(seq)) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0;
}
/**
* <p>Checks if CharSequence contains a search CharSequence, handling {@code null}.
* This method uses {@link String#indexOf(String)} if possible.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchSeq the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence,
* false if not or {@code null} string input
* @since 2.0
* @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
*/
public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
if (seq == null || searchSeq == null) {
return false;
}
return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
}
/**
* <p>Checks if CharSequence contains a search CharSequence irrespective of case,
* handling {@code null}. Case-insensitivity is defined as by
* {@link String#equalsIgnoreCase(String)}.
*
* <p>A {@code null} CharSequence will return {@code false}.</p>
*
* <pre>
* StringUtils.contains(null, *) = false
* StringUtils.contains(*, null) = false
* StringUtils.contains("", "") = true
* StringUtils.contains("abc", "") = true
* StringUtils.contains("abc", "a") = true
* StringUtils.contains("abc", "z") = false
* StringUtils.contains("abc", "A") = true
* StringUtils.contains("abc", "Z") = false
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStr the CharSequence to find, may be null
* @return true if the CharSequence contains the search CharSequence irrespective of
* case or false if not or {@code null} string input
* @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence)
*/
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) {
if (str == null || searchStr == null) {
return false;
}
final int len = searchStr.length();
final int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
/**
* Check whether the given CharSequence contains any whitespace characters.
* @param seq the CharSequence to check (may be {@code null})
* @return {@code true} if the CharSequence is not empty and
* contains at least 1 whitespace character
* @see java.lang.Character#isWhitespace
* @since 3.0
*/
// From org.springframework.util.StringUtils, under Apache License 2.0
public static boolean containsWhitespace(final CharSequence seq) {
if (isEmpty(seq)) {
return false;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(seq.charAt(i))) {
return true;
}
}
return false;
}
// IndexOfAny chars
//-----------------------------------------------------------------------
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
* StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...)
*/
public static int indexOfAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, "") = -1
* StringUtils.indexOfAny("zzabyycdxx", "za") = 0
* StringUtils.indexOfAny("zzabyycdxx", "by") = 3
* StringUtils.indexOfAny("aba","z") = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String)
*/
public static int indexOfAny(final CharSequence cs, final String searchChars) {
if (isEmpty(cs) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
return indexOfAny(cs, searchChars.toCharArray());
}
// ContainsAny
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains any character in the given
* set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} or zero length search array will return {@code false}.</p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("zzabyycdxx",['z','a']) = true
* StringUtils.containsAny("zzabyycdxx",['b','y']) = true
* StringUtils.containsAny("aba", ['z']) = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the {@code true} if any of the chars are found,
* {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...)
*/
public static boolean containsAny(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
final int csLength = cs.length();
final int searchLength = searchChars.length;
final int csLast = csLength - 1;
final int searchLast = searchLength - 1;
for (int i = 0; i < csLength; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return true;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
/**
* <p>
* Checks if the CharSequence contains any character in the given set of characters.
* </p>
*
* <p>
* A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return
* {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, "") = false
* StringUtils.containsAny("zzabyycdxx", "za") = true
* StringUtils.containsAny("zzabyycdxx", "by") = true
* StringUtils.containsAny("aba","z") = false
* </pre>
*
* @param cs
* the CharSequence to check, may be null
* @param searchChars
* the chars to search for, may be null
* @return the {@code true} if any of the chars are found, {@code false} if no match or null input
* @since 2.4
* @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence)
*/
public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) {
if (searchChars == null) {
return false;
}
return containsAny(cs, CharSequenceUtils.toCharArray(searchChars));
}
/**
* <p>Checks if the CharSequence contains any of the CharSequences in the given array.</p>
*
* <p>
* A {@code null} CharSequence will return {@code false}. A {@code null} or zero
* length search array will return {@code false}.
* </p>
*
* <pre>
* StringUtils.containsAny(null, *) = false
* StringUtils.containsAny("", *) = false
* StringUtils.containsAny(*, null) = false
* StringUtils.containsAny(*, []) = false
* StringUtils.containsAny("abcd", "ab", "cd") = false
* StringUtils.containsAny("abc", "d", "abc") = true
* </pre>
*
*
* @param cs The CharSequence to check, may be null
* @param searchCharSequences The array of CharSequences to search for, may be null
* @return {@code true} if any of the search CharSequences are found, {@code false} otherwise
* @since 3.4
*/
public static boolean containsAny(CharSequence cs, CharSequence... searchCharSequences) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) {
return false;
}
for (CharSequence searchCharSequence : searchCharSequences) {
if (contains(cs, searchCharSequence)) {
return true;
}
}
return false;
}
// IndexOfAnyBut chars
//-----------------------------------------------------------------------
/**
* <p>Searches a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, []) = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
* StringUtils.indexOfAnyBut("aba", new char[] {'z'} ) = 0
* StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} ) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...)
*/
public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
outer:
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
if (searchChars[j + 1] == cs.charAt(i + 1)) {
continue outer;
}
} else {
continue outer;
}
}
}
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Search a CharSequence to find the first index of any
* character not in the given set of characters.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or empty search string will return {@code -1}.</p>
*
* <pre>
* StringUtils.indexOfAnyBut(null, *) = -1
* StringUtils.indexOfAnyBut("", *) = -1
* StringUtils.indexOfAnyBut(*, null) = -1
* StringUtils.indexOfAnyBut(*, "") = -1
* StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtils.indexOfAnyBut("zzabyycdxx", "") = -1
* StringUtils.indexOfAnyBut("aba","ab") = -1
* </pre>
*
* @param seq the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the index of any of the chars, -1 if no match or null input
* @since 2.0
* @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence)
*/
public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) {
if (isEmpty(seq) || isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
final char ch = seq.charAt(i);
final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0;
if (i + 1 < strLen && Character.isHighSurrogate(ch)) {
final char ch2 = seq.charAt(i + 1);
if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) {
return i;
}
} else {
if (!chFound) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
// ContainsOnly
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character array will return {@code false}.
* An empty CharSequence (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", '') = false
* StringUtils.containsOnly("abab", 'abc') = true
* StringUtils.containsOnly("ab1", 'abc') = false
* StringUtils.containsOnly("abz", 'abc') = false
* </pre>
*
* @param cs the String to check, may be null
* @param valid an array of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...)
*/
public static boolean containsOnly(final CharSequence cs, final char... valid) {
// All these pre-checks are to maintain API with an older version
if (valid == null || cs == null) {
return false;
}
if (cs.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND;
}
/**
* <p>Checks if the CharSequence contains only certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code false}.
* A {@code null} valid character String will return {@code false}.
* An empty String (length()=0) always returns {@code true}.</p>
*
* <pre>
* StringUtils.containsOnly(null, *) = false
* StringUtils.containsOnly(*, null) = false
* StringUtils.containsOnly("", *) = true
* StringUtils.containsOnly("ab", "") = false
* StringUtils.containsOnly("abab", "abc") = true
* StringUtils.containsOnly("ab1", "abc") = false
* StringUtils.containsOnly("abz", "abc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param validChars a String of valid chars, may be null
* @return true if it only contains valid chars and is non-null
* @since 2.0
* @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String)
*/
public static boolean containsOnly(final CharSequence cs, final String validChars) {
if (cs == null || validChars == null) {
return false;
}
return containsOnly(cs, validChars.toCharArray());
}
// ContainsNone
//-----------------------------------------------------------------------
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty CharSequence (length()=0) always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", '') = true
* StringUtils.containsNone("abab", 'xyz') = true
* StringUtils.containsNone("ab1", 'xyz') = true
* StringUtils.containsNone("abz", 'xyz') = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars an array of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...)
*/
public static boolean containsNone(final CharSequence cs, final char... searchChars) {
if (cs == null || searchChars == null) {
return true;
}
final int csLen = cs.length();
final int csLast = csLen - 1;
final int searchLen = searchChars.length;
final int searchLast = searchLen - 1;
for (int i = 0; i < csLen; i++) {
final char ch = cs.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (Character.isHighSurrogate(ch)) {
if (j == searchLast) {
// missing low surrogate, fine, like String.indexOf(String)
return false;
}
if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) {
return false;
}
} else {
// ch is in the Basic Multilingual Plane
return false;
}
}
}
}
return true;
}
/**
* <p>Checks that the CharSequence does not contain certain characters.</p>
*
* <p>A {@code null} CharSequence will return {@code true}.
* A {@code null} invalid character array will return {@code true}.
* An empty String ("") always returns true.</p>
*
* <pre>
* StringUtils.containsNone(null, *) = true
* StringUtils.containsNone(*, null) = true
* StringUtils.containsNone("", *) = true
* StringUtils.containsNone("ab", "") = true
* StringUtils.containsNone("abab", "xyz") = true
* StringUtils.containsNone("ab1", "xyz") = true
* StringUtils.containsNone("abz", "xyz") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param invalidChars a String of invalid chars, may be null
* @return true if it contains none of the invalid chars, or is null
* @since 2.0
* @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String)
*/
public static boolean containsNone(final CharSequence cs, final String invalidChars) {
if (cs == null || invalidChars == null) {
return true;
}
return containsNone(cs, invalidChars.toCharArray());
}
// IndexOfAny strings
//-----------------------------------------------------------------------
/**
* <p>Find the first index of any of a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.
* A {@code null} search array entry will be ignored, but a search
* array containing "" will return {@code 0} if {@code str} is not
* null. This method uses {@link String#indexOf(String)} if possible.</p>
*
* <pre>
* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtils.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtils.indexOfAny("", [""]) = 0
* StringUtils.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the first index of any of the searchStrs in str, -1 if no match
* @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...)
*/
public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
final int sz = searchStrs.length;
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (int i = 0; i < sz; i++) {
final CharSequence search = searchStrs[i];
if (search == null) {
continue;
}
tmp = CharSequenceUtils.indexOf(str, search, 0);
if (tmp == INDEX_NOT_FOUND) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret;
}
/**
* <p>Find the latest index of any of a set of potential substrings.</p>
*
* <p>A {@code null} CharSequence will return {@code -1}.
* A {@code null} search array will return {@code -1}.
* A {@code null} or zero length search array entry will be ignored,
* but a search array containing "" will return the length of {@code str}
* if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible</p>
*
* <pre>
* StringUtils.lastIndexOfAny(null, *) = -1
* StringUtils.lastIndexOfAny(*, null) = -1
* StringUtils.lastIndexOfAny(*, []) = -1
* StringUtils.lastIndexOfAny(*, [null]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str the CharSequence to check, may be null
* @param searchStrs the CharSequences to search for, may be null
* @return the last index of any of the CharSequences, -1 if no match
* @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence)
*/
public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) {
if (str == null || searchStrs == null) {
return INDEX_NOT_FOUND;
}
final int sz = searchStrs.length;
int ret = INDEX_NOT_FOUND;
int tmp = 0;
for (int i = 0; i < sz; i++) {
final CharSequence search = searchStrs[i];
if (search == null) {
continue;
}
tmp = CharSequenceUtils.lastIndexOf(str, search, str.length());
if (tmp > ret) {
ret = tmp;
}
}
return ret;
}
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start/end {@code n}
* characters from the end of the String.</p>
*
* <p>The returned substring starts with the character in the {@code start}
* position and ends before the {@code end} position. All position counting is
* zero-based -- i.e., to start at the beginning of the string use
* {@code start = 0}. Negative start and end positions can be used to
* specify offsets relative to the end of the String.</p>
*
* <p>If {@code start} is not strictly to the left of {@code end}, ""
* is returned.</p>
*
* <pre>
* StringUtils.substring(null, *, *) = null
* StringUtils.substring("", * , *) = "";
* StringUtils.substring("abc", 0, 2) = "ab"
* StringUtils.substring("abc", 2, 0) = ""
* StringUtils.substring("abc", 2, 4) = "c"
* StringUtils.substring("abc", 4, 6) = ""
* StringUtils.substring("abc", 2, 2) = ""
* StringUtils.substring("abc", -2, -1) = "b"
* StringUtils.substring("abc", -4, 2) = "ab"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @param end the position to end at (exclusive), negative means
* count back from the end of the String by this many characters
* @return substring from start position to end position,
* {@code null} if null String input
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return EMPTY;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
// Left/Right/Mid
//-----------------------------------------------------------------------
/**
* <p>Gets the leftmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the
* String is {@code null}, the String will be returned without
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.left(null, *) = null
* StringUtils.left(*, -ve) = ""
* StringUtils.left("", *) = ""
* StringUtils.left("abc", 0) = ""
* StringUtils.left("abc", 2) = "ab"
* StringUtils.left("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the leftmost characters from, may be null
* @param len the length of the required String
* @return the leftmost characters, {@code null} if null String input
*/
public static String left(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(0, len);
}
/**
* <p>Gets the rightmost {@code len} characters of a String.</p>
*
* <p>If {@code len} characters are not available, or the String
* is {@code null}, the String will be returned without an
* an exception. An empty String is returned if len is negative.</p>
*
* <pre>
* StringUtils.right(null, *) = null
* StringUtils.right(*, -ve) = ""
* StringUtils.right("", *) = ""
* StringUtils.right("abc", 0) = ""
* StringUtils.right("abc", 2) = "bc"
* StringUtils.right("abc", 4) = "abc"
* </pre>
*
* @param str the String to get the rightmost characters from, may be null
* @param len the length of the required String
* @return the rightmost characters, {@code null} if null String input
*/
public static String right(final String str, final int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY;
}
if (str.length() <= len) {
return str;
}
return str.substring(str.length() - len);
}
/**
* <p>Gets {@code len} characters from the middle of a String.</p>
*
* <p>If {@code len} characters are not available, the remainder
* of the String will be returned without an exception. If the
* String is {@code null}, {@code null} will be returned.
* An empty String is returned if len is negative or exceeds the
* length of {@code str}.</p>
*
* <pre>
* StringUtils.mid(null, *, *) = null
* StringUtils.mid(*, *, -ve) = ""
* StringUtils.mid("", 0, *) = ""
* StringUtils.mid("abc", 0, 2) = "ab"
* StringUtils.mid("abc", 0, 4) = "abc"
* StringUtils.mid("abc", 2, 4) = "c"
* StringUtils.mid("abc", 4, 2) = ""
* StringUtils.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str the String to get the characters from, may be null
* @param pos the position to start from, negative treated as zero
* @param len the length of the required String
* @return the middle characters, {@code null} if null String input
*/
public static String mid(final String str, int pos, final int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= pos + len) {
return str.substring(pos);
}
return str.substring(pos, pos + len);
}
// SubStringAfter/SubStringBefore
//-----------------------------------------------------------------------
/**
* <p>Gets the substring before the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBefore(null, *) = null
* StringUtils.substringBefore("", *) = ""
* StringUtils.substringBefore("abc", "a") = ""
* StringUtils.substringBefore("abcba", "b") = "a"
* StringUtils.substringBefore("abc", "c") = "ab"
* StringUtils.substringBefore("abc", "d") = "abc"
* StringUtils.substringBefore("abc", "") = ""
* StringUtils.substringBefore("abc", null) = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBefore(final String str, final String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.isEmpty()) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the first occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* A {@code null} separator will return the empty string if the
* input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfter(null, *) = null
* StringUtils.substringAfter("", *) = ""
* StringUtils.substringAfter(*, null) = ""
* StringUtils.substringAfter("abc", "a") = "bc"
* StringUtils.substringAfter("abcba", "b") = "cba"
* StringUtils.substringAfter("abc", "c") = ""
* StringUtils.substringAfter("abc", "d") = ""
* StringUtils.substringAfter("abc", "") = "abc"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the first occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
/**
* <p>Gets the substring before the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the input string.</p>
*
* <p>If nothing is found, the string input is returned.</p>
*
* <pre>
* StringUtils.substringBeforeLast(null, *) = null
* StringUtils.substringBeforeLast("", *) = ""
* StringUtils.substringBeforeLast("abcba", "b") = "abc"
* StringUtils.substringBeforeLast("abc", "c") = "ab"
* StringUtils.substringBeforeLast("a", "a") = ""
* StringUtils.substringBeforeLast("a", "z") = "a"
* StringUtils.substringBeforeLast("a", null) = "a"
* StringUtils.substringBeforeLast("a", "") = "a"
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring before the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringBeforeLast(final String str, final String separator) {
if (isEmpty(str) || isEmpty(separator)) {
return str;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
/**
* <p>Gets the substring after the last occurrence of a separator.
* The separator is not returned.</p>
*
* <p>A {@code null} string input will return {@code null}.
* An empty ("") string input will return the empty string.
* An empty or {@code null} separator will return the empty string if
* the input string is not {@code null}.</p>
*
* <p>If nothing is found, the empty string is returned.</p>
*
* <pre>
* StringUtils.substringAfterLast(null, *) = null
* StringUtils.substringAfterLast("", *) = ""
* StringUtils.substringAfterLast(*, "") = ""
* StringUtils.substringAfterLast(*, null) = ""
* StringUtils.substringAfterLast("abc", "a") = "bc"
* StringUtils.substringAfterLast("abcba", "b") = "a"
* StringUtils.substringAfterLast("abc", "c") = ""
* StringUtils.substringAfterLast("a", "a") = ""
* StringUtils.substringAfterLast("a", "z") = ""
* </pre>
*
* @param str the String to get a substring from, may be null
* @param separator the String to search for, may be null
* @return the substring after the last occurrence of the separator,
* {@code null} if null String input
* @since 2.0
*/
public static String substringAfterLast(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (isEmpty(separator)) {
return EMPTY;
}
final int pos = str.lastIndexOf(separator);
if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
// Substring between
//-----------------------------------------------------------------------
/**
* <p>Gets the String that is nested in between two instances of the
* same String.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} tag returns {@code null}.</p>
*
* <pre>
* StringUtils.substringBetween(null, *) = null
* StringUtils.substringBetween("", "") = ""
* StringUtils.substringBetween("", "tag") = null
* StringUtils.substringBetween("tagabctag", null) = null
* StringUtils.substringBetween("tagabctag", "") = ""
* StringUtils.substringBetween("tagabctag", "tag") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param tag the String before and after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String tag) {
return substringBetween(str, tag, tag);
}
/**
* <p>Gets the String that is nested in between two Strings.
* Only the first match is returned.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open and close returns an empty string.</p>
*
* <pre>
* StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
* StringUtils.substringBetween(null, *, *) = null
* StringUtils.substringBetween(*, null, *) = null
* StringUtils.substringBetween(*, *, null) = null
* StringUtils.substringBetween("", "", "") = ""
* StringUtils.substringBetween("", "", "]") = null
* StringUtils.substringBetween("", "[", "]") = null
* StringUtils.substringBetween("yabcz", "", "") = ""
* StringUtils.substringBetween("yabcz", "y", "z") = "abc"
* StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
*
* @param str the String containing the substring, may be null
* @param open the String before the substring, may be null
* @param close the String after the substring, may be null
* @return the substring, {@code null} if no match
* @since 2.0
*/
public static String substringBetween(final String str, final String open, final String close) {
if (str == null || open == null || close == null) {
return null;
}
final int start = str.indexOf(open);
if (start != INDEX_NOT_FOUND) {
final int end = str.indexOf(close, start + open.length());
if (end != INDEX_NOT_FOUND) {
return str.substring(start + open.length(), end);
}
}
return null;
}
/**
* <p>Searches a String for substrings delimited by a start and end tag,
* returning all matching substrings in an array.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} open/close returns {@code null} (no match).
* An empty ("") open/close returns {@code null} (no match).</p>
*
* <pre>
* StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
* StringUtils.substringsBetween(null, *, *) = null
* StringUtils.substringsBetween(*, null, *) = null
* StringUtils.substringsBetween(*, *, null) = null
* StringUtils.substringsBetween("", "[", "]") = []
* </pre>
*
* @param str the String containing the substrings, null returns null, empty returns empty
* @param open the String identifying the start of the substring, empty returns null
* @param close the String identifying the end of the substring, empty returns null
* @return a String Array of substrings, or {@code null} if no match
* @since 2.3
*/
public static String[] substringsBetween(final String str, final String open, final String close) {
if (str == null || isEmpty(open) || isEmpty(close)) {
return null;
}
final int strLen = str.length();
if (strLen == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final int closeLen = close.length();
final int openLen = open.length();
final List<String> list = new ArrayList<String>();
int pos = 0;
while (pos < strLen - closeLen) {
int start = str.indexOf(open, pos);
if (start < 0) {
break;
}
start += openLen;
final int end = str.indexOf(close, start);
if (end < 0) {
break;
}
list.add(str.substring(start, end));
pos = end + closeLen;
}
if (list.isEmpty()) {
return null;
}
return list.toArray(new String [list.size()]);
}
// Nested extraction
//-----------------------------------------------------------------------
// Splitting
//-----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null) = null
* StringUtils.split("") = []
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split("abc def") = ["abc", "def"]
* StringUtils.split(" abc ") = ["abc"]
* </pre>
*
* @param str the String to parse, may be null
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str) {
return split(str, null, -1);
}
/**
* <p>Splits the provided text into an array, separator specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtils.split("a:b:c", '.') = ["a:b:c"]
* StringUtils.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChar the character used as the delimiter
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.0
*/
public static String[] split(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, false);
}
/**
* <p>Splits the provided text into an array, separators specified.
* This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.split(null, *) = null
* StringUtils.split("", *) = []
* StringUtils.split("abc def", null) = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, false);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.split(null, *, *) = null
* StringUtils.split("", *, *) = []
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
*/
public static String[] split(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *) = null
* StringUtils.splitByWholeSeparator("", *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator(final String str, final String separator) {
return splitByWholeSeparatorWorker( str, separator, -1, false ) ;
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator(s) will not be included in the returned String array.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparator(null, *, *) = null
* StringUtils.splitByWholeSeparator("", *, *) = []
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
*/
public static String[] splitByWholeSeparator( final String str, final String separator, final int max ) {
return splitByWholeSeparatorWorker(str, separator, max, false);
}
/**
* <p>Splits the provided text into an array, separator string specified. </p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
/**
* <p>Splits the provided text into an array, separator string specified.
* Returns a maximum of {@code max} substrings.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separator splits on whitespace.</p>
*
* <pre>
* StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *) = null
* StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *) = []
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0) = ["ab", "", "", "de", "fg"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
* StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
* </pre>
*
* @param str the String to parse, may be null
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @return an array of parsed Strings, {@code null} if null String was input
* @since 2.4
*/
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) {
return splitByWholeSeparatorWorker(str, separator, max, true);
}
/**
* Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods.
*
* @param str the String to parse, may be {@code null}
* @param separator String containing the String to be used as a delimiter,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the returned
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByWholeSeparatorWorker(
final String str, final String separator, final int max, final boolean preserveAllTokens) {
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
if (separator == null || EMPTY.equals(separator)) {
// Split on whitespace.
return splitWorker(str, null, max, preserveAllTokens);
}
final int separatorLength = separator.length();
final ArrayList<String> substrings = new ArrayList<String>();
int numberOfSubstrings = 0;
int beg = 0;
int end = 0;
while (end < len) {
end = str.indexOf(separator, beg);
if (end > -1) {
if (end > beg) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
// The following is OK, because String.substring( beg, end ) excludes
// the character at the position 'end'.
substrings.add(str.substring(beg, end));
// Set the starting point for the next search.
// The following is equivalent to beg = end + (separatorLength - 1) + 1,
// which is the right calculation:
beg = end + separatorLength;
}
} else {
// We found a consecutive occurrence of the separator, so skip it.
if (preserveAllTokens) {
numberOfSubstrings += 1;
if (numberOfSubstrings == max) {
end = len;
substrings.add(str.substring(beg));
} else {
substrings.add(EMPTY);
}
}
beg = end + separatorLength;
}
} else {
// String.substring( beg ) goes from 'beg' to the end of the String.
substrings.add(str.substring(beg));
end = len;
}
}
return substrings.toArray(new String[substrings.size()]);
}
// -----------------------------------------------------------------------
/**
* <p>Splits the provided text into an array, using whitespace as the
* separator, preserving all tokens, including empty tokens created by
* adjacent separators. This is an alternative to using StringTokenizer.
* Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null) = null
* StringUtils.splitPreserveAllTokens("") = []
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"]
* StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str) {
return splitWorker(str, null, -1, true);
}
/**
* <p>Splits the provided text into an array, separator specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "", "b", "c"]
* StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"]
* StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""]
* StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"]
* StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the character used as the delimiter,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final char separatorChar) {
return splitWorker(str, separatorChar, true);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that do not return a
* maximum array length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChar the separate character
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<String>();
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
while (i < len) {
if (str.charAt(i) == separatorChar) {
if (match || preserveAllTokens) {
list.add(str.substring(start, i));
match = false;
lastMatch = true;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits the provided text into an array, separators specified,
* preserving all tokens, including empty tokens created by adjacent
* separators. This is an alternative to using StringTokenizer.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* For more control over the split use the StrTokenizer class.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *) = null
* StringUtils.splitPreserveAllTokens("", *) = []
* StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"]
* StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""]
* StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
* StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"]
* StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"]
* StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars) {
return splitWorker(str, separatorChars, -1, true);
}
/**
* <p>Splits the provided text into an array with a maximum length,
* separators specified, preserving all tokens, including empty tokens
* created by adjacent separators.</p>
*
* <p>The separator is not included in the returned String array.
* Adjacent separators are treated as separators for empty tokens.
* Adjacent separators are treated as one separator.</p>
*
* <p>A {@code null} input String returns {@code null}.
* A {@code null} separatorChars splits on whitespace.</p>
*
* <p>If more than {@code max} delimited substrings are found, the last
* returned string includes all characters after the first {@code max - 1}
* returned strings (including separator characters).</p>
*
* <pre>
* StringUtils.splitPreserveAllTokens(null, *, *) = null
* StringUtils.splitPreserveAllTokens("", *, *) = []
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"]
* StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
* </pre>
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the characters used as the delimiters,
* {@code null} splits on whitespace
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.1
*/
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) {
return splitWorker(str, separatorChars, max, true);
}
/**
* Performs the logic for the {@code split} and
* {@code splitPreserveAllTokens} methods that return a maximum array
* length.
*
* @param str the String to parse, may be {@code null}
* @param separatorChars the separate character
* @param max the maximum number of elements to include in the
* array. A zero or negative value implies no limit.
* @param preserveAllTokens if {@code true}, adjacent separators are
* treated as empty token separators; if {@code false}, adjacent
* separators are treated as one separator.
* @return an array of parsed Strings, {@code null} if null String input
*/
private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) {
// Performance tuned for 2.0 (JDK1.4)
// Direct code is quicker than StringTokenizer.
// Also, StringTokenizer uses isSpace() not isWhitespace()
if (str == null) {
return null;
}
final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<String>();
int sizePlus1 = 1;
int i = 0, start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// Optimise 1 character case
final char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
} else {
// standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens.
* <pre>
* StringUtils.splitByCharacterType(null) = null
* StringUtils.splitByCharacterType("") = []
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterType("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterType("number5") = ["number", "5"]
* StringUtils.splitByCharacterType("fooBar") = ["foo", "B", "ar"]
* StringUtils.splitByCharacterType("foo200Bar") = ["foo", "200", "B", "ar"]
* StringUtils.splitByCharacterType("ASFRules") = ["ASFR", "ules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterType(final String str) {
return splitByCharacterType(str, false);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: the character of type
* {@code Character.UPPERCASE_LETTER}, if any, immediately
* preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* <pre>
* StringUtils.splitByCharacterTypeCamelCase(null) = null
* StringUtils.splitByCharacterTypeCamelCase("") = []
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"]
* StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"]
* StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"]
* StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
* StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
* </pre>
* @param str the String to split, may be {@code null}
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
public static String[] splitByCharacterTypeCamelCase(final String str) {
return splitByCharacterType(str, true);
}
/**
* <p>Splits a String by Character type as returned by
* {@code java.lang.Character.getType(char)}. Groups of contiguous
* characters of the same type are returned as complete tokens, with the
* following exception: if {@code camelCase} is {@code true},
* the character of type {@code Character.UPPERCASE_LETTER}, if any,
* immediately preceding a token of type {@code Character.LOWERCASE_LETTER}
* will belong to the following token rather than to the preceding, if any,
* {@code Character.UPPERCASE_LETTER} token.
* @param str the String to split, may be {@code null}
* @param camelCase whether to use so-called "camel-case" for letter types
* @return an array of parsed Strings, {@code null} if null String input
* @since 2.4
*/
private static String[] splitByCharacterType(final String str, final boolean camelCase) {
if (str == null) {
return null;
}
if (str.isEmpty()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final char[] c = str.toCharArray();
final List<String> list = new ArrayList<String>();
int tokenStart = 0;
int currentType = Character.getType(c[tokenStart]);
for (int pos = tokenStart + 1; pos < c.length; pos++) {
final int type = Character.getType(c[pos]);
if (type == currentType) {
continue;
}
if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) {
final int newTokenStart = pos - 1;
if (newTokenStart != tokenStart) {
list.add(new String(c, tokenStart, newTokenStart - tokenStart));
tokenStart = newTokenStart;
}
} else {
list.add(new String(c, tokenStart, pos - tokenStart));
tokenStart = pos;
}
currentType = type;
}
list.add(new String(c, tokenStart, c.length - tokenStart));
return list.toArray(new String[list.size()]);
}
// Joining
//-----------------------------------------------------------------------
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No separator is added to the joined String.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null) = null
* StringUtils.join([]) = ""
* StringUtils.join([null]) = ""
* StringUtils.join(["a", "b", "c"]) = "abc"
* StringUtils.join([null, "", "a"]) = "a"
* </pre>
*
* @param <T> the specific type of values to join together
* @param elements the values to join together, may be null
* @return the joined String, {@code null} if null array input
* @since 2.0
* @since 3.0 Changed signature to use varargs
*/
public static <T> String join(final T... elements) {
return join(elements, null);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], ';') = "a;b;c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join([null, "", "a"], ';') = ";;a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use
* @param startIndex the first index to start joining from. It is
* an error to pass in an end index past the end of the array
* @param endIndex the index to stop joining from (exclusive). It is
* an error to pass in an end index past the end of the array
* @return the joined String, {@code null} if null array input
* @since 2.0
*/
public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>
* Joins the elements of the provided array into a single String containing the provided list of elements.
* </p>
*
* <p>
* No delimiter is added before or after the list. Null objects or empty strings within the array are represented
* by empty strings.
* </p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join([1, 2, 3], ';') = "1;2;3"
* StringUtils.join([1, 2, 3], null) = "123"
* </pre>
*
* @param array
* the array of values to join together, may be null
* @param separator
* the separator character to use
* @param startIndex
* the first index to start joining from. It is an error to pass in an end index past the end of the
* array
* @param endIndex
* the index to stop joining from (exclusive). It is an error to pass in an end index past the end of
* the array
* @return the joined String, {@code null} if null array input
* @since 3.2
*/
public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
buf.append(array[i]);
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *) = null
* StringUtils.join([], *) = ""
* StringUtils.join([null], *) = ""
* StringUtils.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtils.join(["a", "b", "c"], null) = "abc"
* StringUtils.join(["a", "b", "c"], "") = "abc"
* StringUtils.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null array input
*/
public static String join(final Object[] array, final String separator) {
if (array == null) {
return null;
}
return join(array, separator, 0, array.length);
}
/**
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").
* Null objects or empty strings within the array are represented by
* empty strings.</p>
*
* <pre>
* StringUtils.join(null, *, *, *) = null
* StringUtils.join([], *, *, *) = ""
* StringUtils.join([null], *, *, *) = ""
* StringUtils.join(["a", "b", "c"], "--", 0, 3) = "a--b--c"
* StringUtils.join(["a", "b", "c"], "--", 1, 3) = "b--c"
* StringUtils.join(["a", "b", "c"], "--", 2, 3) = "c"
* StringUtils.join(["a", "b", "c"], "--", 2, 2) = ""
* StringUtils.join(["a", "b", "c"], null, 0, 3) = "abc"
* StringUtils.join(["a", "b", "c"], "", 0, 3) = "abc"
* StringUtils.join([null, "", "a"], ',', 0, 3) = ",,a"
* </pre>
*
* @param array the array of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @param startIndex the first index to start joining from.
* @param endIndex the index to stop joining from (exclusive).
* @return the joined String, {@code null} if null array input; or the empty string
* if {@code endIndex - startIndex <= 0}. The number of joined entries is given by
* {@code endIndex - startIndex}
* @throws ArrayIndexOutOfBoundsException ife<br>
* {@code startIndex < 0} or <br>
* {@code startIndex >= array.length()} or <br>
* {@code endIndex < 0} or <br>
* {@code endIndex > array.length()}
*/
public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY;
}
// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator))
// (Assuming that all Strings are roughly equally long)
final int noOfItems = endIndex - startIndex;
if (noOfItems <= 0) {
return EMPTY;
}
final StringBuilder buf = new StringBuilder(noOfItems * 16);
for (int i = startIndex; i < endIndex; i++) {
if (i > startIndex) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.0
*/
public static String join(final Iterator<?> iterator, final char separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
@SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2
final
String result = ObjectUtils.toString(first);
return result;
}
// two or more elements
final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
buf.append(separator);
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterator} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterator the {@code Iterator} of values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
*/
public static String join(final Iterator<?> iterator, final String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
@SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2
final String result = ObjectUtils.toString(first);
return result;
}
// two or more elements
final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list. Null objects or empty
* strings within the iteration are represented by empty strings.</p>
*
* <p>See the examples here: {@link #join(Object[],char)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final char separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
/**
* <p>Joins the elements of the provided {@code Iterable} into
* a single String containing the provided elements.</p>
*
* <p>No delimiter is added before or after the list.
* A {@code null} separator is the same as an empty String ("").</p>
*
* <p>See the examples here: {@link #join(Object[],String)}. </p>
*
* @param iterable the {@code Iterable} providing the values to join together, may be null
* @param separator the separator character to use, null treated as ""
* @return the joined String, {@code null} if null iterator input
* @since 2.3
*/
public static String join(final Iterable<?> iterable, final String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
// Delete
//-----------------------------------------------------------------------
/**
* <p>Deletes all whitespaces from a String as defined by
* {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.deleteWhitespace(null) = null
* StringUtils.deleteWhitespace("") = ""
* StringUtils.deleteWhitespace("abc") = "abc"
* StringUtils.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str the String to delete whitespace from, may be null
* @return the String without whitespaces, {@code null} if null String input
*/
public static String deleteWhitespace(final String str) {
if (isEmpty(str)) {
return str;
}
final int sz = str.length();
final char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
// Remove
//-----------------------------------------------------------------------
/**
* <p>Removes a substring only if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStart(null, *) = null
* StringUtils.removeStart("", *) = ""
* StringUtils.removeStart(*, null) = *
* StringUtils.removeStart("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStart("domain.com", "www.") = "domain.com"
* StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStart("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeStart(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.startsWith(remove)){
return str.substring(remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the beginning of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeStartIgnoreCase(null, *) = null
* StringUtils.removeStartIgnoreCase("", *) = ""
* StringUtils.removeStartIgnoreCase(*, null) = *
* StringUtils.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
* StringUtils.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
* StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeStartIgnoreCase("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeStartIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (startsWithIgnoreCase(str, remove)) {
return str.substring(remove.length());
}
return str;
}
/**
* <p>Removes a substring only if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEnd(null, *) = null
* StringUtils.removeEnd("", *) = ""
* StringUtils.removeEnd(*, null) = *
* StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEnd("abc", "") = "abc"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String removeEnd(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (str.endsWith(remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Case insensitive removal of a substring if it is at the end of a source string,
* otherwise returns the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} search string will return the source string.</p>
*
* <pre>
* StringUtils.removeEndIgnoreCase(null, *) = null
* StringUtils.removeEndIgnoreCase("", *) = ""
* StringUtils.removeEndIgnoreCase(*, null) = *
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com.") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".com") = "www.domain"
* StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
* StringUtils.removeEndIgnoreCase("abc", "") = "abc"
* StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
* StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for (case insensitive) and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.4
*/
public static String removeEndIgnoreCase(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
if (endsWithIgnoreCase(str, remove)) {
return str.substring(0, str.length() - remove.length());
}
return str;
}
/**
* <p>Removes all occurrences of a substring from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.
* A {@code null} remove string will return the source string.
* An empty ("") remove string will return the source string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove(*, null) = *
* StringUtils.remove(*, "") = *
* StringUtils.remove("queued", "ue") = "qd"
* StringUtils.remove("queued", "zz") = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the String to search for and remove, may be null
* @return the substring with the string removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final String remove) {
if (isEmpty(str) || isEmpty(remove)) {
return str;
}
return replace(str, remove, EMPTY, -1);
}
/**
* <p>Removes all occurrences of a character from within the source string.</p>
*
* <p>A {@code null} source string will return {@code null}.
* An empty ("") source string will return the empty string.</p>
*
* <pre>
* StringUtils.remove(null, *) = null
* StringUtils.remove("", *) = ""
* StringUtils.remove("queued", 'u') = "qeed"
* StringUtils.remove("queued", 'z') = "queued"
* </pre>
*
* @param str the source String to search, may be null
* @param remove the char to search for and remove, may be null
* @return the substring with the char removed if found,
* {@code null} if null String input
* @since 2.1
*/
public static String remove(final String str, final char remove) {
if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) {
return str;
}
final char[] chars = str.toCharArray();
int pos = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] != remove) {
chars[pos++] = chars[i];
}
}
return new String(chars, 0, pos);
}
// Replacing
//-----------------------------------------------------------------------
/**
* <p>Replaces a String with another String inside a larger String, once.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replaceOnce(null, *, *) = null
* StringUtils.replaceOnce("", *, *) = ""
* StringUtils.replaceOnce("any", null, *) = "any"
* StringUtils.replaceOnce("any", *, null) = "any"
* StringUtils.replaceOnce("any", "", *) = "any"
* StringUtils.replaceOnce("aba", "a", null) = "aba"
* StringUtils.replaceOnce("aba", "a", "") = "ba"
* StringUtils.replaceOnce("aba", "a", "z") = "zba"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replaceOnce(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, 1);
}
/**
* Replaces each substring of the source String that matches the given regular expression with the given
* replacement using the {@link Pattern#DOTALL} option. DOTALL is also know as single-line mode in Perl. This call
* is also equivalent to:
* <ul>
* <li>{@code source.replaceAll("(?s)" + regex, replacement)}</li>
* <li>{@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}</li>
* </ul>
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @param replacement
* the string to be substituted for each match
* @return The resulting {@code String}
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
*/
public static String replacePattern(final String source, final String regex, final String replacement) {
return Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement);
}
/**
* Removes each substring of the source String that matches the given regular expression using the DOTALL option.
*
* @param source
* the source string
* @param regex
* the regular expression to which this string is to be matched
* @return The resulting {@code String}
* @see String#replaceAll(String, String)
* @see Pattern#DOTALL
* @since 3.2
*/
public static String removePattern(final String source, final String regex) {
return replacePattern(source, regex, StringUtils.EMPTY);
}
/**
* <p>Replaces all occurrences of a String within another String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *) = null
* StringUtils.replace("", *, *) = ""
* StringUtils.replace("any", null, *) = "any"
* StringUtils.replace("any", *, null) = "any"
* StringUtils.replace("any", "", *) = "any"
* StringUtils.replace("aba", "a", null) = "aba"
* StringUtils.replace("aba", "a", "") = "b"
* StringUtils.replace("aba", "a", "z") = "zbz"
* </pre>
*
* @see #replace(String text, String searchString, String replacement, int max)
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement) {
return replace(text, searchString, replacement, -1);
}
/**
* <p>Replaces a String with another String inside a larger String,
* for the first {@code max} values of the search String.</p>
*
* <p>A {@code null} reference passed to this method is a no-op.</p>
*
* <pre>
* StringUtils.replace(null, *, *, *) = null
* StringUtils.replace("", *, *, *) = ""
* StringUtils.replace("any", null, *, *) = "any"
* StringUtils.replace("any", *, null, *) = "any"
* StringUtils.replace("any", "", *, *) = "any"
* StringUtils.replace("any", *, *, 0) = "any"
* StringUtils.replace("abaa", "a", null, -1) = "abaa"
* StringUtils.replace("abaa", "a", "", -1) = "b"
* StringUtils.replace("abaa", "a", "z", 0) = "abaa"
* StringUtils.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtils.replace("abaa", "a", "z", 2) = "zbza"
* StringUtils.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
*
* @param text text to search and replace in, may be null
* @param searchString the String to search for, may be null
* @param replacement the String to replace it with, may be null
* @param max maximum number of values to replace, or {@code -1} if no maximum
* @return the text with any replacements processed,
* {@code null} if null String input
*/
public static String replace(final String text, final String searchString, final String replacement, int max) {
if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
return text;
}
int start = 0;
int end = text.indexOf(searchString, start);
if (end == INDEX_NOT_FOUND) {
return text;
}
final int replLength = searchString.length();
int increase = replacement.length() - replLength;
increase = increase < 0 ? 0 : increase;
increase *= max < 0 ? 16 : max > 64 ? 64 : max;
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (end != INDEX_NOT_FOUND) {
buf.append(text.substring(start, end)).append(replacement);
start = end + replLength;
if (--max == 0) {
break;
}
end = text.indexOf(searchString, start);
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored. This will not repeat. For repeating replaces, call the
* overloaded method.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *) = null
* StringUtils.replaceEach("", *, *) = ""
* StringUtils.replaceEach("aba", null, null) = "aba"
* StringUtils.replaceEach("aba", new String[0], null) = "aba"
* StringUtils.replaceEach("aba", null, new String[0]) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it does not repeat)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) {
return replaceEach(text, searchList, replacementList, false, 0);
}
/**
* <p>
* Replaces all occurrences of Strings within another String.
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEachRepeatedly(null, *, *) = null
* StringUtils.replaceEachRepeatedly("", *, *) = ""
* StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
* StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
* StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
* StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) {
// timeToLive should be 0 if not used or nothing to replace, else it's
// the length of the replace array
final int timeToLive = searchList == null ? 0 : searchList.length;
return replaceEach(text, searchList, replacementList, true, timeToLive);
}
/**
* <p>
* Replace all occurrences of Strings within another String.
* This is a private recursive helper method for {@link #replaceEachRepeatedly(String, String[], String[])} and
* {@link #replaceEach(String, String[], String[])}
* </p>
*
* <p>
* A {@code null} reference passed to this method is a no-op, or if
* any "search string" or "string to replace" is null, that replace will be
* ignored.
* </p>
*
* <pre>
* StringUtils.replaceEach(null, *, *, *, *) = null
* StringUtils.replaceEach("", *, *, *, *) = ""
* StringUtils.replaceEach("aba", null, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba"
* StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba"
* StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b"
* StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte"
* (example of how it repeats)
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte"
* StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException
* </pre>
*
* @param text
* text to search and replace in, no-op if null
* @param searchList
* the Strings to search for, no-op if null
* @param replacementList
* the Strings to replace them with, no-op if null
* @param repeat if true, then replace repeatedly
* until there are no more possible replacements or timeToLive < 0
* @param timeToLive
* if less than 0 then there is a circular reference and endless
* loop
* @return the text with any replacements processed, {@code null} if
* null String input
* @throws IllegalStateException
* if the search is repeating and there is an endless loop due
* to outputs of one being inputs to another
* @throws IllegalArgumentException
* if the lengths of the arrays are not the same (null is ok,
* and/or size 0)
* @since 2.4
*/
private static String replaceEach(
final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) {
// mchyzer Performance note: This creates very few new objects (one major goal)
// let me know if there are performance requests, we can create a harness to measure
if (text == null || text.isEmpty() || searchList == null ||
searchList.length == 0 || replacementList == null || replacementList.length == 0) {
return text;
}
// if recursing, this shouldn't be less than 0
if (timeToLive < 0) {
throw new IllegalStateException("Aborting to protect against StackOverflowError - " +
"output of one loop is the input of another");
}
final int searchLength = searchList.length;
final int replacementLength = replacementList.length;
// make sure lengths are ok, these need to be equal
if (searchLength != replacementLength) {
throw new IllegalArgumentException("Search and Replace array lengths don't match: "
+ searchLength
+ " vs "
+ replacementLength);
}
// keep track of which still have matches
final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];
// index on index that the match was found
int textIndex = -1;
int replaceIndex = -1;
int tempIndex = -1;
// index of replace array that will replace the search string found
// NOTE: logic duplicated below START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i]);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic mostly below END
// no search strings found, we are done
if (textIndex == -1) {
return text;
}
int start = 0;
// get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit
int increase = 0;
// count the replacement text elements that are larger than their corresponding text being replaced
for (int i = 0; i < searchList.length; i++) {
if (searchList[i] == null || replacementList[i] == null) {
continue;
}
final int greater = replacementList[i].length() - searchList[i].length();
if (greater > 0) {
increase += 3 * greater; // assume 3 matches
}
}
// have upper-bound at 20% increase, then let Java take over
increase = Math.min(increase, text.length() / 5);
final StringBuilder buf = new StringBuilder(text.length() + increase);
while (textIndex != -1) {
for (int i = start; i < textIndex; i++) {
buf.append(text.charAt(i));
}
buf.append(replacementList[replaceIndex]);
start = textIndex + searchList[replaceIndex].length();
textIndex = -1;
replaceIndex = -1;
tempIndex = -1;
// find the next earliest match
// NOTE: logic mostly duplicated above START
for (int i = 0; i < searchLength; i++) {
if (noMoreMatchesForReplIndex[i] || searchList[i] == null ||
searchList[i].isEmpty() || replacementList[i] == null) {
continue;
}
tempIndex = text.indexOf(searchList[i], start);
// see if we need to keep searching for this
if (tempIndex == -1) {
noMoreMatchesForReplIndex[i] = true;
} else {
if (textIndex == -1 || tempIndex < textIndex) {
textIndex = tempIndex;
replaceIndex = i;
}
}
}
// NOTE: logic duplicated above END
}
final int textLength = text.length();
for (int i = start; i < textLength; i++) {
buf.append(text.charAt(i));
}
final String result = buf.toString();
if (!repeat) {
return result;
}
return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);
}
// Replace, character based
//-----------------------------------------------------------------------
/**
* <p>Replaces all occurrences of a character in a String with another.
* This is a null-safe version of {@link String#replace(char, char)}.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChar the character to search for, may be null
* @param replaceChar the character to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final char searchChar, final char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* <p>Replaces multiple characters in a String in one go.
* This method can also be used to delete characters.</p>
*
* <p>For example:<br>
* <code>replaceChars("hello", "ho", "jy") = jelly</code>.</p>
*
* <p>A {@code null} string input returns {@code null}.
* An empty ("") string input returns an empty string.
* A null or empty set of search characters returns the input string.</p>
*
* <p>The length of the search characters should normally equal the length
* of the replace characters.
* If the search characters is longer, then the extra search characters
* are deleted.
* If the search characters is shorter, then the extra replace characters
* are ignored.</p>
*
* <pre>
* StringUtils.replaceChars(null, *, *) = null
* StringUtils.replaceChars("", *, *) = ""
* StringUtils.replaceChars("abc", null, *) = "abc"
* StringUtils.replaceChars("abc", "", *) = "abc"
* StringUtils.replaceChars("abc", "b", null) = "ac"
* StringUtils.replaceChars("abc", "b", "") = "ac"
* StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtils.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
*
* @param str String to replace characters in, may be null
* @param searchChars a set of characters to search for, may be null
* @param replaceChars a set of characters to replace, may be null
* @return modified String, {@code null} if null string input
* @since 2.0
*/
public static String replaceChars(final String str, final String searchChars, String replaceChars) {
if (isEmpty(str) || isEmpty(searchChars)) {
return str;
}
if (replaceChars == null) {
replaceChars = EMPTY;
}
boolean modified = false;
final int replaceCharsLength = replaceChars.length();
final int strLength = str.length();
final StringBuilder buf = new StringBuilder(strLength);
for (int i = 0; i < strLength; i++) {
final char ch = str.charAt(i);
final int index = searchChars.indexOf(ch);
if (index >= 0) {
modified = true;
if (index < replaceCharsLength) {
buf.append(replaceChars.charAt(index));
}
} else {
buf.append(ch);
}
}
if (modified) {
return buf.toString();
}
return str;
}
// Overlay
//-----------------------------------------------------------------------
/**
* <p>Overlays part of a String with another String.</p>
*
* <p>A {@code null} string input returns {@code null}.
* A negative index is treated as zero.
* An index greater than the string length is treated as the string length.
* The start index is always the smaller of the two indices.</p>
*
* <pre>
* StringUtils.overlay(null, *, *, *) = null
* StringUtils.overlay("", "abc", 0, 0) = "abc"
* StringUtils.overlay("abcdef", null, 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 2, 4) = "abef"
* StringUtils.overlay("abcdef", "", 4, 2) = "abef"
* StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
*
* @param str the String to do overlaying in, may be null
* @param overlay the String to overlay, may be null
* @param start the position to start overlaying at
* @param end the position to stop overlaying before
* @return overlayed String, {@code null} if null String input
* @since 2.0
*/
public static String overlay(final String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY;
}
final int len = str.length();
if (start < 0) {
start = 0;
}
if (start > len) {
start = len;
}
if (end < 0) {
end = 0;
}
if (end > len) {
end = len;
}
if (start > end) {
final int temp = start;
start = end;
end = temp;
}
return new StringBuilder(len + start - end + overlay.length() + 1)
.append(str.substring(0, start))
.append(overlay)
.append(str.substring(end))
.toString();
}
// Chomping
//-----------------------------------------------------------------------
/**
* <p>Removes one newline from end of a String if it's there,
* otherwise leave it alone. A newline is "{@code \n}",
* "{@code \r}", or "{@code \r\n}".</p>
*
* <p>NOTE: This method changed in 2.0.
* It now more closely matches Perl chomp.</p>
*
* <pre>
* StringUtils.chomp(null) = null
* StringUtils.chomp("") = ""
* StringUtils.chomp("abc \r") = "abc "
* StringUtils.chomp("abc\n") = "abc"
* StringUtils.chomp("abc\r\n") = "abc"
* StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtils.chomp("abc\n\r") = "abc\n"
* StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtils.chomp("\r") = ""
* StringUtils.chomp("\n") = ""
* StringUtils.chomp("\r\n") = ""
* </pre>
*
* @param str the String to chomp a newline from, may be null
* @return String without newline, {@code null} if null String input
*/
public static String chomp(final String str) {
if (isEmpty(str)) {
return str;
}
if (str.length() == 1) {
final char ch = str.charAt(1);
if (ch == CharUtils.CR || ch == CharUtils.LF) {
return EMPTY;
}
return str;
}
int lastIdx = str.length() - 1;
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF) {
if (str.charAt(lastIdx - 1) == CharUtils.CR) {
lastIdx--;
}
} else if (last != CharUtils.CR) {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* <p>Removes {@code separator} from the end of
* {@code str} if it's there, otherwise leave it alone.</p>
*
* <p>NOTE: This method changed in version 2.0.
* It now more closely matches Perl chomp.
* For the previous behavior, use {@link #substringBeforeLast(String, String)}.
* This method uses {@link String#endsWith(String)}.</p>
*
* <pre>
* StringUtils.chomp(null, *) = null
* StringUtils.chomp("", *) = ""
* StringUtils.chomp("foobar", "bar") = "foo"
* StringUtils.chomp("foobar", "baz") = "foobar"
* StringUtils.chomp("foo", "foo") = ""
* StringUtils.chomp("foo ", "foo") = "foo "
* StringUtils.chomp(" foo", "foo") = " "
* StringUtils.chomp("foo", "foooo") = "foo"
* StringUtils.chomp("foo", "") = "foo"
* StringUtils.chomp("foo", null) = "foo"
* </pre>
*
* @param str the String to chomp from, may be null
* @param separator separator String, may be null
* @return String without trailing separator, {@code null} if null String input
* @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead
*/
@Deprecated
public static String chomp(final String str, final String separator) {
return removeEnd(str,separator);
}
// Chopping
//-----------------------------------------------------------------------
/**
* <p>Remove the last character from a String.</p>
*
* <p>If the String ends in {@code \r\n}, then remove both
* of them.</p>
*
* <pre>
* StringUtils.chop(null) = null
* StringUtils.chop("") = ""
* StringUtils.chop("abc \r") = "abc "
* StringUtils.chop("abc\n") = "abc"
* StringUtils.chop("abc\r\n") = "abc"
* StringUtils.chop("abc") = "ab"
* StringUtils.chop("abc\nabc") = "abc\nab"
* StringUtils.chop("a") = ""
* StringUtils.chop("\r") = ""
* StringUtils.chop("\n") = ""
* StringUtils.chop("\r\n") = ""
* </pre>
*
* @param str the String to chop last character from, may be null
* @return String without last character, {@code null} if null String input
*/
public static String chop(final String str) {
if (str == null) {
return null;
}
final int strLen = str.length();
if (strLen < 2) {
return EMPTY;
}
final int lastIdx = strLen - 1;
final String ret = str.substring(0, lastIdx);
final char last = str.charAt(lastIdx);
if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) {
return ret.substring(0, lastIdx - 1);
}
return ret;
}
// Conversion
//-----------------------------------------------------------------------
// Padding
//-----------------------------------------------------------------------
/**
* <p>Repeat a String {@code repeat} times to form a
* new String.</p>
*
* <pre>
* StringUtils.repeat(null, 2) = null
* StringUtils.repeat("", 0) = ""
* StringUtils.repeat("", 2) = ""
* StringUtils.repeat("a", 3) = "aaa"
* StringUtils.repeat("ab", 2) = "abab"
* StringUtils.repeat("a", -2) = ""
* </pre>
*
* @param str the String to repeat, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
*/
public static String repeat(final String str, final int repeat) {
// Performance tuned for 2.0 (JDK1.4)
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY;
}
final int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
if (inputLength == 1 && repeat <= PAD_LIMIT) {
return repeat(str.charAt(0), repeat);
}
final int outputLength = inputLength * repeat;
switch (inputLength) {
case 1 :
return repeat(str.charAt(0), repeat);
case 2 :
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
final char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default :
final StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
/**
* <p>Repeat a String {@code repeat} times to form a
* new String, with a String separator injected each time. </p>
*
* <pre>
* StringUtils.repeat(null, null, 2) = null
* StringUtils.repeat(null, "x", 2) = null
* StringUtils.repeat("", null, 0) = ""
* StringUtils.repeat("", "", 2) = ""
* StringUtils.repeat("", "x", 3) = "xxx"
* StringUtils.repeat("?", ", ", 3) = "?, ?, ?"
* </pre>
*
* @param str the String to repeat, may be null
* @param separator the String to inject, may be null
* @param repeat number of times to repeat str, negative treated as zero
* @return a new String consisting of the original String repeated,
* {@code null} if null String input
* @since 2.5
*/
public static String repeat(final String str, final String separator, final int repeat) {
if(str == null || separator == null) {
return repeat(str, repeat);
}
// given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it
final String result = repeat(str + separator, repeat);
return removeEnd(result, separator);
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.repeat('e', 0) = ""
* StringUtils.repeat('e', 3) = "eee"
* StringUtils.repeat('e', -2) = ""
* </pre>
*
* <p>Note: this method doesn't not support padding with
* <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a>
* as they require a pair of {@code char}s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param ch character to repeat
* @param repeat number of times to repeat char, negative treated as zero
* @return String with repeated character
* @see #repeat(String, int)
*/
public static String repeat(final char ch, final int repeat) {
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
/**
* <p>Right pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *) = null
* StringUtils.rightPad("", 3) = " "
* StringUtils.rightPad("bat", 3) = "bat"
* StringUtils.rightPad("bat", 5) = "bat "
* StringUtils.rightPad("bat", 1) = "bat"
* StringUtils.rightPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size) {
return rightPad(str, size, ' ');
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, 'z') = "zzz"
* StringUtils.rightPad("bat", 3, 'z') = "bat"
* StringUtils.rightPad("bat", 5, 'z') = "batzz"
* StringUtils.rightPad("bat", 1, 'z') = "bat"
* StringUtils.rightPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String rightPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return rightPad(str, size, String.valueOf(padChar));
}
return str.concat(repeat(padChar, pads));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.rightPad(null, *, *) = null
* StringUtils.rightPad("", 3, "z") = "zzz"
* StringUtils.rightPad("bat", 3, "yz") = "bat"
* StringUtils.rightPad("bat", 5, "yz") = "batyz"
* StringUtils.rightPad("bat", 8, "yz") = "batyzyzy"
* StringUtils.rightPad("bat", 1, "yz") = "bat"
* StringUtils.rightPad("bat", -1, "yz") = "bat"
* StringUtils.rightPad("bat", 5, null) = "bat "
* StringUtils.rightPad("bat", 5, "") = "bat "
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return right padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String rightPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return rightPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return str.concat(padStr);
} else if (pads < padLen) {
return str.concat(padStr.substring(0, pads));
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return str.concat(new String(padding));
}
}
/**
* <p>Left pad a String with spaces (' ').</p>
*
* <p>The String is padded to the size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *) = null
* StringUtils.leftPad("", 3) = " "
* StringUtils.leftPad("bat", 3) = "bat"
* StringUtils.leftPad("bat", 5) = " bat"
* StringUtils.leftPad("bat", 1) = "bat"
* StringUtils.leftPad("bat", -1) = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size) {
return leftPad(str, size, ' ');
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, 'z') = "zzz"
* StringUtils.leftPad("bat", 3, 'z') = "bat"
* StringUtils.leftPad("bat", 5, 'z') = "zzbat"
* StringUtils.leftPad("bat", 1, 'z') = "bat"
* StringUtils.leftPad("bat", -1, 'z') = "bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padChar the character to pad with
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
* @since 2.0
*/
public static String leftPad(final String str, final int size, final char padChar) {
if (str == null) {
return null;
}
final int pads = size - str.length();
if (pads <= 0) {
return str; // returns original String when possible
}
if (pads > PAD_LIMIT) {
return leftPad(str, size, String.valueOf(padChar));
}
return repeat(padChar, pads).concat(str);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of {@code size}.</p>
*
* <pre>
* StringUtils.leftPad(null, *, *) = null
* StringUtils.leftPad("", 3, "z") = "zzz"
* StringUtils.leftPad("bat", 3, "yz") = "bat"
* StringUtils.leftPad("bat", 5, "yz") = "yzbat"
* StringUtils.leftPad("bat", 8, "yz") = "yzyzybat"
* StringUtils.leftPad("bat", 1, "yz") = "bat"
* StringUtils.leftPad("bat", -1, "yz") = "bat"
* StringUtils.leftPad("bat", 5, null) = " bat"
* StringUtils.leftPad("bat", 5, "") = " bat"
* </pre>
*
* @param str the String to pad out, may be null
* @param size the size to pad to
* @param padStr the String to pad with, null or empty treated as single space
* @return left padded String or original String if no padding is necessary,
* {@code null} if null String input
*/
public static String leftPad(final String str, final int size, String padStr) {
if (str == null) {
return null;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int padLen = padStr.length();
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str; // returns original String when possible
}
if (padLen == 1 && pads <= PAD_LIMIT) {
return leftPad(str, size, padStr.charAt(0));
}
if (pads == padLen) {
return padStr.concat(str);
} else if (pads < padLen) {
return padStr.substring(0, pads).concat(str);
} else {
final char[] padding = new char[pads];
final char[] padChars = padStr.toCharArray();
for (int i = 0; i < pads; i++) {
padding[i] = padChars[i % padLen];
}
return new String(padding).concat(str);
}
}
/**
* Gets a CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
*
* @param cs
* a CharSequence or {@code null}
* @return CharSequence length or {@code 0} if the CharSequence is
* {@code null}.
* @since 2.4
* @since 3.0 Changed signature from length(String) to length(CharSequence)
*/
public static int length(final CharSequence cs) {
return cs == null ? 0 : cs.length();
}
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size {@code size}
* using the space character (' ').</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to {@code center(str, size, " ")}.</p>
*
* <pre>
* StringUtils.center(null, *) = null
* StringUtils.center("", 4) = " "
* StringUtils.center("ab", -1) = "ab"
* StringUtils.center("ab", 4) = " ab "
* StringUtils.center("abcd", 2) = "abcd"
* StringUtils.center("a", 4) = " a "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, {@code null} if null String input
*/
public static String center(final String str, final int size) {
return center(str, size, ' ');
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, ' ') = " "
* StringUtils.center("ab", -1, ' ') = "ab"
* StringUtils.center("ab", 4, ' ') = " ab "
* StringUtils.center("abcd", 2, ' ') = "abcd"
* StringUtils.center("a", 4, ' ') = " a "
* StringUtils.center("a", 4, 'y') = "yayy"
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padChar the character to pad the new String with
* @return centered String, {@code null} if null String input
* @since 2.0
*/
public static String center(String str, final int size, final char padChar) {
if (str == null || size <= 0) {
return str;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padChar);
str = rightPad(str, size, padChar);
return str;
}
/**
* <p>Centers a String in a larger String of size {@code size}.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A {@code null} String returns {@code null}.
* A negative size is treated as zero.</p>
*
* <pre>
* StringUtils.center(null, *, *) = null
* StringUtils.center("", 4, " ") = " "
* StringUtils.center("ab", -1, " ") = "ab"
* StringUtils.center("ab", 4, " ") = " ab "
* StringUtils.center("abcd", 2, " ") = "abcd"
* StringUtils.center("a", 4, " ") = " a "
* StringUtils.center("a", 4, "yz") = "yayz"
* StringUtils.center("abc", 7, null) = " abc "
* StringUtils.center("abc", 7, "") = " abc "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @param padStr the String to pad the new String with, must not be null or empty
* @return centered String, {@code null} if null String input
* @throws IllegalArgumentException if padStr is {@code null} or empty
*/
public static String center(String str, final int size, String padStr) {
if (str == null || size <= 0) {
return str;
}
if (isEmpty(padStr)) {
padStr = SPACE;
}
final int strLen = str.length();
final int pads = size - strLen;
if (pads <= 0) {
return str;
}
str = leftPad(str, strLen + pads / 2, padStr);
str = rightPad(str, size, padStr);
return str;
}
// Case conversion
//-----------------------------------------------------------------------
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null) = null
* StringUtils.upperCase("") = ""
* StringUtils.upperCase("aBc") = "ABC"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toUpperCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to upper case, may be null
* @return the upper cased String, {@code null} if null String input
*/
public static String upperCase(final String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* <p>Converts a String to upper case as per {@link String#toUpperCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.upperCase(null, Locale.ENGLISH) = null
* StringUtils.upperCase("", Locale.ENGLISH) = ""
* StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
* </pre>
*
* @param str the String to upper case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the upper cased String, {@code null} if null String input
* @since 2.5
*/
public static String upperCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toUpperCase(locale);
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null) = null
* StringUtils.lowerCase("") = ""
* StringUtils.lowerCase("aBc") = "abc"
* </pre>
*
* <p><strong>Note:</strong> As described in the documentation for {@link String#toLowerCase()},
* the result of this method is affected by the current locale.
* For platform-independent case transformations, the method {@link #lowerCase(String, Locale)}
* should be used with a specific locale (e.g. {@link Locale#ENGLISH}).</p>
*
* @param str the String to lower case, may be null
* @return the lower cased String, {@code null} if null String input
*/
public static String lowerCase(final String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* <p>Converts a String to lower case as per {@link String#toLowerCase(Locale)}.</p>
*
* <p>A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.lowerCase(null, Locale.ENGLISH) = null
* StringUtils.lowerCase("", Locale.ENGLISH) = ""
* StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
* </pre>
*
* @param str the String to lower case, may be null
* @param locale the locale that defines the case transformation rules, must not be null
* @return the lower cased String, {@code null} if null String input
* @since 2.5
*/
public static String lowerCase(final String str, final Locale locale) {
if (str == null) {
return null;
}
return str.toLowerCase(locale);
}
/**
* <p>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(final String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
final char firstChar = str.charAt(0);
if (Character.isTitleCase(firstChar)) {
// already capitalized
return str;
}
return new StringBuilder(strLen)
.append(Character.toTitleCase(firstChar))
.append(str.substring(1))
.toString();
}
/**
* <p>Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, {@code null} if null String input
* @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String)
* @see #capitalize(String)
* @since 2.0
*/
public static String uncapitalize(final String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
final char firstChar = str.charAt(0);
if (Character.isLowerCase(firstChar)) {
// already uncapitalized
return str;
}
return new StringBuilder(strLen)
.append(Character.toLowerCase(firstChar))
.append(str.substring(1))
.toString();
}
/**
* <p>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}.
* A {@code null} input String returns {@code null}.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in org.apache.commons.lang3.text.WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, {@code null} if null String input
*/
public static String swapCase(final String str) {
if (StringUtils.isEmpty(str)) {
return str;
}
final char[] buffer = str.toCharArray();
for (int i = 0; i < buffer.length; i++) {
final char ch = buffer[i];
if (Character.isUpperCase(ch)) {
buffer[i] = Character.toLowerCase(ch);
} else if (Character.isTitleCase(ch)) {
buffer[i] = Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
buffer[i] = Character.toUpperCase(ch);
}
}
return new String(buffer);
}
// Count matches
//-----------------------------------------------------------------------
/**
* <p>Counts how many times the substring appears in the larger string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", null) = 0
* StringUtils.countMatches("abba", "") = 0
* StringUtils.countMatches("abba", "a") = 2
* StringUtils.countMatches("abba", "ab") = 1
* StringUtils.countMatches("abba", "xxx") = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param sub the substring to count, may be null
* @return the number of occurrences, 0 if either CharSequence is {@code null}
* @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence)
*/
public static int countMatches(final CharSequence str, final CharSequence sub) {
if (isEmpty(str) || isEmpty(sub)) {
return 0;
}
int count = 0;
int idx = 0;
while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) {
count++;
idx += sub.length();
}
return count;
}
/**
* <p>Counts how many times the char appears in the given string.</p>
*
* <p>A {@code null} or empty ("") String input returns {@code 0}.</p>
*
* <pre>
* StringUtils.countMatches(null, *) = 0
* StringUtils.countMatches("", *) = 0
* StringUtils.countMatches("abba", 0) = 0
* StringUtils.countMatches("abba", 'a') = 2
* StringUtils.countMatches("abba", 'b') = 2
* StringUtils.countMatches("abba", 'x') = 0
* </pre>
*
* @param str the CharSequence to check, may be null
* @param ch the char to count
* @return the number of occurrences, 0 if the CharSequence is {@code null}
* @since 3.4
*/
public static int countMatches(final CharSequence str, final char ch) {
if (isEmpty(str)) {
return 0;
}
int count = 0;
// We could also call str.toCharArray() for faster look ups but that would generate more garbage.
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
count++;
}
}
return count;
}
// Character Tests
//-----------------------------------------------------------------------
/**
* <p>Checks if the CharSequence contains only Unicode letters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlpha(null) = false
* StringUtils.isAlpha("") = false
* StringUtils.isAlpha(" ") = false
* StringUtils.isAlpha("abc") = true
* StringUtils.isAlpha("ab2c") = false
* StringUtils.isAlpha("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, and is non-null
* @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlpha(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetter(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters and
* space (' ').</p>
*
* <p>{@code null} will return {@code false}
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphaSpace(null) = false
* StringUtils.isAlphaSpace("") = true
* StringUtils.isAlphaSpace(" ") = true
* StringUtils.isAlphaSpace("abc") = true
* StringUtils.isAlphaSpace("ab c") = true
* StringUtils.isAlphaSpace("ab2c") = false
* StringUtils.isAlphaSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters and space,
* and is non-null
* @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence)
*/
public static boolean isAlphaSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters or digits.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAlphanumeric(null) = false
* StringUtils.isAlphanumeric("") = false
* StringUtils.isAlphanumeric(" ") = false
* StringUtils.isAlphanumeric("abc") = true
* StringUtils.isAlphanumeric("ab c") = false
* StringUtils.isAlphanumeric("ab2c") = true
* StringUtils.isAlphanumeric("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters or digits,
* and is non-null
* @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isAlphanumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetterOrDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode letters, digits
* or space ({@code ' '}).</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAlphanumericSpace(null) = false
* StringUtils.isAlphanumericSpace("") = true
* StringUtils.isAlphanumericSpace(" ") = true
* StringUtils.isAlphanumericSpace("abc") = true
* StringUtils.isAlphanumericSpace("ab c") = true
* StringUtils.isAlphanumericSpace("ab2c") = true
* StringUtils.isAlphanumericSpace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains letters, digits or space,
* and is non-null
* @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence)
*/
public static boolean isAlphanumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only ASCII printable characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isAsciiPrintable(null) = false
* StringUtils.isAsciiPrintable("") = true
* StringUtils.isAsciiPrintable(" ") = true
* StringUtils.isAsciiPrintable("Ceki") = true
* StringUtils.isAsciiPrintable("ab2c") = true
* StringUtils.isAsciiPrintable("!ab-c~") = true
* StringUtils.isAsciiPrintable("\u0020") = true
* StringUtils.isAsciiPrintable("\u0021") = true
* StringUtils.isAsciiPrintable("\u007e") = true
* StringUtils.isAsciiPrintable("\u007f") = false
* StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if every character is in the range
* 32 thru 126
* @since 2.1
* @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence)
*/
public static boolean isAsciiPrintable(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode digits.
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <p>Note that the method does not allow for a leading sign, either positive or negative.
* Also, if a String passes the numeric test, it may still generate a NumberFormatException
* when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range
* for int or long respectively.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = false
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* StringUtils.isNumeric("-123") = false
* StringUtils.isNumeric("+123") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode digits or space
* ({@code ' '}).
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isNumericSpace(null) = false
* StringUtils.isNumericSpace("") = true
* StringUtils.isNumericSpace(" ") = true
* StringUtils.isNumericSpace("123") = true
* StringUtils.isNumericSpace("12 3") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("\u0967\u0968 \u0969") = true
* StringUtils.isNumericSpace("ab2c") = false
* StringUtils.isNumericSpace("12-3") = false
* StringUtils.isNumericSpace("12.3") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits or space,
* and is non-null
* @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence)
*/
public static boolean isNumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only whitespace.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code true}.</p>
*
* <pre>
* StringUtils.isWhitespace(null) = false
* StringUtils.isWhitespace("") = true
* StringUtils.isWhitespace(" ") = true
* StringUtils.isWhitespace("abc") = false
* StringUtils.isWhitespace("ab2c") = false
* StringUtils.isWhitespace("ab-c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains whitespace, and is non-null
* @since 2.0
* @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence)
*/
public static boolean isWhitespace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only lowercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllLowerCase(null) = false
* StringUtils.isAllLowerCase("") = false
* StringUtils.isAllLowerCase(" ") = false
* StringUtils.isAllLowerCase("abc") = true
* StringUtils.isAllLowerCase("abC") = false
* StringUtils.isAllLowerCase("ab c") = false
* StringUtils.isAllLowerCase("ab1c") = false
* StringUtils.isAllLowerCase("ab/c") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains lowercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence)
*/
public static boolean isAllLowerCase(final CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isLowerCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only uppercase characters.</p>
*
* <p>{@code null} will return {@code false}.
* An empty String (length()=0) will return {@code false}.</p>
*
* <pre>
* StringUtils.isAllUpperCase(null) = false
* StringUtils.isAllUpperCase("") = false
* StringUtils.isAllUpperCase(" ") = false
* StringUtils.isAllUpperCase("ABC") = true
* StringUtils.isAllUpperCase("aBC") = false
* StringUtils.isAllUpperCase("A C") = false
* StringUtils.isAllUpperCase("A1C") = false
* StringUtils.isAllUpperCase("A/C") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains uppercase characters, and is non-null
* @since 2.5
* @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence)
*/
public static boolean isAllUpperCase(final CharSequence cs) {
if (cs == null || isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (Character.isUpperCase(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
// Defaults
//-----------------------------------------------------------------------
/**
* <p>Returns either the passed in String,
* or if the String is {@code null}, an empty String ("").</p>
*
* <pre>
* StringUtils.defaultString(null) = ""
* StringUtils.defaultString("") = ""
* StringUtils.defaultString("bat") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @return the passed in String, or the empty String if it
* was {@code null}
*/
public static String defaultString(final String str) {
return str == null ? EMPTY : str;
}
/**
* <p>Returns either the passed in String, or if the String is
* {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultString(null, "NULL") = "NULL"
* StringUtils.defaultString("", "NULL") = ""
* StringUtils.defaultString("bat", "NULL") = "bat"
* </pre>
*
* @see ObjectUtils#toString(Object,String)
* @see String#valueOf(Object)
* @param str the String to check, may be null
* @param defaultStr the default String to return
* if the input is {@code null}, may be null
* @return the passed in String, or the default if it was {@code null}
*/
public static String defaultString(final String str, final String defaultStr) {
return str == null ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultIfBlank(null, "NULL") = "NULL"
* StringUtils.defaultIfBlank("", "NULL") = "NULL"
* StringUtils.defaultIfBlank(" ", "NULL") = "NULL"
* StringUtils.defaultIfBlank("bat", "NULL") = "bat"
* StringUtils.defaultIfBlank("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is whitespace, empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) {
return isBlank(str) ? defaultStr : str;
}
/**
* <p>Returns either the passed in CharSequence, or if the CharSequence is
* empty or {@code null}, the value of {@code defaultStr}.</p>
*
* <pre>
* StringUtils.defaultIfEmpty(null, "NULL") = "NULL"
* StringUtils.defaultIfEmpty("", "NULL") = "NULL"
* StringUtils.defaultIfEmpty(" ", "NULL") = " "
* StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
* StringUtils.defaultIfEmpty("", null) = null
* </pre>
* @param <T> the specific kind of CharSequence
* @param str the CharSequence to check, may be null
* @param defaultStr the default CharSequence to return
* if the input is empty ("") or {@code null}, may be null
* @return the passed in CharSequence, or the default
* @see StringUtils#defaultString(String, String)
*/
public static <T extends CharSequence> T defaultIfEmpty(final T str, final T defaultStr) {
return isEmpty(str) ? defaultStr : str;
}
// Reversing
//-----------------------------------------------------------------------
/**
* <p>Reverses a String as per {@link StringBuilder#reverse()}.</p>
*
* <p>A {@code null} String returns {@code null}.</p>
*
* <pre>
* StringUtils.reverse(null) = null
* StringUtils.reverse("") = ""
* StringUtils.reverse("bat") = "tab"
* </pre>
*
* @param str the String to reverse, may be null
* @return the reversed String, {@code null} if null String input
*/
public static String reverse(final String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
/**
* <p>Reverses a String that is delimited by a specific character.</p>
*
* <p>The Strings between the delimiters are not reversed.
* Thus java.lang.String becomes String.lang.java (if the delimiter
* is {@code '.'}).</p>
*
* <pre>
* StringUtils.reverseDelimited(null, *) = null
* StringUtils.reverseDelimited("", *) = ""
* StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
* </pre>
*
* @param str the String to reverse, may be null
* @param separatorChar the separator character to use
* @return the reversed String, {@code null} if null String input
* @since 2.0
*/
public static String reverseDelimited(final String str, final char separatorChar) {
if (str == null) {
return null;
}
// could implement manually, but simple way is to reuse other,
// probably slower, methods.
final String[] strs = split(str, separatorChar);
ArrayUtils.reverse(strs);
return join(strs, separatorChar);
}
// Abbreviating
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:</p>
* <ul>
* <li>If the number of characters in {@code str} is less than or equal to
* {@code maxWidth}, return {@code str}.</li>
* <li>Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.</li>
* <li>If {@code maxWidth} is less than {@code 4}, throw an
* {@code IllegalArgumentException}.</li>
* <li>In no case will it return a String of length greater than
* {@code maxWidth}.</li>
* </ul>
*
* <pre>
* StringUtils.abbreviate(null, *) = null
* StringUtils.abbreviate("", 4) = ""
* StringUtils.abbreviate("abcdefg", 6) = "abc..."
* StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtils.abbreviate("abcdefg", 4) = "a..."
* StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, final int maxWidth) {
return abbreviate(str, 0, maxWidth);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like {@code abbreviate(String, int)}, but allows you to specify
* a "left edge" offset. Note that this left edge is not necessarily going to
* be the leftmost character in the result, or the first character following the
* ellipses, but it will appear somewhere in the result.
*
* <p>In no case will it return a String of length greater than
* {@code maxWidth}.</p>
*
* <pre>
* StringUtils.abbreviate(null, *, *) = null
* StringUtils.abbreviate("", 0, 4) = ""
* StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
*
* @param str the String to check, may be null
* @param offset left edge of source String
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, {@code null} if null String input
* @throws IllegalArgumentException if the width is too small
* @since 2.0
*/
public static String abbreviate(final String str, int offset, final int maxWidth) {
if (str == null) {
return null;
}
if (maxWidth < 4) {
throw new IllegalArgumentException("Minimum abbreviation width is 4");
}
if (str.length() <= maxWidth) {
return str;
}
if (offset > str.length()) {
offset = str.length();
}
if (str.length() - offset < maxWidth - 3) {
offset = str.length() - (maxWidth - 3);
}
final String abrevMarker = "...";
if (offset <= 4) {
return str.substring(0, maxWidth - 3) + abrevMarker;
}
if (maxWidth < 7) {
throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
}
if (offset + maxWidth - 3 < str.length()) {
return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3);
}
return abrevMarker + str.substring(str.length() - (maxWidth - 3));
}
/**
* <p>Abbreviates a String to the length passed, replacing the middle characters with the supplied
* replacement String.</p>
*
* <p>This abbreviation only occurs if the following criteria is met:</p>
* <ul>
* <li>Neither the String for abbreviation nor the replacement String are null or empty </li>
* <li>The length to truncate to is less than the length of the supplied String</li>
* <li>The length to truncate to is greater than 0</li>
* <li>The abbreviated String will have enough room for the length supplied replacement String
* and the first and last characters of the supplied String for abbreviation</li>
* </ul>
* <p>Otherwise, the returned String will be the same as the supplied String for abbreviation.
* </p>
*
* <pre>
* StringUtils.abbreviateMiddle(null, null, 0) = null
* StringUtils.abbreviateMiddle("abc", null, 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 0) = "abc"
* StringUtils.abbreviateMiddle("abc", ".", 3) = "abc"
* StringUtils.abbreviateMiddle("abcdef", ".", 4) = "ab.f"
* </pre>
*
* @param str the String to abbreviate, may be null
* @param middle the String to replace the middle characters with, may be null
* @param length the length to abbreviate {@code str} to.
* @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation.
* @since 2.5
*/
public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isEmpty(str) || isEmpty(middle)) {
return str;
}
if (length >= str.length() || length < middle.length()+2) {
return str;
}
final int targetSting = length-middle.length();
final int startOffset = targetSting/2+targetSting%2;
final int endOffset = str.length()-targetSting/2;
final StringBuilder builder = new StringBuilder(length);
builder.append(str.substring(0,startOffset));
builder.append(middle);
builder.append(str.substring(endOffset));
return builder.toString();
}
// Difference
//-----------------------------------------------------------------------
/**
* <p>Compares two Strings, and returns the portion where they differ.
* More precisely, return the remainder of the second String,
* starting from where it's different from the first. This means that
* the difference between "abc" and "ab" is the empty String and not "c". </p>
*
* <p>For example,
* {@code difference("i am a machine", "i am a robot") -> "robot"}.</p>
*
* <pre>
* StringUtils.difference(null, null) = null
* StringUtils.difference("", "") = ""
* StringUtils.difference("", "abc") = "abc"
* StringUtils.difference("abc", "") = ""
* StringUtils.difference("abc", "abc") = ""
* StringUtils.difference("abc", "ab") = ""
* StringUtils.difference("ab", "abxyz") = "xyz"
* StringUtils.difference("abcde", "abxyz") = "xyz"
* StringUtils.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 the first String, may be null
* @param str2 the second String, may be null
* @return the portion of str2 where it differs from str1; returns the
* empty String if they are equal
* @see #indexOfDifference(CharSequence,CharSequence)
* @since 2.0
*/
public static String difference(final String str1, final String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
final int at = indexOfDifference(str1, str2);
if (at == INDEX_NOT_FOUND) {
return EMPTY;
}
return str2.substring(at);
}
/**
* <p>Compares two CharSequences, and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* {@code indexOfDifference("i am a machine", "i am a robot") -> 7}</p>
*
* <pre>
* StringUtils.indexOfDifference(null, null) = -1
* StringUtils.indexOfDifference("", "") = -1
* StringUtils.indexOfDifference("", "abc") = 0
* StringUtils.indexOfDifference("abc", "") = 0
* StringUtils.indexOfDifference("abc", "abc") = -1
* StringUtils.indexOfDifference("ab", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "abxyz") = 2
* StringUtils.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param cs1 the first CharSequence, may be null
* @param cs2 the second CharSequence, may be null
* @return the index where cs1 and cs2 begin to differ; -1 if they are equal
* @since 2.0
* @since 3.0 Changed signature from indexOfDifference(String, String) to
* indexOfDifference(CharSequence, CharSequence)
*/
public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return INDEX_NOT_FOUND;
}
if (cs1 == null || cs2 == null) {
return 0;
}
int i;
for (i = 0; i < cs1.length() && i < cs2.length(); ++i) {
if (cs1.charAt(i) != cs2.charAt(i)) {
break;
}
}
if (i < cs2.length() || i < cs1.length()) {
return i;
}
return INDEX_NOT_FOUND;
}
/**
* <p>Compares all CharSequences in an array and returns the index at which the
* CharSequences begin to differ.</p>
*
* <p>For example,
* <code>indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7</code></p>
*
* <pre>
* StringUtils.indexOfDifference(null) = -1
* StringUtils.indexOfDifference(new String[] {}) = -1
* StringUtils.indexOfDifference(new String[] {"abc"}) = -1
* StringUtils.indexOfDifference(new String[] {null, null}) = -1
* StringUtils.indexOfDifference(new String[] {"", ""}) = -1
* StringUtils.indexOfDifference(new String[] {"", null}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
* StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
* StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
* StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
* StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
* StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
* StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
* StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
* </pre>
*
* @param css array of CharSequences, entries may be null
* @return the index where the strings begin to differ; -1 if they are all equal
* @since 2.4
* @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...)
*/
public static int indexOfDifference(final CharSequence... css) {
if (css == null || css.length <= 1) {
return INDEX_NOT_FOUND;
}
boolean anyStringNull = false;
boolean allStringsNull = true;
final int arrayLen = css.length;
int shortestStrLen = Integer.MAX_VALUE;
int longestStrLen = 0;
// find the min and max string lengths; this avoids checking to make
// sure we are not exceeding the length of the string each time through
// the bottom loop.
for (int i = 0; i < arrayLen; i++) {
if (css[i] == null) {
anyStringNull = true;
shortestStrLen = 0;
} else {
allStringsNull = false;
shortestStrLen = Math.min(css[i].length(), shortestStrLen);
longestStrLen = Math.max(css[i].length(), longestStrLen);
}
}
// handle lists containing all nulls or all empty strings
if (allStringsNull || longestStrLen == 0 && !anyStringNull) {
return INDEX_NOT_FOUND;
}
// handle lists containing some nulls or some empty strings
if (shortestStrLen == 0) {
return 0;
}
// find the position with the first difference across all strings
int firstDiff = -1;
for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) {
final char comparisonChar = css[0].charAt(stringPos);
for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) {
if (css[arrayPos].charAt(stringPos) != comparisonChar) {
firstDiff = stringPos;
break;
}
}
if (firstDiff != -1) {
break;
}
}
if (firstDiff == -1 && shortestStrLen != longestStrLen) {
// we compared all of the characters up to the length of the
// shortest string and didn't find a match, but the string lengths
// vary, so return the length of the shortest string.
return shortestStrLen;
}
return firstDiff;
}
/**
* <p>Compares all Strings in an array and returns the initial sequence of
* characters that is common to all of them.</p>
*
* <p>For example,
* <code>getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "</code></p>
*
* <pre>
* StringUtils.getCommonPrefix(null) = ""
* StringUtils.getCommonPrefix(new String[] {}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"", null}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
* StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
* StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
* StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
* StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
* StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
* StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
* StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
* </pre>
*
* @param strs array of String objects, entries may be null
* @return the initial sequence of characters that are common to all Strings
* in the array; empty String if the array is null, the elements are all null
* or if there is no common prefix.
* @since 2.4
*/
public static String getCommonPrefix(final String... strs) {
if (strs == null || strs.length == 0) {
return EMPTY;
}
final int smallestIndexOfDiff = indexOfDifference(strs);
if (smallestIndexOfDiff == INDEX_NOT_FOUND) {
// all strings were identical
if (strs[0] == null) {
return EMPTY;
}
return strs[0];
} else if (smallestIndexOfDiff == 0) {
// there were no common initial characters
return EMPTY;
} else {
// we found a common initial character sequence
return strs[0].substring(0, smallestIndexOfDiff);
}
}
// Misc
//-----------------------------------------------------------------------
/**
* <p>Find the Levenshtein distance between two Strings.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>The previous implementation of the Levenshtein distance algorithm
* was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
* which can occur when my Java implementation is used with very large strings.<br>
* This implementation of the Levenshtein distance algorithm
* is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","") = 0
* StringUtils.getLevenshteinDistance("","a") = 1
* StringUtils.getLevenshteinDistance("aaapppp", "") = 7
* StringUtils.getLevenshteinDistance("frog", "fog") = 1
* StringUtils.getLevenshteinDistance("fly", "ant") = 3
* StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
* StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
* StringUtils.getLevenshteinDistance("hello", "hallo") = 1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.0 Changed signature from getLevenshteinDistance(String, String) to
* getLevenshteinDistance(CharSequence, CharSequence)
*/
public static int getLevenshteinDistance(CharSequence s, CharSequence t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
/*
The difference between this impl. and the previous is that, rather
than creating and retaining a matrix of size s.length() + 1 by t.length() + 1,
we maintain two single-dimensional arrays of length s.length() + 1. The first, d,
is the 'current working' distance array that maintains the newest distance cost
counts as we iterate through the characters of String s. Each time we increment
the index of String t we are comparing, d is copied to p, the second int[]. Doing so
allows us to retain the previous cost counts as required by the algorithm (taking
the minimum of the cost count to the left, up one, and diagonally up and to the left
of the current cost count being calculated). (Note that the arrays aren't really
copied anymore, just switched...this is clearly much better than cloning an array
or doing a System.arraycopy() each time through the outer loop.)
Effectively, the difference between the two implementations is this one does not
cause an out of memory condition when calculating the LD over two very large strings.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
if (n > m) {
// swap the input strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1]; //'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i <= n; i++) {
p[i] = i;
}
for (j = 1; j <= m; j++) {
t_j = t.charAt(j - 1);
d[0] = j;
for (i = 1; i <= n; i++) {
cost = s.charAt(i - 1) == t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
/**
* <p>Find the Levenshtein distance between two Strings if it's less than or equal to a given
* threshold.</p>
*
* <p>This is the number of changes needed to change one String into
* another, where each change is a single character modification (deletion,
* insertion or substitution).</p>
*
* <p>This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield
* and Chas Emerick's implementation of the Levenshtein distance algorithm from
* <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
*
* <pre>
* StringUtils.getLevenshteinDistance(null, *, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, null, *) = IllegalArgumentException
* StringUtils.getLevenshteinDistance(*, *, -1) = IllegalArgumentException
* StringUtils.getLevenshteinDistance("","", 0) = 0
* StringUtils.getLevenshteinDistance("aaapppp", "", 8) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 7) = 7
* StringUtils.getLevenshteinDistance("aaapppp", "", 6)) = -1
* StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
* StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
* StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
* StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
* </pre>
*
* @param s the first String, must not be null
* @param t the second String, must not be null
* @param threshold the target threshold, must not be negative
* @return result distance, or {@code -1} if the distance would be greater than the threshold
* @throws IllegalArgumentException if either String input {@code null} or negative threshold
*/
public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
if (threshold < 0) {
throw new IllegalArgumentException("Threshold must not be negative");
}
/*
This implementation only computes the distance if it's less than or equal to the
threshold value, returning -1 if it's greater. The advantage is performance: unbounded
distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only
computing a diagonal stripe of width 2k + 1 of the cost table.
It is also possible to use this to compute the unbounded Levenshtein distance by starting
the threshold at 1 and doubling each time until the distance is found; this is O(dm), where
d is the distance.
One subtlety comes from needing to ignore entries on the border of our stripe
eg.
p[] = |#|#|#|*
d[] = *|#|#|#|
We must ignore the entry to the left of the leftmost member
We must ignore the entry above the rightmost member
Another subtlety comes from our stripe running off the matrix if the strings aren't
of the same size. Since string s is always swapped to be the shorter of the two,
the stripe will always run off to the upper right instead of the lower left of the matrix.
As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1.
In this case we're going to walk a stripe of length 3. The matrix would look like so:
1 2 3 4 5
1 |#|#| | | |
2 |#|#|#| | |
3 | |#|#|#| |
4 | | |#|#|#|
5 | | | |#|#|
6 | | | | |#|
7 | | | | | |
Note how the stripe leads off the table as there is no possible way to turn a string of length 5
into one of length 7 in edit distance of 1.
Additionally, this implementation decreases memory usage by using two
single-dimensional arrays and swapping them back and forth instead of allocating
an entire n by m matrix. This requires a few minor changes, such as immediately returning
when it's detected that the stripe has run off the matrix and initially filling the arrays with
large values so that entries we don't compute are ignored.
See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion.
*/
int n = s.length(); // length of s
int m = t.length(); // length of t
// if one string is empty, the edit distance is necessarily the length of the other
if (n == 0) {
return m <= threshold ? m : -1;
} else if (m == 0) {
return n <= threshold ? n : -1;
}
if (n > m) {
// swap the two strings to consume less memory
final CharSequence tmp = s;
s = t;
t = tmp;
n = m;
m = t.length();
}
int p[] = new int[n + 1]; // 'previous' cost array, horizontally
int d[] = new int[n + 1]; // cost array, horizontally
int _d[]; // placeholder to assist in swapping p and d
// fill in starting table values
final int boundary = Math.min(n, threshold) + 1;
for (int i = 0; i < boundary; i++) {
p[i] = i;
}
// these fills ensure that the value above the rightmost entry of our
// stripe will be ignored in following loop iterations
Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE);
Arrays.fill(d, Integer.MAX_VALUE);
// iterates through t
for (int j = 1; j <= m; j++) {
final char t_j = t.charAt(j - 1); // jth character of t
d[0] = j;
// compute stripe indices, constrain to array size
final int min = Math.max(1, j - threshold);
final int max = (j > Integer.MAX_VALUE - threshold) ? n : Math.min(n, j + threshold);
// the stripe may lead off of the table if s and t are of different sizes
if (min > max) {
return -1;
}
// ignore entry left of leftmost
if (min > 1) {
d[min - 1] = Integer.MAX_VALUE;
}
// iterates through [min, max] in s
for (int i = min; i <= max; i++) {
if (s.charAt(i - 1) == t_j) {
// diagonally left and up
d[i] = p[i - 1];
} else {
// 1 + minimum of cell to the left, to the top, diagonally left and up
d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]);
}
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// if p[n] is greater than the threshold, there's no guarantee on it being the correct
// distance
if (p[n] <= threshold) {
return p[n];
}
return -1;
}
/**
* <p>Find the Jaro Winkler Distance which indicates the similarity score between two Strings.</p>
*
* <p>The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters.
* Winkler increased this measure for matching initial characters.</p>
*
* <p>This implementation is based on the Jaro Winkler similarity algorithm
* from <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance">http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>.</p>
*
* <pre>
* StringUtils.getJaroWinklerDistance(null, null) = IllegalArgumentException
* StringUtils.getJaroWinklerDistance("","") = 0.0
* StringUtils.getJaroWinklerDistance("","a") = 0.0
* StringUtils.getJaroWinklerDistance("aaapppp", "") = 0.0
* StringUtils.getJaroWinklerDistance("frog", "fog") = 0.93
* StringUtils.getJaroWinklerDistance("fly", "ant") = 0.0
* StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
* StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
* StringUtils.getJaroWinklerDistance("hello", "hallo") = 0.88
* StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.91
* StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.93
* StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.94
* StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA") = 0.9
* </pre>
*
* @param first the first String, must not be null
* @param second the second String, must not be null
* @return result distance
* @throws IllegalArgumentException if either String input {@code null}
* @since 3.3
*/
public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) {
final double DEFAULT_SCALING_FACTOR = 0.1;
if (first == null || second == null) {
throw new IllegalArgumentException("Strings must not be null");
}
final double jaro = score(first,second);
final int cl = commonPrefixLength(first, second);
final double matchScore = Math.round((jaro + (DEFAULT_SCALING_FACTOR * cl * (1.0 - jaro))) *100.0)/100.0;
return matchScore;
}
/**
* This method returns the Jaro-Winkler score for string matching.
* @param first the first string to be matched
* @param second the second string to be machted
* @return matching score without scaling factor impact
*/
private static double score(final CharSequence first, final CharSequence second) {
String shorter;
String longer;
// Determine which String is longer.
if (first.length() > second.length()) {
longer = first.toString().toLowerCase();
shorter = second.toString().toLowerCase();
} else {
longer = second.toString().toLowerCase();
shorter = first.toString().toLowerCase();
}
// Calculate the half length() distance of the shorter String.
final int halflength = (shorter.length() / 2) + 1;
// Find the set of matching characters between the shorter and longer strings. Note that
// the set of matching characters may be different depending on the order of the strings.
final String m1 = getSetOfMatchingCharacterWithin(shorter, longer, halflength);
final String m2 = getSetOfMatchingCharacterWithin(longer, shorter, halflength);
// If one or both of the sets of common characters is empty, then
// there is no similarity between the two strings.
if (m1.length() == 0 || m2.length() == 0) {
return 0.0;
}
// If the set of common characters is not the same size, then
// there is no similarity between the two strings, either.
if (m1.length() != m2.length()) {
return 0.0;
}
// Calculate the number of transposition between the two sets
// of common characters.
final int transpositions = transpositions(m1, m2);
// Calculate the distance.
final double dist =
(m1.length() / ((double)shorter.length()) +
m2.length() / ((double)longer.length()) +
(m1.length() - transpositions) / ((double)m1.length())) / 3.0;
return dist;
}
/**
* <p>Find the Fuzzy Distance which indicates the similarity score between two Strings.</p>
*
* <p>This string matching algorithm is similar to the algorithms of editors such as Sublime Text,
* TextMate, Atom and others. One point is given for every matched character. Subsequent
* matches yield two bonus points. A higher score indicates a higher similarity.</p>
*
* <pre>
* StringUtils.getFuzzyDistance(null, null, null) = IllegalArgumentException
* StringUtils.getFuzzyDistance("", "", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH) = 0
* StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH) = 1
* StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH) = 2
* StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH) = 4
* StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
* </pre>
*
* @param term a full term that should be matched against, must not be null
* @param query the query that will be matched against a term, must not be null
* @param locale This string matching logic is case insensitive. A locale is necessary to normalize
* both Strings to lower case.
* @return result score
* @throws IllegalArgumentException if either String input {@code null} or Locale input {@code null}
* @since 3.4
*/
public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) {
if (term == null || query == null) {
throw new IllegalArgumentException("Strings must not be null");
} else if (locale == null) {
throw new IllegalArgumentException("Locale must not be null");
}
// fuzzy logic is case insensitive. We normalize the Strings to lower
// case right from the start. Turning characters to lower case
// via Character.toLowerCase(char) is unfortunately insufficient
// as it does not accept a locale.
final String termLowerCase = term.toString().toLowerCase(locale);
final String queryLowerCase = query.toString().toLowerCase(locale);
// the resulting score
int score = 0;
// the position in the term which will be scanned next for potential
// query character matches
int termIndex = 0;
// index of the previously matched character in the term
int previousMatchingCharacterIndex = Integer.MIN_VALUE;
for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
final char queryChar = queryLowerCase.charAt(queryIndex);
boolean termCharacterMatchFound = false;
for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) {
final char termChar = termLowerCase.charAt(termIndex);
if (queryChar == termChar) {
// simple character matches result in one point
score++;
// subsequent character matches further improve
// the score.
if (previousMatchingCharacterIndex + 1 == termIndex) {
score += 2;
}
previousMatchingCharacterIndex = termIndex;
// we can leave the nested loop. Every character in the
// query can match at most one character in the term.
termCharacterMatchFound = true;
}
}
}
return score;
}
/**
* Gets a set of matching characters between two strings.
*
* <p><Two characters from the first string and the second string are considered matching if the character's
* respective positions are no farther than the limit value.</p>
*
* @param first The first string.
* @param second The second string.
* @param limit The maximum distance to consider.
* @return A string contain the set of common characters.
*/
private static String getSetOfMatchingCharacterWithin(final CharSequence first, final CharSequence second, final int limit) {
final StringBuilder common = new StringBuilder();
final StringBuilder copy = new StringBuilder(second);
for (int i = 0; i < first.length(); i++) {
final char ch = first.charAt(i);
boolean found = false;
// See if the character is within the limit positions away from the original position of that character.
for (int j = Math.max(0, i - limit); !found && j < Math.min(i + limit, second.length()); j++) {
if (copy.charAt(j) == ch) {
found = true;
common.append(ch);
copy.setCharAt(j,'*');
}
}
}
return common.toString();
}
/**
* Calculates the number of transposition between two strings.
* @param first The first string.
* @param second The second string.
* @return The number of transposition between the two strings.
*/
private static int transpositions(final CharSequence first, final CharSequence second) {
int transpositions = 0;
for (int i = 0; i < first.length(); i++) {
if (first.charAt(i) != second.charAt(i)) {
transpositions++;
}
}
return transpositions / 2;
}
/**
* Calculates the number of characters from the beginning of the strings that match exactly one-to-one,
* up to a maximum of four (4) characters.
* @param first The first string.
* @param second The second string.
* @return A number between 0 and 4.
*/
private static int commonPrefixLength(final CharSequence first, final CharSequence second) {
final int result = getCommonPrefix(first.toString(), second.toString()).length();
// Limit the result to 4.
return result > 4 ? 4 : result;
}
// startsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.startsWith(null, null) = true
* StringUtils.startsWith(null, "abc") = false
* StringUtils.startsWith("abcdef", null) = false
* StringUtils.startsWith("abcdef", "abc") = true
* StringUtils.startsWith("ABCDEF", "abc") = false
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence)
*/
public static boolean startsWith(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, false);
}
/**
* <p>Case insensitive check if a CharSequence starts with a specified prefix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.startsWithIgnoreCase(null, null) = true
* StringUtils.startsWithIgnoreCase(null, "abc") = false
* StringUtils.startsWithIgnoreCase("abcdef", null) = false
* StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @return {@code true} if the CharSequence starts with the prefix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) {
return startsWith(str, prefix, true);
}
/**
* <p>Check if a CharSequence starts with a specified prefix (optionally case insensitive).</p>
*
* @see java.lang.String#startsWith(String)
* @param str the CharSequence to check, may be null
* @param prefix the prefix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) {
if (str == null || prefix == null) {
return str == null && prefix == null;
}
if (prefix.length() > str.length()) {
return false;
}
return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length());
}
/**
* <p>Check if a CharSequence starts with any of an array of specified strings.</p>
*
* <pre>
* StringUtils.startsWithAny(null, null) = false
* StringUtils.startsWithAny(null, new String[] {"abc"}) = false
* StringUtils.startsWithAny("abcxyz", null) = false
* StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
* StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
* StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* </pre>
*
* @param string the CharSequence to check, may be null
* @param searchStrings the CharSequences to find, may be null or empty
* @return {@code true} if the CharSequence starts with any of the the prefixes, case insensitive, or
* both {@code null}
* @since 2.5
* @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
*/
public static boolean startsWithAny(final CharSequence string, final CharSequence... searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (startsWith(string, searchString)) {
return true;
}
}
return false;
}
// endsWith
//-----------------------------------------------------------------------
/**
* <p>Check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.endsWith(null, null) = true
* StringUtils.endsWith(null, "def") = false
* StringUtils.endsWith("abcdef", null) = false
* StringUtils.endsWith("abcdef", "def") = true
* StringUtils.endsWith("ABCDEF", "def") = false
* StringUtils.endsWith("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case sensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence)
*/
public static boolean endsWith(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, false);
}
/**
* <p>Case insensitive check if a CharSequence ends with a specified suffix.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case insensitive.</p>
*
* <pre>
* StringUtils.endsWithIgnoreCase(null, null) = true
* StringUtils.endsWithIgnoreCase(null, "def") = false
* StringUtils.endsWithIgnoreCase("abcdef", null) = false
* StringUtils.endsWithIgnoreCase("abcdef", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
* StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
* </pre>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @return {@code true} if the CharSequence ends with the suffix, case insensitive, or
* both {@code null}
* @since 2.4
* @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence)
*/
public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) {
return endsWith(str, suffix, true);
}
/**
* <p>Check if a CharSequence ends with a specified suffix (optionally case insensitive).</p>
*
* @see java.lang.String#endsWith(String)
* @param str the CharSequence to check, may be null
* @param suffix the suffix to find, may be null
* @param ignoreCase indicates whether the compare should ignore case
* (case insensitive) or not.
* @return {@code true} if the CharSequence starts with the prefix or
* both {@code null}
*/
private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) {
if (str == null || suffix == null) {
return str == null && suffix == null;
}
if (suffix.length() > str.length()) {
return false;
}
final int strOffset = str.length() - suffix.length();
return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length());
}
/**
* <p>
* Similar to <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize
* -space</a>
* </p>
* <p>
* The function returns the argument string with whitespace normalized by using
* <code>{@link #trim(String)}</code> to remove leading and trailing whitespace
* and then replacing sequences of whitespace characters by a single space.
* </p>
* In XML Whitespace characters are the same as those allowed by the <a
* href="http://www.w3.org/TR/REC-xml/#NT-S">S</a> production, which is S ::= (#x20 | #x9 | #xD | #xA)+
* <p>
* Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r]
*
* <p>For reference:</p>
* <ul>
* <li>\x0B = vertical tab</li>
* <li>\f = #xC = form feed</li>
* <li>#x20 = space</li>
* <li>#x9 = \t</li>
* <li>#xA = \n</li>
* <li>#xD = \r</li>
* </ul>
*
* <p>
* The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also
* normalize. Additionally <code>{@link #trim(String)}</code> removes control characters (char <= 32) from both
* ends of this String.
* </p>
*
* @see Pattern
* @see #trim(String)
* @see <a
* href="http://www.w3.org/TR/xpath/#function-normalize-space">http://www.w3.org/TR/xpath/#function-normalize-space</a>
* @param str the source String to normalize whitespaces from, may be null
* @return the modified string with whitespace normalized, {@code null} if null String input
*
* @since 3.0
*/
public static String normalizeSpace(final String str) {
// LANG-1020: Improved performance significantly by normalizing manually instead of using regex
// See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test
if (isEmpty(str)) {
return str;
}
final int size = str.length();
final char[] newChars = new char[size];
int count = 0;
int whitespacesCount = 0;
boolean startWhitespaces = true;
for (int i = 0; i < size; i++) {
char actualChar = str.charAt(i);
boolean isWhitespace = Character.isWhitespace(actualChar);
if (!isWhitespace) {
startWhitespaces = false;
newChars[count++] = (actualChar == 160 ? 32 : actualChar);
whitespacesCount = 0;
} else {
if (whitespacesCount == 0 && !startWhitespaces) {
newChars[count++] = SPACE.charAt(0);
}
whitespacesCount++;
}
}
if (startWhitespaces) {
return EMPTY;
}
return new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0));
}
/**
* <p>Check if a CharSequence ends with any of an array of specified strings.</p>
*
* <pre>
* StringUtils.endsWithAny(null, null) = false
* StringUtils.endsWithAny(null, new String[] {"abc"}) = false
* StringUtils.endsWithAny("abcxyz", null) = false
* StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
* StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
* </pre>
*
* @param string the CharSequence to check, may be null
* @param searchStrings the CharSequences to find, may be null or empty
* @return {@code true} if the CharSequence ends with any of the the prefixes, case insensitive, or
* both {@code null}
* @since 3.0
*/
public static boolean endsWithAny(final CharSequence string, final CharSequence... searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (final CharSequence searchString : searchStrings) {
if (endsWith(string, searchString)) {
return true;
}
}
return false;
}
/**
* Appends the suffix to the end of the string if the string does not
* already end in the suffix.
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param suffixes Additional suffixes that are valid terminators (optional).
*
* @return A new String if suffix was appened, the same string otherwise.
*/
private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) {
if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) {
return str;
}
if (suffixes != null && suffixes.length > 0) {
for (final CharSequence s : suffixes) {
if (endsWith(str, s, ignoreCase)) {
return str;
}
}
}
return str + suffix.toString();
}
/**
* Appends the suffix to the end of the string if the string does not
* already end with any the suffixes.
*
* <pre>
* StringUtils.appendIfMissing(null, null) = null
* StringUtils.appendIfMissing("abc", null) = "abc"
* StringUtils.appendIfMissing("", "xyz") = "xyz"
* StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissing(null, null, null) = null
* StringUtils.appendIfMissing("abc", null, null) = "abc"
* StringUtils.appendIfMissing("", "xyz", null) = "xyz"
* StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
* StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appened, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, false, suffixes);
}
/**
* Appends the suffix to the end of the string if the string does not
* already end, case insensitive, with any of the suffixes.
*
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
* </pre>
* <p>With additional suffixes,</p>
* <pre>
* StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
* StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
* StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
* StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
* StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
* StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
* </pre>
*
* @param str The string.
* @param suffix The suffix to append to the end of the string.
* @param suffixes Additional suffixes that are valid terminators.
*
* @return A new String if suffix was appened, the same string otherwise.
*
* @since 3.2
*/
public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) {
return appendIfMissing(str, suffix, true, suffixes);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param ignoreCase Indicates whether the compare should ignore case.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*/
private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) {
if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) {
return str;
}
if (prefixes != null && prefixes.length > 0) {
for (final CharSequence p : prefixes) {
if (startsWith(str, p, ignoreCase)) {
return str;
}
}
}
return prefix.toString() + str;
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissing(null, null) = null
* StringUtils.prependIfMissing("abc", null) = "abc"
* StringUtils.prependIfMissing("", "xyz") = "xyz"
* StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissing(null, null, null) = null
* StringUtils.prependIfMissing("abc", null, null) = "abc"
* StringUtils.prependIfMissing("", "xyz", null) = "xyz"
* StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
* StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid.
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, false, prefixes);
}
/**
* Prepends the prefix to the start of the string if the string does not
* already start, case insensitive, with any of the prefixes.
*
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
* </pre>
* <p>With additional prefixes,</p>
* <pre>
* StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
* StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
* StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
* StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
* StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
* StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
* StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
* </pre>
*
* @param str The string.
* @param prefix The prefix to prepend to the start of the string.
* @param prefixes Additional prefixes that are valid (optional).
*
* @return A new String if prefix was prepended, the same string otherwise.
*
* @since 3.2
*/
public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) {
return prependIfMissing(str, prefix, true, prefixes);
}
/**
* Converts a <code>byte[]</code> to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charsetName
* the encoding to use, if null then use the platform default
* @return a new String
* @throws UnsupportedEncodingException
* If the named charset is not supported
* @throws NullPointerException
* if the input is null
* @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code
* @since 3.1
*/
@Deprecated
public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException {
return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset());
}
/**
* Converts a <code>byte[]</code> to a String using the specified character encoding.
*
* @param bytes
* the byte array to read from
* @param charset
* the encoding to use, if null then use the platform default
* @return a new String
* @throws NullPointerException
* if {@code bytes} is null
* @since 3.2
* @since 3.3 No longer throws {@link UnsupportedEncodingException}.
*/
public static String toEncodedString(final byte[] bytes, final Charset charset) {
return new String(bytes, charset != null ? charset : Charset.defaultCharset());
}
/**
* <p>
* Wraps a string with a char.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", '\0') = "ab"
* StringUtils.wrap("ab", 'x') = "xabx"
* StringUtils.wrap("ab", '\'') = "'ab'"
* StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\""
* </pre>
*
* @param str
* the string to be wrapped, may be {@code null}
* @param wrapWith
* the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null}
* @since 3.4
*/
public static String wrap(final String str, final char wrapWith) {
if (isEmpty(str) || wrapWith == '\0') {
return str;
}
return wrapWith + str + wrapWith;
}
/**
* <p>
* Wraps a String with another String.
* </p>
*
* <p>
* A {@code null} input String returns {@code null}.
* </p>
*
* <pre>
* StringUtils.wrap(null, *) = null
* StringUtils.wrap("", *) = ""
* StringUtils.wrap("ab", null) = "ab"
* StringUtils.wrap("ab", "x") = "xabx"
* StringUtils.wrap("ab", "\"") = "\"ab\""
* StringUtils.wrap("\"ab\"", "\"") = "\"\"ab\"\""
* StringUtils.wrap("ab", "'") = "'ab'"
* StringUtils.wrap("'abcd'", "'") = "''abcd''"
* StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
* StringUtils.wrap("'abcd'", "\"") = "\"'abcd'\""
* </pre>
*
* @param str
* the String to be wrapper, may be null
* @param wrapWith
* the String that will wrap str
* @return wrapped String, {@code null} if null String input
* @since 3.4
*/
public static String wrap(final String str, final String wrapWith) {
if (isEmpty(str) || isEmpty(wrapWith)) {
return str;
}
return wrapWith.concat(str).concat(wrapWith);
}
}
| [
"giachi.iada@gmail.com"
] | giachi.iada@gmail.com |
49e20dd8ee4cf357be7c5a9a0db4282e5e2dedfe | 35af39ed46a4841923116f44e9fa62e5fc53d7d8 | /src/com/Lbins/cpy/util/StringUtil.java | 70d4b64b821358ab084d60a391926e56e16d480e | [] | no_license | eryiyi/CpCloudApp | e45985a9876e0e303339f45c0b1397116815a8db | b1602c447a401a4c843147186073e24022078c5c | refs/heads/master | 2021-01-17T17:19:04.956312 | 2016-08-09T08:33:44 | 2016-08-09T08:33:44 | 65,277,786 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,300 | java | package com.Lbins.cpy.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 1.二进制转换为十六进制
* 2.E-mail 检测
* 3.URL检测
* 4.text是否包含空字符串
* 5.添加对象数组
*
* @author dds
*/
public class StringUtil {
//判断是否为JSOn格式
public static boolean isJson(String json) {
if (StringUtil.isNullOrEmpty(json)) {
return false;
}
try {
new JsonParser().parse(json);
return true;
} catch (JsonParseException e) {
return false;
}
}
/**
* 方法描述:取得当前日期的上月或下月日期 ,amount=-1为上月日期,amount=1为下月日期;创建人:jya
*
* @return
* @throws Exception
*/
public static String getFrontBackStrDate(String strDate, String format, int amount) throws Exception {
if (null == strDate) {
return null;
}
try {
DateFormat fmt = new SimpleDateFormat(format);
Calendar c = Calendar.getInstance();
c.setTime(fmt.parse(strDate));
c.add(Calendar.MONTH, amount);
return fmt.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().isEmpty();
}
/**
* 添加对象数组
*
* @param spliter 间隔符
* @param arr 数组
* @return
*/
public static String join(String spliter, Object[] arr) {
if (arr == null || arr.length == 0) {
return "";
}
if (spliter == null) {
spliter = "";
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
break;
}
if (arr[i] == null) {
continue;
}
builder.append(arr[i].toString());
builder.append(spliter);
}
return builder.toString();
}
/**
* java去除字符串中的空格、回车、换行符、制表符
*/
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 生成32位编码
*
* @return string
*/
public static String getUUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static byte[] getBytes(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
//通过传入图片url获取位图方法
public static Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public static final String distanceCon(String latStr1, String lngStr1, String latStr2, String lngStr2) {
LatLng lat1 = new LatLng(Double.valueOf(latStr1), Double.valueOf(lngStr1));
LatLng lat2 = new LatLng(Double.valueOf(latStr2), Double.valueOf(lngStr2));
float dis = AMapUtils.calculateLineDistance(lat1, lat2);
dis = dis / 1000;
return String.valueOf(dis);
}
/**
* 计算两点之间距离
*
* @param start
* @param end
* @return 米
*/
public static String getDistance(LatLng start, LatLng end) {
double lat1 = (Math.PI / 180) * start.latitude;
double lat2 = (Math.PI / 180) * end.latitude;
double lon1 = (Math.PI / 180) * start.longitude;
double lon2 = (Math.PI / 180) * end.longitude;
// double Lat1r = (Math.PI/180)*(gp1.getLatitudeE6()/1E6);
// double Lat2r = (Math.PI/180)*(gp2.getLatitudeE6()/1E6);
// double Lon1r = (Math.PI/180)*(gp1.getLongitudeE6()/1E6);
// double Lon2r = (Math.PI/180)*(gp2.getLongitudeE6()/1E6);
//地球半径
double R = 6371;
//两点间距离 km,如果想要米的话,结果*1000就可以了
double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
DecimalFormat df = new DecimalFormat("0.00");
return df.format(d);
}
public static String valuteNumber(String str) {
Pattern p = Pattern.compile("[0-9\\.]+");
Matcher m = p.matcher(str);
String string = "";
while (m.find()) {
string += m.group();
}
return string;
}
public static String getLocalIpAddress(Context context) {
// WifiManager wifimanage=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);//获取WifiManager
// if(!wifimanage.isWifiEnabled()) {
// wifimanage.setWifiEnabled(true);
// }
// WifiInfo wifiinfo= wifimanage.getConnectionInfo();
// String ip=intToIp(wifiinfo.getIpAddress());
// return ip;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements();) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
public static String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
public static String getSignWx(String strA){
return MD5Util.getMD5ofStr(strA).toUpperCase();
}
}
| [
"826321978@qq.com"
] | 826321978@qq.com |
480215bcce146bf77c1fb976a767d561e62484ff | 8bcc9e66b5b2584eb00a26cd9c5e05bd2c22b613 | /Networking/src/nebulous/Client.java | 31448a26139aecb22ea651f08628072322cbcec3 | [] | no_license | Nebulous03/BensJavaDev | 8ed2b0bb4879995359a70bdfe7d0f9347c949fed | f19c72c21221ee9f4ffae2044ff948f816914dce | refs/heads/master | 2021-06-12T14:00:52.935631 | 2017-02-11T16:53:24 | 2017-02-11T16:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,223 | java | package nebulous;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
private Socket socket;
private String username;
private short uuid;
private DataInputStream inputStream;
private DataOutputStream outputStream;
public Client(Socket socket){
this.socket = socket;
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
// TEMP - Will be added to dependent client class
public void send(String message){
try {
byte[] bytes = message.getBytes();
outputStream.writeInt(bytes.length);
outputStream.write(bytes);
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect(){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Socket getSocket(){
return socket;
}
public String getUsername() {
return username;
}
public DataInputStream getInputStream() {
return inputStream;
}
public DataOutputStream getOutputStream() {
return outputStream;
}
}
| [
"nebulousdev@gmail.com"
] | nebulousdev@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.