file_id
int64 1
180k
| content
stringlengths 13
357k
| repo
stringlengths 6
109
| path
stringlengths 6
1.15k
|
---|---|---|---|
180,025 | package pl.koziolekweb.guava;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.common.net.InternetDomainName;
import java.util.HashMap;
import static com.google.common.base.Joiner.on;
import static com.google.common.net.InternetDomainName.from;
import static com.google.common.net.InternetDomainName.isValid;
import static pl.koziolekweb.guava.BooleanMap.equalNotEqual;
import static pl.koziolekweb.guava.BooleanMap.validInvalid;
import static pl.koziolekweb.guava.BooleanMap.yesNo;
/**
* TODO write JAVADOC!!!
* User: koziolek
*/
public class InternetDomainNamesBasics {
public static final String KOZIOLEKWEB_PL = "koziolekweb.pl";
public static final InternetDomainName KOZIOLEKWEB_PL_IDN = from(KOZIOLEKWEB_PL);
public static final String APPSPOT_COM = "appspot.com";
public static final InternetDomainName APPSPOT_COM_IDN = from(APPSPOT_COM);
public static final String TYRSOFT_PL = "tyrsoft.com";
public static final InternetDomainName TYRSOFT_PL_IDN = from(TYRSOFT_PL);
public static final String ETH = "8thcolour";
public static final String ETH_TYRSOFT_PL = "8thcolour.tyrsoft.com";
public static final InternetDomainName ETH_TYRSOFT_PL_IDN = from(ETH_TYRSOFT_PL);
public static void main(String[] args) {
isValidExample();
childExample();
parentExample();
hasParentExample();
hasPublicSuffixExample();
isPublicSuffixExample();
isTopPrivateExample();
isUnderPublicSuffixExample();
partsExample();
publicSuffixExample();
topPrivateDomainExample();
}
public static void isValidExample() {
System.out.printf("Domain %s is %s\n", KOZIOLEKWEB_PL, validInvalid(isValid(KOZIOLEKWEB_PL)));
System.out.printf("Domain %s is %s\n", "Koziołekłeb.pl", validInvalid(isValid("Koziołekłeb.pl")));
System.out.printf("Domain %s is %s\n", "$#%$##.com", validInvalid(isValid("$#%$##.com")));
}
public static void childExample() {
InternetDomainName child = TYRSOFT_PL_IDN.child(ETH);
System.out.printf("Domain %s has child %s and it is %s to %s\n", TYRSOFT_PL, child,
equalNotEqual(child.equals(ETH_TYRSOFT_PL_IDN)),
ETH_TYRSOFT_PL);
}
public static void parentExample() {
InternetDomainName parent = ETH_TYRSOFT_PL_IDN.parent();
System.out.printf("Parent of %s is %s and is %s to %s\n", ETH_TYRSOFT_PL, parent
, equalNotEqual(parent.equals(TYRSOFT_PL_IDN)), TYRSOFT_PL);
System.out.printf("Parent of %s is %s\n", TYRSOFT_PL, TYRSOFT_PL_IDN.parent());
}
public static void hasParentExample() {
System.out.printf("Is domain %s has parent? %s\n", TYRSOFT_PL, yesNo(TYRSOFT_PL_IDN.hasParent()));
}
public static void hasPublicSuffixExample() {
System.out.printf("Has domain %s public suffix? %s\n", TYRSOFT_PL, yesNo(TYRSOFT_PL_IDN.hasPublicSuffix()));
System.out.printf("Has domain %s public suffix? %s\n", ETH_TYRSOFT_PL, yesNo(ETH_TYRSOFT_PL_IDN.hasPublicSuffix()));
}
public static void isPublicSuffixExample() {
System.out.printf("Is domain %s public suffix? %s\n", TYRSOFT_PL, yesNo(TYRSOFT_PL_IDN.isPublicSuffix()));
System.out.printf("Is domain %s public suffix? %s\n", APPSPOT_COM, yesNo(APPSPOT_COM_IDN.isPublicSuffix()));
}
public static void isTopPrivateExample() {
System.out.printf("Is domain %s TPD? %s\n", TYRSOFT_PL, yesNo(TYRSOFT_PL_IDN.isTopPrivateDomain()));
System.out.printf("Is domain %s TPD? %s\n", ETH_TYRSOFT_PL, yesNo(ETH_TYRSOFT_PL_IDN.isTopPrivateDomain()));
System.out.printf("Is domain %s TPD? %s\n", APPSPOT_COM, yesNo(APPSPOT_COM_IDN.isTopPrivateDomain()));
}
public static void isUnderPublicSuffixExample() {
System.out.printf("Is domain %s under public suffix? %s\n", ETH_TYRSOFT_PL, yesNo(ETH_TYRSOFT_PL_IDN.isUnderPublicSuffix()));
System.out.printf("Is domain %s under public suffix? %s\n", APPSPOT_COM, yesNo(APPSPOT_COM_IDN.isUnderPublicSuffix()));
}
public static void partsExample() {
System.out.printf("Domain %s parts: %s\n", ETH_TYRSOFT_PL, on(", ").join(ETH_TYRSOFT_PL_IDN.parts()));
}
public static void publicSuffixExample() {
System.out.printf("Domain %s public suffix is %s\n", ETH_TYRSOFT_PL, ETH_TYRSOFT_PL_IDN.publicSuffix());
}
public static void topPrivateDomainExample() {
System.out.printf("TPD of %s is %s\n", ETH_TYRSOFT_PL, ETH_TYRSOFT_PL_IDN.topPrivateDomain());
}
}
| Koziolek/koziolekweb | guava/idn/src/main/java/pl/koziolekweb/guava/InternetDomainNamesBasics.java |
180,032 | package pl.put.poznan.SQC.app.ScenarioManagement;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import pl.put.poznan.SQC.app.Wizytator.WizytatorLiczacy;
import pl.put.poznan.SQC.app.Wizytator.WizytatorLiczacyWarunki;
import pl.put.poznan.SQC.app.Wizytator.WizytatorNazywajacy;
import pl.put.poznan.SQC.app.Wizytator.WizytatorSprawdzajacyAktorow;
import java.util.ArrayList;
/**
* Klasa przechowuje scenariusz odczytany z pliku jako obiekt.
* Deleguje wizytatorów z interfejsu Wizytator na obiekty klasy Step.
*/
public class Scenario {
/**
* Nazwa scenariusza.
*/
@JsonProperty(index=1)
private String scenarioName;
/**
* Lista aktorów w scenariuszu.
*/
@JsonProperty(index=2)
private ArrayList<String> actors;
/**
* Lista aktorów systemowych w scenariuszu.
*/
@JsonProperty(index=3)
private ArrayList<String> systemActors;
/**
* Lista kroków w scenariuszu.
*/
private ArrayList<Step> steps;
/**
* Konstruktor wykorzystywany przy wczytaniu z pliku .json
* @param scenarioName nazwa scenariusza
* @param actors lista aktorów
* @param systemActors lista aktorów systemowych
* @param steps lista korków
*/
@JsonCreator
public Scenario(@JsonProperty("scenarioName") String scenarioName,
@JsonProperty("actors") ArrayList<String> actors,
@JsonProperty("systemActors") ArrayList<String> systemActors,
@JsonProperty("steps") ArrayList<Step> steps) {
this.scenarioName = scenarioName;
this.actors = actors;
this.systemActors = systemActors;
this.steps = steps;
if(steps != null)
calculateStepIndexes();
}
/**
* Konstruktor kopiujący
* @param scenario obiekt do skopiowania
*/
public Scenario(Scenario scenario){
this(scenario.scenarioName, scenario.actors, scenario.systemActors, null);
this.steps = new ArrayList<>();
for(Step step : scenario.steps)
this.steps.add(new Step(step));
}
/**
* Konwertuje obiekt Scenario na JSON w postaci String-a.
* @return String zawierający JSON
* @throws JsonProcessingException problem podczas przetwarzania JSON
*/
public String scenarioToJson() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* Getter scenarioName
* @return String scenarioName
*/
public String getScenarioName(){return this.scenarioName;}
/**
* Getter actors
* @return lista aktorów
*/
public ArrayList<String> getActors(){
return this.actors;
}
/**
* Getter systemActors
* @return lista aktorów systemowych
*/
public ArrayList<String> getSystemActors(){
return this.systemActors;
}
/**
* Getter steps
* @return lista kroków
*/
public ArrayList<Step> getStepsList(){return this.steps;}
/**
* Oblicza ilość kroków w scenariuszu.
* @return ilość kroków
*/
public int calculateStepLength(){
WizytatorLiczacy wizytatorLiczacy = new WizytatorLiczacy();
for(Step step : steps){
step.accept(wizytatorLiczacy);
}
return wizytatorLiczacy.getLength();
}
/**
* Oblicza ilość poziomów scenariusza.
* @return ilość poziomów
*/
public int calculateStepCondition(){
WizytatorLiczacyWarunki wizytatorLiczacyWarunki = new WizytatorLiczacyWarunki();
for(Step step : steps){
step.accept(wizytatorLiczacyWarunki);
}
return wizytatorLiczacyWarunki.getLength();
}
/**
* Oblicza kolejne numery kroków scenariusza.
*/
public void calculateStepIndexes(){
WizytatorNazywajacy wizytatorNazywajacy = new WizytatorNazywajacy();
for(Step step : steps){
step.accept(wizytatorNazywajacy);
}
}
/**
* Znajduje nieprawidłowe kroki scenariusza
* @return Lista kroków bez aktora
*/
public ArrayList<String> calculateMissingActors(){
WizytatorSprawdzajacyAktorow wizytatorSprawdzajacyAktorow = new WizytatorSprawdzajacyAktorow(this);
for(Step step : steps){
step.accept(wizytatorSprawdzajacyAktorow);
}
return wizytatorSprawdzajacyAktorow.getStepArrayList();
}
/**
* Ogranicza scenariusz do ustalonego poziomu
* @param poziom poziom zagłebienia
* @return Okrojony scenariusz
* @throws JsonProcessingException problem podczas przetwarzania JSON
*/
public Scenario calculateLeveledScenario(int poziom) throws JsonProcessingException {
/// Nad tą linijką poleciały klawiszę, proszę ją uczcić pół minutką ciszy
Scenario scenario = new Scenario(this);
// Proszę przemilczmy tę linijkę
for(Step subStep : scenario.steps){
int stepLength = subStep.calculateConditionalSteps() ;
if(stepLength >= poziom){
subStep.seekAndDestory(poziom - 1);
}
}
return scenario;
}
}
| Wiktor-Jordeczka/Spring-Boot-SQC | src/main/java/pl/put/poznan/SQC/app/ScenarioManagement/Scenario.java |
180,034 | package pl.zyczu.minecraft.launcher.gui;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.minecraft.LauncherFrame;
import pl.zyczu.minecraft.launcher.Minecraft;
import pl.zyczu.minecraft.launcher.repo.Mod;
import pl.zyczu.minecraft.launcher.repo.Repository;
import pl.zyczu.minecraft.launcher.repo.RepositoryManager;
import pl.zyczu.util.WrapLayout;
public class ModView extends Loadable implements Refreshable {
private static final long serialVersionUID = 800L;
private Mod modek = null;
private static ModView instance = null;
private ModView(boolean b) {
super(b);
this.setOpaque(false);
this.setLayout(new WrapLayout());
}
public static ModView getInstance() {
if (instance == null) {
instance = new ModView(true);
}
return instance;
}
public void loadModInfo(Mod mod) {
this.removeAll();
this.modek = mod;
boolean zainstalowany = this.getCurrentModPack().containsMod(mod);
StringBuilder bld = new StringBuilder();
boolean pierwsze = true;
boolean dostepny = false;
for(Repository repo : RepositoryManager.getInstance().getRepositoriesInOrder()) {
if (repo.containsMod(mod)) {
if (this.getCurrentModPack().getRepository().equals(repo)) {
dostepny = true;
}
if (pierwsze) {
bld.append(repo.getName());
pierwsze = false;
} else {
bld.append("<br>" + repo.getName());
}
}
}
String repozytoria = bld.toString();
JPanel zbiorczy = new JPanel() {
private final Color kolorek = Color.WHITE;
private static final long serialVersionUID = -5951374986891143962L;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Composite originalComposite = g2.getComposite();
g2.setPaint(this.kolorek);
g2.setComposite(this.makeComposite());
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setComposite(originalComposite);
}
private AlphaComposite makeComposite() {
int type = 3;
return AlphaComposite.getInstance(type, 0.2F);
}
};
zbiorczy.setOpaque(false);
JLabel nagl = new JLabel("<html><table width=600><p style=\"font-family:MinecraftZyczu\">" + mod.getName() + "</p></table></html>");
nagl.setFont(Minecraft.getInstance().getFont(18));
zbiorczy.add(nagl, "West");
if (!mod.getId().equals("minecraft")) {
JButton btn = null;
if (zainstalowany) {
btn = new JButton("Usuń z minecrafta");
btn.addActionListener(new UsunActionListener(mod));
} else if (dostepny) {
btn = new JButton("Dodaj do minecrafta");
btn.addActionListener(new DodajDoMinecraftaActionListener(mod));
} else {
btn = new JButton("Niedostępny na " + this.getCurrentModPack().getRepository().getShortName());
btn.setEnabled(false);
}
btn.setFont(Minecraft.getInstance().getFont(12));
zbiorczy.add(btn, "East");
}
this.add(zbiorczy);
JPanel lewe = new JPanel();
lewe.setLayout(new BoxLayout(lewe, 1));
lewe.setOpaque(false);
final String łebsajt = mod.getWebsite();
JLabel aut = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">Autor: " + mod.getAuthor() + "</p></table></html>");
aut.setFont(Minecraft.getInstance().getFont(11));
lewe.add(aut);
JLabel www = new JLabel(
"<html><table width=800><p style=\"font-family:MinecraftZyczu\">Strona: <a href=\""
+ mod.getWebsite()
+ "\">"
+ mod.getWebsite()
+ "</a> </p></table></html>"
);
www.setFont(Minecraft.getInstance().getFont(11));
www.addMouseListener(new MouseAdapter() {
private boolean bylo = false;
public void mousePressed(MouseEvent arg0) {
this.bylo = true;
}
public void mouseReleased(MouseEvent arg0) {
if (this.bylo) {
Minecraft.log.debug("Przekierowywanie na " + łebsajt);
try {
Desktop.getDesktop().browse(new URL(łebsajt).toURI());
} catch (MalformedURLException var3) {
var3.printStackTrace();
} catch (IOException var4) {
var4.printStackTrace();
} catch (URISyntaxException var5) {
var5.printStackTrace();
}
}
this.bylo = false;
}
});
lewe.add(www);
JLabel rep = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">Dostępny na: " + repozytoria + "</p></table></html>");
rep.setFont(Minecraft.getInstance().getFont(11));
lewe.add(rep);
JLabel opis = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">" + mod.getText().replace("\n", "<br>") + "</p></table></html>");
opis.setFont(Minecraft.getInstance().getFont(12));
lewe.add(opis);
this.add(lewe, "West");
if (mod.getDependencies().size() > 0) {
JLabel n = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">Wymaga:</p></table></html>");
n.setFont(Minecraft.getInstance().getFont(14));
this.add(n);
Iterator<String> it2 = mod.getDependencies().iterator();
while(it2.hasNext()) {
final Mod inny = RepositoryManager.getInstance().getModById((String)it2.next());
zbiorczy = new JPanel() {
private final Color kolorek = Color.WHITE;
private static final long serialVersionUID = -5951374986891143962L;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Composite originalComposite = g2.getComposite();
g2.setPaint(this.kolorek);
g2.setComposite(this.makeComposite());
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setComposite(originalComposite);
}
private AlphaComposite makeComposite() {
int type = 3;
return AlphaComposite.getInstance(type, 0.2F);
}
};
zbiorczy.setOpaque(false);
JLabel ngl2 = new JLabel("<html><table width=600><p style=\"font-family:MinecraftZyczu\">" + inny.getName() + "</p></table></html>");
ngl2.setFont(Minecraft.getInstance().getFont(16));
zbiorczy.add(ngl2, "West");
JButton btn = new JButton("Informacje o modzie");
btn.setFont(Minecraft.getInstance().getFont(12));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
LauncherFrame.getInstance().enableGlassPane();
ModView.this.loadModInfo(inny);
ModView.this.update();
LauncherFrame.getInstance().disableGlassPane();
}
});
zbiorczy.add(btn, "East");
this.add(zbiorczy);
}
}
if (mod.getReplacements().size() > 0) {
JLabel n = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">Zastępuje:</p></table></html>");
n.setFont(Minecraft.getInstance().getFont(14));
this.add(n);
Iterator<String> it2 = mod.getReplacements().iterator();
while(it2.hasNext()) {
final Mod inny = RepositoryManager.getInstance().getModById((String)it2.next());
zbiorczy = new JPanel() {
private final Color kolorek = Color.WHITE;
private static final long serialVersionUID = -5951374986891143962L;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Composite originalComposite = g2.getComposite();
g2.setPaint(this.kolorek);
g2.setComposite(this.makeComposite());
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setComposite(originalComposite);
}
private AlphaComposite makeComposite() {
int type = 3;
return AlphaComposite.getInstance(type, 0.2F);
}
};
zbiorczy.setOpaque(false);
JLabel ngl2 = new JLabel("<html><table width=600><p style=\"font-family:MinecraftZyczu\">" + inny.getName() + "</p></table></html>");
ngl2.setFont(Minecraft.getInstance().getFont(16));
zbiorczy.add(ngl2, "West");
JButton btn = new JButton("Informacje o modzie");
btn.setFont(Minecraft.getInstance().getFont(12));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ModView.this.loadModInfo(inny);
}
});
zbiorczy.add(btn, "East");
this.add(zbiorczy);
}
}
if (mod.getConflicts().size() > 0) {
JLabel n = new JLabel("<html><table width=800><p style=\"font-family:MinecraftZyczu\">Nie działa z:</p></table></html>");
n.setFont(Minecraft.getInstance().getFont(14));
this.add(n);
Iterator<String> it2 = mod.getConflicts().iterator();
while(it2.hasNext()) {
final Mod inny = RepositoryManager.getInstance().getModById((String)it2.next());
zbiorczy = new JPanel() {
private final Color kolorek = Color.WHITE;
private static final long serialVersionUID = -5951374986891143962L;
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Composite originalComposite = g2.getComposite();
g2.setPaint(this.kolorek);
g2.setComposite(this.makeComposite());
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.setComposite(originalComposite);
}
private AlphaComposite makeComposite() {
int type = 3;
return AlphaComposite.getInstance(type, 0.2F);
}
};
zbiorczy.setOpaque(false);
JLabel ngl2 = new JLabel("<html><table width=600><p style=\"font-family:MinecraftZyczu\">" + inny.getName() + "</p></table></html>");
ngl2.setFont(Minecraft.getInstance().getFont(16));
zbiorczy.add(ngl2, "West");
JButton btn = new JButton("Informacje o modzie");
btn.setFont(Minecraft.getInstance().getFont(12));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ModView.this.loadModInfo(inny);
}
});
zbiorczy.add(btn, "East");
this.add(zbiorczy);
}
}
}
@Override
public void refresh() {
this.loadModInfo(this.modek);
}
private void refreshInEventQueue() {
EventQueue.invokeLater(new Runnable() {
public void run() {
ModView.this.refresh();
}
});
}
private void update() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ModView.this.update(ModView.this.getGraphics());
} catch (NullPointerException var2) {
Minecraft.log.warning("NPE przy rysowaniu interfejsu!");
}
}
});
}
@Override
public void onLoad(MultiPanelStub ref) {
}
@Override
public void onModPackChanged() {
this.refresh();
}
}
| kondziux1/By-Zyczu_src | pl/zyczu/minecraft/launcher/gui/ModView.java |
180,035 | /*
* 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 Prototyp;
/**
*
* @author KrzysieK
*/
public class Test {
public static void main(String[] args) {
System.out.println("Płytkie klonowanie");
System.out.println(
"--------------------------------------------------------");
System.out.println("A) Utworzenie kopii i jej wypisanie:");
Osoba jeden = new Osoba("Janusz", "Kowalski", "80-456", new Przedsiebiorstwo("piekarz"), new Hobby("rower"));
wypisz(jeden,"oryginal");
Osoba blizniak = (Osoba)jeden.KlonowaniePlytkie();
wypisz(blizniak,"kopia");
System.out.println("-------------------------------------");
System.out.println("\n"+"B) Zmina danych w klonie - płytki poziom:");
blizniak.imie = "Mikołaj";
blizniak.nazwisko = "Golum";
wypisz(jeden, "oryginał");
wypisz(blizniak, "kopia");
System.out.println(
"--------------------------------------------------------");
System.out.println("\n"+"C) Zmina danych w klonie - głęboki poziom:");
blizniak.praca.szef.nazwa = "Kinga Mazga";
blizniak.adres.miasto = "Wąchock";
wypisz(jeden, "oryginał");
wypisz(blizniak, "kopia");
System.out.println("\n"+
"Głębokie klonowanie");
System.out.println(
"--------------------------------------------------------");
System.out.println("\n"+"A) Utworzenie kopii i jej wypisanie:");
Osoba dwa = new Osoba("Daria", "MIchalczewska", "54-318", new Przedsiebiorstwo("kwiaciarka"), new Hobby("plywanie"));
wypisz(dwa,"oryginal");
Osoba blizniaczka = (Osoba)dwa.KlonowanieGlebokie(dwa);
wypisz(blizniaczka,"kopia");
System.out.println(
"--------------------------------------------------------");
System.out.println("\n"+"B) Zmina danych w klonie - płytki poziom:");
blizniaczka.imie = "Zuzanna";
blizniaczka.nazwisko = "Piskoń";
wypisz(dwa, "oryginał");
wypisz(blizniaczka, "kopia");
System.out.println(
"--------------------------------------------------------");
System.out.println("\n"+ "C) Zmina danych w klonie - głęboki poziom:");
blizniaczka.praca.szef.nazwa = "Magda Witkowska";
blizniaczka.adres.miasto = "Łeba";
blizniaczka.praca.stanowisko = "analityk";
wypisz(dwa, "oryginał");
wypisz(blizniaczka, "kopia");
}
private static void wypisz(Osoba osoba, String typ) {
System.out.println(" " + osoba.getClass().getName() + " \"" + typ + "\":");
System.out.println(osoba.przedstawSie());
}
}
| adrych/DesignPatterns | 04Prototype/Students/2016/Szarafinski/Test.java |
180,037 | /*
* 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 Tury;
import java.util.ArrayList;
/**
*
* @author Grzechu
*/
public class Tura {
private int iloscGraczy;
public ArrayList<TuraPole> lista;
private int obecnie = 0;
public Tura (int iloscGraczy)
{
lista = new ArrayList<>();
this.iloscGraczy = iloscGraczy;
}
public int obecna ()
{
return this.obecnie;
}
public void dodajTure(int jakiNumer, int ileInicjatywy)
{
TuraPole p = new TuraPole(jakiNumer, ileInicjatywy);
lista.add(p);
}
@Override
public String toString ()
{
StringBuilder pom = new StringBuilder();
for (int i=0; i < this.iloscGraczy; i++)
{
pom.append(this.lista.get(i).kto).append(" -> ").append(this.lista.get(i).ile).append("\n");
}
return pom.toString();
}
public void nastepna()
{
if ((this.obecnie + 1) == this.iloscGraczy)
obecnie = 0;
else obecnie++;
}
}
| bieleck1/DandD | DandD/src/Tury/Tura.java |
180,044 | /*
* 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 beanStatystyka;
import entity.Statystyka;
import java.io.Serializable;
/**
*
* @author Osito
*/
public class StatystykaExt extends Statystyka implements Serializable {
private double wspolczynnik;
private double fakturaobecnie;
private double fakturanowa;
public StatystykaExt(double wspolczynnik, double fakturaobecnie, double fakturanowa, Statystyka o) {
super(o);
this.wspolczynnik = wspolczynnik;
this.fakturaobecnie = fakturaobecnie;
this.fakturanowa = fakturanowa;
}
public StatystykaExt() {
}
public double getWspolczynnik() {
return wspolczynnik;
}
public void setWspolczynnik(double wspolczynnik) {
this.wspolczynnik = wspolczynnik;
}
public double getFakturaobecnie() {
return fakturaobecnie;
}
public void setFakturaobecnie(double fakturaobecnie) {
this.fakturaobecnie = fakturaobecnie;
}
public double getFakturanowa() {
return fakturanowa;
}
public void setFakturanowa(double fakturanowa) {
this.fakturanowa = fakturanowa;
}
}
| brzaskun/NetBeansProjects | npkpir_23/src/java/beanStatystyka/StatystykaExt.java |
180,056 | package pl.grm.pts.tabs;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import pl.grm.pts.CalcCore;
import pl.grm.pts.Tab;
import pl.grm.pts.core.misc.Complex;
public class DFT extends JPanel implements Tab {
private static final long serialVersionUID = 1L;
private JTextField tFieldSignalInput;
private JTextArea tA_Result;
private JTextField tF_w1dc;
private JTextField tF_w11;
private JTextField tF_w12;
private JTextField tF_w2dc;
private JTextField tF_w21;
private JTextField tF_w22;
private JTextField tf_w3dc;
private JTextField tF_w31;
private JTextField tF_w32;
public DFT() {
setLayout(new BorderLayout(0, 0));
JPanel panel_Top = new JPanel();
add(panel_Top, BorderLayout.NORTH);
JLabel lblSygna = new JLabel("Sygna\u0142");
panel_Top.add(lblSygna);
tFieldSignalInput = new JTextField();
tFieldSignalInput.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(() -> {
countDFT();
}).start();
}
});
tFieldSignalInput.setColumns(10);
panel_Top.add(tFieldSignalInput);
JButton btnObliczDft = new JButton("Oblicz DFT");
btnObliczDft.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(() -> {
countDFT();
}).start();
}
});
panel_Top.add(btnObliczDft);
JPanel panel_Main = new JPanel();
add(panel_Main, BorderLayout.CENTER);
panel_Main.setLayout(new BorderLayout(0, 0));
tA_Result = new JTextArea();
tA_Result.setRows(10);
tA_Result.setEditable(false);
tA_Result.setColumns(40);
panel_Main.add(tA_Result, BorderLayout.CENTER);
JPanel panel_SideIn = new JPanel();
panel_Main.add(panel_SideIn, BorderLayout.EAST);
panel_SideIn.setLayout(new GridLayout(0, 1, 0, 0));
JPanel panel_w1 = new JPanel();
panel_SideIn.add(panel_w1);
panel_w1.setLayout(new GridLayout(3, 2, 0, 0));
JLabel lblWersja = new JLabel("Wersja 1 DC");
lblWersja.setHorizontalAlignment(SwingConstants.CENTER);
panel_w1.add(lblWersja);
tF_w1dc = new JTextField();
panel_w1.add(tF_w1dc);
tF_w1dc.setColumns(10);
JLabel lblNewLabel = new JLabel("1 h");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel_w1.add(lblNewLabel);
tF_w11 = new JTextField();
panel_w1.add(tF_w11);
tF_w11.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("2 h");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
panel_w1.add(lblNewLabel_1);
tF_w12 = new JTextField();
panel_w1.add(tF_w12);
tF_w12.setColumns(10);
JPanel panel_w2 = new JPanel();
panel_SideIn.add(panel_w2);
panel_w2.setLayout(new GridLayout(3, 2, 0, 0));
JLabel lblWersja_1 = new JLabel("Wersja 2 DC");
lblWersja_1.setHorizontalAlignment(SwingConstants.CENTER);
panel_w2.add(lblWersja_1);
tF_w2dc = new JTextField();
tF_w2dc.setColumns(10);
panel_w2.add(tF_w2dc);
JLabel label = new JLabel("1 h");
label.setHorizontalAlignment(SwingConstants.CENTER);
panel_w2.add(label);
tF_w21 = new JTextField();
tF_w21.setColumns(10);
panel_w2.add(tF_w21);
JLabel label_1 = new JLabel("2 h");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
panel_w2.add(label_1);
tF_w22 = new JTextField();
tF_w22.setColumns(10);
panel_w2.add(tF_w22);
JPanel panel_w3 = new JPanel();
panel_SideIn.add(panel_w3);
panel_w3.setLayout(new GridLayout(3, 2, 0, 0));
JLabel lblWersjai = new JLabel("W 3 (I optyczna) DC");
lblWersjai.setHorizontalAlignment(SwingConstants.CENTER);
panel_w3.add(lblWersjai);
tf_w3dc = new JTextField();
tf_w3dc.setColumns(10);
panel_w3.add(tf_w3dc);
JLabel label_2 = new JLabel("1 h");
label_2.setHorizontalAlignment(SwingConstants.CENTER);
panel_w3.add(label_2);
tF_w31 = new JTextField();
tF_w31.setColumns(10);
panel_w3.add(tF_w31);
JLabel label_3 = new JLabel("2 h");
label_3.setHorizontalAlignment(SwingConstants.CENTER);
panel_w3.add(label_3);
tF_w32 = new JTextField();
tF_w32.setColumns(10);
panel_w3.add(tF_w32);
JPanel panel_Bottom = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel_Bottom.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
add(panel_Bottom, BorderLayout.SOUTH);
JLabel lblObecnieMax = new JLabel("Obecnie tylko 4 sk");
lblObecnieMax.setHorizontalAlignment(SwingConstants.LEFT);
panel_Bottom.add(lblObecnieMax);
}
protected void countDFT() {
Vector<Complex> resultSignal;
try {
resultSignal = CalcCore.instance.calcDFT(tFieldSignalInput.getText());
int size = resultSignal.size();
String out = "For " + size + " sampled input [" + tFieldSignalInput.getText() + "]\n";
Iterator<Complex> iterator = resultSignal.iterator();
while (iterator.hasNext()) {
Complex cx = iterator.next();
out += cx.toString() + "\n";
}
tA_Result.setText(out);
if (size > 1) {
final Complex w1dc = resultSignal.get(0);
tF_w1dc.setText(w1dc.toString());
tF_w2dc.setText(w1dc.divide(size).toString());
tF_w32.setText(w1dc.divide(size).toString());
if (size > 3) {
Complex w11 = resultSignal.get(1);
Complex w12 = resultSignal.get(2);
Complex w13 = resultSignal.get(3);
tF_w11.setText(w11.add(w13).toString());
tF_w12.setText(w12.toString());
tF_w21.setText(w11.add(w13).divide(size).toString());
tF_w22.setText(w12.divide(size).toString());
tf_w3dc.setText(w12.divide(size).toString());
tF_w31.setText(w11.add(w13).divide(size).toString());
}
}
}
catch (Exception e1) {
JOptionPane
.showInternalMessageDialog(DFT.this.getParent().getParent(), e1.getMessage());
}
}
}
| GRM-dev/PTS | src/main/java/pl/grm/pts/tabs/DFT.java |
180,058 | package multi;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.Semaphore;
public class SharedDeadlock1 {
private static Semaphore s1 = new Semaphore(1, true);
private static int count = 0;
static String myTrain;
static void safelyAcquiring(
@NotNull final Semaphore s,
final int permits,
@NotNull final Runnable body) {
boolean acquired = false;
try {
s.acquire(permits);
acquired = true;
body.run();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (acquired)
s.release(permits);
}
}
@NotNull
@Contract("_ -> new")
static Thread makeTrain(String s) {
return new Thread(() -> {
safelyAcquiring(s1, 1, () -> {
safelyAcquiring(s1, 1, () -> {
count += s.length();
System.out.println("Obecnie count jest równy " + count);
});
});
});
}
public static void main(String... args) {
makeTrain("E-09").start();
makeTrain(myTrain).start();
makeTrain("E-08").start();
// Semafory nie są RE-ENTRANT
System.out.println("Koniec.");
}
}
| kongra/SAN | 2019 zimowy/Conc/MultiTasking/src/main/java/multi/SharedDeadlock1.java |
180,059 | package multi;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
public class SharedDeadlock2 {
private static int count = 0;
static String myTrain;
@NotNull
@Contract("_ -> new")
static Thread makeTrain(String s) {
return new Thread(() -> {
synchronized (SharedDeadlock2.class) {
synchronized (SharedDeadlock2.class) {
count += s.length();
System.out.println("Obecnie count jest równy " + count);
}
}
});
}
public static void main(String... args) {
makeTrain("E-09").start();
makeTrain(myTrain).start();
makeTrain("E-08").start();
// Monitory są RE-ENTRANT
System.out.println("Koniec.");
}
}
| kongra/SAN | 2019 zimowy/Conc/MultiTasking/src/main/java/multi/SharedDeadlock2.java |
180,066 | /*
* Copyright (C) 2014 TheMolkaPL - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Aleksander Jagiełło <[email protected]>, 2014
*/
package pl.shg.arcade.api.command.def;
import pl.shg.arcade.api.command.Command;
import pl.shg.arcade.api.command.Command.CommandMessage;
import pl.shg.arcade.api.command.CommandException;
import pl.shg.arcade.api.command.Sender;
import pl.shg.arcade.api.human.Player;
import pl.shg.arcade.api.text.Color;
/**
*
* @author Aleksander
*/
public class MyteamCommand extends Command {
public MyteamCommand() {
super(new String[] {"myteam", "mt"},
"Wyswietla informacje w której druzynie sie znajdujesz", "myteam [-r]",
new char[] {'r'});
this.setOption("-r", "surowa informacja");
this.setPermission("arcade.command.myteam");
}
@Override
public void execute(Sender sender, String[] args) throws CommandException {
if (sender.isConsole()) {
this.throwMessage(sender, CommandMessage.PLAYER_NEEDED);
} else if (this.hasFlag(args, 'r')) {
sender.sendMessage(Color.YELLOW + ((Player) sender).getTeam().getName());
} else {
sender.sendMessage(Color.GRAY + "Obecnie znajdujesz sie w druzynie " +
((Player) sender).getTeam().getDisplayName() + Color.RESET + Color.GRAY + ".");
}
}
@Override
public int minArguments() {
return 0;
}
}
| ShootGame/Arcade | src/main/java/pl/shg/arcade/api/command/def/MyteamCommand.java |
180,068 | /*
* Copyright (C) 2014 TheMolkaPL - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Aleksander Jagiełło <[email protected]>, 2014
*/
package pl.shg.arcade.api.command.def;
import java.util.List;
import pl.shg.arcade.api.Arcade;
import pl.shg.arcade.api.command.Command;
import pl.shg.arcade.api.command.CommandException;
import pl.shg.arcade.api.command.Sender;
import pl.shg.arcade.api.team.Team;
import pl.shg.arcade.api.text.Color;
/**
*
* @author Aleksander
*/
public class TeamsCommand extends Command {
public TeamsCommand() {
super(new String[] {"teams", "teamlist"},
"Pokaz liste zarejestrowanych obecnie druzyn na mapie oraz informacje", "teams [-i]",
new char[] {'i'});
this.setOption("-i", "informacje konfiguracyjne");
this.setPermission("arcade.command.teams");
}
@Override
public void execute(Sender sender, String[] args) throws CommandException {
if (!this.hasFlag(args, 'i')) {
this.showTeams(sender, false);
} else if (!this.canNot(sender, "arcade.command.teams.info")) {
this.showTeams(sender, true);
}
}
@Override
public int minArguments() {
return 0;
}
private void showTeams(Sender sender, boolean info) {
StringBuilder builder = new StringBuilder();
List<Team> teams = Arcade.getTeams().getTeams();
for (int i = 0; i < teams.size(); i++) {
Team team = teams.get(i);
builder.append(Color.YELLOW).append(i + 1).append(". ").append(team.getDisplayName());
builder.append(Color.GRAY).append(" (").append(team.getPlayers().size()).append("/").append(team.getSlots()).append(")");
if (info) {
builder.append(Color.GREEN).append(" teamColor=").append(team.getTeamColor().toString());
builder.append(", frendly=").append(team.isFrendlyFire());
}
builder.append("\n");
}
sender.sendMessage(Command.getTitle("Druzyny", Color.GRAY + "(" + teams.size() + ")"));
sender.sendMessage(builder.toString());
}
}
| ShootGame/Arcade | src/main/java/pl/shg/arcade/api/command/def/TeamsCommand.java |
180,073 | package Warehouse.app.View;
import Warehouse.app.CarSpot.CarServiceSpot;
import Warehouse.app.CarSpot.IndependentCarServiceSpot;
import Warehouse.app.Menu.MainMenu;
import Warehouse.app.Vehicle.Vehicle;
import javax.swing.*;
import java.util.Map;
public class StopRepairView {
public StopRepairView(){
MainMenu.unlockViev();
ublockAllButons(false);
MainMenu.getTextArea().setText("Jaki rodzaj naprawy chcesz zakonczyc?");
MainMenu.jTextField.setBounds(415,650,0,0);
MainMenu.buttonOK.setBounds(415,650,0,0);
JButton newOkButton = new JButton("Serwisowa naprawa");
newOkButton.setBounds(415,650,275,50);
newOkButton.setFocusPainted(false);
MainMenu.frame.add(newOkButton);
JButton buttonNO = new JButton("Samodzielna naprawa");
buttonNO.setBounds(690,650,275,50);
buttonNO.setFocusPainted(false);
MainMenu.frame.add(buttonNO);
buttonNO.setOpaque(true);
buttonNO.setOpaque(true);
newOkButton.addActionListener(e -> {
ublockAllButons(true);
Map<CarServiceSpot, Vehicle> lista = CarServiceSpot.getAllRepairedVehicles();
MainMenu.getTextArea().setText("Lista napraw serwisowych:\n\n ");
MainMenu.getTextArea().append(""+lista);
if (!lista.isEmpty()) {
MainMenu.getTextArea().setText("Wybierz miejsce serwisowe:");
MainMenu.getTextArea().append(""+lista);
ublockAllButons(true);
MainMenu.finishCSS=true;
} else {
MainMenu.blockViev();
MainMenu.getTextArea().setText("Nie ma obecnie zadnych napraw.");
MainMenu.jTextField.setEnabled(false);
MainMenu.buttonOK.setEnabled(false);
}
MainMenu.jTextField.setBounds(415,650,450,50);
MainMenu.buttonOK.setText("OK");
newOkButton.setBounds(690,650,0,0);
MainMenu.buttonOK.setBounds(865,650,100,50);
MainMenu.buttonOK.setFocusPainted(false);
});
buttonNO.addActionListener(e -> {
ublockAllButons(true);
Map<IndependentCarServiceSpot, Vehicle> lista = IndependentCarServiceSpot.getAllServicedVehiclesList();
MainMenu.getTextArea().setText("Lista napraw samodzielnych:\n\n ");
MainMenu.getTextArea().append(""+lista);
if (lista.isEmpty()) {
MainMenu.blockViev();
MainMenu.getTextArea().setText("Nie ma obecnie zadnych napraw.");
MainMenu.jTextField.setEnabled(false);
MainMenu.buttonOK.setEnabled(false);
}else {
MainMenu.finishICSS=true;
}
MainMenu.jTextField.setBounds(415,650,450,50);
MainMenu.buttonOK.setText("OK");
newOkButton.setBounds(690,650,0,0);
MainMenu.buttonOK.setBounds(865,650,100,50);
MainMenu.buttonOK.setFocusPainted(false);
});
}
public static void ublockAllButons(boolean b){
for (JButton jx:
MainMenu.getjButtonList()) {
jx.setEnabled(b);
}
}
}
| alankaczmarzyk/Pjatk-JavaGUI_Warehouses-Project | src/Warehouse/app/View/StopRepairView.java |
180,074 | 404: Not Found | Domomod/Procastinateflix | src/Produkt/Generatory/MiesiacRok.java |
180,075 | package game_player;
import game_main.GameState;
import game_table.GameTable;
import game_utils.Colors;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Klasa gracza grającego według algorytmu ALFA-BETA
* @author Michał Żakowski
*
*/
public class AIPlayerAlfaBeta extends AIPlayer {
/**
* Zmienna określająca ile ruchów wprzód analizuje algorytm alfa-beta
*/
private int depthLevel;
private static Random RAND = new Random();
public AIPlayerAlfaBeta(GameTable gameTable, Integer playerPos,
GameState gameState, Integer opponentsPlayerId, int depthLevel) {
super(gameTable, playerPos, gameState, opponentsPlayerId);
this.depthLevel = depthLevel;
}
/**
* Metoda ustawia liczbę analizowanych ruchów algorytmu.
* Nie należy ustawiać wartości większych niż 5
*/
@Override
public void setDifficultyLevel(int level) {
if(level < 1) level = 1;
depthLevel = level;
}
@Override
public void makeMove() {
opponentsColor = gameState.getOtherPlayersColor(playerId);
List<Colors> availableColors = gameState.getAvailableColorsForCurrentPlayer();
int bestResult = Integer.MIN_VALUE;
Colors bestChoice = Colors.BLACK;
for(Colors color : availableColors) {
int moveValue = alfaBetaEvaluateMove(color, 0, availableColors, 0, 0, currentPlayerColor,
opponentsColor,Integer.MIN_VALUE,Integer.MAX_VALUE);
if(moveValue > bestResult) {
bestChoice = color;
bestResult = moveValue;
}
else if(moveValue == bestResult) {
if(RAND.nextInt(2) == 0) {
bestChoice = color;
}
}
}
setChosenColor(bestChoice);
takenFields = gameTable.makeHypotheticalMove(playerId, bestChoice);
gameTable.acceptMove(0);
}
/**
* Metoda wywoływana rekurencyjnie zwracająca wartość wykonywanego ruchu (czyli
* różnicę między ilością kwadratów gracza, a ilością kwadratów przeciwnika
* @param tryColor - kolor, który testujemy
* @param movesMade - ilość ruchów wykonanych do tej pory (0 dla pierwszego wywołania metody)
* @param availableColors - dostępne kolory
* @param ourPoints - obecnie uzyskane punkty (kwadraty) gracza
* @param opponentsPoints - obecnie uzyskane punkty przeciwnika
* @param currentColor - aktualny kolor gracza
* @param opponentsCurrentColor - aktualny kolor przeciwnika
* @param alfa - aktualna maksymalna wartosc osiagnieta przez nas
* @param beta - aktualna minimalna wartosc osiagnieta przez przeciwnika
* @return wartość danego ruchu
*/
private int alfaBetaEvaluateMove(Colors tryColor, int movesMade, List<Colors> availableColors,
int ourPoints, int opponentsPoints, Colors currentColor, Colors opponentsCurrentColor,int alfa,int beta) {
List<Colors> nextAvailableColors = new ArrayList<Colors>();
nextAvailableColors.addAll(availableColors);
if(movesMade % 2 == 0) {
//our turn
ourPoints = gameTable.makeHypotheticalMove(playerId, tryColor).size();
if(movesMade == depthLevel-1) {
gameTable.undoHypotheticalMove(1);
return ourPoints-opponentsPoints;
}
nextAvailableColors.remove(tryColor);
if(currentColor != null && currentColor != Colors.BLACK) {
nextAvailableColors.add(currentColor);
}
for(Colors currentTryColor : nextAvailableColors) {
int currentPoints = alfaBetaEvaluateMove(currentTryColor,
movesMade+1, nextAvailableColors, ourPoints, opponentsPoints, tryColor, opponentsCurrentColor,
alfa,beta);
if(currentPoints<beta)
beta=currentPoints;
if(alfa>=beta){
gameTable.undoHypotheticalMove(1);
return alfa;
}
}
gameTable.undoHypotheticalMove(1);
return beta;
}
else {
//opponent's turn
//System.out.println(tryColor);
opponentsPoints = gameTable.makeHypotheticalMove(opponentsPlayerId, tryColor).size();
if(movesMade == depthLevel-1) {
gameTable.undoHypotheticalMove(1);
return ourPoints-opponentsPoints;
}
nextAvailableColors.remove(tryColor);
if(opponentsCurrentColor != null && opponentsCurrentColor != Colors.BLACK) {
nextAvailableColors.add(opponentsCurrentColor);
}
for(Colors currentTryColor : nextAvailableColors) {
int currentPoints = alfaBetaEvaluateMove(currentTryColor,
movesMade+1, nextAvailableColors, ourPoints, opponentsPoints, currentColor, tryColor,
alfa,beta);
if(currentPoints>alfa)
alfa=currentPoints;
if(alfa>=beta){
gameTable.undoHypotheticalMove(1);
return beta;
}
}
gameTable.undoHypotheticalMove(1);
return alfa;
}
}
}
| m4ttek/BattleOfColors | workspace/BattleOfColors/src/game_player/AIPlayerAlfaBeta.java |
180,082 | package game_player;
import game_main.GameState;
import game_table.GameTable;
import game_utils.Colors;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Klasa gracza grającego według algorytmu MIN-MAX
* @author Michał Pluta
*
*/
public class AIPlayerMinMax extends AIPlayer {
/**
* Zmienna określająca ile ruchów wprzód analizuje algorytm min-max
*/
private int depthLevel;
private static Random RAND = new Random();
public AIPlayerMinMax(GameTable gameTable, Integer playerPos,
GameState gameState, Integer opponentsPlayerId, int depthLevel) {
super(gameTable, playerPos, gameState, opponentsPlayerId);
this.depthLevel = depthLevel;
}
/**
* Metoda ustawia liczbę analizowanych ruchów algorytmu.
* Nie należy ustawiać wartości większych niż 5
*/
@Override
public void setDifficultyLevel(int level) {
if(level < 1) level = 1;
depthLevel = level;
}
@Override
public void makeMove() {
opponentsColor = gameState.getOtherPlayersColor(playerId);
//System.out.println("Other player's color is " + opponentsColor);
List<Colors> availableColors = gameState.getAvailableColorsForCurrentPlayer();
int bestResult = Integer.MIN_VALUE;
Colors bestChoice = Colors.BLACK;
for(Colors color : availableColors) {
int moveValue = minMaxEvaluateMove(color, 0, availableColors, 0, 0, currentPlayerColor,
opponentsColor);
//System.out.println(color + " would give me " + moveValue + " points.");
if(moveValue > bestResult) {
bestChoice = color;
bestResult = moveValue;
}
else if(moveValue == bestResult) {
if(RAND.nextInt(2) == 0) {
bestChoice = color;
}
}
}
setChosenColor(bestChoice);
takenFields = gameTable.makeHypotheticalMove(playerId, bestChoice);
gameTable.acceptMove(0);
}
/**
* Metoda wywoływana rekurencyjnie zwracająca wartość wykonywanego ruchu (czyli
* różnicę między ilością kwadratów gracza, a ilością kwadratów przeciwnika
* @param tryColor - kolor, który testujemy
* @param movesMade - ilość ruchów wykonanych do tej pory (0 dla pierwszego wywołania metody)
* @param availableColors - dostępne kolory
* @param ourPoints - obecnie uzyskane punkty (kwadraty) gracza
* @param opponentsPoints - obecnie uzyskane punkty przeciwnika
* @param currentColor - aktualny kolor gracza
* @param opponentsCurrentColor - aktualny kolor przeciwnika
* @return wartość danego ruchu
*/
private int minMaxEvaluateMove(Colors tryColor, int movesMade, List<Colors> availableColors,
int ourPoints, int opponentsPoints, Colors currentColor, Colors opponentsCurrentColor) {
List<Colors> nextAvailableColors = new ArrayList<Colors>();
nextAvailableColors.addAll(availableColors);
if(movesMade % 2 == 0) {
//our turn
ourPoints = gameTable.makeHypotheticalMove(playerId, tryColor).size();
//DEBUG
/*for(int i = 0; i < movesMade; i++) {
System.out.print(" ");
}
System.out.println("I get " + ourPoints + " points for picking " + tryColor);*/
if(movesMade == depthLevel-1) {
gameTable.undoHypotheticalMove(1);
return ourPoints-opponentsPoints;
}
nextAvailableColors.remove(tryColor);
if(currentColor != null && currentColor != Colors.BLACK) {
nextAvailableColors.add(currentColor);
}
List<Integer> moveValues = new ArrayList<Integer>(4);
for(Colors currentTryColor : nextAvailableColors) {
moveValues.add(minMaxEvaluateMove(currentTryColor,
movesMade+1, nextAvailableColors, ourPoints, opponentsPoints, tryColor, opponentsCurrentColor));
}
gameTable.undoHypotheticalMove(1);
return min(moveValues);
}
else {
//opponent's turn
opponentsPoints = gameTable.makeHypotheticalMove(opponentsPlayerId, tryColor).size();
//DEBUG
/*for(int i = 0; i < movesMade; i++) {
System.out.print(" ");
}
System.out.println("My opponent would get " + opponentsPoints + " points for picking " + tryColor);*/
if(movesMade == depthLevel-1) {
gameTable.undoHypotheticalMove(1);
return ourPoints-opponentsPoints;
}
nextAvailableColors.remove(tryColor);
if(opponentsCurrentColor != null && opponentsCurrentColor != Colors.BLACK) {
nextAvailableColors.add(opponentsCurrentColor);
}
List<Integer> moveValues = new ArrayList<Integer>(4);
for(Colors currentTryColor : nextAvailableColors) {
moveValues.add(minMaxEvaluateMove(currentTryColor,
movesMade+1, nextAvailableColors, ourPoints, opponentsPoints, currentColor, tryColor));
}
gameTable.undoHypotheticalMove(1);
return max(moveValues);
}
}
protected int max(List<Integer> numbers) {
int maxValue = Integer.MIN_VALUE;
for(Integer currentNumber : numbers) {
if(currentNumber > maxValue) {
maxValue = currentNumber;
}
}
return maxValue;
}
protected int min(List<Integer> numbers) {
int minValue = Integer.MAX_VALUE;
for(Integer currentNumber : numbers) {
if(currentNumber < minValue) {
minValue = currentNumber;
}
}
return minValue;
}
}
| m4ttek/BattleOfColors | workspace/BattleOfColors/src/game_player/AIPlayerMinMax.java |
180,083 | package pl.lodz.p.it.ssbd2020.ssbd05.web.auth;
import lombok.extern.java.Log;
import pl.lodz.p.it.ssbd2020.ssbd05.utils.ResourceBundles;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.logging.Level;
/**
* Kontroler odpowiedzialny za wylogowywanie użytkownika
*/
@RequestScoped
@Named
@Log
public class LogoutController {
@Inject
private RoleController roleController;
/**
* Metoda odpowiedzialna za kończenie sesji obecnie zalogowanego użytkownika
*/
public void logout() {
roleController.setSelectedRole(null);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
log.info("["+LocalDateTime.now()+"] User: "+ externalContext.getUserPrincipal().getName() + " session invalidated");
externalContext.invalidateSession();
try {
externalContext.redirect(externalContext.getRequestContextPath() + "/index.xhtml");
} catch (IOException e) {
log.log(Level.WARNING, e.getClass().toString() + " " + e.getMessage());
ResourceBundles.emitErrorMessage(null, "error.default");
}
}
}
| sgruda/KozaNostra | src/main/java/pl/lodz/p/it/ssbd2020/ssbd05/web/auth/LogoutController.java |
180,093 | package com;
import java.io.File;
/**
* Klasa odpowiedzialna za ustawianie ścieżki dostępu do awatarów
*/
public class Avatars {
/** Scieżka dostępu do folderu przechowującego awatary */
private static String avatars_path="Pliki/avatars";
/**
* Metoda ustawiająca ścieżkę dostępu do awataru
* @param numberOfAvatar numer wczytywanego obecnie awataru
* @return metoda zwraca ścieżkę dostępu do odpowiedniego awatara
*/
public static String load_avatars(int numberOfAvatar)
{
String fnameNoExt = null;
File avtrs= new File(avatars_path);
File[] files=avtrs.listFiles();
for (Integer i = 0; i < files.length; i++){
if(i==numberOfAvatar) {
fnameNoExt = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
}
}
return avatars_path+"\\"+fnameNoExt+".png";
}
}
| albertbog/proze20z_bogdanovic_kocemba | Sokoban_ostatnie_starcie/Serwer/src/com/Avatars.java |
180,095 | package com;
import java.io.File;
/**
* Klasa odpowiedzialna za ustawianie ścieżki dostępu do tekstur
*/
public class Textures {
/** Scieżka dostępu do folderu przechowującego tekstury */
private static String textures_path="Pliki/textures";
/**
* Metoda ustawiająca ścieżkę dostępu do tekstury
* @param numberOfTexture numer wczytywanej obecnie tekstury
* @return metoda zwraca ścieżkę dostępu do odpowiedniej tekstury
*/
public static String load_textures(int numberOfTexture)
{
String fnameNoExt = null;
File avtrs= new File(textures_path);
File[] files=avtrs.listFiles();
for (Integer i = 0; i < files.length; i++){
if(i==numberOfTexture) {
fnameNoExt = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
}
}
return textures_path+"\\"+fnameNoExt+".png";
}
}
| albertbog/proze20z_bogdanovic_kocemba | Sokoban_ostatnie_starcie/Serwer/src/com/Textures.java |
180,104 | package pl.sages.kodolamacz;
import java.util.ArrayList;
public class Tablice {
int age; //domyslna wartosc 0
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
// na zmienna typu int nie wstawimy całej tablicy
// int d = new int[5];
Object[] tab = {"abc",1, 4.21};
// tablica jest związana z TYPEM zmiennej a nie jej NAZWĄ
int[] tablica = new int[10];
// to może być mylące;
int tablica2[];
// jesli nie zadeklaruje wartosci w tablicy (prymitywnych)
// to dostana wartosci domyslne, czyli zero
double[] tablicaRzeczywista = new double[5];
String[] napisy = new String[5];
// elementy indeksowane sa od zera
napisy[0] = "Ala";
napisy[1] = "ma";
napisy[2] = "kota";
System.out.println(napisy[3]);
System.out.println(tablica[0]);
int[] wartosci = {1, 4, 8, 12, 35, 88, 99};
int szukana = 5;
int znalezionaPozycja = -1;
for (int i = 0; i < wartosci.length; i++) {
int aktualnaWartosc = wartosci[i];
System.out.println("Obecnie jestem na pozycji "+i +
" a wartość wynosi "+ aktualnaWartosc);
if(szukana == aktualnaWartosc){
System.out.println("Wartości są równe!");
znalezionaPozycja = i;
break; // przerwać wykonywanie pętli
}
}
System.out.println("Znaleziono tutaj "+znalezionaPozycja);
}
}
| bartektartanus/kodolamacz2017 | src/main/java/pl/sages/kodolamacz/Tablice.java |
180,107 | package pl.xcrafters.xcrbungeetools.commands;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.plugin.Command;
import pl.xcrafters.xcrbungeetools.ToolsPlugin;
public class ListCommand extends Command{
ToolsPlugin plugin;
public ListCommand(ToolsPlugin plugin){
super("list", "tools.list", "glist");
this.plugin = plugin;
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, this);
}
@Override
public void execute(CommandSender sender, String[] args){
if(sender.hasPermission("tools.list.admin")) {
String message = "";
int total = 0;
for (ServerInfo srv : ProxyServer.getInstance().getServers().values()) {
int players = plugin.dataManager.onlinePlayers.get(srv.getName()) == null ? 0 : plugin.dataManager.onlinePlayers.get(srv.getName()).size();
total += players;
message += "&8" + srv.getName().toUpperCase() + ": " + (players == 0 ? "&7" : "&6") + players + " ";
}
sender.sendMessage(plugin.color("&8Lacznie graczy: &6" + total + "/" + plugin.configManager.maxSlots));
sender.sendMessage(plugin.color(message));
} else {
int total = 0;
for (ServerInfo srv : ProxyServer.getInstance().getServers().values()) {
int players = plugin.dataManager.onlinePlayers.get(srv.getName()) == null ? 0 : plugin.dataManager.onlinePlayers.get(srv.getName()).size();
total += players;
}
sender.sendMessage(plugin.color("&9Na serwerze jest obecnie &b" + total + " &9na &b" + plugin.configManager.maxSlots + " &9mozliwych."));
}
}
}
| Lojtar/xcrBungeeTools | src/main/java/pl/xcrafters/xcrbungeetools/commands/ListCommand.java |
180,111 | /*
* Copyright (C) 2014 TheMolkaPL - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Aleksander Jagiełło <[email protected]>, 2014
*/
package pl.shg.arcade.api.command.def;
import org.apache.commons.lang3.Validate;
import pl.shg.arcade.api.command.Command;
import pl.shg.arcade.api.command.CommandException;
import pl.shg.arcade.api.command.Sender;
import pl.shg.arcade.api.event.Event;
import pl.shg.arcade.api.map.Map;
import pl.shg.arcade.api.map.MapManager;
import pl.shg.arcade.api.text.Color;
/**
*
* @author Aleksander
*/
public class MapinfoCommand extends Command {
public MapinfoCommand() {
super(new String[] {"mapinfo", "map"},
"Informacje o obecnie granej lub podanej mapie", "map [map...]");
this.setPermission("arcade.command.mapinfo");
}
@Override
public void execute(Sender sender, String[] args) throws CommandException {
MapManager maps = this.getPlugin().getMaps();
if (args.length == 0) {
show(sender, maps.getCurrentMap(), true);
} else {
String targetMap = this.getStringFromArgs(0, args).replace(" ", "_");
int found = 0;
Map result = null;
for (Map map : maps.getMaps()) {
if (map.getName().toLowerCase().contains(targetMap.toLowerCase())) {
found++;
result = map;
}
}
if (found > 1) {
sender.sendError("Znaleziono wiecej niz jedna mape. Pokazywanie 1 z " + found + "...");
}
if (result == null) {
sender.sendError("Nie znaleziono zadnej mapy o podanych kryteriach.");
} else {
show(sender, result, true);
}
}
}
@Override
public int minArguments() {
return 0;
}
public static void show(Sender sender, Map map, boolean full) {
Validate.notNull(sender, "sender can not be null");
Validate.notNull(map, "map can not be null");
sender.sendMessage(Command.getTitle(map.getDisplayName(), Color.GRAY + map.getVersionString()));
// Objective
if (map.getObjective() != null) {
sender.sendMessage(getLine("Cel gry", map.getObjective()));
}
// Authors
String authors = map.getAuthorsString(Color.RED, Color.DARK_PURPLE);
if (map.getAuthors() == null || map.getAuthors().length > 1) {
sender.sendMessage(getLine("Autorzy", authors));
} else {
sender.sendMessage(getLine("Autor", authors));
}
// we can do more with this command by executing an event that modules can listen to!
Event.callEvent(new MapinfoEvent(sender, full));
}
private static String getLine(String key, String value) {
Validate.notNull(key, "key can not be null");
Validate.notNull(value, "value can not be null");
return Color.DARK_PURPLE + Color.BOLD + key + ": " + Color.RESET + Color.RED + value;
}
public static class MapinfoEvent extends Event {
private final Sender sender;
private final boolean full;
public MapinfoEvent(Sender sender, boolean full) {
super(MapinfoEvent.class);
this.sender = sender;
this.full = full;
}
public Sender getSender() {
return this.sender;
}
public boolean isFull() {
return this.full;
}
}
}
| ShootGame/Arcade | src/main/java/pl/shg/arcade/api/command/def/MapinfoCommand.java |
180,112 | package main.buffer;
import main.common.messages.RequestType;
import java.util.Arrays;
abstract public class BufferSelector {
protected Buffer[] mBufferSet;
protected final int[] mBufferCapacities;
protected final int[] mCurrentBufferCapacities;
protected final boolean[] mBufferStatus; // true - obecnie realizuje operacje
protected final int mNumberOfBuffers;
public BufferSelector(Buffer[] bufferSet, int[] bufferCapacities) {
mBufferSet = bufferSet;
mNumberOfBuffers = bufferSet.length;
if (mNumberOfBuffers != bufferCapacities.length) {
mBufferCapacities = new int[mNumberOfBuffers];
Arrays.fill(mBufferCapacities, bufferCapacities[0]);
} else {
mBufferCapacities = bufferCapacities;
}
mBufferStatus = new boolean[mNumberOfBuffers];
Arrays.fill(mBufferStatus, false);
mCurrentBufferCapacities = new int[mNumberOfBuffers];
Arrays.fill(mCurrentBufferCapacities, 0);
}
protected boolean isProductionPossibleForBufferAt(int i, int resources) {
return mBufferCapacities[i] - mCurrentBufferCapacities[i] >= resources && !isBufferLocked(i);
}
protected boolean isConsumptionPossibleForBufferAt(int i, int resources) {
return mCurrentBufferCapacities[i] >= resources && !isBufferLocked(i);
}
abstract public BufferEntryPair getBufferForOperation(RequestType requestType, int resources);
public void lockBuffer(int i, RequestType requestType) {
if (mBufferStatus[i]) {
throw new IllegalStateException("BufferSelector: Buffer " + i + " already locked");
}
mBufferStatus[i] = true;
if (requestType == RequestType.CONSUME) {
mCurrentBufferCapacities[i]--;
} else {
mCurrentBufferCapacities[i]++;
}
}
public void unlockBuffer(int i) {
if (!mBufferStatus[i]) {
throw new IllegalStateException("BufferSelector: Attempt to unlock not locked buffer " + i);
}
mBufferStatus[i] = false;
}
private boolean isBufferLocked(int i) {
return mBufferStatus[i];
}
}
| kkafar/concurrency-theory-lab | csp/src/main/buffer/BufferSelector.java |
180,113 | package skladoweStatyczne;
public class Swiat {
private static final int JABLKO = 666;
//dzieki stalej nie ma kkoniecznosci twozrenai obeiektu
public static void main(String[] args) {
Czlowiek adam = new Czlowiek("Adam", 199);
Czlowiek ewa = new Czlowiek("Ewa", 166);
Czlowiek.sredni_wzrost = (adam.getWzrost() + ewa.getWzrost())/2;
System.out.println("sredni wzrost: " + Czlowiek.sredni_wzrost);
System.out.println("sredni wzrost: " + adam.sredni_wzrost);
System.out.println("sredni wzrost: " + ewa.sredni_wzrost);
//2 ost to zla praktyka
//wypiszSredniWzrost(); (obecnie: private void wypiszSredniWzrost(){)
//metoda main jest metoda statyczna = nie jest powiazana z zadna instancja
//= moznemy sie w niej odnosic tylko do innych metod tatycznych w ramach tej klasy
// ==> wiec teoretycznie trzeba zrobic:
/*
wypiszSredniWzrost wsw = new wypiszSredniWzrost();
wsw.wypiszSredniWzrost();
*/
//zeby odwolac sie pezez sama nazwe to musi byc to metoda statyczna
wypiszSredniWzrost();
}
private static void wypiszSredniWzrost(){
System.out.println("sredni wzrost: " + Czlowiek.sredni_wzrost);
}
}
| hankav21/Java-podstawy | 015 Enkapsulacja i hermetyzacja/skladoweStatyczne/Swiat.java |
180,120 | /*
* Copyright (C) 2015 TheMolkaPL - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Aleksander Jagiełło <[email protected]>, 2015
*/
package pl.shg.arcade.api.development;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import pl.shg.arcade.api.command.Command;
import pl.shg.arcade.api.command.CommandException;
import pl.shg.arcade.api.command.CommandExecutor;
import pl.shg.arcade.api.command.CommandTest;
import pl.shg.arcade.api.command.Sender;
import pl.shg.arcade.api.event.EventTest;
import pl.shg.arcade.api.text.Color;
/**
*
* @author Aleksander
*/
public class TestCommand extends Command {
private static final List<Test> tests = new ArrayList<>();
public TestCommand() {
super(new String[] {"test", "try"},
Development.COMMAND_PREFIX + "Testuj funkcje pluginu Arcade", "test [-l]", new char[] {'l'});
this.setOption("l", "Wyswietl liste dostepnych testów");
this.setPermission("arcade.command.test");
}
@Override
public void execute(Sender sender, String[] args) throws CommandException {
if (args.length == 0 || args[0].equals("-l")) {
this.printList(sender);
} else {
for (Test test : getTests()) {
if (test.getName().equals(args[0].toLowerCase())) {
this.performTest(sender, args, test);
return;
}
}
sender.sendError("Nie znaleziono zadnego testu o nazwie " + args[0] + ".");
}
}
@Override
public int minArguments() {
return 0;
}
private void performTest(Sender sender, String[] args, Test test) throws CommandException {
if (!test.isConsoleAllowed() && sender.isConsole()) {
sender.sendError("Nie mozna wykonac tego testu z poziomu konsoli.");
} if (args.length < test.minArguments()) {
sender.sendError("Podano zbyt malo argumentów do wykonania testu.");
} else {
try {
long millis = System.currentTimeMillis();
test.execute(sender, args);
sender.sendError("Test zostal wykonany w " + (System.currentTimeMillis() - millis) + " milisekund.");
} catch (CommandException ex) {
sender.sendError(ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
sender.sendError("Nie udalo sie wykonac testu " + test.getName() + " poniewaz wykryto naganny blad.");
}
}
}
private void printList(Sender sender) {
List<Test> list = getTests();
if (list.isEmpty()) {
sender.sendError("Obecnie brak mozliwych testów do wykonania.");
} else {
sender.sendMessage(Command.getTitle("Lista testów", Color.GRAY + "(" + list.size() + ")"));
for (Test test : list) {
String usage = test.getUsage();
if (usage == null) {
usage = "";
} else {
usage = " " + usage;
}
String desc = test.getDescription();
if (desc == null) {
desc = Color.ITALIC + "Brak dostepnego opisu.";
}
sender.sendMessage(Color.GREEN + test.getName() + usage + Color.YELLOW + " - " + desc);
}
sender.sendMessage(Color.DARK_AQUA + "Wykonaj test uzywajac komendy /test <test>.");
}
}
public static List<Test> getTests() {
return tests;
}
public static void register(Test test) {
Validate.notNull(test);
tests.add(test);
}
public static void registerDefaults() {
if (!getTests().isEmpty()) {
throw new UnsupportedOperationException("Could not set default tests twice");
}
new CommandTest().register();
new EventTest().register();
}
public static abstract class Test implements CommandExecutor {
private final String name;
private final String usage;
private final boolean console;
private final String description;
public Test(String name, String usage, boolean console, String description) {
Validate.notNull(name);
this.name = name.toLowerCase();
this.usage = usage;
this.console = console;
this.description = description;
}
@Override
public int minArguments() {
return 1;
}
public String getName() {
return this.name;
}
public String getUsage() {
return this.usage;
}
public String getDescription() {
return this.description;
}
public boolean isConsoleAllowed() {
return this.console;
}
public void register() {
TestCommand.register(this);
}
}
}
| ShootGame/Arcade | src/main/java/pl/shg/arcade/api/development/TestCommand.java |
180,121 | package com.example.shamanApi.service;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.stream.Collectors;
/**
* klasa generująca Tokena o ważności 1 godziny
* */
@Service
public class TokenService {
private final JwtEncoder encoder;
public TokenService(JwtEncoder encoder) {
this.encoder = encoder;
}
/**
*funkcja generująca tokena
*
* @param authentication obecnie używana autenktykacja przez API
* @return wartość wygenerowanego tokena
* */
public String generateToken(Authentication authentication) {
Instant now = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(24, ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope", scope)
.build();
return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
}
| broniuu/shaman-web-app | api/src/main/java/com/example/shamanApi/service/TokenService.java |
180,138 | /**
* 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.drools.base.factmodel;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.drools.base.phreak.Reactive;
import org.kie.api.definition.type.Annotation;
import org.kie.api.definition.type.FactField;
import org.kie.api.definition.type.FactType;
/**
* Declares a class to be dynamically created
*/
public class ClassDefinition
implements
FactType {
public enum TRAITING_MODE { NONE, BASIC, LOGICAL }
private String className;
private String superClass;
private String[] interfaces;
private transient Class< ? > definedClass;
private TRAITING_MODE traitable;
private boolean abstrakt = false;
private Map<String, Object> metaData;
protected LinkedHashMap<String, FieldDefinition> fields = new LinkedHashMap<>();
private Map<String, AnnotationDefinition> annotations;
private Map<String, List<String>> modifiedPropsByMethod;
public ClassDefinition() {
this( null,
null,
null );
}
public ClassDefinition( String className ) {
this( className,
null,
null );
}
public ClassDefinition( String className,
String superClass,
String[] interfaces ) {
this.setClassName( className );
this.setSuperClass( superClass );
this.setInterfaces( interfaces );
}
public ClassDefinition( Class<?> cls ) {
this.definedClass = cls;
this.setClassName( cls.getCanonicalName() );
this.setSuperClass( cls.getSuperclass() != null ? cls.getSuperclass().getCanonicalName() : null );
String[] interfaces = new String[cls.getInterfaces().length];
int i = 0;
for (Class<?> interfaze : cls.getInterfaces()) {
interfaces[i++] = interfaze.getCanonicalName();
}
this.setInterfaces( interfaces );
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.className = (String) in.readObject();
this.superClass = (String) in.readObject();
this.interfaces = (String[]) in.readObject();
this.fields = (LinkedHashMap<String, FieldDefinition>) in.readObject();
this.annotations = (Map<String, AnnotationDefinition>) in.readObject();
this.modifiedPropsByMethod = (Map<String, List<String>>) in.readObject();
this.traitable = (ClassDefinition.TRAITING_MODE) in.readObject();
this.abstrakt = in.readBoolean();
this.metaData = (HashMap<String,Object>) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( this.className );
out.writeObject( this.superClass );
out.writeObject( this.interfaces );
out.writeObject( this.fields );
out.writeObject( this.annotations );
out.writeObject( this.modifiedPropsByMethod);
out.writeObject( this.traitable );
out.writeBoolean( this.abstrakt );
out.writeObject( this.metaData );
}
/**
* @return Returns the name.
*/
public final String getClassName() {
return this.className;
}
/**
* @param className The name to set.
*/
public final void setClassName(final String className) {
this.className = className;
}
/**
* @return Returns the className.
*/
public final Class< ? > getDefinedClass() {
return definedClass;
}
/**
* @param definedClass The class to set.
*/
public void setDefinedClass(final Class< ? > definedClass) {
this.definedClass = definedClass;
}
/**
* Adds a field definition to this class
* @param attr
*/
public final void addField(FieldDefinition attr) {
this.fields.put( attr.getName(),
attr );
}
/**
* @return Returns an unmodifiable collection of field definitions
*/
public final Collection<FieldDefinition> getFieldsDefinitions() {
return Collections.unmodifiableCollection( this.fields.values() );
}
/**
* Returns the field definition object for the given field name
*
* @param fieldName
* @return
*/
public FieldDefinition getField(final String fieldName) {
return this.fields.get( fieldName );
}
public FieldDefinition getFieldByAlias( String alias ) {
for ( FactField factField : getFields() ) {
FieldDefinition def = (FieldDefinition) factField;
if ( def.resolveAlias().equals( alias ) ) {
return def;
}
}
return null;
}
/**
* Returns the field at position index, as defined by the builder using the @position annotation
* @param index
* @return the index-th field
*/
public FieldDefinition getField(int index) {
if (index >= fields.size() || index < 0) {
return null;
}
Iterator<FieldDefinition> iter = fields.values().iterator();
for (int j = 0; j < index ; j++) {
iter.next();
}
return iter.next();
}
/**
* @return Returns the interfaces.
*/
public final String[] getInterfaces() {
return interfaces;
}
/**
* @param interfaces The interfaces to set.
*/
public final void setInterfaces(String[] interfaces) {
this.interfaces = (interfaces != null) ? interfaces : new String[0];
}
public final void addInterface(String interfaze) {
if (interfaces == null) {
interfaces = new String[] { interfaze };
} else {
String[] i2 = new String[interfaces.length+1];
System.arraycopy( interfaces, 0, i2, 0, interfaces.length );
i2[interfaces.length] = interfaze;
this.interfaces = i2;
}
}
/**
* @return Returns the superClass.
*/
public final String getSuperClass() {
return superClass;
}
/**
* @param superClass The superClass to set.
*/
public final void setSuperClass(final String superClass) {
this.superClass = (superClass != null) ? superClass : "java.lang.Object";
}
public String getName() {
return getClassName();
}
public String getSimpleName() {
return getClassName().substring( getClassName().lastIndexOf( '.' ) + 1 );
}
public String getPackageName() {
return getClassName().substring( 0, getClassName().lastIndexOf( '.' ) );
}
public Object newInstance() throws InstantiationException,
IllegalAccessException {
return this.definedClass.newInstance();
}
public Class< ? > getFactClass() {
return getDefinedClass();
}
public List<FactField> getFields() {
return new ArrayList<>( fields.values() );
}
public Object get(Object bean,
String field) {
FieldDefinition fieldDefinition = getField( field );
if (fieldDefinition != null) {
return fieldDefinition.getFieldAccessor().getValue( bean );
}
return null;
}
public void set(Object bean,
String field,
Object value) {
FieldDefinition fieldDefinition = getField( field );
if (fieldDefinition != null) {
fieldDefinition.getFieldAccessor().setValue( bean, value );
}
}
public Map<String, Object> getAsMap(Object bean) {
Map<String, Object> m = new HashMap<>( fields.size() );
for (Map.Entry<String, FieldDefinition> ent : this.fields.entrySet()) {
Object val = ent.getValue().getFieldAccessor().getValue(bean);
m.put(ent.getKey(),
val);
}
return m;
}
public void setFromMap(Object bean,
Map<String, Object> data) {
for (Map.Entry<String, Object> ent : data.entrySet()) {
set(bean,
ent.getKey(),
ent.getValue());
}
}
public void addAnnotation(AnnotationDefinition annotationDefinition) {
if (this.annotations == null) {
this.annotations = new HashMap<>();
}
this.annotations.put( annotationDefinition.getName(), annotationDefinition );
}
public Collection<AnnotationDefinition> getAnnotations() {
return annotations != null ? annotations.values() : Collections.emptyList();
}
public AnnotationDefinition getAnnotation(Class<?> annotationClass) {
return annotations != null ? annotations.get(annotationClass.getName()) : null;
}
public List<Annotation> getClassAnnotations() {
return Collections.unmodifiableList( new ArrayList( getAnnotations() ) );
}
public Map<String, Object> getMetaData() {
return metaData;
}
public Object getMetaData(String name) {
return metaData != null ? metaData.get(name) : null;
}
public void addMetaData( String key, Object value ) {
if ( this.metaData == null ) {
metaData = new HashMap<>();
}
metaData.put( key, value );
}
public void addModifiedPropsByMethod(Method method, List<String> props) {
if (modifiedPropsByMethod == null) {
modifiedPropsByMethod = new HashMap<>();
}
String methodName = modifiedPropsByMethodKey(method);
modifiedPropsByMethod.put(methodName, props);
}
public List<String> getModifiedPropsByMethod(Method method) {
return getModifiedPropsByMethod(method.getName(), method.getParameterTypes().length );
}
public List<String> getModifiedPropsByMethod(String methodName, int args) {
if (modifiedPropsByMethod == null) {
return null;
}
List<String> byExactNumberOfArgs = modifiedPropsByMethod.get( methodName + "_" + args );
List<String> bestEffortVarArgs = modifiedPropsByMethod.get( methodName + "_*" );
if ( byExactNumberOfArgs != null ) {
return byExactNumberOfArgs;
}
return bestEffortVarArgs; // << indeed maybe null
}
public static String modifiedPropsByMethodKey(Method method) {
return method.getName() + "_" + ( method.isVarArgs() ? "*" : method.getParameterTypes().length );
}
public boolean isReactive() {
return getAnnotation( Reactive.class ) != null;
}
public boolean isTraitable() {
return traitable != null && traitable != TRAITING_MODE.NONE;
}
public void setTraitable( boolean traitable ) {
setTraitable( traitable, false );
}
public void setTraitable( boolean traitable, boolean enableLogical ) {
if ( ! traitable ) {
this.traitable = TRAITING_MODE.NONE;
} else {
this.traitable = enableLogical ? TRAITING_MODE.LOGICAL : TRAITING_MODE.BASIC;
}
}
public boolean isFullTraiting() {
return this.traitable == TRAITING_MODE.LOGICAL;
}
public boolean isAbstrakt() {
return abstrakt;
}
public void setAbstrakt(boolean abstrakt) {
this.abstrakt = abstrakt;
}
public String toString() {
return "ClassDefinition{" +
"className='" + className + '\'' +
", superClass='" + superClass + '\'' +
", interfaces=" + (interfaces == null ? null : Arrays.asList(interfaces)) +
", definedClass=" + definedClass +
", traitable=" + traitable +
", abstract=" + abstrakt +
", fields=" + fields +
", annotations=" + annotations +
'}';
}
}
| apache/incubator-kie-drools | drools-base/src/main/java/org/drools/base/factmodel/ClassDefinition.java |
180,139 | /*
* Copyright 2014 Chris Banes
*
* 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 app.philm.in;
public class Constants {
public static final String TRAKT_API_KEY = "6e9904413059e7d847bbd28f0d71da1ad36d1588";
public static final String TMDB_API_KEY = "f413bc4bacac8dff174a909f8ef535ae";
public static final String TRAKT_ACCOUNT_TYPE = "app.philm.in.account";
public static final String TRAKT_AUTHTOKEN_PASSWORD_TYPE = "password";
private static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
public static final long FUTURE_SOON_THRESHOLD = 30 * DAY_IN_MILLIS;
public static final long STALE_USER_PROFILE_THRESHOLD = 3 * DAY_IN_MILLIS;
public static final long STALE_MOVIE_DETAIL_THRESHOLD = 2 * DAY_IN_MILLIS;
public static final long FULL_MOVIE_DETAIL_ATTEMPT_THRESHOLD = 60 * 60 * 1000; // 60 secs
public static final int FILTER_HIGHLY_RATED = 70;
public static final boolean DEBUG = true;
public static final boolean DEBUG_NETWORK = false;
public static final String TRAKT_MESSAGE_ITEM_REPLACE = "[item]";
public static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
public static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
}
| chrisbanes/philm | lib/src/main/java/app/philm/in/Constants.java |
180,142 | /*
* Copyright 2016 The Netty Project
*
* The Netty Project 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.util;
public interface ResourceLeakTracker<T> {
/**
* Records the caller's current stack trace so that the {@link ResourceLeakDetector} can tell where the leaked
* resource was accessed lastly. This method is a shortcut to {@link #record(Object) record(null)}.
*/
void record();
/**
* Records the caller's current stack trace and the specified additional arbitrary information
* so that the {@link ResourceLeakDetector} can tell where the leaked resource was accessed lastly.
*/
void record(Object hint);
/**
* Close the leak so that {@link ResourceLeakTracker} does not warn about leaked resources.
* After this method is called a leak associated with this ResourceLeakTracker should not be reported.
*
* @return {@code true} if called first time, {@code false} if called already
*/
boolean close(T trackedObject);
}
| netty/netty | common/src/main/java/io/netty/util/ResourceLeakTracker.java |
180,143 | class Usage {
void usage() {
test.AKt.a();
}
} | JetBrains/kotlin | jps/jps-plugin/testData/incremental/withJava/kotlinUsedInJava/packageFileAdded/Usage.java |
180,145 | package mindustry.world.blocks.defense;
import arc.graphics.*;
import arc.graphics.g2d.*;
import arc.math.*;
import arc.util.*;
import arc.util.io.*;
import mindustry.annotations.Annotations.*;
import mindustry.graphics.*;
import mindustry.world.meta.*;
import static mindustry.Vars.*;
public class ShieldWall extends Wall{
public float shieldHealth = 900f;
public float breakCooldown = 60f * 10f;
public float regenSpeed = 2f;
public Color glowColor = Color.valueOf("ff7531").a(0.5f);
public float glowMag = 0.6f, glowScl = 8f;
public @Load("@-glow") TextureRegion glowRegion;
public ShieldWall(String name){
super(name);
update = true;
}
@Override
public void setStats(){
super.setStats();
stats.add(Stat.shieldHealth, shieldHealth);
}
public class ShieldWallBuild extends WallBuild{
public float shield = shieldHealth, shieldRadius = 0f;
public float breakTimer;
@Override
public void draw(){
Draw.rect(block.region, x, y);
if(shieldRadius > 0){
float radius = shieldRadius * tilesize * size / 2f;
Draw.z(Layer.shields);
Draw.color(team.color, Color.white, Mathf.clamp(hit));
if(renderer.animateShields){
Fill.square(x, y, radius);
}else{
Lines.stroke(1.5f);
Draw.alpha(0.09f + Mathf.clamp(0.08f * hit));
Fill.square(x, y, radius);
Draw.alpha(1f);
Lines.poly(x, y, 4, radius, 45f);
Draw.reset();
}
Draw.reset();
Drawf.additive(glowRegion, glowColor, (1f - glowMag + Mathf.absin(glowScl, glowMag)) * shieldRadius, x, y, 0f, Layer.blockAdditive);
}
}
@Override
public void updateTile(){
if(breakTimer > 0){
breakTimer -= Time.delta;
}else{
//regen when not broken
shield = Mathf.clamp(shield + regenSpeed * edelta(), 0f, shieldHealth);
}
if(hit > 0){
hit -= Time.delta / 10f;
hit = Math.max(hit, 0f);
}
shieldRadius = Mathf.lerpDelta(shieldRadius, broken() ? 0f : 1f, 0.12f);
}
public boolean broken(){
return breakTimer > 0 || !canConsume();
}
@Override
public void pickedUp(){
shieldRadius = 0f;
}
@Override
public void damage(float damage){
float shieldTaken = broken() ? 0f : Math.min(shield, damage);
shield -= shieldTaken;
if(shieldTaken > 0){
hit = 1f;
}
//shield was destroyed, needs to go down
if(shield <= 0.00001f && shieldTaken > 0){
breakTimer = breakCooldown;
}
if(damage - shieldTaken > 0){
super.damage(damage - shieldTaken);
}
}
@Override
public void write(Writes write){
super.write(write);
write.f(shield);
}
@Override
public void read(Reads read, byte revision){
super.read(read, revision);
shield = read.f();
if(shield > 0) shieldRadius = 1f;
}
}
}
| Anuken/Mindustry | core/src/mindustry/world/blocks/defense/ShieldWall.java |
180,146 | package com.alibaba.druid.admin.model.dto;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author linchtech
* @date 2020-09-16 18:32
**/
@Data
@NoArgsConstructor
public class DataSourceResult {
@JSONField(name = "ResultCode")
private int ResultCode;
@JSONField(name = "Content")
private List<ContentBean> Content;
@NoArgsConstructor
@Data
public static class ContentBean {
private String serviceId;
@JSONField(name = "Identity")
private int Identity;
@JSONField(name = "Name")
private String Name;
@JSONField(name = "DbType")
private String DbType;
@JSONField(name = "DriverClassName")
private String DriverClassName;
@JSONField(name = "URL")
private String URL;
@JSONField(name = "UserName")
private String UserName;
@JSONField(name = "WaitThreadCount")
private int WaitThreadCount;
@JSONField(name = "NotEmptyWaitCount")
private int NotEmptyWaitCount;
@JSONField(name = "NotEmptyWaitMillis")
private int NotEmptyWaitMillis;
@JSONField(name = "PoolingCount")
private int PoolingCount;
@JSONField(name = "PoolingPeak")
private int PoolingPeak;
@JSONField(name = "PoolingPeakTime")
private String PoolingPeakTime;
@JSONField(name = "ActiveCount")
private int ActiveCount;
@JSONField(name = "ActivePeak")
private int ActivePeak;
@JSONField(name = "ActivePeakTime")
private String ActivePeakTime;
@JSONField(name = "InitialSize")
private int InitialSize;
@JSONField(name = "MinIdle")
private int MinIdle;
@JSONField(name = "MaxActive")
private int MaxActive;
@JSONField(name = "QueryTimeout")
private int QueryTimeout;
@JSONField(name = "TransactionQueryTimeout")
private int TransactionQueryTimeout;
@JSONField(name = "LoginTimeout")
private int LoginTimeout;
@JSONField(name = "ValidConnectionCheckerClassName")
private String ValidConnectionCheckerClassName;
@JSONField(name = "ExceptionSorterClassName")
private String ExceptionSorterClassName;
@JSONField(name = "TestOnBorrow")
private boolean TestOnBorrow;
@JSONField(name = "TestOnReturn")
private boolean TestOnReturn;
@JSONField(name = "TestWhileIdle")
private boolean TestWhileIdle;
@JSONField(name = "DefaultAutoCommit")
private boolean DefaultAutoCommit;
@JSONField(name = "DefaultReadOnly")
private Object DefaultReadOnly;
@JSONField(name = "DefaultTransactionIsolation")
private Object DefaultTransactionIsolation;
@JSONField(name = "LogicConnectCount")
private int LogicConnectCount;
@JSONField(name = "LogicCloseCount")
private int LogicCloseCount;
@JSONField(name = "LogicConnectErrorCount")
private int LogicConnectErrorCount;
@JSONField(name = "PhysicalConnectCount")
private int PhysicalConnectCount;
@JSONField(name = "PhysicalCloseCount")
private int PhysicalCloseCount;
@JSONField(name = "PhysicalConnectErrorCount")
private int PhysicalConnectErrorCount;
@JSONField(name = "ExecuteCount")
private int ExecuteCount;
@JSONField(name = "ExecuteUpdateCount")
private int ExecuteUpdateCount;
@JSONField(name = "ExecuteQueryCount")
private int ExecuteQueryCount;
@JSONField(name = "ExecuteBatchCount")
private int ExecuteBatchCount;
@JSONField(name = "ErrorCount")
private int ErrorCount;
@JSONField(name = "CommitCount")
private int CommitCount;
@JSONField(name = "RollbackCount")
private int RollbackCount;
@JSONField(name = "PSCacheAccessCount")
private int PSCacheAccessCount;
@JSONField(name = "PSCacheHitCount")
private int PSCacheHitCount;
@JSONField(name = "PSCacheMissCount")
private int PSCacheMissCount;
@JSONField(name = "StartTransactionCount")
private int StartTransactionCount;
@JSONField(name = "RemoveAbandoned")
private boolean RemoveAbandoned;
@JSONField(name = "ClobOpenCount")
private long ClobOpenCount;
@JSONField(name = "BlobOpenCount")
private int BlobOpenCount;
@JSONField(name = "KeepAliveCheckCount")
private int KeepAliveCheckCount;
@JSONField(name = "KeepAlive")
private boolean KeepAlive;
@JSONField(name = "FailFast")
private boolean FailFast;
@JSONField(name = "MaxWait")
private int MaxWait;
@JSONField(name = "MaxWaitThreadCount")
private int MaxWaitThreadCount;
@JSONField(name = "PoolPreparedStatements")
private boolean PoolPreparedStatements;
@JSONField(name = "MaxPoolPreparedStatementPerConnectionSize")
private int MaxPoolPreparedStatementPerConnectionSize;
@JSONField(name = "MinEvictableIdleTimeMillis")
private int MinEvictableIdleTimeMillis;
@JSONField(name = "MaxEvictableIdleTimeMillis")
private int MaxEvictableIdleTimeMillis;
@JSONField(name = "LogDifferentThread")
private boolean LogDifferentThread;
@JSONField(name = "RecycleErrorCount")
private int RecycleErrorCount;
@JSONField(name = "PreparedStatementOpenCount")
private int PreparedStatementOpenCount;
@JSONField(name = "PreparedStatementClosedCount")
private int PreparedStatementClosedCount;
@JSONField(name = "UseUnfairLock")
private boolean UseUnfairLock;
@JSONField(name = "InitGlobalVariants")
private boolean InitGlobalVariants;
@JSONField(name = "InitVariants")
private boolean InitVariants;
@JSONField(name = "FilterClassNames")
private List<String> FilterClassNames;
@JSONField(name = "TransactionHistogram")
private List<Integer> TransactionHistogram;
@JSONField(name = "ConnectionHoldTimeHistogram")
private List<Integer> ConnectionHoldTimeHistogram;
}
}
| alibaba/druid | druid-admin/src/main/java/com/alibaba/druid/admin/model/dto/DataSourceResult.java |
180,147 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface KeycloakTransaction {
void begin();
void commit();
void rollback();
void setRollbackOnly();
boolean getRollbackOnly();
boolean isActive();
}
| keycloak/keycloak | server-spi/src/main/java/org/keycloak/models/KeycloakTransaction.java |
180,148 | /*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.tools.nsc.profile;
import javax.management.ObjectName;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
@SuppressWarnings("unused")
public abstract class ExtendedThreadMxBean implements ThreadMXBean {
static final ExtendedThreadMxBean proxy;
static {
ExtendedThreadMxBean local;
ThreadMXBean threadMx = ManagementFactory.getThreadMXBean();
try {
Class cls = Class.forName("com.sun.management.ThreadMXBean");
if (cls.isInstance(threadMx)) {
local = new SunThreadMxBean(threadMx);
} else {
local = new OtherThreadMxBean(threadMx);
}
} catch (ClassNotFoundException e) {
local = new OtherThreadMxBean(threadMx);
}
proxy = local;
}
protected final ThreadMXBean underlying;
protected ExtendedThreadMxBean(ThreadMXBean underlying) {
this.underlying = underlying;
}
public abstract long[] getThreadUserTime(long[] longs) throws Exception;
public abstract boolean isThreadAllocatedMemoryEnabled() throws Exception;
public abstract void setThreadAllocatedMemoryEnabled(boolean b) throws Exception;
public abstract long getThreadAllocatedBytes(long l) throws Exception;
public abstract long[] getThreadAllocatedBytes(long[] longs) throws Exception;
public abstract boolean isThreadAllocatedMemorySupported() throws Exception;
public abstract long[] getThreadCpuTime(long[] longs) throws Exception;
//common features from java.lang.management.ThreadMXBean
@Override
public int getThreadCount() {
return underlying.getThreadCount();
}
@Override
public int getPeakThreadCount() {
return underlying.getPeakThreadCount();
}
@Override
public long getTotalStartedThreadCount() {
return underlying.getTotalStartedThreadCount();
}
@Override
public int getDaemonThreadCount() {
return underlying.getDaemonThreadCount();
}
@Override
public long[] getAllThreadIds() {
return underlying.getAllThreadIds();
}
@Override
public ThreadInfo getThreadInfo(long id) {
return underlying.getThreadInfo(id);
}
@Override
public ThreadInfo[] getThreadInfo(long[] ids) {
return underlying.getThreadInfo(ids);
}
@Override
public ThreadInfo getThreadInfo(long id, int maxDepth) {
return underlying.getThreadInfo(id, maxDepth);
}
@Override
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) {
return underlying.getThreadInfo(ids, maxDepth);
}
@Override
public boolean isThreadContentionMonitoringSupported() {
return underlying.isThreadContentionMonitoringSupported();
}
@Override
public boolean isThreadContentionMonitoringEnabled() {
return underlying.isThreadContentionMonitoringEnabled();
}
@Override
public void setThreadContentionMonitoringEnabled(boolean enable) {
underlying.setThreadContentionMonitoringEnabled(enable);
}
@Override
public long getCurrentThreadCpuTime() {
return underlying.getCurrentThreadCpuTime();
}
@Override
public long getCurrentThreadUserTime() {
return underlying.getCurrentThreadUserTime();
}
@Override
public long getThreadCpuTime(long id) {
return underlying.getThreadCpuTime(id);
}
@Override
public long getThreadUserTime(long id) {
return underlying.getThreadUserTime(id);
}
@Override
public boolean isThreadCpuTimeSupported() {
return underlying.isThreadCpuTimeSupported();
}
@Override
public boolean isCurrentThreadCpuTimeSupported() {
return underlying.isCurrentThreadCpuTimeSupported();
}
@Override
public boolean isThreadCpuTimeEnabled() {
return underlying.isThreadCpuTimeEnabled();
}
@Override
public void setThreadCpuTimeEnabled(boolean enable) {
underlying.setThreadCpuTimeEnabled(enable);
}
@Override
public long[] findMonitorDeadlockedThreads() {
return underlying.findMonitorDeadlockedThreads();
}
@Override
public void resetPeakThreadCount() {
underlying.resetPeakThreadCount();
}
@Override
public long[] findDeadlockedThreads() {
return underlying.findDeadlockedThreads();
}
@Override
public boolean isObjectMonitorUsageSupported() {
return underlying.isObjectMonitorUsageSupported();
}
@Override
public boolean isSynchronizerUsageSupported() {
return underlying.isSynchronizerUsageSupported();
}
@Override
public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers) {
return underlying.getThreadInfo(ids, lockedMonitors, lockedSynchronizers);
}
@Override
public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) {
return underlying.dumpAllThreads(lockedMonitors, lockedSynchronizers);
}
@Override
public ObjectName getObjectName() {
return underlying.getObjectName();
}
}
class OtherThreadMxBean extends ExtendedThreadMxBean {
OtherThreadMxBean(ThreadMXBean underlying) {
super(underlying);
}
@Override
public long[] getThreadUserTime(long[] longs) throws Exception {
return new long[0];
}
@Override
public boolean isThreadAllocatedMemoryEnabled() throws Exception {
return false;
}
@Override
public void setThreadAllocatedMemoryEnabled(boolean b) throws Exception {
}
@Override
public long getThreadAllocatedBytes(long l) throws Exception {
return -1;
}
@Override
public long[] getThreadAllocatedBytes(long[] longs) throws Exception {
return new long[0];
}
@Override
public boolean isThreadAllocatedMemorySupported() throws Exception {
return false;
}
@Override
public long[] getThreadCpuTime(long[] longs) throws Exception {
return new long[0];
}
}
class SunThreadMxBean extends ExtendedThreadMxBean {
private final ThreadMXBean real;
private final Method getThreadUserTimeMethod;
private final Method isThreadAllocatedMemoryEnabledMethod;
private final Method setThreadAllocatedMemoryEnabledMethod;
private final Method getThreadAllocatedBytesMethod1;
private final Method getThreadAllocatedBytesMethod2;
private final Method isThreadAllocatedMemorySupportedMethod;
private final Method getThreadCpuTimeMethod;
public SunThreadMxBean(ThreadMXBean underlying) {
super(underlying);
this.real = underlying;
try {
Class<?> cls = Class.forName("com.sun.management.ThreadMXBean");
getThreadUserTimeMethod = cls.getMethod("getThreadUserTime", long[].class);
isThreadAllocatedMemoryEnabledMethod = cls.getMethod("isThreadAllocatedMemoryEnabled");
setThreadAllocatedMemoryEnabledMethod = cls.getMethod("setThreadAllocatedMemoryEnabled", Boolean.TYPE);
getThreadAllocatedBytesMethod1 = cls.getMethod("getThreadAllocatedBytes", Long.TYPE);
getThreadAllocatedBytesMethod2 = cls.getMethod("getThreadAllocatedBytes", long[].class);
isThreadAllocatedMemorySupportedMethod = cls.getMethod("isThreadAllocatedMemorySupported");
getThreadCpuTimeMethod = cls.getMethod("getThreadCpuTime", long[].class);
getThreadUserTimeMethod.setAccessible(true);
isThreadAllocatedMemoryEnabledMethod.setAccessible(true);
setThreadAllocatedMemoryEnabledMethod.setAccessible(true);
getThreadAllocatedBytesMethod1.setAccessible(true);
getThreadAllocatedBytesMethod2.setAccessible(true);
isThreadAllocatedMemorySupportedMethod.setAccessible(true);
getThreadCpuTimeMethod.setAccessible(true);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public boolean isExtended() {
return true;
}
public long[] getThreadUserTime(long[] longs) throws Exception {
return (long[]) getThreadUserTimeMethod.invoke(real, longs);
}
public boolean isThreadAllocatedMemoryEnabled() throws Exception {
return (boolean) isThreadAllocatedMemoryEnabledMethod.invoke(real);
}
public void setThreadAllocatedMemoryEnabled(boolean b) throws Exception {
setThreadAllocatedMemoryEnabledMethod.invoke(real, b);
}
public long getThreadAllocatedBytes(long l) throws Exception {
return (long) getThreadAllocatedBytesMethod1.invoke(real,l);
}
public long[] getThreadAllocatedBytes(long[] longs) throws Exception {
return (long[]) getThreadAllocatedBytesMethod2.invoke(real, longs);
}
public boolean isThreadAllocatedMemorySupported() throws Exception {
return (boolean) isThreadAllocatedMemorySupportedMethod.invoke(real);
}
public long[] getThreadCpuTime(long[] longs) throws Exception {
return (long[]) getThreadCpuTimeMethod.invoke(real, longs);
}
}
| scala/scala | src/compiler/scala/tools/nsc/profile/ExtendedThreadMxBean.java |
180,150 | /*
* Copyright (C) 2021 The Dagger Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.hilt.android.internal.managers;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import android.os.Build;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import dagger.hilt.android.AndroidEntryPoint;
import dagger.hilt.android.internal.managers.ViewComponentManager.FragmentContextWrapper;
import dagger.hilt.android.testing.HiltAndroidRule;
import dagger.hilt.android.testing.HiltAndroidTest;
import dagger.hilt.android.testing.HiltTestApplication;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
@HiltAndroidTest
@RunWith(AndroidJUnit4.class)
// Robolectric requires Java9 to run API 29 and above, so use API 28 instead
@Config(sdk = Build.VERSION_CODES.P, application = HiltTestApplication.class)
public final class FragmentContextWrapperLeakTest {
/** An activity to test injection. */
@AndroidEntryPoint(FragmentActivity.class)
public static final class TestActivity extends Hilt_FragmentContextWrapperLeakTest_TestActivity {}
/** A fragment to test injection. */
@AndroidEntryPoint(Fragment.class)
public static final class TestFragment extends Hilt_FragmentContextWrapperLeakTest_TestFragment {}
@Rule public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@Test
public void testFragmentContextWrapperDoesNotLeakFragment() {
try (ActivityScenario<TestActivity> scenario = ActivityScenario.launch(TestActivity.class)) {
TestFragment fragment = new TestFragment();
scenario.onActivity(
activity ->
activity
.getSupportFragmentManager()
.beginTransaction()
.add(fragment, "TestFragment")
.commitNow());
FragmentContextWrapper fragmentContextWrapper =
(FragmentContextWrapper) fragment.getContext();
assertThat(fragmentContextWrapper.getFragment()).isEqualTo(fragment);
scenario.moveToState(Lifecycle.State.DESTROYED);
NullPointerException exception =
assertThrows(NullPointerException.class, fragmentContextWrapper::getFragment);
assertThat(exception).hasMessageThat().contains("The fragment has already been destroyed");
}
}
}
| google/dagger | javatests/dagger/hilt/android/internal/managers/FragmentContextWrapperLeakTest.java |
180,154 | /*
* Copyright (c) 2016 JFoenix
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.jfoenix.controls;
import com.jfoenix.utils.JFXNodeUtils;
import javafx.beans.InvalidationListener;
import javafx.beans.WeakInvalidationListener;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import java.lang.ref.WeakReference;
/**
* JFXTreeCell is simple material design implementation of a tree cell.
*
* @author Shadi Shaheen
* @version 1.0
* @since 2017-02-15
*/
public class JFXTreeCell<T> extends TreeCell<T> {
protected JFXRippler cellRippler = new JFXRippler(this){
@Override
protected Node getMask() {
Region clip = new Region();
JFXNodeUtils.updateBackground(JFXTreeCell.this.getBackground(), clip);
double width = control.getLayoutBounds().getWidth();
double height = control.getLayoutBounds().getHeight();
clip.resize(width, height);
return clip;
}
@Override
protected void positionControl(Node control) {
// do nothing
}
};
private HBox hbox;
private StackPane selectedPane = new StackPane();
private InvalidationListener treeItemGraphicInvalidationListener = observable -> updateDisplay(getItem(),
isEmpty());
private WeakInvalidationListener weakTreeItemGraphicListener = new WeakInvalidationListener(
treeItemGraphicInvalidationListener);
private WeakReference<TreeItem<T>> treeItemRef;
public JFXTreeCell() {
selectedPane.getStyleClass().add("selection-bar");
selectedPane.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
selectedPane.setPrefWidth(3);
selectedPane.setMouseTransparent(true);
selectedProperty().addListener((o, oldVal, newVal) -> selectedPane.setVisible(newVal ? true : false));
final InvalidationListener treeItemInvalidationListener = observable -> {
TreeItem<T> oldTreeItem = treeItemRef == null ? null : treeItemRef.get();
if (oldTreeItem != null) {
oldTreeItem.graphicProperty().removeListener(weakTreeItemGraphicListener);
}
TreeItem<T> newTreeItem = getTreeItem();
if (newTreeItem != null) {
newTreeItem.graphicProperty().addListener(weakTreeItemGraphicListener);
treeItemRef = new WeakReference<>(newTreeItem);
}
};
final WeakInvalidationListener weakTreeItemListener = new WeakInvalidationListener(treeItemInvalidationListener);
treeItemProperty().addListener(weakTreeItemListener);
if (getTreeItem() != null) {
getTreeItem().graphicProperty().addListener(weakTreeItemGraphicListener);
}
}
@Override
protected void layoutChildren() {
super.layoutChildren();
if (!getChildren().contains(selectedPane)) {
getChildren().add(0, cellRippler);
cellRippler.rippler.clear();
getChildren().add(0, selectedPane);
}
cellRippler.resizeRelocate(0, 0, getWidth(), getHeight());
cellRippler.releaseRipple();
selectedPane.resizeRelocate(0, 0, selectedPane.prefWidth(-1), getHeight());
selectedPane.setVisible(isSelected() ? true : false);
}
private void updateDisplay(T item, boolean empty) {
if (item == null || empty) {
hbox = null;
setText(null);
setGraphic(null);
} else {
TreeItem<T> treeItem = getTreeItem();
if (treeItem != null && treeItem.getGraphic() != null) {
if (item instanceof Node) {
setText(null);
if (hbox == null) {
hbox = new HBox(3);
}
hbox.getChildren().setAll(treeItem.getGraphic(), (Node) item);
setGraphic(hbox);
} else {
hbox = null;
setText(item.toString());
setGraphic(treeItem.getGraphic());
}
} else {
hbox = null;
if (item instanceof Node) {
setText(null);
setGraphic((Node) item);
} else {
setText(item.toString());
setGraphic(null);
}
}
}
}
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
updateDisplay(item, empty);
setMouseTransparent(item == null || empty);
}
}
| sshahine/JFoenix | jfoenix/src/main/java/com/jfoenix/controls/JFXTreeCell.java |
180,156 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.server;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.Immutable;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import io.trino.execution.QueryStats;
import io.trino.operator.BlockedReason;
import org.joda.time.DateTime;
import java.util.OptionalDouble;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Lightweight version of QueryStats. Parts of the web UI depend on the fields
* being named consistently across these classes.
*/
@Immutable
public class BasicQueryStats
{
private final DateTime createTime;
private final DateTime endTime;
private final Duration queuedTime;
private final Duration elapsedTime;
private final Duration executionTime;
private final int failedTasks;
private final int totalDrivers;
private final int queuedDrivers;
private final int runningDrivers;
private final int completedDrivers;
private final int blockedDrivers;
private final DataSize rawInputDataSize;
private final long rawInputPositions;
private final DataSize spilledDataSize;
private final DataSize physicalInputDataSize;
private final DataSize physicalWrittenDataSize;
private final double cumulativeUserMemory;
private final double failedCumulativeUserMemory;
private final DataSize userMemoryReservation;
private final DataSize totalMemoryReservation;
private final DataSize peakUserMemoryReservation;
private final DataSize peakTotalMemoryReservation;
private final Duration totalCpuTime;
private final Duration failedCpuTime;
private final Duration totalScheduledTime;
private final Duration failedScheduledTime;
private final boolean fullyBlocked;
private final Set<BlockedReason> blockedReasons;
private final OptionalDouble progressPercentage;
private final OptionalDouble runningPercentage;
@JsonCreator
public BasicQueryStats(
@JsonProperty("createTime") DateTime createTime,
@JsonProperty("endTime") DateTime endTime,
@JsonProperty("queuedTime") Duration queuedTime,
@JsonProperty("elapsedTime") Duration elapsedTime,
@JsonProperty("executionTime") Duration executionTime,
@JsonProperty("failedTasks") int failedTasks,
@JsonProperty("totalDrivers") int totalDrivers,
@JsonProperty("queuedDrivers") int queuedDrivers,
@JsonProperty("runningDrivers") int runningDrivers,
@JsonProperty("completedDrivers") int completedDrivers,
@JsonProperty("blockedDrivers") int blockedDrivers,
@JsonProperty("rawInputDataSize") DataSize rawInputDataSize,
@JsonProperty("rawInputPositions") long rawInputPositions,
@JsonProperty("spilledDataSize") DataSize spilledDataSize,
@JsonProperty("physicalInputDataSize") DataSize physicalInputDataSize,
@JsonProperty("physicalWrittenDataSize") DataSize physicalWrittenDataSize,
@JsonProperty("cumulativeUserMemory") double cumulativeUserMemory,
@JsonProperty("failedCumulativeUserMemory") double failedCumulativeUserMemory,
@JsonProperty("userMemoryReservation") DataSize userMemoryReservation,
@JsonProperty("totalMemoryReservation") DataSize totalMemoryReservation,
@JsonProperty("peakUserMemoryReservation") DataSize peakUserMemoryReservation,
@JsonProperty("peakTotalMemoryReservation") DataSize peakTotalMemoryReservation,
@JsonProperty("totalCpuTime") Duration totalCpuTime,
@JsonProperty("failedCpuTime") Duration failedCpuTime,
@JsonProperty("totalScheduledTime") Duration totalScheduledTime,
@JsonProperty("failedScheduledTime") Duration failedScheduledTime,
@JsonProperty("fullyBlocked") boolean fullyBlocked,
@JsonProperty("blockedReasons") Set<BlockedReason> blockedReasons,
@JsonProperty("progressPercentage") OptionalDouble progressPercentage,
@JsonProperty("runningPercentage") OptionalDouble runningPercentage)
{
this.createTime = createTime;
this.endTime = endTime;
this.queuedTime = requireNonNull(queuedTime, "queuedTime is null");
this.elapsedTime = requireNonNull(elapsedTime, "elapsedTime is null");
this.executionTime = requireNonNull(executionTime, "executionTime is null");
checkArgument(failedTasks >= 0, "failedTasks is negative");
this.failedTasks = failedTasks;
checkArgument(totalDrivers >= 0, "totalDrivers is negative");
this.totalDrivers = totalDrivers;
checkArgument(queuedDrivers >= 0, "queuedDrivers is negative");
this.queuedDrivers = queuedDrivers;
checkArgument(runningDrivers >= 0, "runningDrivers is negative");
this.runningDrivers = runningDrivers;
checkArgument(completedDrivers >= 0, "completedDrivers is negative");
this.completedDrivers = completedDrivers;
checkArgument(blockedDrivers >= 0, "blockedDrivers is negative");
this.blockedDrivers = blockedDrivers;
this.rawInputDataSize = requireNonNull(rawInputDataSize, "rawInputDataSize is null");
this.rawInputPositions = rawInputPositions;
this.spilledDataSize = spilledDataSize;
this.physicalInputDataSize = physicalInputDataSize;
this.physicalWrittenDataSize = physicalWrittenDataSize;
this.cumulativeUserMemory = cumulativeUserMemory;
this.failedCumulativeUserMemory = failedCumulativeUserMemory;
this.userMemoryReservation = userMemoryReservation;
this.totalMemoryReservation = totalMemoryReservation;
this.peakUserMemoryReservation = peakUserMemoryReservation;
this.peakTotalMemoryReservation = peakTotalMemoryReservation;
this.totalCpuTime = totalCpuTime;
this.failedCpuTime = failedCpuTime;
this.totalScheduledTime = totalScheduledTime;
this.failedScheduledTime = failedScheduledTime;
this.fullyBlocked = fullyBlocked;
this.blockedReasons = ImmutableSet.copyOf(requireNonNull(blockedReasons, "blockedReasons is null"));
this.progressPercentage = requireNonNull(progressPercentage, "progressPercentage is null");
this.runningPercentage = requireNonNull(runningPercentage, "runningPercentage is null");
}
public BasicQueryStats(QueryStats queryStats)
{
this(queryStats.getCreateTime(),
queryStats.getEndTime(),
queryStats.getQueuedTime(),
queryStats.getElapsedTime(),
queryStats.getExecutionTime(),
queryStats.getFailedTasks(),
queryStats.getTotalDrivers(),
queryStats.getQueuedDrivers(),
queryStats.getRunningDrivers(),
queryStats.getCompletedDrivers(),
queryStats.getBlockedDrivers(),
queryStats.getRawInputDataSize(),
queryStats.getRawInputPositions(),
queryStats.getSpilledDataSize(),
queryStats.getPhysicalInputDataSize(),
queryStats.getPhysicalWrittenDataSize(),
queryStats.getCumulativeUserMemory(),
queryStats.getFailedCumulativeUserMemory(),
queryStats.getUserMemoryReservation(),
queryStats.getTotalMemoryReservation(),
queryStats.getPeakUserMemoryReservation(),
queryStats.getPeakTotalMemoryReservation(),
queryStats.getTotalCpuTime(),
queryStats.getFailedCpuTime(),
queryStats.getTotalScheduledTime(),
queryStats.getFailedScheduledTime(),
queryStats.isFullyBlocked(),
queryStats.getBlockedReasons(),
queryStats.getProgressPercentage(),
queryStats.getRunningPercentage());
}
public static BasicQueryStats immediateFailureQueryStats()
{
DateTime now = DateTime.now();
return new BasicQueryStats(
now,
now,
new Duration(0, MILLISECONDS),
new Duration(0, MILLISECONDS),
new Duration(0, MILLISECONDS),
0,
0,
0,
0,
0,
0,
DataSize.ofBytes(0),
0,
DataSize.ofBytes(0),
DataSize.ofBytes(0),
DataSize.ofBytes(0),
0,
0,
DataSize.ofBytes(0),
DataSize.ofBytes(0),
DataSize.ofBytes(0),
DataSize.ofBytes(0),
new Duration(0, MILLISECONDS),
new Duration(0, MILLISECONDS),
new Duration(0, MILLISECONDS),
new Duration(0, MILLISECONDS),
false,
ImmutableSet.of(),
OptionalDouble.empty(),
OptionalDouble.empty());
}
@JsonProperty
public DateTime getCreateTime()
{
return createTime;
}
@JsonProperty
public DateTime getEndTime()
{
return endTime;
}
@JsonProperty
public Duration getQueuedTime()
{
return queuedTime;
}
@JsonProperty
public Duration getElapsedTime()
{
return elapsedTime;
}
@JsonProperty
public Duration getExecutionTime()
{
return executionTime;
}
@JsonProperty
public int getFailedTasks()
{
return failedTasks;
}
@JsonProperty
public int getTotalDrivers()
{
return totalDrivers;
}
@JsonProperty
public int getQueuedDrivers()
{
return queuedDrivers;
}
@JsonProperty
public int getRunningDrivers()
{
return runningDrivers;
}
@JsonProperty
public int getCompletedDrivers()
{
return completedDrivers;
}
@JsonProperty
public int getBlockedDrivers()
{
return blockedDrivers;
}
@JsonProperty
public DataSize getRawInputDataSize()
{
return rawInputDataSize;
}
@JsonProperty
public long getRawInputPositions()
{
return rawInputPositions;
}
@JsonProperty
public DataSize getSpilledDataSize()
{
return spilledDataSize;
}
@JsonProperty
public DataSize getPhysicalInputDataSize()
{
return physicalInputDataSize;
}
@JsonProperty
public DataSize getPhysicalWrittenDataSize()
{
return physicalWrittenDataSize;
}
@JsonProperty
public double getCumulativeUserMemory()
{
return cumulativeUserMemory;
}
@JsonProperty
public double getFailedCumulativeUserMemory()
{
return failedCumulativeUserMemory;
}
@JsonProperty
public DataSize getUserMemoryReservation()
{
return userMemoryReservation;
}
@JsonProperty
public DataSize getTotalMemoryReservation()
{
return totalMemoryReservation;
}
@JsonProperty
public DataSize getPeakUserMemoryReservation()
{
return peakUserMemoryReservation;
}
@JsonProperty
public DataSize getPeakTotalMemoryReservation()
{
return peakTotalMemoryReservation;
}
@JsonProperty
public Duration getTotalCpuTime()
{
return totalCpuTime;
}
@JsonProperty
public Duration getFailedCpuTime()
{
return failedCpuTime;
}
@JsonProperty
public Duration getTotalScheduledTime()
{
return totalScheduledTime;
}
@JsonProperty
public Duration getFailedScheduledTime()
{
return failedScheduledTime;
}
@JsonProperty
public boolean isFullyBlocked()
{
return fullyBlocked;
}
@JsonProperty
public Set<BlockedReason> getBlockedReasons()
{
return blockedReasons;
}
@JsonProperty
public OptionalDouble getProgressPercentage()
{
return progressPercentage;
}
@JsonProperty
public OptionalDouble getRunningPercentage()
{
return runningPercentage;
}
}
| trinodb/trino | core/trino-main/src/main/java/io/trino/server/BasicQueryStats.java |
180,157 | // Targeted by JavaCPP version 1.5.11-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.pytorch;
import org.bytedeco.pytorch.Allocator;
import org.bytedeco.pytorch.Function;
import org.bytedeco.pytorch.functions.*;
import org.bytedeco.pytorch.Module;
import org.bytedeco.javacpp.annotation.Cast;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.openblas.global.openblas_nolapack.*;
import static org.bytedeco.openblas.global.openblas.*;
import static org.bytedeco.pytorch.global.torch.*;
// [Constant Object Weak CompilationUnit Reference]
// A non owning pointer to a type. When a class get inserted as a constant
// into a graph, if we used a strong pointer we would have a circular reference
// from Object -> CompilationUnit and CompilationUnit -> Graph (which owns the
// Constant Object)
@Namespace("c10") @Properties(inherit = org.bytedeco.pytorch.presets.torch.class)
public class WeakTypePtr extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public WeakTypePtr(Pointer p) { super(p); }
public native @ByRef Type.TypePtr type_(); public native WeakTypePtr type_(Type.TypePtr setter);
}
| bytedeco/javacpp-presets | pytorch/src/gen/java/org/bytedeco/pytorch/WeakTypePtr.java |
180,158 | package com.zzg.mybatis.generator.view;
import com.zzg.mybatis.generator.model.DatabaseConfig;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakInvalidationListener;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.HBox;
import java.lang.ref.WeakReference;
/**
* Created by Owen on 6/14/16.
*/
public class LeftDbTreeCell extends TreeCell<DatabaseConfig> {
private HBox hbox;
private WeakReference<TreeItem<DatabaseConfig>> treeItemRef;
private InvalidationListener treeItemGraphicListener = observable -> {
updateDisplay(getItem(), isEmpty());
};
private InvalidationListener treeItemListener = new InvalidationListener() {
@Override
public void invalidated(Observable observable) {
TreeItem<DatabaseConfig> oldTreeItem = treeItemRef == null ? null : treeItemRef.get();
if (oldTreeItem != null) {
oldTreeItem.graphicProperty().removeListener(weakTreeItemGraphicListener);
}
TreeItem<DatabaseConfig> newTreeItem = getTreeItem();
if (newTreeItem != null) {
newTreeItem.graphicProperty().addListener(weakTreeItemGraphicListener);
treeItemRef = new WeakReference<TreeItem<DatabaseConfig>>(newTreeItem);
}
}
};
private WeakInvalidationListener weakTreeItemGraphicListener =
new WeakInvalidationListener(treeItemGraphicListener);
private WeakInvalidationListener weakTreeItemListener =
new WeakInvalidationListener(treeItemListener);
public LeftDbTreeCell() {
treeItemProperty().addListener(weakTreeItemListener);
if (getTreeItem() != null) {
getTreeItem().graphicProperty().addListener(weakTreeItemGraphicListener);
}
}
void updateDisplay(DatabaseConfig item, boolean empty) {
if (item == null || empty) {
hbox = null;
setText(null);
setGraphic(null);
} else {
// update the graphic if one is set in the TreeItem
TreeItem<DatabaseConfig> treeItem = getTreeItem();
if (treeItem != null && treeItem.getGraphic() != null) {
hbox = null;
setText(item.toString());
setGraphic(treeItem.getGraphic());
} else {
hbox = null;
setText(item.getName());
setGraphic(null);
}
}
}
@Override
public void updateItem(DatabaseConfig item, boolean empty) {
super.updateItem(item, empty);
updateDisplay(item, empty);
}
}
| zouzg/mybatis-generator-gui | src/main/java/com/zzg/mybatis/generator/view/LeftDbTreeCell.java |
180,160 | /*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.management;
import sun.misc.SharedSecrets;
import sun.misc.WispEngineAccess;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import javax.management.ObjectName;
import java.util.Objects;
/**
* Implementation class for the thread subsystem.
* Standard and committed hotspot-specific metrics if any.
*
* ManagementFactory.getThreadMXBean() returns an instance
* of this class.
*/
class ThreadImpl implements com.sun.management.ThreadMXBean {
private static WispEngineAccess WEA = SharedSecrets.getWispEngineAccess();
private final VMManagement jvm;
// default for thread contention monitoring is disabled.
private boolean contentionMonitoringEnabled = false;
private boolean cpuTimeEnabled;
private boolean allocatedMemoryEnabled;
/**
* Constructor of ThreadImpl class.
*/
ThreadImpl(VMManagement vm) {
this.jvm = vm;
this.cpuTimeEnabled = jvm.isThreadCpuTimeEnabled();
this.allocatedMemoryEnabled = jvm.isThreadAllocatedMemoryEnabled();
}
public int getThreadCount() {
return jvm.getLiveThreadCount();
}
public int getPeakThreadCount() {
return jvm.getPeakThreadCount();
}
public long getTotalStartedThreadCount() {
return jvm.getTotalThreadCount();
}
public int getDaemonThreadCount() {
return jvm.getDaemonThreadCount();
}
public boolean isThreadContentionMonitoringSupported() {
return jvm.isThreadContentionMonitoringSupported();
}
public synchronized boolean isThreadContentionMonitoringEnabled() {
if (!isThreadContentionMonitoringSupported()) {
throw new UnsupportedOperationException(
"Thread contention monitoring is not supported.");
}
return contentionMonitoringEnabled;
}
public boolean isThreadCpuTimeSupported() {
return jvm.isOtherThreadCpuTimeSupported();
}
public boolean isCurrentThreadCpuTimeSupported() {
return jvm.isCurrentThreadCpuTimeSupported();
}
public boolean isThreadAllocatedMemorySupported() {
return jvm.isThreadAllocatedMemorySupported();
}
public boolean isThreadCpuTimeEnabled() {
if (!isThreadCpuTimeSupported() &&
!isCurrentThreadCpuTimeSupported()) {
throw new UnsupportedOperationException(
"Thread CPU time measurement is not supported");
}
return cpuTimeEnabled;
}
private void ensureThreadAllocatedMemorySupported() {
if (!isThreadAllocatedMemorySupported()) {
throw new UnsupportedOperationException(
"Thread allocated memory measurement is not supported.");
}
}
public boolean isThreadAllocatedMemoryEnabled() {
ensureThreadAllocatedMemorySupported();
return allocatedMemoryEnabled;
}
public long[] getAllThreadIds() {
Util.checkMonitorAccess();
Thread[] threads = getThreads();
int length = threads.length;
long[] ids = new long[length];
for (int i = 0; i < length; i++) {
Thread t = threads[i];
ids[i] = t.getId();
}
return ids;
}
public ThreadInfo getThreadInfo(long id) {
long[] ids = new long[1];
ids[0] = id;
final ThreadInfo[] infos = getThreadInfo(ids, 0);
return infos[0];
}
public ThreadInfo getThreadInfo(long id, int maxDepth) {
long[] ids = new long[1];
ids[0] = id;
final ThreadInfo[] infos = getThreadInfo(ids, maxDepth);
return infos[0];
}
public ThreadInfo[] getThreadInfo(long[] ids) {
return getThreadInfo(ids, 0);
}
private void verifyThreadId(long id) {
if (id <= 0) {
throw new IllegalArgumentException(
"Invalid thread ID parameter: " + id);
}
}
private void verifyThreadIds(long[] ids) {
Objects.requireNonNull(ids);
for (int i = 0; i < ids.length; i++) {
verifyThreadId(ids[i]);
}
}
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth) {
verifyThreadIds(ids);
if (maxDepth < 0) {
throw new IllegalArgumentException(
"Invalid maxDepth parameter: " + maxDepth);
}
// ids has been verified to be non-null
// an empty array of ids should return an empty array of ThreadInfos
if (ids.length == 0) return new ThreadInfo[0];
Util.checkMonitorAccess();
ThreadInfo[] infos = new ThreadInfo[ids.length]; // nulls
if (maxDepth == Integer.MAX_VALUE) {
getThreadInfo1(ids, -1, infos);
} else {
getThreadInfo1(ids, maxDepth, infos);
}
return infos;
}
public void setThreadContentionMonitoringEnabled(boolean enable) {
if (!isThreadContentionMonitoringSupported()) {
throw new UnsupportedOperationException(
"Thread contention monitoring is not supported");
}
Util.checkControlAccess();
synchronized (this) {
if (contentionMonitoringEnabled != enable) {
if (enable) {
// if reeabled, reset contention time statistics
// for all threads
resetContentionTimes0(0);
}
// update the VM of the state change
setThreadContentionMonitoringEnabled0(enable);
contentionMonitoringEnabled = enable;
}
}
}
private boolean verifyCurrentThreadCpuTime() {
// check if Thread CPU time measurement is supported.
if (!isCurrentThreadCpuTimeSupported()) {
throw new UnsupportedOperationException(
"Current thread CPU time measurement is not supported.");
}
return isThreadCpuTimeEnabled();
}
public long getCurrentThreadCpuTime() {
if (verifyCurrentThreadCpuTime()) {
if (WEA != null && WEA.isAllThreadAsWisp()) {
long[] times = new long[1];
WEA.getCpuTime(new long[]{Thread.currentThread().getId()}, times);
return times[0];
}
return getThreadTotalCpuTime0(0);
}
return -1;
}
public long getThreadCpuTime(long id) {
long[] ids = new long[1];
ids[0] = id;
final long[] times = getThreadCpuTime(ids);
return times[0];
}
private boolean verifyThreadCpuTime(long[] ids) {
verifyThreadIds(ids);
// check if Thread CPU time measurement is supported.
if (!isThreadCpuTimeSupported() &&
!isCurrentThreadCpuTimeSupported()) {
throw new UnsupportedOperationException(
"Thread CPU time measurement is not supported.");
}
if (!isThreadCpuTimeSupported()) {
// support current thread only
for (int i = 0; i < ids.length; i++) {
if (ids[i] != Thread.currentThread().getId()) {
throw new UnsupportedOperationException(
"Thread CPU time measurement is only supported" +
" for the current thread.");
}
}
}
return isThreadCpuTimeEnabled();
}
public long[] getThreadCpuTime(long[] ids) {
boolean verified = verifyThreadCpuTime(ids);
int length = ids.length;
long[] times = new long[length];
java.util.Arrays.fill(times, -1);
if (verified) {
if (WEA != null && WEA.isAllThreadAsWisp()) {
WEA.getCpuTime(ids, times);
} else if (length == 1) {
long id = ids[0];
if (id == Thread.currentThread().getId()) {
id = 0;
}
times[0] = getThreadTotalCpuTime0(id);
} else {
getThreadTotalCpuTime1(ids, times);
}
}
return times;
}
public long getCurrentThreadUserTime() {
boolean wispEnabled = WEA != null && WEA.isAllThreadAsWisp();
if (!wispEnabled && verifyCurrentThreadCpuTime()) {
return getThreadUserCpuTime0(0);
}
return -1;
}
public long getThreadUserTime(long id) {
long[] ids = new long[1];
ids[0] = id;
final long[] times = getThreadUserTime(ids);
return times[0];
}
public long[] getThreadUserTime(long[] ids) {
boolean wispEnabled = WEA != null && WEA.isAllThreadAsWisp();
boolean verified = verifyThreadCpuTime(ids) && !wispEnabled;
int length = ids.length;
long[] times = new long[length];
java.util.Arrays.fill(times, -1);
if (verified) {
if (length == 1) {
long id = ids[0];
if (id == Thread.currentThread().getId()) {
id = 0;
}
times[0] = getThreadUserCpuTime0(id);
} else {
getThreadUserCpuTime1(ids, times);
}
}
return times;
}
public void setThreadCpuTimeEnabled(boolean enable) {
if (!isThreadCpuTimeSupported() &&
!isCurrentThreadCpuTimeSupported()) {
throw new UnsupportedOperationException(
"Thread CPU time measurement is not supported");
}
Util.checkControlAccess();
synchronized (this) {
if (cpuTimeEnabled != enable) {
// notify VM of the state change
setThreadCpuTimeEnabled0(enable);
cpuTimeEnabled = enable;
}
}
}
public long getCurrentThreadAllocatedBytes() {
if (isThreadAllocatedMemoryEnabled()) {
return getThreadAllocatedMemory0(0);
}
return -1;
}
private boolean verifyThreadAllocatedMemory(long id) {
verifyThreadId(id);
return isThreadAllocatedMemoryEnabled();
}
public long getThreadAllocatedBytes(long id) {
boolean verified = verifyThreadAllocatedMemory(id);
if (verified) {
return getThreadAllocatedMemory0(
Thread.currentThread().getId() == id ? 0 : id);
}
return -1;
}
private boolean verifyThreadAllocatedMemory(long[] ids) {
verifyThreadIds(ids);
return isThreadAllocatedMemoryEnabled();
}
public long[] getThreadAllocatedBytes(long[] ids) {
Objects.requireNonNull(ids);
if (ids.length == 1) {
long size = getThreadAllocatedBytes(ids[0]);
return new long[] { size };
}
boolean verified = verifyThreadAllocatedMemory(ids);
long[] sizes = new long[ids.length];
java.util.Arrays.fill(sizes, -1);
if (verified) {
getThreadAllocatedMemory1(ids, sizes);
}
return sizes;
}
public void setThreadAllocatedMemoryEnabled(boolean enable) {
ensureThreadAllocatedMemorySupported();
Util.checkControlAccess();
synchronized (this) {
if (allocatedMemoryEnabled != enable) {
// notify VM of the state change
setThreadAllocatedMemoryEnabled0(enable);
allocatedMemoryEnabled = enable;
}
}
}
public long[] findMonitorDeadlockedThreads() {
Util.checkMonitorAccess();
Thread[] threads = findMonitorDeadlockedThreads0();
if (threads == null) {
return null;
}
long[] ids = new long[threads.length];
for (int i = 0; i < threads.length; i++) {
Thread t = threads[i];
ids[i] = t.getId();
}
return ids;
}
public long[] findDeadlockedThreads() {
if (!isSynchronizerUsageSupported()) {
throw new UnsupportedOperationException(
"Monitoring of Synchronizer Usage is not supported.");
}
Util.checkMonitorAccess();
Thread[] threads = findDeadlockedThreads0();
if (threads == null) {
return null;
}
long[] ids = new long[threads.length];
for (int i = 0; i < threads.length; i++) {
Thread t = threads[i];
ids[i] = t.getId();
}
return ids;
}
public void resetPeakThreadCount() {
Util.checkControlAccess();
resetPeakThreadCount0();
}
public boolean isObjectMonitorUsageSupported() {
return jvm.isObjectMonitorUsageSupported();
}
public boolean isSynchronizerUsageSupported() {
return jvm.isSynchronizerUsageSupported();
}
private void verifyDumpThreads(boolean lockedMonitors,
boolean lockedSynchronizers) {
if (lockedMonitors && !isObjectMonitorUsageSupported()) {
throw new UnsupportedOperationException(
"Monitoring of Object Monitor Usage is not supported.");
}
if (lockedSynchronizers && !isSynchronizerUsageSupported()) {
throw new UnsupportedOperationException(
"Monitoring of Synchronizer Usage is not supported.");
}
Util.checkMonitorAccess();
}
public ThreadInfo[] getThreadInfo(long[] ids,
boolean lockedMonitors,
boolean lockedSynchronizers) {
return dumpThreads0(ids, lockedMonitors, lockedSynchronizers,
Integer.MAX_VALUE);
}
public ThreadInfo[] getThreadInfo(long[] ids,
boolean lockedMonitors,
boolean lockedSynchronizers,
int maxDepth) {
if (maxDepth < 0) {
throw new IllegalArgumentException(
"Invalid maxDepth parameter: " + maxDepth);
}
verifyThreadIds(ids);
// ids has been verified to be non-null
// an empty array of ids should return an empty array of ThreadInfos
if (ids.length == 0) return new ThreadInfo[0];
verifyDumpThreads(lockedMonitors, lockedSynchronizers);
return dumpThreads0(ids, lockedMonitors, lockedSynchronizers, maxDepth);
}
public ThreadInfo[] dumpAllThreads(boolean lockedMonitors,
boolean lockedSynchronizers) {
return dumpAllThreads(lockedMonitors, lockedSynchronizers,
Integer.MAX_VALUE);
}
public ThreadInfo[] dumpAllThreads(boolean lockedMonitors,
boolean lockedSynchronizers,
int maxDepth) {
if (maxDepth < 0) {
throw new IllegalArgumentException(
"Invalid maxDepth parameter: " + maxDepth);
}
verifyDumpThreads(lockedMonitors, lockedSynchronizers);
return dumpThreads0(null, lockedMonitors, lockedSynchronizers, maxDepth);
}
// VM support where maxDepth == -1 to request entire stack dump
private static native Thread[] getThreads();
private static native void getThreadInfo1(long[] ids,
int maxDepth,
ThreadInfo[] result);
private static native long getThreadTotalCpuTime0(long id);
private static native void getThreadTotalCpuTime1(long[] ids, long[] result);
private static native long getThreadUserCpuTime0(long id);
private static native void getThreadUserCpuTime1(long[] ids, long[] result);
private static native long getThreadAllocatedMemory0(long id);
private static native void getThreadAllocatedMemory1(long[] ids, long[] result);
private static native void setThreadCpuTimeEnabled0(boolean enable);
private static native void setThreadAllocatedMemoryEnabled0(boolean enable);
private static native void setThreadContentionMonitoringEnabled0(boolean enable);
private static native Thread[] findMonitorDeadlockedThreads0();
private static native Thread[] findDeadlockedThreads0();
private static native void resetPeakThreadCount0();
private static native ThreadInfo[] dumpThreads0(long[] ids,
boolean lockedMonitors,
boolean lockedSynchronizers,
int maxDepth);
// tid == 0 to reset contention times for all threads
private static native void resetContentionTimes0(long tid);
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/management/ThreadImpl.java |
180,161 | package edu.stanford.nlp.pipeline;
import java.util.List;
import java.util.Properties;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.SentenceUtils;
import edu.stanford.nlp.util.CoreMap;
import edu.stanford.nlp.util.PropertiesUtils;
/** This class has tests for segmenter languages (Chinese, Arabic) that require
* resources to run. Most of the tests are in the unit test class.
*
* @author Christopher Manning
*/
public class WordsToSentencesAnnotatorITest {
private static final String headline = "“习主席欧洲行”漫评④:为世界经济联动增长贡献“中国方略”\n\n7日,国家主席习近平在“世界桥城”" +
"汉堡出席二十国集团(G20)领导人第十二次峰会并发表题为《坚\n持开放包容 推动联动增长》的重要讲话,提出四点“中国主张”," +
"为G20未来发展规划蓝图,为世界经济联动增长指明方向,受到与会各方和国际社会高度评价。[详细]";
@Test
public void testTwoNewlineIsSentenceBreakTokenizeNLs() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ”",
"7日 , 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 发表 题 为 " +
"《 坚持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , " +
"为 G20 未来 发展 规划 蓝图 , 为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。",
"[ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"tokenize.options", "tokenizeNLs,invertible,ptb3Escaping=true",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.newlineIsSentenceBreak", "two",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
@Test
public void testTwoNewlineIsSentenceBreak() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ”",
"7日 , 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 发表 题 为 " +
"《 坚持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , " +
"为 G20 未来 发展 规划 蓝图 , 为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。",
"[ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"tokenize.options", "invertible,ptb3Escaping=true",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.newlineIsSentenceBreak", "two",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
@Test
public void testNewlineIsSentenceBreakTokenizeNLs() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ”",
"7日 , 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 发表 题 为 " +
"《 坚",
"持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , " +
"为 G20 未来 发展 规划 蓝图 , 为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。",
"[ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"tokenize.options", "tokenizeNLs,invertible,ptb3Escaping=true",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.newlineIsSentenceBreak", "always",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
@Test
public void testNewlineIsSentenceBreakNever() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ” " +
"7日 , 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 " +
"发表 题 为 《 坚持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , " +
"为 G20 未来 发展 规划 蓝图 , 为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。",
"[ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.newlineIsSentenceBreak", "never",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
@Test
public void testEolOnly() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ”",
// "",
"7日 , 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 发表 题 为 " +
"《 坚",
"持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , 为 G20 未来 发展 规划 蓝图 , " +
"为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。 [ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"tokenize.options", "invertible",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.eolonly", "true",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
// Note: although there is an option for allowing empty sentences, at present it is always turned off in Annotator.
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
@Test
public void testIsOneSentence() {
String[] sents = {
"“ 习 主席 欧洲行 ” 漫评 ④ : 为 世界 经济 联动 增长 贡献 “ 中国 方略 ” 7日 ," +
" 国家 主席 习近平 在 “ 世界 桥 城 ” 汉堡 出席 二十 国 集团 ( G20 ) 领导人 第十二 次 峰会 并 发表 题 为 " +
"《 坚持 开放 包容 推动 联动 增长 》 的 重要 讲话 , 提出 四点 “ 中国 主张 ” , 为 G20 " +
"未来 发展 规划 蓝图 , 为 世界 经济 联动 增长 指明 方向 , 受到 与会 各 方 和 国际 社会 高度 评价 。 " +
"[ 详细 ]"
};
Properties props = PropertiesUtils.asProperties(
"annotators", "tokenize, ssplit",
"tokenize.language", "zh",
"ssplit.boundaryTokenRegex", "[.。]|[!?!?]+",
"ssplit.isOneSentence", "true",
"segment.model", "edu/stanford/nlp/models/segmenter/chinese/ctb.gz",
"segment.sighanCorporaDict", "edu/stanford/nlp/models/segmenter/chinese",
"segment.serDictionary", "edu/stanford/nlp/models/segmenter/chinese/dict-chris6.ser.gz",
"segment.sighanPostProcessing", "true"
);
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
Annotation document1 = new Annotation(headline);
pipeline.annotate(document1);
List<CoreMap> sentences = document1.get(CoreAnnotations.SentencesAnnotation.class);
assertEquals(sents.length, sentences.size());
for (int i = 0; i < Math.min(sents.length, sentences.size()); i++) {
CoreMap sentence = sentences.get(i);
String sentenceText = SentenceUtils.listToString(sentence.get(CoreAnnotations.TokensAnnotation.class));
assertEquals("Bad sentence #" + i, sents[i], sentenceText);
}
}
}
| stanfordnlp/CoreNLP | itest/src/edu/stanford/nlp/pipeline/WordsToSentencesAnnotatorITest.java |
180,162 | package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.L;
import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.N_MR1;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.O_MR1;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static org.robolectric.annotation.TextLayoutMode.Mode.REALISTIC;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.PathEffect;
import android.graphics.Shader;
import android.graphics.Typeface;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.InDevelopment;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.TextLayoutMode;
import org.robolectric.config.ConfigurationRegistry;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.versioning.AndroidVersions.U;
import org.robolectric.versioning.AndroidVersions.V;
@SuppressWarnings({"UnusedDeclaration"})
@Implements(value = Paint.class, looseSignatures = true)
public class ShadowPaint {
private int color;
private Paint.Style style;
private Paint.Cap cap;
private Paint.Join join;
private float width;
private float shadowRadius;
private float shadowDx;
private float shadowDy;
private int shadowColor;
private Shader shader;
private int alpha;
private ColorFilter filter;
private boolean antiAlias;
private boolean dither;
private int flags;
private PathEffect pathEffect;
private float letterSpacing;
private float textScaleX = 1f;
private float textSkewX;
private float wordSpacing;
@RealObject Paint paint;
private Typeface typeface;
private float textSize;
private Paint.Align textAlign = Paint.Align.LEFT;
@Implementation
protected void __constructor__(Paint otherPaint) {
ShadowPaint otherShadowPaint = Shadow.extract(otherPaint);
this.color = otherShadowPaint.color;
this.style = otherShadowPaint.style;
this.cap = otherShadowPaint.cap;
this.join = otherShadowPaint.join;
this.width = otherShadowPaint.width;
this.shadowRadius = otherShadowPaint.shadowRadius;
this.shadowDx = otherShadowPaint.shadowDx;
this.shadowDy = otherShadowPaint.shadowDy;
this.shadowColor = otherShadowPaint.shadowColor;
this.shader = otherShadowPaint.shader;
this.alpha = otherShadowPaint.alpha;
this.filter = otherShadowPaint.filter;
this.antiAlias = otherShadowPaint.antiAlias;
this.dither = otherShadowPaint.dither;
this.flags = otherShadowPaint.flags;
this.pathEffect = otherShadowPaint.pathEffect;
this.letterSpacing = otherShadowPaint.letterSpacing;
this.textScaleX = otherShadowPaint.textScaleX;
this.textSkewX = otherShadowPaint.textSkewX;
this.wordSpacing = otherShadowPaint.wordSpacing;
Shadow.invokeConstructor(Paint.class, paint, ClassParameter.from(Paint.class, otherPaint));
}
@Implementation(minSdk = N)
protected static long nInit() {
return 1;
}
@Implementation
protected int getFlags() {
return flags;
}
@Implementation
protected void setFlags(int flags) {
this.flags = flags;
}
@Implementation
protected void setUnderlineText(boolean underlineText) {
if (underlineText) {
setFlags(flags | Paint.UNDERLINE_TEXT_FLAG);
} else {
setFlags(flags & ~Paint.UNDERLINE_TEXT_FLAG);
}
}
@Implementation
protected void setStrikeThruText(boolean strikeThruText) {
if (strikeThruText) {
setFlags(flags | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
setFlags(flags & ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
@Implementation
protected Shader setShader(Shader shader) {
this.shader = shader;
return shader;
}
@Implementation
protected int getAlpha() {
return alpha;
}
@Implementation
protected void setAlpha(int alpha) {
this.alpha = alpha;
}
@Implementation
protected Shader getShader() {
return shader;
}
@Implementation
protected void setColor(int color) {
this.color = color;
}
@Implementation
protected int getColor() {
return color;
}
@Implementation
protected void setStyle(Paint.Style style) {
this.style = style;
}
@Implementation
protected Paint.Style getStyle() {
return style;
}
@Implementation
protected void setStrokeCap(Paint.Cap cap) {
this.cap = cap;
}
@Implementation
protected Paint.Cap getStrokeCap() {
return cap;
}
@Implementation
protected void setStrokeJoin(Paint.Join join) {
this.join = join;
}
@Implementation
protected Paint.Join getStrokeJoin() {
return join;
}
@Implementation
protected void setStrokeWidth(float width) {
this.width = width;
}
@Implementation
protected float getStrokeWidth() {
return width;
}
@Implementation
protected void setShadowLayer(float radius, float dx, float dy, int color) {
shadowRadius = radius;
shadowDx = dx;
shadowDy = dy;
shadowColor = color;
}
@Implementation
protected Typeface getTypeface() {
return typeface;
}
@Implementation
protected Typeface setTypeface(Typeface typeface) {
this.typeface = typeface;
return typeface;
}
@Implementation
protected float getTextSize() {
return textSize;
}
@Implementation
protected void setTextSize(float textSize) {
this.textSize = textSize;
}
@Implementation
protected float getTextScaleX() {
return textScaleX;
}
@Implementation
protected void setTextScaleX(float scaleX) {
this.textScaleX = scaleX;
}
@Implementation
protected float getTextSkewX() {
return textSkewX;
}
@Implementation
protected void setTextSkewX(float skewX) {
this.textSkewX = skewX;
}
@Implementation(minSdk = L)
protected float getLetterSpacing() {
return letterSpacing;
}
@Implementation(minSdk = L)
protected void setLetterSpacing(float letterSpacing) {
this.letterSpacing = letterSpacing;
}
@Implementation(minSdk = Q)
protected float getWordSpacing() {
return wordSpacing;
}
@Implementation(minSdk = Q)
protected void setWordSpacing(float wordSpacing) {
this.wordSpacing = wordSpacing;
}
@Implementation
protected void setTextAlign(Paint.Align align) {
textAlign = align;
}
@Implementation
protected Paint.Align getTextAlign() {
return textAlign;
}
/**
* @return shadow radius (Paint related shadow, not Robolectric Shadow)
*/
public float getShadowRadius() {
return shadowRadius;
}
/**
* @return shadow Dx (Paint related shadow, not Robolectric Shadow)
*/
public float getShadowDx() {
return shadowDx;
}
/**
* @return shadow Dx (Paint related shadow, not Robolectric Shadow)
*/
public float getShadowDy() {
return shadowDy;
}
/**
* @return shadow color (Paint related shadow, not Robolectric Shadow)
*/
public int getShadowColor() {
return shadowColor;
}
public Paint.Cap getCap() {
return cap;
}
public Paint.Join getJoin() {
return join;
}
public float getWidth() {
return width;
}
@Implementation
protected ColorFilter getColorFilter() {
return filter;
}
@Implementation
protected ColorFilter setColorFilter(ColorFilter filter) {
this.filter = filter;
return filter;
}
@Implementation
protected void setAntiAlias(boolean antiAlias) {
this.flags = (flags & ~Paint.ANTI_ALIAS_FLAG) | (antiAlias ? Paint.ANTI_ALIAS_FLAG : 0);
}
@Implementation
protected void setDither(boolean dither) {
this.dither = dither;
}
@Implementation
protected boolean isDither() {
return dither;
}
@Implementation
protected boolean isAntiAlias() {
return (flags & Paint.ANTI_ALIAS_FLAG) == Paint.ANTI_ALIAS_FLAG;
}
@Implementation
protected boolean isFilterBitmap() {
return (flags & Paint.FILTER_BITMAP_FLAG) == Paint.FILTER_BITMAP_FLAG;
}
@Implementation
protected void setFilterBitmap(boolean filterBitmap) {
this.flags =
(flags & ~Paint.FILTER_BITMAP_FLAG) | (filterBitmap ? Paint.FILTER_BITMAP_FLAG : 0);
}
@Implementation
protected PathEffect getPathEffect() {
return pathEffect;
}
@Implementation
protected PathEffect setPathEffect(PathEffect effect) {
this.pathEffect = effect;
return effect;
}
@Implementation
protected float measureText(String text) {
return applyTextScaleX(text.length());
}
@Implementation
protected float measureText(CharSequence text, int start, int end) {
return applyTextScaleX(end - start);
}
@Implementation
protected float measureText(String text, int start, int end) {
return applyTextScaleX(end - start);
}
@Implementation
protected float measureText(char[] text, int index, int count) {
return applyTextScaleX(count);
}
private float applyTextScaleX(float textWidth) {
return Math.max(0f, textScaleX) * textWidth;
}
@Implementation(maxSdk = M)
protected static int native_breakText(
long native_object,
long native_typeface,
char[] text,
int index,
int count,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
@Implementation(minSdk = N, maxSdk = O_MR1)
protected static int nBreakText(
long nObject,
long nTypeface,
char[] text,
int index,
int count,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
@Implementation(minSdk = P)
protected static int nBreakText(
long nObject,
char[] text,
int index,
int count,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
private static int breakText(char[] text, float maxWidth, float[] measuredWidth) {
if (measuredWidth != null) {
measuredWidth[0] = maxWidth;
}
return text.length;
}
@Implementation(maxSdk = M)
protected static int native_breakText(
long native_object,
long native_typeface,
String text,
boolean measureForwards,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
@Implementation(minSdk = N, maxSdk = O_MR1)
protected static int nBreakText(
long nObject,
long nTypeface,
String text,
boolean measureForwards,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
@Implementation(minSdk = P)
protected static int nBreakText(
long nObject,
String text,
boolean measureForwards,
float maxWidth,
int bidiFlags,
float[] measuredWidth) {
return breakText(text, maxWidth, measuredWidth);
}
private static int breakText(String text, float maxWidth, float[] measuredWidth) {
if (measuredWidth != null) {
measuredWidth[0] = maxWidth;
}
return text.length();
}
@Implementation(minSdk = V.SDK_INT)
protected static int nGetFontMetricsInt(
long paintPtr, FontMetricsInt fmi, /* Ignored */ boolean useLocale) {
return nGetFontMetricsInt(paintPtr, fmi);
}
@Implementation(minSdk = P, maxSdk = U.SDK_INT)
protected static int nGetFontMetricsInt(long paintPtr, FontMetricsInt fmi) {
if (ConfigurationRegistry.get(TextLayoutMode.Mode.class) == REALISTIC) {
// TODO: hack, just set values to those we see on emulator
int descent = 7;
int ascent = -28;
int leading = 0;
if (fmi != null) {
fmi.top = -32;
fmi.ascent = ascent;
fmi.descent = descent;
fmi.bottom = 9;
fmi.leading = leading;
}
return descent - ascent + leading;
}
return 0;
}
@Implementation(minSdk = O, maxSdk = O_MR1)
protected static int nGetFontMetricsInt(
long nativePaint, long nativeTypeface, FontMetricsInt fmi) {
return nGetFontMetricsInt(nativePaint, fmi);
}
@Implementation(minSdk = N, maxSdk = N_MR1)
protected int nGetFontMetricsInt(Object nativePaint, Object nativeTypeface, Object fmi) {
return nGetFontMetricsInt((long) nativePaint, (FontMetricsInt) fmi);
}
@Implementation(maxSdk = M)
protected int getFontMetricsInt(FontMetricsInt fmi) {
return nGetFontMetricsInt(0, fmi);
}
@Implementation(minSdk = P)
protected static float nGetRunAdvance(
long paintPtr,
char[] text,
int start,
int end,
int contextStart,
int contextEnd,
boolean isRtl,
int offset) {
if (ConfigurationRegistry.get(TextLayoutMode.Mode.class) == REALISTIC) {
// be consistent with measureText for measurements, and measure 1 pixel per char
return end - start;
}
return 0f;
}
@Implementation(minSdk = U.SDK_INT, maxSdk = U.SDK_INT)
protected static float nGetRunCharacterAdvance(
long paintPtr,
char[] text,
int start,
int end,
int contextStart,
int contextEnd,
boolean isRtl,
int offset,
float[] advances,
int advancesIndex) {
return nGetRunAdvance(paintPtr, text, start, end, contextStart, contextEnd, isRtl, offset);
}
@Implementation(minSdk = V.SDK_INT)
@InDevelopment
protected static float nGetRunCharacterAdvance(
Object /* long */ paintPtr,
Object /* char[] */ text,
Object /* int */ start,
Object /* int */ end,
Object /* int */ contextStart,
Object /* int */ contextEnd,
Object /* boolean */ isRtl,
Object /* int */ offset,
Object /* float[] */ advances,
Object /* int */ advancesIndex,
Object /* RectF */ drawingBounds,
Object /* RunInfo */ runInfo) {
return nGetRunCharacterAdvance(
(long) paintPtr,
(char[]) text,
(int) start,
(int) end,
(int) contextStart,
(int) contextEnd,
(boolean) isRtl,
(int) offset,
(float[]) advances,
(int) advancesIndex);
}
@Implementation(minSdk = N, maxSdk = O_MR1)
protected static float nGetRunAdvance(
long paintPtr,
long typefacePtr,
char[] text,
int start,
int end,
int contextStart,
int contextEnd,
boolean isRtl,
int offset) {
return nGetRunAdvance(paintPtr, text, start, end, contextStart, contextEnd, isRtl, offset);
}
@Implementation(minSdk = M, maxSdk = M)
protected static float native_getRunAdvance(
long nativeObject,
long nativeTypeface,
char[] text,
int start,
int end,
int contextStart,
int contextEnd,
boolean isRtl,
int offset) {
return nGetRunAdvance(0, text, start, end, contextStart, contextEnd, isRtl, offset);
}
@Implementation(maxSdk = LOLLIPOP_MR1)
protected static float native_getTextRunAdvances(
long nativeObject,
long nativeTypeface,
char[] text,
int index,
int count,
int contextIndex,
int contextCount,
boolean isRtl,
float[] advances,
int advancesIndex) {
return nGetRunAdvance(
0, text, index, index + count, contextIndex, contextIndex + contextCount, isRtl, index);
}
@Implementation(maxSdk = LOLLIPOP_MR1)
protected static float native_getTextRunAdvances(
long nativeObject,
long nativeTypeface,
String text,
int start,
int end,
int contextStart,
int contextEnd,
boolean isRtl,
float[] advances,
int advancesIndex) {
return nGetRunAdvance(0, text.toCharArray(), start, end, contextStart, contextEnd, isRtl, 0);
}
}
| robolectric/robolectric | shadows/framework/src/main/java/org/robolectric/shadows/ShadowPaint.java |
180,164 | /*
* Copyright 2011-2024 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* 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.jmx.spi;
import org.apache.commons.logging.LogFactory;
/**
* SPI used to retrieve JMX information and can survive the absence of JMX.
*/
public interface JmxInfoProvider {
public long[] getFileDecriptorInfo();
public int getThreadCount();
public int getDaemonThreadCount();
public int getPeakThreadCount();
public long getTotalStartedThreadCount();
public long[] findDeadlockedThreads();
public boolean isEnabled();
public static class Factory {
private static final JmxInfoProvider provider;
static {
JmxInfoProvider p;
try {
Class<?> c = Class.forName("com.amazonaws.jmx.JmxInfoProviderSupport");
p = (JmxInfoProvider)c.newInstance();
} catch (Exception e) {
LogFactory
.getLog(JmxInfoProvider.class)
.debug("Failed to load the JMX implementation module - JMX is disabled", e);
p = NONE;
}
provider = p;
}
public static JmxInfoProvider getJmxInfoProvider() {
return provider;
}
}
static final JmxInfoProvider NONE = new JmxInfoProvider() {
@Override
public long[] getFileDecriptorInfo() {
return null;
}
@Override
public int getThreadCount() {
return 0;
}
@Override
public int getDaemonThreadCount() {
return 0;
}
@Override
public int getPeakThreadCount() {
return 0;
}
@Override
public long getTotalStartedThreadCount() {
return 0;
}
@Override
public long[] findDeadlockedThreads() {
return null;
}
@Override
public boolean isEnabled() {
return false;
}
};
}
| aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/jmx/spi/JmxInfoProvider.java |
180,165 | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [https://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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 <https://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.transaction.stats;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import org.neo4j.io.layout.DatabaseFile;
import org.neo4j.kernel.impl.monitoring.TransactionMonitor;
import org.neo4j.kernel.impl.monitoring.TransactionSizeMonitor;
public class DatabaseTransactionStats implements TransactionMonitor, TransactionCounters {
@FunctionalInterface
public interface Factory {
DatabaseTransactionStats create();
}
private final AtomicLong activeReadTransactionCount = new AtomicLong();
private final LongAdder startedTransactionCount = new LongAdder();
private final LongAdder activeWriteTransactionCount = new LongAdder();
private final LongAdder committedReadTransactionCount = new LongAdder();
private final LongAdder committedWriteTransactionCount = new LongAdder();
private final LongAdder rolledBackReadTransactionCount = new LongAdder();
private final LongAdder rolledBackWriteTransactionCount = new LongAdder();
private final LongAdder terminatedReadTransactionCount = new LongAdder();
private final LongAdder terminatedWriteTransactionCount = new LongAdder();
private final LongAdder totalTransactionsValidationFailures = new LongAdder();
private final AtomicLong peakTransactionCount = new AtomicLong();
private volatile TransactionSizeMonitor transactionSizeCallback = NullTransactionSizeCallback.INSTANCE;
@Override
public void transactionStarted() {
startedTransactionCount.increment();
long active = activeReadTransactionCount.incrementAndGet();
peakTransactionCount.updateAndGet(peak -> Math.max(peak, active));
}
@Override
public void transactionFinished(boolean committed, boolean write) {
if (write) {
activeWriteTransactionCount.decrement();
} else {
activeReadTransactionCount.decrementAndGet();
}
if (committed) {
incrementCounter(committedReadTransactionCount, committedWriteTransactionCount, write);
} else {
incrementCounter(rolledBackReadTransactionCount, rolledBackWriteTransactionCount, write);
}
}
@Override
public void transactionTerminated(boolean write) {
incrementCounter(terminatedReadTransactionCount, terminatedWriteTransactionCount, write);
}
@Override
public void upgradeToWriteTransaction() {
activeReadTransactionCount.decrementAndGet();
activeWriteTransactionCount.increment();
}
@Override
public void transactionValidationFailure(DatabaseFile databaseFile) {
totalTransactionsValidationFailures.increment();
}
@Override
public long getPeakConcurrentNumberOfTransactions() {
return peakTransactionCount.longValue();
}
@Override
public long getNumberOfStartedTransactions() {
return startedTransactionCount.longValue();
}
@Override
public long getNumberOfCommittedTransactions() {
return getNumberOfCommittedReadTransactions() + getNumberOfCommittedWriteTransactions();
}
@Override
public long getNumberOfCommittedReadTransactions() {
return committedReadTransactionCount.longValue();
}
@Override
public long getNumberOfCommittedWriteTransactions() {
return committedWriteTransactionCount.longValue();
}
@Override
public long getNumberOfActiveTransactions() {
return getNumberOfActiveReadTransactions() + getNumberOfActiveWriteTransactions();
}
@Override
public long getNumberOfActiveReadTransactions() {
return activeReadTransactionCount.longValue();
}
@Override
public long getNumberOfActiveWriteTransactions() {
return activeWriteTransactionCount.longValue();
}
@Override
public long getNumberOfTerminatedTransactions() {
return getNumberOfTerminatedReadTransactions() + getNumberOfTerminatedWriteTransactions();
}
@Override
public long getNumberOfTerminatedReadTransactions() {
return terminatedReadTransactionCount.longValue();
}
@Override
public long getNumberOfTerminatedWriteTransactions() {
return terminatedWriteTransactionCount.longValue();
}
@Override
public long getNumberOfRolledBackTransactions() {
return getNumberOfRolledBackReadTransactions() + getNumberOfRolledBackWriteTransactions();
}
@Override
public long getNumberOfRolledBackReadTransactions() {
return rolledBackReadTransactionCount.longValue();
}
@Override
public long getNumberOfRolledBackWriteTransactions() {
return rolledBackWriteTransactionCount.longValue();
}
@Override
public long totalTransactionsValidationFailures() {
return totalTransactionsValidationFailures.longValue();
}
@Override
public void setTransactionSizeCallback(TransactionSizeMonitor transactionSizeMonitor) {
this.transactionSizeCallback =
transactionSizeMonitor != null ? transactionSizeMonitor : NullTransactionSizeCallback.INSTANCE;
}
@Override
public void addHeapTransactionSize(long transactionSizeHeap) {
transactionSizeCallback.addHeapTransactionSize(transactionSizeHeap);
}
@Override
public void addNativeTransactionSize(long transactionSizeNative) {
transactionSizeCallback.addNativeTransactionSize(transactionSizeNative);
}
private static void incrementCounter(LongAdder readCount, LongAdder writeCount, boolean write) {
if (write) {
writeCount.increment();
} else {
readCount.increment();
}
}
private static class NullTransactionSizeCallback implements TransactionSizeMonitor {
private static final TransactionSizeMonitor INSTANCE = new NullTransactionSizeCallback();
private NullTransactionSizeCallback() {}
@Override
public void addHeapTransactionSize(long transactionSizeHeap) {}
@Override
public void addNativeTransactionSize(long transactionSizeNative) {}
}
}
| neo4j/neo4j | community/kernel/src/main/java/org/neo4j/kernel/impl/transaction/stats/DatabaseTransactionStats.java |
180,169 | /*
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.fr;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_fr extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"Heure de l'Acre", "ACT",
"Heure d'\u00e9t\u00e9 de l'Acre", "ACST",
"Heure de l'Acre", "ACT"};
String ADELAIDE[] = new String[] {"Heure standard d'Australie centrale (Australie du sud)", "ACST",
"Heure d'\u00E9t\u00E9 d'Australie centrale (Australie du sud)", "ACDT",
"Centre (Australie-M\u00E9ridionale)", "ACT"};
String AGT[] = new String[] {"Heure D'Argentine", "ART",
"Heure d'\u00e9t\u00e9 D'Argentine", "ARST",
"Heure d'Argentine", "ART"} ;
String AKST[] = new String[] {"Heure normale d'Alaska", "AKST",
"Heure avanc\u00e9e d'Alaska", "AKDT",
"Alaska", "AKT"} ;
String AMT[] = new String[] {"Heure normale d'Amazonie", "AMT",
"Heure d'\u00e9t\u00e9 d'Amazonie", "AMST",
"Heure d'Amazonie", "AMT"} ;
String ARAST[] = new String[] {"Heure normale d'Arabie", "AST",
"Heure avanc\u00e9e d'Arabie", "ADT",
"Arabie", "AT"} ;
String ARMT[] = new String[] {"Heure d'Arm\u00e9nie", "AMT",
"Heure d'\u00e9t\u00e9 d'Arm\u00e9nie", "AMST",
"Heure d'Arm\u00E9nie", "AMT"} ;
String AST[] = new String[] {"Heure normale de l'Atlantique", "AST",
"Heure avanc\u00e9e de l'Atlantique", "ADT",
"Atlantique", "AT"} ;
String BDT[] = new String[] {"Heure du Bangladesh", "BDT",
"Heure d'\u00e9t\u00e9 du Bangladesh", "BDST",
"Heure du Bangladesh", "BDT"} ;
String BRISBANE[] = new String[] {"Heure standard d'Australie orientale (Queensland)", "AEST",
"Heure d'\u00E9t\u00E9 d'Australie orientale (Queensland)", "AEDT",
"C\u00F4te Est (Queensland)", "AET"};
String BROKEN_HILL[] = new String[] {"Heure standard d'Australie centrale (Australie du sud/Nouvelle-Galles du sud)", "ACST",
"Heure d'\u00E9t\u00E9 d'Australie centrale (Australie du sud/Nouvelle-Galles du sud)", "ACDT",
"Centre (Australie-M\u00E9ridionale/Nouvelle-Galles du Sud)", "ACT"};
String BRT[] = new String[] {"Heure du Br\u00e9sil", "BRT",
"Heure d'\u00e9t\u00e9 du Br\u00e9sil", "BRST",
"Heure du Br\u00E9sil", "BRT"} ;
String BTT[] = new String[] {"Heure du Bhoutan", "BTT",
"Heure d'\u00e9t\u00e9 du Bhoutan", "BTST",
"Heure du Bhoutan", "BTT"} ;
String CAT[] = new String[] {"Heure d'Afrique centrale", "CAT",
"Heure d'\u00e9t\u00e9 d'Afrique centrale", "CAST",
"Heure d'Afrique centrale", "CAT"} ;
String CET[] = new String[] {"Heure d'Europe centrale", "CET",
"Heure d'\u00e9t\u00e9 d'Europe centrale", "CEST",
"Heure d'Europe centrale", "CET"} ;
String CHAST[] = new String[] {"Heure standard de Chatham", "CHAST",
"Heure avanc\u00e9e de Chatham", "CHADT",
"Chatham", "CHAT"};
String CHUT[] = new String[] {"Heure de Chuuk", "CHUT",
"Heure d'\u00E9t\u00E9 de Chuuk", "CHUST",
"Heure de Chuuk", "CHUT"};
String CIT[] = new String[] {"Heure d'Indon\u00e9sie centrale", "WITA",
"Heure d'\u00e9t\u00e9 d'Indon\u00e9sie centrale", "CIST",
"Heure d'Indon\u00E9sie centrale", "WITA"};
String CLT[] = new String[] {"Heure du Chili", "CLT",
"Heure d'\u00e9t\u00e9 du Chili", "CLST",
"Heure du Chili", "CLT"} ;
String CST[] = new String[] {"Heure normale du Centre", "CST",
"Heure avanc\u00e9e du Centre", "CDT",
"Centre", "CT"} ;
String CTT[] = new String[] {"Heure normale de Chine", "CST",
"Heure avanc\u00e9e de Chine", "CDT",
"Chine", "CT"} ;
String CUBA[] = new String[] {"Heure standard de Cuba", "CST",
"Heure d'\u00e9t\u00e9 de Cuba", "CDT",
"Heure de Cuba", "CT"};
String DARWIN[] = new String[] {"Heure standard d'Australie centrale (Territoire du Nord)", "ACST",
"Heure d'\u00E9t\u00E9 d'Australie centrale (Territoire du Nord)", "ACDT",
"Centre (Territoire du Nord)", "ACT"};
String DUBLIN[] = new String[] {"Heure du m\u00e9ridien de Greenwich", "GMT",
"Heure d'\u00e9t\u00e9 irlandaise", "IST",
"Heure irlandaise", "IT"};
String EAT[] = new String[] {"Heure d'Afrique de l'Est", "EAT",
"Heure d'\u00e9t\u00e9 d'Afrique de l'Est", "EAST",
"Heure d'Afrique de l'Est", "EAT"} ;
String EASTER[] = new String[] {"Heure de l'Ile de P\u00e2ques", "EAST",
"Heure d'\u00e9t\u00e9 de l'Ile de P\u00e2ques", "EASST",
"Heure de l'Ile de P\u00E2ques", "EAST"};
String EET[] = new String[] {"Heure d'Europe de l'Est", "EET",
"Heure d'\u00e9t\u00e9 d'Europe de l'Est", "EEST",
"Heure d'Europe de l'Est", "EET"} ;
String EGT[] = new String[] {"Heure du Groenland de l'Est", "EGT",
"Heure d'\u00e9t\u00e9 du Groenland de l'Est", "EGST",
"Heure du Groenland de l'Est", "EGT"} ;
String EST[] = new String[] {"Heure normale de l'Est", "EST",
"Heure avanc\u00e9e de l'Est", "EDT",
"C\u00F4te Est", "ET"} ;
String EST_NSW[] = new String[] {"Heure normale de l'Est (Nouvelle-Galles du Sud)", "AEST",
"Heure d'\u00E9t\u00E9 de l'Est (Nouvelle-Galles du Sud)", "AEDT",
"C\u00F4te Est (Nouvelle-Galles du Sud)", "AET"} ;
String FET[] = new String[] {"Heure d'Europe de l'Est UTC+3", "FET",
"Heure d'\u00E9t\u00E9 d'Europe de l'Est UTC+3", "FEST",
"Heure d'Europe de l'Est UTC+3", "FET"};
String GHMT[] = new String[] {"Heure du Ghana", "GMT",
"Heure d'\u00e9t\u00e9 du Ghana", "GHST",
"Heure du Ghana", "GMT"};
String GAMBIER[] = new String[] {"Heure de Gambi", "GAMT",
"Heure d'\u00e9t\u00e9 de Gambi", "GAMST",
"Heure de Gambi", "GAMT"};
String GMT[] = new String[] {"Heure de Greenwich", "GMT",
"Heure de Greenwich", "GMT",
"Heure de Greenwich", "GMT"} ;
String GMTBST[] = new String[] {"Heure du m\u00e9ridien de Greenwich", "GMT",
"Heure d'\u00e9t\u00e9 britannique", "BST",
"Heure britannique", "BT"};
String GST[] = new String[] {"Heure normale du Golfe", "GST",
"Heure avanc\u00e9e du Golfe", "GDT",
"Golfe", "GT"} ;
String HKT[] = new String[] {"Heure de Hong Kong", "HKT",
"Heure d'\u00e9t\u00e9 de Hong Kong", "HKST",
"Heure de Hong-Kong", "HKT"};
String HST[] = new String[] {"Heure normale d'Hawa\u00ef", "HST",
"Heure avanc\u00e9e d'Hawa\u00ef", "HDT",
"Hawa\u00EF", "HT"} ;
String ICT[] = new String[] {"Heure d'Indochine", "ICT",
"Heure d'\u00e9t\u00e9 d'Indochine", "ICST",
"Heure d'Indochine", "ICT"} ;
String IRKT[] = new String[] {"Heure d'Irkutsk", "IRKT",
"Heure d'\u00e9t\u00e9 d'Irkutsk", "IRKST",
"Heure d'Irkutsk", "IRKT"};
String IRT[] = new String[] {"Heure normale d'Iran", "IRST",
"Heure avanc\u00e9e d'Iran", "IRDT",
"Heure d'Iran", "IRT"} ;
String ISRAEL[] = new String[] {"Heure standard d'Isra\u00ebl", "IST",
"Heure avanc\u00e9e d'Isra\u00ebl", "IDT",
"Isra\u00EBl", "IT"};
String IST[] = new String[] {"Heure normale d'Inde", "IST",
"Heure avanc\u00e9e d'Inde", "IDT",
"Inde", "IT"} ;
String JST[] = new String[] {"Heure normale du Japon", "JST",
"Heure avanc\u00e9e du Japon", "JDT",
"Japon", "JT"} ;
String KRAT[] = new String[] {"Heure de Krasno\u00efarsk", "KRAT",
"Heure d'\u00e9t\u00e9 de Krasno\u00efarsk", "KRAST",
"Heure de Krasno\u00EFarsk", "KRAT"};
String KST[] = new String[] {"Heure normale de Cor\u00e9e", "KST",
"Heure avanc\u00e9e de Cor\u00e9e", "KDT",
"Cor\u00E9e", "KT"} ;
String LORD_HOWE[] = new String[] {"Heure standard de Lord Howe", "LHST",
"Heure d'\u00e9t\u00e9 de Lord Howe", "LHDT",
"Heure de Lord Howe", "LHT"};
String MHT[] = new String[] {"Heure des Iles Marshall", "MHT",
"Heure d'\u00e9t\u00e9 des Iles Marshall", "MHST",
"Heure des Iles Marshall", "MHT"};
String MMT[] = new String[] {"Heure de Myanmar", "MMT",
"Heure d'\u00e9t\u00e9 de Myanmar", "MMST",
"Heure de Myanmar", "MMT"};
String MSK[] = new String[] {"Heure standard de Moscou", "MSK",
"Heure avanc\u00e9e de Moscou", "MSD",
"Moscou", "MT"};
String MST[] = new String[] {"Heure normale des Rocheuses", "MST",
"Heure avanc\u00e9e des Rocheuses", "MDT",
"Rocheuses", "MT"} ;
String MYT[] = new String[] {"Heure de Malaisie", "MYT",
"Heure d'\u00e9t\u00e9 de Malaisie", "MYST",
"Heure de Malaisie", "MYT"};
String NORONHA[] = new String[] {"Heure de Fernando de Noronha", "FNT",
"Heure d'\u00e9t\u00e9 de Fernando de Noronha", "FNST",
"Heure de Fernando de Noronha", "FNT"};
String NOVT[] = new String[] {"Heure de Novossibirsk", "NOVT",
"Heure d'\u00e9t\u00e9 de Novossibirsk", "NOVST",
"Heure de Novossibirsk", "NOVT"};
String NPT[] = new String[] {"Heure du N\u00e9pal", "NPT",
"Heure d'\u00e9t\u00e9 du N\u00e9pal", "NPST",
"Heure du N\u00E9pal", "NPT"};
String NST[] = new String[] {"Heure normale de Terre-Neuve", "NST",
"Heure avanc\u00e9e de Terre-Neuve", "NDT",
"Terre-Neuve", "NT"} ;
String NZST[] = new String[] {"Heure normale de Nouvelle-Z\u00e9lande", "NZST",
"Heure avanc\u00e9e de Nouvelle-Z\u00e9lande", "NZDT",
"Nouvelle-Z\u00E9lande", "NZT"} ;
String PITCAIRN[] = new String[] {"Heure standard des Pitcairn", "PST",
"heure avanc\u00e9e des Pitcairn", "PDT",
"Pitcairn", "PT"};
String PKT[] = new String[] {"Heure du Pakistan", "PKT",
"Heure d'\u00e9t\u00e9 du Pakistan", "PKST",
"Heure du Pakistan", "PKT"} ;
String PONT[] = new String[] {"Heure de Pohnpei", "PONT",
"Heure d'\u00E9t\u00E9 de Pohnpei", "PONST",
"Ponape", "PONT"};
String PST[] = new String[] {"Heure normale du Pacifique", "PST",
"Heure avanc\u00e9e du Pacifique", "PDT",
"Pacifique", "PT"} ;
String SAST[] = new String[] {"Heure normale d'Afrique du Sud", "SAST",
"Heure d'\u00e9t\u00e9 d'Afrique du Sud", "SAST",
"Afrique du Sud", "SAT"} ;
String SBT[] = new String[] {"Heure des \u00celes Salomon", "SBT",
"Heure d'\u00e9t\u00e9 des \u00celes Salomon", "SBST",
"Heure des Iles Salomon", "SBT"} ;
String SGT[] = new String[] {"Heure de Singapour", "SGT",
"Heure d'\u00e9t\u00e9 de Singapour", "SGST",
"Heure de Singapour", "SGT"};
String TASMANIA[] = new String[] {"Heure standard d'Australie orientale (Tasmanie)", "AEST",
"Heure d'\u00E9t\u00E9 d'Australie orientale (Tasmanie)", "AEDT",
"C\u00F4te Est (Tasmanie)", "AET"};
String TMT[] = new String[] {"Heure du Turkm\u00e9nistan", "TMT",
"Heure d'\u00e9t\u00e9 du Turkm\u00e9nistan", "TMST",
"Heure du Turkm\u00E9nistan", "TMT"} ;
String ULAT[]= new String[] {"Heure de l'Ulaanbaatar", "ULAT",
"Heure d'\u00e9t\u00e9 de l'Ulaanbaatar", "ULAST",
"Heure de l'Ulaanbaatar", "ULAT"} ;
String WAT[] = new String[] {"Heure d'Afrique de l'Ouest", "WAT",
"Heure d'\u00e9t\u00e9 d'Afrique de l'Ouest", "WAST",
"Heure d'Afrique de l'Ouest", "WAT"} ;
String WET[] = new String[] {"Heure d'Europe de l'Ouest", "WET",
"Heure d'\u00e9t\u00e9 d'Europe de l'Ouest", "WEST",
"Heure d'Europe de l'Ouest", "WET"} ;
String WGT[] = new String[] {"Heure du Groenland de l'Ouest", "WGT",
"Heure d'\u00e9t\u00e9 du Groenland de l'Ouest", "WGST",
"Heure du Groenland de l'Ouest", "WGT"};
String WIT[] = new String[] {"Heure de l'Indon\u00e9sie occidentale", "WIB",
"Heure d'\u00e9t\u00e9 de l'Indon\u00e9sie occidentale", "WIST",
"Heure de l'Indon\u00E9sie occidentale", "WIB"};
String WST_AUS[] = new String[] {"Heure normale de l'Ouest (Australie)", "AWST",
"Heure d'\u00E9t\u00E9 de l'Ouest (Australie)", "AWDT",
"Ouest (Australie)", "AWT"} ;
String SAMOA[] = new String[] {"Heure standard de Samoa", "SST",
"Heure avanc\u00e9e de Samoa", "SDT",
"Samoa", "ST"};
String WST_SAMOA[] = new String[] {"Heure des Samoas occidentales", "WSST",
"Heure d'\u00e9t\u00e9 des Samoas occidentales", "WSDT",
"Heure des Samoas occidentales", "WST"} ;
String ChST[] = new String[] {"Heure normale des \u00eeles Mariannes", "ChST",
"Heure d'\u00e9t\u00e9 des \u00eeles Mariannes", "ChDT",
"Chamorro", "ChT"};
String VICTORIA[] = new String[] {"Heure standard d'Australie orientale (Victoria)", "AEST",
"Heure d'\u00E9t\u00E9 d'Australie orientale (Victoria)", "AEDT",
"C\u00F4te Est (Victoria)", "AET"};
String UTC[] = new String[] {"Temps universel coordonn\u00e9", "UTC",
"Temps universel coordonn\u00e9", "UTC",
"Temps universel coordonn\u00E9", "UTC"};
String UZT[] = new String[] {"Heure de l'Ouzb\u00e9kistan", "UZT",
"Heure d'\u00e9t\u00e9 de l'Ouzb\u00e9kistan", "UZST",
"Heure de l'Ouzb\u00E9kistan", "UZT"};
String XJT[] = new String[] {"Heure normale de Chine", "XJT",
"Heure avanc\u00e9e de Chine", "XJDT",
"Chine", "XJT"};
String YAKT[] = new String[] {"Heure du Iakoutsk", "YAKT",
"Heure d'\u00e9t\u00e9 du Iakoutsk", "YAKST",
"Heure du Iakoutsk", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", CAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", CAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", new String[] {"Central African Time", "CAT",
"Western African Time", "WAT",
"Central African Time", "CAT"}},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"Heure du Paraguay", "PYT",
"Heure d'\u00e9t\u00e9 du Paraguay", "PYST",
"Heure du Paraguay", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"Heure de Colombie", "COT",
"Heure d'\u00e9t\u00e9 de Colombie", "COST",
"Heure de Colombie", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"Heure du Venezuela", "VET",
"Heure d'\u00e9t\u00e9 du Venezuela", "VEST",
"Heure du Venezuela", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"Heure de Guyane fran\u00e7aise", "GFT",
"Heure d'\u00e9t\u00e9 de Guyane fran\u00e7aise", "GFST",
"Heure de Guyane fran\u00E7aise", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", CST},
{"America/Ciudad_Juarez", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", MST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", WGT},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", EST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"Heure de l'\u00c9quateur", "ECT",
"Heure d'\u00e9t\u00e9 de l'\u00c9quateur", "ECST",
"Heure de l'Equateur", "ECT"}},
{"America/Guyana", new String[] {"Heure de Guyana", "GYT",
"Heure d'\u00e9t\u00e9 de Guyana", "GYST",
"Heure de Guyana", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"Heure de Bolivie", "BOT",
"Heure d'\u00e9t\u00e9 de Bolivie", "BOST",
"Heure de Bolivie", "BOT"}},
{"America/Lima", new String[] {"Heure du P\u00e9rou", "PET",
"Heure d'\u00e9t\u00e9 du P\u00e9rou", "PEST",
"Heure du P\u00E9rou", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"Heure normale de Saint-Pierre et Miquelon", "PMST",
"Heure avanc\u00e9e de Saint-Pierre et Miquelon", "PMDT",
"Saint-Pierre-et-Miquelon", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"Heure de l'Uruguay", "UYT",
"Heure d'\u00e9t\u00e9 de l'Uruguay", "UYST",
"Heure de l'Uruguay", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Nuuk", WGT},
{"America/Ojinaga", CST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"Heure du Surinam", "SRT",
"Heure d'\u00e9t\u00e9 du Surinam", "SRST",
"Heure du Surinam", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", MST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"Heure de Davis", "DAVT",
"Heure d'\u00e9t\u00e9 de Davis", "DAVST",
"Heure de Davis", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"Heure de Dumont-d'Urville", "DDUT",
"Heure d'\u00e9t\u00e9 de Dumont-d'Urville", "DDUST",
"Heure de Dumont-d'Urville", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"Australian Eastern Standard Time (Macquarie)", "AEST",
"Australian Eastern Daylight Time (Macquarie)", "AEDT",
"Australian Eastern Time (Macquarie)", "AET"}},
{"Antarctica/Mawson", new String[] {"Heure de Mawson", "MAWT",
"Heure d'\u00e9t\u00e9 de Mawson", "MAWST",
"Heure de Mawson", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"Heure de Rothera", "ROTT",
"Heure d'\u00e9t\u00e9 de Rothera", "ROTST",
"Heure de Rothera", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"Heure de Syowa", "SYOT",
"Heure d'\u00e9t\u00e9 de Syowa", "SYOST",
"Heure de Syowa", "SYOT"}},
{"Antarctica/Troll", new String[] {"Temps universel coordonn\u00e9", "UTC",
"Heure d'\u00e9t\u00e9 d'Europe centrale", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"Heure de Vostok", "VOST",
"Heure d'\u00e9t\u00e9 de Vostok", "VOSST",
"Heure de Vostok", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"Heure d'Alma-Ata", "ALMT",
"Heure d'\u00e9t\u00e9 d'Alma-Ata", "ALMST",
"Heure d'Alma-Ata", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"Heure d'Anadyr", "ANAT",
"Heure d'\u00e9t\u00e9 d'Anadyr", "ANAST",
"Heure d'Anadyr", "ANAT"}},
{"Asia/Aqtau", new String[] {"Heure d'Aqtau", "AQTT",
"Heure d'\u00e9t\u00e9 d'Aqtau", "AQTST",
"Heure d'Aqtau", "AQTT"}},
{"Asia/Aqtobe", new String[] {"Heure d'Aqtobe", "AQTT",
"Heure d'\u00e9t\u00e9 d'Aqtobe", "AQTST",
"Heure d'Aqtobe", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"Heure d'Azerba\u00efdjan", "AZT",
"Heure d'\u00e9t\u00e9 d'Azerba\u00efdjan", "AZST",
"Heure d'Azerba\u00EFdjan", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"Heure du Kirghizistan", "KGT",
"Heure d'\u00e9t\u00e9 du Kirghizistan", "KGST",
"Heure du Kirghizistan", "KGT"}},
{"Asia/Brunei", new String[] {"Heure du Brunei", "BNT",
"Heure d'\u00e9t\u00e9 du Brunei", "BNST",
"Heure du Brunei", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"Heure de Choibalsan", "CHOT",
"Heure d'\u00e9t\u00e9 de Choibalsan", "CHOST",
"Heure de Choibalsan", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"Heure de Timor-Leste", "TLT",
"Heure d'\u00e9t\u00e9 de Timor-Leste", "TLST",
"Heure de Timor-Leste", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"Heure du Tadjikistan", "TJT",
"Heure d'\u00e9t\u00e9 du Tadjikistan", "TJST",
"Heure du Tadjikistan", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"Heure de Hovd", "HOVT",
"Heure d'\u00e9t\u00e9 de Hovd", "HOVST",
"Heure de Hovd", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"Heure d'Indon\u00e9sie orientale", "WIT",
"Heure d'\u00e9t\u00e9 d'Indon\u00e9sie orientale", "EIST",
"Heure d'Indon\u00E9sie orientale", "WIT"}},
{"Asia/Kabul", new String[] {"Heure d'Afghanistan", "AFT",
"Heure d'\u00e9t\u00e9 d'Afghanistan", "AFST",
"Heure d'Afghanistan", "AFT"}},
{"Asia/Kamchatka", new String[] {"Heure de Petropavlovsk-Kamchatski", "PETT",
"Heure d'\u00e9t\u00e9 de Petropavlovsk-Kamchatski", "PETST",
"Heure de Petropavlovsk-Kamchatski", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"Heure de Magadan", "MAGT",
"Heure d'\u00e9t\u00e9 de Magadan", "MAGST",
"Heure de Magadan", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"Philippines Standard Time", "PST",
"Philippines Daylight Time", "PDT",
"Philippines Time", "PT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"Heure d'Oral", "ORAT",
"Heure d'\u00e9t\u00e9 d'Oral", "ORAST",
"Heure d'Oral", "ORAT"}},
{"Asia/Omsk", new String[] {"Heure d'Omsk", "OMST",
"Heure d'\u00e9t\u00e9 d'Omsk", "OMSST",
"Heure d'Omsk", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"Heure de Kyzylorda", "QYZT",
"Heure d'\u00e9t\u00e9 de Kyzylorda", "QYZST",
"Heure de Kyzylorda", "QYZT"}},
{"Asia/Rangoon", MMT},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"Heure de Sakhalin", "SAKT",
"Heure d'\u00e9t\u00e9 de Sakhalin", "SAKST",
"Heure de Sakhalin", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", CTT},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"Heure de G\u00e9orgie", "GET",
"Heure d'\u00e9t\u00e9 de G\u00e9orgie", "GEST",
"Heure de G\u00E9orgie", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"Heure d'Ust-Nera", "VLAT",
"Heure d'\u00E9t\u00E9 d'Ust-Nera", "VLAST",
"Heure d'Ust-Nera", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"Heure de Vladivostok", "VLAT",
"Heure d'\u00e9t\u00e9 de Vladivostok", "VLAST",
"Heure de Vladivostok", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yangon", MMT},
{"Asia/Yekaterinburg", new String[] {"Heure de Yekaterinburg", "YEKT",
"Heure d'\u00e9t\u00e9 de Yekaterinburg", "YEKST",
"Heure de Yekaterinburg", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"Heure des A\u00e7ores", "AZOT",
"Heure d'\u00e9t\u00e9 des A\u00e7ores", "AZOST",
"Heure des A\u00E7ores", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"Heure de Cap-Vert", "CVT",
"Heure d'\u00e9t\u00e9 de Cap-Vert", "CVST",
"Heure de Cap-Vert", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"Heure normale de G\u00e9orgie du Sud", "GST",
"Heure avanc\u00e9e de G\u00e9orgie du Sud", "GDT",
"G\u00E9orgie du Sud", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"Heure des \u00eeles Falkland", "FKT",
"Heure d'\u00e9t\u00e9 des \u00eeles Falkland", "FKST",
"Heure des \u00EEles Falkland", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"Heure standard de l'Australie occidentale (centre)", "ACWST",
"Heure d'\u00E9t\u00E9 de l'Australie occidentale (centre)", "ACWDT",
"Heure de l'Australie occidentale (centre)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", MST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"Heure normale de Samara", "SAMT",
"Heure d'\u00e9t\u00e9 de Samara", "SAMST",
"Heure de Samara", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"Heure de l'oc\u00e9an Indien", "IOT",
"Heure d'\u00e9t\u00e9 de l'oc\u00e9an Indien", "IOST",
"Heure de l'oc\u00E9an Indien", "IOT"}},
{"Indian/Christmas", new String[] {"Heure de l'\u00cele Christmas", "CXT",
"Heure d'\u00e9t\u00e9 de l'\u00cele Christmas", "CXST",
"Heure de l'Ile Christmas", "CIT"}},
{"Indian/Cocos", new String[] {"Heure des \u00celes Cocos", "CCT",
"Heure d'\u00e9t\u00e9 des \u00celes Cocos", "CCST",
"Heure des Iles Cocos", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"Heure des Terres australes antartiques fran\u00e7aises", "TFT",
"Heure d'\u00e9t\u00e9 des Terres australes antartiques fran\u00e7aises", "TFST",
"Heure des Terres australes antarctiques fran\u00E7aises", "TFT"}},
{"Indian/Mahe", new String[] {"Heure des Seychelles", "SCT",
"Heure d'\u00e9t\u00e9 des Seychelles", "SCST",
"Heure des Seychelles", "SCT"}},
{"Indian/Maldives", new String[] {"Heure des Maldives", "MVT",
"Heure d'\u00e9t\u00e9 des Maldives", "MVST",
"Heure des Maldives", "MVT"}},
{"Indian/Mauritius", new String[] {"Heure de Maurice", "MUT",
"Heure d'\u00e9t\u00e9 de Maurice", "MUST",
"Heure de Maurice", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"Heure de la R\u00e9union", "RET",
"Heure d'\u00e9t\u00e9 de la R\u00e9union", "REST",
"Heure de la R\u00E9union", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"Heure de l'Europe centrale", "MET",
"Heure d'\u00e9t\u00e9 de l'Europe centrale", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", CHUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"Heure du Vanuatu", "VUT",
"Heure d'\u00e9t\u00e9 du Vanuatu", "VUST",
"Heure du Vanuatu", "VUT"}},
{"Pacific/Enderbury", new String[] {"Heure de l'\u00cele de Phoenix", "PHOT",
"Heure d'\u00e9t\u00e9 de l'\u00cele de Phoenix", "PHOST",
"Heure de l'Ile de Phoenix", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"Heure de Tokelau", "TKT",
"Heure d'\u00e9t\u00e9 de Tokelau", "TKST",
"Heure de Tokelau", "TKT"}},
{"Pacific/Fiji", new String[] {"Heure de Fidji", "FJT",
"Heure d'\u00e9t\u00e9 de Fidji", "FJST",
"Heure de Fidji", "FJT"}},
{"Pacific/Funafuti", new String[] {"Heure de Tuvalu", "TVT",
"Heure d'\u00e9t\u00e9 de Tuvalu", "TVST",
"Heure de Tuvalu", "TVT"}},
{"Pacific/Galapagos", new String[] {"Heure des Galapagos", "GALT",
"Heure d'\u00e9t\u00e9 des Galapagos", "GALST",
"Heure des Galapagos", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"Heure de l'\u00cele de Line", "LINT",
"Heure d'\u00e9t\u00e9 de l'\u00cele de Line", "LINST",
"Heure de l'Ile de Line", "LINT"}},
{"Pacific/Kosrae", new String[] {"Heure de Kusaie", "KOST",
"Heure d'\u00e9t\u00e9 de Kusaie", "KOSST",
"Heure de Kusaie", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"Heure des Marquises", "MART",
"Heure d'\u00e9t\u00e9 des Marquises", "MARST",
"Heure des Marquises", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"Heure de Nauru", "NRT",
"Heure d'\u00e9t\u00e9 de Nauru", "NRST",
"Heure de Nauru", "NRT"}},
{"Pacific/Niue", new String[] {"Heure de Niue", "NUT",
"Heure d'\u00e9t\u00e9 de Niue", "NUST",
"Heure de Niue", "NUT"}},
{"Pacific/Norfolk", new String[] {"Heure de Norfolk", "NFT",
"Heure d'\u00e9t\u00e9 de Norfolk", "NFST",
"Heure de Norfolk", "NFT"}},
{"Pacific/Noumea", new String[] {"Heure de Nouvelle-Cal\u00e9donie", "NCT",
"Heure d'\u00e9t\u00e9 de Nouvelle-Cal\u00e9donie", "NCST",
"Heure de Nouvelle-Cal\u00E9donie", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"Heure de Palaos", "PWT",
"Heure d'\u00e9t\u00e9 de Palaos", "PWST",
"Heure de Palaos", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"Heure de Papouasie-Nouvelle-Guin\u00e9e", "PGT",
"Heure d'\u00e9t\u00e9 de de Papouasie-Nouvelle-Guin\u00e9e", "PGST",
"Heure de Papouasie-Nouvelle-Guin\u00E9e", "PGT"}},
{"Pacific/Rarotonga", new String[] {"Heure des \u00celes Cook", "CKT",
"Heure d'\u00e9t\u00e9 des \u00celes Cook", "CKHST",
"Heure des Iles Cook", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"Heure de Tahiti", "TAHT",
"Heure d'\u00e9t\u00e9 de Tahiti", "TAHST",
"Heure de Tahiti", "TAHT"}},
{"Pacific/Tarawa", new String[] {"Heure de Kiribati", "GILT",
"Heure d'\u00e9t\u00e9 de Kiribati", "GILST",
"Heure de Kiribati", "GILT"}},
{"Pacific/Tongatapu", new String[] {"Heure de Tonga", "TOT",
"Heure d'\u00e9t\u00e9 de Tonga", "TOST",
"Heure de Tonga", "TOT"}},
{"Pacific/Truk", CHUT},
{"Pacific/Wake", new String[] {"Heure de Wake", "WAKT",
"Heure d'\u00e9t\u00e9 de Wake", "WAKST",
"Heure de Wake", "WAKT"}},
{"Pacific/Wallis", new String[] {"Heure de Wallis et Futuna", "WFT",
"Heure d'\u00e9t\u00e9 de Wallis et Futuna", "WFST",
"Heure de Wallis-et-Futuna", "WFT"}},
{"Pacific/Yap", CHUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/util/resources/fr/TimeZoneNames_fr.java |
180,170 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import leakcanary.FailTestOnLeak;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MemoryLeakTests {
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
@Test
@FailTestOnLeak
public void platformViewHybridComposition_launchActivityFinishAndLaunchAgain() throws Exception {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.putExtra("scenario_name", "platform_view");
intent.putExtra("use_android_view", true);
intent.putExtra("view_type", PlatformViewsActivity.TEXT_VIEW_PV);
activityRule.launchActivity(intent);
}
}
| flutter/engine | testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/MemoryLeakTests.java |
180,171 | /*
* Copyright (c) 2019-2022 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.geyser.util;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.cloudburstmc.math.vector.Vector3i;
import org.geysermc.geyser.inventory.GeyserItemStack;
import org.geysermc.geyser.inventory.PlayerInventory;
import org.geysermc.geyser.inventory.item.Enchantment;
import org.geysermc.geyser.level.block.BlockStateValues;
import org.geysermc.geyser.registry.BlockRegistries;
import org.geysermc.geyser.registry.type.BlockMapping;
import org.geysermc.geyser.registry.type.ItemMapping;
import org.geysermc.geyser.session.GeyserSession;
import org.geysermc.geyser.session.cache.tags.BlockTag;
import org.geysermc.geyser.translator.collision.BlockCollision;
import org.geysermc.mcprotocollib.protocol.data.game.item.component.DataComponents;
public final class BlockUtils {
private static boolean correctTool(GeyserSession session, BlockMapping blockMapping, String itemToolType) {
return switch (itemToolType) {
case "axe" -> session.getTagCache().is(BlockTag.AXE_EFFECTIVE, blockMapping);
case "hoe" -> session.getTagCache().is(BlockTag.HOE_EFFECTIVE, blockMapping);
case "pickaxe" -> session.getTagCache().is(BlockTag.PICKAXE_EFFECTIVE, blockMapping);
case "shears" -> session.getTagCache().is(BlockTag.LEAVES, blockMapping) || session.getTagCache().is(BlockTag.WOOL, blockMapping);
case "shovel" -> session.getTagCache().is(BlockTag.SHOVEL_EFFECTIVE, blockMapping);
case "sword" -> blockMapping.getJavaBlockId() == BlockStateValues.JAVA_COBWEB_ID;
default -> {
session.getGeyser().getLogger().warning("Unknown tool type: " + itemToolType);
yield false;
}
};
}
private static double toolBreakTimeBonus(String toolType, String toolTier, boolean isShearsEffective) {
if (toolType.equals("shears")) return isShearsEffective ? 5.0 : 15.0;
if (toolType.isEmpty()) return 1.0;
return switch (toolTier) {
// https://minecraft.wiki/w/Breaking#Speed
case "wooden" -> 2.0;
case "stone" -> 4.0;
case "iron" -> 6.0;
case "diamond" -> 8.0;
case "netherite" -> 9.0;
case "golden" -> 12.0;
default -> 1.0;
};
}
private static boolean canToolTierBreakBlock(GeyserSession session, BlockMapping blockMapping, String toolTier) {
if (toolTier.equals("netherite") || toolTier.equals("diamond")) {
// As of 1.17, these tiers can mine everything that is mineable
return true;
}
switch (toolTier) {
// Use intentional fall-throughs to check each tier with this block
default:
if (session.getTagCache().is(BlockTag.NEEDS_STONE_TOOL, blockMapping)) {
return false;
}
case "stone":
if (session.getTagCache().is(BlockTag.NEEDS_IRON_TOOL, blockMapping)) {
return false;
}
case "iron":
if (session.getTagCache().is(BlockTag.NEEDS_DIAMOND_TOOL, blockMapping)) {
return false;
}
}
return true;
}
// https://minecraft.wiki/w/Breaking
private static double calculateBreakTime(double blockHardness, String toolTier, boolean canHarvestWithHand, boolean correctTool, boolean canTierMineBlock,
String toolType, boolean isShearsEffective, int toolEfficiencyLevel, int hasteLevel, int miningFatigueLevel,
boolean insideOfWaterWithoutAquaAffinity, boolean onGround) {
double baseTime = (((correctTool && canTierMineBlock) || canHarvestWithHand) ? 1.5 : 5.0) * blockHardness;
double speed = 1.0 / baseTime;
if (correctTool) {
speed *= toolBreakTimeBonus(toolType, toolTier, isShearsEffective);
speed += toolEfficiencyLevel == 0 ? 0 : toolEfficiencyLevel * toolEfficiencyLevel + 1;
}
speed *= 1.0 + (0.2 * hasteLevel);
switch (miningFatigueLevel) {
case 0:
break;
case 1:
speed -= (speed * 0.7);
break;
case 2:
speed -= (speed * 0.91);
break;
case 3:
speed -= (speed * 0.9973);
break;
default:
speed -= (speed * 0.99919);
break;
}
if (insideOfWaterWithoutAquaAffinity) speed *= 0.2;
if (!onGround) speed *= 0.2;
return 1.0 / speed;
}
public static double getBreakTime(GeyserSession session, BlockMapping blockMapping, ItemMapping item, @Nullable DataComponents components, boolean isSessionPlayer) {
boolean isShearsEffective = session.getTagCache().is(BlockTag.LEAVES, blockMapping) || session.getTagCache().is(BlockTag.WOOL, blockMapping); //TODO called twice
boolean canHarvestWithHand = blockMapping.isCanBreakWithHand();
String toolType = "";
String toolTier = "";
boolean correctTool = false;
boolean toolCanBreak = false;
if (item.isTool()) {
toolType = item.getToolType();
toolTier = item.getToolTier();
correctTool = correctTool(session, blockMapping, toolType);
toolCanBreak = canToolTierBreakBlock(session, blockMapping, toolTier);
}
int toolEfficiencyLevel = ItemUtils.getEnchantmentLevel(components, Enchantment.JavaEnchantment.EFFICIENCY);
int hasteLevel = 0;
int miningFatigueLevel = 0;
if (!isSessionPlayer) {
// Another entity is currently mining; we have all the information we know
return calculateBreakTime(blockMapping.getHardness(), toolTier, canHarvestWithHand, correctTool, toolCanBreak, toolType, isShearsEffective,
toolEfficiencyLevel, hasteLevel, miningFatigueLevel, false, true);
}
hasteLevel = Math.max(session.getEffectCache().getHaste(), session.getEffectCache().getConduitPower());
miningFatigueLevel = session.getEffectCache().getMiningFatigue();
boolean waterInEyes = session.getCollisionManager().isWaterInEyes();
boolean insideOfWaterWithoutAquaAffinity = waterInEyes &&
ItemUtils.getEnchantmentLevel(session.getPlayerInventory().getItem(5).getComponents(), Enchantment.JavaEnchantment.AQUA_AFFINITY) < 1;
return calculateBreakTime(blockMapping.getHardness(), toolTier, canHarvestWithHand, correctTool, toolCanBreak, toolType, isShearsEffective,
toolEfficiencyLevel, hasteLevel, miningFatigueLevel, insideOfWaterWithoutAquaAffinity, session.getPlayerEntity().isOnGround());
}
public static double getSessionBreakTime(GeyserSession session, BlockMapping blockMapping) {
PlayerInventory inventory = session.getPlayerInventory();
GeyserItemStack item = inventory.getItemInHand();
ItemMapping mapping = ItemMapping.AIR;
DataComponents components = null;
if (item != null) {
mapping = item.getMapping(session);
components = item.getComponents();
}
return getBreakTime(session, blockMapping, mapping, components, true);
}
/**
* Given a position, return the position if a block were located on the specified block face.
* @param blockPos the block position
* @param face the face of the block - see {@link org.geysermc.mcprotocollib.protocol.data.game.entity.object.Direction}
* @return the block position with the block face accounted for
*/
public static Vector3i getBlockPosition(Vector3i blockPos, int face) {
return switch (face) {
case 0 -> blockPos.sub(0, 1, 0);
case 1 -> blockPos.add(0, 1, 0);
case 2 -> blockPos.sub(0, 0, 1);
case 3 -> blockPos.add(0, 0, 1);
case 4 -> blockPos.sub(1, 0, 0);
case 5 -> blockPos.add(1, 0, 0);
default -> blockPos;
};
}
/**
* Taking in a complete Java block state identifier, output just the block ID of this block state without the states.
* Examples:
* minecraft:oak_log[axis=x] = minecraft:oak_log
* minecraft:stone_brick_wall[east=low,north=tall,south=none,up=true,waterlogged=false,west=tall] = minecraft:stone_brick_wall
* minecraft:stone = minecraft:stone
*
* @param fullJavaIdentifier a full Java block identifier, with possible block states.
* @return a clean identifier in the format of minecraft:block
*/
public static String getCleanIdentifier(String fullJavaIdentifier) {
int stateIndex = fullJavaIdentifier.indexOf('[');
if (stateIndex == -1) {
// Identical to its clean variation
return fullJavaIdentifier;
}
return fullJavaIdentifier.substring(0, stateIndex);
}
public static BlockCollision getCollision(int blockId) {
return BlockRegistries.COLLISIONS.get(blockId);
}
public static BlockCollision getCollisionAt(GeyserSession session, Vector3i blockPos) {
return getCollision(session.getGeyser().getWorldManager().getBlockAt(session, blockPos));
}
public static BlockCollision getCollisionAt(GeyserSession session, int x, int y, int z) {
return getCollision(session.getGeyser().getWorldManager().getBlockAt(session, x, y, z));
}
private BlockUtils() {
}
}
| GeyserMC/Geyser | core/src/main/java/org/geysermc/geyser/util/BlockUtils.java |
180,172 | /*
* Copyright (c) 2023, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2023, Red Hat Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.core.nmt;
import static com.oracle.svm.core.Uninterruptible.CALLED_FROM_UNINTERRUPTIBLE_CODE;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.Platform;
import org.graalvm.nativeimage.Platforms;
import org.graalvm.nativeimage.c.struct.SizeOf;
import org.graalvm.word.Pointer;
import org.graalvm.word.PointerBase;
import org.graalvm.word.UnsignedWord;
import org.graalvm.word.WordFactory;
import com.oracle.svm.core.Uninterruptible;
import com.oracle.svm.core.VMInspectionOptions;
import com.oracle.svm.core.jdk.RuntimeSupport;
import com.oracle.svm.core.memory.NativeMemory;
import com.oracle.svm.core.util.UnsignedUtils;
import jdk.graal.compiler.api.replacements.Fold;
/**
* This class implements native memory tracking (NMT). There are two components to NMT: tracking
* memory allocations (malloc/realloc/calloc), and tracking virtual memory usage (not supported
* yet).
*
* For tracking memory allocations, we have an internal API (see {@link NativeMemory}) that adds a
* custom {@link NmtMallocHeader header} to each allocation if NMT is enabled. This header stores
* data that is needed to properly untrack the memory when it is freed.
*/
public class NativeMemoryTracking {
private static final UnsignedWord ALIGNMENT = WordFactory.unsigned(16);
private static final int MAGIC = 0xF0F1F2F3;
private final NmtMallocMemoryInfo[] categories;
private final NmtMallocMemoryInfo total;
@Platforms(Platform.HOSTED_ONLY.class)
public NativeMemoryTracking() {
total = new NmtMallocMemoryInfo();
categories = new NmtMallocMemoryInfo[NmtCategory.values().length];
for (int i = 0; i < categories.length; i++) {
categories[i] = new NmtMallocMemoryInfo();
}
}
@Fold
public static NativeMemoryTracking singleton() {
return ImageSingletons.lookup(NativeMemoryTracking.class);
}
@Fold
public static UnsignedWord sizeOfNmtHeader() {
/*
* Align the header to 16 bytes to preserve platform-specific malloc alignment up to 16
* bytes (i.e., the allocation payload is aligned to 16 bytes if the platform-specific
* malloc implementation returns a pointer that is aligned to at least 16 bytes).
*/
return UnsignedUtils.roundUp(SizeOf.unsigned(NmtMallocHeader.class), ALIGNMENT);
}
/**
* Initializes the NMT header and returns a pointer to the allocation payload (i.e., the inner
* pointer).
*/
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
@SuppressWarnings("static-method")
public Pointer initializeHeader(PointerBase outerPtr, UnsignedWord size, NmtCategory category) {
NmtMallocHeader mallocHeader = (NmtMallocHeader) outerPtr;
mallocHeader.setAllocationSize(size);
mallocHeader.setCategory(category.ordinal());
assert setMagic(mallocHeader);
return getInnerPointer(mallocHeader);
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
private static boolean setMagic(NmtMallocHeader mallocHeader) {
mallocHeader.setMagic(MAGIC);
return true;
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public void track(PointerBase innerPtr) {
if (innerPtr.isNull()) {
return;
}
NmtMallocHeader header = getHeader(innerPtr);
UnsignedWord nmtHeaderSize = sizeOfNmtHeader();
UnsignedWord allocationSize = header.getAllocationSize();
UnsignedWord totalSize = allocationSize.add(nmtHeaderSize);
getInfo(header.getCategory()).track(allocationSize);
getInfo(NmtCategory.NMT).track(nmtHeaderSize);
total.track(totalSize);
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public PointerBase untrack(PointerBase innerPtr) {
if (innerPtr.isNull()) {
return WordFactory.nullPointer();
}
NmtMallocHeader header = getHeader(innerPtr);
untrack(header.getAllocationSize(), header.getCategory());
return header;
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public void untrack(UnsignedWord size, int category) {
getInfo(category).untrack(size);
getInfo(NmtCategory.NMT).untrack(sizeOfNmtHeader());
total.untrack(size.add(sizeOfNmtHeader()));
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public static NmtMallocHeader getHeader(PointerBase innerPtr) {
NmtMallocHeader result = (NmtMallocHeader) ((Pointer) innerPtr).subtract(sizeOfNmtHeader());
assert result.getMagic() == MAGIC : "bad NMT malloc header";
return result;
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
private static Pointer getInnerPointer(NmtMallocHeader mallocHeader) {
return ((Pointer) mallocHeader).add(sizeOfNmtHeader());
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getUsedMemory(NmtCategory category) {
return getInfo(category).getUsed();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getPeakUsedMemory(NmtCategory category) {
return getInfo(category).getPeakUsed();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getCountAtPeakUsage(NmtCategory category) {
return getInfo(category).getCountAtPeakUsage();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getTotalCount() {
return total.getCount();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getTotalUsedMemory() {
return total.getUsed();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getPeakTotalUsedMemory() {
return total.getPeakUsed();
}
@Uninterruptible(reason = CALLED_FROM_UNINTERRUPTIBLE_CODE, mayBeInlined = true)
public long getCountAtTotalPeakUsage() {
return total.getCountAtPeakUsage();
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
private NmtMallocMemoryInfo getInfo(NmtCategory category) {
return getInfo(category.ordinal());
}
@Uninterruptible(reason = "Called from uninterruptible code.", mayBeInlined = true)
private NmtMallocMemoryInfo getInfo(int category) {
assert category < categories.length;
return categories[category];
}
public static RuntimeSupport.Hook shutdownHook() {
return isFirstIsolate -> NativeMemoryTracking.singleton().printStatistics();
}
private void printStatistics() {
if (VMInspectionOptions.PrintNMTStatistics.getValue()) {
System.out.println();
System.out.println("Native memory tracking");
System.out.println(" Peak total used memory: " + getPeakTotalUsedMemory() + " bytes");
System.out.println(" Total alive allocations at peak usage: " + getCountAtTotalPeakUsage());
System.out.println(" Total used memory: " + getTotalUsedMemory() + " bytes");
System.out.println(" Total alive allocations: " + getTotalCount());
for (int i = 0; i < NmtCategory.values().length; i++) {
String name = NmtCategory.values()[i].getName();
NmtMallocMemoryInfo info = getInfo(i);
System.out.println(" " + name + " peak used memory: " + info.getPeakUsed() + " bytes");
System.out.println(" " + name + " alive allocations at peak: " + info.getCountAtPeakUsage());
System.out.println(" " + name + " currently used memory: " + info.getUsed() + " bytes");
System.out.println(" " + name + " currently alive allocations: " + info.getCount());
}
}
}
}
| oracle/graal | substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/nmt/NativeMemoryTracking.java |
180,173 | /*
* Copyright 2011-2024 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* 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.jmx;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.List;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.jmx.spi.JmxInfoProvider;
public class JmxInfoProviderSupport implements JmxInfoProvider {
@Override
public long[] getFileDecriptorInfo() {
MBeanServer mbsc = MBeans.getMBeanServer();
AttributeList attributes;
try {
attributes = mbsc.getAttributes(
new ObjectName("java.lang:type=OperatingSystem"),
new String[]{"OpenFileDescriptorCount", "MaxFileDescriptorCount"});
List<Attribute> attrList = attributes.asList();
long openFdCount = (Long)attrList.get(0).getValue();
long maxFdCount = (Long)attrList.get(1).getValue();
long[] fdCounts = { openFdCount, maxFdCount};
return fdCounts;
} catch (Exception e) {
LogFactory.getLog(SdkMBeanRegistrySupport.class).debug(
"Failed to retrieve file descriptor info", e);
}
return null;
}
@Override
public int getThreadCount() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return threadMXBean.getThreadCount();
}
@Override
public int getDaemonThreadCount() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return threadMXBean.getDaemonThreadCount();
}
@Override
public int getPeakThreadCount() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return threadMXBean.getPeakThreadCount();
}
@Override
public long getTotalStartedThreadCount() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return threadMXBean.getTotalStartedThreadCount();
}
@Override
public long[] findDeadlockedThreads() {
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
return threadMXBean.findDeadlockedThreads();
}
@Override
public boolean isEnabled() {
return true;
}
}
| aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/jmx/JmxInfoProviderSupport.java |
180,174 | /*
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.ja;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_ja extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"\u30a2\u30af\u30ec\u6642\u9593", "ACT",
"\u30a2\u30af\u30ec\u590f\u6642\u9593", "ACST",
"\u30a2\u30af\u30ec\u6642\u9593", "ACT"};
String ADELAIDE[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACT"};
String AGT[] = new String[] {"\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u6642\u9593", "ART",
"\u30a2\u30eb\u30bc\u30f3\u30c1\u30f3\u590f\u6642\u9593", "ARST",
"\u30A2\u30EB\u30BC\u30F3\u30C1\u30F3\u6642\u9593", "ART"};
String AKST[] = new String[] {"\u30a2\u30e9\u30b9\u30ab\u6a19\u6e96\u6642", "AKST",
"\u30a2\u30e9\u30b9\u30ab\u590f\u6642\u9593", "AKDT",
"\u30A2\u30E9\u30B9\u30AB\u6642\u9593", "AKT"};
String AMT[] = new String[] {"\u30a2\u30de\u30be\u30f3\u6642\u9593", "AMT",
"\u30a2\u30de\u30be\u30f3\u590f\u6642\u9593", "AMST",
"\u30A2\u30DE\u30BE\u30F3\u6642\u9593", "AMT"};
String ARAST[] = new String[] {"\u30a2\u30e9\u30d3\u30a2\u6a19\u6e96\u6642", "AST",
"\u30a2\u30e9\u30d3\u30a2\u590f\u6642\u9593", "ADT",
"\u30A2\u30E9\u30D3\u30A2\u6642\u9593", "AT"};
String ARMT[] = new String[] {"\u30a2\u30eb\u30e1\u30cb\u30a2\u6642\u9593", "AMT",
"\u30a2\u30eb\u30e1\u30cb\u30a2\u590f\u6642\u9593", "AMST",
"\u30A2\u30EB\u30E1\u30CB\u30A2\u6642\u9593", "AMT"};
String AST[] = new String[] {"\u5927\u897f\u6d0b\u6a19\u6e96\u6642", "AST",
"\u5927\u897f\u6d0b\u590f\u6642\u9593", "ADT",
"\u5927\u897F\u6D0B\u6A19\u6E96\u6642", "AT"};
String BDT[] = new String[] {"\u30d0\u30f3\u30b0\u30e9\u30c7\u30b7\u30e5\u6642\u9593", "BDT",
"\u30d0\u30f3\u30b0\u30e9\u30c7\u30b7\u30e5\u590f\u6642\u9593", "BDST",
"\u30D0\u30F3\u30B0\u30E9\u30C7\u30B7\u30E5\u6642\u9593", "BDT"};
String BRISBANE[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30AF\u30A4\u30FC\u30F3\u30BA\u30E9\u30F3\u30C9)", "AET"};
String BROKEN_HILL[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u5357\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2/\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "ACT"};
String BRT[] = new String[] {"\u30d6\u30e9\u30b8\u30eb\u6642\u9593", "BRT",
"\u30d6\u30e9\u30b8\u30eb\u590f\u6642\u9593", "BRST",
"\u30D6\u30E9\u30B8\u30EA\u30A2\u6642\u9593", "BRT"};
String BTT[] = new String[] {"\u30d6\u30fc\u30bf\u30f3\u6642\u9593", "BTT",
"\u30d6\u30fc\u30bf\u30f3\u590f\u6642\u9593", "BTST",
"\u30D6\u30FC\u30BF\u30F3\u6642\u9593", "BTT"};
String CAT[] = new String[] {"\u4e2d\u90e8\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "CAT",
"\u4e2d\u90e8\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "CAST",
"\u4E2D\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "CAT"};
String CET[] = new String[] {"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "CET",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "CEST",
"\u4E2D\u90E8\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "CET"};
String CHAST[] = new String[] {"\u30c1\u30e3\u30bf\u30e0\u6a19\u6e96\u6642", "CHAST",
"\u30c1\u30e3\u30bf\u30e0\u590f\u6642\u9593", "CHADT",
"\u30C1\u30E3\u30BF\u30E0\u6642\u9593", "CHAT"};
String CHUT[] = new String[] {"\u30C1\u30E5\u30FC\u30AF\u6642\u9593", "CHUT",
"Chuuk Time", "CHUST",
"\u30C1\u30E5\u30FC\u30AF\u6642\u9593", "CHUT"};
String CIT[] = new String[] {"\u4e2d\u592e\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WITA",
"\u4e2d\u592e\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "CIST",
"\u4E2D\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WITA"};
String CLT[] = new String[] {"\u30c1\u30ea\u6642\u9593", "CLT",
"\u30c1\u30ea\u590f\u6642\u9593", "CLST",
"\u30C1\u30EA\u6642\u9593", "CLT"};
String CST[] = new String[] {"\u4e2d\u90e8\u6a19\u6e96\u6642", "CST",
"\u4e2d\u90e8\u590f\u6642\u9593", "CDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642", "CT"};
String CTT[] = new String[] {"\u4e2d\u56fd\u6a19\u6e96\u6642", "CST",
"\u4e2d\u56fd\u590f\u6642\u9593", "CDT",
"\u4E2D\u56FD\u6642\u9593", "CT"};
String CUBA[] = new String[] {"\u30ad\u30e5\u30fc\u30d0\u6a19\u6e96\u6642", "CST",
"\u30ad\u30e5\u30fc\u30d0\u590f\u6642\u9593", "CDT",
"\u30AD\u30E5\u30FC\u30D0\u6642\u9593", "CT"};
String DARWIN[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACST",
"\u4E2D\u90E8\u590F\u6642\u9593(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACDT",
"\u4E2D\u90E8\u6A19\u6E96\u6642(\u30CE\u30FC\u30B6\u30F3\u30C6\u30EA\u30C8\u30EA\u30FC)", "ACT"};
String DUBLIN[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30a2\u30a4\u30eb\u30e9\u30f3\u30c9\u590f\u6642\u9593", "IST",
"\u30A2\u30A4\u30EB\u30E9\u30F3\u30C9\u6642\u9593", "IT"};
String EAT[] = new String[] {"\u6771\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "EAT",
"\u6771\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "EAST",
"\u6771\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "EAT"};
String EASTER[] = new String[] {"\u30a4\u30fc\u30b9\u30bf\u30fc\u5cf6\u6642\u9593", "EAST",
"\u30a4\u30fc\u30b9\u30bf\u30fc\u5cf6\u590f\u6642\u9593", "EASST",
"\u30A4\u30FC\u30B9\u30BF\u30FC\u5CF6\u6642\u9593", "EAST"};
String EET[] = new String[] {"\u6771\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "EET",
"\u6771\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "EEST",
"\u6771\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "EET"};
String EGT[] = new String[] {"\u6771\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u6642\u9593", "EGT",
"\u6771\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u590f\u6642\u9593", "EGST",
"\u6771\u90E8\u30B0\u30EA\u30FC\u30F3\u30E9\u30F3\u30C9\u6642\u9593", "EGT"};
String EST[] = new String[] {"\u6771\u90e8\u6a19\u6e96\u6642", "EST",
"\u6771\u90e8\u590f\u6642\u9593", "EDT",
"\u6771\u90E8\u6A19\u6E96\u6642", "ET"};
String EST_NSW[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30CB\u30E5\u30FC\u30B5\u30A6\u30B9\u30A6\u30A7\u30FC\u30EB\u30BA)", "AET"};
String FET[] = new String[] {"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "FET",
"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u590F\u6642\u9593", "FEST",
"\u6975\u6771\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "FET"};
String GHMT[] = new String[] {"\u30ac\u30fc\u30ca\u6a19\u6e96\u6642", "GMT",
"\u30ac\u30fc\u30ca\u590f\u6642\u9593", "GHST",
"\u30AC\u30FC\u30CA\u6A19\u6E96\u6642", "GMT"};
String GAMBIER[] = new String[] {"\u30ac\u30f3\u30d3\u30a2\u6642\u9593", "GAMT",
"\u30ac\u30f3\u30d3\u30a2\u590f\u6642\u9593", "GAMST",
"\u30AC\u30F3\u30D3\u30A8\u6642\u9593", "GAMT"};
String GMT[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u30B0\u30EA\u30CB\u30C3\u30B8\u6A19\u6E96\u6642", "GMT"};
String GMTBST[] = new String[] {"\u30b0\u30ea\u30cb\u30c3\u30b8\u6a19\u6e96\u6642", "GMT",
"\u82f1\u56fd\u590f\u6642\u9593", "BST",
"\u30A4\u30AE\u30EA\u30B9\u6642\u9593", "BT"};
String GST[] = new String[] {"\u6e7e\u5cb8\u6a19\u6e96\u6642", "GST",
"\u6e7e\u5cb8\u590f\u6642\u9593", "GDT",
"\u6E7E\u5CB8\u6642\u9593", "GT"};
String HKT[] = new String[] {"\u9999\u6e2f\u6642\u9593", "HKT",
"\u9999\u6e2f\u590f\u6642\u9593", "HKST",
"\u9999\u6E2F\u6642\u9593", "HKT"};
String HST[] = new String[] {"\u30cf\u30ef\u30a4\u6a19\u6e96\u6642", "HST",
"\u30cf\u30ef\u30a4\u590f\u6642\u9593", "HDT",
"\u30CF\u30EF\u30A4\u6642\u9593", "HT"};
String ICT[] = new String[] {"\u30a4\u30f3\u30c9\u30b7\u30ca\u6642\u9593", "ICT",
"\u30a4\u30f3\u30c9\u30b7\u30ca\u590f\u6642\u9593", "ICST",
"\u30A4\u30F3\u30C9\u30B7\u30CA\u6642\u9593", "ICT"};
String IRKT[] = new String[] {"\u30a4\u30eb\u30af\u30fc\u30c4\u30af\u6642\u9593", "IRKT",
"\u30a4\u30eb\u30af\u30fc\u30c4\u30af\u590f\u6642\u9593", "IRKST",
"\u30A4\u30EB\u30AF\u30FC\u30C4\u30AF\u6642\u9593", "IRKT"};
String IRT[] = new String[] {"\u30a4\u30e9\u30f3\u6a19\u6e96\u6642", "IRST",
"\u30a4\u30e9\u30f3\u590f\u6642\u9593", "IRDT",
"\u30A4\u30E9\u30F3\u6642\u9593", "IRT"};
String ISRAEL[] = new String[] {"\u30a4\u30b9\u30e9\u30a8\u30eb\u6a19\u6e96\u6642", "IST",
"\u30a4\u30b9\u30e9\u30a8\u30eb\u590f\u6642\u9593", "IDT",
"\u30A4\u30B9\u30E9\u30A8\u30EB\u6642\u9593", "IT"};
String IST[] = new String[] {"\u30a4\u30f3\u30c9\u6a19\u6e96\u6642", "IST",
"\u30a4\u30f3\u30c9\u590f\u6642\u9593", "IDT",
"\u30A4\u30F3\u30C9\u6642\u9593", "IT"};
String JST[] = new String[] {"\u65e5\u672c\u6a19\u6e96\u6642", "JST",
"\u65e5\u672c\u590f\u6642\u9593", "JDT",
"\u65E5\u672C\u6642\u9593", "JT"};
String KRAT[] = new String[] {"\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u6642\u9593", "KRAT",
"\u30af\u30e9\u30b9\u30ce\u30e4\u30eb\u30b9\u30af\u590f\u6642\u9593", "KRAST",
"\u30AF\u30E9\u30B9\u30CE\u30E4\u30EB\u30B9\u30AF\u6642\u9593", "KRAT"};
String KST[] = new String[] {"\u97d3\u56fd\u6a19\u6e96\u6642", "KST",
"\u97d3\u56fd\u590f\u6642\u9593", "KDT",
"\u97D3\u56FD\u6642\u9593", "KT"};
String LORD_HOWE[] = new String[] {"\u30ed\u30fc\u30c9\u30cf\u30a6\u5cf6\u6a19\u6e96\u6642", "LHST",
"\u30ed\u30fc\u30c9\u30cf\u30a6\u5cf6\u590f\u6642\u9593", "LHDT",
"\u30ED\u30FC\u30C9\u30CF\u30A6\u6642\u9593", "LHT"};
String MHT[] = new String[] {"\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u6642\u9593", "MHT",
"\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u590f\u6642\u9593", "MHST",
"\u30DE\u30FC\u30B7\u30E3\u30EB\u8AF8\u5CF6\u6642\u9593", "MHT"};
String MMT[] = new String[] {"\u30df\u30e3\u30f3\u30de\u30fc\u6642\u9593", "MMT",
"\u30df\u30e3\u30f3\u30de\u30fc\u590f\u6642\u9593", "MMST",
"\u30DF\u30E3\u30F3\u30DE\u30FC\u6642\u9593", "MMT"};
String MSK[] = new String[] {"\u30e2\u30b9\u30af\u30ef\u6a19\u6e96\u6642", "MSK",
"\u30e2\u30b9\u30af\u30ef\u590f\u6642\u9593", "MSD",
"\u30E2\u30B9\u30AF\u30EF\u6642\u9593", "MT"};
String MST[] = new String[] {"\u5c71\u5730\u6a19\u6e96\u6642", "MST",
"\u5c71\u5730\u590f\u6642\u9593", "MDT",
"\u5C71\u5730\u6A19\u6E96\u6642", "MT"};
String MYT[] = new String[] {"\u30de\u30ec\u30fc\u30b7\u30a2\u6642\u9593", "MYT",
"\u30de\u30ec\u30fc\u30b7\u30a2\u590f\u6642\u9593", "MYST",
"\u30DE\u30EC\u30FC\u30B7\u30A2\u6642\u9593", "MYT"};
String NORONHA[] = new String[] {"\u30d5\u30a7\u30eb\u30ca\u30f3\u30c9\u30fb\u30c7\u30fb\u30ce\u30ed\u30fc\u30cb\u30e3\u6642\u9593", "FNT",
"\u30d5\u30a7\u30eb\u30ca\u30f3\u30c9\u30fb\u30c7\u30fb\u30ce\u30ed\u30fc\u30cb\u30e3\u590f\u6642\u9593", "FNST",
"\u30D5\u30A7\u30EB\u30CA\u30F3\u30C9\u30FB\u30C7\u30FB\u30CE\u30ED\u30FC\u30CB\u30E3\u6642\u9593", "FNT"};
String NOVT[] = new String[] {"\u30ce\u30dc\u30b7\u30d3\u30eb\u30b9\u30af\u6642\u9593", "NOVT",
"\u30ce\u30dc\u30b7\u30d3\u30eb\u30b9\u30af\u590f\u6642\u9593", "NOVST",
"\u30CE\u30F4\u30A9\u30B7\u30D3\u30EB\u30B9\u30AF\u6642\u9593", "NOVT"};
String NPT[] = new String[] {"\u30cd\u30d1\u30fc\u30eb\u6642\u9593", "NPT",
"\u30cd\u30d1\u30fc\u30eb\u590f\u6642\u9593", "NPST",
"\u30CD\u30D1\u30FC\u30EB\u6642\u9593", "NPT"};
String NST[] = new String[] {"\u30cb\u30e5\u30fc\u30d5\u30a1\u30f3\u30c9\u30e9\u30f3\u30c9\u6a19\u6e96\u6642", "NST",
"\u30cb\u30e5\u30fc\u30d5\u30a1\u30f3\u30c9\u30e9\u30f3\u30c9\u590f\u6642\u9593", "NDT",
"\u30CB\u30E5\u30FC\u30D5\u30A1\u30F3\u30C9\u30E9\u30F3\u30C9\u6642\u9593", "NT"};
String NZST[] = new String[] {"\u30cb\u30e5\u30fc\u30b8\u30fc\u30e9\u30f3\u30c9\u6a19\u6e96\u6642", "NZST",
"\u30cb\u30e5\u30fc\u30b8\u30fc\u30e9\u30f3\u30c9\u590f\u6642\u9593", "NZDT",
"\u30CB\u30E5\u30FC\u30B8\u30FC\u30E9\u30F3\u30C9\u6642\u9593", "NZT"};
String PITCAIRN[] = new String[] {"\u30d4\u30c8\u30b1\u30eb\u30f3\u5cf6\u6a19\u6e96\u6642", "PST",
"\u30d4\u30c8\u30b1\u30eb\u30f3\u5cf6\u590f\u6642\u9593", "PDT",
"\u30D4\u30C8\u30B1\u30A2\u30F3\u6642\u9593", "PT"};
String PKT[] = new String[] {"\u30d1\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "PKT",
"\u30d1\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "PKST",
"\u30D1\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "PKT"};
String PONT[] = new String[] {"\u30DD\u30F3\u30DA\u30A4\u6642\u9593", "PONT",
"\u30DD\u30F3\u30DA\u30A4\u590F\u6642\u9593", "PONST",
"\u30DD\u30CA\u30DA\u6642\u9593", "PONT"};
String PST[] = new String[] {"\u592a\u5e73\u6d0b\u6a19\u6e96\u6642", "PST",
"\u592a\u5e73\u6d0b\u590f\u6642\u9593", "PDT",
"\u592A\u5E73\u6D0B\u6A19\u6E96\u6642", "PT"};
String SAST[] = new String[] {"\u5357\u30a2\u30d5\u30ea\u30ab\u6a19\u6e96\u6642", "SAST",
"\u5357\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "SAST",
"\u5357\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "SAT"};
String SBT[] = new String[] {"\u30bd\u30ed\u30e2\u30f3\u8af8\u5cf6\u6642\u9593", "SBT",
"\u30bd\u30ed\u30e2\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "SBST",
"\u30BD\u30ED\u30E2\u30F3\u8AF8\u5CF6\u6642\u9593", "SBT"};
String SGT[] = new String[] {"\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb\u6642\u9593", "SGT",
"\u30b7\u30f3\u30ac\u30dd\u30fc\u30eb\u590f\u6642\u9593", "SGST",
"\u30B7\u30F3\u30AC\u30DD\u30FC\u30EB\u6642\u9593", "SGT"};
String TASMANIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30BF\u30B9\u30DE\u30CB\u30A2)", "AET"};
String TMT[] = new String[] {"\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3\u6642\u9593", "TMT",
"\u30c8\u30eb\u30af\u30e1\u30cb\u30b9\u30bf\u30f3\u590f\u6642\u9593", "TMST",
"\u30C8\u30EB\u30AF\u30E1\u30CB\u30B9\u30BF\u30F3\u6642\u9593", "TMT"};
String ULAT[]= new String[] {"\u30a6\u30e9\u30fc\u30f3\u30d0\u30fc\u30c8\u30eb\u6642\u9593", "ULAT",
"\u30a6\u30e9\u30fc\u30f3\u30d0\u30fc\u30c8\u30eb\u590f\u6642\u9593", "ULAST",
"\u30A6\u30E9\u30F3\u30D0\u30FC\u30C8\u30EB\u6642\u9593", "ULAT"};
String WAT[] = new String[] {"\u897f\u30a2\u30d5\u30ea\u30ab\u6642\u9593", "WAT",
"\u897f\u30a2\u30d5\u30ea\u30ab\u590f\u6642\u9593", "WAST",
"\u897F\u90E8\u30A2\u30D5\u30EA\u30AB\u6642\u9593", "WAT"};
String WET[] = new String[] {"\u897f\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "WET",
"\u897f\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "WEST",
"\u897F\u90E8\u30E8\u30FC\u30ED\u30C3\u30D1\u6642\u9593", "WET"};
String WGT[] = new String[] {"\u897f\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u6642\u9593", "WGT",
"\u897f\u30b0\u30ea\u30fc\u30f3\u30e9\u30f3\u30c9\u590f\u6642\u9593", "WGST",
"\u897F\u90E8\u30B0\u30EA\u30FC\u30F3\u30E9\u30F3\u30C9\u6642\u9593", "WGT"};
String WIT[] = new String[] {"\u897f\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WIB",
"\u897f\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "WIST",
"\u897F\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WIB"};
String WST_AUS[] = new String[] {"\u897F\u90E8\u6A19\u6E96\u6642(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWST",
"\u897F\u90E8\u590F\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWDT",
"\u897F\u90E8\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "AWT"};
String SAMOA[] = new String[] {"\u30b5\u30e2\u30a2\u6a19\u6e96\u6642", "SST",
"\u30b5\u30e2\u30a2\u590f\u6642\u9593", "SDT",
"\u30B5\u30E2\u30A2\u6642\u9593", "ST"};
String WST_SAMOA[] = new String[] {"\u897f\u30b5\u30e2\u30a2\u6642\u9593", "WSST",
"\u897f\u30b5\u30e2\u30a2\u590f\u6642\u9593", "WSDT",
"\u897F\u30B5\u30E2\u30A2\u6642\u9593", "WST"};
String ChST[] = new String[] {"\u30b0\u30a2\u30e0\u6a19\u6e96\u6642", "ChST",
"\u30b0\u30a2\u30e0\u590f\u6642\u9593", "ChDT",
"\u30C1\u30E3\u30E2\u30ED\u6642\u9593", "ChT"};
String VICTORIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AEST",
"\u6771\u90E8\u590F\u6642\u9593(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AEDT",
"\u6771\u90E8\u6A19\u6E96\u6642(\u30D3\u30AF\u30C8\u30EA\u30A2)", "AET"};
String UTC[] = new String[] {"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u5354\u5B9A\u4E16\u754C\u6642", "UTC"};
String UZT[] = new String[] {"\u30a6\u30ba\u30d9\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "UZT",
"\u30a6\u30ba\u30d9\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "UZST",
"\u30A6\u30BA\u30D9\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "UZT"};
String XJT[] = new String[] {"\u4e2d\u56fd\u6a19\u6e96\u6642", "XJT",
"\u4e2d\u56fd\u590f\u6642\u9593", "XJDT",
"\u4E2D\u56FD\u6642\u9593", "XJT"};
String YAKT[] = new String[] {"\u30e4\u30af\u30fc\u30c4\u30af\u6642\u9593", "YAKT",
"\u30e4\u30af\u30fc\u30c4\u30af\u590f\u6642\u9593", "YAKST",
"\u30E4\u30AF\u30FC\u30C4\u30AF\u6642\u9593", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", CAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", CAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", new String[] {"Central African Time", "CAT",
"Western African Time", "WAT",
"Central African Time", "CAT"}},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"\u30d1\u30e9\u30b0\u30a2\u30a4\u6642\u9593", "PYT",
"\u30d1\u30e9\u30b0\u30a2\u30a4\u590f\u6642\u9593", "PYST",
"\u30D1\u30E9\u30B0\u30A2\u30A4\u6642\u9593", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"\u30b3\u30ed\u30f3\u30d3\u30a2\u6642\u9593", "COT",
"\u30b3\u30ed\u30f3\u30d3\u30a2\u590f\u6642\u9593", "COST",
"\u30B3\u30ED\u30F3\u30D3\u30A2\u6642\u9593", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"\u30d9\u30cd\u30ba\u30a8\u30e9\u6642\u9593", "VET",
"\u30d9\u30cd\u30ba\u30a8\u30e9\u590f\u6642\u9593", "VEST",
"\u30D9\u30CD\u30BA\u30A8\u30E9\u6642\u9593", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"\u4ecf\u9818\u30ae\u30a2\u30ca\u6642\u9593", "GFT",
"\u4ecf\u9818\u30ae\u30a2\u30ca\u590f\u6642\u9593", "GFST",
"\u30D5\u30E9\u30F3\u30B9\u9818\u30AE\u30A2\u30CA\u6642\u9593", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", CST},
{"America/Ciudad_Juarez", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", MST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", WGT},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", EST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"\u30a8\u30af\u30a2\u30c9\u30eb\u6642\u9593", "ECT",
"\u30a8\u30af\u30a2\u30c9\u30eb\u590f\u6642\u9593", "ECST",
"\u30A8\u30AF\u30A2\u30C9\u30EB\u6642\u9593", "ECT"}},
{"America/Guyana", new String[] {"\u30ac\u30a4\u30a2\u30ca\u6642\u9593", "GYT",
"\u30ac\u30a4\u30a2\u30ca\u590f\u6642\u9593", "GYST",
"\u30AC\u30A4\u30A2\u30CA\u6642\u9593", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"\u30dc\u30ea\u30d3\u30a2\u6642\u9593", "BOT",
"\u30dc\u30ea\u30d3\u30a2\u590f\u6642\u9593", "BOST",
"\u30DC\u30EA\u30D3\u30A2\u6642\u9593", "BOT"}},
{"America/Lima", new String[] {"\u30da\u30eb\u30fc\u6642\u9593", "PET",
"\u30da\u30eb\u30fc\u590f\u6642\u9593", "PEST",
"\u30DA\u30EB\u30FC\u6642\u9593", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"\u30b5\u30f3\u30d4\u30a8\u30fc\u30eb\u30fb\u30df\u30af\u30ed\u30f3\u8af8\u5cf6\u6a19\u6e96\u6642", "PMST",
"\u30b5\u30f3\u30d4\u30a8\u30fc\u30eb\u30fb\u30df\u30af\u30ed\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "PMDT",
"\u30D4\u30A8\u30FC\u30EB\u30FB\u30DF\u30AF\u30ED\u30F3\u6642\u9593", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"\u30a6\u30eb\u30b0\u30a2\u30a4\u6642\u9593", "UYT",
"\u30a6\u30eb\u30b0\u30a2\u30a4\u590f\u6642\u9593", "UYST",
"\u30A6\u30EB\u30B0\u30A2\u30A4\u6642\u9593", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Nuuk", WGT},
{"America/Ojinaga", CST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"\u30b9\u30ea\u30ca\u30e0\u6642\u9593", "SRT",
"\u30b9\u30ea\u30ca\u30e0\u590f\u6642\u9593", "SRST",
"\u30B9\u30EA\u30CA\u30E0\u6642\u9593", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", MST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"\u30c7\u30a4\u30d3\u30b9\u6642\u9593", "DAVT",
"\u30c7\u30a4\u30d3\u30b9\u590f\u6642\u9593", "DAVST",
"\u30C7\u30FC\u30D3\u30B9\u6642\u9593", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"\u30c7\u30e5\u30e2\u30f3\u30c7\u30e5\u30eb\u30f4\u30a3\u30eb\u6642\u9593", "DDUT",
"\u30c7\u30e5\u30e2\u30f3\u30c7\u30e5\u30eb\u30f4\u30a3\u30eb\u590f\u6642\u9593", "DDUST",
"\u30C7\u30E5\u30E2\u30F3\u30FB\u30C7\u30E5\u30EB\u30D3\u30EB\u6642\u9593", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"Australian Eastern Standard Time (Macquarie)", "AEST",
"Australian Eastern Daylight Time (Macquarie)", "AEDT",
"Australian Eastern Time (Macquarie)", "AET"}},
{"Antarctica/Mawson", new String[] {"\u30e2\u30fc\u30bd\u30f3\u6642\u9593", "MAWT",
"\u30e2\u30fc\u30bd\u30f3\u590f\u6642\u9593", "MAWST",
"\u30E2\u30FC\u30BD\u30F3\u6642\u9593", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"\u30ed\u30bc\u30e9\u6642\u9593", "ROTT",
"\u30ed\u30bc\u30e9\u590f\u6642\u9593", "ROTST",
"\u30ED\u30BC\u30E9\u6642\u9593", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"\u662d\u548c\u57fa\u5730\u6642\u9593", "SYOT",
"\u662d\u548c\u57fa\u5730\u590f\u6642\u9593", "SYOST",
"\u662D\u548C\u57FA\u5730\u6642\u9593", "SYOT"}},
{"Antarctica/Troll", new String[] {"\u5354\u5b9a\u4e16\u754c\u6642", "UTC",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"\u30dc\u30b9\u30c8\u30fc\u30af\u57fa\u5730\u6642\u9593", "VOST",
"\u30dc\u30b9\u30c8\u30fc\u30af\u57fa\u5730\u590f\u6642\u9593", "VOSST",
"\u30DC\u30B9\u30C8\u30FC\u30AF\u6642\u9593", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"\u30a2\u30eb\u30de\u30a2\u30bf\u6642\u9593", "ALMT",
"\u30a2\u30eb\u30de\u30a2\u30bf\u590f\u6642\u9593", "ALMST",
"\u30A2\u30EB\u30DE\u30A2\u30BF\u6642\u9593", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"\u30a2\u30ca\u30c9\u30a5\u30a4\u30ea\u6642\u9593", "ANAT",
"\u30a2\u30ca\u30c9\u30a5\u30a4\u30ea\u590f\u6642\u9593", "ANAST",
"\u30A2\u30CA\u30C7\u30A3\u30EA\u6642\u9593", "ANAT"}},
{"Asia/Aqtau", new String[] {"\u30a2\u30af\u30bf\u30a6\u6642\u9593", "AQTT",
"\u30a2\u30af\u30bf\u30a6\u590f\u6642\u9593", "AQTST",
"\u30A2\u30AF\u30BF\u30A6\u6642\u9593", "AQTT"}},
{"Asia/Aqtobe", new String[] {"\u30a2\u30af\u30c8\u30d9\u6642\u9593", "AQTT",
"\u30a2\u30af\u30c8\u30d9\u590f\u6642\u9593", "AQTST",
"\u30A2\u30AF\u30C8\u30D9\u6642\u9593", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3\u6642\u9593", "AZT",
"\u30a2\u30bc\u30eb\u30d0\u30a4\u30b8\u30e3\u30f3\u590f\u6642\u9593", "AZST",
"\u30A2\u30BC\u30EB\u30D0\u30A4\u30B8\u30E3\u30F3\u6642\u9593", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"\u30ad\u30eb\u30ae\u30b9\u30bf\u30f3\u6642\u9593", "KGT",
"\u30ad\u30eb\u30ae\u30b9\u30bf\u30f3\u590f\u6642\u9593", "KGST",
"\u30AD\u30EB\u30AE\u30B9\u6642\u9593", "KGT"}},
{"Asia/Brunei", new String[] {"\u30d6\u30eb\u30cd\u30a4\u6642\u9593", "BNT",
"\u30d6\u30eb\u30cd\u30a4\u590f\u6642\u9593", "BNST",
"\u30D6\u30EB\u30CD\u30A4\u6642\u9593", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"\u30c1\u30e7\u30a4\u30d0\u30eb\u30b5\u30f3\u6642\u9593", "CHOT",
"\u30c1\u30e7\u30a4\u30d0\u30eb\u30b5\u30f3\u590f\u6642\u9593", "CHOST",
"\u30C1\u30E7\u30A4\u30D0\u30EB\u30B5\u30F3\u6642\u9593", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"\u6771\u30c6\u30a3\u30e2\u30fc\u30eb\u6642\u9593", "TLT",
"\u6771\u30c6\u30a3\u30e2\u30fc\u30eb\u590f\u6642\u9593", "TLST",
"\u6771\u30C6\u30A3\u30E2\u30FC\u30EB\u6642\u9593", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3\u6642\u9593", "TJT",
"\u30bf\u30b8\u30ad\u30b9\u30bf\u30f3\u590f\u6642\u9593", "TJST",
"\u30BF\u30B8\u30AD\u30B9\u30BF\u30F3\u6642\u9593", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"\u30db\u30d6\u30c9\u6642\u9593", "HOVT",
"\u30db\u30d6\u30c9\u590f\u6642\u9593", "HOVST",
"\u30DB\u30D6\u30C9\u6642\u9593", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"\u6771\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u6642\u9593", "WIT",
"\u6771\u30a4\u30f3\u30c9\u30cd\u30b7\u30a2\u590f\u6642\u9593", "EIST" ,
"\u6771\u90E8\u30A4\u30F3\u30C9\u30CD\u30B7\u30A2\u6642\u9593", "WIT"}},
{"Asia/Kabul", new String[] {"\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3\u6642\u9593", "AFT",
"\u30a2\u30d5\u30ac\u30cb\u30b9\u30bf\u30f3\u590f\u6642\u9593", "AFST",
"\u30A2\u30D5\u30AC\u30CB\u30B9\u30BF\u30F3\u6642\u9593", "AFT"}},
{"Asia/Kamchatka", new String[] {"\u30da\u30c8\u30ed\u30d1\u30d6\u30ed\u30d5\u30b9\u30af\u30ab\u30e0\u30c1\u30e3\u30c4\u30ad\u30fc\u6642\u9593", "PETT",
"\u30da\u30c8\u30ed\u30d1\u30d6\u30ed\u30d5\u30b9\u30af\u30ab\u30e0\u30c1\u30e3\u30c4\u30ad\u30fc\u590f\u6642\u9593", "PETST",
"\u30DA\u30C8\u30ED\u30D1\u30D6\u30ED\u30D5\u30B9\u30AF\u30FB\u30AB\u30E0\u30C1\u30E3\u30C4\u30AD\u30FC\u6642\u9593", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"\u30de\u30ac\u30c0\u30f3\u6642\u9593", "MAGT",
"\u30de\u30ac\u30c0\u30f3\u590f\u6642\u9593", "MAGST",
"\u30DE\u30AC\u30C0\u30F3\u6642\u9593", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"Philippines Standard Time", "PST",
"Philippines Daylight Time", "PDT",
"Philippines Time", "PT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"\u30aa\u30e9\u30eb\u6642\u9593", "ORAT",
"\u30aa\u30e9\u30eb\u590f\u6642\u9593", "ORAST",
"\u30AA\u30E9\u30EB\u6642\u9593", "ORAT"}},
{"Asia/Omsk", new String[] {"\u30aa\u30e0\u30b9\u30af\u6642\u9593", "OMST",
"\u30aa\u30e0\u30b9\u30af\u590f\u6642\u9593", "OMSST",
"\u30AA\u30E0\u30B9\u30AF\u6642\u9593", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u6642\u9593", "QYZT",
"\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u590f\u6642\u9593", "QYZST",
"\u30AF\u30BA\u30ED\u30EB\u30C0\u6642\u9593", "QYZT"}},
{"Asia/Rangoon", MMT},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"\u6a3a\u592a\u6642\u9593", "SAKT",
"\u6a3a\u592a\u590f\u6642\u9593", "SAKST",
"\u30B5\u30CF\u30EA\u30F3\u6642\u9593", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", CTT},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"\u30b0\u30eb\u30b8\u30a2\u6642\u9593", "GET",
"\u30b0\u30eb\u30b8\u30a2\u590f\u6642\u9593", "GEST",
"\u30B0\u30EB\u30B8\u30A2\u6642\u9593", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"\u30A6\u30B9\u30C1\u30CD\u30E9\u6642\u9593", "VLAT",
"\u30A6\u30B9\u30C1\u30CD\u30E9\u590F\u6642\u9593", "VLAST",
"\u30A6\u30B9\u30C1\u30CD\u30E9\u6642\u9593", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"\u30a6\u30e9\u30b8\u30aa\u30b9\u30c8\u30af\u6642\u9593", "VLAT",
"\u30a6\u30e9\u30b8\u30aa\u30b9\u30c8\u30af\u590f\u6642\u9593", "VLAST",
"\u30A6\u30E9\u30B8\u30AA\u30B9\u30C8\u30AF\u6642\u9593", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yangon", MMT},
{"Asia/Yekaterinburg", new String[] {"\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u6642\u9593", "YEKT",
"\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u590f\u6642\u9593", "YEKST",
"\u30A8\u30AB\u30C6\u30EA\u30F3\u30D6\u30EB\u30AF\u6642\u9593", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"\u30a2\u30be\u30ec\u30b9\u6642\u9593", "AZOT",
"\u30a2\u30be\u30ec\u30b9\u590f\u6642\u9593", "AZOST",
"\u30A2\u30BE\u30EC\u30B9\u6642\u9593", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"\u30ab\u30fc\u30dc\u30d9\u30eb\u30c7\u6642\u9593", "CVT",
"\u30ab\u30fc\u30dc\u30d9\u30eb\u30c7\u590f\u6642\u9593", "CVST",
"\u30AB\u30FC\u30DC\u30D9\u30EB\u30C7\u6642\u9593", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"\u5357\u30b8\u30e7\u30fc\u30b8\u30a2\u5cf6\u6a19\u6e96\u6642", "GST",
"\u5357\u30b8\u30e7\u30fc\u30b8\u30a2\u5cf6\u590f\u6642\u9593", "GDT",
"\u5357\u30B8\u30E7\u30FC\u30B8\u30A2\u6642\u9593", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"\u30d5\u30a9\u30fc\u30af\u30e9\u30f3\u30c9\u8af8\u5cf6\u6642\u9593", "FKT",
"\u30d5\u30a9\u30fc\u30af\u30e9\u30f3\u30c9\u8af8\u5cf6\u590f\u6642\u9593", "FKST",
"\u30D5\u30A9\u30FC\u30AF\u30E9\u30F3\u30C9\u8AF8\u5CF6\u6642\u9593", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"\u4E2D\u897F\u90E8\u6A19\u6E96\u6642(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWST",
"\u4E2D\u897F\u90E8\u590F\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWDT",
"\u4E2D\u897F\u90E8\u6642\u9593(\u30AA\u30FC\u30B9\u30C8\u30E9\u30EA\u30A2)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", MST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"\u30b5\u30de\u30e9\u6642\u9593", "SAMT",
"\u30b5\u30de\u30e9\u590f\u6642\u9593", "SAMST",
"\u30B5\u30DE\u30E9\u6642\u9593", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"\u30a4\u30f3\u30c9\u6d0b\u5730\u57df\u6642\u9593", "IOT",
"\u30a4\u30f3\u30c9\u6d0b\u5730\u57df\u590f\u6642\u9593", "IOST",
"\u30A4\u30F3\u30C9\u6D0B\u5730\u57DF\u6642\u9593", "IOT"}},
{"Indian/Christmas", new String[] {"\u30af\u30ea\u30b9\u30de\u30b9\u8af8\u5cf6\u6642\u9593", "CXT",
"\u30af\u30ea\u30b9\u30de\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "CXST",
"\u30AF\u30EA\u30B9\u30DE\u30B9\u5CF6\u6642\u9593", "CIT"}},
{"Indian/Cocos", new String[] {"\u30b3\u30b3\u30b9\u8af8\u5cf6\u6642\u9593", "CCT",
"\u30b3\u30b3\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "CCST",
"\u30B3\u30B3\u30B9\u8AF8\u5CF6\u6642\u9593", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"\u4ecf\u5357\u65b9\u9818\u304a\u3088\u3073\u5357\u6975\u6642\u9593", "TFT",
"\u4ecf\u5357\u65b9\u9818\u304a\u3088\u3073\u5357\u6975\u590f\u6642\u9593", "TFST",
"\u30D5\u30E9\u30F3\u30B9\u9818\u5357\u65B9\u304A\u3088\u3073\u5357\u6975\u5927\u9678\u6642\u9593", "TFT"}},
{"Indian/Mahe", new String[] {"\u30bb\u30a4\u30b7\u30a7\u30eb\u6642\u9593", "SCT",
"\u30bb\u30a4\u30b7\u30a7\u30eb\u590f\u6642\u9593", "SCST",
"\u30BB\u30FC\u30B7\u30A7\u30EB\u6642\u9593", "SCT"}},
{"Indian/Maldives", new String[] {"\u30e2\u30eb\u30b8\u30d6\u6642\u9593", "MVT",
"\u30e2\u30eb\u30b8\u30d6\u590f\u6642\u9593", "MVST",
"\u30E2\u30EB\u30B8\u30D6\u6642\u9593", "MVT"}},
{"Indian/Mauritius", new String[] {"\u30e2\u30fc\u30ea\u30b7\u30e3\u30b9\u6642\u9593", "MUT",
"\u30e2\u30fc\u30ea\u30b7\u30e3\u30b9\u590f\u6642\u9593", "MUST",
"\u30E2\u30FC\u30EA\u30B7\u30E3\u30B9\u6642\u9593", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"\u30ec\u30e6\u30cb\u30aa\u30f3\u6642\u9593", "RET",
"\u30ec\u30e6\u30cb\u30aa\u30f3\u590f\u6642\u9593", "REST",
"\u30EC\u30E6\u30CB\u30AA\u30F3\u6642\u9593", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u6642\u9593", "MET",
"\u4e2d\u90e8\u30e8\u30fc\u30ed\u30c3\u30d1\u590f\u6642\u9593", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", CHUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"\u30d0\u30cc\u30a2\u30c4\u6642\u9593", "VUT",
"\u30d0\u30cc\u30a2\u30c4\u590f\u6642\u9593", "VUST",
"\u30D0\u30CC\u30A2\u30C4\u6642\u9593", "VUT"}},
{"Pacific/Enderbury", new String[] {"\u30d5\u30a7\u30cb\u30c3\u30af\u30b9\u8af8\u5cf6\u6642\u9593", "PHOT",
"\u30d5\u30a7\u30cb\u30c3\u30af\u30b9\u8af8\u5cf6\u590f\u6642\u9593", "PHOST",
"\u30D5\u30A7\u30CB\u30C3\u30AF\u30B9\u8AF8\u5CF6\u6642\u9593", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"\u30c8\u30b1\u30e9\u30a6\u8af8\u5cf6\u6642\u9593", "TKT",
"\u30c8\u30b1\u30e9\u30a6\u8af8\u5cf6\u590f\u6642\u9593", "TKST",
"\u30C8\u30B1\u30E9\u30A6\u6642\u9593", "TKT"}},
{"Pacific/Fiji", new String[] {"\u30d5\u30a3\u30b8\u30fc\u6642\u9593", "FJT",
"\u30d5\u30a3\u30b8\u30fc\u590f\u6642\u9593", "FJST",
"\u30D5\u30A3\u30B8\u30FC\u6642\u9593", "FJT"}},
{"Pacific/Funafuti", new String[] {"\u30c4\u30d0\u30eb\u6642\u9593", "TVT",
"\u30c4\u30d0\u30eb\u590f\u6642\u9593", "TVST",
"\u30C4\u30D0\u30EB\u6642\u9593", "TVT"}},
{"Pacific/Galapagos", new String[] {"\u30ac\u30e9\u30d1\u30b4\u30b9\u6642\u9593", "GALT",
"\u30ac\u30e9\u30d1\u30b4\u30b9\u590f\u6642\u9593", "GALST",
"\u30AC\u30E9\u30D1\u30B4\u30B9\u6642\u9593", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"\u30e9\u30a4\u30f3\u8af8\u5cf6\u6642\u9593", "LINT",
"\u30e9\u30a4\u30f3\u8af8\u5cf6\u590f\u6642\u9593", "LINST",
"\u30E9\u30A4\u30F3\u8AF8\u5CF6\u6642\u9593", "LINT"}},
{"Pacific/Kosrae", new String[] {"\u30b3\u30b9\u30e9\u30a8\u6642\u9593", "KOST",
"\u30b3\u30b9\u30e9\u30a8\u590f\u6642\u9593", "KOSST",
"\u30B3\u30B9\u30E9\u30A8\u6642\u9593", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"\u30de\u30eb\u30b1\u30b5\u30b9\u6642\u9593", "MART",
"\u30de\u30eb\u30b1\u30b5\u30b9\u590f\u6642\u9593", "MARST",
"\u30DE\u30EB\u30AD\u30FC\u30BA\u6642\u9593", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"\u30ca\u30a6\u30eb\u6642\u9593", "NRT",
"\u30ca\u30a6\u30eb\u590f\u6642\u9593", "NRST",
"\u30CA\u30A6\u30EB\u6642\u9593", "NRT"}},
{"Pacific/Niue", new String[] {"\u30cb\u30a6\u30a8\u5cf6\u6642\u9593", "NUT",
"\u30cb\u30a6\u30a8\u5cf6\u590f\u6642\u9593", "NUST",
"\u30CB\u30A6\u30A8\u6642\u9593", "NUT"}},
{"Pacific/Norfolk", new String[] {"\u30ce\u30fc\u30d5\u30a9\u30fc\u30af\u6642\u9593", "NFT",
"\u30ce\u30fc\u30d5\u30a9\u30fc\u30af\u590f\u6642\u9593", "NFST",
"\u30CE\u30FC\u30D5\u30A9\u30FC\u30AF\u6642\u9593", "NFT"}},
{"Pacific/Noumea", new String[] {"\u30cb\u30e5\u30fc\u30ab\u30ec\u30c9\u30cb\u30a2\u6642\u9593", "NCT",
"\u30cb\u30e5\u30fc\u30ab\u30ec\u30c9\u30cb\u30a2\u590f\u6642\u9593", "NCST",
"\u30CB\u30E5\u30FC\u30AB\u30EC\u30C9\u30CB\u30A2\u6642\u9593", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"\u30d1\u30e9\u30aa\u6642\u9593", "PWT",
"\u30d1\u30e9\u30aa\u590f\u6642\u9593", "PWST",
"\u30D1\u30E9\u30AA\u6642\u9593", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"\u30d1\u30d7\u30a2\u30cb\u30e5\u30fc\u30ae\u30cb\u30a2\u6642\u9593", "PGT",
"\u30d1\u30d7\u30a2\u30cb\u30e5\u30fc\u30ae\u30cb\u30a2\u590f\u6642\u9593", "PGST",
"\u30D1\u30D7\u30A2\u30CB\u30E5\u30FC\u30AE\u30CB\u30A2\u6642\u9593", "PGT"}},
{"Pacific/Rarotonga", new String[] {"\u30af\u30c3\u30af\u8af8\u5cf6\u6642\u9593", "CKT",
"\u30af\u30c3\u30af\u8af8\u5cf6\u590f\u6642\u9593", "CKHST",
"\u30AF\u30C3\u30AF\u8AF8\u5CF6\u6642\u9593", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"\u30bf\u30d2\u30c1\u6642\u9593", "TAHT",
"\u30bf\u30d2\u30c1\u590f\u6642\u9593", "TAHST",
"\u30BF\u30D2\u30C1\u6642\u9593", "TAHT"}},
{"Pacific/Tarawa", new String[] {"\u30ae\u30eb\u30d0\u30fc\u30c8\u8af8\u5cf6\u6642\u9593", "GILT",
"\u30ae\u30eb\u30d0\u30fc\u30c8\u8af8\u5cf6\u590f\u6642\u9593", "GILST",
"\u30AE\u30EB\u30D0\u30FC\u30C8\u8AF8\u5CF6\u6642\u9593", "GILT"}},
{"Pacific/Tongatapu", new String[] {"\u30c8\u30f3\u30ac\u6642\u9593", "TOT",
"\u30c8\u30f3\u30ac\u590f\u6642\u9593", "TOST",
"\u30C8\u30F3\u30AC\u6642\u9593", "TOT"}},
{"Pacific/Truk", CHUT},
{"Pacific/Wake", new String[] {"\u30a6\u30a7\u30fc\u30af\u6642\u9593", "WAKT",
"\u30a6\u30a7\u30fc\u30af\u590f\u6642\u9593", "WAKST",
"\u30A6\u30A7\u30FC\u30AF\u6642\u9593", "WAKT"}},
{"Pacific/Wallis", new String[] {"\u30ef\u30ea\u30b9\u53ca\u3073\u30d5\u30c4\u30ca\u6642\u9593", "WFT",
"\u30ef\u30ea\u30b9\u53ca\u3073\u30d5\u30c4\u30ca\u590f\u6642\u9593", "WFST",
"\u30A6\u30A9\u30EA\u30B9\u30FB\u30D5\u30C4\u30CA\u6642\u9593", "WFT"}},
{"Pacific/Yap", CHUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java |
180,175 | /*
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.zh;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_zh_CN extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"Acre \u65f6\u95f4", "ACT",
"Acre \u590f\u4ee4\u65f6", "ACST",
"Acre \u65f6\u95f4", "ACT"};
String ADELAIDE[] = new String[] {"\u4E2D\u592E\u6807\u51C6\u65F6\u95F4 (\u5357\u6FB3\u5927\u5229\u4E9A)", "ACST",
"\u4E2D\u592E\u590F\u4EE4\u65F6 (\u5357\u6FB3\u5927\u5229\u4E9A)", "ACDT",
"\u4E2D\u90E8\u65F6\u95F4 (\u5357\u6FB3\u5927\u5229\u4E9A)", "ACT"};
String AGT[] = new String[] {"\u963f\u6839\u5ef7\u65f6\u95f4", "ART",
"\u963f\u6839\u5ef7\u590f\u4ee4\u65f6", "ARST",
"\u963F\u6839\u5EF7\u65F6\u95F4", "ART"};
String AKST[] = new String[] {"\u963f\u62c9\u65af\u52a0\u6807\u51c6\u65f6\u95f4", "AKST",
"\u963f\u62c9\u65af\u52a0\u590f\u4ee4\u65f6", "AKDT",
"\u963F\u62C9\u65AF\u52A0\u65F6\u95F4", "AKT"};
String AMT[] = new String[] {"\u4e9a\u9a6c\u900a\u65f6\u95f4", "AMT",
"\u4e9a\u9a6c\u900a\u590f\u4ee4\u65f6", "AMST",
"\u4E9A\u9A6C\u900A\u65F6\u95F4", "AMT"};
String ARAST[] = new String[] {"\u963f\u62c9\u4f2f\u6807\u51c6\u65f6\u95f4", "AST",
"\u963f\u62c9\u4f2f\u590f\u4ee4\u65f6", "ADT",
"\u963F\u62C9\u4F2F\u534A\u5C9B\u65F6\u95F4", "AT"};
String ARMT[] = new String[] {"\u4e9a\u7f8e\u5c3c\u4e9a\u65f6\u95f4", "AMT",
"\u4e9a\u7f8e\u5c3c\u4e9a\u590f\u4ee4\u65f6", "AMST",
"\u4E9A\u7F8E\u5C3C\u4E9A\u65F6\u95F4", "AMT"};
String AST[] = new String[] {"\u5927\u897f\u6d0b\u6807\u51c6\u65f6\u95f4", "AST",
"\u5927\u897f\u6d0b\u590f\u4ee4\u65f6", "ADT",
"\u5927\u897F\u6D0B\u65F6\u95F4", "AT"};
String BDT[] = new String[] {"\u5b5f\u52a0\u62c9\u65f6\u95f4", "BDT",
"\u5b5f\u52a0\u62c9\u590f\u4ee4\u65f6", "BDST",
"\u5B5F\u52A0\u62C9\u65F6\u95F4", "BDT"};
String BRISBANE[] = new String[] {"\u4E1C\u90E8\u6807\u51C6\u65F6\u95F4 (\u6606\u58EB\u5170)", "AEST",
"\u4E1C\u90E8\u590F\u4EE4\u65F6 (\u6606\u58EB\u5170)", "AEDT",
"\u4E1C\u90E8\u65F6\u95F4 (\u6606\u58EB\u5170)", "AET"};
String BROKEN_HILL[] = new String[] {"\u4E2D\u592E\u6807\u51C6\u65F6\u95F4 (\u5357\u6FB3\u5927\u5229\u4E9A/\u65B0\u5357\u5A01\u5C14\u65AF)", "ACST",
"\u4E2D\u592E\u590F\u4EE4\u65F6 (\u5357\u6FB3\u5927\u5229\u4E9A/\u65B0\u5357\u5A01\u5C14\u65AF)", "ACDT",
"\u4E2D\u90E8\u65F6\u95F4 (\u5357\u6FB3\u5927\u5229\u4E9A/\u65B0\u5357\u5A01\u5C14\u65AF)", "ACT"};
String BRT[] = new String[] {"\u5df4\u897f\u5229\u4e9a\u65f6\u95f4", "BRT",
"\u5df4\u897f\u5229\u4e9a\u590f\u4ee4\u65f6", "BRST",
"\u5DF4\u897F\u5229\u4E9A\u65F6\u95F4", "BRT"};
String BTT[] = new String[] {"\u4e0d\u4e39\u65f6\u95f4", "BTT",
"\u4e0d\u4e39\u590f\u4ee4\u65f6", "BTST",
"\u4E0D\u4E39\u65F6\u95F4", "BTT"};
String CAT[] = new String[] {"\u4e2d\u975e\u65f6\u95f4", "CAT",
"\u4e2d\u975e\u590f\u4ee4\u65f6", "CAST",
"\u4E2D\u975E\u65F6\u95F4", "CAT"};
String CET[] = new String[] {"\u4e2d\u6b27\u65f6\u95f4", "CET",
"\u4e2d\u6b27\u590f\u4ee4\u65f6", "CEST",
"\u4E2D\u6B27\u65F6\u95F4", "CET"};
String CHAST[] = new String[] {"\u67e5\u8428\u59c6\u6807\u51c6\u65f6\u95f4", "CHAST",
"\u67e5\u8428\u59c6\u590f\u4ee4\u65f6", "CHADT",
"\u67E5\u5854\u59C6\u65F6\u95F4", "CHAT"};
String CHUT[] = new String[] {"\u4E18\u514B\u65F6\u95F4", "CHUT",
"\u4E18\u514B\u590F\u4EE4\u65F6", "CHUST",
"\u4E18\u514B\u65F6\u95F4", "CHUT"};
String CIT[] = new String[] {"\u4e2d\u90e8\u5370\u5ea6\u5c3c\u897f\u4e9a\u65f6\u95f4", "WITA",
"\u4e2d\u90e8\u5370\u5ea6\u5c3c\u897f\u4e9a\u590f\u4ee4\u65f6", "CIST",
"\u4E2D\u90E8\u5370\u5EA6\u5C3C\u897F\u4E9A\u65F6\u95F4", "WITA"};
String CLT[] = new String[] {"\u667a\u5229\u65f6\u95f4", "CLT",
"\u667a\u5229\u590f\u4ee4\u65f6", "CLST",
"\u667A\u5229\u65F6\u95F4", "CLT"};
String CST[] = new String[] {"\u4e2d\u592e\u6807\u51c6\u65f6\u95f4", "CST",
"\u4e2d\u592e\u590f\u4ee4\u65f6", "CDT",
"\u4E2D\u90E8\u65F6\u95F4", "CT"};
String CTT[] = new String[] {"\u4e2d\u56fd\u6807\u51c6\u65f6\u95f4", "CST",
"\u4e2d\u56fd\u590f\u4ee4\u65f6", "CDT",
"\u4E2D\u56FD\u65F6\u95F4", "CT"};
String CUBA[] = new String[] {"\u53e4\u5df4\u6807\u51c6\u65f6\u95f4", "CST",
"\u53e4\u5df4\u590f\u4ee4\u65f6", "CDT",
"\u53E4\u5DF4\u65F6\u95F4", "CT"};
String DARWIN[] = new String[] {"\u4E2D\u592E\u6807\u51C6\u65F6\u95F4 (\u5317\u9886\u5730)", "ACST",
"\u4E2D\u592E\u590F\u4EE4\u65F6 (\u5317\u9886\u5730)", "ACDT",
"\u4E2D\u90E8\u65F6\u95F4 (\u5317\u90E8\u5730\u533A)", "ACT"};
String DUBLIN[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u65f6\u95f4", "GMT",
"\u7231\u5c14\u5170\u590f\u4ee4\u65f6", "IST",
"\u7231\u5C14\u5170\u65F6\u95F4", "IT"};
String EAT[] = new String[] {"\u4e1c\u975e\u65f6\u95f4", "EAT",
"\u4e1c\u975e\u590f\u4ee4\u65f6", "EAST",
"\u4E1C\u975E\u65F6\u95F4", "EAT"};
String EASTER[] = new String[] {"\u590d\u6d3b\u5c9b\u65f6\u95f4", "EAST",
"\u590d\u6d3b\u5c9b\u590f\u4ee4\u65f6", "EASST",
"\u590D\u6D3B\u5C9B\u65F6\u95F4", "EAST"};
String EET[] = new String[] {"\u4e1c\u6b27\u65f6\u95f4", "EET",
"\u4e1c\u6b27\u590f\u4ee4\u65f6", "EEST",
"\u4e1c\u6b27\u65f6\u95f4", "EET"};
String EGT[] = new String[] {"\u4e1c\u683c\u6797\u5c9b\u65f6\u95f4", "EGT",
"\u4e1c\u683c\u6797\u5c9b\u590f\u4ee4\u65f6", "EGST",
"\u4E1C\u683C\u6797\u5C9B\u65F6\u95F4", "EGT"};
String EST[] = new String[] {"\u4e1c\u90e8\u6807\u51c6\u65f6\u95f4", "EST",
"\u4e1c\u90e8\u590f\u4ee4\u65f6", "EDT",
"\u4E1C\u90E8\u65F6\u95F4", "ET"};
String EST_NSW[] = new String[] {"\u4E1C\u90E8\u6807\u51C6\u65F6\u95F4 (\u65B0\u5357\u5A01\u5C14\u65AF)", "AEST",
"\u4E1C\u90E8\u590F\u4EE4\u65F6 (\u65B0\u5357\u5A01\u5C14\u65AF)", "AEDT",
"\u4E1C\u90E8\u65F6\u95F4 (\u65B0\u5357\u5A01\u5C14\u65AF)", "AET"};
String FET[] = new String[] {"\u8FDC\u4E1C\u6B27\u65F6\u95F4", "FET",
"\u8FDC\u4E1C\u6B27\u590F\u4EE4\u65F6", "FEST",
"\u8FDC\u4E1C\u6B27\u65F6\u95F4", "FET"};
String GHMT[] = new String[] {"\u52a0\u7eb3\u65f6\u95f4", "GMT",
"\u52a0\u7eb3\u590f\u4ee4\u65f6", "GHST",
"\u52A0\u7EB3\u65F6\u95F4", "GMT"};
String GAMBIER[] = new String[] {"\u5188\u6bd4\u4e9a\u65f6\u95f4", "GAMT",
"\u5188\u6bd4\u4e9a\u590f\u4ee4\u65f6", "GAMST",
"\u5188\u6BD4\u4E9A\u65F6\u95F4", "GAMT"};
String GMT[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u65f6\u95f4", "GMT",
"\u683c\u6797\u5a01\u6cbb\u65f6\u95f4", "GMT",
"\u683C\u6797\u5A01\u6CBB\u65F6\u95F4", "GMT"};
String GMTBST[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u65f6\u95f4", "GMT",
"\u82f1\u56fd\u590f\u4ee4\u65f6", "BST",
"\u82F1\u56FD\u65F6\u95F4", "BT"};
String GST[] = new String[] {"\u6ce2\u65af\u6e7e\u6807\u51c6\u65f6\u95f4", "GST",
"\u6ce2\u65af\u6e7e\u590f\u4ee4\u65f6", "GDT",
"\u6D77\u6E7E\u65F6\u95F4", "GT"};
String HKT[] = new String[] {"\u9999\u6e2f\u65f6\u95f4", "HKT",
"\u9999\u6e2f\u590f\u4ee4\u65f6", "HKST",
"\u9999\u6E2F\u65F6\u95F4", "HKT"};
String HST[] = new String[] {"\u590f\u5a01\u5937\u6807\u51c6\u65f6\u95f4", "HST",
"\u590f\u5a01\u5937\u590f\u4ee4\u65f6", "HDT",
"\u590F\u5A01\u5937\u65F6\u95F4", "HT"};
String ICT[] = new String[] {"\u5370\u5ea6\u652f\u90a3\u65f6\u95f4", "ICT",
"\u5370\u5ea6\u652f\u90a3\u590f\u4ee4\u65f6", "ICST",
"\u5370\u5EA6\u652F\u90A3\u65F6\u95F4", "ICT"};
String IRKT[] = new String[] {"\u4f0a\u5c14\u5e93\u6b21\u514b\u65f6\u95f4", "IRKT",
"\u4f0a\u5c14\u5e93\u6b21\u514b\u590f\u4ee4\u65f6", "IRKST",
"\u4F0A\u5C14\u5E93\u6B21\u514B\u65F6\u95F4", "IRKT"};
String IRT[] = new String[] {"\u4f0a\u6717\u6807\u51c6\u65f6\u95f4", "IRST",
"\u4f0a\u6717\u590f\u4ee4\u65f6", "IRDT",
"\u4F0A\u6717\u65F6\u95F4", "IRT"};
String ISRAEL[] = new String[] {"\u4ee5\u8272\u5217\u6807\u51c6\u65f6\u95f4", "IST",
"\u4ee5\u8272\u5217\u590f\u4ee4\u65f6", "IDT",
"\u4EE5\u8272\u5217\u65F6\u95F4", "IT"};
String IST[] = new String[] {"\u5370\u5ea6\u6807\u51c6\u65f6\u95f4", "IST",
"\u5370\u5ea6\u590f\u4ee4\u65f6", "IDT",
"\u5370\u5EA6\u65F6\u95F4", "IT"};
String JST[] = new String[] {"\u65e5\u672c\u6807\u51c6\u65f6\u95f4", "JST",
"\u65e5\u672c\u590f\u4ee4\u65f6", "JDT",
"\u65E5\u672C\u65F6\u95F4", "JT"};
String KRAT[] = new String[] {"\u514b\u62c9\u65af\u8bfa\u4e9a\u5c14\u65af\u514b\u65f6\u95f4", "KRAT",
"\u514b\u62c9\u65af\u8bfa\u4e9a\u5c14\u65af\u514b\u590f\u4ee4\u65f6", "KRAST",
"\u514B\u62C9\u65AF\u8BFA\u4E9A\u5C14\u65AF\u514B\u65F6\u95F4", "KRAT"};
String KST[] = new String[] {"\u97e9\u56fd\u6807\u51c6\u65f6\u95f4", "KST",
"\u97e9\u56fd\u590f\u4ee4\u65f6", "KDT",
"\u97E9\u56FD\u65F6\u95F4", "KT"};
String LORD_HOWE[] = new String[] {"\u8c6a\u516c\u6807\u51c6\u65f6\u95f4", "LHST",
"\u8c6a\u516c\u590f\u4ee4\u65f6", "LHDT",
"\u8C6A\u516C\u65F6\u95F4", "LHT"};
String MHT[] = new String[] {"\u9a6c\u7ecd\u5c14\u7fa4\u5c9b\u65f6\u95f4", "MHT",
"\u9a6c\u7ecd\u5c14\u7fa4\u5c9b\u590f\u4ee4\u65f6", "MHST",
"\u9A6C\u7ECD\u5C14\u7FA4\u5C9B\u65F6\u95F4", "MHT"};
String MMT[] = new String[] {"\u7f05\u7538\u65f6\u95f4", "MMT",
"\u7f05\u7538\u590f\u4ee4\u65f6", "MMST",
"\u7F05\u7538\u65F6\u95F4", "MMT"};
String MSK[] = new String[] {"\u83ab\u65af\u79d1\u6807\u51c6\u65f6\u95f4", "MSK",
"\u83ab\u65af\u79d1\u590f\u4ee4\u65f6", "MSD",
"\u83AB\u65AF\u79D1\u65F6\u95F4", "MT"};
String MST[] = new String[] {"Mountain \u6807\u51c6\u65f6\u95f4", "MST",
"Mountain \u590f\u4ee4\u65f6", "MDT",
"\u5C71\u5730\u65F6\u95F4", "MT"};
String MYT[] = new String[] {"\u9a6c\u6765\u897f\u4e9a\u65f6\u95f4", "MYT",
"\u9a6c\u6765\u897f\u4e9a\u590f\u4ee4\u65f6", "MYST",
"\u9A6C\u6765\u897F\u4E9A\u65F6\u95F4", "MYT"};
String NORONHA[] = new String[] {"\u8d39\u5c14\u5357\u591a\u5fb7\u8bfa\u7f57\u5c3c\u4e9a\u65f6\u95f4", "FNT",
"\u8d39\u5c14\u5357\u591a\u5fb7\u8bfa\u7f57\u5c3c\u4e9a\u590f\u4ee4\u65f6", "FNST",
"\u8D39\u5C14\u5357\u591A\u5FB7\u8BFA\u7F57\u5C3C\u4E9A\u65F6\u95F4", "FNT"};
String NOVT[] = new String[] {"Novosibirsk \u65f6\u95f4", "NOVT",
"Novosibirsk \u590f\u4ee4\u65f6", "NOVST",
"Novosibirsk \u65F6\u95F4", "NOVT"};
String NPT[] = new String[] {"\u5c3c\u6cca\u5c14\u65f6\u95f4", "NPT",
"\u5c3c\u6cca\u5c14\u590f\u4ee4\u65f6", "NPST",
"\u5C3C\u6CCA\u5C14\u65F6\u95F4", "NPT"};
String NST[] = new String[] {"\u7ebd\u82ac\u5170\u6807\u51c6\u65f6\u95f4", "NST",
"\u7ebd\u82ac\u5170\u590f\u4ee4\u65f6", "NDT",
"\u7EBD\u82AC\u5170\u65F6\u95F4", "NT"};
String NZST[] = new String[] {"\u65b0\u897f\u5170\u6807\u51c6\u65f6\u95f4", "NZST",
"\u65b0\u897f\u5170\u590f\u4ee4\u65f6", "NZDT",
"\u65B0\u897F\u5170\u65F6\u95F4", "NZT"};
String PITCAIRN[] = new String[] {"\u76ae\u7279\u5eb7\u5c9b\u6807\u51c6\u65f6\u95f4", "PST",
"\u76ae\u7279\u5eb7\u5c9b\u590f\u4ee4\u65f6", "PDT",
"\u76AE\u7279\u51EF\u6069\u65F6\u95F4", "PT"};
String PKT[] = new String[] {"\u5df4\u57fa\u65af\u5766\u65f6\u95f4", "PKT",
"\u5df4\u57fa\u65af\u5766\u590f\u4ee4\u65f6", "PKST",
"\u5DF4\u57FA\u65AF\u5766\u65F6\u95F4", "PKT"};
String PONT[] = new String[] {"\u6CE2\u7EB3\u4F69\u65F6\u95F4", "PONT",
"\u6CE2\u7EB3\u4F69\u590F\u4EE4\u65F6", "PONST",
"\u6CE2\u7EB3\u4F69\u65F6\u95F4", "PONT"};
String PST[] = new String[] {"\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4", "PST",
"\u592a\u5e73\u6d0b\u590f\u4ee4\u65f6", "PDT",
"\u592A\u5E73\u6D0B\u65F6\u95F4", "PT"};
String SAST[] = new String[] {"\u5357\u975e\u6807\u51c6\u65f6\u95f4", "SAST",
"\u5357\u975e\u590f\u4ee4\u65f6", "SAST",
"\u5357\u975E\u65F6\u95F4", "SAT"};
String SBT[] = new String[] {"\u6240\u7f57\u95e8\u7fa4\u5c9b\u65f6\u95f4", "SBT",
"\u6240\u7f57\u95e8\u7fa4\u5c9b\u590f\u4ee4\u65f6", "SBST",
"\u6240\u7F57\u95E8\u7FA4\u5C9B\u65F6\u95F4", "SBT"};
String SGT[] = new String[] {"\u65b0\u52a0\u5761\u65f6\u95f4", "SGT",
"\u65b0\u52a0\u5761\u590f\u4ee4\u65f6", "SGST",
"\u65B0\u52A0\u5761\u65F6\u95F4", "SGT"};
String TASMANIA[] = new String[] {"\u4E1C\u90E8\u6807\u51C6\u65F6\u95F4 (\u5854\u65AF\u9A6C\u5C3C\u4E9A)", "AEST",
"\u4E1C\u90E8\u590F\u4EE4\u65F6 (\u5854\u65AF\u9A6C\u5C3C\u4E9A)", "AEDT",
"\u4E1C\u90E8\u65F6\u95F4 (\u5854\u65AF\u9A6C\u5C3C\u4E9A)", "AET"};
String TMT[] = new String[] {"\u571f\u5e93\u66fc\u65f6\u95f4", "TMT",
"\u571f\u5e93\u66fc\u590f\u4ee4\u65f6", "TMST",
"\u571F\u5E93\u66FC\u65F6\u95F4", "TMT"};
String ULAT[]= new String[] {"\u5e93\u4f26\u65f6\u95f4", "ULAT",
"\u5e93\u4f26\u590f\u4ee4\u65f6", "ULAST",
"\u5E93\u4F26\u65F6\u95F4", "ULAT"};
String WAT[] = new String[] {"\u897f\u975e\u65f6\u95f4", "WAT",
"\u897f\u975e\u590f\u4ee4\u65f6", "WAST",
"\u897F\u975E\u65F6\u95F4", "WAT"};
String WET[] = new String[] {"\u897f\u6b27\u65f6\u95f4", "WET",
"\u897f\u6b27\u590f\u4ee4\u65f6", "WEST",
"\u897F\u6B27\u65F6\u95F4", "WET"};
String WGT[] = new String[] {"\u897f\u683c\u6797\u5170\u5c9b\u65f6\u95f4", "WGT",
"\u897f\u683c\u6797\u5170\u5c9b\u590f\u4ee4\u65f6", "WGST",
"\u897F\u683C\u6797\u5170\u5C9B\u65F6\u95F4", "WGT"};
String WIT[] = new String[] {"\u897f\u5370\u5ea6\u5c3c\u897f\u4e9a\u65f6\u95f4", "WIB",
"\u897f\u5370\u5ea6\u5c3c\u897f\u4e9a\u590f\u4ee4\u65f6", "WIST",
"\u897F\u5370\u5EA6\u5C3C\u897F\u4E9A\u65F6\u95F4", "WIB"};
String WST_AUS[] = new String[] {"\u897F\u90E8\u6807\u51C6\u65F6\u95F4 (\u6FB3\u5927\u5229\u4E9A)", "AWST",
"\u897F\u90E8\u590F\u4EE4\u65F6 (\u6FB3\u5927\u5229\u4E9A)", "AWDT",
"\u897F\u90E8\u65F6\u95F4 (\u6FB3\u5927\u5229\u4E9A)", "AWT"};
String SAMOA[] = new String[] {"\u8428\u6469\u4e9a\u7fa4\u5c9b\u6807\u51c6\u65f6\u95f4", "SST",
"\u8428\u6469\u4e9a\u7fa4\u5c9b\u590f\u4ee4\u65f6", "SDT",
"\u8428\u6469\u4E9A\u65F6\u95F4", "ST"};
String WST_SAMOA[] = new String[] {"\u897f\u8428\u6469\u4e9a\u65f6\u95f4", "WSST",
"\u897f\u8428\u6469\u4e9a\u590f\u4ee4\u65f6", "WSDT",
"\u897F\u8428\u6469\u4E9A\u65F6\u95F4", "WST"};
String ChST[] = new String[] {"Chamorro \u6807\u51c6\u65f6\u95f4", "ChST",
"Chamorro \u590f\u4ee4\u65f6", "ChDT",
"\u67E5\u6469\u6D1B\u65F6\u95F4", "ChT"};
String VICTORIA[] = new String[] {"\u4E1C\u90E8\u6807\u51C6\u65F6\u95F4 (\u7EF4\u591A\u5229\u4E9A)", "AEST",
"\u4E1C\u90E8\u590F\u4EE4\u65F6 (\u7EF4\u591A\u5229\u4E9A)", "AEDT",
"\u4E1C\u90E8\u65F6\u95F4 (\u7EF4\u591A\u5229\u4E9A)", "AET"};
String UTC[] = new String[] {"\u534f\u8c03\u4e16\u754c\u65f6\u95f4", "UTC",
"\u534f\u8c03\u4e16\u754c\u65f6\u95f4", "UTC",
"\u534F\u8C03\u4E16\u754C\u65F6\u95F4", "UTC"};
String UZT[] = new String[] {"\u4e4c\u5179\u522b\u514b\u65af\u5766\u65f6\u95f4", "UZT",
"\u4e4c\u5179\u522b\u514b\u65af\u5766\u590f\u4ee4\u65f6", "UZST",
"\u4E4C\u5179\u522B\u514B\u65AF\u5766\u65F6\u95F4", "UZT"};
String XJT[] = new String[] {"\u4e2d\u56fd\u6807\u51c6\u65f6\u95f4", "XJT",
"\u4e2d\u56fd\u590f\u4ee4\u65f6", "XJDT",
"\u4E2D\u56FD\u65F6\u95F4", "XJT"};
String YAKT[] = new String[] {"\u4e9a\u5e93\u6b21\u514b\u65f6\u95f4", "YAKT",
"\u4e9a\u5e93\u6b21\u514b\u590f\u4ee4\u65f6", "YAKST",
"\u4E9A\u5E93\u6B21\u514B\u65F6\u95F4", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", CAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", CAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", new String[] {"Central African Time", "CAT",
"Western African Time", "WAT",
"Central African Time", "CAT"}},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"\u5df4\u62c9\u572d\u65f6\u95f4", "PYT",
"\u5df4\u62c9\u572d\u590f\u4ee4\u65f6", "PYST",
"\u5DF4\u62C9\u572D\u65F6\u95F4", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"\u54e5\u4f26\u6bd4\u4e9a\u65f6\u95f4", "COT",
"\u54e5\u4f26\u6bd4\u4e9a\u590f\u4ee4\u65f6", "COST",
"\u54E5\u4F26\u6BD4\u4E9A\u65F6\u95F4", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"\u59d4\u5185\u745e\u62c9\u65f6\u95f4", "VET",
"\u59d4\u5185\u745e\u62c9\u590f\u4ee4\u65f6", "VEST",
"\u59D4\u5185\u745E\u62C9\u65F6\u95F4", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"\u6cd5\u5c5e\u572d\u4e9a\u90a3\u65f6\u95f4", "GFT",
"\u6cd5\u5c5e\u572d\u4e9a\u90a3\u590f\u4ee4\u65f6", "GFST",
"\u6CD5\u5C5E\u572D\u4E9A\u90A3\u65F6\u95F4", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", CST},
{"America/Ciudad_Juarez", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", MST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", WGT},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", EST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"\u5384\u74dc\u591a\u5c14\u65f6\u95f4", "ECT",
"\u5384\u74dc\u591a\u5c14\u590f\u4ee4\u65f6", "ECST",
"\u5384\u74DC\u591A\u5C14\u65F6\u95F4", "ECT"}},
{"America/Guyana", new String[] {"\u572d\u4e9a\u90a3\u65f6\u95f4", "GYT",
"\u572d\u4e9a\u90a3\u590f\u4ee4\u65f6", "GYST",
"\u572D\u4E9A\u90A3\u65F6\u95F4", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"\u73bb\u5229\u7ef4\u4e9a\u65f6\u95f4", "BOT",
"\u73bb\u5229\u7ef4\u4e9a\u590f\u4ee4\u65f6", "BOST",
"\u73BB\u5229\u7EF4\u4E9A\u65F6\u95F4", "BOT"}},
{"America/Lima", new String[] {"\u79d8\u9c81\u65f6\u95f4", "PET",
"\u79d8\u9c81\u590f\u4ee4\u65f6", "PEST",
"\u79D8\u9C81\u65F6\u95F4", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"\u76ae\u57c3\u5c14\u5c9b\u53ca\u5bc6\u514b\u9686\u5c9b\u6807\u51c6\u65f6\u95f4", "PMST",
"\u76ae\u57c3\u5c14\u5c9b\u53ca\u5bc6\u514b\u9686\u5c9b\u590f\u4ee4\u65f6", "PMDT",
"\u76AE\u57C3\u5C14\u548C\u5BC6\u514B\u9686\u5C9B\u65F6\u95F4", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"\u4e4c\u62c9\u572d\u65f6\u95f4", "UYT",
"\u4e4c\u62c9\u572d\u590f\u4ee4\u65f6", "UYST",
"\u4E4C\u62C9\u572D\u65F6\u95F4", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Nuuk", WGT},
{"America/Ojinaga", CST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"\u82cf\u5229\u5357\u65f6\u95f4", "SRT",
"\u82cf\u5229\u5357\u590f\u4ee4\u65f6", "SRST",
"\u82CF\u5229\u5357\u65F6\u95F4", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", MST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"\u6234\u7ef4\u65af\u65f6\u95f4", "DAVT",
"\u6234\u7ef4\u65af\u590f\u4ee4\u65f6", "DAVST",
"\u6234\u7EF4\u65AF\u65F6\u95F4", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"Dumont-d'Urville \u65f6\u95f4", "DDUT",
"Dumont-d'Urville \u590f\u4ee4\u65f6", "DDUST",
"Dumont-d'Urville \u65F6\u95F4", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"Australian Eastern Standard Time (Macquarie)", "AEST",
"Australian Eastern Daylight Time (Macquarie)", "AEDT",
"Australian Eastern Time (Macquarie)", "AET"}},
{"Antarctica/Mawson", new String[] {"\u83ab\u68ee\u65f6\u95f4", "MAWT",
"\u83ab\u68ee\u590f\u4ee4\u65f6", "MAWST",
"\u83AB\u68EE\u65F6\u95F4", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"\u7f57\u745f\u62c9\u65f6\u95f4", "ROTT",
"\u7f57\u745f\u62c9\u590f\u4ee4\u65f6", "ROTST",
"\u7F57\u745F\u62C9\u65F6\u95F4", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"Syowa \u65f6\u95f4", "SYOT",
"Syowa \u590f\u4ee4\u65f6", "SYOST",
"Syowa \u65F6\u95F4", "SYOT"}},
{"Antarctica/Troll", new String[] {"\u534f\u8c03\u4e16\u754c\u65f6\u95f4", "UTC",
"\u4e2d\u6b27\u590f\u4ee4\u65f6", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"\u83ab\u65af\u6258\u514b\u65f6\u95f4", "VOST",
"\u83ab\u65af\u6258\u514b\u590f\u4ee4\u65f6", "VOSST",
"\u83AB\u65AF\u6258\u514B\u65F6\u95F4", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"Alma-Ata \u65f6\u95f4", "ALMT",
"Alma-Ata \u590f\u4ee4\u65f6", "ALMST",
"Alma-Ata \u65F6\u95F4", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"\u963f\u90a3\u5e95\u6cb3\u65f6\u95f4", "ANAT",
"\u963f\u90a3\u5e95\u6cb3\u590f\u4ee4\u65f6", "ANAST",
"\u963F\u90A3\u5E95\u6CB3\u65F6\u95F4", "ANAT"}},
{"Asia/Aqtau", new String[] {"Aqtau \u65f6\u95f4", "AQTT",
"Aqtau \u590f\u4ee4\u65f6", "AQTST",
"Aqtau \u65F6\u95F4", "AQTT"}},
{"Asia/Aqtobe", new String[] {"Aqtobe \u65f6\u95f4", "AQTT",
"Aqtobe \u590f\u4ee4\u65f6", "AQTST",
"Aqtobe \u65F6\u95F4", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"\u4e9a\u585e\u62dc\u7136\u65f6\u95f4", "AZT",
"\u4e9a\u585e\u62dc\u7136\u590f\u4ee4\u65f6", "AZST",
"\u4E9A\u585E\u62DC\u7136\u65F6\u95F4", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"\u5409\u5c14\u5409\u65af\u65af\u5766\u65f6\u95f4", "KGT",
"\u5409\u5c14\u5409\u65af\u65af\u5766\u590f\u4ee4\u65f6", "KGST",
"\u5409\u5C14\u5409\u65AF\u65AF\u5766\u65F6\u95F4", "KGT"}},
{"Asia/Brunei", new String[] {"\u6587\u83b1\u65f6\u95f4", "BNT",
"\u6587\u83b1\u590f\u4ee4\u65f6", "BNST",
"\u6587\u83B1\u65F6\u95F4", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"Choibalsan \u65f6\u95f4", "CHOT",
"Choibalsan \u590f\u4ee4\u65f6", "CHOST",
"Choibalsan \u65F6\u95F4", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"\u4e1c\u5e1d\u6c76\u65f6\u95f4", "TLT",
"\u4e1c\u5e1d\u6c76\u590f\u4ee4\u65f6", "TLST",
"\u4E1C\u5E1D\u6C76\u65F6\u95F4", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"\u5854\u5409\u514b\u65af\u5766\u65f6\u95f4", "TJT",
"\u5854\u5409\u514b\u65af\u5766\u590f\u4ee4\u65f6", "TJST",
"\u5854\u5409\u514B\u65AF\u5766\u65F6\u95F4", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"\u79d1\u5e03\u591a\u65f6\u95f4", "HOVT",
"\u79d1\u5e03\u591a\u590f\u4ee4\u65f6", "HOVST",
"\u79D1\u5E03\u591A\u65F6\u95F4", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"\u4e1c\u5370\u5ea6\u5c3c\u897f\u4e9a\u65f6\u95f4", "WIT",
"\u4e1c\u5370\u5ea6\u5c3c\u897f\u4e9a\u590f\u4ee4\u65f6", "EIST",
"\u4E1C\u5370\u5EA6\u5C3C\u897F\u4E9A\u65F6\u95F4", "WIT"}},
{"Asia/Kabul", new String[] {"\u963f\u5bcc\u6c57\u65f6\u95f4", "AFT",
"\u963f\u5bcc\u6c57\u590f\u4ee4\u65f6", "AFST",
"\u963F\u5BCC\u6C57\u65F6\u95F4", "AFT"}},
{"Asia/Kamchatka", new String[] {"\u5f7c\u5f97\u7f57\u5df4\u752b\u6d1b\u592b\u65af\u514b\u65f6\u95f4", "PETT",
"\u5f7c\u5f97\u7f57\u5df4\u752b\u6d1b\u592b\u65af\u514b\u590f\u4ee4\u65f6", "PETST",
"\u5F7C\u5F97\u7F57\u5DF4\u752B\u6D1B\u592B\u65AF\u514B\u65F6\u95F4", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"Magadan \u65f6\u95f4", "MAGT",
"Magadan \u590f\u4ee4\u65f6", "MAGST",
"Magadan \u65F6\u95F4", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"Philippines Standard Time", "PST",
"Philippines Daylight Time", "PDT",
"Philippines Time", "PT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"Oral \u65f6\u95f4", "ORAT",
"Oral \u590f\u4ee4\u65f6", "ORAST",
"Oral \u65F6\u95F4", "ORAT"}},
{"Asia/Omsk", new String[] {"\u9102\u6728\u65af\u514b\u65f6\u95f4", "OMST",
"\u9102\u6728\u65af\u514b\u590f\u4ee4\u65f6", "OMSST",
"\u9102\u6728\u65AF\u514B\u65F6\u95F4", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"Qyzylorda \u65f6\u95f4", "QYZT",
"Qyzylorda \u590f\u4ee4\u65f6", "QYZST",
"Qyzylorda \u65F6\u95F4", "QYZT"}},
{"Asia/Rangoon", MMT},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"\u5e93\u9875\u5c9b\u65f6\u95f4", "SAKT",
"\u5e93\u9875\u5c9b\u590f\u4ee4\u65f6", "SAKST",
"\u5E93\u9875\u5C9B\u65F6\u95F4", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", CTT},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"\u4e54\u6cbb\u4e9a\u65f6\u95f4", "GET",
"\u4e54\u6cbb\u4e9a\u590f\u4ee4\u65f6", "GEST",
"\u4E54\u6CBB\u4E9A\u65F6\u95F4", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"\u4E4C\u65AF\u5B63\u6D85\u62C9\u65F6\u95F4", "VLAT",
"\u4E4C\u65AF\u5B63\u6D85\u62C9\u590F\u4EE4\u65F6", "VLAST",
"\u4E4C\u65AF\u5B63\u6D85\u62C9\u65F6\u95F4", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"\u6d77\u53c2\u5d34\u65f6\u95f4", "VLAT",
"\u6d77\u53c2\u5d34\u590f\u4ee4\u65f6", "VLAST",
"\u6D77\u53C2\u5D34\u65F6\u95F4", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yangon", MMT},
{"Asia/Yekaterinburg", new String[] {"Yekaterinburg \u65f6\u95f4", "YEKT",
"Yekaterinburg \u590f\u4ee4\u65f6", "YEKST",
"Yekaterinburg \u65F6\u95F4", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"\u4e9a\u901f\u5c14\u7fa4\u5c9b\u65f6\u95f4", "AZOT",
"\u4e9a\u901f\u5c14\u7fa4\u5c9b\u590f\u4ee4\u65f6", "AZOST",
"\u4E9A\u901F\u5C14\u7FA4\u5C9B\u65F6\u95F4", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"\u4f5b\u5fb7\u89d2\u65f6\u95f4", "CVT",
"\u4f5b\u5fb7\u89d2\u590f\u4ee4\u65f6", "CVST",
"\u4F5B\u5FB7\u89D2\u65F6\u95F4", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"\u5357\u4e54\u6cbb\u4e9a\u6807\u51c6\u65f6\u95f4", "GST",
"\u5357\u4e54\u6cbb\u4e9a\u590f\u4ee4\u65f6", "GDT",
"\u5357\u4E54\u6CBB\u4E9A\u5C9B\u65F6\u95F4", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"\u798f\u514b\u5170\u7fa4\u5c9b\u65f6\u95f4", "FKT",
"\u798f\u514b\u5170\u7fa4\u5c9b\u590f\u4ee4\u65f6", "FKST",
"\u798F\u514B\u5170\u7FA4\u5C9B\u65F6\u95F4", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"\u4E2D\u897F\u90E8\u6807\u51C6\u65F6\u95F4 (\u6FB3\u5927\u5229\u4E9A)", "ACWST",
"\u4E2D\u897F\u90E8\u590F\u4EE4\u65F6 (\u6FB3\u5927\u5229\u4E9A)", "ACWDT",
"\u4E2D\u897F\u90E8\u65F6\u95F4 (\u6FB3\u5927\u5229\u4E9A)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", MST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"\u6c99\u9a6c\u62c9\u65f6\u95f4", "SAMT",
"\u6c99\u9a6c\u62c9\u590f\u4ee4\u65f6", "SAMST",
"\u6C99\u9A6C\u62C9\u65F6\u95F4", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"\u5370\u5ea6\u6d0b\u5730\u5e26\u65f6\u95f4", "IOT",
"\u5370\u5ea6\u6d0b\u5730\u5e26\u590f\u4ee4\u65f6", "IOST",
"\u5370\u5EA6\u6D0B\u5730\u5E26\u65F6\u95F4", "IOT"}},
{"Indian/Christmas", new String[] {"\u5723\u8bde\u5c9b\u65f6\u95f4", "CXT",
"\u5723\u8bde\u5c9b\u590f\u4ee4\u65f6", "CXST",
"\u5723\u8BDE\u5C9B\u65F6\u95F4", "CIT"}},
{"Indian/Cocos", new String[] {"\u53ef\u53ef\u65af\u7fa4\u5c9b\u65f6\u95f4", "CCT",
"\u53ef\u53ef\u65af\u7fa4\u5c9b\u590f\u4ee4\u65f6", "CCST",
"\u53EF\u53EF\u65AF\u7FA4\u5C9B\u65F6\u95F4", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"\u6cd5\u5c5e\u5357\u6781\u65f6\u95f4", "TFT",
"\u6cd5\u5c5e\u5357\u6781\u590f\u4ee4\u65f6", "TFST",
"\u6CD5\u5C5E\u5357\u6781\u65F6\u95F4", "TFT"}},
{"Indian/Mahe", new String[] {"\u585e\u5e2d\u5c14\u7fa4\u5c9b\u65f6\u95f4", "SCT",
"\u585e\u5e2d\u5c14\u7fa4\u5c9b\u590f\u4ee4\u65f6", "SCST",
"\u585E\u5E2D\u5C14\u7FA4\u5C9B\u65F6\u95F4", "SCT"}},
{"Indian/Maldives", new String[] {"\u9a6c\u5c14\u4ee3\u592b\u65f6\u95f4", "MVT",
"\u9a6c\u5c14\u4ee3\u592b\u590f\u4ee4\u65f6", "MVST",
"\u9A6C\u5C14\u4EE3\u592B\u65F6\u95F4", "MVT"}},
{"Indian/Mauritius", new String[] {"\u6469\u91cc\u897f\u65af\u65f6\u95f4", "MUT",
"\u6469\u91cc\u897f\u65af\u590f\u4ee4\u65f6", "MUST",
"\u6469\u91CC\u897F\u65AF\u65F6\u95F4", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"\u7559\u5c3c\u65fa\u5c9b\u65f6\u95f4", "RET",
"\u7559\u5c3c\u65fa\u5c9b\u590f\u4ee4\u65f6", "REST",
"\u7559\u5C3C\u65FA\u5C9B\u65F6\u95F4", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"\u4e2d\u6b27\u65f6\u95f4", "MET",
"\u4e2d\u6b27\u590f\u4ee4\u65f6", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", CHUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"\u74e6\u5974\u963f\u56fe\u65f6\u95f4", "VUT",
"\u74e6\u5974\u963f\u56fe\u590f\u4ee4\u65f6", "VUST",
"\u74E6\u5974\u963F\u56FE\u65F6\u95F4", "VUT"}},
{"Pacific/Enderbury", new String[] {"\u83f2\u5c3c\u514b\u65af\u7fa4\u5c9b\u65f6\u95f4", "PHOT",
"\u83f2\u5c3c\u514b\u65af\u7fa4\u5c9b\u590f\u4ee4\u65f6", "PHOST",
"\u83F2\u5C3C\u514B\u65AF\u7FA4\u5C9B\u65F6\u95F4", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"\u6258\u514b\u52b3\u7fa4\u5c9b\u65f6\u95f4", "TKT",
"\u6258\u514b\u52b3\u7fa4\u5c9b\u590f\u4ee4\u65f6", "TKST",
"\u6258\u514B\u52B3\u7FA4\u5C9B\u65F6\u95F4", "TKT"}},
{"Pacific/Fiji", new String[] {"\u6590\u6d4e\u65f6\u95f4", "FJT",
"\u6590\u6d4e\u590f\u4ee4\u65f6", "FJST",
"\u6590\u6D4E\u65F6\u95F4", "FJT"}},
{"Pacific/Funafuti", new String[] {"\u5410\u9c81\u74e6\u65f6\u95f4", "TVT",
"\u5410\u9c81\u74e6\u590f\u4ee4\u65f6", "TVST",
"\u5410\u9C81\u74E6\u65F6\u95F4", "TVT"}},
{"Pacific/Galapagos", new String[] {"\u52a0\u62c9\u5df4\u54e5\u65f6\u95f4", "GALT",
"\u52a0\u62c9\u5df4\u54e5\u590f\u4ee4\u65f6", "GALST",
"\u52A0\u62C9\u5DF4\u54E5\u65F6\u95F4", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"Line \u5c9b\u65f6\u95f4", "LINT",
"Line \u5c9b\u590f\u4ee4\u65f6", "LINST",
"Line \u5C9B\u65F6\u95F4", "LINT"}},
{"Pacific/Kosrae", new String[] {"Kosrae \u65f6\u95f4", "KOST",
"Kosrae \u590f\u4ee4\u65f6", "KOSST",
"Kosrae \u65F6\u95F4", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"\u9a6c\u514b\u8428\u65af\u65f6\u95f4", "MART",
"\u9a6c\u514b\u8428\u65af\u590f\u4ee4\u65f6", "MARST",
"\u9A6C\u514B\u8428\u65AF\u65F6\u95F4", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"\u8bfa\u9c81\u65f6\u95f4", "NRT",
"\u8bfa\u9c81\u590f\u4ee4\u65f6", "NRST",
"\u8BFA\u9C81\u65F6\u95F4", "NRT"}},
{"Pacific/Niue", new String[] {"\u7ebd\u5a01\u5c9b\u65f6\u95f4", "NUT",
"\u7ebd\u5a01\u5c9b\u590f\u4ee4\u65f6", "NUST",
"\u7EBD\u5A01\u5C9B\u65F6\u95F4", "NUT"}},
{"Pacific/Norfolk", new String[] {"\u8bfa\u798f\u514b\u65f6\u95f4", "NFT",
"\u8bfa\u798f\u514b\u590f\u4ee4\u65f6", "NFST",
"\u8BFA\u798F\u514B\u65F6\u95F4", "NFT"}},
{"Pacific/Noumea", new String[] {"\u65b0\u52a0\u52d2\u591a\u5c3c\u4e9a\u65f6\u95f4", "NCT",
"\u65b0\u52a0\u52d2\u591a\u5c3c\u4e9a\u590f\u4ee4\u65f6", "NCST",
"\u65B0\u52A0\u52D2\u591A\u5C3C\u4E9A\u65F6\u95F4", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"\u5e1b\u7409\u65f6\u95f4", "PWT",
"\u5e1b\u7409\u590f\u4ee4\u65f6", "PWST",
"\u5E1B\u7409\u65F6\u95F4", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"\u5df4\u5e03\u4e9a\u65b0\u51e0\u5185\u4e9a\u65f6\u95f4", "PGT",
"\u5df4\u5e03\u4e9a\u65b0\u51e0\u5185\u4e9a\u590f\u4ee4\u65f6", "PGST",
"\u5DF4\u5E03\u4E9A\u65B0\u51E0\u5185\u4E9A\u65F6\u95F4", "PGT"}},
{"Pacific/Rarotonga", new String[] {"\u5e93\u514b\u7fa4\u5c9b\u65f6\u95f4", "CKT",
"\u5e93\u514b\u7fa4\u5c9b\u590f\u4ee4\u65f6", "CKHST",
"\u5E93\u514B\u7FA4\u5C9B\u65F6\u95F4", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"\u5927\u6eaa\u5730\u5c9b\u65f6\u95f4", "TAHT",
"\u5927\u6eaa\u5730\u5c9b\u590f\u4ee4\u65f6", "TAHST",
"\u5927\u6EAA\u5730\u5C9B\u65F6\u95F4", "TAHT"}},
{"Pacific/Tarawa", new String[] {"\u5409\u4f2f\u7279\u7fa4\u5c9b\u65f6\u95f4", "GILT",
"\u5409\u4f2f\u7279\u7fa4\u5c9b\u590f\u4ee4\u65f6", "GILST",
"\u5409\u4F2F\u7279\u7FA4\u5C9B\u65F6\u95F4", "GILT"}},
{"Pacific/Tongatapu", new String[] {"\u4e1c\u52a0\u65f6\u95f4", "TOT",
"\u4e1c\u52a0\u590f\u4ee4\u65f6", "TOST",
"\u4E1C\u52A0\u65F6\u95F4", "TOT"}},
{"Pacific/Truk", CHUT},
{"Pacific/Wake", new String[] {"\u5a01\u514b\u65f6\u95f4", "WAKT",
"\u5a01\u514b\u590f\u4ee4\u65f6", "WAKST",
"\u5A01\u514B\u65F6\u95F4", "WAKT"}},
{"Pacific/Wallis", new String[] {"\u74e6\u5229\u65af\u53ca\u798f\u675c\u7eb3\u7fa4\u5c9b\u65f6\u95f4", "WFT",
"\u74e6\u5229\u65af\u53ca\u798f\u675c\u7eb3\u7fa4\u5c9b\u590f\u4ee4\u65f6", "WFST",
"\u74E6\u5229\u65AF\u53CA\u798F\u675C\u7EB3\u7FA4\u5C9B\u65F6\u95F4", "WFT"}},
{"Pacific/Yap", CHUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_CN.java |
180,176 | /*
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.pt;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_pt_BR extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"Fuso hor\u00e1rio do Acre", "ACT",
"Fuso hor\u00e1rio de ver\u00e3o do Acre", "ACST",
"Fuso hor\u00e1rio do Acre", "ACT"};
String ADELAIDE[] = new String[] {"Hor\u00E1rio-Padr\u00E3o Central (Austr\u00E1lia do Sul)", "ACST",
"Fuso Hor\u00E1rio de Ver\u00E3o Central (Austr\u00E1lia do Sul)", "ACDT",
"Hor\u00E1rio Central (Austr\u00E1lia do Sul)", "ACT"};
String AGT[] = new String[] {"Fuso hor\u00e1rio da Argentina", "ART",
"Fuso hor\u00e1rio de ver\u00e3o da Argentina", "ARST",
"Hor\u00E1rio da Argentina", "ART"};
String AKST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do Alaska", "AKST",
"Hor\u00e1rio de luz natural do Alaska", "AKDT",
"Hor\u00E1rio do Alasca", "AKT"};
String AMT[] = new String[] {"Fuso hor\u00e1rio do Amazonas", "AMT",
"Fuso hor\u00e1rio de ver\u00e3o do Amazonas", "AMST",
"Hor\u00E1rio do Amazonas", "AMT"};
String ARAST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da Ar\u00e1bia", "AST",
"Hor\u00e1rio de luz natural da Ar\u00e1bia", "ADT",
"Hor\u00E1rio da Ar\u00E1bia", "AT"};
String ARMT[] = new String[] {"Fuso hor\u00e1rio da Arm\u00eania", "AMT",
"Fuso hor\u00e1rio de ver\u00e3o da Arm\u00eania", "AMST",
"Hor\u00E1rio da Arm\u00EAnia", "AMT"};
String AST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do Atl\u00e2ntico", "AST",
"Hor\u00e1rio de luz natural do Atl\u00e2ntico", "ADT",
"Hor\u00E1rio do Atl\u00E2ntico", "AT"};
String BDT[] = new String[] {"Fuso hor\u00e1rio de Bangladesh", "BDT",
"Fuso hor\u00e1rio de ver\u00e3o de Bangladesh", "BDST",
"Hor\u00E1rio de Bangladesh", "BDT"};
String BRISBANE[] = new String[] {"Hor\u00E1rio-Padr\u00E3o do Leste (Queensland)", "AEST",
"Fuso Hor\u00E1rio de Ver\u00E3o Oriental (Queensland)", "AEDT",
"Hor\u00E1rio do Leste (Queensland)", "AET"};
String BROKEN_HILL[] = new String[] {"Hor\u00E1rio-Padr\u00E3o Central (Austr\u00E1lia do Sul/Nova Gales do Sul)", "ACST",
"Fuso Hor\u00E1rio de Ver\u00E3o Central (Austr\u00E1lia do Sul/Nova Gales do Sul)", "ACDT",
"Hor\u00E1rio Central (Austr\u00E1lia do Sul/Nova Gales do Sul)", "ACT"};
String BRT[] = new String[] {"Fuso hor\u00e1rio de Bras\u00edlia", "BRT",
"Fuso hor\u00e1rio de ver\u00e3o de Bras\u00edlia", "BRST",
"Hor\u00E1rio de Bras\u00EDlia", "BRT"};
String BTT[] = new String[] {"Fuso hor\u00e1rio de But\u00e3o", "BTT",
"Fuso hor\u00e1rio de ver\u00e3o de But\u00e3o", "BTST",
"Hor\u00E1rio do But\u00E3o", "BTT"};
String CAT[] = new String[] {"Fuso hor\u00e1rio da \u00c1frica Central", "CAT",
"Fuso hor\u00e1rio de ver\u00e3o da \u00c1frica Central", "CAST",
"Hor\u00E1rio da \u00C1frica Central", "CAT"};
String CET[] = new String[] {"Fuso hor\u00e1rio da Europa Central", "CET",
"Fuso hor\u00e1rio de ver\u00e3o da Europa Central", "CEST",
"Hor\u00E1rio da Europa Central", "CET"};
String CHAST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Chatham", "CHAST",
"Hor\u00e1rio de luz natural de Chatham", "CHADT",
"Hor\u00E1rio de Chatham", "CHAT"};
String CIT[] = new String[] {"Fuso hor\u00e1rio da Indon\u00e9sia Central", "WITA",
"Fuso hor\u00e1rio de ver\u00e3o da Indon\u00e9sia Central", "CIST",
"Hor\u00E1rio da Indon\u00E9sia Central", "WITA"};
String CLT[] = new String[] {"Fuso hor\u00e1rio do Chile", "CLT",
"Fuso hor\u00e1rio de ver\u00e3o do Chile", "CLST",
"Hor\u00E1rio do Chile", "CLT"};
String CST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o central", "CST",
"Hor\u00e1rio de luz natural central", "CDT",
"Hor\u00E1rio Central", "CT"};
String CTT[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da China", "CST",
"Hor\u00e1rio de luz natural da China", "CDT",
"Hor\u00E1rio da China", "CT"};
String CUBA[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Cuba", "CST",
"Hor\u00e1rio de luz natural de Cuba", "CDT",
"Hor\u00E1rio de Cuba", "CT"};
String DARWIN[] = new String[] {"Hor\u00E1rio-Padr\u00E3o Central (Territ\u00F3rio do Norte)", "ACST",
"Fuso Hor\u00E1rio de Ver\u00E3o Central (Territ\u00F3rio do Norte)", "ACDT",
"Hor\u00E1rio Central (Territ\u00F3rio do Norte)", "ACT"};
String DUBLIN[] = new String[] {"Fuso hor\u00e1rio do meridiano de Greenwich", "GMT",
"Fuso hor\u00e1rio de ver\u00e3o da Irlanda", "IST",
"Hor\u00E1rio da Rep\u00FAblica da Irlanda", "IT"};
String EAT[] = new String[] {"Fuso hor\u00e1rio da \u00c1frica Oriental", "EAT",
"Fuso hor\u00e1rio padr\u00e3o da \u00c1frica Oriental", "EAST",
"Hor\u00E1rio do Leste da \u00C1frica", "EAT"};
String EASTER[] = new String[] {"Fuso hor\u00e1rio da Ilha de P\u00e1scoa", "EAST",
"Fuso hor\u00e1rio de ver\u00e3o da Ilha de P\u00e1scoa", "EASST",
"Hor\u00E1rio da Ilha de P\u00E1scoa", "EAST"};
String EET[] = new String[] {"Fuso hor\u00e1rio da Europa Oriental", "EET",
"Fuso hor\u00e1rio de ver\u00e3o da Europa Oriental", "EEST",
"Hor\u00e1rio da Europa Oriental", "EET"};
String EGT[] = new String[] {"Fuso hor\u00e1rio da Groenl\u00e2ndia Oriental", "EGT",
"Fuso hor\u00e1rio de ver\u00e3o da Groenl\u00e2ndia Oriental", "EGST",
"Hor\u00E1rio da Groenl\u00E2ndia Oriental", "EGT"};
String EST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o oriental", "EST",
"Hor\u00e1rio de luz natural oriental", "EDT",
"Hor\u00E1rio do Leste", "ET"};
String EST_NSW[] = new String[] {"Hor\u00E1rio-Padr\u00E3o Oriental (Nova Gales do Sul)", "AEST",
"Fuso Hor\u00E1rio de Ver\u00E3o Oriental (Nova Gales do Sul)", "AEDT",
"Hor\u00E1rio Oriental (Nova Gales do Sul)", "AET"};
String FET[] = new String[] {"Hor\u00E1rio do Extremo Leste Europeu (FET)", "FET",
"Fuso Hor\u00E1rio de Ver\u00E3o do Extremo Leste Europeu", "FEST",
"Hor\u00E1rio do Extremo Leste Europeu (FET)", "FET"};
String GHMT[] = new String[] {"Fuso hor\u00e1rio do meridiano de Gana", "GMT",
"Fuso hor\u00e1rio de ver\u00e3o de Gana", "GHST",
"Fuso Hor\u00E1rio do Meridiano de Gana", "GMT"};
String GAMBIER[] = new String[] {"Fuso hor\u00e1rio de Gambier", "GAMT",
"Fuso hor\u00e1rio de ver\u00e3o de Gambier", "GAMST",
"Hor\u00E1rio de Gambier", "GAMT"};
String GMT[] = new String[] {"Fuso hor\u00e1rio do meridiano de Greenwich", "GMT",
"Fuso hor\u00e1rio do meridiano de Greenwich", "GMT",
"Hor\u00E1rio M\u00E9dio de Greenwich", "GMT"};
String GMTBST[] = new String[] {"Fuso hor\u00e1rio do meridiano de Greenwich", "GMT",
"Fuso hor\u00e1rio de ver\u00e3o da Gr\u00e3-Bretanha", "BST",
"Hor\u00E1rio do Reino Unido", "BT"};
String GST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do golfo", "GST",
"Hor\u00e1rio de luz natural do golfo", "GDT",
"Hor\u00E1rio do Golfo", "GT"};
String HKT[] = new String[] {"Fuso hor\u00e1rio de Hong Kong", "HKT",
"Fuso hor\u00e1rio de ver\u00e3o de Hong Kong", "HKST",
"Hor\u00E1rio de Hong Kong", "HKT"};
String HST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do Hava\u00ed", "HST",
"Hor\u00e1rio de luz natural do Hava\u00ed", "HDT",
"Hor\u00E1rio do Hava\u00ED", "HT"};
String ICT[] = new String[] {"Fuso hor\u00e1rio da Indochina", "ICT",
"Fuso hor\u00e1rio de ver\u00e3o da Indochina", "ICST",
"Hor\u00E1rio da Indochina", "ICT"};
String IRKT[] = new String[] {"Fuso hor\u00e1rio de Irkutsk", "IRKT",
"Fuso hor\u00e1rio de ver\u00e3o de Irkutsk", "IRKST",
"Hor\u00E1rio de Irkutsk", "IRKT"};
String IRT[] = new String[] {"Fuso hor\u00e1rio do Ir\u00e3", "IRST",
"Hor\u00e1rio de luz natural do Ir\u00e3", "IRDT",
"Hor\u00E1rio do Ir\u00E3", "IRT"};
String ISRAEL[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Israel", "IST",
"Hor\u00e1rio de luz natural de Israel", "IDT",
"Hor\u00E1rio de Israel", "IT"};
String IST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da \u00cdndia", "IST",
"Hor\u00e1rio de luz natural da \u00cdndia", "IDT",
"Hor\u00E1rio da \u00CDndia", "IT"};
String JST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do Jap\u00e3o", "JST",
"Hor\u00e1rio de luz natural do Jap\u00e3o", "JDT",
"Hor\u00E1rio do Jap\u00E3o", "JT"};
String KRAT[] = new String[] {"Fuso hor\u00e1rio de Krasnoyarsk", "KRAT",
"Fuso hor\u00e1rio de ver\u00e3o de Krasnoyarsk", "KRAST",
"Hor\u00E1rio de Krasnoyarsk", "KRAT"};
String KST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da Coreia", "KST",
"Hor\u00e1rio de luz natural da Coreia", "KDT",
"Hor\u00E1rio da Coreia", "KT"};
String LORD_HOWE[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Lord Howe", "LHST",
"Fuso hor\u00e1rio de ver\u00e3o de Lord Howe", "LHDT",
"Hor\u00E1rio de Lord Howe", "LHT"};
String MHT[] = new String[] {"Fuso hor\u00e1rio das Ilhas Marshall", "MHT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Marshall", "MHST",
"Hor\u00E1rio das Ilhas Marshall", "MHT"};
String MSK[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Moscou", "MSK",
"Hor\u00e1rio de luz natural de Moscou", "MSD",
"Hor\u00E1rio de Moscou", "MT"};
String MMT[] = new String[] {"Fuso hor\u00e1rio de Mianmar", "MMT",
"Fuso hor\u00e1rio de ver\u00e3o de Mianmar", "MMST",
"Hor\u00E1rio de Mianmar", "MMT"};
String MST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o das montanhas", "MST",
"Hor\u00e1rio de luz natural das montanhas", "MDT",
"Hor\u00E1rio das Montanhas Rochosas", "MT"};
String MYT[] = new String[] {"Fuso hor\u00e1rio da Mal\u00e1sia", "MYT",
"Fuso hor\u00e1rio de ver\u00e3o da Mal\u00e1sia", "MYST",
"Hor\u00E1rio da Mal\u00E1sia", "MYT"};
String NORONHA[] = new String[] {"Fuso hor\u00e1rio de Fernando de Noronha", "FNT",
"Fuso hor\u00e1rio de ver\u00e3o de Fernando de Noronha", "FNST",
"Hor\u00E1rio de Fernando de Noronha", "FNT"};
String NOVT[] = new String[] {"Fuso hor\u00e1rio de Novosibirsk", "NOVT",
"Fuso hor\u00e1rio de ver\u00e3o de Novosibirsk", "NOVST",
"Hor\u00E1rio de Novosibirsk", "NOVT"};
String NPT[] = new String[] {"Fuso hor\u00e1rio do Nepal", "NPT",
"Fuso hor\u00e1rio de ver\u00e3o do Nepal", "NPST",
"Hor\u00E1rio do Nepal", "NPT"};
String NST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Terra Nova", "NST",
"Hor\u00e1rio de luz natural de Terra Nova", "NDT",
"Hor\u00E1rio de Terra Nova", "NT"};
String NZST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da Nova Zel\u00e2ndia", "NZST",
"Hor\u00e1rio de luz natural da Nova Zel\u00e2ndia", "NZDT",
"Hor\u00E1rio da Nova Zel\u00E2ndia", "NZT"};
String PITCAIRN[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Pitcairn", "PST",
"Hor\u00e1rio de luz natural de Pitcairn", "PDT",
"Hor\u00E1rio de Pitcairn", "PT"};
String PKT[] = new String[] {"Fuso hor\u00e1rio do Paquist\u00e3o", "PKT",
"Fuso hor\u00e1rio de ver\u00e3o do Paquist\u00e3o", "PKST",
"Hor\u00E1rio do Paquist\u00E3o", "PKT"};
String PONT[] = new String[] {"Fuso Hor\u00E1rio de Pohnpei", "PONT",
"Fuso Hor\u00E1rio de Ver\u00E3o de Pohnpei", "PONST",
"Hor\u00E1rio de Ponape", "PONT"};
String PST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o do Pac\u00edfico", "PST",
"Hor\u00e1rio de luz natural do Pac\u00edfico", "PDT",
"Hor\u00E1rio do Pac\u00EDfico", "PT"};
String SAST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da \u00c1frica do Sul", "SAST",
"Fuso hor\u00e1rio de ver\u00e3o da \u00c1frica do Sul", "SAST",
"Hor\u00E1rio da \u00C1frica do Sul", "SAT"};
String SBT[] = new String[] {"Fuso hor\u00e1rio das Ilhas Salom\u00e3o", "SBT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Salom\u00e3o", "SBST",
"Hor\u00E1rio das Ilhas Salom\u00E3o", "SBT"};
String SGT[] = new String[] {"Fuso hor\u00e1rio de Cingapura", "SGT",
"Fuso hor\u00e1rio de ver\u00e1 de Cingapura", "SGST",
"Hor\u00E1rio de Cingapura", "SGT"};
String TASMANIA[] = new String[] {"Hor\u00E1rio-Padr\u00E3o do Leste (Tasm\u00E2nia)", "AEST",
"Fuso Hor\u00E1rio de Ver\u00E3o Oriental (Tasm\u00E2nia)", "AEDT",
"Hor\u00E1rio do Leste (Tasm\u00E2nia)", "AET"};
String TMT[] = new String[] {"Fuso hor\u00e1rio do Turcomenist\u00e3o", "TMT",
"Fuso hor\u00e1rio de ver\u00e3o do Turcomenist\u00e3o", "TMST",
"Hor\u00E1rio do Turcomenist\u00E3o", "TMT"};
String TRUT[] = new String[] {"Fuso Hor\u00E1rio de Chuuk", "CHUT",
"Fuso Hor\u00E1rio de Ver\u00E3o de Chuuk", "CHUST",
"Fuso Hor\u00E1rio de Chuuk", "CHUT"};
String ULAT[]= new String[] {"Fuso hor\u00e1rio de Ulan Bator", "ULAT",
"Fuso hor\u00e1rio de ver\u00e3o de Ulan Bator", "ULAST",
"Hor\u00E1rio de Ulaanbaatar", "ULAT"};
String WAT[] = new String[] {"Fuso hor\u00e1rio da \u00c1frica Ocidental", "WAT",
"Fuso hor\u00e1rio de ver\u00e3o da \u00c1frica Ocidental", "WAST",
"Hor\u00E1rio da \u00C1frica Ocidental", "WAT"};
String WET[] = new String[] {"Fuso hor\u00e1rio da Europa Ocidental", "WET",
"Fuso hor\u00e1rio de ver\u00e3o da Europa Ocidental", "WEST",
"Hor\u00E1rio da Europa Ocidental", "WET"};
String WGT[] = new String[] {"Fuso hor\u00e1rio da Groenl\u00e2ndia Ocidental", "WGT",
"Fuso hor\u00e1rio de ver\u00e3o da Groenl\u00e2ndia Ocidental", "WGST",
"Hor\u00E1rio da Groenl\u00E2ndia Ocidental", "WGT"};
String WIT[] = new String[] {"Fuso hor\u00e1rio da Indon\u00e9sia Ocidental", "WIB",
"Fuso hor\u00e1rio de ver\u00e3o da Indon\u00e9sia Ocidental", "WIST",
"Hor\u00E1rio da Indon\u00E9sia Ocidental", "WIB"};
String WST_AUS[] = new String[] {"Hor\u00E1rio-Padr\u00E3o Ocidental (Austr\u00E1lia)", "AWST",
"Fuso Hor\u00E1rio de Ver\u00E3o Ocidental (Austr\u00E1lia)", "AWDT",
"Hor\u00E1rio Ocidental (Austr\u00E1lia)", "AWT"};
String SAMOA[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Samoa", "SST",
"Hor\u00e1rio de luz natural de Samoa", "SDT",
"Hor\u00E1rio da Samoa", "ST"};
String WST_SAMOA[] = new String[] {"Fuso hor\u00e1rio de Samoa Ocidental", "WSST",
"Fuso hor\u00e1rio de ver\u00e3o de Samoa Ocidental", "WSDT",
"Fuso Hor\u00E1rio de Samoa Ocidental", "WST"};
String ChST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Chamorro", "ChST",
"Hor\u00e1rio de luz natural de Chamorro", "ChDT",
"Hor\u00E1rio de Chamorro", "ChT"};
String VICTORIA[] = new String[] {"Hor\u00E1rio-Padr\u00E3o do Leste (Victoria)", "AEST",
"Fuso Hor\u00E1rio de Ver\u00E3o Oriental (Victoria)", "AEDT",
"Hor\u00E1rio do Leste (Victoria)", "AET"};
String UTC[] = new String[] {"Tempo universal coordenado", "UTC",
"Tempo universal coordenado", "UTC",
"Hor\u00E1rio Universal Coordenado", "UTC"};
String UZT[] = new String[] {"Fuso hor\u00e1rio do Uzbequist\u00e3o", "UZT",
"Fuso hor\u00e1rio de ver\u00e3o do Uzbequist\u00e3o", "UZST",
"Hor\u00E1rio do Uzbequist\u00E3o", "UZT"};
String XJT[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o da China", "XJT",
"Hor\u00e1rio de luz natural da China", "XJDT",
"Hor\u00E1rio da China", "XJT"};
String YAKT[] = new String[] {"Fuso hor\u00e1rio de Yakutsk", "YAKT",
"Fuso hor\u00e1rio de ver\u00e3o de Yakutsk", "YAKST",
"Hor\u00E1rio de Yakutsk", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", CAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", CAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", new String[] {"Central African Time", "CAT",
"Western African Time", "WAT",
"Central African Time", "CAT"}},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"Fuso hor\u00e1rio do Paraguai", "PYT",
"Fuso hor\u00e1rio de ver\u00e3o do Paraguai", "PYST",
"Hor\u00E1rio do Paraguai", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"Fuso hor\u00e1rio da Col\u00f4mbia", "COT",
"Fuso hor\u00e1rio de ver\u00e3o da Col\u00f4mbia", "COST",
"Hor\u00E1rio da Col\u00F4mbia", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"Fuso hor\u00e1rio da Venezuela", "VET",
"Fuso hor\u00e1rio de ver\u00e3o da Venezuela", "VEST",
"Hor\u00E1rio da Venezuela", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"Fuso hor\u00e1rio da Guiana Francesa", "GFT",
"Fuso hor\u00e1rio de ver\u00e3o da Guiana Francesa", "GFST",
"Hor\u00E1rio da Guiana Francesa", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", CST},
{"America/Ciudad_Juarez", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", MST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", WGT},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", EST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"Fuso hor\u00e1rio do Equador", "ECT",
"Fuso hor\u00e1rio de ver\u00e3o do Equador", "ECST",
"Hor\u00E1rio do Equador", "ECT"}},
{"America/Guyana", new String[] {"Fuso hor\u00e1rio da Guiana", "GYT",
"Fuso hor\u00e1rio de ver\u00e3o da Guiana", "GYST",
"Hor\u00E1rios da Guiana", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"Fuso hor\u00e1rio da Bol\u00edvia", "BOT",
"Fuso hor\u00e1rio de ver\u00e3o da Bol\u00edvia", "BOST",
"Hor\u00E1rio da Bol\u00EDvia", "BOT"}},
{"America/Lima", new String[] {"Fuso hor\u00e1rio do Peru", "PET",
"Fuso hor\u00e1rio de ver\u00e3o do Peru", "PEST",
"Hor\u00E1rio do Peru", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"Fuso hor\u00e1rio padr\u00e3o de S\u00e3o Pedro e Miquelon", "PMST",
"Hor\u00e1rio de luz natural de S\u00e3o Pedro e Miquelon", "PMDT",
"Hor\u00E1rio de Saint Pierre e Miquelon", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"Fuso hor\u00e1rio do Uruguai", "UYT",
"Fuso hor\u00e1rio de ver\u00e3o do Uruguai", "UYST",
"Hor\u00E1rio do Uruguai", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Nuuk", WGT},
{"America/Ojinaga", CST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"Fuso hor\u00e1rio do Suriname", "SRT",
"Fuso hor\u00e1rio de ver\u00e3o do Suriname", "SRST",
"Hor\u00E1rio do Suriname", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", MST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"Fuso hor\u00e1rio de Davis", "DAVT",
"Fuso hor\u00e1rio de ver\u00e3o de Davis", "DAVST",
"Hor\u00E1rio de Davis", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"Fuso hor\u00e1rio de Dumont-d'Urville", "DDUT",
"Fuso hor\u00e1rio de ver\u00e3o de Dumont-d'Urville", "DDUST",
"Fuso Hor\u00E1rio de Dumont-d'Urville", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"Australian Eastern Standard Time (Macquarie)", "AEST",
"Australian Eastern Daylight Time (Macquarie)", "AEDT",
"Australian Eastern Time (Macquarie)", "AET"}},
{"Antarctica/Mawson", new String[] {"Fuso hor\u00e1rio de Mawson", "MAWT",
"Fuso hor\u00e1rio de ver\u00e3o de Mawson", "MAWST",
"Hor\u00E1rio de Mawson", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"Fuso hor\u00e1rio de Rothera", "ROTT",
"Fuso hor\u00e1rio de ver\u00e3o de Rothera", "ROTST",
"Hor\u00E1rio de Rothera", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"Fuso hor\u00e1rio de Syowa", "SYOT",
"Fuso hor\u00e1rio de ver\u00e3o de Syowa", "SYOST",
"Hor\u00E1rio de Syowa", "SYOT"}},
{"Antarctica/Troll", new String[] {"Tempo universal coordenado", "UTC",
"Fuso hor\u00e1rio de ver\u00e3o da Europa Central", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"Fuso hor\u00e1rio de Vostok", "VOST",
"Fuso hor\u00e1rio de ver\u00e3o de Vostok", "VOSST",
"Hor\u00E1rio de Vostok", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"Fuso hor\u00e1rio de Alma-Ata", "ALMT",
"Fuso hor\u00e1rio de ver\u00e3o de Alma-Ata", "ALMST",
"Hor\u00E1rio de Alma-Ata", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"Fuso hor\u00e1rio de Anadyr", "ANAT",
"Fuso hor\u00e1rio de ver\u00e3o de Anadyr", "ANAST",
"Hor\u00E1rio de Anadyr", "ANAT"}},
{"Asia/Aqtau", new String[] {"Fuso hor\u00e1rio de Aqtau", "AQTT",
"Fuso hor\u00e1rio de ver\u00e3o de Aqtau", "AQTST",
"Hor\u00E1rio de Aqtau", "AQTT"}},
{"Asia/Aqtobe", new String[] {"Fuso hor\u00e1rio de Aqtobe", "AQTT",
"Fuso hor\u00e1rio de ver\u00e3o de Aqtobe", "AQTST",
"Hor\u00E1rio de Aqtobe", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"Fuso hor\u00e1rio do Azerbaij\u00e3o", "AZT",
"Fuso hor\u00e1rio de ver\u00e3o do Azerbaij\u00e3o", "AZST",
"Hor\u00E1rio do Azerbaij\u00E3o", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"Fuso hor\u00e1rio do Quirguist\u00e3o", "KGT",
"Fuso hor\u00e1rio de ver\u00e3o do Quirguist\u00e3o", "KGST",
"Hor\u00E1rio do Quirguist\u00E3o", "KGT"}},
{"Asia/Brunei", new String[] {"Fuso hor\u00e1rio de Brunei", "BNT",
"Fuso hor\u00e1rio de ver\u00e3o de Brunei", "BNST",
"Hor\u00E1rio de Brunei", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"Fuso hor\u00e1rio de Choibalsan", "CHOT",
"Fuso hor\u00e1rio de ver\u00e3o de Choibalsan", "CHOST",
"Hor\u00E1rio de Choibalsan", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"Fuso hor\u00e1rio do Timor-Leste", "TLT",
"Fuso hor\u00e1rio de ver\u00e3o do Timor-Leste", "TLST",
"Hor\u00E1rio do Timor-Leste", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"Fuso hor\u00e1rio do Tadjiquist\u00e3o", "TJT",
"Fuso hor\u00e1rio de ver\u00e3o do Tadjiquist\u00e3o", "TJST",
"Hor\u00E1rio do Tadjiquist\u00E3o", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"Fuso hor\u00e1rio de Hovd", "HOVT",
"Fuso hor\u00e1rio de ver\u00e3o de Hovd", "HOVST",
"Hor\u00E1rio de Hovd", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"Fuso hor\u00e1rio da Indon\u00e9sia Oriental", "WIT",
"Fuso hor\u00e1rio de ver\u00e3o da Indon\u00e9sia Oriental", "EIST",
"Hor\u00E1rio da Indon\u00E9sia Oriental", "WIT"}},
{"Asia/Kabul", new String[] {"Fuso hor\u00e1rio do Afeganist\u00e3o", "AFT",
"Fuso hor\u00e1rio de ver\u00e3o do Afeganist\u00e3o", "AFST",
"Hor\u00E1rio do Afeganist\u00E3o", "AFT"}},
{"Asia/Kamchatka", new String[] {"Fuso hor\u00e1rio de Petropavlovsk-Kamchatski", "PETT",
"Fuso hor\u00e1rio de ver\u00e3o de Petropavlovsk-Kamchatski", "PETST",
"Hor\u00E1rio de Petropavlovsk-Kamchatski", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"Fuso hor\u00e1rio de Magadan", "MAGT",
"Fuso hor\u00e1rio de ver\u00e3o de Magadan", "MAGST",
"Hor\u00E1rio de Magadan", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"Philippines Standard Time", "PST",
"Philippines Daylight Time", "PDT",
"Philippines Time", "PT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"Fuso hor\u00e1rio de Uralsk", "ORAT",
"Fuso hor\u00e1rio de ver\u00e3o de Uralsk", "ORAST",
"Hor\u00E1rio de Uralsk", "ORAT"}},
{"Asia/Omsk", new String[] {"Fuso hor\u00e1rio de Omsk", "OMST",
"Fuso hor\u00e1rio de ver\u00e3o de Omsk", "OMSST",
"Hor\u00E1rio de Omsk", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"Fuso hor\u00e1rio de Kizil-Orda", "QYZT",
"Fuso hor\u00e1rio de ver\u00e3o de Kizil-Orda", "QYZST",
"Hor\u00E1rio de Qyzylorda", "QYZT"}},
{"Asia/Rangoon", MMT},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"Fuso hor\u00e1rio de Sakhalina", "SAKT",
"Fuso hor\u00e1rio de ver\u00e3o de Sakhalina", "SAKST",
"Hor\u00E1rio de Sakhalin", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", CTT},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"Fuso hor\u00e1rio da Ge\u00f3rgia", "GET",
"Fuso hor\u00e1rio de ver\u00e3o da Ge\u00f3rgia", "GEST",
"Hor\u00E1rio da Ge\u00F3rgia", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"Hor\u00E1rio de Ust-Nera", "VLAT",
"Hor\u00E1rio de Ver\u00E3o de Ust-Nera", "VLAST",
"Hor\u00E1rio de Ust-Nera", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"Fuso hor\u00e1rio de Vladivostok", "VLAT",
"Fuso hor\u00e1rio de ver\u00e3o de Vladivostok", "VLAST",
"Hor\u00E1rio de Vladivostok", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yangon", MMT},
{"Asia/Yekaterinburg", new String[] {"Fuso hor\u00e1rio de Yekaterinburgo", "YEKT",
"Fuso hor\u00e1rio de ver\u00e3o de Yekaterinburgo", "YEKST",
"Hor\u00E1rio de Yekaterinburg", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"Fuso hor\u00e1rio das A\u00e7ores", "AZOT",
"Fuso hor\u00e1rio de ver\u00e3o das A\u00e7ores", "AZOST",
"Hor\u00E1rio de A\u00E7ores", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"Fuso hor\u00e1rio de Cabo Verde", "CVT",
"Fuso hor\u00e1rio de ver\u00e3o de Cabo Verde", "CVST",
"Hor\u00E1rio de Cabo Verde", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"Fuso hor\u00e1rio padr\u00e3o da Ge\u00f3rgia do Sul", "GST",
"Hor\u00e1rio de luz natural da Ge\u00f3rgia do Sul", "GDT",
"Hor\u00E1rio da Ge\u00F3rgia do Sul", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"Fuso hor\u00e1rio das Ilhas Falkland", "FKT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Falkland", "FKST",
"Hor\u00E1rio das Ilhas Malvinas", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"Fuso Hor\u00E1rio Ocidental Central (Austr\u00E1lia)", "ACWST",
"Fuso Hor\u00E1rio de Ver\u00E3o Ocidental Central (Austr\u00E1lia)", "ACWDT",
"Hor\u00E1rio Ocidental Central (Austr\u00E1lia)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", MST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"Fuso hor\u00e1rio de Samara", "SAMT",
"Fuso hor\u00e1rio de ver\u00e3o de Samara", "SAMST",
"Hor\u00E1rio de Samara", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"Fuso hor\u00e1rio dos territ\u00f3rios do Oceano \u00cdndico", "IOT",
"Fuso hor\u00e1rio de ver\u00e3o dos territ\u00f3rios do Oceano \u00cdndico", "IOST",
"Hor\u00E1rio do Territ\u00F3rio do Oceano \u00CDndico", "IOT"}},
{"Indian/Christmas", new String[] {"Fuso hor\u00e1rio das Ilhas Christmas", "CXT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Christmas", "CXST",
"Hor\u00E1rio da Ilha Christmas", "CIT"}},
{"Indian/Cocos", new String[] {"Fuso hor\u00e1rio das Ilhas Cocos", "CCT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Cocos", "CCST",
"Hor\u00E1rio das Ilhas Cocos", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"Fuso hor\u00e1rio das Terras Austrais e Ant\u00e1rticas Francesas", "TFT",
"Fuso hor\u00e1rio de ver\u00e3o das Terras Austrais e Ant\u00e1rticas Francesas", "TFST",
"Hor\u00E1rio do Territ\u00F3rio Franc\u00EAs no Sul da Ant\u00E1rtica", "TFT"}},
{"Indian/Mahe", new String[] {"Fuso hor\u00e1rio das Seychelles", "SCT",
"Fuso hor\u00e1rio de ver\u00e3o das Seychelles", "SCST",
"Hor\u00E1rio de Seychelles", "SCT"}},
{"Indian/Maldives", new String[] {"Fuso hor\u00e1rio das Maldivas", "MVT",
"Fuso hor\u00e1rio de ver\u00e3o das Maldivas", "MVST",
"Hor\u00E1rio das Maldivas", "MVT"}},
{"Indian/Mauritius", new String[] {"Fuso hor\u00e1rio das Ilhas Maur\u00edcio", "MUT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Maur\u00edcio", "MUST",
"Hor\u00E1rio de Maur\u00EDcio", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"Fuso hor\u00e1rio de Reuni\u00e3o", "RET",
"Fuso hor\u00e1rio de ver\u00e3o de Reuni\u00e3o", "REST",
"Hor\u00E1rio das Ilhas Reuni\u00E3o", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"Fuso hor\u00e1rio da Europa M\u00e9dia", "MET",
"Fuso hor\u00e1rio de ver\u00e3o da Europa M\u00e9dia", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", TRUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"Fuso hor\u00e1rio de Vanuatu", "VUT",
"Fuso hor\u00e1rio de ver\u00e3o de Vanuatu", "VUST",
"Hor\u00E1rio de Vanuatu", "VUT"}},
{"Pacific/Enderbury", new String[] {"Fuso hor\u00e1rio das Ilhas F\u00e9nix", "PHOT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas F\u00e9nix", "PHOST",
"Hor\u00E1rio da Ilha Phoenix", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"Fuso hor\u00e1rio de Tokelau", "TKT",
"Fuso hor\u00e1rio de ver\u00e3o de Tokelau", "TKST",
"Hor\u00E1rio de Toquelau", "TKT"}},
{"Pacific/Fiji", new String[] {"Fuso hor\u00e1rio de Fiji", "FJT",
"Fuso hor\u00e1rio de ver\u00e3o de Fiji", "FJST",
"Hor\u00E1rio de Fiji", "FJT"}},
{"Pacific/Funafuti", new String[] {"Fuso hor\u00e1rio de Tuvalu", "TVT",
"Fuso hor\u00e1rio de ver\u00e3o de Tuvalu", "TVST",
"Hor\u00E1rio de Tuvalu", "TVT"}},
{"Pacific/Galapagos", new String[] {"Fuso hor\u00e1rio das Ilhas Gal\u00e1pagos", "GALT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Gal\u00e1pagos", "GALST",
"Hor\u00E1rio de Gal\u00E1pagos", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"Fuso hor\u00e1rio das Esp\u00f3rades Equatoriais", "LINT",
"Fuso hor\u00e1rio de ver\u00e3o das Esp\u00f3rades Equatoriais", "LINST",
"Hor\u00E1rio das Ilhas Line", "LINT"}},
{"Pacific/Kosrae", new String[] {"Fuso hor\u00e1rio de Kosrae", "KOST",
"Fuso hor\u00e1rio de ver\u00e3o de Kosrae", "KOSST",
"Hor\u00E1rio de Kosrae", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"Fuso hor\u00e1rio das Ilhas Marquesas", "MART",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Marquesas", "MARST",
"Hor\u00E1rio das Ilhas Marquesas", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"Fuso hor\u00e1rio de Nauru", "NRT",
"Fuso hor\u00e1rio de ver\u00e3o de Nauru", "NRST",
"Hor\u00E1rio de Nauru", "NRT"}},
{"Pacific/Niue", new String[] {"Fuso hor\u00e1rio de Niue", "NUT",
"Fuso hor\u00e1rio de ver\u00e3o de Niue", "NUST",
"Hor\u00E1rio de Niue", "NUT"}},
{"Pacific/Norfolk", new String[] {"Fuso hor\u00e1rio da Ilha de Norfolk", "NFT",
"Fuso hor\u00e1rio de ver\u00e3o da Ilha de Norfolk", "NFST",
"Hor\u00E1rio de Norfolk", "NFT"}},
{"Pacific/Noumea", new String[] {"Fuso hor\u00e1rio da Nova Caled\u00f4nia", "NCT",
"Fuso hor\u00e1rio de ver\u00e3o da Nova Caled\u00f4nia", "NCST",
"Hor\u00E1rio da Nova Caled\u00F4nia", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"Fuso hor\u00e1rio de Palau", "PWT",
"Fuso hor\u00e1rio de ver\u00e3o de Palau", "PWST",
"Hor\u00E1rio de Palau", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"Fuso hor\u00e1rio de Papua-Nova Guin\u00e9", "PGT",
"Fuso hor\u00e1rio de ver\u00e3o de Papua-Nova Guin\u00e9", "PGST",
"Hor\u00E1rio de Papua-Nova Guin\u00E9", "PGT"}},
{"Pacific/Rarotonga", new String[] {"Fuso hor\u00e1rio das Ilhas Cook", "CKT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Cook", "CKHST",
"Hor\u00E1rio das Ilhas Cook", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"Fuso hor\u00e1rio do Taiti", "TAHT",
"Fuso hor\u00e1rio de ver\u00e3o do Taiti", "TAHST",
"Hor\u00E1rio do Tahiti", "TAHT"}},
{"Pacific/Tarawa", new String[] {"Fuso hor\u00e1rio das Ilhas Gilbert", "GILT",
"Fuso hor\u00e1rio de ver\u00e3o das Ilhas Gilbert", "GILST",
"Hor\u00E1rio das Ilhas Gilbert", "GILT"}},
{"Pacific/Tongatapu", new String[] {"Fuso hor\u00e1rio de Tonga", "TOT",
"Fuso hor\u00e1rio de ver\u00e3o de Tonga", "TOST",
"Hor\u00E1rio de Tonga", "TOT"}},
{"Pacific/Truk", TRUT},
{"Pacific/Wake", new String[] {"Fuso hor\u00e1rio de Wake", "WAKT",
"Fuso hor\u00e1rio de ver\u00e3o de Wake", "WAKST",
"Hor\u00E1rio de Wake", "WAKT"}},
{"Pacific/Wallis", new String[] {"Fuso hor\u00e1rio de Wallis e Futuna", "WFT",
"Fuso hor\u00e1rio de ver\u00e3o de Wallis e Futuna", "WFST",
"Hor\u00E1rio das Ilhas Wallis e Futuna", "WFT"}},
{"Pacific/Yap", TRUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/util/resources/pt/TimeZoneNames_pt_BR.java |
180,177 | /*
* Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.util.resources.zh;
import sun.util.resources.TimeZoneNamesBundle;
public final class TimeZoneNames_zh_TW extends TimeZoneNamesBundle {
protected final Object[][] getContents() {
String ACT[] = new String[] {"Acre \u6642\u9593", "ACT",
"Acre \u590f\u4ee4\u6642\u9593", "ACST",
"Acre \u6642\u9593", "ACT"};
String ADELAIDE[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u90E8)", "ACST",
"\u4E2D\u90E8\u590F\u4EE4\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u5340)", "ACDT",
"\u4E2D\u90E8\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u90E8)", "ACT"};
String AGT[] = new String[] {"\u963f\u6839\u5ef7\u6642\u9593", "ART",
"\u963f\u6839\u5ef7\u590f\u4ee4\u6642\u9593", "ARST",
"\u963F\u6839\u5EF7\u6642\u9593", "ART"};
String AKST[] = new String[] {"\u963f\u62c9\u65af\u52a0\u6a19\u6e96\u6642\u9593", "AKST",
"\u963f\u62c9\u65af\u52a0\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "AKDT",
"\u963F\u62C9\u65AF\u52A0\u6642\u9593", "AKT"};
String AMT[] = new String[] {"\u4e9e\u99ac\u905c\u6642\u9593", "AMT",
"\u4e9e\u99ac\u905c\u590f\u4ee4\u6642\u9593", "AMST",
"\u4E9E\u99AC\u905C\u6642\u9593", "AMT"};
String ARAST[] = new String[] {"\u963f\u62c9\u4f2f\u6a19\u6e96\u6642\u9593", "AST",
"\u963f\u62c9\u4f2f\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "ADT",
"\u963F\u62C9\u4F2F\u6642\u9593", "AT"};
String ARMT[] = new String[] {"\u4e9e\u7f8e\u5c3c\u4e9e\u6642\u9593", "AMT",
"\u4e9e\u7f8e\u5c3c\u4e9e\u590f\u4ee4\u6642\u9593", "AMST",
"\u4E9E\u7F8E\u5C3C\u4E9E\u6642\u9593", "AMT"};
String AST[] = new String[] {"\u5927\u897f\u6d0b\u6a19\u6e96\u6642\u9593", "AST",
"\u5927\u897f\u6d0b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "ADT",
"\u5927\u897F\u6D0B\u6642\u9593", "AT"};
String BDT[] = new String[] {"\u5b5f\u52a0\u62c9\u6642\u9593", "BDT",
"\u5b5f\u52a0\u62c9\u590f\u4ee4\u6642\u9593", "BDST",
"\u5B5F\u52A0\u62C9\u6642\u9593", "BDT"};
String BRISBANE[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642\u9593 (\u6606\u58EB\u862D)", "AEST",
"\u6771\u90E8\u590F\u4EE4\u6642\u9593 (\u6606\u58EB\u862D)", "AEDT",
"\u6771\u90E8\u6642\u9593 (\u6606\u58EB\u862D)", "AET"};
String BROKEN_HILL[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u5340/\u65B0\u5357\u5A01\u723E\u65AF)", "ACST",
"\u4E2D\u90E8\u590F\u4EE4\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u5340/\u65B0\u5357\u5A01\u723E\u65AF)", "ACDT",
"\u4E2D\u90E8\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E\u5357\u90E8/\u65B0\u5357\u5A01\u723E\u65AF)", "ACT"};
String BRT[] = new String[] {"\u5df4\u897f\u5229\u4e9e\u6642\u9593", "BRT",
"\u5df4\u897f\u5229\u4e9e\u590f\u4ee4\u6642\u9593", "BRST",
"\u5DF4\u897F\u5229\u4E9E\u6642\u9593", "BRT"};
String BTT[] = new String[] {"\u4e0d\u4e39\u6642\u9593", "BTT",
"\u4e0d\u4e39\u590f\u4ee4\u6642\u9593", "BTST",
"\u4E0D\u4E39\u6642\u9593", "BTT"};
String CAT[] = new String[] {"\u4e2d\u975e\u6642\u9593", "CAT",
"\u4e2d\u975e\u590f\u4ee4\u6642\u9593", "CAST",
"\u4E2D\u975E\u6642\u9593", "CAT"};
String CET[] = new String[] {"\u4e2d\u6b50\u6642\u9593", "CET",
"\u4e2d\u6b50\u590f\u4ee4\u6642\u9593", "CEST",
"\u4E2D\u6B50\u6642\u9593", "CET"};
String CHAST[] = new String[] {"\u67e5\u5766\u6a19\u6e96\u6642\u9593", "CHAST",
"\u67e5\u5766\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "CHADT",
"\u67E5\u5766\u6642\u9593", "CHAT"};
String CHUT[] = new String[] {"\u695A\u514B\u6642\u9593", "CHUT",
"\u695A\u514B\u590F\u4EE4\u6642\u9593", "CHUST",
"\u695A\u514B\u6642\u9593", "CHUT"};
String CIT[] = new String[] {"\u4e2d\u5370\u5ea6\u5c3c\u897f\u4e9e\u6642\u9593", "WITA",
"\u4e2d\u5370\u5ea6\u5c3c\u897f\u4e9e\u590f\u4ee4\u6642\u9593", "CIST",
"\u4E2D\u5370\u5EA6\u5C3C\u897F\u4E9E\u6642\u9593", "WITA"};
String CLT[] = new String[] {"\u667a\u5229\u6642\u9593", "CLT",
"\u667a\u5229\u590f\u4ee4\u6642\u9593", "CLST",
"\u667A\u5229\u6642\u9593", "CLT"};
String CST[] = new String[] {"\u4e2d\u592e\u6a19\u6e96\u6642\u9593", "CST",
"\u4e2d\u592e\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "CDT",
"\u7F8E\u570B\u4E2D\u90E8\u6642\u9593", "CT"};
String CTT[] = new String[] {"\u4e2d\u570b\u6a19\u6e96\u6642\u9593", "CST",
"\u4e2d\u570b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "CDT",
"\u4E2D\u570B\u6642\u9593", "CT"};
String CUBA[] = new String[] {"\u53e4\u5df4\u6a19\u6e96\u6642\u9593", "CST",
"\u53e4\u5df4\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "CDT",
"\u53E4\u5DF4\u6642\u9593", "CT"};
String DARWIN[] = new String[] {"\u4E2D\u90E8\u6A19\u6E96\u6642\u9593 (\u5317\u90E8\u5404\u5730\u5340)", "ACST",
"\u4E2D\u90E8\u590F\u4EE4\u6642\u9593 (\u5317\u90E8\u5404\u5730\u5340)", "ACDT",
"\u6FB3\u5927\u5229\u4E9E\u4E2D\u90E8\u6642\u9593 (\u5317\u65B9\u5340\u57DF)", "ACT"};
String DUBLIN[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u5e73\u5747\u6642\u9593", "GMT",
"\u611b\u723e\u862d\u590f\u4ee4\u6642\u9593", "IST",
"\u611B\u723E\u862D\u6587\u6642\u9593", "IT"};
String EAT[] = new String[] {"\u6771\u975e\u6642\u9593", "EAT",
"\u6771\u975e\u590f\u4ee4\u6642\u9593", "EAST",
"\u6771\u975E\u6642\u9593", "EAT"};
String EASTER[] = new String[] {"\u5fa9\u6d3b\u5cf6\u6642\u9593", "EAST",
"\u5fa9\u6d3b\u5cf6\u590f\u4ee4\u6642\u9593", "EASST",
"\u5FA9\u6D3B\u5CF6\u6642\u9593", "EAST"};
String EET[] = new String[] {"\u6771\u6b50\u6642\u9593", "EET",
"\u6771\u6b50\u590f\u4ee4\u6642\u9593", "EEST",
"\u6771\u6b50\u6642\u9593", "EET"};
String EGT[] = new String[] {"\u6771\u683c\u6797\u5cf6\u6642\u9593", "EGT",
"\u6771\u683c\u6797\u5cf6\u590f\u4ee4\u6642\u9593", "EGST",
"\u6771\u683C\u9675\u862D\u6642\u9593", "EGT"};
String EST[] = new String[] {"\u6771\u65b9\u6a19\u6e96\u6642\u9593", "EST",
"\u6771\u65b9\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "EDT",
"\u7F8E\u570B\u6771\u90E8\u6642\u9593", "ET"};
String EST_NSW[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642\u9593 (\u65B0\u5357\u5A01\u723E\u65AF)", "AEST",
"\u6771\u90E8\u590F\u4EE4\u6642\u9593 (\u65B0\u5357\u5A01\u723E\u65AF)", "AEDT",
"\u6771\u90E8\u6642\u9593 (\u65B0\u5357\u5A01\u723E\u65AF)", "AET"};
String FET[] = new String[] {"\u6771\u6B50\u5167\u9678\u6642\u9593", "FET",
"\u6771\u6B50\u5167\u9678\u590F\u4EE4\u6642\u9593", "FEST",
"\u6771\u6B50\u5167\u9678\u6642\u9593", "FET"};
String GHMT[] = new String[] {"\u8fe6\u7d0d\u5e73\u5747\u6642\u9593", "GMT",
"\u8fe6\u7d0d\u590f\u4ee4\u6642\u9593", "GHST",
"\u8FE6\u7D0D\u6642\u9593", "GMT"};
String GAMBIER[] = new String[] {"\u7518\u6bd4\u723e\u6642\u9593", "GAMT",
"\u7518\u6bd4\u723e\u590f\u4ee4\u6642\u9593", "GAMST",
"\u7518\u6BD4\u723E\u6642\u9593", "GAMT"};
String GMT[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u6642\u9593", "GMT",
"\u683c\u6797\u5a01\u6cbb\u6642\u9593", "GMT",
"\u683C\u6797\u5A01\u6CBB\u6642\u9593", "GMT"};
String GMTBST[] = new String[] {"\u683c\u6797\u5a01\u6cbb\u5e73\u5747\u6642\u9593", "GMT",
"\u82f1\u570b\u590f\u4ee4\u6642\u9593", "BST",
"\u82F1\u570B\u6642\u9593", "BT"};
String GST[] = new String[] {"\u6ce2\u65af\u7063\u6a19\u6e96\u6642\u9593", "GST",
"\u6ce2\u65af\u7063\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "GDT",
"\u6CE2\u65AF\u7063\u6642\u9593", "GT"};
String HKT[] = new String[] {"\u9999\u6e2f\u6642\u9593", "HKT",
"\u9999\u6e2f\u590f\u4ee4\u6642\u9593", "HKST",
"\u9999\u6E2F\u6642\u9593", "HKT"};
String HST[] = new String[] {"\u590f\u5a01\u5937\u6a19\u6e96\u6642\u9593", "HST",
"\u590f\u5a01\u5937\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "HDT",
"\u590F\u5A01\u5937\u6642\u9593", "HT"};
String ICT[] = new String[] {"\u5370\u5ea6\u652f\u90a3\u6642\u9593", "ICT",
"\u5370\u5ea6\u652f\u90a3\u590f\u4ee4\u6642\u9593", "ICST",
"\u5370\u5EA6\u652F\u90A3\u6642\u9593", "ICT"};
String IRKT[] = new String[] {"Irkutsk \u6642\u9593", "IRKT",
"Irkutsk \u590f\u4ee4\u6642\u9593", "IRKST",
"\u4F0A\u723E\u5EAB\u6B21\u514B\u6642\u9593", "IRKT"};
String IRT[] = new String[] {"\u4f0a\u6717\u6a19\u6e96\u6642\u9593", "IRST",
"\u4f0a\u6717\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "IRDT",
"\u4F0A\u6717\u6642\u9593", "IRT"};
String ISRAEL[] = new String[] {"\u4ee5\u8272\u5217\u6a19\u6e96\u6642\u9593", "IST",
"\u4ee5\u8272\u5217\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "IDT",
"\u4EE5\u8272\u5217\u6642\u9593", "IT"};
String IST[] = new String[] {"\u5370\u5ea6\u6a19\u6e96\u6642\u9593", "IST",
"\u5370\u5ea6\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "IDT",
"\u5370\u5EA6\u6642\u9593", "IT"};
String JST[] = new String[] {"\u65e5\u672c\u6a19\u6e96\u6642\u9593", "JST",
"\u65e5\u672c\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "JDT",
"\u65E5\u672C\u6642\u9593", "JT"};
String KRAT[] = new String[] {"\u514b\u62c9\u65af\u8afe\u4e9e\u723e\u65af\u514b\u6642\u9593", "KRAT",
"\u514b\u62c9\u65af\u8afe\u4e9e\u723e\u65af\u514b\u590f\u4ee4\u6642\u9593", "KRAST",
"\u514B\u62C9\u65AF\u8AFE\u4E9E\u723E\u65AF\u514B\u6642\u9593", "KRAT"};
String KST[] = new String[] {"\u97d3\u570b\u6a19\u6e96\u6642\u9593", "KST",
"\u97d3\u570b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "KDT",
"\u97D3\u570B\u6642\u9593", "KT"};
String LORD_HOWE[] = new String[] {"\u8c6a\u52f3\u7235\u5cf6\u6a19\u6e96\u6642\u9593", "LHST",
"\u8c6a\u52f3\u7235\u5cf6\u590f\u4ee4\u6642\u9593", "LHDT",
"\u8C6A\u52F3\u7235\u5CF6\u6642\u9593", "LHT"};
String MHT[] = new String[] {"\u99ac\u7d39\u723e\u7fa4\u5cf6\u6642\u9593", "MHT",
"\u99ac\u7d39\u723e\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "MHST",
"\u99AC\u7D39\u723E\u7FA4\u5CF6\u6642\u9593", "MHT"};
String MMT[] = new String[] {"\u7dec\u7538\u6642\u9593", "MMT",
"\u7dec\u7538\u590f\u4ee4\u6642\u9593", "MMST",
"\u7DEC\u7538\u6642\u9593", "MMT"};
String MSK[] = new String[] {"\u83ab\u65af\u79d1\u6a19\u6e96\u6642\u9593", "MSK",
"\u83ab\u65af\u79d1\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "MSD",
"\u83AB\u65AF\u79D1\u6642\u9593", "MT"};
String MST[] = new String[] {"\u5c71\u5340\u6a19\u6e96\u6642\u9593", "MST",
"\u5c71\u5340\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "MDT",
"\u7F8E\u570B\u5C71\u5340\u6642\u9593", "MT"};
String MYT[] = new String[] {"\u99ac\u4f86\u897f\u4e9e\u6642\u9593", "MYT",
"\u99ac\u4f86\u897f\u4e9e\u590f\u4ee4\u6642\u9593", "MYST",
"\u99AC\u4F86\u897F\u4E9E\u6642\u9593", "MYT"};
String NORONHA[] = new String[] {"\u8cbb\u723e\u5357\u591a-\u8fea\u8afe\u7f85\u5c3c\u4e9e\u6642\u9593", "FNT",
"\u8cbb\u723e\u5357\u591a-\u8fea\u8afe\u7f85\u5c3c\u4e9e\u590f\u4ee4\u6642\u9593", "FNST",
"\u8CBB\u723E\u5357\u591A-\u8FEA\u8AFE\u7F85\u5C3C\u4E9E\u6642\u9593", "FNT"};
String NOVT[] = new String[] {"Novosibirsk \u6642\u9593", "NOVT",
"Novosibirsk \u590f\u4ee4\u6642\u9593", "NOVST",
"\u65B0\u897F\u4F2F\u5229\u4E9E\u6642\u9593", "NOVT"};
String NPT[] = new String[] {"\u5c3c\u6cca\u723e\u6642\u9593", "NPT",
"\u5c3c\u6cca\u723e\u590f\u4ee4\u6642\u9593", "NPST",
"\u5C3C\u6CCA\u723E\u6642\u9593", "NPT"};
String NST[] = new String[] {"\u7d10\u82ac\u862d\u6a19\u6e96\u6642\u9593", "NST",
"\u7d10\u82ac\u862d\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "NDT",
"\u7D10\u82AC\u862D\u6642\u9593", "NT"};
String NZST[] = new String[] {"\u7d10\u897f\u862d\u6a19\u6e96\u6642\u9593", "NZST",
"\u7d10\u897f\u862d\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "NZDT",
"\u7D10\u897F\u862D\u6642\u9593", "NZT"};
String PITCAIRN[] = new String[] {"\u76ae\u7279\u5eb7\u6a19\u6e96\u6642\u9593", "PST",
"\u76ae\u7279\u5eb7\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "PDT",
"\u76AE\u7279\u5EB7\u6642\u9593", "PT"};
String PKT[] = new String[] {"\u5df4\u57fa\u65af\u5766\u6642\u9593", "PKT",
"\u5df4\u57fa\u65af\u5766\u590f\u4ee4\u6642\u9593", "PKST",
"\u5DF4\u57FA\u65AF\u5766\u6642\u9593", "PKT"};
String PONT[] = new String[] {"\u6CE2\u7D0D\u4F69\u6642\u9593", "PONT",
"\u6CE2\u7D0D\u4F69\u590F\u4EE4\u6642\u9593", "PONST",
"\u6CE2\u7D0D\u4F69\u5CF6\u6642\u9593", "PONT"};
String PST[] = new String[] {"\u592a\u5e73\u6d0b\u6a19\u6e96\u6642\u9593", "PST",
"\u592a\u5e73\u6d0b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "PDT",
"\u592A\u5E73\u6D0B\u6642\u9593", "PT"};
String SAST[] = new String[] {"\u5357\u975e\u6a19\u6e96\u6642\u9593", "SAST",
"\u5357\u975e\u590f\u4ee4\u6642\u9593", "SAST",
"\u5357\u975E\u6642\u9593", "SAT"};
String SBT[] = new String[] {"\u6240\u7f85\u9580\u7fa4\u5cf6\u6642\u9593", "SBT",
"\u6240\u7f85\u9580\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "SBST",
"\u6240\u7F85\u9580\u7FA4\u5CF6\u6642\u9593", "SBT"};
String SGT[] = new String[] {"\u65b0\u52a0\u5761\u6642\u9593", "SGT",
"\u65b0\u52a0\u5761\u590f\u4ee4\u6642\u9593", "SGST",
"\u65B0\u52A0\u5761\u6642\u9593", "SGT"};
String TASMANIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642\u9593 (\u5854\u65AF\u6885\u5C3C\u4E9E\u5CF6)", "AEST",
"\u6771\u90E8\u590F\u4EE4\u6642\u9593 (\u5854\u65AF\u6885\u5C3C\u4E9E\u5CF6)", "AEDT",
"\u6FB3\u5927\u5229\u4E9E\u6771\u90E8\u6642\u9593 (\u5854\u65AF\u99AC\u5C3C\u4E9E\u5CF6)", "AET"};
String TMT[] = new String[] {"\u571f\u5eab\u66fc\u6642\u9593", "TMT",
"\u571f\u5eab\u66fc\u590f\u4ee4\u6642\u9593", "TMST",
"\u571F\u5EAB\u66FC\u6642\u9593", "TMT"};
String ULAT[]= new String[] {"\u5eab\u502b\u6642\u9593", "ULAT",
"\u5eab\u502b\u590f\u4ee4\u6642\u9593", "ULAST",
"\u5EAB\u502B\u6642\u9593", "ULAT"};
String WAT[] = new String[] {"\u897f\u975e\u6642\u9593", "WAT",
"\u897f\u975e\u590f\u4ee4\u6642\u9593", "WAST",
"\u897F\u975E\u6642\u9593", "WAT"};
String WET[] = new String[] {"\u897f\u6b50\u6642\u9593", "WET",
"\u897f\u6b50\u590f\u4ee4\u6642\u9593", "WEST",
"\u897F\u6B50\u6642\u9593", "WET"};
String WGT[] = new String[] {"\u897f\u683c\u6797\u862d\u5cf6\u6642\u9593", "WGT",
"\u897f\u683c\u6797\u862d\u5cf6\u590f\u4ee4\u6642\u9593", "WGST",
"\u897F\u683C\u9675\u862D\u6642\u9593", "WGT"};
String WIT[] = new String[] {"\u897f\u5370\u5c3c\u6642\u9593", "WIB",
"\u897f\u5370\u5c3c\u590f\u4ee4\u6642\u9593", "WIST",
"\u897F\u5370\u5C3C\u6642\u9593", "WIB"};
String WST_AUS[] = new String[] {"\u897F\u90E8\u6A19\u6E96\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "AWST",
"\u897F\u90E8\u590F\u4EE4\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "AWDT",
"\u897F\u90E8\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "AWT"};
String SAMOA[] = new String[] {"\u85a9\u6469\u4e9e\u6a19\u6e96\u6642\u9593", "SST",
"\u85a9\u6469\u4e9e\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "SDT",
"\u85A9\u6469\u4E9E\u6642\u9593", "ST"};
String WST_SAMOA[] = new String[] {"\u897f\u85a9\u6469\u4e9e\u6642\u9593", "WSST",
"\u897f\u85a9\u6469\u4e9e\u590f\u4ee4\u6642\u9593", "WSDT",
"\u897F\u85A9\u6469\u4E9E\u6642\u9593", "WST"};
String ChST[] = new String[] {"\u67e5\u83ab\u6d1b\u6a19\u6e96\u6642\u9593", "ChST",
"\u67e5\u83ab\u6d1b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "ChDT",
"\u67E5\u83AB\u7F85\u6642\u9593", "ChT"};
String VICTORIA[] = new String[] {"\u6771\u90E8\u6A19\u6E96\u6642\u9593 (\u7DAD\u591A\u5229\u4E9E\u90A6)", "AEST",
"\u6771\u90E8\u590F\u4EE4\u6642\u9593 (\u7DAD\u591A\u5229\u4E9E\u90A6)", "AEDT",
"\u6771\u90E8\u6642\u9593 (\u7DAD\u591A\u5229\u4E9E)", "AET"};
String UTC[] = new String[] {"\u5354\u8abf\u4e16\u754c\u6642\u9593", "UTC",
"\u5354\u8abf\u4e16\u754c\u6642\u9593", "UTC",
"\u5354\u8ABF\u4E16\u754C\u6642\u9593", "UTC"};
String UZT[] = new String[] {"\u70cf\u8332\u5225\u514b\u65af\u5766\u6642\u9593", "UZT",
"\u70cf\u8332\u5225\u514b\u65af\u5766\u590f\u4ee4\u6642\u9593", "UZST",
"\u70CF\u8332\u5225\u514B\u65AF\u5766\u6642\u9593", "UZT"};
String XJT[] = new String[] {"\u4e2d\u570b\u6a19\u6e96\u6642\u9593", "XJT",
"\u4e2d\u570b\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "XJDT",
"\u4E2D\u570B\u6642\u9593", "XJT"};
String YAKT[] = new String[] {"\u4e9e\u5eab\u6b21\u514b\u6642\u9593", "YAKT",
"\u4e9e\u5eab\u6b21\u514b\u590f\u4ee4\u6642\u9593", "YAKST",
"\u4E9E\u5EAB\u6B21\u514B\u6642\u9593", "YAKT"};
return new Object[][] {
{"America/Los_Angeles", PST},
{"PST", PST},
{"America/Denver", MST},
{"MST", MST},
{"America/Phoenix", MST},
{"PNT", MST},
{"America/Chicago", CST},
{"CST", CST},
{"America/New_York", EST},
{"EST", EST},
{"America/Indianapolis", EST},
{"IET", EST},
{"Pacific/Honolulu", HST},
{"HST", HST},
{"America/Anchorage", AKST},
{"AST", AKST},
{"America/Halifax", AST},
{"America/Sitka", AKST},
{"America/St_Johns", NST},
{"CNT", NST},
{"Europe/Paris", CET},
{"ECT", CET},
{"GMT", GMT},
{"Africa/Casablanca", WET},
{"Asia/Jerusalem", ISRAEL},
{"Asia/Tokyo", JST},
{"JST", JST},
{"Europe/Bucharest", EET},
{"Asia/Shanghai", CTT},
{"CTT", CTT},
{"UTC", UTC},
/* Don't change the order of the above zones
* to keep compatibility with the previous version.
*/
{"ACT", DARWIN},
{"AET", EST_NSW},
{"AGT", AGT},
{"ART", EET},
{"Africa/Abidjan", GMT},
{"Africa/Accra", GHMT},
{"Africa/Addis_Ababa", EAT},
{"Africa/Algiers", CET},
{"Africa/Asmara", EAT},
{"Africa/Asmera", EAT},
{"Africa/Bamako", GMT},
{"Africa/Bangui", WAT},
{"Africa/Banjul", GMT},
{"Africa/Bissau", GMT},
{"Africa/Blantyre", CAT},
{"Africa/Brazzaville", WAT},
{"Africa/Bujumbura", CAT},
{"Africa/Cairo", EET},
{"Africa/Ceuta", CET},
{"Africa/Conakry", GMT},
{"Africa/Dakar", GMT},
{"Africa/Dar_es_Salaam", EAT},
{"Africa/Djibouti", EAT},
{"Africa/Douala", WAT},
{"Africa/El_Aaiun", WET},
{"Africa/Freetown", GMT},
{"Africa/Gaborone", CAT},
{"Africa/Harare", CAT},
{"Africa/Johannesburg", SAST},
{"Africa/Juba", CAT},
{"Africa/Kampala", EAT},
{"Africa/Khartoum", CAT},
{"Africa/Kigali", CAT},
{"Africa/Kinshasa", WAT},
{"Africa/Lagos", WAT},
{"Africa/Libreville", WAT},
{"Africa/Lome", GMT},
{"Africa/Luanda", WAT},
{"Africa/Lubumbashi", CAT},
{"Africa/Lusaka", CAT},
{"Africa/Malabo", WAT},
{"Africa/Maputo", CAT},
{"Africa/Maseru", SAST},
{"Africa/Mbabane", SAST},
{"Africa/Mogadishu", EAT},
{"Africa/Monrovia", GMT},
{"Africa/Nairobi", EAT},
{"Africa/Ndjamena", WAT},
{"Africa/Niamey", WAT},
{"Africa/Nouakchott", GMT},
{"Africa/Ouagadougou", GMT},
{"Africa/Porto-Novo", WAT},
{"Africa/Sao_Tome", GMT},
{"Africa/Timbuktu", GMT},
{"Africa/Tripoli", EET},
{"Africa/Tunis", CET},
{"Africa/Windhoek", new String[] {"Central African Time", "CAT",
"Western African Time", "WAT",
"Central African Time", "CAT"}},
{"America/Adak", HST},
{"America/Anguilla", AST},
{"America/Antigua", AST},
{"America/Araguaina", BRT},
{"America/Argentina/Buenos_Aires", AGT},
{"America/Argentina/Catamarca", AGT},
{"America/Argentina/ComodRivadavia", AGT},
{"America/Argentina/Cordoba", AGT},
{"America/Argentina/Jujuy", AGT},
{"America/Argentina/La_Rioja", AGT},
{"America/Argentina/Mendoza", AGT},
{"America/Argentina/Rio_Gallegos", AGT},
{"America/Argentina/Salta", AGT},
{"America/Argentina/San_Juan", AGT},
{"America/Argentina/San_Luis", AGT},
{"America/Argentina/Tucuman", AGT},
{"America/Argentina/Ushuaia", AGT},
{"America/Aruba", AST},
{"America/Asuncion", new String[] {"\u5df4\u62c9\u572d\u6642\u9593", "PYT",
"\u5df4\u62c9\u572d\u590f\u4ee4\u6642\u9593", "PYST",
"\u5DF4\u62C9\u572D\u6642\u9593", "PYT"}},
{"America/Atikokan", EST},
{"America/Atka", HST},
{"America/Bahia", BRT},
{"America/Bahia_Banderas", CST},
{"America/Barbados", AST},
{"America/Belem", BRT},
{"America/Belize", CST},
{"America/Blanc-Sablon", AST},
{"America/Boa_Vista", AMT},
{"America/Bogota", new String[] {"\u54e5\u502b\u6bd4\u4e9e\u6642\u9593", "COT",
"\u54e5\u502b\u6bd4\u4e9e\u590f\u4ee4\u6642\u9593", "COST",
"\u54E5\u502B\u6BD4\u4E9E\u6642\u9593", "COT"}},
{"America/Boise", MST},
{"America/Buenos_Aires", AGT},
{"America/Cambridge_Bay", MST},
{"America/Campo_Grande", AMT},
{"America/Cancun", EST},
{"America/Caracas", new String[] {"\u59d4\u5167\u745e\u62c9\u6642\u9593", "VET",
"\u59d4\u5167\u745e\u62c9\u590f\u4ee4\u6642\u9593", "VEST",
"\u59D4\u5167\u745E\u62C9\u6642\u9593", "VET"}},
{"America/Catamarca", AGT},
{"America/Cayenne", new String[] {"\u6cd5\u5c6c\u572d\u4e9e\u90a3\u6642\u9593", "GFT",
"\u6cd5\u5c6c\u572d\u4e9e\u90a3\u590f\u4ee4\u6642\u9593", "GFST",
"\u6CD5\u5C6C\u572D\u4E9E\u90A3\u6642\u9593", "GFT"}},
{"America/Cayman", EST},
{"America/Chihuahua", CST},
{"America/Ciudad_Juarez", MST},
{"America/Creston", MST},
{"America/Coral_Harbour", EST},
{"America/Cordoba", AGT},
{"America/Costa_Rica", CST},
{"America/Cuiaba", AMT},
{"America/Curacao", AST},
{"America/Danmarkshavn", GMT},
{"America/Dawson", MST},
{"America/Dawson_Creek", MST},
{"America/Detroit", EST},
{"America/Dominica", AST},
{"America/Edmonton", MST},
{"America/Eirunepe", ACT},
{"America/El_Salvador", CST},
{"America/Ensenada", PST},
{"America/Fort_Nelson", MST},
{"America/Fort_Wayne", EST},
{"America/Fortaleza", BRT},
{"America/Glace_Bay", AST},
{"America/Godthab", WGT},
{"America/Goose_Bay", AST},
{"America/Grand_Turk", EST},
{"America/Grenada", AST},
{"America/Guadeloupe", AST},
{"America/Guatemala", CST},
{"America/Guayaquil", new String[] {"\u5384\u74dc\u591a\u723e\u6642\u9593", "ECT",
"\u5384\u74dc\u591a\u723e\u590f\u4ee4\u6642\u9593", "ECST",
"\u5384\u74DC\u591A\u723E\u6642\u9593", "ECT"}},
{"America/Guyana", new String[] {"\u84cb\u4e9e\u90a3\u6642\u9593", "GYT",
"\u84cb\u4e9e\u90a3\u590f\u4ee4\u6642\u9593", "GYST",
"\u84CB\u4E9E\u90A3\u6642\u9593", "GYT"}},
{"America/Havana", CUBA},
{"America/Hermosillo", MST},
{"America/Indiana/Indianapolis", EST},
{"America/Indiana/Knox", CST},
{"America/Indiana/Marengo", EST},
{"America/Indiana/Petersburg", EST},
{"America/Indiana/Tell_City", CST},
{"America/Indiana/Vevay", EST},
{"America/Indiana/Vincennes", EST},
{"America/Indiana/Winamac", EST},
{"America/Inuvik", MST},
{"America/Iqaluit", EST},
{"America/Jamaica", EST},
{"America/Jujuy", AGT},
{"America/Juneau", AKST},
{"America/Kentucky/Louisville", EST},
{"America/Kentucky/Monticello", EST},
{"America/Knox_IN", CST},
{"America/Kralendijk", AST},
{"America/La_Paz", new String[] {"\u73bb\u5229\u7dad\u4e9e\u6642\u9593", "BOT",
"\u73bb\u5229\u7dad\u4e9e\u590f\u4ee4\u6642\u9593", "BOST",
"\u73BB\u5229\u7DAD\u4E9E\u6642\u9593", "BOT"}},
{"America/Lima", new String[] {"\u7955\u9b6f\u6642\u9593", "PET",
"\u7955\u9b6f\u590f\u4ee4\u6642\u9593", "PEST",
"\u7955\u9B6F\u6642\u9593", "PET"}},
{"America/Louisville", EST},
{"America/Lower_Princes", AST},
{"America/Maceio", BRT},
{"America/Managua", CST},
{"America/Manaus", AMT},
{"America/Marigot", AST},
{"America/Martinique", AST},
{"America/Matamoros", CST},
{"America/Mazatlan", MST},
{"America/Mendoza", AGT},
{"America/Menominee", CST},
{"America/Merida", CST},
{"America/Metlakatla", AKST},
{"America/Mexico_City", CST},
{"America/Miquelon", new String[] {"\u76ae\u57c3\u723e\u5cf6\u53ca\u5bc6\u514b\u9686\u5cf6\u6a19\u6e96\u6642\u9593", "PMST",
"\u76ae\u57c3\u723e\u5cf6\u53ca\u5bc6\u514b\u9686\u5cf6\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "PMDT",
"\u8056\u5F7C\u5FB7\u8207\u5BC6\u555F\u5D19\u6642\u9593", "PMT"}},
{"America/Moncton", AST},
{"America/Montevideo", new String[] {"\u70cf\u62c9\u572d\u6642\u9593", "UYT",
"\u70cf\u62c9\u572d\u590f\u4ee4\u6642\u9593", "UYST",
"\u70CF\u62C9\u572D\u6642\u9593", "UYT"}},
{"America/Monterrey", CST},
{"America/Montreal", EST},
{"America/Montserrat", AST},
{"America/Nassau", EST},
{"America/Nipigon", EST},
{"America/Nome", AKST},
{"America/Noronha", NORONHA},
{"America/North_Dakota/Beulah", CST},
{"America/North_Dakota/Center", CST},
{"America/North_Dakota/New_Salem", CST},
{"America/Nuuk", WGT},
{"America/Ojinaga", CST},
{"America/Panama", EST},
{"America/Pangnirtung", EST},
{"America/Paramaribo", new String[] {"\u8607\u5229\u5357\u6642\u9593", "SRT",
"\u8607\u5229\u5357\u590f\u4ee4\u6642\u9593", "SRST",
"\u8607\u5229\u5357\u6642\u9593", "SRT"}},
{"America/Port-au-Prince", EST},
{"America/Port_of_Spain", AST},
{"America/Porto_Acre", ACT},
{"America/Porto_Velho", AMT},
{"America/Puerto_Rico", AST},
{"America/Rainy_River", CST},
{"America/Rankin_Inlet", CST},
{"America/Recife", BRT},
{"America/Regina", CST},
{"America/Resolute", CST},
{"America/Rio_Branco", ACT},
{"America/Rosario", AGT},
{"America/Santa_Isabel", PST},
{"America/Santarem", BRT},
{"America/Santiago", CLT},
{"America/Santo_Domingo", AST},
{"America/Sao_Paulo", BRT},
{"America/Scoresbysund", EGT},
{"America/Shiprock", MST},
{"America/St_Barthelemy", AST},
{"America/St_Kitts", AST},
{"America/St_Lucia", AST},
{"America/St_Thomas", AST},
{"America/St_Vincent", AST},
{"America/Swift_Current", CST},
{"America/Tegucigalpa", CST},
{"America/Thule", AST},
{"America/Thunder_Bay", EST},
{"America/Tijuana", PST},
{"America/Toronto", EST},
{"America/Tortola", AST},
{"America/Vancouver", PST},
{"America/Virgin", AST},
{"America/Whitehorse", MST},
{"America/Winnipeg", CST},
{"America/Yakutat", AKST},
{"America/Yellowknife", MST},
{"Antarctica/Casey", WST_AUS},
{"Antarctica/Davis", new String[] {"\u81fa\u7dad\u65af\u6642\u9593", "DAVT",
"\u81fa\u7dad\u65af\u590f\u4ee4\u6642\u9593", "DAVST",
"\u81FA\u7DAD\u65AF\u6642\u9593", "DAVT"}},
{"Antarctica/DumontDUrville", new String[] {"Dumont-d'Urville \u6642\u9593", "DDUT",
"Dumont-d'Urville \u590f\u4ee4\u6642\u9593", "DDUST",
"Dumont-d'Urville \u6642\u9593", "DDUT"}},
{"Antarctica/Macquarie", new String[] {"Australian Eastern Standard Time (Macquarie)", "AEST",
"Australian Eastern Daylight Time (Macquarie)", "AEDT",
"Australian Eastern Time (Macquarie)", "AET"}},
{"Antarctica/Mawson", new String[] {"\u83ab\u68ee\u6642\u9593", "MAWT",
"\u83ab\u68ee\u590f\u4ee4\u6642\u9593", "MAWST",
"\u83AB\u68EE\u6642\u9593", "MAWT"}},
{"Antarctica/McMurdo", NZST},
{"Antarctica/Palmer", CLT},
{"Antarctica/Rothera", new String[] {"\u7f85\u897f\u62c9\u6642\u9593", "ROTT",
"\u7f85\u897f\u62c9\u590f\u4ee4\u6642\u9593", "ROTST",
"\u7F85\u897F\u62C9\u6642\u9593", "ROTT"}},
{"Antarctica/South_Pole", NZST},
{"Antarctica/Syowa", new String[] {"\u5915\u6b50\u74e6 (Syowa) \u6642\u9593", "SYOT",
"\u5915\u6b50\u74e6 (Syowa) \u590f\u4ee4\u6642\u9593", "SYOST",
"\u5915\u6B50\u74E6 (Syowa) \u6642\u9593", "SYOT"}},
{"Antarctica/Troll", new String[] {"\u5354\u8abf\u4e16\u754c\u6642\u9593", "UTC",
"\u4e2d\u6b50\u590f\u4ee4\u6642\u9593", "CEST",
"Troll Time", "ATT"}},
{"Antarctica/Vostok", new String[] {"\u4f5b\u65af\u6258 (Vostok) \u6642\u9593", "VOST",
"\u4f5b\u65af\u6258 (Vostok) \u590f\u4ee4\u6642\u9593", "VOSST",
"\u4F5B\u65AF\u6258 (Vostok) \u6642\u9593", "VOST"}},
{"Arctic/Longyearbyen", CET},
{"Asia/Aden", ARAST},
{"Asia/Almaty", new String[] {"Alma-Ata \u6642\u9593", "ALMT",
"Alma-Ata \u590f\u4ee4\u6642\u9593", "ALMST",
"\u963F\u62C9\u6728\u5716\u6642\u9593", "ALMT"}},
{"Asia/Amman", EET},
{"Asia/Anadyr", new String[] {"\u963f\u90a3\u5e95\u6cb3\u6642\u9593", "ANAT",
"\u963f\u90a3\u5e95\u6cb3\u590f\u4ee4\u6642\u9593", "ANAST",
"\u963F\u90A3\u5E95\u6CB3\u6642\u9593", "ANAT"}},
{"Asia/Aqtau", new String[] {"Aqtau \u6642\u9593", "AQTT",
"Aqtau \u590f\u4ee4\u6642\u9593", "AQTST",
"\u963F\u514B\u5957\u6642\u9593", "AQTT"}},
{"Asia/Aqtobe", new String[] {"Aqtobe \u6642\u9593", "AQTT",
"Aqtobe \u590f\u4ee4\u6642\u9593", "AQTST",
"\u963F\u514B\u6258\u5225\u6642\u9593", "AQTT"}},
{"Asia/Ashgabat", TMT},
{"Asia/Ashkhabad", TMT},
{"Asia/Baghdad", ARAST},
{"Asia/Bahrain", ARAST},
{"Asia/Baku", new String[] {"\u4e9e\u585e\u62dc\u7136\u6642\u9593", "AZT",
"\u4e9e\u585e\u62dc\u7136\u590f\u4ee4\u6642\u9593", "AZST",
"\u4E9E\u585E\u62DC\u7136\u6642\u9593", "AZT"}},
{"Asia/Bangkok", ICT},
{"Asia/Beirut", EET},
{"Asia/Bishkek", new String[] {"Kirgizstan \u6642\u9593", "KGT",
"Kirgizstan \u590f\u4ee4\u6642\u9593", "KGST",
"\u5409\u723E\u5409\u65AF\u6642\u9593", "KGT"}},
{"Asia/Brunei", new String[] {"\u6c76\u840a\u6642\u9593", "BNT",
"\u6c76\u840a\u590f\u4ee4\u6642\u9593", "BNST",
"\u6C76\u840A\u6642\u9593", "BNT"}},
{"Asia/Calcutta", IST},
{"Asia/Chita", YAKT},
{"Asia/Choibalsan", new String[] {"\u5de7\u5df4\u5c71 (Choibalsan) \u6642\u9593", "CHOT",
"\u5de7\u5df4\u5c71 (Choibalsan) \u590f\u4ee4\u6642\u9593", "CHOST",
"\u5DE7\u5DF4\u5C71 (Choibalsan) \u6642\u9593", "CHOT"}},
{"Asia/Chongqing", CTT},
{"Asia/Chungking", CTT},
{"Asia/Colombo", IST},
{"Asia/Dacca", BDT},
{"Asia/Dhaka", BDT},
{"Asia/Dili", new String[] {"\u6771\u5e1d\u6c76\u6642\u9593", "TLT",
"\u6771\u5e1d\u6c76\u590f\u4ee4\u6642\u9593", "TLST",
"\u6771\u5E1D\u6C76\u6642\u9593", "TLT"}},
{"Asia/Damascus", EET},
{"Asia/Dubai", GST},
{"Asia/Dushanbe", new String[] {"\u5854\u5409\u514b\u6642\u9593", "TJT",
"\u5854\u5409\u514b\u590f\u4ee4\u6642\u9593", "TJST",
"\u5854\u5409\u514B\u6642\u9593", "TJT"}},
{"Asia/Gaza", EET},
{"Asia/Harbin", CTT},
{"Asia/Hebron", EET},
{"Asia/Ho_Chi_Minh", ICT},
{"Asia/Hong_Kong", HKT},
{"Asia/Hovd", new String[] {"\u4faf\u5fb7 (Hovd) \u6642\u9593", "HOVT",
"\u4faf\u5fb7 (Hovd) \u590f\u4ee4\u6642\u9593", "HOVST",
"\u4FAF\u5FB7 (Hovd) \u6642\u9593", "HOVT"}},
{"Asia/Irkutsk", IRKT},
{"Asia/Istanbul", EET},
{"Asia/Jakarta", WIT},
{"Asia/Jayapura", new String[] {"\u6771\u5370\u5ea6\u5c3c\u897f\u4e9e\u6642\u9593", "WIT",
"\u6771\u5370\u5ea6\u5c3c\u897f\u4e9e\u590f\u65e5\u6642\u9593", "EIST",
"\u6771\u5370\u5EA6\u5C3C\u897F\u4E9E\u6642\u9593", "WIT"}},
{"Asia/Kabul", new String[] {"\u963f\u5bcc\u6c57\u6642\u9593", "AFT",
"\u963f\u5bcc\u6c57\u590f\u4ee4\u6642\u9593", "AFST",
"\u963F\u5BCC\u6C57\u6642\u9593", "AFT"}},
{"Asia/Kamchatka", new String[] {"Petropavlovsk-Kamchatski \u6642\u9593", "PETT",
"Petropavlovsk-Kamchatski \u590f\u4ee4\u6642\u9593", "PETST",
"Petropavlovsk-Kamchatski \u6642\u9593", "PETT"}},
{"Asia/Karachi", PKT},
{"Asia/Kashgar", XJT},
{"Asia/Kathmandu", NPT},
{"Asia/Katmandu", NPT},
{"Asia/Khandyga", YAKT},
{"Asia/Kolkata", IST},
{"Asia/Krasnoyarsk", KRAT},
{"Asia/Kuala_Lumpur", MYT},
{"Asia/Kuching", MYT},
{"Asia/Kuwait", ARAST},
{"Asia/Macao", CTT},
{"Asia/Macau", CTT},
{"Asia/Magadan", new String[] {"Magadan \u6642\u9593", "MAGT",
"Magadan \u590f\u4ee4\u6642\u9593", "MAGST",
"\u99AC\u52A0\u4E39\u6642\u9593", "MAGT"}},
{"Asia/Makassar", CIT},
{"Asia/Manila", new String[] {"Philippines Standard Time", "PST",
"Philippines Daylight Time", "PDT",
"Philippines Time", "PT"}},
{"Asia/Muscat", GST},
{"Asia/Nicosia", EET},
{"Asia/Novokuznetsk", KRAT},
{"Asia/Novosibirsk", NOVT},
{"Asia/Oral", new String[] {"\u6b50\u4f5b\u6642\u9593", "ORAT",
"\u6b50\u4f5b\u590f\u4ee4\u6642\u9593", "ORAST",
"\u6B50\u4F5B\u6642\u9593", "ORAT"}},
{"Asia/Omsk", new String[] {"\u6b50\u59c6\u65af\u514b (Omsk) \u6642\u9593", "OMST",
"\u6b50\u59c6\u65af\u514b (Omsk) \u590f\u4ee4\u6642\u9593", "OMSST",
"\u6B50\u59C6\u65AF\u514B (Omsk) \u6642\u9593", "OMST"}},
{"Asia/Phnom_Penh", ICT},
{"Asia/Pontianak", WIT},
{"Asia/Pyongyang", KST},
{"Asia/Qatar", ARAST},
{"Asia/Qyzylorda", new String[] {"Qyzylorda \u6642\u9593", "QYZT",
"Qyzylorda \u590f\u4ee4\u6642\u9593", "QYZST",
"\u514B\u5B5C\u6D1B\u723E\u9054\u6642\u9593", "QYZT"}},
{"Asia/Rangoon", MMT},
{"Asia/Riyadh", ARAST},
{"Asia/Saigon", ICT},
{"Asia/Sakhalin", new String[] {"\u5eab\u9801\u5cf6\u6642\u9593", "SAKT",
"\u5eab\u9801\u5cf6\u590f\u4ee4\u6642\u9593", "SAKST",
"\u5EAB\u9801\u5CF6\u6642\u9593", "SAKT"}},
{"Asia/Samarkand", UZT},
{"Asia/Seoul", KST},
{"Asia/Singapore", SGT},
{"Asia/Srednekolymsk", new String[] {"Srednekolymsk Time", "SRET",
"Srednekolymsk Daylight Time", "SREDT",
"Srednekolymsk Time", "SRET"}},
{"Asia/Taipei", new String[] {"\u53f0\u7063\u6a19\u6e96\u6642\u9593", "TST",
"\u53f0\u7063\u590f\u4ee4\u6642\u9593", "TDT",
"\u53f0\u7063\u6642\u9593", "TT"}},
{"Asia/Tel_Aviv", ISRAEL},
{"Asia/Tashkent", UZT},
{"Asia/Tbilisi", new String[] {"\u55ac\u6cbb\u4e9e\u6642\u9593", "GET",
"\u55ac\u6cbb\u4e9e\u590f\u4ee4\u6642\u9593", "GEST",
"\u55AC\u6CBB\u4E9E\u6642\u9593", "GET"}},
{"Asia/Tehran", IRT},
{"Asia/Thimbu", BTT},
{"Asia/Thimphu", BTT},
{"Asia/Ujung_Pandang", CIT},
{"Asia/Ulaanbaatar", ULAT},
{"Asia/Ulan_Bator", ULAT},
{"Asia/Urumqi", XJT},
{"Asia/Ust-Nera", new String[] {"\u70CF\u65AF\u5167\u62C9 (Ust-Nera) \u6642\u9593", "VLAT",
"\u70CF\u65AF\u5167\u62C9 (Ust-Nera) \u590F\u4EE4\u6642\u9593", "VLAST",
"\u70CF\u65AF\u5167\u62C9 (Ust-Nera) \u6642\u9593", "VLAT"}},
{"Asia/Vientiane", ICT},
{"Asia/Vladivostok", new String[] {"\u6d77\u53c3\u5d34\u6642\u9593", "VLAT",
"\u6d77\u53c3\u5d34\u590f\u4ee4\u6642\u9593", "VLAST",
"\u6D77\u53C3\u5D34\u6642\u9593", "VLAT"}},
{"Asia/Yakutsk", YAKT},
{"Asia/Yangon", MMT},
{"Asia/Yekaterinburg", new String[] {"Yekaterinburg \u6642\u9593", "YEKT",
"Yekaterinburg \u590f\u4ee4\u6642\u9593", "YEKST",
"\u8449\u5361\u6377\u7433\u5821\u6642\u9593", "YEKT"}},
{"Asia/Yerevan", ARMT},
{"Atlantic/Azores", new String[] {"\u4e9e\u901f\u723e\u7fa4\u5cf6\u6642\u9593", "AZOT",
"\u4e9e\u901f\u723e\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "AZOST",
"\u4E9E\u901F\u723E\u7FA4\u5CF6\u6642\u9593", "AZOT"}},
{"Atlantic/Bermuda", AST},
{"Atlantic/Canary", WET},
{"Atlantic/Cape_Verde", new String[] {"\u4f5b\u5fb7\u89d2\u6642\u9593", "CVT",
"\u4f5b\u5fb7\u89d2\u590f\u4ee4\u6642\u9593", "CVST",
"\u4F5B\u5FB7\u89D2\u6642\u9593", "CVT"}},
{"Atlantic/Faeroe", WET},
{"Atlantic/Faroe", WET},
{"Atlantic/Jan_Mayen", CET},
{"Atlantic/Madeira", WET},
{"Atlantic/Reykjavik", GMT},
{"Atlantic/South_Georgia", new String[] {"\u5357\u55ac\u6cbb\u4e9e\u6a19\u6e96\u6642\u9593", "GST",
"\u5357\u55ac\u6cbb\u4e9e\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "GDT",
"\u5357\u55AC\u6CBB\u4E9E\u6642\u9593", "GT"}},
{"Atlantic/St_Helena", GMT},
{"Atlantic/Stanley", new String[] {"\u798f\u514b\u862d\u7fa4\u5cf6\u6642\u9593", "FKT",
"\u798f\u514b\u862d\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "FKST",
"\u798F\u514B\u862D\u7FA4\u5CF6\u6642\u9593", "FKT"}},
{"Australia/ACT", EST_NSW},
{"Australia/Adelaide", ADELAIDE},
{"Australia/Brisbane", BRISBANE},
{"Australia/Broken_Hill", BROKEN_HILL},
{"Australia/Canberra", EST_NSW},
{"Australia/Currie", EST_NSW},
{"Australia/Darwin", DARWIN},
{"Australia/Eucla", new String[] {"\u4E2D\u897F\u90E8\u6A19\u6E96\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "ACWST",
"\u4E2D\u897F\u90E8\u590F\u4EE4\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "ACWDT",
"\u4E2D\u897F\u90E8\u6642\u9593 (\u6FB3\u5927\u5229\u4E9E)", "ACWT"}},
{"Australia/Hobart", TASMANIA},
{"Australia/LHI", LORD_HOWE},
{"Australia/Lindeman", BRISBANE},
{"Australia/Lord_Howe", LORD_HOWE},
{"Australia/Melbourne", VICTORIA},
{"Australia/North", DARWIN},
{"Australia/NSW", EST_NSW},
{"Australia/Perth", WST_AUS},
{"Australia/Queensland", BRISBANE},
{"Australia/South", ADELAIDE},
{"Australia/Sydney", EST_NSW},
{"Australia/Tasmania", TASMANIA},
{"Australia/Victoria", VICTORIA},
{"Australia/West", WST_AUS},
{"Australia/Yancowinna", BROKEN_HILL},
{"BET", BRT},
{"BST", BDT},
{"Brazil/Acre", ACT},
{"Brazil/DeNoronha", NORONHA},
{"Brazil/East", BRT},
{"Brazil/West", AMT},
{"Canada/Atlantic", AST},
{"Canada/Central", CST},
{"Canada/Eastern", EST},
{"Canada/Mountain", MST},
{"Canada/Newfoundland", NST},
{"Canada/Pacific", PST},
{"Canada/Yukon", MST},
{"Canada/Saskatchewan", CST},
{"CAT", CAT},
{"CET", CET},
{"Chile/Continental", CLT},
{"Chile/EasterIsland", EASTER},
{"CST6CDT", CST},
{"Cuba", CUBA},
{"EAT", EAT},
{"EET", EET},
{"Egypt", EET},
{"Eire", DUBLIN},
{"EST5EDT", EST},
{"Etc/Greenwich", GMT},
{"Etc/UCT", UTC},
{"Etc/Universal", UTC},
{"Etc/UTC", UTC},
{"Etc/Zulu", UTC},
{"Europe/Amsterdam", CET},
{"Europe/Andorra", CET},
{"Europe/Athens", EET},
{"Europe/Belfast", GMTBST},
{"Europe/Belgrade", CET},
{"Europe/Berlin", CET},
{"Europe/Bratislava", CET},
{"Europe/Brussels", CET},
{"Europe/Budapest", CET},
{"Europe/Busingen", CET},
{"Europe/Chisinau", EET},
{"Europe/Copenhagen", CET},
{"Europe/Dublin", DUBLIN},
{"Europe/Gibraltar", CET},
{"Europe/Guernsey", GMTBST},
{"Europe/Helsinki", EET},
{"Europe/Isle_of_Man", GMTBST},
{"Europe/Istanbul", EET},
{"Europe/Jersey", GMTBST},
{"Europe/Kaliningrad", EET},
{"Europe/Kiev", EET},
{"Europe/Lisbon", WET},
{"Europe/Ljubljana", CET},
{"Europe/London", GMTBST},
{"Europe/Luxembourg", CET},
{"Europe/Madrid", CET},
{"Europe/Malta", CET},
{"Europe/Mariehamn", EET},
{"Europe/Minsk", MSK},
{"Europe/Monaco", CET},
{"Europe/Moscow", MSK},
{"Europe/Nicosia", EET},
{"Europe/Oslo", CET},
{"Europe/Podgorica", CET},
{"Europe/Prague", CET},
{"Europe/Riga", EET},
{"Europe/Rome", CET},
{"Europe/Samara", new String[] {"\u6c99\u99ac\u62c9\u6642\u9593", "SAMT",
"\u6c99\u99ac\u62c9\u590f\u4ee4\u6642\u9593", "SAMST",
"\u6C99\u99AC\u62C9\u6642\u9593", "SAMT"}},
{"Europe/San_Marino", CET},
{"Europe/Sarajevo", CET},
{"Europe/Simferopol", MSK},
{"Europe/Skopje", CET},
{"Europe/Sofia", EET},
{"Europe/Stockholm", CET},
{"Europe/Tallinn", EET},
{"Europe/Tirane", CET},
{"Europe/Tiraspol", EET},
{"Europe/Uzhgorod", EET},
{"Europe/Vaduz", CET},
{"Europe/Vatican", CET},
{"Europe/Vienna", CET},
{"Europe/Vilnius", EET},
{"Europe/Volgograd", MSK},
{"Europe/Warsaw", CET},
{"Europe/Zagreb", CET},
{"Europe/Zaporozhye", EET},
{"Europe/Zurich", CET},
{"GB", GMTBST},
{"GB-Eire", GMTBST},
{"Greenwich", GMT},
{"Hongkong", HKT},
{"Iceland", GMT},
{"Iran", IRT},
{"IST", IST},
{"Indian/Antananarivo", EAT},
{"Indian/Chagos", new String[] {"\u5370\u5ea6\u6d0b\u5730\u5340\u6642\u9593", "IOT",
"\u5370\u5ea6\u6d0b\u5730\u5340\u590f\u4ee4\u6642\u9593", "IOST",
"\u82F1\u5C6C\u5370\u5EA6\u6D0B\u5730\u5340", "IOT"}},
{"Indian/Christmas", new String[] {"\u8056\u8a95\u5cf6\u6642\u9593", "CXT",
"\u8056\u8a95\u5cf6\u590f\u4ee4\u6642\u9593", "CXST",
"\u8056\u8A95\u5CF6\u6642\u9593", "CIT"}},
{"Indian/Cocos", new String[] {"\u53ef\u53ef\u65af\u7fa4\u5cf6\u6642\u9593", "CCT",
"\u53ef\u53ef\u65af\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "CCST",
"\u53EF\u53EF\u65AF\u7FA4\u5CF6\u6642\u9593", "CCT"}},
{"Indian/Comoro", EAT},
{"Indian/Kerguelen", new String[] {"\u6cd5\u570b\u5357\u534a\u7403\u53ca\u5357\u6975\u5c6c\u5730\u6642\u9593", "TFT",
"\u6cd5\u570b\u5357\u534a\u7403\u53ca\u5357\u6975\u5c6c\u5730\u590f\u4ee4\u6642\u9593", "TFST",
"\u6CD5\u570B\u5357\u534A\u7403\u53CA\u5357\u6975\u5C6C\u5730\u6642\u9593", "TFT"}},
{"Indian/Mahe", new String[] {"\u585e\u5e2d\u723e\u7fa4\u5cf6\u6642\u9593", "SCT",
"\u585e\u5e2d\u723e\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "SCST",
"\u585E\u5E2D\u723E\u7FA4\u5CF6\u6642\u9593", "SCT"}},
{"Indian/Maldives", new String[] {"\u99ac\u723e\u5730\u592b\u6642\u9593", "MVT",
"\u99ac\u723e\u5730\u592b\u590f\u4ee4\u6642\u9593", "MVST",
"\u99AC\u723E\u5730\u592B\u6642\u9593", "MVT"}},
{"Indian/Mauritius", new String[] {"\u6469\u91cc\u897f\u65af\u6642\u9593", "MUT",
"\u6469\u91cc\u897f\u65af\u590f\u4ee4\u6642\u9593", "MUST",
"\u6469\u91CC\u897F\u65AF\u6642\u9593", "MUT"}},
{"Indian/Mayotte", EAT},
{"Indian/Reunion", new String[] {"\u7559\u5c3c\u65fa\u5cf6\u6642\u9593", "RET",
"\u7559\u5c3c\u65fa\u5cf6\u590f\u4ee4\u6642\u9593", "REST",
"\u7559\u5C3C\u65FA\u5CF6\u6642\u9593", "RET"}},
{"Israel", ISRAEL},
{"Jamaica", EST},
{"Japan", JST},
{"Kwajalein", MHT},
{"Libya", EET},
{"MET", new String[] {"\u4e2d\u6b50\u6642\u9593", "MET",
"\u4e2d\u6b50\u590f\u4ee4\u6642\u9593", "MEST",
"MET", "MET"}},
{"Mexico/BajaNorte", PST},
{"Mexico/BajaSur", MST},
{"Mexico/General", CST},
{"MIT", WST_SAMOA},
{"MST7MDT", MST},
{"Navajo", MST},
{"NET", ARMT},
{"NST", NZST},
{"NZ", NZST},
{"NZ-CHAT", CHAST},
{"PLT", PKT},
{"Portugal", WET},
{"PRT", AST},
{"Pacific/Apia", WST_SAMOA},
{"Pacific/Auckland", NZST},
{"Pacific/Bougainville", new String[] {"Bougainville Standard Time", "BST",
"Bougainville Daylight Time", "BST",
"Bougainville Time", "BT"}},
{"Pacific/Chatham", CHAST},
{"Pacific/Chuuk", CHUT},
{"Pacific/Easter", EASTER},
{"Pacific/Efate", new String[] {"\u74e6\u5974\u963f\u5716\u6642\u9593", "VUT",
"\u74e6\u5974\u963f\u5716\u590f\u4ee4\u6642\u9593", "VUST",
"\u74E6\u5974\u963F\u5716\u6642\u9593", "VUT"}},
{"Pacific/Enderbury", new String[] {"\u83f2\u5c3c\u514b\u65af\u7fa4\u5cf6\u6642\u9593", "PHOT",
"\u83f2\u5c3c\u514b\u65af\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "PHOST",
"\u83F2\u5C3C\u514B\u65AF\u7FA4\u5CF6\u6642\u9593", "PHOT"}},
{"Pacific/Fakaofo", new String[] {"\u6258\u514b\u52de\u7fa4\u5cf6\u6642\u9593", "TKT",
"\u6258\u514b\u52de\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "TKST",
"\u6258\u514B\u52DE\u7FA4\u5CF6\u6642\u9593", "TKT"}},
{"Pacific/Fiji", new String[] {"\u6590\u6fdf\u6642\u9593", "FJT",
"\u6590\u6fdf\u590f\u4ee4\u6642\u9593", "FJST",
"\u6590\u6FDF\u6642\u9593", "FJT"}},
{"Pacific/Funafuti", new String[] {"\u5410\u9b6f\u74e6\u6642\u9593", "TVT",
"\u5410\u9b6f\u74e6\u590f\u4ee4\u6642\u9593", "TVST",
"\u5410\u74E6\u9B6F\u6642\u9593", "TVT"}},
{"Pacific/Galapagos", new String[] {"\u52a0\u62c9\u5df4\u54e5\u6642\u9593", "GALT",
"\u52a0\u62c9\u5df4\u54e5\u590f\u4ee4\u6642\u9593", "GALST",
"\u52A0\u62C9\u5DF4\u54E5\u6642\u9593", "GALT"}},
{"Pacific/Gambier", GAMBIER},
{"Pacific/Guadalcanal", SBT},
{"Pacific/Guam", ChST},
{"Pacific/Johnston", HST},
{"Pacific/Kiritimati", new String[] {"Line Is. \u6642\u9593", "LINT",
"Line Is. \u590f\u4ee4\u6642\u9593", "LINST",
"\u5217\u5DBC\u7FA4\u5CF6\u6642\u9593", "LINT"}},
{"Pacific/Kosrae", new String[] {"Kosrae \u6642\u9593", "KOST",
"Kosrae \u590f\u4ee4\u6642\u9593", "KOSST",
"Kosrae \u6642\u9593", "KOST"}},
{"Pacific/Kwajalein", MHT},
{"Pacific/Majuro", MHT},
{"Pacific/Marquesas", new String[] {"\u99ac\u514b\u85a9\u65af\u6642\u9593", "MART",
"\u99ac\u514b\u85a9\u65af\u590f\u4ee4\u6642\u9593", "MARST",
"\u99AC\u514B\u85A9\u65AF\u6642\u9593", "MART"}},
{"Pacific/Midway", SAMOA},
{"Pacific/Nauru", new String[] {"\u8afe\u9b6f\u6642\u9593", "NRT",
"\u8afe\u9b6f\u590f\u4ee4\u6642\u9593", "NRST",
"\u8AFE\u9B6F\u6642\u9593", "NRT"}},
{"Pacific/Niue", new String[] {"\u7d10\u5a01\u5cf6\u6642\u9593", "NUT",
"\u7d10\u5a01\u5cf6\u590f\u4ee4\u6642\u9593", "NUST",
"\u7D10\u5A01\u5CF6\u6642\u9593", "NUT"}},
{"Pacific/Norfolk", new String[] {"\u8afe\u798f\u514b\u6642\u9593", "NFT",
"\u8afe\u798f\u514b\u590f\u4ee4\u6642\u9593", "NFST",
"\u8AFE\u798F\u514B\u6642\u9593", "NFT"}},
{"Pacific/Noumea", new String[] {"\u65b0\u52a0\u52d2\u591a\u5c3c\u4e9e\u6642\u9593", "NCT",
"\u65b0\u52a0\u52d2\u591a\u5c3c\u4e9e\u590f\u4ee4\u6642\u9593", "NCST",
"\u65B0\u52A0\u52D2\u591A\u5C3C\u4E9E\u6642\u9593", "NCT"}},
{"Pacific/Pago_Pago", SAMOA},
{"Pacific/Palau", new String[] {"\u5e1b\u7409\u6642\u9593", "PWT",
"\u5e1b\u7409\u590f\u4ee4\u6642\u9593", "PWST",
"\u5E1B\u7409\u6642\u9593", "PWT"}},
{"Pacific/Pitcairn", PITCAIRN},
{"Pacific/Pohnpei", PONT},
{"Pacific/Ponape", PONT},
{"Pacific/Port_Moresby", new String[] {"\u5df4\u5e03\u4e9e\u65b0\u5e7e\u5167\u4e9e\u6642\u9593", "PGT",
"\u5df4\u5e03\u4e9e\u65b0\u5e7e\u5167\u4e9e\u590f\u4ee4\u6642\u9593", "PGST",
"\u5DF4\u5E03\u4E9E\u65B0\u5E7E\u5167\u4E9E\u6642\u9593", "PGT"}},
{"Pacific/Rarotonga", new String[] {"\u5eab\u514b\u7fa4\u5cf6\u6642\u9593", "CKT",
"\u5eab\u514b\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "CKHST",
"\u5EAB\u514B\u7FA4\u5CF6\u6642\u9593", "CKT"}},
{"Pacific/Saipan", ChST},
{"Pacific/Samoa", SAMOA},
{"Pacific/Tahiti", new String[] {"\u5927\u6eaa\u5730\u5cf6\u6642\u9593", "TAHT",
"\u5927\u6eaa\u5730\u5cf6\u590f\u4ee4\u6642\u9593", "TAHST",
"\u5927\u6EAA\u5730\u6642\u9593", "TAHT"}},
{"Pacific/Tarawa", new String[] {"\u5409\u4f2f\u7279\u7fa4\u5cf6\u6642\u9593", "GILT",
"\u5409\u4f2f\u7279\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "GILST",
"\u5409\u4F2F\u7279\u7FA4\u5CF6\u6642\u9593", "GILT"}},
{"Pacific/Tongatapu", new String[] {"\u6771\u52a0\u6642\u9593", "TOT",
"\u6771\u52a0\u590f\u4ee4\u6642\u9593", "TOST",
"\u6771\u52A0\u6642\u9593", "TOT"}},
{"Pacific/Truk", CHUT},
{"Pacific/Wake", new String[] {"\u5a01\u514b\u6642\u9593", "WAKT",
"\u5a01\u514b\u590f\u4ee4\u6642\u9593", "WAKST",
"\u5A01\u514B\u6642\u9593", "WAKT"}},
{"Pacific/Wallis", new String[] {"\u74e6\u5229\u65af\u53ca\u798f\u675c\u7d0d\u7fa4\u5cf6\u6642\u9593", "WFT",
"\u74e6\u5229\u65af\u53ca\u798f\u675c\u7d0d\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "WFST",
"\u74E6\u5229\u65AF\u53CA\u798F\u675C\u7D0D\u7FA4\u5CF6\u6642\u9593", "WFT"}},
{"Pacific/Yap", CHUT},
{"Poland", CET},
{"PRC", CTT},
{"PST8PDT", PST},
{"ROK", KST},
{"Singapore", SGT},
{"SST", SBT},
{"SystemV/AST4", AST},
{"SystemV/AST4ADT", AST},
{"SystemV/CST6", CST},
{"SystemV/CST6CDT", CST},
{"SystemV/EST5", EST},
{"SystemV/EST5EDT", EST},
{"SystemV/HST10", HST},
{"SystemV/MST7", MST},
{"SystemV/MST7MDT", MST},
{"SystemV/PST8", PST},
{"SystemV/PST8PDT", PST},
{"SystemV/YST9", AKST},
{"SystemV/YST9YDT", AKST},
{"Turkey", EET},
{"UCT", UTC},
{"Universal", UTC},
{"US/Alaska", AKST},
{"US/Aleutian", HST},
{"US/Arizona", MST},
{"US/Central", CST},
{"US/Eastern", EST},
{"US/Hawaii", HST},
{"US/Indiana-Starke", CST},
{"US/East-Indiana", EST},
{"US/Michigan", EST},
{"US/Mountain", MST},
{"US/Pacific", PST},
{"US/Samoa", SAMOA},
{"VST", ICT},
{"W-SU", MSK},
{"WET", WET},
{"Zulu", UTC},
};
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_TW.java |
180,178 | package jadx.core.dex.visitors.regions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.dex.attributes.AFlag;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.attributes.nodes.EdgeInsnAttr;
import jadx.core.dex.instructions.InsnType;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.IBlock;
import jadx.core.dex.nodes.IContainer;
import jadx.core.dex.nodes.IRegion;
import jadx.core.dex.nodes.InsnContainer;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.regions.Region;
import jadx.core.dex.regions.SwitchRegion;
import jadx.core.dex.regions.SynchronizedRegion;
import jadx.core.dex.regions.loops.LoopRegion;
import jadx.core.dex.visitors.AbstractVisitor;
import jadx.core.dex.visitors.shrink.CodeShrinkVisitor;
import jadx.core.utils.InsnRemover;
import jadx.core.utils.RegionUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxException;
/**
* Pack blocks into regions for code generation
*/
public class RegionMakerVisitor extends AbstractVisitor {
private static final Logger LOG = LoggerFactory.getLogger(RegionMakerVisitor.class);
private static final IRegionVisitor POST_REGION_VISITOR = new PostRegionVisitor();
@Override
public void visit(MethodNode mth) throws JadxException {
if (mth.isNoCode() || mth.getBasicBlocks().isEmpty()) {
return;
}
RegionMaker rm = new RegionMaker(mth);
RegionStack state = new RegionStack(mth);
// fill region structure
BlockNode startBlock = Utils.first(mth.getEnterBlock().getCleanSuccessors());
mth.setRegion(rm.makeRegion(startBlock, state));
if (!mth.isNoExceptionHandlers()) {
IRegion expOutBlock = rm.processTryCatchBlocks(mth);
if (expOutBlock != null) {
mth.getRegion().add(expOutBlock);
}
}
postProcessRegions(mth);
}
private static void postProcessRegions(MethodNode mth) {
processForceInlineInsns(mth);
// make try-catch regions
ProcessTryCatchRegions.process(mth);
DepthRegionTraversal.traverse(mth, POST_REGION_VISITOR);
CleanRegions.process(mth);
if (mth.getAccessFlags().isSynchronized()) {
removeSynchronized(mth);
}
}
private static void processForceInlineInsns(MethodNode mth) {
boolean needShrink = mth.getBasicBlocks().stream()
.flatMap(block -> block.getInstructions().stream())
.anyMatch(insn -> insn.contains(AFlag.FORCE_ASSIGN_INLINE));
if (needShrink) {
CodeShrinkVisitor.shrinkMethod(mth);
}
}
private static final class PostRegionVisitor extends AbstractRegionVisitor {
@Override
public void leaveRegion(MethodNode mth, IRegion region) {
if (region instanceof LoopRegion) {
// merge conditions in loops
LoopRegion loop = (LoopRegion) region;
loop.mergePreCondition();
} else if (region instanceof SwitchRegion) {
// insert 'break' in switch cases (run after try/catch insertion)
processSwitch(mth, (SwitchRegion) region);
} else if (region instanceof Region) {
insertEdgeInsn((Region) region);
}
}
/**
* Insert insn block from edge insn attribute.
*/
private static void insertEdgeInsn(Region region) {
List<IContainer> subBlocks = region.getSubBlocks();
if (subBlocks.isEmpty()) {
return;
}
IContainer last = subBlocks.get(subBlocks.size() - 1);
List<EdgeInsnAttr> edgeInsnAttrs = last.getAll(AType.EDGE_INSN);
if (edgeInsnAttrs.isEmpty()) {
return;
}
EdgeInsnAttr insnAttr = edgeInsnAttrs.get(0);
if (!insnAttr.getStart().equals(last)) {
return;
}
if (last instanceof BlockNode) {
BlockNode block = (BlockNode) last;
if (block.getInstructions().isEmpty()) {
block.getInstructions().add(insnAttr.getInsn());
return;
}
}
List<InsnNode> insns = Collections.singletonList(insnAttr.getInsn());
region.add(new InsnContainer(insns));
}
private static void processSwitch(MethodNode mth, SwitchRegion sw) {
for (IContainer c : sw.getBranches()) {
if (c instanceof Region) {
Set<IBlock> blocks = new HashSet<>();
RegionUtils.getAllRegionBlocks(c, blocks);
if (blocks.isEmpty()) {
addBreakToContainer((Region) c);
} else {
for (IBlock block : blocks) {
if (block instanceof BlockNode) {
addBreakForBlock(mth, c, blocks, (BlockNode) block);
}
}
}
}
}
}
private static void addBreakToContainer(Region c) {
if (RegionUtils.hasExitEdge(c)) {
return;
}
List<InsnNode> insns = new ArrayList<>(1);
insns.add(new InsnNode(InsnType.BREAK, 0));
c.add(new InsnContainer(insns));
}
private static void addBreakForBlock(MethodNode mth, IContainer c, Set<IBlock> blocks, BlockNode bn) {
for (BlockNode s : bn.getCleanSuccessors()) {
if (!blocks.contains(s)
&& !bn.contains(AFlag.ADDED_TO_REGION)
&& !s.contains(AFlag.FALL_THROUGH)) {
addBreak(mth, c, bn);
return;
}
}
}
private static void addBreak(MethodNode mth, IContainer c, BlockNode bn) {
IContainer blockContainer = RegionUtils.getBlockContainer(c, bn);
if (blockContainer instanceof Region) {
addBreakToContainer((Region) blockContainer);
} else if (c instanceof Region) {
addBreakToContainer((Region) c);
} else {
LOG.warn("Can't insert break, container: {}, block: {}, mth: {}", blockContainer, bn, mth);
}
}
}
private static void removeSynchronized(MethodNode mth) {
Region startRegion = mth.getRegion();
List<IContainer> subBlocks = startRegion.getSubBlocks();
if (!subBlocks.isEmpty() && subBlocks.get(0) instanceof SynchronizedRegion) {
SynchronizedRegion synchRegion = (SynchronizedRegion) subBlocks.get(0);
InsnNode synchInsn = synchRegion.getEnterInsn();
if (!synchInsn.getArg(0).isThis()) {
LOG.warn("In synchronized method {}, top region not synchronized by 'this' {}", mth, synchInsn);
return;
}
// replace synchronized block with inner region
startRegion.getSubBlocks().set(0, synchRegion.getRegion());
// remove 'monitor-enter' instruction
InsnRemover.remove(mth, synchInsn);
// remove 'monitor-exit' instruction
for (InsnNode exit : synchRegion.getExitInsns()) {
InsnRemover.remove(mth, exit);
}
// run region cleaner again
CleanRegions.process(mth);
// assume that CodeShrinker will be run after this
}
}
}
| skylot/jadx | jadx-core/src/main/java/jadx/core/dex/visitors/regions/RegionMakerVisitor.java |
180,179 | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fedai.osx.core.jvm;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
/**
* 类描述:JVM 线程信息工具类
**/
public class JVMThreadUtils {
static private ThreadMXBean threadMXBean;
static {
threadMXBean = ManagementFactory.getThreadMXBean();
}
/**
* Daemon线程总量
*
* @return
*/
static public int getDaemonThreadCount() {
return threadMXBean.getDaemonThreadCount();
}
/**
* 当前线程总量
*
* @return
*/
static public int getThreadCount() {
return threadMXBean.getThreadCount();
}
/**
* 获取线程数量峰值(从启动或resetPeakThreadCount()方法重置开始统计)
*
* @return
*/
static public int getPeakThreadCount() {
return threadMXBean.getPeakThreadCount();
}
/**
* 获取线程数量峰值(从启动或resetPeakThreadCount()方法重置开始统计),并重置
*
* @return
* @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
*/
static public int getAndResetPeakThreadCount() {
int count = threadMXBean.getPeakThreadCount();
resetPeakThreadCount();
return count;
}
/**
* 重置线程数量峰值
*
* @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
*/
static public void resetPeakThreadCount() {
threadMXBean.resetPeakThreadCount();
}
/**
* 死锁线程总量
*
* @return
* @Throws IllegalStateException 没有权限或JVM不支持的操作
*/
static public int getDeadLockedThreadCount() {
try {
long[] deadLockedThreadIds = threadMXBean.findDeadlockedThreads();
if (deadLockedThreadIds == null) {
return 0;
}
return deadLockedThreadIds.length;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| FederatedAI/FATE | java/osx/osx-core/src/main/java/org/fedai/osx/core/jvm/JVMThreadUtils.java |
180,180 | package com.foobnix.tts;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.EngineInfo;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.support.v4.media.session.MediaSessionCompat;
import android.widget.Toast;
import com.foobnix.android.utils.IO;
import com.foobnix.android.utils.LOG;
import com.foobnix.android.utils.MyMath;
import com.foobnix.android.utils.ResultResponse;
import com.foobnix.android.utils.TxtUtils;
import com.foobnix.android.utils.Vibro;
import com.foobnix.mobi.parser.IOUtils;
import com.foobnix.mobi.parser.MobiParserIS;
import com.foobnix.model.AppBookmark;
import com.foobnix.model.AppSP;
import com.foobnix.model.AppState;
import com.foobnix.pdf.info.BookmarksData;
import com.foobnix.pdf.info.R;
import com.foobnix.pdf.info.model.BookCSS;
import com.foobnix.pdf.info.wrapper.DocumentController;
import com.foobnix.sys.TempHolder;
import com.github.axet.lamejni.Lame;
import com.foobnix.LibreraApp;
import org.greenrobot.eventbus.EventBus;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class TTSEngine {
public static final String FINISHED_SIGNAL = "Finished";
public static final String STOP_SIGNAL = "Stoped";
public static final String UTTERANCE_ID_DONE = "LirbiReader";
public static final String WAV = ".wav";
public static final String MP3 = ".mp3";
private static final String TAG = "TTSEngine";
private static TTSEngine INSTANCE = new TTSEngine();
volatile TextToSpeech ttsEngine;
volatile MediaPlayer mp;
Timer mTimer;
Object helpObject = new Object();
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, String> mapTemp = new HashMap<String, String>();
OnInitListener listener = new OnInitListener() {
@Override
public void onInit(int status) {
LOG.d(TAG, "onInit", "SUCCESS", status == TextToSpeech.SUCCESS);
if (status == TextToSpeech.ERROR) {
Toast.makeText(LibreraApp.context, R.string.msg_unexpected_error, Toast.LENGTH_LONG).show();
}
}
};
private String text = "";
{
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, UTTERANCE_ID_DONE);
}
{
mapTemp.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "Temp");
}
public static TTSEngine get() {
return INSTANCE;
}
public static AppBookmark fastTTSBookmakr(DocumentController dc) {
return fastTTSBookmakr(dc.getActivity(), dc.getCurrentBook().getPath(), dc.getCurentPageFirst1(), dc.getPageCount());
}
public static AppBookmark fastTTSBookmakr(Context c, String bookPath, int page, int pages) {
LOG.d("fastTTSBookmakr", page, pages);
if (pages == 0) {
LOG.d("fastTTSBookmakr skip");
return null;
}
boolean hasBookmark = BookmarksData.get().hasBookmark(bookPath, page, pages);
if (!hasBookmark) {
final AppBookmark bookmark = new AppBookmark(bookPath, c.getString(R.string.fast_bookmark), MyMath.percent(page, pages));
BookmarksData.get().add(bookmark);
String TEXT = c.getString(R.string.fast_bookmark) + " " + TxtUtils.LONG_DASH1 + " " + c.getString(R.string.page) + " " + page + "";
Toast.makeText(c, TEXT, Toast.LENGTH_SHORT).show();
return bookmark;
}
Vibro.vibrate();
return null;
}
public static String engineToString(EngineInfo info) {
return info.label;
}
public void shutdown() {
LOG.d(TAG, "shutdown");
synchronized (helpObject) {
if (ttsEngine != null) {
ttsEngine.shutdown();
}
ttsEngine = null;
}
}
public TextToSpeech getTTS() {
return getTTS(null);
}
public TextToSpeech getTTS(OnInitListener onLisnter) {
if (LibreraApp.context == null) {
return null;
}
synchronized (helpObject) {
if (TTSEngine.get().isMp3() && mp == null) {
TTSEngine.get().loadMP3(BookCSS.get().mp3BookPathGet());
}
if (ttsEngine != null) {
return ttsEngine;
}
if (onLisnter == null) {
onLisnter = listener;
}
ttsEngine = new TextToSpeech(LibreraApp.context, onLisnter);
}
return ttsEngine;
}
public synchronized boolean isShutdown() {
return ttsEngine == null;
}
public void stop() {
stop(null);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public void stop(MediaSessionCompat mediaSessionCompat) {
if (mediaSessionCompat != null) {
mediaSessionCompat.setActive(false);
}
if (!AppState.get().allowOtherMusic) {
try {
AudioManager mAudioManager = (AudioManager) LibreraApp.context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.abandonAudioFocus(null);
} catch (Exception e) {
LOG.e(e);
}
}
LOG.d(TAG, "stop");
synchronized (helpObject) {
if (ttsEngine != null) {
if (Build.VERSION.SDK_INT >= 15) {
ttsEngine.setOnUtteranceProgressListener(null);
} else {
ttsEngine.setOnUtteranceCompletedListener(null);
}
ttsEngine.stop();
EventBus.getDefault().post(new TtsStatus());
}
}
}
public void stopDestroy() {
LOG.d(TAG, "stop");
TxtUtils.dictHash = "";
synchronized (helpObject) {
if (ttsEngine != null) {
ttsEngine.shutdown();
}
ttsEngine = null;
}
AppSP.get().lastBookParagraph = 0;
}
public TextToSpeech setTTSWithEngine(String engine) {
shutdown();
synchronized (helpObject) {
ttsEngine = new TextToSpeech(LibreraApp.context, listener, engine);
}
return ttsEngine;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public synchronized void speek(final String text) {
this.text = text;
if (AppSP.get().tempBookPage != AppSP.get().lastBookPage) {
AppSP.get().tempBookPage = AppSP.get().lastBookPage;
AppSP.get().lastBookParagraph = 0;
}
LOG.d(TAG, "speek", AppSP.get().lastBookPage, "par", AppSP.get().lastBookParagraph);
if (TxtUtils.isEmpty(text)) {
return;
}
if (ttsEngine == null) {
LOG.d("getTTS-status was null");
} else {
LOG.d("getTTS-status not null");
}
ttsEngine = getTTS(new OnInitListener() {
@Override
public void onInit(int status) {
LOG.d("getTTS-status", status);
if (status == TextToSpeech.SUCCESS) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
speek(text);
}
}
});
ttsEngine.setPitch(AppState.get().ttsPitch);
if (AppState.get().ttsSpeed == 0.0f) {
AppState.get().ttsSpeed = 0.01f;
}
ttsEngine.setSpeechRate(AppState.get().ttsSpeed);
LOG.d(TAG, "Speek s", AppState.get().ttsSpeed);
LOG.d(TAG, "Speek AppSP.get().lastBookParagraph", AppSP.get().lastBookParagraph);
if (AppState.get().ttsPauseDuration > 0 && text.contains(TxtUtils.TTS_PAUSE)) {
String[] parts = text.split(TxtUtils.TTS_PAUSE);
ttsEngine.playSilence(0l, TextToSpeech.QUEUE_FLUSH, mapTemp);
for (int i = AppSP.get().lastBookParagraph; i < parts.length; i++) {
String big = parts[i];
big = big.trim();
if (TxtUtils.isNotEmpty(big)) {
if (big.length() == 1 && !Character.isLetterOrDigit(big.charAt(0))) {
LOG.d("Skip: " + big);
continue;
}
if (big.contains(TxtUtils.TTS_SKIP)) {
continue;
}
if (big.contains(TxtUtils.TTS_STOP)) {
HashMap<String, String> mapStop = new HashMap<String, String>();
mapStop.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, STOP_SIGNAL);
ttsEngine.playSilence(AppState.get().ttsPauseDuration, TextToSpeech.QUEUE_ADD, mapStop);
LOG.d("Add stop signal");
}
if (big.contains(TxtUtils.TTS_NEXT)) {
ttsEngine.playSilence(0L, TextToSpeech.QUEUE_ADD, map);
LOG.d("next-page signal");
break;
}
HashMap<String, String> mapTemp1 = new HashMap<String, String>();
mapTemp1.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, FINISHED_SIGNAL + i);
ttsEngine.speak(big, TextToSpeech.QUEUE_ADD, mapTemp1);
ttsEngine.playSilence(AppState.get().ttsPauseDuration, TextToSpeech.QUEUE_ADD, mapTemp);
LOG.d("pageHTML-parts", i, big);
}
}
ttsEngine.playSilence(0L, TextToSpeech.QUEUE_ADD, map);
} else {
String textToPlay = text.replace(TxtUtils.TTS_PAUSE, "");
LOG.d("pageHTML-parts-single", text);
ttsEngine.speak(textToPlay, TextToSpeech.QUEUE_FLUSH, map);
}
}
public void speakToFile(final DocumentController controller, final ResultResponse<String> info, int from, int to) {
File dirFolder = new File(BookCSS.get().ttsSpeakPath, "TTS_" + controller.getCurrentBook().getName());
if (!dirFolder.exists()) {
dirFolder.mkdirs();
}
if (!dirFolder.exists()) {
info.onResultRecive(controller.getActivity().getString(R.string.file_not_found) + " " + dirFolder.getPath());
return;
}
String path = dirFolder.getPath();
speakToFile(controller, from - 1, path, info, from - 1, to);
}
public void speakToFile(final DocumentController controller, final int page, final String folder, final ResultResponse<String> info, int from, int to) {
LOG.d("speakToFile", page, controller.getPageCount());
if (ttsEngine == null) {
LOG.d("TTS is null");
if (controller != null && controller.getActivity() != null) {
Toast.makeText(controller.getActivity(), R.string.msg_unexpected_error, Toast.LENGTH_SHORT).show();
}
return;
}
ttsEngine.setPitch(AppState.get().ttsPitch);
ttsEngine.setSpeechRate(AppState.get().ttsSpeed);
if (page >= to || !TempHolder.isRecordTTS) {
LOG.d("speakToFile finish", page, controller.getPageCount());
info.onResultRecive((controller.getActivity().getString(R.string.success)));
TempHolder.isRecordTTS = false;
return;
}
info.onResultRecive((page + 1) + " / " + to);
DecimalFormat df = new DecimalFormat("0000");
String pageName = "page-" + df.format(page + 1);
final String wav = new File(folder, pageName + WAV).getPath();
String fileText = controller.getTextForPage(page);
controller.recyclePage(page);
LOG.d("synthesizeToFile", fileText);
if (TxtUtils.isEmpty(fileText)) {
speakToFile(controller, page + 1, folder, info, from, to);
} else {
if (fileText.length() > 3950) {
fileText = TxtUtils.substringSmart(fileText, 3950) + " " + controller.getString(R.string.text_is_too_long);
LOG.d("Text-too-long", page);
}
ttsEngine.synthesizeToFile(fileText, map, wav);
TTSEngine.get().getTTS().setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
LOG.d("speakToFile onUtteranceCompleted", page, controller.getPageCount());
if (AppState.get().isConvertToMp3) {
try {
File file = new File(wav);
Lame lame = new Lame();
InputStream input = new BufferedInputStream(new FileInputStream(file));
input.mark(44);
int bitrate = MobiParserIS.asInt_LITTLE_ENDIAN(input, 24, 4);
LOG.d("bitrate", bitrate);
input.close();
input = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(input);
short[] shorts = new short[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts);
lame.open(1, bitrate, 128, 4);
byte[] res = lame.encode(shorts, 44, shorts.length);
lame.close();
File toFile = new File(wav.replace(".wav", ".mp3"));
toFile.delete();
IO.copyFile(new ByteArrayInputStream(res), toFile);
input.close();
file.delete();
} catch (Exception e) {
LOG.e(e);
}
}
//lame.encode();
speakToFile(controller, page + 1, folder, info, from, to);
}
});
}
}
public boolean isTempPausing() {
if (AppState.get().isEnableAccessibility) {
return true;
}
return mp != null || ttsEngine != null;
}
public boolean isPlaying() {
if (TempHolder.isRecordTTS) {
return false;
}
if (isMp3()) {
return mp != null && mp.isPlaying();
}
synchronized (helpObject) {
if (ttsEngine == null) {
return false;
}
return ttsEngine != null && ttsEngine.isSpeaking();
}
}
public boolean hasNoEngines() {
try {
return ttsEngine != null && (ttsEngine.getEngines() == null || ttsEngine.getEngines().size() == 0);
} catch (Exception e) {
return true;
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public String getCurrentLang() {
try {
if (Build.VERSION.SDK_INT >= 21 && ttsEngine != null && ttsEngine.getDefaultVoice() != null && ttsEngine.getDefaultVoice().getLocale() != null) {
return ttsEngine.getDefaultVoice().getLocale().getDisplayLanguage();
}
} catch (Exception e) {
LOG.e(e);
}
return "---";
}
public int getEngineCount() {
try {
if (ttsEngine == null || ttsEngine.getEngines() == null) {
return -1;
}
return ttsEngine.getEngines().size();
} catch (Exception e) {
LOG.e(e);
}
return 0;
}
public String getCurrentEngineName() {
try {
if (ttsEngine != null) {
String enginePackage = ttsEngine.getDefaultEngine();
List<EngineInfo> engines = ttsEngine.getEngines();
for (final EngineInfo eInfo : engines) {
if (eInfo.name.equals(enginePackage)) {
return engineToString(eInfo);
}
}
}
} catch (Exception e) {
LOG.e(e);
}
return "---";
}
public void loadMP3(String ttsPlayMp3Path) {
loadMP3(ttsPlayMp3Path, false);
}
public void loadMP3(String ttsPlayMp3Path, final boolean play) {
LOG.d("loadMP3-", ttsPlayMp3Path);
if (TxtUtils.isEmpty(ttsPlayMp3Path) || !new File(ttsPlayMp3Path).isFile()) {
LOG.d("loadMP3-skip mp3");
return;
}
try {
mp3Destroy();
mp = new MediaPlayer();
mp.setDataSource(ttsPlayMp3Path);
mp.prepare();
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.pause();
}
});
if (play) {
mp.start();
}
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
AppState.get().mp3seek = mp.getCurrentPosition();
//LOG.d("Run timer-task");
EventBus.getDefault().post(new TtsStatus());
}
;
}, 1000, 1000);
} catch (Exception e) {
LOG.e(e);
}
}
public MediaPlayer getMP() {
return mp;
}
public void mp3Destroy() {
if (mp != null) {
mp.stop();
mp.reset();
mp = null;
if (mTimer != null) {
mTimer.purge();
mTimer.cancel();
mTimer = null;
}
}
LOG.d("mp3Desproy");
}
public void mp3Next() {
int seek = mp.getCurrentPosition();
mp.seekTo(seek + 5 * 1000);
}
public void mp3Prev() {
int seek = mp.getCurrentPosition();
mp.seekTo(seek - 5 * 1000);
}
public boolean isMp3PlayPause() {
if (isMp3()) {
if (mp == null) {
loadMP3(BookCSS.get().mp3BookPathGet());
}
if (mp == null) {
return false;
}
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
TTSNotification.showLast();
return true;
}
return false;
}
public void playMp3() {
if (mp != null) {
mp.start();
}
}
public void pauseMp3() {
if (mp != null) {
mp.pause();
}
}
public boolean isMp3() {
return TxtUtils.isNotEmpty(BookCSS.get().mp3BookPathGet());
}
public void seekTo(int i) {
if (mp != null) {
mp.seekTo(i);
}
}
}
| foobnix/LibreraReader | app/src/main/java/com/foobnix/tts/TTSEngine.java |
180,181 | 404: Not Found | corretto/corretto-8 | jdk/src/share/classes/sun/management/ThreadImpl.java |
180,182 | package eu.faircode.email;
/*
This file is part of FairEmail.
FairEmail 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.
FairEmail 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 FairEmail. If not, see <http://www.gnu.org/licenses/>.
Copyright 2018-2024 by Marcel Bokhorst (M66B)
*/
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.text.TextUtils;
import java.io.File;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.mail.Address;
// https://www.sqlite.org/fts3.html
// fts4 requires sqlite 3.7.4, API 21
// "unicode61" tokenizer requires sqlite 3.7.13, API 21
public class Fts4DbHelper extends SQLiteOpenHelper {
private Context context;
@SuppressLint("StaticFieldLeak")
private static Fts4DbHelper instance = null;
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "fts4a.db";
private Fts4DbHelper(Context context) {
super(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);
this.context = context.getApplicationContext();
}
static SQLiteDatabase getInstance(Context context) {
boolean has = context.getDatabasePath(DATABASE_NAME).exists();
if (instance == null || !has) {
if (!has)
DB.getInstance(context).message().resetFts();
instance = new Fts4DbHelper(context);
}
return instance.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i("FTS create");
db.execSQL("CREATE VIRTUAL TABLE `message`" +
" USING fts4" +
" (`account`" +
", `folder`" +
", `time`" +
", `address`" +
", `subject`" +
", `keyword`" +
", `text`" +
", `notes`" +
", `filenames`" +
", notindexed=`account`" +
", notindexed=`folder`" +
", notindexed=`time`)");
// https://www.sqlite.org/fts3.html#tokenizer
// https://unicode.org/reports/tr29/
// https://www.sqlite.org/fts3.html#fts4aux
db.execSQL("CREATE VIRTUAL TABLE message_terms USING fts4aux('message');");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("FTS upgrade from " + oldVersion + " to " + newVersion);
db.execSQL("DROP TABLE IF EXISTS `message`");
db.execSQL("DROP TABLE IF EXISTS `message_terms`");
onCreate(db);
DB.getInstance(context).message().resetFts();
}
static void insert(SQLiteDatabase db, EntityMessage message, List<EntityAttachment> attachments, String text) {
Log.i("FTS insert id=" + message.id);
List<Address> address = new ArrayList<>();
if (message.from != null)
address.addAll(Arrays.asList(message.from));
if (message.to != null)
address.addAll(Arrays.asList(message.to));
if (message.cc != null)
address.addAll(Arrays.asList(message.cc));
if (message.bcc != null)
address.addAll(Arrays.asList(message.bcc));
List<String> filenames = new ArrayList<>();
if (attachments != null)
for (EntityAttachment attachment : attachments)
if (!TextUtils.isEmpty(attachment.name))
filenames.add(attachment.name);
delete(db, message.id);
ContentValues cv = new ContentValues();
cv.put("rowid", message.id);
cv.put("account", message.account);
cv.put("folder", message.folder);
cv.put("time", message.received);
cv.put("address", MessageHelper.formatAddresses(address.toArray(new Address[0]), true, false));
cv.put("subject", processBreakText(message.subject));
cv.put("keyword", TextUtils.join(" ", message.keywords));
cv.put("text", processBreakText(text));
cv.put("notes", processBreakText(message.notes));
cv.put("filenames", processBreakText(TextUtils.join(" ", filenames)));
db.insertWithOnConflict("message", null, cv, SQLiteDatabase.CONFLICT_FAIL);
}
static void delete(SQLiteDatabase db) {
db.delete("message", null, null);
}
static void delete(SQLiteDatabase db, long id) {
db.delete("message", "rowid = ?", new String[]{Long.toString(id)});
}
static String preprocessText(String text) {
return Normalizer.normalize(text.trim().toLowerCase(), Normalizer.Form.NFKD)
.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
}
static String processBreakText(String text) {
if (TextUtils.isEmpty(text))
return "";
return breakText(preprocessText(text));
}
static String breakText(String text) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
return text;
// https://www.sqlite.org/fts3.html#tokenizer
StringBuilder sb = new StringBuilder();
android.icu.text.BreakIterator boundary = android.icu.text.BreakIterator.getWordInstance();
boundary.setText(text);
int start = boundary.first();
for (int end = boundary.next(); end != android.icu.text.BreakIterator.DONE; end = boundary.next()) {
String word = text.substring(start, end).trim().toLowerCase();
if (!TextUtils.isEmpty(word)) {
if (sb.length() > 0)
sb.append(' ');
sb.append(word);
}
start = end;
}
return sb.toString();
}
static List<String> getSuggestions(SQLiteDatabase db, String query, int max) {
List<String> result = new ArrayList<>();
try (Cursor cursor = db.rawQuery(
"SELECT term FROM message_terms" +
" WHERE term LIKE ?" +
" GROUP BY term" +
" ORDER BY SUM(occurrences) DESC" +
" LIMIT " + max,
new String[]{preprocessText(query)})) {
while (cursor != null && cursor.moveToNext())
result.add(cursor.getString(0));
}
return result;
}
static List<Long> match(
SQLiteDatabase db,
Long account, Long folder, long[] exclude,
BoundaryCallbackMessages.SearchCriteria criteria, String query) {
String search = escape(processBreakText(query));
StringBuilder select = new StringBuilder();
List<String> args = new ArrayList<>();
if (account != null) {
select.append("account = CAST(? AS INTEGER) AND ");
args.add(Long.toString(account));
}
if (folder != null) {
select.append("folder = CAST(? AS INTEGER) AND ");
args.add(Long.toString(folder));
}
if (exclude.length > 0) {
select.append("NOT folder IN (");
for (int i = 0; i < exclude.length; i++) {
if (i > 0)
select.append(", ");
select.append("CAST(? AS INTEGER)");
args.add(Long.toString(exclude[i]));
}
select.append(") AND ");
}
if (criteria.after != null) {
select.append("time > CAST(? AS INTEGER) AND ");
args.add(Long.toString(criteria.after));
}
if (criteria.before != null) {
select.append("time < CAST(? AS INTEGER) AND ");
args.add(Long.toString(criteria.before));
}
select.append("message MATCH ?");
args.add(search);
Log.i("FTS select=" + select +
" args=" + TextUtils.join(", ", args) +
" query=" + query);
List<Long> result = new ArrayList<>();
// TODO CASA composed SQL with placeholders
try (Cursor cursor = db.query(
"message", new String[]{"rowid"},
select.toString(),
args.toArray(new String[0]),
null, null, "time DESC", null)) {
while (cursor != null && cursor.moveToNext())
result.add(cursor.getLong(0));
}
Log.i("FTS result=" + result.size());
return result;
}
private static String escape(String word) {
return "'" + word
.replaceAll("'", "''")
.replaceAll("\"", "\"\"") +
"'";
}
static Cursor getIds(SQLiteDatabase db) {
return db.query(
"message", new String[]{"rowid"},
null, null,
null, null, "time");
}
static long size(Context context) {
return context.getDatabasePath(DATABASE_NAME).length();
}
static void optimize(SQLiteDatabase db) {
Log.i("FTS optimize");
db.execSQL("INSERT INTO message (message) VALUES ('optimize')");
}
static void delete(Context context) {
File db = context.getDatabasePath(DATABASE_NAME);
for (File file : db.getParentFile().listFiles())
if (file.getName().startsWith(DATABASE_NAME)) {
Log.i("FTS delete=" + file);
Helper.secureDelete(file);
}
}
}
| M66B/FairEmail | app/src/main/java/eu/faircode/email/Fts4DbHelper.java |
180,183 | package net.i2p.router.tunnel;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import net.i2p.data.Base64;
import net.i2p.data.Hash;
import net.i2p.data.SessionKey;
import net.i2p.data.TunnelId;
import net.i2p.router.RouterContext;
import net.i2p.router.TunnelInfo;
import net.i2p.router.networkdb.kademlia.MessageWrapper.OneTimeSession;
/**
* Coordinate the info that the tunnel creator keeps track of, including what
* peers are in the tunnel and what their configuration is
*
* See PooledTunnelCreatorConfig for the non-abstract class
*/
public abstract class TunnelCreatorConfig implements TunnelInfo {
protected final RouterContext _context;
/** only necessary for client tunnels */
private final Hash _destination;
/** gateway first */
private final HopConfig _config[];
/** gateway first */
private final Hash _peers[];
private volatile long _expiration;
private List<Integer> _order;
private long _replyMessageId;
private final boolean _isInbound;
private int _messagesProcessed;
private long _verifiedBytesTransferred;
private final AtomicInteger _failures = new AtomicInteger();
private boolean _reused;
private int _priority;
//private static final int THROUGHPUT_COUNT = 3;
// Fastest 1 minute throughput, in bytes per minute, ordered with fastest first.
//private final double _peakThroughput[] = new double[THROUGHPUT_COUNT];
private long _peakThroughputCurrentTotal;
private long _peakThroughputLastCoallesce = System.currentTimeMillis();
private Hash _blankHash;
private SessionKey[] _ChaReplyKeys;
private byte[][] _ChaReplyADs;
private final SessionKey[] _AESReplyKeys;
private final byte[][] _AESReplyIVs;
// short record OBEP only
private OneTimeSession _garlicReplyKeys;
/**
* IV length for {@link #getAESReplyIV}
* @since 0.9.48 moved from HopConfig
*/
public static final int REPLY_IV_LENGTH = 16;
// Make configurable? - but can't easily get to pool options from here
private static final int MAX_CONSECUTIVE_TEST_FAILURES = 3;
/**
* For exploratory only (null destination)
* @param length 1 minimum (0 hop is length 1)
*/
public TunnelCreatorConfig(RouterContext ctx, int length, boolean isInbound) {
this(ctx, length, isInbound, null);
}
/**
* @param length 1 minimum (0 hop is length 1)
* @param destination null for exploratory
*/
public TunnelCreatorConfig(RouterContext ctx, int length, boolean isInbound, Hash destination) {
_context = ctx;
if (length <= 0)
throw new IllegalArgumentException("0 length? 0 hop tunnels are 1 length!");
_config = new HopConfig[length];
_peers = new Hash[length];
for (int i = 0; i < length; i++) {
_config[i] = new HopConfig();
}
_isInbound = isInbound;
_destination = destination;
_AESReplyKeys = new SessionKey[length];
_AESReplyIVs = new byte[length][];
}
/**
* How many hops are there in the tunnel?
* INCLUDING US.
* i.e. one more than the TunnelCreatorConfig length.
*/
public int getLength() { return _config.length; }
public Properties getOptions() { return null; }
/**
* retrieve the config for the given hop. the gateway is
* hop 0.
*/
public HopConfig getConfig(int hop) { return _config[hop]; }
/**
* retrieve the tunnelId that the given hop receives messages on.
* the gateway is hop 0.
*
*/
public TunnelId getReceiveTunnelId(int hop) { return _config[hop].getReceiveTunnel(); }
/**
* retrieve the tunnelId that the given hop sends messages on.
* the gateway is hop 0.
*
*/
public TunnelId getSendTunnelId(int hop) { return _config[hop].getSendTunnel(); }
/** retrieve the peer at the given hop. the gateway is hop 0 */
public Hash getPeer(int hop) { return _peers[hop]; }
public void setPeer(int hop, Hash peer) { _peers[hop] = peer; }
/**
* For convenience
* @return getPeer(0)
* @since 0.8.9
*/
public Hash getGateway() {
return _peers[0];
}
/**
* For convenience
* @return getPeer(getLength() - 1)
* @since 0.8.9
*/
public Hash getEndpoint() {
return _peers[_peers.length - 1];
}
/**
* For convenience
* @return isInbound() ? getGateway() : getEndpoint()
* @since 0.8.9
*/
public Hash getFarEnd() {
return _peers[_isInbound ? 0 : _peers.length - 1];
}
/** is this an inbound tunnel? */
public boolean isInbound() { return _isInbound; }
/**
* If this is a client tunnel, what destination is it for?
* @return null for exploratory
*/
public Hash getDestination() { return _destination; }
public long getExpiration() { return _expiration; }
public void setExpiration(long when) { _expiration = when; }
/** component ordering in the new style request */
public List<Integer> getReplyOrder() { return _order; }
public void setReplyOrder(List<Integer> order) { _order = order; }
/** new style reply message id */
public long getReplyMessageId() { return _replyMessageId; }
public void setReplyMessageId(long id) { _replyMessageId = id; }
/** take note of a message being pumped through this tunnel */
public synchronized void incrementProcessedMessages() { _messagesProcessed++; }
public synchronized int getProcessedMessagesCount() { return _messagesProcessed; }
/**
* This calls profile manager tunnelDataPushed1m() for each peer
*/
public synchronized void incrementVerifiedBytesTransferred(int bytes) {
_verifiedBytesTransferred += bytes;
_peakThroughputCurrentTotal += bytes;
long now = System.currentTimeMillis();
long timeSince = now - _peakThroughputLastCoallesce;
if (timeSince >= 60*1000) {
long tot = _peakThroughputCurrentTotal;
int normalized = (int) (tot * 60d*1000d / timeSince);
_peakThroughputLastCoallesce = now;
_peakThroughputCurrentTotal = 0;
if (_context != null) {
// skip ourselves
int start = _isInbound ? 0 : 1;
int end = _isInbound ? _peers.length - 1 : _peers.length;
for (int i = start; i < end; i++) {
_context.profileManager().tunnelDataPushed1m(_peers[i], normalized);
}
}
}
}
public synchronized long getVerifiedBytesTransferred() { return _verifiedBytesTransferred; }
/**** unused
public synchronized double getPeakThroughputKBps() {
double rv = 0;
for (int i = 0; i < THROUGHPUT_COUNT; i++)
rv += _peakThroughput[i];
rv /= (60d*1024d*THROUGHPUT_COUNT);
return rv;
}
public synchronized void setPeakThroughputKBps(double kBps) {
_peakThroughput[0] = kBps*60*1024;
//for (int i = 0; i < THROUGHPUT_COUNT; i++)
// _peakThroughput[i] = kBps*60;
}
****/
/**
* The tunnel failed a test, so (maybe) stop using it
*
* @return false if we stopped using it, true if still ok
*/
public boolean tunnelFailed() {
boolean rv = _failures.incrementAndGet() <= MAX_CONSECUTIVE_TEST_FAILURES;
// don't allow it to be rebuilt
if (!rv)
_reused = true;
return rv;
}
/**
* The tunnel failed completely, so definitely stop using it
*
* @since 0.9.53
*/
public void tunnelFailedCompletely() {
_failures.addAndGet(MAX_CONSECUTIVE_TEST_FAILURES + 1);
// don't allow it to be rebuilt
_reused = true;
}
/**
* Has the tunnel failed completely?
*
* @since 0.9.53
*/
public boolean getTunnelFailed() { return _failures.get() > MAX_CONSECUTIVE_TEST_FAILURES; }
public int getTunnelFailures() { return _failures.get(); }
public void testSuccessful(int ms) {
_failures.set(0);
}
/**
* Did we reuse this tunnel?
* @since 0.8.11
*/
public boolean wasReused() { return _reused; }
/**
* Note that we reused this tunnel
* @since 0.8.11
*/
public void setReused() { _reused = true; }
/**
* Outbound message priority - for outbound tunnels only
* @return -25 to +25, default 0
* @since 0.9.4
*/
public int getPriority() { return _priority; }
/**
* Outbound message priority - for outbound tunnels only
* @param priority -25 to +25, default 0
* @since 0.9.4
*/
public void setPriority(int priority) { _priority = priority; }
/**
* Key and IV to encrypt the reply sent for the tunnel creation crypto.
*
* @throws IllegalArgumentException if iv not 16 bytes
* @since 0.9.48 moved from HopConfig
*/
public void setAESReplyKeys(int hop, SessionKey key, byte[] iv) {
if (iv.length != REPLY_IV_LENGTH)
throw new IllegalArgumentException();
_AESReplyKeys[hop] = key;
_AESReplyIVs[hop] = iv;
}
/**
* Key to encrypt the reply sent for the tunnel creation crypto.
* Null for short build record.
*
* @return key or null
* @throws IllegalArgumentException if iv not 16 bytes
* @since 0.9.48 moved from HopConfig
*/
public SessionKey getAESReplyKey(int hop) { return _AESReplyKeys[hop]; }
/**
* IV used to encrypt the reply sent for the tunnel creation crypto.
* Null for short build record.
*
* @return 16 bytes or null
* @since 0.9.48 moved from HopConfig
*/
public byte[] getAESReplyIV(int hop) { return _AESReplyIVs[hop]; }
/**
* Checksum for blank record
* @since 0.9.48
*/
public Hash getBlankHash() { return _blankHash; }
/**
* Checksum for blank record
* @since 0.9.48
*/
public void setBlankHash(Hash h) { _blankHash = h; }
/**
* Set ECIES reply key and IV
* @since 0.9.48
*/
public void setChaChaReplyKeys(int hop, SessionKey key, byte[] ad) {
if (_ChaReplyKeys == null) {
_ChaReplyKeys = new SessionKey[_config.length];
_ChaReplyADs = new byte[_config.length][];
}
_ChaReplyKeys[hop] = key;
_ChaReplyADs[hop] = ad;
}
/**
* Is it an ECIES hop?
* @since 0.9.48
*/
public boolean isEC(int hop) {
if (_ChaReplyKeys == null)
return false;
return _ChaReplyKeys[hop] != null;
}
/**
* Get ECIES reply key
* @since 0.9.48
*/
public SessionKey getChaChaReplyKey(int hop) {
if (_ChaReplyKeys == null)
return null;
return _ChaReplyKeys[hop];
}
/**
* Get ECIES reply AD
* @since 0.9.48
*/
public byte[] getChaChaReplyAD(int hop) {
if (_ChaReplyADs == null)
return null;
return _ChaReplyADs[hop];
}
/**
* ECIES short OBEP record only.
* @since 0.9.51
*/
public void setGarlicReplyKeys(OneTimeSession keys) {
_garlicReplyKeys = keys;
}
/**
* ECIES short OBEP record only.
* @return null for ElGamal or ECIES long record or non-OBEP
* @since 0.9.51
*/
public OneTimeSession getGarlicReplyKeys() {
return _garlicReplyKeys;
}
@Override
public String toString() {
// H0:1235-->H1:2345-->H2:2345
StringBuilder buf = new StringBuilder(128);
if (_isInbound)
buf.append("IB");
else
buf.append("OB");
if (_destination == null)
buf.append(" expl");
else
buf.append(" client ").append(Base64.encode(_destination.getData(), 0, 3));
buf.append(": GW ");
for (int i = 0; i < _peers.length; i++) {
buf.append(_peers[i].toBase64(), 0, 4);
long id = _config[i].getReceiveTunnelId();
if (id != 0) {
// don't show for "me" at OBGW or IBEP
if (!_isInbound || i != _peers.length - 1)
buf.append(isEC(i) ? " EC:" : " ElG:");
else
buf.append(' ');
buf.append(id);
} else {
buf.append(" me");
}
id = _config[i].getSendTunnelId();
if (id != 0) {
buf.append('.');
buf.append(id);
} else if (_isInbound || i == 0) {
buf.append(".me");
}
if (i + 1 < _peers.length)
buf.append("-->");
}
buf.append(" exp. ").append(new Date(_expiration));
if (_replyMessageId > 0)
buf.append(" replyMsgID ").append(_replyMessageId);
if (_messagesProcessed > 0)
buf.append(" with ").append(_messagesProcessed).append("/").append(_verifiedBytesTransferred).append(" msgs/bytes");
int fails = _failures.get();
if (fails > 0)
buf.append(" with ").append(fails).append(" consec. failures");
return buf.toString();
}
/**
* @since 0.9.51
*/
public String toStringFull() {
StringBuilder buf = new StringBuilder(1024);
buf.append(toString());
for (int i = 0; i < _peers.length; i++) {
if (i == 0)
buf.append("\nGW ");
else if (i == _peers.length - 1)
buf.append("\nEP ");
else
buf.append("\nHop ").append(i);
buf.append(": ").append(_config[i]);
}
if (_garlicReplyKeys != null) {
buf.append("\nGarlic reply key: ").append(_garlicReplyKeys.key).append(" tag: ").append(_garlicReplyKeys.rtag);
}
return buf.toString();
}
}
| i2p/i2p.i2p | router/java/src/net/i2p/router/tunnel/TunnelCreatorConfig.java |
180,184 | package com.linkedin.metadata.config;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class EbeanConfiguration {
private String username;
private String password;
private String url;
private String driver;
private long minConnections;
private long maxConnections;
private long maxInactiveTimeSeconds;
private long maxAgeMinutes;
private long leakTimeMinutes;
private long waitTimeoutMillis;
private boolean autoCreateDdl;
private boolean postgresUseIamAuth;
private LockingConfiguration locking;
public static final EbeanConfiguration testDefault =
EbeanConfiguration.builder().locking(LockingConfiguration.testDefault).build();
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class LockingConfiguration {
private boolean enabled;
private long durationSeconds;
private long maximumLocks;
public static final LockingConfiguration testDefault =
LockingConfiguration.builder()
.enabled(true)
.durationSeconds(60)
.maximumLocks(10000)
.build();
}
}
| datahub-project/datahub | metadata-service/configuration/src/main/java/com/linkedin/metadata/config/EbeanConfiguration.java |
180,186 | /*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This source code is provided to illustrate the usage of a given feature
* or technique and has been deliberately simplified. Additional steps
* required for a production-quality application, such as security checks,
* input validation and proper error handling, might not be present in
* this sample code.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.text.AttributedString;
import java.util.EnumSet;
import java.util.Vector;
import javax.imageio.*;
import javax.swing.*;
import static java.awt.RenderingHints.*;
/**
* FontPanel.java
*
* @author Shinsuke Fukuda
* @author Ankit Patel [Conversion to Swing - 01/07/30]
*/
/// This panel is combination of the text drawing area of Font2DTest
/// and the custom controlled scroll bar
public final class FontPanel extends JPanel implements AdjustmentListener {
/// Drawing Option Constants
private final String STYLES[] =
{ "plain", "bold", "italic", "bold italic" };
private final int NONE = 0;
private final int SCALE = 1;
private final int SHEAR = 2;
private final int ROTATE = 3;
private final String TRANSFORMS[] =
{ "with no transforms", "with scaling", "with Shearing", "with rotation" };
private final int DRAW_STRING = 0;
private final int DRAW_CHARS = 1;
private final int DRAW_BYTES = 2;
private final int DRAW_GLYPHV = 3;
private final int TL_DRAW = 4;
private final int GV_OUTLINE = 5;
private final int TL_OUTLINE = 6;
private final String METHODS[] = {
"drawString", "drawChars", "drawBytes", "drawGlyphVector",
"TextLayout.draw", "GlyphVector.getOutline", "TextLayout.getOutline" };
public final int RANGE_TEXT = 0;
public final int ALL_GLYPHS = 1;
public final int USER_TEXT = 2;
public final int FILE_TEXT = 3;
private final String MS_OPENING[] =
{ " Unicode ", " Glyph Code ", " lines ", " lines " };
private final String MS_CLOSING[] =
{ "", "", " of User Text ", " of LineBreakMeasurer-reformatted Text " };
/// General Graphics Variable
private final JScrollBar verticalBar;
private final FontCanvas fc;
private boolean updateBackBuffer = true;
private boolean updateFontMetrics = true;
private boolean updateFont = true;
private boolean force16Cols = false;
public boolean showingError = false;
private int g2Transform = NONE; /// ABP
/// Printing constants and variables
public final int ONE_PAGE = 0;
public final int CUR_RANGE = 1;
public final int ALL_TEXT = 2;
private int printMode = ONE_PAGE;
private PageFormat page = null;
private PrinterJob printer = null;
/// Text drawing variables
private String fontName = "Dialog";
private float fontSize = 12;
private int fontStyle = Font.PLAIN;
private int fontTransform = NONE;
private Font testFont = null;
private Object antiAliasType = VALUE_TEXT_ANTIALIAS_DEFAULT;
private Object fractionalMetricsType = VALUE_FRACTIONALMETRICS_DEFAULT;
private Object lcdContrast = getDefaultLCDContrast();
private int drawMethod = DRAW_STRING;
private int textToUse = RANGE_TEXT;
private String userText[] = null;
private String fileText[] = null;
private int drawRange[] = { 0x0000, 0x007f };
private String fontInfos[] = new String[2];
private boolean showGrid = true;
/// Parent Font2DTest panel
private final Font2DTest f2dt;
private final JFrame parent;
public FontPanel( Font2DTest demo, JFrame f ) {
f2dt = demo;
parent = f;
verticalBar = new JScrollBar ( JScrollBar.VERTICAL );
fc = new FontCanvas();
this.setLayout( new BorderLayout() );
this.add( "Center", fc );
this.add( "East", verticalBar );
verticalBar.addAdjustmentListener( this );
this.addComponentListener( new ComponentAdapter() {
public void componentResized( ComponentEvent e ) {
updateBackBuffer = true;
updateFontMetrics = true;
}
});
/// Initialize font and its infos
testFont = new Font(fontName, fontStyle, (int)fontSize);
if ((float)((int)fontSize) != fontSize) {
testFont = testFont.deriveFont(fontSize);
}
updateFontInfo();
}
public Dimension getPreferredSize() {
return new Dimension(600, 200);
}
/// Functions called by the main programs to set the various parameters
public void setTransformG2( int transform ) {
g2Transform = transform;
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
}
/// convenience fcn to create AffineTransform of appropriate type
private AffineTransform getAffineTransform( int transform ) {
/// ABP
AffineTransform at = new AffineTransform();
switch ( transform )
{
case SCALE:
at.setToScale( 1.5f, 1.5f ); break;
case ROTATE:
at.setToRotation( Math.PI / 6 ); break;
case SHEAR:
at.setToShear( 0.4f, 0 ); break;
case NONE:
break;
default:
//System.err.println( "Illegal G2 Transform Arg: " + transform);
break;
}
return at;
}
public void setFontParams(Object obj, float size,
int style, int transform) {
setFontParams( (String)obj, size, style, transform );
}
public void setFontParams(String name, float size,
int style, int transform) {
boolean fontModified = false;
if ( !name.equals( fontName ) || style != fontStyle )
fontModified = true;
fontName = name;
fontSize = size;
fontStyle = style;
fontTransform = transform;
/// Recreate the font as specified
testFont = new Font(fontName, fontStyle, (int)fontSize);
if ((float)((int)fontSize) != fontSize) {
testFont = testFont.deriveFont(fontSize);
}
if ( fontTransform != NONE ) {
AffineTransform at = getAffineTransform( fontTransform );
testFont = testFont.deriveFont( at );
}
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
if ( fontModified ) {
/// Tell main panel to update the font info
updateFontInfo();
f2dt.fireUpdateFontInfo();
}
}
public void setRenderingHints( Object aa, Object fm, Object contrast) {
antiAliasType = ((AAValues)aa).getHint();
fractionalMetricsType = ((FMValues)fm).getHint();
lcdContrast = contrast;
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
}
public void setDrawMethod( int i ) {
drawMethod = i;
updateBackBuffer = true;
fc.repaint();
}
public void setTextToDraw( int i, int range[],
String textSet[], String fileData[] ) {
textToUse = i;
if ( textToUse == RANGE_TEXT )
drawRange = range;
else if ( textToUse == ALL_GLYPHS )
drawMethod = DRAW_GLYPHV;
else if ( textToUse == USER_TEXT )
userText = textSet;
else if ( textToUse == FILE_TEXT ) {
fileText = fileData;
drawMethod = TL_DRAW;
}
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
updateFontInfo();
}
public void setGridDisplay( boolean b ) {
showGrid = b;
updateBackBuffer = true;
fc.repaint();
}
public void setForce16Columns( boolean b ) {
force16Cols = b;
updateBackBuffer = true;
updateFontMetrics = true;
fc.repaint();
}
/// Prints out the text display area
public void doPrint( int i ) {
if ( printer == null ) {
printer = PrinterJob.getPrinterJob();
page = printer.defaultPage();
}
printMode = i;
printer.setPrintable( fc, page );
if ( printer.printDialog() ) {
try {
printer.print();
}
catch ( Exception e ) {
f2dt.fireChangeStatus( "ERROR: Printing Failed; See Stack Trace", true );
}
}
}
/// Displays the page setup dialog and updates PageFormat info
public void doPageSetup() {
if ( printer == null ) {
printer = PrinterJob.getPrinterJob();
page = printer.defaultPage();
}
page = printer.pageDialog( page );
}
/// Obtains the information about selected font
private void updateFontInfo() {
int numGlyphs = 0, numCharsInRange = drawRange[1] - drawRange[0] + 1;
fontInfos[0] = "Font Face Name: " + testFont.getFontName();
fontInfos[1] = "Glyphs in This Range: ";
if ( textToUse == RANGE_TEXT ) {
for ( int i = drawRange[0]; i < drawRange[1]; i++ )
if ( testFont.canDisplay( i ))
numGlyphs++;
fontInfos[1] = fontInfos[1] + numGlyphs + " / " + numCharsInRange;
}
else
fontInfos[1] = null;
}
/// Accessor for the font information
public String[] getFontInfo() {
return fontInfos;
}
/// Collects the currectly set options and returns them as string
public String getCurrentOptions() {
/// Create a new String to store the options
/// The array will contain all 8 setting (font name, size...) and
/// character range or user text data used (no file text data)
int userTextSize = 0;
String options;
options = ( fontName + "\n" + fontSize + "\n" + fontStyle + "\n" +
fontTransform + "\n" + g2Transform + "\n"+
textToUse + "\n" + drawMethod + "\n" +
AAValues.getHintVal(antiAliasType) + "\n" +
FMValues.getHintVal(fractionalMetricsType) + "\n" +
lcdContrast + "\n");
if ( textToUse == USER_TEXT )
for ( int i = 0; i < userText.length; i++ )
options += ( userText[i] + "\n" );
return options;
}
/// Reload all options and refreshes the canvas
public void loadOptions( boolean grid, boolean force16, int start, int end,
String name, float size, int style,
int transform, int g2transform,
int text, int method, int aa, int fm,
int contrast, String user[] ) {
int range[] = { start, end };
/// Since repaint call has a low priority, these functions will finish
/// before the actual repainting is done
setGridDisplay( grid );
setForce16Columns( force16 );
// previous call to readTextFile has already set the text to draw
if (textToUse != FILE_TEXT) {
setTextToDraw( text, range, user, null );
}
setFontParams( name, size, style, transform );
setTransformG2( g2transform ); // ABP
setDrawMethod( method );
setRenderingHints(AAValues.getValue(aa), FMValues.getValue(fm),
new Integer(contrast));
}
/// Writes the current screen to PNG file
public void doSavePNG( String fileName ) {
fc.writePNG( fileName );
}
/// When scrolled using the scroll bar, update the backbuffer
public void adjustmentValueChanged( AdjustmentEvent e ) {
updateBackBuffer = true;
fc.repaint();
}
public void paintComponent( Graphics g ) {
// Windows does not repaint correctly, after
// a zoom. Thus, we need to force the canvas
// to repaint, but only once. After the first repaint,
// everything stabilizes. [ABP]
fc.repaint();
}
/// Inner class definition...
/// Inner panel that holds the actual drawing area and its routines
private class FontCanvas extends JPanel implements MouseListener, MouseMotionListener, Printable {
/// Number of characters that will fit across and down this canvas
private int numCharAcross, numCharDown;
/// First and last character/line that will be drawn
/// Limit is the end of range/text where no more draw will be done
private int drawStart, drawEnd, drawLimit;
/// FontMetrics variables
/// Here, gridWidth is equivalent to maxAdvance (slightly bigger though)
/// and gridHeight is equivalent to lineHeight
private int maxAscent, maxDescent, gridWidth = 0, gridHeight = 0;
/// Offset from the top left edge of the canvas where the draw will start
private int canvasInset_X = 5, canvasInset_Y = 5;
/// Offscreen buffer of this canvas
private BufferedImage backBuffer = null;
/// LineBreak'ed TextLayout vector
private Vector lineBreakTLs = null;
/// Whether the current draw command requested is for printing
private boolean isPrinting = false;
/// Other printing infos
private int lastPage, printPageNumber, currentlyShownChar = 0;
private final int PR_OFFSET = 10;
private final int PR_TITLE_LINEHEIGHT = 30;
/// Information about zooming (used with range text draw)
private final JWindow zoomWindow;
private BufferedImage zoomImage = null;
private int mouseOverCharX = -1, mouseOverCharY = -1;
private int currMouseOverChar = -1, prevZoomChar = -1;
private float ZOOM = 2.0f;
private boolean nowZooming = false;
private boolean firstTime = true;
// ABP
/// Status bar message backup
private String backupStatusString = null;
/// Error constants
private final String ERRORS[] = {
"ERROR: drawBytes cannot handle characters beyond 0x00FF. Select different range or draw methods.",
"ERROR: Cannot fit text with the current font size. Resize the window or use smaller font size.",
"ERROR: Cannot print with the current font size. Use smaller font size.",
};
private final int DRAW_BYTES_ERROR = 0;
private final int CANT_FIT_DRAW = 1;
private final int CANT_FIT_PRINT = 2;
/// Other variables
private final Cursor blankCursor;
public FontCanvas() {
this.addMouseListener( this );
this.addMouseMotionListener( this );
this.setForeground( Color.black );
this.setBackground( Color.white );
/// Creates an invisble pointer by giving it bogus image
/// Possibly find a workaround for this...
Toolkit tk = Toolkit.getDefaultToolkit();
byte bogus[] = { (byte) 0 };
blankCursor =
tk.createCustomCursor( tk.createImage( bogus ), new Point(0, 0), "" );
zoomWindow = new JWindow( parent ) {
public void paint( Graphics g ) {
g.drawImage( zoomImage, 0, 0, zoomWindow );
}
};
zoomWindow.setCursor( blankCursor );
zoomWindow.pack();
}
public boolean firstTime() { return firstTime; }
public void refresh() {
firstTime = false;
updateBackBuffer = true;
repaint();
}
/// Sets the font, hints, according to the set parameters
private void setParams( Graphics2D g2 ) {
g2.setFont( testFont );
g2.setRenderingHint(KEY_TEXT_ANTIALIASING, antiAliasType);
g2.setRenderingHint(KEY_FRACTIONALMETRICS, fractionalMetricsType);
g2.setRenderingHint(KEY_TEXT_LCD_CONTRAST, lcdContrast);
/* I am preserving a somewhat dubious behaviour of this program.
* Outline text would be drawn anti-aliased by setting the
* graphics anti-aliasing hint if the text anti-aliasing hint
* was set. The dubious element here is that people simply
* using this program may think this is built-in behaviour
* but its not - at least not when the app explicitly draws
* outline text.
* This becomes more dubious in cases such as "GASP" where the
* size at which text is AA'ed is not something you can easily
* calculate, so mimicing that behaviour isn't going to be easy.
* So I precisely preserve the behaviour : this is done only
* if the AA value is "ON". Its not applied in the other cases.
*/
if (antiAliasType == VALUE_TEXT_ANTIALIAS_ON &&
(drawMethod == TL_OUTLINE || drawMethod == GV_OUTLINE)) {
g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
} else {
g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_OFF);
}
}
/// Draws the grid (Used for unicode/glyph range drawing)
private void drawGrid( Graphics2D g2 ) {
int totalGridWidth = numCharAcross * gridWidth;
int totalGridHeight = numCharDown * gridHeight;
g2.setColor( Color.black );
for ( int i = 0; i < numCharDown + 1; i++ )
g2.drawLine( canvasInset_X, i * gridHeight + canvasInset_Y,
canvasInset_X + totalGridWidth, i * gridHeight + canvasInset_Y );
for ( int i = 0; i < numCharAcross + 1; i++ )
g2.drawLine( i * gridWidth + canvasInset_X, canvasInset_Y,
i * gridWidth + canvasInset_X, canvasInset_Y + totalGridHeight );
}
/// Draws one character at time onto the canvas according to
/// the method requested (Used for RANGE_TEXT and ALL_GLYPHS)
public void modeSpecificDrawChar( Graphics2D g2, int charCode,
int baseX, int baseY ) {
GlyphVector gv;
int oneGlyph[] = { charCode };
char charArray[] = Character.toChars( charCode );
FontRenderContext frc = g2.getFontRenderContext();
AffineTransform oldTX = g2.getTransform();
/// Create GlyphVector to measure the exact visual advance
/// Using that number, adjust the position of the character drawn
if ( textToUse == ALL_GLYPHS )
gv = testFont.createGlyphVector( frc, oneGlyph );
else
gv = testFont.createGlyphVector( frc, charArray );
Rectangle2D r2d2 = gv.getPixelBounds(frc, 0, 0);
int shiftedX = baseX;
// getPixelBounds returns a result in device space.
// we need to convert back to user space to be able to
// calculate the shift as baseX is in user space.
try {
double pt[] = new double[4];
pt[0] = r2d2.getX();
pt[1] = r2d2.getY();
pt[2] = r2d2.getX()+r2d2.getWidth();
pt[3] = r2d2.getY()+r2d2.getHeight();
oldTX.inverseTransform(pt,0,pt,0,2);
shiftedX = baseX - (int) ( pt[2] / 2 + pt[0] );
} catch (NoninvertibleTransformException e) {
}
/// ABP - keep track of old tform, restore it later
g2.translate( shiftedX, baseY );
g2.transform( getAffineTransform( g2Transform ) );
if ( textToUse == ALL_GLYPHS )
g2.drawGlyphVector( gv, 0f, 0f );
else {
if ( testFont.canDisplay( charCode ))
g2.setColor( Color.black );
else {
g2.setColor( Color.lightGray );
}
switch ( drawMethod ) {
case DRAW_STRING:
g2.drawString( new String( charArray ), 0, 0 );
break;
case DRAW_CHARS:
g2.drawChars( charArray, 0, 1, 0, 0 );
break;
case DRAW_BYTES:
if ( charCode > 0xff )
throw new CannotDrawException( DRAW_BYTES_ERROR );
byte oneByte[] = { (byte) charCode };
g2.drawBytes( oneByte, 0, 1, 0, 0 );
break;
case DRAW_GLYPHV:
g2.drawGlyphVector( gv, 0f, 0f );
break;
case TL_DRAW:
TextLayout tl = new TextLayout( new String( charArray ), testFont, frc );
tl.draw( g2, 0f, 0f );
break;
case GV_OUTLINE:
r2d2 = gv.getVisualBounds();
shiftedX = baseX - (int) ( r2d2.getWidth() / 2 + r2d2.getX() );
g2.draw( gv.getOutline( 0f, 0f ));
break;
case TL_OUTLINE:
r2d2 = gv.getVisualBounds();
shiftedX = baseX - (int) ( r2d2.getWidth() / 2 + r2d2.getX() );
TextLayout tlo =
new TextLayout( new String( charArray ), testFont,
g2.getFontRenderContext() );
g2.draw( tlo.getOutline( null ));
}
}
/// ABP - restore old tform
g2.setTransform ( oldTX );
}
/// Draws one line of text at given position
private void modeSpecificDrawLine( Graphics2D g2, String line,
int baseX, int baseY ) {
/// ABP - keep track of old tform, restore it later
AffineTransform oldTx = null;
oldTx = g2.getTransform();
g2.translate( baseX, baseY );
g2.transform( getAffineTransform( g2Transform ) );
switch ( drawMethod ) {
case DRAW_STRING:
g2.drawString( line, 0, 0 );
break;
case DRAW_CHARS:
g2.drawChars( line.toCharArray(), 0, line.length(), 0, 0 );
break;
case DRAW_BYTES:
try {
byte lineBytes[] = line.getBytes( "ISO-8859-1" );
g2.drawBytes( lineBytes, 0, lineBytes.length, 0, 0 );
}
catch ( Exception e ) {
e.printStackTrace();
}
break;
case DRAW_GLYPHV:
GlyphVector gv =
testFont.createGlyphVector( g2.getFontRenderContext(), line );
g2.drawGlyphVector( gv, (float) 0, (float) 0 );
break;
case TL_DRAW:
TextLayout tl = new TextLayout( line, testFont,
g2.getFontRenderContext() );
tl.draw( g2, (float) 0, (float) 0 );
break;
case GV_OUTLINE:
GlyphVector gvo =
testFont.createGlyphVector( g2.getFontRenderContext(), line );
g2.draw( gvo.getOutline( (float) 0, (float) 0 ));
break;
case TL_OUTLINE:
TextLayout tlo =
new TextLayout( line, testFont,
g2.getFontRenderContext() );
AffineTransform at = new AffineTransform();
g2.draw( tlo.getOutline( at ));
}
/// ABP - restore old tform
g2.setTransform ( oldTx );
}
/// Draws one line of text at given position
private void tlDrawLine( Graphics2D g2, TextLayout tl,
float baseX, float baseY ) {
/// ABP - keep track of old tform, restore it later
AffineTransform oldTx = null;
oldTx = g2.getTransform();
g2.translate( baseX, baseY );
g2.transform( getAffineTransform( g2Transform ) );
tl.draw( g2, (float) 0, (float) 0 );
/// ABP - restore old tform
g2.setTransform ( oldTx );
}
/// If textToUse is set to range drawing, then convert
/// int to hex string and prepends 0s to make it length 4
/// Otherwise line number was fed; simply return number + 1 converted to String
/// (This is because first line is 1, not 0)
private String modeSpecificNumStr( int i ) {
if ( textToUse == USER_TEXT || textToUse == FILE_TEXT )
return String.valueOf( i + 1 );
StringBuffer s = new StringBuffer( Integer.toHexString( i ));
while ( s.length() < 4 )
s.insert( 0, "0" );
return s.toString().toUpperCase();
}
/// Resets the scrollbar to display correct range of text currently on screen
/// (This scrollbar is not part of a "ScrollPane". It merely simulates its effect by
/// indicating the necessary area to be drawn within the panel.
/// By doing this, it prevents creating gigantic panel when large text range,
/// i.e. CJK Ideographs, is requested)
private void resetScrollbar( int oldValue ) {
int totalNumRows = 1, numCharToDisplay;
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
if ( textToUse == RANGE_TEXT )
numCharToDisplay = drawRange[1] - drawRange[0];
else /// textToUse == ALL_GLYPHS
numCharToDisplay = testFont.getNumGlyphs();
totalNumRows = numCharToDisplay / numCharAcross;
if ( numCharToDisplay % numCharAcross != 0 )
totalNumRows++;
if ( oldValue / numCharAcross > totalNumRows )
oldValue = 0;
verticalBar.setValues( oldValue / numCharAcross,
numCharDown, 0, totalNumRows );
}
else {
if ( textToUse == USER_TEXT )
totalNumRows = userText.length;
else /// textToUse == FILE_TEXT;
totalNumRows = lineBreakTLs.size();
verticalBar.setValues( oldValue, numCharDown, 0, totalNumRows );
}
if ( totalNumRows <= numCharDown && drawStart == 0) {
verticalBar.setEnabled( false );
}
else {
verticalBar.setEnabled( true );
}
}
/// Calculates the font's metrics that will be used for draw
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
FontMetrics fm;
Graphics2D g2 = (Graphics2D)g2d.create();
/// ABP
if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
fm = g2.getFontMetrics();
}
else {
fm = g2.getFontMetrics();
}
maxAscent = fm.getMaxAscent();
maxDescent = fm.getMaxDescent();
if (maxAscent == 0) maxAscent = 10;
if (maxDescent == 0) maxDescent = 5;
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
/// Give slight extra room for each character
maxAscent += 3;
maxDescent += 3;
gridWidth = fm.getMaxAdvance() + 6;
gridHeight = maxAscent + maxDescent;
if ( force16Cols )
numCharAcross = 16;
else
numCharAcross = ( w - 10 ) / gridWidth;
numCharDown = ( h - 10 ) / gridHeight;
canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
if ( numCharDown == 0 || numCharAcross == 0 )
throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
if ( !isPrinting )
resetScrollbar( verticalBar.getValue() * numCharAcross );
}
else {
maxDescent += fm.getLeading();
canvasInset_X = 5;
canvasInset_Y = 5;
/// gridWidth and numCharAcross will not be used in this mode...
gridHeight = maxAscent + maxDescent;
numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;
if ( numCharDown == 0 )
throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
/// If this is text loaded from file, prepares the LineBreak'ed
/// text layout at this point
if ( textToUse == FILE_TEXT ) {
if ( !isPrinting )
f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
lineBreakTLs = new Vector();
for ( int i = 0; i < fileText.length; i++ ) {
AttributedString as =
new AttributedString( fileText[i], g2.getFont().getAttributes() );
LineBreakMeasurer lbm =
new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );
while ( lbm.getPosition() < fileText[i].length() )
lineBreakTLs.add( lbm.nextLayout( (float) w ));
}
}
if ( !isPrinting )
resetScrollbar( verticalBar.getValue() );
}
}
/// Calculates the amount of text that will be displayed on screen
private void calcTextRange() {
String displaying = null;
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
if ( isPrinting )
if ( printMode == ONE_PAGE )
drawStart = currentlyShownChar;
else /// printMode == CUR_RANGE
drawStart = numCharAcross * numCharDown * printPageNumber;
else
drawStart = verticalBar.getValue() * numCharAcross;
if ( textToUse == RANGE_TEXT ) {
drawStart += drawRange[0];
drawLimit = drawRange[1];
}
else
drawLimit = testFont.getNumGlyphs();
drawEnd = drawStart + numCharAcross * numCharDown - 1;
if ( drawEnd >= drawLimit )
drawEnd = drawLimit;
}
else {
if ( isPrinting )
if ( printMode == ONE_PAGE )
drawStart = currentlyShownChar;
else /// printMode == ALL_TEXT
drawStart = numCharDown * printPageNumber;
else {
drawStart = verticalBar.getValue();
}
drawEnd = drawStart + numCharDown - 1;
if ( textToUse == USER_TEXT )
drawLimit = userText.length - 1;
else
drawLimit = lineBreakTLs.size() - 1;
if ( drawEnd >= drawLimit )
drawEnd = drawLimit;
}
// ABP
if ( drawStart > drawEnd ) {
drawStart = 0;
verticalBar.setValue(drawStart);
}
/// Change the status bar if not printing...
if ( !isPrinting ) {
backupStatusString = ( "Displaying" + MS_OPENING[textToUse] +
modeSpecificNumStr( drawStart ) + " to " +
modeSpecificNumStr( drawEnd ) +
MS_CLOSING[textToUse] );
f2dt.fireChangeStatus( backupStatusString, false );
}
}
/// Draws text according to the parameters set by Font2DTest GUI
private void drawText( Graphics g, int w, int h ) {
Graphics2D g2;
/// Create back buffer when not printing, and its Graphics2D
/// Then set drawing parameters for that Graphics2D object
if ( isPrinting )
g2 = (Graphics2D) g;
else {
backBuffer = (BufferedImage) this.createImage( w, h );
g2 = backBuffer.createGraphics();
g2.setColor(Color.white);
g2.fillRect(0, 0, w, h);
g2.setColor(Color.black);
}
/// sets font, RenderingHints.
setParams( g2 );
/// If flag is set, recalculate fontMetrics and reset the scrollbar
if ( updateFontMetrics || isPrinting ) {
/// NOTE: re-calculates in case G2 transform
/// is something other than NONE
calcFontMetrics( g2, w, h );
updateFontMetrics = false;
}
/// Calculate the amount of text that can be drawn...
calcTextRange();
/// Draw according to the set "Text to Use" mode
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
int charToDraw = drawStart;
if ( showGrid )
drawGrid( g2 );
if ( !isPrinting )
g.drawImage( backBuffer, 0, 0, this );
for ( int i = 0; i < numCharDown && charToDraw <= drawEnd; i++ ) {
for ( int j = 0; j < numCharAcross && charToDraw <= drawEnd; j++, charToDraw++ ) {
int gridLocX = j * gridWidth + canvasInset_X;
int gridLocY = i * gridHeight + canvasInset_Y;
modeSpecificDrawChar( g2, charToDraw,
gridLocX + gridWidth / 2,
gridLocY + maxAscent );
//if ( !isPrinting ) {
// g.setClip( gridLocX, gridLocY, gridWidth + 1, gridHeight + 1 );
// g.drawImage( backBuffer, 0, 0, this );
//}
}
}
}
else if ( textToUse == USER_TEXT ) {
g2.drawRect( 0, 0, w - 1, h - 1 );
if ( !isPrinting )
g.drawImage( backBuffer, 0, 0, this );
for ( int i = drawStart; i <= drawEnd; i++ ) {
int lineStartX = canvasInset_Y;
int lineStartY = ( i - drawStart ) * gridHeight + maxAscent;
modeSpecificDrawLine( g2, userText[i], lineStartX, lineStartY );
}
}
else {
float xPos, yPos = (float) canvasInset_Y;
g2.drawRect( 0, 0, w - 1, h - 1 );
if ( !isPrinting )
g.drawImage( backBuffer, 0, 0, this );
for ( int i = drawStart; i <= drawEnd; i++ ) {
TextLayout oneLine = (TextLayout) lineBreakTLs.elementAt( i );
xPos =
oneLine.isLeftToRight() ?
canvasInset_X : ( (float) w - oneLine.getAdvance() - canvasInset_X );
float fmData[] = {0, oneLine.getAscent(), 0, oneLine.getDescent(), 0, oneLine.getLeading()};
if (g2Transform != NONE) {
AffineTransform at = getAffineTransform(g2Transform);
at.transform( fmData, 0, fmData, 0, 3);
}
//yPos += oneLine.getAscent();
yPos += fmData[1]; // ascent
//oneLine.draw( g2, xPos, yPos );
tlDrawLine( g2, oneLine, xPos, yPos );
//yPos += oneLine.getDescent() + oneLine.getLeading();
yPos += fmData[3] + fmData[5]; // descent + leading
}
}
if ( !isPrinting )
g.drawImage( backBuffer, 0, 0, this );
g2.dispose();
}
/// Component paintComponent function...
/// Draws/Refreshes canvas according to flag(s) set by other functions
public void paintComponent( Graphics g ) {
if ( updateBackBuffer ) {
Dimension d = this.getSize();
isPrinting = false;
try {
drawText( g, d.width, d.height );
}
catch ( CannotDrawException e ) {
f2dt.fireChangeStatus( ERRORS[ e.id ], true );
super.paintComponent(g);
return;
}
}
else {
/// Screen refresh
g.drawImage( backBuffer, 0, 0, this );
}
showingError = false;
updateBackBuffer = false;
}
/// Printable interface function
/// Component print function...
public int print( Graphics g, PageFormat pf, int pageIndex ) {
if ( pageIndex == 0 ) {
/// Reset the last page index to max...
lastPage = Integer.MAX_VALUE;
currentlyShownChar = verticalBar.getValue() * numCharAcross;
}
if ( printMode == ONE_PAGE ) {
if ( pageIndex > 0 )
return NO_SUCH_PAGE;
}
else {
if ( pageIndex > lastPage )
return NO_SUCH_PAGE;
}
int pageWidth = (int) pf.getImageableWidth();
int pageHeight = (int) pf.getImageableHeight();
/// Back up metrics and other drawing info before printing modifies it
int backupDrawStart = drawStart, backupDrawEnd = drawEnd;
int backupNumCharAcross = numCharAcross, backupNumCharDown = numCharDown;
Vector backupLineBreakTLs = null;
if ( textToUse == FILE_TEXT )
backupLineBreakTLs = (Vector) lineBreakTLs.clone();
printPageNumber = pageIndex;
isPrinting = true;
/// Push the actual draw area 60 down to allow info to be printed
g.translate( (int) pf.getImageableX(), (int) pf.getImageableY() + 60 );
try {
drawText( g, pageWidth, pageHeight - 60 );
}
catch ( CannotDrawException e ) {
f2dt.fireChangeStatus( ERRORS[ e.id ], true );
return NO_SUCH_PAGE;
}
/// Draw information about what is being printed
String hints = ( " with antialias " + antiAliasType + "and" +
" fractional metrics " + fractionalMetricsType +
" and lcd contrast = " + lcdContrast);
String infoLine1 = ( "Printing" + MS_OPENING[textToUse] +
modeSpecificNumStr( drawStart ) + " to " +
modeSpecificNumStr( drawEnd ) + MS_CLOSING[textToUse] );
String infoLine2 = ( "With " + fontName + " " + STYLES[fontStyle] + " at " +
fontSize + " point size " + TRANSFORMS[fontTransform] );
String infoLine3 = "Using " + METHODS[drawMethod] + hints;
String infoLine4 = "Page: " + ( pageIndex + 1 );
g.setFont( new Font( "dialog", Font.PLAIN, 12 ));
g.setColor( Color.black );
g.translate( 0, -60 );
g.drawString( infoLine1, 15, 10 );
g.drawString( infoLine2, 15, 22 );
g.drawString( infoLine3, 15, 34 );
g.drawString( infoLine4, 15, 46 );
if ( drawEnd == drawLimit )
/// This indicates that the draw will be completed with this page
lastPage = pageIndex;
/// Restore the changed values back...
/// This is important for JScrollBar settings and LineBreak'ed TLs
drawStart = backupDrawStart;
drawEnd = backupDrawEnd;
numCharAcross = backupNumCharAcross;
numCharDown = backupNumCharDown;
if ( textToUse == FILE_TEXT )
lineBreakTLs = backupLineBreakTLs;
return PAGE_EXISTS;
}
/// Ouputs the current canvas into a given PNG file
public void writePNG( String fileName ) {
try {
ImageIO.write(backBuffer, "png", new java.io.File(fileName));
}
catch ( Exception e ) {
f2dt.fireChangeStatus( "ERROR: Failed to Save PNG image; See stack trace", true );
e.printStackTrace();
}
}
/// Figures out whether a character at the pointer location is valid
/// And if so, updates mouse location informations, as well as
/// the information on the status bar
private boolean checkMouseLoc( MouseEvent e ) {
if ( gridWidth != 0 && gridHeight != 0 )
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
int charLocX = ( e.getX() - canvasInset_X ) / gridWidth;
int charLocY = ( e.getY() - canvasInset_Y ) / gridHeight;
/// Check to make sure the mouse click location is within drawn area
if ( charLocX >= 0 && charLocY >= 0 &&
charLocX < numCharAcross && charLocY < numCharDown ) {
int mouseOverChar =
charLocX + ( verticalBar.getValue() + charLocY ) * numCharAcross;
if ( textToUse == RANGE_TEXT )
mouseOverChar += drawRange[0];
if ( mouseOverChar > drawEnd )
return false;
mouseOverCharX = charLocX;
mouseOverCharY = charLocY;
currMouseOverChar = mouseOverChar;
/// Update status bar
f2dt.fireChangeStatus( "Pointing to" + MS_OPENING[textToUse] +
modeSpecificNumStr( mouseOverChar ), false );
return true;
}
}
return false;
}
/// Shows (updates) the character zoom window
public void showZoomed() {
GlyphVector gv;
Font backup = testFont;
Point canvasLoc = this.getLocationOnScreen();
/// Calculate the zoom area's location and size...
int dialogOffsetX = (int) ( gridWidth * ( ZOOM - 1 ) / 2 );
int dialogOffsetY = (int) ( gridHeight * ( ZOOM - 1 ) / 2 );
int zoomAreaX =
mouseOverCharX * gridWidth + canvasInset_X - dialogOffsetX;
int zoomAreaY =
mouseOverCharY * gridHeight + canvasInset_Y - dialogOffsetY;
int zoomAreaWidth = (int) ( gridWidth * ZOOM );
int zoomAreaHeight = (int) ( gridHeight * ZOOM );
/// Position and set size of zoom window as needed
zoomWindow.setLocation( canvasLoc.x + zoomAreaX, canvasLoc.y + zoomAreaY );
if ( !nowZooming ) {
if ( zoomWindow.getWarningString() != null )
/// If this is not opened as a "secure" window,
/// it has a banner below the zoom dialog which makes it look really BAD
/// So enlarge it by a bit
zoomWindow.setSize( zoomAreaWidth + 1, zoomAreaHeight + 20 );
else
zoomWindow.setSize( zoomAreaWidth + 1, zoomAreaHeight + 1 );
}
/// Prepare zoomed image
zoomImage =
(BufferedImage) zoomWindow.createImage( zoomAreaWidth + 1,
zoomAreaHeight + 1 );
Graphics2D g2 = (Graphics2D) zoomImage.getGraphics();
testFont = testFont.deriveFont( fontSize * ZOOM );
setParams( g2 );
g2.setColor( Color.white );
g2.fillRect( 0, 0, zoomAreaWidth, zoomAreaHeight );
g2.setColor( Color.black );
g2.drawRect( 0, 0, zoomAreaWidth, zoomAreaHeight );
modeSpecificDrawChar( g2, currMouseOverChar,
zoomAreaWidth / 2, (int) ( maxAscent * ZOOM ));
g2.dispose();
if ( !nowZooming )
zoomWindow.show();
/// This is sort of redundant... since there is a paint function
/// inside zoomWindow definition that does the drawImage.
/// (I should be able to call just repaint() here)
/// However, for some reason, that paint function fails to respond
/// from second time and on; So I have to force the paint here...
zoomWindow.getGraphics().drawImage( zoomImage, 0, 0, this );
nowZooming = true;
prevZoomChar = currMouseOverChar;
testFont = backup;
// Windows does not repaint correctly, after
// a zoom. Thus, we need to force the canvas
// to repaint, but only once. After the first repaint,
// everything stabilizes. [ABP]
if ( firstTime() ) {
refresh();
}
}
/// Listener Functions
/// MouseListener interface function
/// Zooms a character when mouse is pressed above it
public void mousePressed( MouseEvent e ) {
if ( !showingError) {
if ( checkMouseLoc( e )) {
showZoomed();
this.setCursor( blankCursor );
}
}
}
/// MouseListener interface function
/// Redraws the area that was drawn over by zoomed character
public void mouseReleased( MouseEvent e ) {
if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
if ( nowZooming )
zoomWindow.hide();
nowZooming = false;
}
this.setCursor( Cursor.getDefaultCursor() );
}
/// MouseListener interface function
/// Resets the status bar to display range instead of a specific character
public void mouseExited( MouseEvent e ) {
if ( !showingError && !nowZooming )
f2dt.fireChangeStatus( backupStatusString, false );
}
/// MouseMotionListener interface function
/// Adjusts the status bar message when mouse moves over a character
public void mouseMoved( MouseEvent e ) {
if ( !showingError ) {
if ( !checkMouseLoc( e ))
f2dt.fireChangeStatus( backupStatusString, false );
}
}
/// MouseMotionListener interface function
/// Scrolls the zoomed character when mouse is dragged
public void mouseDragged( MouseEvent e ) {
if ( !showingError )
if ( nowZooming ) {
if ( checkMouseLoc( e ) && currMouseOverChar != prevZoomChar )
showZoomed();
}
}
/// Empty function to comply with interface requirement
public void mouseClicked( MouseEvent e ) {}
public void mouseEntered( MouseEvent e ) {}
}
private final class CannotDrawException extends RuntimeException {
/// Error ID
public final int id;
public CannotDrawException( int i ) {
id = i;
}
}
enum FMValues {
FMDEFAULT ("DEFAULT", VALUE_FRACTIONALMETRICS_DEFAULT),
FMOFF ("OFF", VALUE_FRACTIONALMETRICS_OFF),
FMON ("ON", VALUE_FRACTIONALMETRICS_ON);
private String name;
private Object hint;
private static FMValues[] valArray;
FMValues(String s, Object o) {
name = s;
hint = o;
}
public String toString() {
return name;
}
public Object getHint() {
return hint;
}
public static Object getValue(int ordinal) {
if (valArray == null) {
valArray = (FMValues[])EnumSet.allOf(FMValues.class).toArray(new FMValues[0]);
}
for (int i=0;i<valArray.length;i++) {
if (valArray[i].ordinal() == ordinal) {
return valArray[i];
}
}
return valArray[0];
}
private static FMValues[] getArray() {
if (valArray == null) {
valArray = (FMValues[])EnumSet.allOf(FMValues.class).toArray(new FMValues[0]);
}
return valArray;
}
public static int getHintVal(Object hint) {
getArray();
for (int i=0;i<valArray.length;i++) {
if (valArray[i].getHint() == hint) {
return i;
}
}
return 0;
}
}
enum AAValues {
AADEFAULT ("DEFAULT", VALUE_TEXT_ANTIALIAS_DEFAULT),
AAOFF ("OFF", VALUE_TEXT_ANTIALIAS_OFF),
AAON ("ON", VALUE_TEXT_ANTIALIAS_ON),
AAGASP ("GASP", VALUE_TEXT_ANTIALIAS_GASP),
AALCDHRGB ("LCD_HRGB", VALUE_TEXT_ANTIALIAS_LCD_HRGB),
AALCDHBGR ("LCD_HBGR", VALUE_TEXT_ANTIALIAS_LCD_HBGR),
AALCDVRGB ("LCD_VRGB", VALUE_TEXT_ANTIALIAS_LCD_VRGB),
AALCDVBGR ("LCD_VBGR", VALUE_TEXT_ANTIALIAS_LCD_VBGR);
private String name;
private Object hint;
private static AAValues[] valArray;
AAValues(String s, Object o) {
name = s;
hint = o;
}
public String toString() {
return name;
}
public Object getHint() {
return hint;
}
public static boolean isLCDMode(Object o) {
return (o instanceof AAValues &&
((AAValues)o).ordinal() >= AALCDHRGB.ordinal());
}
public static Object getValue(int ordinal) {
if (valArray == null) {
valArray = (AAValues[])EnumSet.allOf(AAValues.class).toArray(new AAValues[0]);
}
for (int i=0;i<valArray.length;i++) {
if (valArray[i].ordinal() == ordinal) {
return valArray[i];
}
}
return valArray[0];
}
private static AAValues[] getArray() {
if (valArray == null) {
Object [] oa = EnumSet.allOf(AAValues.class).toArray(new AAValues[0]);
valArray = (AAValues[])(EnumSet.allOf(AAValues.class).toArray(new AAValues[0]));
}
return valArray;
}
public static int getHintVal(Object hint) {
getArray();
for (int i=0;i<valArray.length;i++) {
if (valArray[i].getHint() == hint) {
return i;
}
}
return 0;
}
}
private static Integer defaultContrast;
static Integer getDefaultLCDContrast() {
if (defaultContrast == null) {
GraphicsConfiguration gc =
GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
Graphics2D g2d =
(Graphics2D)(gc.createCompatibleImage(1,1).getGraphics());
defaultContrast = (Integer)
g2d.getRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST);
}
return defaultContrast;
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/demo/jfc/Font2DTest/FontPanel.java |
180,188 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.service;
import java.io.File;
import java.util.List;
import net.grinder.common.GrinderProperties;
import net.grinder.common.processidentity.AgentIdentity;
import net.grinder.statistics.StatisticsIndexMap;
/**
* {@link SingleConsole} interface for plugin use.
*
*/
@SuppressWarnings("JavadocReference")
public interface ISingleConsole {
/**
* Mark the cancel status.
*/
void cancel();
/**
* Get current running time in ms.
*
* @return running time
*/
long getCurrentRunningTime();
/**
* Get the current total execution count(test count + error count).
*
* @return current total execution count
*/
long getCurrentExecutionCount();
/**
* Get statistics index map used.
*
* @return {@link StatisticsIndexMap}
*/
StatisticsIndexMap getStatisticsIndexMap();
/**
* Get report path.
*
* @return report path
*/
File getReportPath();
/**
* Get peak TPS.
*
* @return peak tps
*/
double getPeakTpsForGraph();
/**
* Get the count of current running threads.
*
* @return running threads.
*/
int getRunningThread();
/**
* Get the count of current running processes.
*
* @return running processes
*/
int getRunningProcess();
/**
* Get the all agents attached in this processes.
*
* @return {@link AgentIdentity} list
* @since 3.1.2
*/
List<AgentIdentity> getAllAttachedAgents();
/**
* Return the assigned console port.
*
* @return console port
*/
int getConsolePort();
/**
* Get the associated grinder properties.
*
* @return grinder properties. null if the test is not started.
*/
GrinderProperties getGrinderProperties();
}
| naver/ngrinder | ngrinder-core/src/main/java/org/ngrinder/service/ISingleConsole.java |
180,190 | package com.alibaba.druid.pool;
import com.alibaba.druid.Constants;
import com.alibaba.druid.DbType;
import com.alibaba.druid.TransactionTimeoutException;
import com.alibaba.druid.VERSION;
import com.alibaba.druid.filter.AutoLoad;
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.mock.MockDriver;
import com.alibaba.druid.pool.vendor.MySqlExceptionSorter;
import com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker;
import com.alibaba.druid.pool.vendor.NullExceptionSorter;
import com.alibaba.druid.proxy.DruidDriver;
import com.alibaba.druid.proxy.jdbc.DataSourceProxyConfig;
import com.alibaba.druid.proxy.jdbc.TransactionInfo;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectQuery;
import com.alibaba.druid.sql.ast.statement.SQLSelectQueryBlock;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.stat.DruidDataSourceStatManager;
import com.alibaba.druid.stat.JdbcDataSourceStat;
import com.alibaba.druid.stat.JdbcSqlStat;
import com.alibaba.druid.stat.JdbcSqlStatValue;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.JMXUtils;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.druid.util.Utils;
import com.alibaba.druid.wall.WallFilter;
import com.alibaba.druid.wall.WallProviderStatValue;
import org.elasticsearch.client.internal.Client;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.PooledConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.alibaba.druid.util.Utils.getBoolean;
/**
* Created by allwefantasy on 8/30/16.
*/
public class ElasticSearchDruidDataSource extends DruidDataSource {
private final static Log LOG = LogFactory.getLog(ElasticSearchDruidDataSource.class);
private static final long serialVersionUID = 1L;
// stats
private volatile long recycleErrorCount = 0L;
private long connectCount = 0L;
private long closeCount = 0L;
private volatile long connectErrorCount = 0L;
private long recycleCount = 0L;
private long removeAbandonedCount = 0L;
private long notEmptyWaitCount = 0L;
private long notEmptySignalCount = 0L;
private long notEmptyWaitNanos = 0L;
private int keepAliveCheckCount = 0;
private int activePeak = 0;
private long activePeakTime = 0;
private int poolingPeak = 0;
private long poolingPeakTime = 0;
// store
private volatile DruidConnectionHolder[] connections;
private int poolingCount = 0;
private int activeCount = 0;
private volatile long discardCount = 0;
private int notEmptyWaitThreadCount = 0;
private int notEmptyWaitThreadPeak = 0;
//
private DruidConnectionHolder[] evictConnections;
private DruidConnectionHolder[] keepAliveConnections;
// threads
private volatile ScheduledFuture<?> destroySchedulerFuture;
private DestroyTask destroyTask;
private volatile Future<?> createSchedulerFuture;
private CreateConnectionThread createConnectionThread;
private DestroyConnectionThread destroyConnectionThread;
private LogStatsThread logStatsThread;
private int createTaskCount;
private final CountDownLatch initedLatch = new CountDownLatch(2);
private volatile boolean enable = true;
private boolean resetStatEnable = true;
private volatile long resetCount = 0L;
private String initStackTrace;
private volatile boolean closing = false;
private volatile boolean closed = false;
private long closeTimeMillis = -1L;
private boolean useGlobalDataSourceStat = false;
private boolean mbeanRegistered = false;
private boolean logDifferentThread = true;
private volatile boolean keepAlive = false;
private boolean asyncInit = false;
private static List<Filter> autoFilters = null;
private boolean loadSpifilterSkip = false;
// elasticsearch client
private final Client client;
public ElasticSearchDruidDataSource(Client client) {
this(false, client);
}
public ElasticSearchDruidDataSource(boolean fairLock, Client client) {
super(fairLock);
this.client = client;
configFromPropety(System.getProperties());
}
public boolean isAsyncInit() {
return asyncInit;
}
public void setAsyncInit(boolean asyncInit) {
this.asyncInit = asyncInit;
}
public void configFromPropety(Properties properties) {
{
String property = properties.getProperty("druid.name");
if (property != null) {
this.setName(property);
}
}
{
String property = properties.getProperty("druid.url");
if (property != null) {
this.setUrl(property);
}
}
{
String property = properties.getProperty("druid.username");
if (property != null) {
this.setUsername(property);
}
}
{
String property = properties.getProperty("druid.password");
if (property != null) {
this.setPassword(property);
}
}
{
Boolean value = getBoolean(properties, "druid.testWhileIdle");
if (value != null) {
this.testWhileIdle = value;
}
}
{
Boolean value = getBoolean(properties, "druid.testOnBorrow");
if (value != null) {
this.testOnBorrow = value;
}
}
{
String property = properties.getProperty("druid.validationQuery");
if (property != null && property.length() > 0) {
this.setValidationQuery(property);
}
}
{
Boolean value = getBoolean(properties, "druid.useGlobalDataSourceStat");
if (value != null) {
this.setUseGlobalDataSourceStat(value);
}
}
{
Boolean value = getBoolean(properties, "druid.useGloalDataSourceStat"); // compatible for early versions
if (value != null) {
this.setUseGlobalDataSourceStat(value);
}
}
{
Boolean value = getBoolean(properties, "druid.asyncInit"); // compatible for early versions
if (value != null) {
this.setAsyncInit(value);
}
}
{
String property = properties.getProperty("druid.filters");
if (property != null && property.length() > 0) {
try {
this.setFilters(property);
} catch (SQLException e) {
LOG.error("setFilters error", e);
}
}
}
{
String property = properties.getProperty(Constants.DRUID_TIME_BETWEEN_LOG_STATS_MILLIS);
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setTimeBetweenLogStatsMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property '" + Constants.DRUID_TIME_BETWEEN_LOG_STATS_MILLIS + "'", e);
}
}
}
{
String property = properties.getProperty(Constants.DRUID_STAT_SQL_MAX_SIZE);
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
if (dataSourceStat != null) {
dataSourceStat.setMaxSqlSize(value);
}
} catch (NumberFormatException e) {
LOG.error("illegal property '" + Constants.DRUID_STAT_SQL_MAX_SIZE + "'", e);
}
}
}
{
Boolean value = getBoolean(properties, "druid.clearFiltersEnable");
if (value != null) {
this.setClearFiltersEnable(value);
}
}
{
Boolean value = getBoolean(properties, "druid.resetStatEnable");
if (value != null) {
this.setResetStatEnable(value);
}
}
{
String property = properties.getProperty("druid.notFullTimeoutRetryCount");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setNotFullTimeoutRetryCount(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.notFullTimeoutRetryCount'", e);
}
}
}
{
String property = properties.getProperty("druid.timeBetweenEvictionRunsMillis");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setTimeBetweenEvictionRunsMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.timeBetweenEvictionRunsMillis'", e);
}
}
}
{
String property = properties.getProperty("druid.maxWaitThreadCount");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setMaxWaitThreadCount(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.maxWaitThreadCount'", e);
}
}
}
{
String property = properties.getProperty("druid.maxWait");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setMaxWait(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.maxWait'", e);
}
}
}
{
Boolean value = getBoolean(properties, "druid.failFast");
if (value != null) {
this.setFailFast(value);
}
}
{
String property = properties.getProperty("druid.phyTimeoutMillis");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setPhyTimeoutMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.phyTimeoutMillis'", e);
}
}
}
{
String property = properties.getProperty("druid.phyMaxUseCount");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setPhyMaxUseCount(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.phyMaxUseCount'", e);
}
}
}
{
String property = properties.getProperty("druid.minEvictableIdleTimeMillis");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setMinEvictableIdleTimeMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.minEvictableIdleTimeMillis'", e);
}
}
}
{
String property = properties.getProperty("druid.maxEvictableIdleTimeMillis");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setMaxEvictableIdleTimeMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.maxEvictableIdleTimeMillis'", e);
}
}
}
{
Boolean value = getBoolean(properties, "druid.keepAlive");
if (value != null) {
this.setKeepAlive(value);
}
}
{
String property = properties.getProperty("druid.keepAliveBetweenTimeMillis");
if (property != null && property.length() > 0) {
try {
long value = Long.parseLong(property);
this.setKeepAliveBetweenTimeMillis(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.keepAliveBetweenTimeMillis'", e);
}
}
}
{
Boolean value = getBoolean(properties, "druid.poolPreparedStatements");
if (value != null) {
this.setPoolPreparedStatements0(value);
}
}
{
Boolean value = getBoolean(properties, "druid.initVariants");
if (value != null) {
this.setInitVariants(value);
}
}
{
Boolean value = getBoolean(properties, "druid.initGlobalVariants");
if (value != null) {
this.setInitGlobalVariants(value);
}
}
{
Boolean value = getBoolean(properties, "druid.useUnfairLock");
if (value != null) {
this.setUseUnfairLock(value);
}
}
{
String property = properties.getProperty("druid.driverClassName");
if (property != null) {
this.setDriverClassName(property);
}
}
{
String property = properties.getProperty("druid.initialSize");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setInitialSize(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.initialSize'", e);
}
}
}
{
String property = properties.getProperty("druid.minIdle");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setMinIdle(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.minIdle'", e);
}
}
}
{
String property = properties.getProperty("druid.maxActive");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setMaxActive(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.maxActive'", e);
}
}
}
{
Boolean value = getBoolean(properties, "druid.killWhenSocketReadTimeout");
if (value != null) {
setKillWhenSocketReadTimeout(value);
}
}
{
String property = properties.getProperty("druid.connectProperties");
if (property != null) {
this.setConnectionProperties(property);
}
}
{
String property = properties.getProperty("druid.maxPoolPreparedStatementPerConnectionSize");
if (property != null && property.length() > 0) {
try {
int value = Integer.parseInt(property);
this.setMaxPoolPreparedStatementPerConnectionSize(value);
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.maxPoolPreparedStatementPerConnectionSize'", e);
}
}
}
{
String property = properties.getProperty("druid.initConnectionSqls");
if (property != null && property.length() > 0) {
try {
StringTokenizer tokenizer = new StringTokenizer(property, ";");
setConnectionInitSqls(Collections.list(tokenizer));
} catch (NumberFormatException e) {
LOG.error("illegal property 'druid.initConnectionSqls'", e);
}
}
}
{
String property = System.getProperty("druid.load.spifilter.skip");
if (property != null && !"false".equals(property)) {
loadSpifilterSkip = true;
}
}
}
public boolean isKillWhenSocketReadTimeout() {
return killWhenSocketReadTimeout;
}
public void setKillWhenSocketReadTimeout(boolean killWhenSocketTimeOut) {
this.killWhenSocketReadTimeout = killWhenSocketTimeOut;
}
public boolean isUseGlobalDataSourceStat() {
return useGlobalDataSourceStat;
}
public void setUseGlobalDataSourceStat(boolean useGlobalDataSourceStat) {
this.useGlobalDataSourceStat = useGlobalDataSourceStat;
}
public boolean isKeepAlive() {
return keepAlive;
}
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public String getInitStackTrace() {
return initStackTrace;
}
public boolean isResetStatEnable() {
return resetStatEnable;
}
public void setResetStatEnable(boolean resetStatEnable) {
this.resetStatEnable = resetStatEnable;
if (dataSourceStat != null) {
dataSourceStat.setResetStatEnable(resetStatEnable);
}
}
public long getDiscardCount() {
return discardCount;
}
public void restart() throws SQLException {
lock.lock();
try {
if (activeCount > 0) {
throw new SQLException("can not restart, activeCount not zero. " + activeCount);
}
if (LOG.isInfoEnabled()) {
LOG.info("{dataSource-" + this.getID() + "} restart");
}
this.close();
this.resetStat();
this.inited = false;
this.enable = true;
this.closed = false;
} finally {
lock.unlock();
}
}
public void resetStat() {
if (!isResetStatEnable()) {
return;
}
lock.lock();
try {
connectCount = 0;
closeCount = 0;
discardCount = 0;
recycleCount = 0;
createCount = 0L;
directCreateCount = 0;
destroyCount = 0L;
removeAbandonedCount = 0;
notEmptyWaitCount = 0;
notEmptySignalCount = 0L;
notEmptyWaitNanos = 0;
activePeak = activeCount;
activePeakTime = 0;
poolingPeak = 0;
createTimespan = 0;
lastError = null;
lastErrorTimeMillis = 0;
lastCreateError = null;
lastCreateErrorTimeMillis = 0;
} finally {
lock.unlock();
}
connectErrorCountUpdater.set(this, 0);
errorCountUpdater.set(this, 0);
commitCountUpdater.set(this, 0);
rollbackCountUpdater.set(this, 0);
startTransactionCountUpdater.set(this, 0);
cachedPreparedStatementHitCountUpdater.set(this, 0);
closedPreparedStatementCountUpdater.set(this, 0);
preparedStatementCountUpdater.set(this, 0);
transactionHistogram.reset();
cachedPreparedStatementDeleteCountUpdater.set(this, 0);
recycleErrorCountUpdater.set(this, 0);
resetCountUpdater.incrementAndGet(this);
}
public long getResetCount() {
return this.resetCount;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
lock.lock();
try {
this.enable = enable;
if (!enable) {
notEmpty.signalAll();
notEmptySignalCount++;
}
} finally {
lock.unlock();
}
}
public void setPoolPreparedStatements(boolean value) {
setPoolPreparedStatements0(value);
}
private void setPoolPreparedStatements0(boolean value) {
if (this.poolPreparedStatements == value) {
return;
}
this.poolPreparedStatements = value;
if (!inited) {
return;
}
if (LOG.isInfoEnabled()) {
LOG.info("set poolPreparedStatements " + this.poolPreparedStatements + " -> " + value);
}
if (!value) {
lock.lock();
try {
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connection = connections[i];
for (PreparedStatementHolder holder : connection.getStatementPool().getMap().values()) {
closePreapredStatement(holder);
}
connection.getStatementPool().getMap().clear();
}
} finally {
lock.unlock();
}
}
}
public void setMaxActive(int maxActive) {
if (this.maxActive == maxActive) {
return;
}
if (maxActive == 0) {
throw new IllegalArgumentException("maxActive can't not set zero");
}
if (!inited) {
this.maxActive = maxActive;
return;
}
if (maxActive < this.minIdle) {
throw new IllegalArgumentException("maxActive less than minIdle, " + maxActive + " < " + this.minIdle);
}
if (LOG.isInfoEnabled()) {
LOG.info("maxActive changed : " + this.maxActive + " -> " + maxActive);
}
lock.lock();
try {
int allCount = this.poolingCount + this.activeCount;
if (maxActive > allCount) {
this.connections = Arrays.copyOf(this.connections, maxActive);
evictConnections = new DruidConnectionHolder[maxActive];
keepAliveConnections = new DruidConnectionHolder[maxActive];
} else {
this.connections = Arrays.copyOf(this.connections, allCount);
evictConnections = new DruidConnectionHolder[allCount];
keepAliveConnections = new DruidConnectionHolder[allCount];
}
this.maxActive = maxActive;
} finally {
lock.unlock();
}
}
@Override
public void validateConnection(Connection conn) throws SQLException {
}
@SuppressWarnings("rawtypes")
public void setConnectProperties(Properties properties) {
if (properties == null) {
properties = new Properties();
}
boolean equals;
if (properties.size() == this.connectProperties.size()) {
equals = true;
for (Map.Entry entry : properties.entrySet()) {
Object value = this.connectProperties.get(entry.getKey());
Object entryValue = entry.getValue();
if (value == null && entryValue != null) {
equals = false;
break;
}
if (!value.equals(entry.getValue())) {
equals = false;
break;
}
}
} else {
equals = false;
}
if (!equals) {
if (inited && LOG.isInfoEnabled()) {
LOG.info("connectProperties changed : " + this.connectProperties + " -> " + properties);
}
configFromPropety(properties);
for (Filter filter : this.filters) {
filter.configFromProperties(properties);
}
if (exceptionSorter != null) {
exceptionSorter.configFromProperties(properties);
}
if (validConnectionChecker != null) {
validConnectionChecker.configFromProperties(properties);
}
if (statLogger != null) {
statLogger.configFromProperties(properties);
}
}
this.connectProperties = properties;
}
public void init() throws SQLException {
if (inited) {
return;
}
// bug fixed for dead lock, for issue #2980
DruidDriver.getInstance();
final ReentrantLock lock = this.lock;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw new SQLException("interrupt", e);
}
boolean init = false;
try {
if (inited) {
return;
}
initStackTrace = Utils.toString(Thread.currentThread().getStackTrace());
this.id = DruidDriver.createDataSourceId();
if (this.id > 1) {
long delta = (this.id - 1) * 100000;
this.connectionIdSeedUpdater.addAndGet(this, delta);
this.statementIdSeedUpdater.addAndGet(this, delta);
this.resultSetIdSeedUpdater.addAndGet(this, delta);
this.transactionIdSeedUpdater.addAndGet(this, delta);
}
if (this.jdbcUrl != null) {
this.jdbcUrl = this.jdbcUrl.trim();
initFromWrapDriverUrl();
}
for (Filter filter : filters) {
filter.init(this);
}
if (this.dbTypeName == null || this.dbTypeName.length() == 0) {
this.dbTypeName = JdbcUtils.getDbType(jdbcUrl, null);
}
DbType dbType = DbType.of(this.dbTypeName);
if (JdbcUtils.isMysqlDbType(dbType)) {
boolean cacheServerConfigurationSet = false;
if (this.connectProperties.containsKey("cacheServerConfiguration")) {
cacheServerConfigurationSet = true;
} else if (this.jdbcUrl.indexOf("cacheServerConfiguration") != -1) {
cacheServerConfigurationSet = true;
}
if (cacheServerConfigurationSet) {
this.connectProperties.put("cacheServerConfiguration", "true");
}
}
if (maxActive <= 0) {
throw new IllegalArgumentException("illegal maxActive " + maxActive);
}
if (maxActive < minIdle) {
throw new IllegalArgumentException("illegal maxActive " + maxActive);
}
if (getInitialSize() > maxActive) {
throw new IllegalArgumentException("illegal initialSize " + this.initialSize + ", maxActive " + maxActive);
}
if (timeBetweenLogStatsMillis > 0 && useGlobalDataSourceStat) {
throw new IllegalArgumentException("timeBetweenLogStatsMillis not support useGlobalDataSourceStat=true");
}
if (maxEvictableIdleTimeMillis < minEvictableIdleTimeMillis) {
throw new SQLException("maxEvictableIdleTimeMillis must be grater than minEvictableIdleTimeMillis");
}
if (this.driverClass != null) {
this.driverClass = driverClass.trim();
}
initFromSPIServiceLoader();
initCheck();
initExceptionSorter();
initValidConnectionChecker();
validationQueryCheck();
if (isUseGlobalDataSourceStat()) {
dataSourceStat = JdbcDataSourceStat.getGlobal();
if (dataSourceStat == null) {
dataSourceStat = new JdbcDataSourceStat("Global", "Global", this.dbTypeName);
JdbcDataSourceStat.setGlobal(dataSourceStat);
}
if (dataSourceStat.getDbType() == null) {
dataSourceStat.setDbType(this.dbTypeName);
}
} else {
dataSourceStat = new JdbcDataSourceStat(this.name, this.jdbcUrl, this.dbTypeName, this.connectProperties);
}
dataSourceStat.setResetStatEnable(this.resetStatEnable);
connections = new DruidConnectionHolder[maxActive];
evictConnections = new DruidConnectionHolder[maxActive];
keepAliveConnections = new DruidConnectionHolder[maxActive];
SQLException connectError = null;
if (createScheduler != null && asyncInit) {
for (int i = 0; i < initialSize; ++i) {
createTaskCount++;
CreateConnectionTask task = new CreateConnectionTask(true);
this.createSchedulerFuture = createScheduler.submit(task);
}
} else if (!asyncInit) {
// init connections
while (poolingCount < initialSize) {
try {
PhysicalConnectionInfo pyConnectInfo = createPhysicalConnection();
DruidConnectionHolder holder = new DruidConnectionHolder(this, pyConnectInfo);
connections[poolingCount++] = holder;
} catch (SQLException ex) {
LOG.error("init datasource error, url: " + this.getUrl(), ex);
if (initExceptionThrow) {
connectError = ex;
break;
} else {
Thread.sleep(3000);
}
}
}
if (poolingCount > 0) {
poolingPeak = poolingCount;
poolingPeakTime = System.currentTimeMillis();
}
}
createAndLogThread();
createAndStartCreatorThread();
createAndStartDestroyThread();
initedLatch.await();
init = true;
initedTime = new Date();
registerMbean();
if (connectError != null && poolingCount == 0) {
throw connectError;
}
if (keepAlive) {
// async fill to minIdle
if (createScheduler != null) {
for (int i = 0; i < minIdle; ++i) {
createTaskCount++;
CreateConnectionTask task = new CreateConnectionTask(true);
this.createSchedulerFuture = createScheduler.submit(task);
}
} else {
this.emptySignal();
}
}
} catch (SQLException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
} catch (RuntimeException e){
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (Error e){
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} finally {
inited = true;
lock.unlock();
if (init && LOG.isInfoEnabled()) {
String msg = "{dataSource-" + this.getID();
if (this.name != null && !this.name.isEmpty()) {
msg += ",";
msg += this.name;
}
msg += "} inited";
LOG.info(msg);
}
}
}
@Override
public PhysicalConnectionInfo createPhysicalConnection() throws SQLException {
String url = this.getUrl();
Properties connectProperties = getConnectProperties();
Connection conn = null;
long connectStartNanos = System.nanoTime();
long connectedNanos, initedNanos, validatedNanos;
Map<String, Object> variables = initVariants
? new HashMap<String, Object>()
: null;
Map<String, Object> globalVariables = initGlobalVariants
? new HashMap<String, Object>()
: null;
createStartNanosUpdater.set(this, connectStartNanos);
creatingCountUpdater.incrementAndGet(this);
try {
conn = createPhysicalConnection(url, connectProperties);
connectedNanos = System.nanoTime();
if (conn == null) {
throw new SQLException("connect error, url " + url + ", driverClass " + this.driverClass);
}
initPhysicalConnection(conn, variables, globalVariables);
initedNanos = System.nanoTime();
validateConnection(conn);
validatedNanos = System.nanoTime();
setFailContinuous(false);
setCreateError(null);
} catch (SQLException ex) {
setCreateError(ex);
JdbcUtils.close(conn);
throw ex;
} catch (RuntimeException ex) {
setCreateError(ex);
JdbcUtils.close(conn);
throw ex;
} catch (Error ex) {
createErrorCountUpdater.incrementAndGet(this);
setCreateError(ex);
JdbcUtils.close(conn);
throw ex;
} finally {
long nano = System.nanoTime() - connectStartNanos;
createTimespan += nano;
creatingCountUpdater.decrementAndGet(this);
}
return new PhysicalConnectionInfo(conn, connectStartNanos, connectedNanos, initedNanos, validatedNanos, variables, globalVariables);
}
@Override
public Connection createPhysicalConnection(String url, Properties info) throws SQLException {
Connection conn = new ElasticSearchConnection(client);
createCountUpdater.incrementAndGet(this);
return conn;
}
private void createAndLogThread() {
if (this.timeBetweenLogStatsMillis <= 0) {
return;
}
String threadName = "Druid-ConnectionPool-Log-" + System.identityHashCode(this);
logStatsThread = new LogStatsThread(threadName);
logStatsThread.start();
this.resetStatEnable = false;
}
protected void createAndStartDestroyThread() {
destroyTask = new DestroyTask();
if (destroyScheduler != null) {
long period = timeBetweenEvictionRunsMillis;
if (period <= 0) {
period = 1000;
}
destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destroyTask, period, period,
TimeUnit.MILLISECONDS);
initedLatch.countDown();
return;
}
String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this);
destroyConnectionThread = new DestroyConnectionThread(threadName);
destroyConnectionThread.start();
}
protected void createAndStartCreatorThread() {
if (createScheduler == null) {
String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this);
createConnectionThread = new CreateConnectionThread(threadName);
createConnectionThread.start();
return;
}
initedLatch.countDown();
}
/**
* load filters from SPI ServiceLoader
*
* @see ServiceLoader
*/
private void initFromSPIServiceLoader() {
if (loadSpifilterSkip) {
return;
}
if (autoFilters == null) {
List<Filter> filters = new ArrayList<Filter>();
ServiceLoader<Filter> autoFilterLoader = ServiceLoader.load(Filter.class);
for (Filter filter : autoFilterLoader) {
AutoLoad autoLoad = filter.getClass().getAnnotation(AutoLoad.class);
if (autoLoad != null && autoLoad.value()) {
filters.add(filter);
}
}
autoFilters = filters;
}
for (Filter filter : autoFilters) {
if (LOG.isInfoEnabled()) {
LOG.info("load filter from spi :" + filter.getClass().getName());
}
addFilter(filter);
}
}
private void initFromWrapDriverUrl() throws SQLException {
if (!jdbcUrl.startsWith(DruidDriver.DEFAULT_PREFIX)) {
return;
}
DataSourceProxyConfig config = DruidDriver.parseConfig(jdbcUrl, null);
this.driverClass = config.getRawDriverClassName();
LOG.error("error url : '" + jdbcUrl + "', it should be : '" + config.getRawUrl() + "'");
this.jdbcUrl = config.getRawUrl();
if (this.name == null) {
this.name = config.getName();
}
for (Filter filter : config.getFilters()) {
addFilter(filter);
}
}
/**
* 会去重复
*
* @param filter
*/
private void addFilter(Filter filter) {
boolean exists = false;
for (Filter initedFilter : this.filters) {
if (initedFilter.getClass() == filter.getClass()) {
exists = true;
break;
}
}
if (!exists) {
filter.init(this);
this.filters.add(filter);
}
}
private void validationQueryCheck() {
if (!(testOnBorrow || testOnReturn || testWhileIdle)) {
return;
}
if (this.validConnectionChecker != null) {
return;
}
if (this.validationQuery != null && this.validationQuery.length() > 0) {
return;
}
String errorMessage = "";
if (testOnBorrow) {
errorMessage += "testOnBorrow is true, ";
}
if (testOnReturn) {
errorMessage += "testOnReturn is true, ";
}
if (testWhileIdle) {
errorMessage += "testWhileIdle is true, ";
}
LOG.error(errorMessage + "validationQuery not set");
}
protected void initCheck() throws SQLException {
DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.oracle) {
isOracle = true;
if (driver.getMajorVersion() < 10) {
throw new SQLException("not support oracle driver " + driver.getMajorVersion() + "."
+ driver.getMinorVersion());
}
if (driver.getMajorVersion() == 10 && isUseOracleImplicitCache()) {
this.getConnectProperties().setProperty("oracle.jdbc.FreeMemoryOnEnterImplicitCache", "true");
}
oracleValidationQueryCheck();
} else if (dbType == DbType.db2) {
db2ValidationQueryCheck();
} else if (dbType == DbType.mysql
|| JdbcUtils.MYSQL_DRIVER.equals(this.driverClass)
|| JdbcUtils.MYSQL_DRIVER_6.equals(this.driverClass)
) {
isMySql = true;
}
if (removeAbandoned) {
LOG.warn("removeAbandoned is true, not use in production.");
}
}
private void oracleValidationQueryCheck() {
if (validationQuery == null) {
return;
}
if (validationQuery.length() == 0) {
return;
}
SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, DbType.of(this.dbTypeName));
List<SQLStatement> stmtList = sqlStmtParser.parseStatementList();
if (stmtList.size() != 1) {
return;
}
SQLStatement stmt = stmtList.get(0);
if (!(stmt instanceof SQLSelectStatement)) {
return;
}
SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
if (query instanceof SQLSelectQueryBlock) {
if (((SQLSelectQueryBlock) query).getFrom() == null) {
LOG.error("invalid oracle validationQuery. " + validationQuery + ", may should be : " + validationQuery
+ " FROM DUAL");
}
}
}
private void db2ValidationQueryCheck() {
if (validationQuery == null) {
return;
}
if (validationQuery.length() == 0) {
return;
}
SQLStatementParser sqlStmtParser = SQLParserUtils.createSQLStatementParser(validationQuery, DbType.of(this.dbTypeName));
List<SQLStatement> stmtList = sqlStmtParser.parseStatementList();
if (stmtList.size() != 1) {
return;
}
SQLStatement stmt = stmtList.get(0);
if (!(stmt instanceof SQLSelectStatement)) {
return;
}
SQLSelectQuery query = ((SQLSelectStatement) stmt).getSelect().getQuery();
if (query instanceof SQLSelectQueryBlock) {
if (((SQLSelectQueryBlock) query).getFrom() == null) {
LOG.error("invalid db2 validationQuery. " + validationQuery + ", may should be : " + validationQuery
+ " FROM SYSDUMMY");
}
}
}
private void initValidConnectionChecker() {
if (this.validConnectionChecker != null) {
return;
}
this.validConnectionChecker = new MySqlValidConnectionChecker();
}
private void initExceptionSorter() {
if (exceptionSorter instanceof NullExceptionSorter) {
if (driver instanceof MockDriver) {
return;
}
} else if (this.exceptionSorter != null) {
return;
}
this.exceptionSorter = new MySqlExceptionSorter();
this.isMySql = true;
}
@Override
public DruidPooledConnection getConnection() throws SQLException {
return getConnection(maxWait);
}
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
init();
return getConnectionDirect(maxWaitMillis);
}
@Override
public PooledConnection getPooledConnection() throws SQLException {
return getConnection(maxWait);
}
@Override
public PooledConnection getPooledConnection(String user, String password) throws SQLException {
throw new UnsupportedOperationException("Not supported by DruidDataSource");
}
public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException {
int notFullTimeoutRetryCnt = 0;
for (; ; ) {
// handle notFullTimeoutRetry
DruidPooledConnection poolableConnection;
try {
poolableConnection = getConnectionInternal(maxWaitMillis);
} catch (GetConnectionTimeoutException ex) {
if (notFullTimeoutRetryCnt <= this.notFullTimeoutRetryCount && !isFull()) {
notFullTimeoutRetryCnt++;
if (LOG.isWarnEnabled()) {
LOG.warn("get connection timeout retry : " + notFullTimeoutRetryCnt);
}
continue;
}
throw ex;
}
if (removeAbandoned) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
poolableConnection.connectStackTrace = stackTrace;
poolableConnection.setConnectedTimeNano();
poolableConnection.traceEnable = true;
activeConnectionLock.lock();
try {
activeConnections.put(poolableConnection, PRESENT);
} finally {
activeConnectionLock.unlock();
}
}
return poolableConnection;
}
}
/**
* 抛弃连接,不进行回收,而是抛弃
*
* @param realConnection
*/
public void discardConnection(Connection realConnection) {
JdbcUtils.close(realConnection);
lock.lock();
try {
activeCount--;
discardCount++;
if (activeCount <= minIdle) {
emptySignal();
}
} finally {
lock.unlock();
}
}
private DruidPooledConnection getConnectionInternal(long maxWait) throws SQLException {
if (closed) {
connectErrorCountUpdater.incrementAndGet(this);
throw new DataSourceClosedException("dataSource already closed at " + new Date(closeTimeMillis));
}
if (!enable) {
connectErrorCountUpdater.incrementAndGet(this);
throw new DataSourceDisableException();
}
final long nanos = TimeUnit.MILLISECONDS.toNanos(maxWait);
final int maxWaitThreadCount = this.maxWaitThreadCount;
DruidConnectionHolder holder;
for (boolean createDirect = false;;) {
if (createDirect) {
createStartNanosUpdater.set(this, System.nanoTime());
if (creatingCountUpdater.compareAndSet(this, 0, 1)) {
PhysicalConnectionInfo pyConnInfo = ElasticSearchDruidDataSource.this.createPhysicalConnection();
holder = new DruidConnectionHolder(this, pyConnInfo);
holder.lastActiveTimeMillis = System.currentTimeMillis();
creatingCountUpdater.decrementAndGet(this);
directCreateCountUpdater.incrementAndGet(this);
if (LOG.isDebugEnabled()) {
LOG.debug("conn-direct_create ");
}
boolean discard = false;
lock.lock();
try {
if (activeCount < maxActive) {
activeCount++;
if (activeCount > activePeak) {
activePeak = activeCount;
activePeakTime = System.currentTimeMillis();
}
break;
} else {
discard = true;
}
} finally {
lock.unlock();
}
if (discard) {
JdbcUtils.close(pyConnInfo.getPhysicalConnection());
}
}
}
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException("interrupt", e);
}
try {
if (maxWaitThreadCount > 0
&& notEmptyWaitThreadCount >= maxWaitThreadCount) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException("maxWaitThreadCount " + maxWaitThreadCount + ", current wait Thread count "
+ lock.getQueueLength());
}
if (onFatalError
&& onFatalErrorMaxActive > 0
&& activeCount >= onFatalErrorMaxActive) {
connectErrorCountUpdater.incrementAndGet(this);
StringBuilder errorMsg = new StringBuilder();
errorMsg.append("onFatalError, activeCount ")
.append(activeCount)
.append(", onFatalErrorMaxActive ")
.append(onFatalErrorMaxActive);
if (lastFatalErrorTimeMillis > 0) {
errorMsg.append(", time '")
.append(StringUtils.formatDateTime19(
lastFatalErrorTimeMillis, TimeZone.getDefault()))
.append("'");
}
if (lastFatalErrorSql != null) {
errorMsg.append(", sql \n")
.append(lastFatalErrorSql);
}
throw new SQLException(
errorMsg.toString(), lastFatalError);
}
connectCount++;
if (createScheduler != null
&& poolingCount == 0
&& activeCount < maxActive
&& creatingCountUpdater.get(this) == 0
&& createScheduler instanceof ScheduledThreadPoolExecutor) {
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) createScheduler;
if (executor.getQueue().size() > 0) {
createDirect = true;
continue;
}
}
if (maxWait > 0) {
holder = pollLast(nanos);
} else {
holder = takeLast();
}
if (holder != null) {
activeCount++;
if (activeCount > activePeak) {
activePeak = activeCount;
activePeakTime = System.currentTimeMillis();
}
}
} catch (InterruptedException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException(e.getMessage(), e);
} catch (SQLException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw e;
} finally {
lock.unlock();
}
break;
}
if (holder == null) {
long waitNanos = waitNanosLocal.get();
StringBuilder buf = new StringBuilder(128);
buf.append("wait millis ")//
.append(waitNanos / (1000 * 1000))//
.append(", active ").append(activeCount)//
.append(", maxActive ").append(maxActive)//
.append(", creating ").append(creatingCount)//
;
if (creatingCount > 0 && createStartNanos > 0) {
long createElapseMillis = (System.nanoTime() - createStartNanos) / (1000 * 1000);
if (createElapseMillis > 0) {
buf.append(", createElapseMillis ").append(createElapseMillis);
}
}
if (createErrorCount > 0) {
buf.append(", createErrorCount ").append(createErrorCount);
}
List<JdbcSqlStatValue> sqlList = this.getDataSourceStat().getRuningSqlList();
for (int i = 0; i < sqlList.size(); ++i) {
if (i != 0) {
buf.append('\n');
} else {
buf.append(", ");
}
JdbcSqlStatValue sql = sqlList.get(i);
buf.append("runningSqlCount ").append(sql.getRunningCount());
buf.append(" : ");
buf.append(sql.getSql());
}
String errorMessage = buf.toString();
if (this.createError != null) {
throw new GetConnectionTimeoutException(errorMessage, createError);
} else {
throw new GetConnectionTimeoutException(errorMessage);
}
}
holder.incrementUseCount();
DruidPooledConnection poolalbeConnection = new ElasticSearchDruidPooledConnection(holder);
return poolalbeConnection;
}
public void handleConnectionException(DruidPooledConnection pooledConnection, Throwable t, String sql) throws SQLException {
final DruidConnectionHolder holder = pooledConnection.getConnectionHolder();
errorCountUpdater.incrementAndGet(this);
lastError = t;
lastErrorTimeMillis = System.currentTimeMillis();
if (t instanceof SQLException) {
SQLException sqlEx = (SQLException) t;
// broadcastConnectionError
ConnectionEvent event = new ConnectionEvent(pooledConnection, sqlEx);
for (ConnectionEventListener eventListener : holder.getConnectionEventListeners()) {
eventListener.connectionErrorOccurred(event);
}
// exceptionSorter.isExceptionFatal
if (exceptionSorter != null && exceptionSorter.isExceptionFatal(sqlEx)) {
handleFatalError(pooledConnection, sqlEx, sql);
}
throw sqlEx;
} else {
throw new SQLException("Error", t);
}
}
/**
* 回收连接
*/
protected void recycle(DruidPooledConnection pooledConnection) throws SQLException {
final DruidConnectionHolder holder = pooledConnection.holder;
if (holder == null) {
LOG.warn("connectionHolder is null");
return;
}
if (logDifferentThread //
&& (!isAsyncCloseConnectionEnable()) //
&& pooledConnection.ownerThread != Thread.currentThread()//
) {
LOG.warn("get/close not same thread");
}
final Connection physicalConnection = holder.conn;
if (pooledConnection.traceEnable) {
Object oldInfo = null;
activeConnectionLock.lock();
try {
if (pooledConnection.traceEnable) {
oldInfo = activeConnections.remove(pooledConnection);
pooledConnection.traceEnable = false;
}
} finally {
activeConnectionLock.unlock();
}
if (oldInfo == null) {
if (LOG.isWarnEnabled()) {
LOG.warn("remove abandonded failed. activeConnections.size " + activeConnections.size());
}
}
}
final boolean isAutoCommit = holder.underlyingAutoCommit;
final boolean isReadOnly = holder.underlyingReadOnly;
final boolean testOnReturn = this.testOnReturn;
try {
// check need to rollback?
if ((!isAutoCommit) && (!isReadOnly)) {
pooledConnection.rollback();
}
// reset holder, restore default settings, clear warnings
boolean isSameThread = pooledConnection.ownerThread == Thread.currentThread();
if (!isSameThread) {
final ReentrantLock lock = pooledConnection.lock;
lock.lock();
try {
holder.reset();
} finally {
lock.unlock();
}
} else {
holder.reset();
}
if (holder.discard) {
return;
}
if (phyMaxUseCount > 0 && holder.useCount >= phyMaxUseCount) {
discardConnection(holder.conn);
return;
}
if (physicalConnection.isClosed()) {
lock.lock();
try {
activeCount--;
closeCount++;
} finally {
lock.unlock();
}
return;
}
if (testOnReturn) {
boolean validate = testConnectionInternal(holder, physicalConnection);
if (!validate) {
JdbcUtils.close(physicalConnection);
destroyCountUpdater.incrementAndGet(this);
lock.lock();
try {
activeCount--;
closeCount++;
} finally {
lock.unlock();
}
return;
}
}
if (!enable) {
discardConnection(holder.conn);
return;
}
boolean result;
final long currentTimeMillis = System.currentTimeMillis();
if (phyTimeoutMillis > 0) {
long phyConnectTimeMillis = currentTimeMillis - holder.connectTimeMillis;
if (phyConnectTimeMillis > phyTimeoutMillis) {
discardConnection(holder.conn);
return;
}
}
lock.lock();
try {
activeCount--;
closeCount++;
result = putLast(holder, currentTimeMillis);
recycleCount++;
} finally {
lock.unlock();
}
if (!result) {
JdbcUtils.close(holder.conn);
LOG.info("connection recyle failed.");
}
} catch (Throwable e) {
holder.clearStatementCache();
if (!holder.discard) {
this.discardConnection(physicalConnection);
holder.discard = true;
}
LOG.error("recyle error", e);
recycleErrorCountUpdater.incrementAndGet(this);
}
}
public long getRecycleErrorCount() {
return recycleErrorCount;
}
public void clearStatementCache() throws SQLException {
lock.lock();
try {
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder conn = connections[i];
if (conn.statementPool != null) {
conn.statementPool.clear();
}
}
} finally {
lock.unlock();
}
}
/**
* close datasource
*/
public void close() {
if (LOG.isInfoEnabled()) {
LOG.info("{dataSource-" + this.getID() + "} closing ...");
}
lock.lock();
try {
if (this.closed) {
return;
}
if (!this.inited) {
return;
}
this.closing = true;
if (logStatsThread != null) {
logStatsThread.interrupt();
}
if (createConnectionThread != null) {
createConnectionThread.interrupt();
}
if (destroyConnectionThread != null) {
destroyConnectionThread.interrupt();
}
if (createSchedulerFuture != null) {
createSchedulerFuture.cancel(true);
}
if (destroySchedulerFuture != null) {
destroySchedulerFuture.cancel(true);
}
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connHolder = connections[i];
for (PreparedStatementHolder stmtHolder : connHolder.getStatementPool().getMap().values()) {
connHolder.getStatementPool().closeRemovedStatement(stmtHolder);
}
connHolder.getStatementPool().getMap().clear();
Connection physicalConnection = connHolder.getConnection();
try {
physicalConnection.close();
} catch (Exception ex) {
LOG.warn("close connection error", ex);
}
connections[i] = null;
destroyCountUpdater.incrementAndGet(this);
}
poolingCount = 0;
// close elasticsearch client
if (this.client != null) {
this.client.close();
}
unregisterMbean();
enable = false;
notEmpty.signalAll();
notEmptySignalCount++;
this.closed = true;
this.closeTimeMillis = System.currentTimeMillis();
for (Filter filter : filters) {
filter.destroy();
}
} finally {
lock.unlock();
}
if (LOG.isInfoEnabled()) {
LOG.info("{dataSource-" + this.getID() + "} closed");
}
}
public void registerMbean() {
if (!mbeanRegistered) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
ObjectName objectName = DruidDataSourceStatManager.addDataSource(ElasticSearchDruidDataSource.this,
ElasticSearchDruidDataSource.this.name);
ElasticSearchDruidDataSource.this.setObjectName(objectName);
ElasticSearchDruidDataSource.this.mbeanRegistered = true;
return null;
}
});
}
}
public void unregisterMbean() {
if (mbeanRegistered) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
DruidDataSourceStatManager.removeDataSource(ElasticSearchDruidDataSource.this);
ElasticSearchDruidDataSource.this.mbeanRegistered = false;
return null;
}
});
}
}
public boolean isMbeanRegistered() {
return mbeanRegistered;
}
boolean putLast(DruidConnectionHolder e, long lastActiveTimeMillis) {
if (poolingCount >= maxActive) {
return false;
}
e.lastActiveTimeMillis = lastActiveTimeMillis;
connections[poolingCount] = e;
incrementPoolingCount();
if (poolingCount > poolingPeak) {
poolingPeak = poolingCount;
poolingPeakTime = lastActiveTimeMillis;
}
notEmpty.signal();
notEmptySignalCount++;
return true;
}
DruidConnectionHolder takeLast() throws InterruptedException, SQLException {
try {
while (poolingCount == 0) {
emptySignal(); // send signal to CreateThread create connection
if (failFast && isFailContinuous()) {
throw new DataSourceNotAvailableException(createError);
}
notEmptyWaitThreadCount++;
if (notEmptyWaitThreadCount > notEmptyWaitThreadPeak) {
notEmptyWaitThreadPeak = notEmptyWaitThreadCount;
}
try {
notEmpty.await(); // signal by recycle or creator
} finally {
notEmptyWaitThreadCount--;
}
notEmptyWaitCount++;
if (!enable) {
connectErrorCountUpdater.incrementAndGet(this);
throw new DataSourceDisableException();
}
}
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
notEmptySignalCount++;
throw ie;
}
decrementPoolingCount();
DruidConnectionHolder last = connections[poolingCount];
connections[poolingCount] = null;
return last;
}
private DruidConnectionHolder pollLast(long nanos) throws InterruptedException, SQLException {
long estimate = nanos;
for (; ; ) {
if (poolingCount == 0) {
emptySignal(); // send signal to CreateThread create connection
if (failFast && isFailContinuous()) {
throw new DataSourceNotAvailableException(createError);
}
if (estimate <= 0) {
waitNanosLocal.set(nanos - estimate);
return null;
}
notEmptyWaitThreadCount++;
if (notEmptyWaitThreadCount > notEmptyWaitThreadPeak) {
notEmptyWaitThreadPeak = notEmptyWaitThreadCount;
}
try {
long startEstimate = estimate;
estimate = notEmpty.awaitNanos(estimate); // signal by
// recycle or
// creator
notEmptyWaitCount++;
notEmptyWaitNanos += (startEstimate - estimate);
if (!enable) {
connectErrorCountUpdater.incrementAndGet(this);
throw new DataSourceDisableException();
}
} catch (InterruptedException ie) {
notEmpty.signal(); // propagate to non-interrupted thread
notEmptySignalCount++;
throw ie;
} finally {
notEmptyWaitThreadCount--;
}
if (poolingCount == 0) {
if (estimate > 0) {
continue;
}
waitNanosLocal.set(nanos - estimate);
return null;
}
}
decrementPoolingCount();
DruidConnectionHolder last = connections[poolingCount];
connections[poolingCount] = null;
long waitNanos = nanos - estimate;
last.setLastNotEmptyWaitNanos(waitNanos);
return last;
}
}
private final void decrementPoolingCount() {
poolingCount--;
}
private final void incrementPoolingCount() {
poolingCount++;
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
if (this.username == null
&& this.password == null
&& username != null
&& password != null) {
this.username = username;
this.password = password;
return getConnection();
}
if (!StringUtils.equals(username, this.username)) {
throw new UnsupportedOperationException("Not supported by DruidDataSource");
}
if (!StringUtils.equals(password, this.password)) {
throw new UnsupportedOperationException("Not supported by DruidDataSource");
}
return getConnection();
}
public long getCreateCount() {
return createCount;
}
public long getDestroyCount() {
return destroyCount;
}
public long getConnectCount() {
lock.lock();
try {
return connectCount;
} finally {
lock.unlock();
}
}
public long getCloseCount() {
return closeCount;
}
public long getConnectErrorCount() {
return connectErrorCountUpdater.get(this);
}
@Override
public int getPoolingCount() {
lock.lock();
try {
return poolingCount;
} finally {
lock.unlock();
}
}
public int getPoolingPeak() {
lock.lock();
try {
return poolingPeak;
} finally {
lock.unlock();
}
}
public Date getPoolingPeakTime() {
if (poolingPeakTime <= 0) {
return null;
}
return new Date(poolingPeakTime);
}
public long getRecycleCount() {
return recycleCount;
}
public int getActiveCount() {
lock.lock();
try {
return activeCount;
} finally {
lock.unlock();
}
}
public void logStats() {
final DruidDataSourceStatLogger statLogger = this.statLogger;
if (statLogger == null) {
return;
}
DruidDataSourceStatValue statValue = getStatValueAndReset();
statLogger.log(statValue);
}
public DruidDataSourceStatValue getStatValueAndReset() {
DruidDataSourceStatValue value = new DruidDataSourceStatValue();
lock.lock();
try {
value.setPoolingCount(this.poolingCount);
value.setPoolingPeak(this.poolingPeak);
value.setPoolingPeakTime(this.poolingPeakTime);
value.setActiveCount(this.activeCount);
value.setActivePeak(this.activePeak);
value.setActivePeakTime(this.activePeakTime);
value.setConnectCount(this.connectCount);
value.setCloseCount(this.closeCount);
value.setWaitThreadCount(lock.getWaitQueueLength(notEmpty));
value.setNotEmptyWaitCount(this.notEmptyWaitCount);
value.setNotEmptyWaitNanos(this.notEmptyWaitNanos);
value.setKeepAliveCheckCount(this.keepAliveCheckCount);
// reset
this.poolingPeak = 0;
this.poolingPeakTime = 0;
this.activePeak = 0;
this.activePeakTime = 0;
this.connectCount = 0;
this.closeCount = 0;
this.keepAliveCheckCount = 0;
this.notEmptyWaitCount = 0;
this.notEmptyWaitNanos = 0;
} finally {
lock.unlock();
}
value.setName(this.getName());
value.setDbType(this.dbTypeName);
value.setDriverClassName(this.getDriverClassName());
value.setUrl(this.getUrl());
value.setUserName(this.getUsername());
value.setFilterClassNames(this.getFilterClassNames());
value.setInitialSize(this.getInitialSize());
value.setMinIdle(this.getMinIdle());
value.setMaxActive(this.getMaxActive());
value.setQueryTimeout(this.getQueryTimeout());
value.setTransactionQueryTimeout(this.getTransactionQueryTimeout());
value.setLoginTimeout(this.getLoginTimeout());
value.setValidConnectionCheckerClassName(this.getValidConnectionCheckerClassName());
value.setExceptionSorterClassName(this.getExceptionSorterClassName());
value.setTestOnBorrow(this.testOnBorrow);
value.setTestOnReturn(this.testOnReturn);
value.setTestWhileIdle(this.testWhileIdle);
value.setDefaultAutoCommit(this.isDefaultAutoCommit());
if (defaultReadOnly != null) {
value.setDefaultReadOnly(defaultReadOnly);
}
value.setDefaultTransactionIsolation(this.getDefaultTransactionIsolation());
value.setLogicConnectErrorCount(connectErrorCountUpdater.getAndSet(this, 0));
value.setPhysicalConnectCount(createCountUpdater.getAndSet(this, 0));
value.setPhysicalCloseCount(destroyCountUpdater.getAndSet(this, 0));
value.setPhysicalConnectErrorCount(createErrorCountUpdater.getAndSet(this, 0));
value.setExecuteCount(this.getAndResetExecuteCount());
value.setErrorCount(errorCountUpdater.getAndSet(this, 0));
value.setCommitCount(commitCountUpdater.getAndSet(this, 0));
value.setRollbackCount(rollbackCountUpdater.getAndSet(this, 0));
value.setPstmtCacheHitCount(cachedPreparedStatementHitCountUpdater.getAndSet(this,0));
value.setPstmtCacheMissCount(cachedPreparedStatementMissCountUpdater.getAndSet(this, 0));
value.setStartTransactionCount(startTransactionCountUpdater.getAndSet(this, 0));
value.setTransactionHistogram(this.getTransactionHistogram().toArrayAndReset());
value.setConnectionHoldTimeHistogram(this.getDataSourceStat().getConnectionHoldHistogram().toArrayAndReset());
value.setRemoveAbandoned(this.isRemoveAbandoned());
value.setClobOpenCount(this.getDataSourceStat().getClobOpenCountAndReset());
value.setBlobOpenCount(this.getDataSourceStat().getBlobOpenCountAndReset());
value.setSqlSkipCount(this.getDataSourceStat().getSkipSqlCountAndReset());
value.setSqlList(this.getDataSourceStat().getSqlStatMapAndReset());
return value;
}
public long getRemoveAbandonedCount() {
return removeAbandonedCount;
}
protected boolean put(PhysicalConnectionInfo physicalConnectionInfo) {
DruidConnectionHolder holder = null;
try {
holder = new DruidConnectionHolder(ElasticSearchDruidDataSource.this, physicalConnectionInfo);
} catch (SQLException ex) {
lock.lock();
try {
if (createScheduler != null) {
createTaskCount--;
}
} finally {
lock.unlock();
}
LOG.error("create connection holder error", ex);
return false;
}
return put(holder);
}
private boolean put(DruidConnectionHolder holder) {
lock.lock();
try {
if (poolingCount >= maxActive) {
return false;
}
connections[poolingCount] = holder;
incrementPoolingCount();
if (poolingCount > poolingPeak) {
poolingPeak = poolingCount;
poolingPeakTime = System.currentTimeMillis();
}
notEmpty.signal();
notEmptySignalCount++;
if (createScheduler != null) {
createTaskCount--;
if (poolingCount + createTaskCount < notEmptyWaitThreadCount //
&& activeCount + poolingCount + createTaskCount < maxActive) {
emptySignal();
}
}
} finally {
lock.unlock();
}
return true;
}
public class CreateConnectionTask implements Runnable {
private int errorCount = 0;
private boolean initTask = false;
public CreateConnectionTask() {
}
public CreateConnectionTask(boolean initTask) {
this.initTask = initTask;
}
@Override
public void run() {
runInternal();
}
private void runInternal() {
for (;;) {
// addLast
lock.lock();
try {
if (closed || closing) {
createTaskCount--;
return;
}
boolean emptyWait = true;
if (createError != null && poolingCount == 0) {
emptyWait = false;
}
if (emptyWait) {
// 必须存在线程等待,才创建连接
if (poolingCount >= notEmptyWaitThreadCount //
&& (!(keepAlive && activeCount + poolingCount < minIdle))
&& (!initTask)
&& !isFailContinuous()
) {
createTaskCount--;
return;
}
// 防止创建超过maxActive数量的连接
if (activeCount + poolingCount >= maxActive) {
createTaskCount--;
return;
}
}
} finally {
lock.unlock();
}
PhysicalConnectionInfo physicalConnection = null;
try {
physicalConnection = createPhysicalConnection();
} catch (OutOfMemoryError e) {
LOG.error("create connection OutOfMemoryError, out memory. ", e);
errorCount++;
if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
// fail over retry attempts
setFailContinuous(true);
if (failFast) {
lock.lock();
try {
notEmpty.signalAll();
} finally {
lock.unlock();
}
}
if (breakAfterAcquireFailure) {
lock.lock();
try {
createTaskCount--;
} finally {
lock.unlock();
}
return;
}
this.errorCount = 0; // reset errorCount
if (closing || closed) {
createTaskCount--;
return;
}
createSchedulerFuture = createScheduler.schedule(this, timeBetweenConnectErrorMillis, TimeUnit.MILLISECONDS);
return;
}
} catch (SQLException e) {
LOG.error("create connection SQLException, url: " + jdbcUrl, e);
errorCount++;
if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
// fail over retry attempts
setFailContinuous(true);
if (failFast) {
lock.lock();
try {
notEmpty.signalAll();
} finally {
lock.unlock();
}
}
if (breakAfterAcquireFailure) {
lock.lock();
try {
createTaskCount--;
} finally {
lock.unlock();
}
return;
}
this.errorCount = 0; // reset errorCount
if (closing || closed) {
createTaskCount--;
return;
}
createSchedulerFuture = createScheduler.schedule(this, timeBetweenConnectErrorMillis, TimeUnit.MILLISECONDS);
return;
}
} catch (RuntimeException e) {
LOG.error("create connection RuntimeException", e);
// unknow fatal exception
setFailContinuous(true);
continue;
} catch (Error e) {
lock.lock();
try {
createTaskCount--;
} finally {
lock.unlock();
}
LOG.error("create connection Error", e);
// unknow fatal exception
setFailContinuous(true);
break;
} catch (Throwable e) {
LOG.error("create connection unexecpted error.", e);
break;
}
if (physicalConnection == null) {
continue;
}
boolean result = put(physicalConnection);
if (!result) {
JdbcUtils.close(physicalConnection.getPhysicalConnection());
LOG.info("put physical connection to pool failed.");
}
break;
}
}
}
public class CreateConnectionThread extends Thread {
public CreateConnectionThread(String name) {
super(name);
this.setDaemon(true);
}
public void run() {
initedLatch.countDown();
long lastDiscardCount = 0;
int errorCount = 0;
for (; ; ) {
// addLast
try {
lock.lockInterruptibly();
} catch (InterruptedException e2) {
break;
}
long discardCount = ElasticSearchDruidDataSource.this.discardCount;
boolean discardChanged = discardCount - lastDiscardCount > 0;
lastDiscardCount = discardCount;
try {
boolean emptyWait = true;
if (createError != null
&& poolingCount == 0
&& !discardChanged) {
emptyWait = false;
}
if (emptyWait
&& asyncInit && createCount < initialSize) {
emptyWait = false;
}
if (emptyWait) {
// 必须存在线程等待,才创建连接
if (poolingCount >= notEmptyWaitThreadCount //
&& (!(keepAlive && activeCount + poolingCount < minIdle))
&& !isFailContinuous()
) {
empty.await();
}
// 防止创建超过maxActive数量的连接
if (activeCount + poolingCount >= maxActive) {
empty.await();
continue;
}
}
} catch (InterruptedException e) {
lastCreateError = e;
lastErrorTimeMillis = System.currentTimeMillis();
if (!closing) {
LOG.error("create connection Thread Interrupted, url: " + jdbcUrl, e);
}
break;
} finally {
lock.unlock();
}
PhysicalConnectionInfo connection = null;
try {
connection = createPhysicalConnection();
} catch (SQLException e) {
LOG.error("create connection SQLException, url: " + jdbcUrl + ", errorCode " + e.getErrorCode()
+ ", state " + e.getSQLState(), e);
errorCount++;
if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
// fail over retry attempts
setFailContinuous(true);
if (failFast) {
lock.lock();
try {
notEmpty.signalAll();
} finally {
lock.unlock();
}
}
if (breakAfterAcquireFailure) {
break;
}
try {
Thread.sleep(timeBetweenConnectErrorMillis);
} catch (InterruptedException interruptEx) {
break;
}
}
} catch (RuntimeException e) {
LOG.error("create connection RuntimeException", e);
setFailContinuous(true);
continue;
} catch (Error e) {
LOG.error("create connection Error", e);
setFailContinuous(true);
break;
}
if (connection == null) {
continue;
}
boolean result = put(connection);
if (!result) {
JdbcUtils.close(connection.getPhysicalConnection());
LOG.info("put physical connection to pool failed.");
}
errorCount = 0; // reset errorCount
}
}
}
public class DestroyConnectionThread extends Thread {
public DestroyConnectionThread(String name){
super(name);
this.setDaemon(true);
}
public void run() {
initedLatch.countDown();
for (; ; ) {
// 从前面开始删除
try {
if (closed) {
break;
}
if (timeBetweenEvictionRunsMillis > 0) {
Thread.sleep(timeBetweenEvictionRunsMillis);
} else {
Thread.sleep(1000); //
}
if (Thread.interrupted()) {
break;
}
destroyTask.run();
} catch (InterruptedException e) {
break;
}
}
}
}
public class DestroyTask implements Runnable {
public DestroyTask() {
}
@Override
public void run() {
shrink(true, keepAlive);
if (isRemoveAbandoned()) {
removeAbandoned();
}
}
}
public class LogStatsThread extends Thread {
public LogStatsThread(String name) {
super(name);
this.setDaemon(true);
}
public void run() {
try {
for (; ; ) {
try {
logStats();
} catch (Exception e) {
LOG.error("logStats error", e);
}
Thread.sleep(timeBetweenLogStatsMillis);
}
} catch (InterruptedException e) {
// skip
}
}
}
public int removeAbandoned() {
int removeCount = 0;
long currrentNanos = System.nanoTime();
List<DruidPooledConnection> abandonedList = new ArrayList<DruidPooledConnection>();
activeConnectionLock.lock();
try {
Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator();
for (; iter.hasNext(); ) {
DruidPooledConnection pooledConnection = iter.next();
if (pooledConnection.isRunning()) {
continue;
}
long timeMillis = (currrentNanos - pooledConnection.getConnectedTimeNano()) / (1000 * 1000);
if (timeMillis >= removeAbandonedTimeoutMillis) {
iter.remove();
pooledConnection.setTraceEnable(false);
abandonedList.add(pooledConnection);
}
}
} finally {
activeConnectionLock.unlock();
}
if (abandonedList.size() > 0) {
for (DruidPooledConnection pooledConnection : abandonedList) {
final ReentrantLock lock = pooledConnection.lock;
lock.lock();
try {
if (pooledConnection.isDisable()) {
continue;
}
} finally {
lock.unlock();
}
JdbcUtils.close(pooledConnection);
pooledConnection.abandond();
removeAbandonedCount++;
removeCount++;
if (isLogAbandoned()) {
StringBuilder buf = new StringBuilder();
buf.append("abandon connection, owner thread: ");
buf.append(pooledConnection.getOwnerThread().getName());
buf.append(", connected at : ");
buf.append(pooledConnection.getConnectedTimeMillis());
buf.append(", open stackTrace\n");
StackTraceElement[] trace = pooledConnection.getConnectStackTrace();
for (int i = 0; i < trace.length; i++) {
buf.append("\tat ");
buf.append(trace[i].toString());
buf.append("\n");
}
buf.append("ownerThread current state is " + pooledConnection.getOwnerThread().getState()
+ ", current stackTrace\n");
trace = pooledConnection.getOwnerThread().getStackTrace();
for (int i = 0; i < trace.length; i++) {
buf.append("\tat ");
buf.append(trace[i].toString());
buf.append("\n");
}
LOG.error(buf.toString());
}
}
}
return removeCount;
}
/**
* Instance key
*/
protected String instanceKey = null;
public Reference getReference() throws NamingException {
final String className = getClass().getName();
final String factoryName = className + "Factory"; // XXX: not robust
Reference ref = new Reference(className, factoryName, null);
ref.add(new StringRefAddr("instanceKey", instanceKey));
ref.add(new StringRefAddr("url", this.getUrl()));
ref.add(new StringRefAddr("username", this.getUsername()));
ref.add(new StringRefAddr("password", this.getPassword()));
// TODO ADD OTHER PROPERTIES
return ref;
}
@Override
public List<String> getFilterClassNames() {
List<String> names = new ArrayList<String>();
for (Filter filter : filters) {
names.add(filter.getClass().getName());
}
return names;
}
public int getRawDriverMajorVersion() {
int version = -1;
if (this.driver != null) {
version = driver.getMajorVersion();
}
return version;
}
public int getRawDriverMinorVersion() {
int version = -1;
if (this.driver != null) {
version = driver.getMinorVersion();
}
return version;
}
public String getProperties() {
Properties properties = new Properties();
properties.putAll(connectProperties);
if (properties.containsKey("password")) {
properties.put("password", "******");
}
return properties.toString();
}
@Override
public void shrink() {
shrink(false, false);
}
public void shrink(boolean checkTime) {
shrink(checkTime, keepAlive);
}
public void shrink(boolean checkTime, boolean keepAlive) {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
return;
}
int evictCount = 0;
int keepAliveCount = 0;
try {
if (!inited) {
return;
}
final int checkCount = poolingCount - minIdle;
final long currentTimeMillis = System.currentTimeMillis();
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connection = connections[i];
if (checkTime) {
if (phyTimeoutMillis > 0) {
long phyConnectTimeMillis = currentTimeMillis - connection.connectTimeMillis;
if (phyConnectTimeMillis > phyTimeoutMillis) {
evictConnections[evictCount++] = connection;
continue;
}
}
long idleMillis = currentTimeMillis - connection.lastActiveTimeMillis;
if (idleMillis < minEvictableIdleTimeMillis
&& idleMillis < keepAliveBetweenTimeMillis
) {
break;
}
if (idleMillis >= minEvictableIdleTimeMillis) {
if (checkTime && i < checkCount) {
evictConnections[evictCount++] = connection;
continue;
} else if (idleMillis > maxEvictableIdleTimeMillis) {
evictConnections[evictCount++] = connection;
continue;
}
}
if (keepAlive && idleMillis >= keepAliveBetweenTimeMillis) {
keepAliveConnections[keepAliveCount++] = connection;
}
} else {
if (i < checkCount) {
evictConnections[evictCount++] = connection;
} else {
break;
}
}
}
int removeCount = evictCount + keepAliveCount;
if (removeCount > 0) {
System.arraycopy(connections, removeCount, connections, 0, poolingCount - removeCount);
Arrays.fill(connections, poolingCount - removeCount, poolingCount, null);
poolingCount -= removeCount;
}
keepAliveCheckCount += keepAliveCount;
} finally {
lock.unlock();
}
if (evictCount > 0) {
for (int i = 0; i < evictCount; ++i) {
DruidConnectionHolder item = evictConnections[i];
Connection connection = item.getConnection();
JdbcUtils.close(connection);
destroyCountUpdater.incrementAndGet(this);
}
Arrays.fill(evictConnections, null);
}
if (keepAliveCount > 0) {
// keep order
for (int i = keepAliveCount - 1; i >= 0; --i) {
DruidConnectionHolder holer = keepAliveConnections[i];
Connection connection = holer.getConnection();
holer.incrementKeepAliveCheckCount();
boolean validate = false;
try {
this.validateConnection(connection);
validate = true;
} catch (Throwable error) {
if (LOG.isDebugEnabled()) {
LOG.debug("keepAliveErr", error);
}
// skip
}
boolean discard = !validate;
if (validate) {
holer.lastKeepTimeMillis = System.currentTimeMillis();
boolean putOk = put(holer);
if (!putOk) {
discard = true;
}
}
if (discard) {
try {
connection.close();
} catch (Exception e) {
// skip
}
lock.lock();
try {
discardCount++;
if (activeCount <= minIdle) {
emptySignal();
}
} finally {
lock.unlock();
}
}
}
this.getDataSourceStat().addKeepAliveCheckCount(keepAliveCount);
Arrays.fill(keepAliveConnections, null);
}
}
public int getWaitThreadCount() {
lock.lock();
try {
return lock.getWaitQueueLength(notEmpty);
} finally {
lock.unlock();
}
}
public long getNotEmptyWaitCount() {
return notEmptyWaitCount;
}
public int getNotEmptyWaitThreadCount() {
lock.lock();
try {
return notEmptyWaitThreadCount;
} finally {
lock.unlock();
}
}
public int getNotEmptyWaitThreadPeak() {
lock.lock();
try {
return notEmptyWaitThreadPeak;
} finally {
lock.unlock();
}
}
public long getNotEmptySignalCount() {
return notEmptySignalCount;
}
public long getNotEmptyWaitMillis() {
return notEmptyWaitNanos / (1000 * 1000);
}
public long getNotEmptyWaitNanos() {
return notEmptyWaitNanos;
}
public int getLockQueueLength() {
return lock.getQueueLength();
}
public int getActivePeak() {
return activePeak;
}
public Date getActivePeakTime() {
if (activePeakTime <= 0) {
return null;
}
return new Date(activePeakTime);
}
public String dump() {
lock.lock();
try {
return this.toString();
} finally {
lock.unlock();
}
}
public long getErrorCount() {
return this.errorCount;
}
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("{");
buf.append("\n\tCreateTime:\"");
buf.append(Utils.toString(getCreatedTime()));
buf.append("\"");
buf.append(",\n\tActiveCount:");
buf.append(getActiveCount());
buf.append(",\n\tPoolingCount:");
buf.append(getPoolingCount());
buf.append(",\n\tCreateCount:");
buf.append(getCreateCount());
buf.append(",\n\tDestroyCount:");
buf.append(getDestroyCount());
buf.append(",\n\tCloseCount:");
buf.append(getCloseCount());
buf.append(",\n\tConnectCount:");
buf.append(getConnectCount());
buf.append(",\n\tConnections:[");
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder conn = connections[i];
if (conn != null) {
if (i != 0) {
buf.append(",");
}
buf.append("\n\t\t");
buf.append(conn.toString());
}
}
buf.append("\n\t]");
buf.append("\n}");
if (this.isPoolPreparedStatements()) {
buf.append("\n\n[");
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder conn = connections[i];
if (conn != null) {
if (i != 0) {
buf.append(",");
}
buf.append("\n\t{\n\tID:");
buf.append(System.identityHashCode(conn.getConnection()));
PreparedStatementPool pool = conn.getStatementPool();
buf.append(", \n\tpoolStatements:[");
int entryIndex = 0;
try {
for (Map.Entry<DruidPooledPreparedStatement.PreparedStatementKey, PreparedStatementHolder> entry : pool.getMap().entrySet()) {
if (entryIndex != 0) {
buf.append(",");
}
buf.append("\n\t\t{hitCount:");
buf.append(entry.getValue().getHitCount());
buf.append(",sql:\"");
buf.append(entry.getKey().getSql());
buf.append("\"");
buf.append("\t}");
entryIndex++;
}
} catch (ConcurrentModificationException e) {
// skip ..
}
buf.append("\n\t\t]");
buf.append("\n\t}");
}
}
buf.append("\n]");
}
return buf.toString();
}
public List<Map<String, Object>> getPoolingConnectionInfo() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
lock.lock();
try {
for (int i = 0; i < poolingCount; ++i) {
DruidConnectionHolder connHolder = connections[i];
Connection conn = connHolder.getConnection();
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("id", System.identityHashCode(conn));
map.put("connectionId", connHolder.getConnectionId());
map.put("useCount", connHolder.getUseCount());
if (connHolder.lastActiveTimeMillis > 0) {
map.put("lastActiveTime", new Date(connHolder.lastActiveTimeMillis));
}
if (connHolder.lastKeepTimeMillis > 0) {
map.put("lastKeepTimeMillis", new Date(connHolder.lastKeepTimeMillis));
}
map.put("connectTime", new Date(connHolder.getTimeMillis()));
map.put("holdability", connHolder.getUnderlyingHoldability());
map.put("transactionIsolation", connHolder.getUnderlyingTransactionIsolation());
map.put("autoCommit", connHolder.underlyingAutoCommit);
map.put("readoOnly", connHolder.isUnderlyingReadOnly());
if (connHolder.isPoolPreparedStatements()) {
List<Map<String, Object>> stmtCache = new ArrayList<Map<String, Object>>();
PreparedStatementPool stmtPool = connHolder.getStatementPool();
for (PreparedStatementHolder stmtHolder : stmtPool.getMap().values()) {
Map<String, Object> stmtInfo = new LinkedHashMap<String, Object>();
stmtInfo.put("sql", stmtHolder.key.getSql());
stmtInfo.put("defaultRowPrefetch", stmtHolder.getDefaultRowPrefetch());
stmtInfo.put("rowPrefetch", stmtHolder.getRowPrefetch());
stmtInfo.put("hitCount", stmtHolder.getHitCount());
stmtCache.add(stmtInfo);
}
map.put("pscache", stmtCache);
}
map.put("keepAliveCheckCount", connHolder.getKeepAliveCheckCount());
list.add(map);
}
} finally {
lock.unlock();
}
return list;
}
public void logTransaction(TransactionInfo info) {
long transactionMillis = info.getEndTimeMillis() - info.getStartTimeMillis();
if (transactionThresholdMillis > 0 && transactionMillis > transactionThresholdMillis) {
StringBuilder buf = new StringBuilder();
buf.append("long time transaction, take ");
buf.append(transactionMillis);
buf.append(" ms : ");
for (String sql : info.getSqlList()) {
buf.append(sql);
buf.append(";");
}
LOG.error(buf.toString(), new TransactionTimeoutException());
}
}
@Override
public String getVersion() {
return VERSION.getVersionNumber();
}
@Override
public JdbcDataSourceStat getDataSourceStat() {
return dataSourceStat;
}
public Object clone() {
return cloneDruidDataSource();
}
public DruidDataSource cloneDruidDataSource() {
DruidDataSource x = new DruidDataSource();
cloneTo(x);
return x;
}
public Map<String, Object> getStatDataForMBean() {
try {
Map<String, Object> map = new HashMap<String, Object>();
// 0 - 4
map.put("Name", this.getName());
map.put("URL", this.getUrl());
map.put("CreateCount", this.getCreateCount());
map.put("DestroyCount", this.getDestroyCount());
map.put("ConnectCount", this.getConnectCount());
// 5 - 9
map.put("CloseCount", this.getCloseCount());
map.put("ActiveCount", this.getActiveCount());
map.put("PoolingCount", this.getPoolingCount());
map.put("LockQueueLength", this.getLockQueueLength());
map.put("WaitThreadCount", this.getNotEmptyWaitThreadPeak());
// 10 - 14
map.put("InitialSize", this.getInitialSize());
map.put("MaxActive", this.getMaxActive());
map.put("MinIdle", this.getMinIdle());
map.put("PoolPreparedStatements", this.isPoolPreparedStatements());
map.put("TestOnBorrow", this.isTestOnBorrow());
// 15 - 19
map.put("TestOnReturn", this.isTestOnReturn());
map.put("MinEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis);
map.put("ConnectErrorCount", this.getConnectErrorCount());
map.put("CreateTimespanMillis", this.getCreateTimespanMillis());
map.put("DbType", this.dbTypeName);
// 20 - 24
map.put("ValidationQuery", this.getValidationQuery());
map.put("ValidationQueryTimeout", this.getValidationQueryTimeout());
map.put("DriverClassName", this.getDriverClassName());
map.put("Username", this.getUsername());
map.put("RemoveAbandonedCount", this.getRemoveAbandonedCount());
// 25 - 29
map.put("NotEmptyWaitCount", this.getNotEmptyWaitCount());
map.put("NotEmptyWaitNanos", this.getNotEmptyWaitNanos());
map.put("ErrorCount", this.getErrorCount());
map.put("ReusePreparedStatementCount", this.getCachedPreparedStatementHitCount());
map.put("StartTransactionCount", this.getStartTransactionCount());
// 30 - 34
map.put("CommitCount", this.getCommitCount());
map.put("RollbackCount", this.getRollbackCount());
map.put("LastError", JMXUtils.getErrorCompositeData(this.getLastError()));
map.put("LastCreateError", JMXUtils.getErrorCompositeData(this.getLastCreateError()));
map.put("PreparedStatementCacheDeleteCount", this.getCachedPreparedStatementDeleteCount());
// 35 - 39
map.put("PreparedStatementCacheAccessCount", this.getCachedPreparedStatementAccessCount());
map.put("PreparedStatementCacheMissCount", this.getCachedPreparedStatementMissCount());
map.put("PreparedStatementCacheHitCount", this.getCachedPreparedStatementHitCount());
map.put("PreparedStatementCacheCurrentCount", this.getCachedPreparedStatementCount());
map.put("Version", this.getVersion());
// 40 -
map.put("LastErrorTime", this.getLastErrorTime());
map.put("LastCreateErrorTime", this.getLastCreateErrorTime());
map.put("CreateErrorCount", this.getCreateErrorCount());
map.put("DiscardCount", this.getDiscardCount());
map.put("ExecuteQueryCount", this.getExecuteQueryCount());
map.put("ExecuteUpdateCount", this.getExecuteUpdateCount());
return map;
} catch (JMException ex) {
throw new IllegalStateException("getStatData error", ex);
}
}
public Map<String, Object> getStatData() {
final int activeCount;
final int activePeak;
final Date activePeakTime;
final int poolingCount;
final int poolingPeak;
final Date poolingPeakTime;
final long connectCount;
final long closeCount;
lock.lock();
try {
poolingCount = this.poolingCount;
poolingPeak = this.poolingPeak;
poolingPeakTime = this.getPoolingPeakTime();
activeCount = this.activeCount;
activePeak = this.activePeak;
activePeakTime = this.getActivePeakTime();
connectCount = this.connectCount;
closeCount = this.closeCount;
} finally {
lock.unlock();
}
Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
dataMap.put("Identity", System.identityHashCode(this));
dataMap.put("Name", this.getName());
dataMap.put("DbType", this.dbTypeName);
dataMap.put("DriverClassName", this.getDriverClassName());
dataMap.put("URL", this.getUrl());
dataMap.put("UserName", this.getUsername());
dataMap.put("FilterClassNames", this.getFilterClassNames());
dataMap.put("WaitThreadCount", this.getWaitThreadCount());
dataMap.put("NotEmptyWaitCount", this.getNotEmptyWaitCount());
dataMap.put("NotEmptyWaitMillis", this.getNotEmptyWaitMillis());
dataMap.put("PoolingCount", poolingCount);
dataMap.put("PoolingPeak", poolingPeak);
dataMap.put("PoolingPeakTime", poolingPeakTime);
dataMap.put("ActiveCount", activeCount);
dataMap.put("ActivePeak", activePeak);
dataMap.put("ActivePeakTime", activePeakTime);
dataMap.put("InitialSize", this.getInitialSize());
dataMap.put("MinIdle", this.getMinIdle());
dataMap.put("MaxActive", this.getMaxActive());
dataMap.put("QueryTimeout", this.getQueryTimeout());
dataMap.put("TransactionQueryTimeout", this.getTransactionQueryTimeout());
dataMap.put("LoginTimeout", this.getLoginTimeout());
dataMap.put("ValidConnectionCheckerClassName", this.getValidConnectionCheckerClassName());
dataMap.put("ExceptionSorterClassName", this.getExceptionSorterClassName());
dataMap.put("TestOnBorrow", this.isTestOnBorrow());
dataMap.put("TestOnReturn", this.isTestOnReturn());
dataMap.put("TestWhileIdle", this.isTestWhileIdle());
dataMap.put("DefaultAutoCommit", this.isDefaultAutoCommit());
dataMap.put("DefaultReadOnly", this.getDefaultReadOnly());
dataMap.put("DefaultTransactionIsolation", this.getDefaultTransactionIsolation());
dataMap.put("LogicConnectCount", connectCount);
dataMap.put("LogicCloseCount", closeCount);
dataMap.put("LogicConnectErrorCount", this.getConnectErrorCount());
dataMap.put("PhysicalConnectCount", this.getCreateCount());
dataMap.put("PhysicalCloseCount", this.getDestroyCount());
dataMap.put("PhysicalConnectErrorCount", this.getCreateErrorCount());
dataMap.put("ExecuteCount", this.getExecuteCount());
dataMap.put("ExecuteUpdateCount", this.getExecuteUpdateCount());
dataMap.put("ExecuteQueryCount", this.getExecuteQueryCount());
dataMap.put("ExecuteBatchCount", this.getExecuteBatchCount());
dataMap.put("ErrorCount", this.getErrorCount());
dataMap.put("CommitCount", this.getCommitCount());
dataMap.put("RollbackCount", this.getRollbackCount());
dataMap.put("PSCacheAccessCount", this.getCachedPreparedStatementAccessCount());
dataMap.put("PSCacheHitCount", this.getCachedPreparedStatementHitCount());
dataMap.put("PSCacheMissCount", this.getCachedPreparedStatementMissCount());
dataMap.put("StartTransactionCount", this.getStartTransactionCount());
dataMap.put("TransactionHistogram", this.getTransactionHistogramValues());
dataMap.put("ConnectionHoldTimeHistogram", this.getDataSourceStat().getConnectionHoldHistogram().toArray());
dataMap.put("RemoveAbandoned", this.isRemoveAbandoned());
dataMap.put("ClobOpenCount", this.getDataSourceStat().getClobOpenCount());
dataMap.put("BlobOpenCount", this.getDataSourceStat().getBlobOpenCount());
dataMap.put("KeepAliveCheckCount", this.getDataSourceStat().getKeepAliveCheckCount());
dataMap.put("KeepAlive", this.isKeepAlive());
dataMap.put("FailFast", this.isFailFast());
dataMap.put("MaxWait", this.getMaxWait());
dataMap.put("MaxWaitThreadCount", this.getMaxWaitThreadCount());
dataMap.put("PoolPreparedStatements", this.isPoolPreparedStatements());
dataMap.put("MaxPoolPreparedStatementPerConnectionSize", this.getMaxPoolPreparedStatementPerConnectionSize());
dataMap.put("MinEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis);
dataMap.put("MaxEvictableIdleTimeMillis", this.maxEvictableIdleTimeMillis);
dataMap.put("LogDifferentThread", isLogDifferentThread());
dataMap.put("RecycleErrorCount", getRecycleErrorCount());
dataMap.put("PreparedStatementOpenCount", getPreparedStatementCount());
dataMap.put("PreparedStatementClosedCount", getClosedPreparedStatementCount());
dataMap.put("UseUnfairLock", isUseUnfairLock());
dataMap.put("InitGlobalVariants", isInitGlobalVariants());
dataMap.put("InitVariants", isInitVariants());
return dataMap;
}
public JdbcSqlStat getSqlStat(int sqlId) {
return this.getDataSourceStat().getSqlStat(sqlId);
}
public JdbcSqlStat getSqlStat(long sqlId) {
return this.getDataSourceStat().getSqlStat(sqlId);
}
public Map<String, JdbcSqlStat> getSqlStatMap() {
return this.getDataSourceStat().getSqlStatMap();
}
public Map<String, Object> getWallStatMap() {
WallProviderStatValue wallStatValue = getWallStatValue(false);
if (wallStatValue != null) {
return wallStatValue.toMap();
}
return null;
}
public WallProviderStatValue getWallStatValue(boolean reset) {
for (Filter filter : this.filters) {
if (filter instanceof WallFilter) {
WallFilter wallFilter = (WallFilter) filter;
return wallFilter.getProvider().getStatValue(reset);
}
}
return null;
}
public Lock getLock() {
return lock;
}
@Override
public boolean isWrapperFor(Class<?> iface) {
for (Filter filter : this.filters) {
if (filter.isWrapperFor(iface)) {
return true;
}
}
if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return true;
}
return super.isWrapperFor(iface);
}
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) {
for (Filter filter : this.filters) {
if (filter.isWrapperFor(iface)) {
return (T) filter;
}
}
if (this.statLogger != null
&& (this.statLogger.getClass() == iface || DruidDataSourceStatLogger.class == iface)) {
return (T) statLogger;
}
return super.unwrap(iface);
}
public boolean isLogDifferentThread() {
return logDifferentThread;
}
public void setLogDifferentThread(boolean logDifferentThread) {
this.logDifferentThread = logDifferentThread;
}
public DruidPooledConnection tryGetConnection() throws SQLException {
if (poolingCount == 0) {
return null;
}
return getConnection();
}
@Override
public int fill() throws SQLException {
return this.fill(this.maxActive);
}
@Override
public int fill(int toCount) throws SQLException {
if (closed) {
throw new DataSourceClosedException("dataSource already closed at " + new Date(closeTimeMillis));
}
if (toCount < 0) {
throw new IllegalArgumentException("toCount can't not be less than zero");
}
init();
if (toCount > this.maxActive) {
toCount = this.maxActive;
}
int fillCount = 0;
for (; ; ) {
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException("interrupt", e);
}
boolean fillable = this.isFillable(toCount);
lock.unlock();
if (!fillable) {
break;
}
DruidConnectionHolder holder;
try {
PhysicalConnectionInfo pyConnInfo = createPhysicalConnection();
holder = new DruidConnectionHolder(this, pyConnInfo);
} catch (SQLException e) {
LOG.error("fill connection error, url: " + this.jdbcUrl, e);
connectErrorCountUpdater.incrementAndGet(this);
throw e;
}
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
connectErrorCountUpdater.incrementAndGet(this);
throw new SQLException("interrupt", e);
}
try {
if (!this.isFillable(toCount)) {
JdbcUtils.close(holder.getConnection());
LOG.info("fill connections skip.");
break;
}
this.putLast(holder, System.currentTimeMillis());
fillCount++;
} finally {
lock.unlock();
}
}
if (LOG.isInfoEnabled()) {
LOG.info("fill " + fillCount + " connections");
}
return fillCount;
}
private boolean isFillable(int toCount) {
int currentCount = this.poolingCount + this.activeCount;
if (currentCount >= toCount || currentCount >= this.maxActive) {
return false;
} else {
return true;
}
}
public boolean isFull() {
lock.lock();
try {
return this.poolingCount + this.activeCount >= this.maxActive;
} finally {
lock.unlock();
}
}
private void emptySignal() {
if (createScheduler == null) {
empty.signal();
return;
}
if (createTaskCount >= maxCreateTaskCount) {
return;
}
if (activeCount + poolingCount + createTaskCount >= maxActive) {
return;
}
createTaskCount++;
CreateConnectionTask task = new CreateConnectionTask();
this.createSchedulerFuture = createScheduler.submit(task);
}
@Override
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
if (server != null) {
try {
if (server.isRegistered(name)) {
server.unregisterMBean(name);
}
} catch (Exception ex) {
LOG.warn("DruidDataSource preRegister error", ex);
}
}
return name;
}
@Override
public void postRegister(Boolean registrationDone) {
}
@Override
public void preDeregister() throws Exception {
}
@Override
public void postDeregister() {
}
public boolean isClosed() {
return this.closed;
}
}
| NLPchina/elasticsearch-sql | src/main/java/com/alibaba/druid/pool/ElasticSearchDruidDataSource.java |
180,191 | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.testFramework.common;
import com.intellij.diagnostic.JVMResponsivenessMonitor;
import com.intellij.diagnostic.PerformanceWatcher;
import com.intellij.execution.process.ProcessIOExecutorService;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.ShutDownTracker;
import com.intellij.util.FlushingDaemon;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.FilePageCacheLockFree;
import com.intellij.util.ui.EDT;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.ApiStatus.Internal;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.io.NettyUtil;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.*;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.TimeUnit;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
@TestOnly
@Internal
public final class ThreadLeakTracker {
private ThreadLeakTracker() { }
private static final MethodHandle getThreads = getThreadsMethodHandle();
public static @NotNull Map<String, Thread> getThreads() {
Thread[] threads;
try {
// faster than Thread.getAllStackTraces().keySet()
threads = (Thread[])getThreads.invokeExact();
}
catch (Throwable e) {
throw new RuntimeException(e);
}
if (threads.length == 0) {
return Collections.emptyMap();
}
Map<String, Thread> map = new HashMap<>(threads.length);
for (Thread thread : threads) {
map.put(thread.getName(), thread);
}
return map;
}
// contains prefixes of the thread names which are known to be long-running (and thus exempted from the leaking threads' detection)
private static final Set<String> wellKnownOffenders;
static {
@SuppressWarnings({"deprecation", "SpellCheckingInspection"}) List<String> offenders = List.of(
"ApplicationImpl pooled thread ", // com.intellij.util.concurrency.AppScheduledExecutorService.POOLED_THREAD_PREFIX
"AWT-EventQueue-",
"AWT-Shutdown",
"AWT-Windows",
"BatchSpanProcessor_WorkerThread", // io.opentelemetry.sdk.trace.export.BatchSpanProcessor.WORKER_THREAD_NAME
"Batik CleanerThread",
"BC Entropy Daemon",
"Cidr Symbol Building Thread", // ForkJoinPool com.jetbrains.cidr.lang.symbols.symtable.building.OCBuildingActivityExecutionService
"Cleaner-0", // Thread[Cleaner-0,8,InnocuousThreadGroup], java.lang.ref.Cleaner in android layoutlib, Java9+
"CompilerThread0",
"Coroutines Debugger Cleaner", // kotlinx.coroutines.debug.internal.DebugProbesImpl.startWeakRefCleanerThread
"dockerjava-netty",
"External compiler",
FilePageCacheLockFree.DEFAULT_HOUSEKEEPER_THREAD_NAME,
"Finalizer",
FlushingDaemon.NAME,
"grpc-default-worker-", // grpc_netty_shaded
"HttpClient-", // JRE's HttpClient thread pool is not supposed to be disposed - to reuse connections
ProcessIOExecutorService.POOLED_THREAD_PREFIX,
"IDEA Test Case Thread",
"Image Fetcher ",
"InnocuousThreadGroup",
"Java2D Disposer",
"JNA Cleaner",
"JobScheduler FJ pool ",
"JPS thread pool",
JVMResponsivenessMonitor.MONITOR_THREAD_NAME,
"Keep-Alive-SocketCleaner", // Thread[Keep-Alive-SocketCleaner,8,InnocuousThreadGroup], JBR-11
"Keep-Alive-Timer",
"main",
"Monitor Ctrl-Break",
"Netty ",
"ObjectCleanerThread",
"OkHttp ConnectionPool", // Dockers okhttp3.internal.connection.RealConnectionPool
"Okio Watchdog", // Dockers "okio.AsyncTimeout.Watchdog"
"Periodic tasks thread", // com.intellij.util.concurrency.AppDelayQueue.TransferThread
"process reaper", // Thread[#46,process reaper(pid7496),10,InnocuousThreadGroup] (since JDK-8279488 part of InnocuousThreadGroup)
"rd throttler", // daemon thread created by com.jetbrains.rd.util.AdditionalApiKt.getTimer
"Reference Handler",
"RMI GC Daemon",
"RMI TCP ",
"Save classpath indexes for file loader",
"Shared Index Hash Index Flushing Queue",
"Signal Dispatcher",
"tc-okhttp-stream", // Dockers "com.github.dockerjava.okhttp.UnixDomainSocket.recv"
"timer-int", //serverIm,
"timer-sys", //clientIm,
"TimerQueue",
"UserActivityMonitor thread",
"VM Periodic Task Thread",
"VM Thread",
"YJPAgent-Telemetry"
);
validateWhitelistedThreads(offenders);
wellKnownOffenders = new HashSet<>(offenders);
try {
// init zillions of timers in e.g., MacOSXPreferencesFile
Preferences.userRoot().flush();
}
catch (BackingStoreException e) {
throw new RuntimeException(e);
}
}
// marks Thread with this name as long-running, which should be ignored from the thread-leaking checks
public static void longRunningThreadCreated(@NotNull Disposable parentDisposable, @NotNull String @NotNull ... threadNamePrefixes) {
ContainerUtil.addAll(wellKnownOffenders, threadNamePrefixes);
Disposer.register(parentDisposable, () -> ContainerUtil.removeAll(wellKnownOffenders, threadNamePrefixes));
}
public static void awaitQuiescence() {
NettyUtil.awaitQuiescenceOfGlobalEventExecutor(100, TimeUnit.SECONDS);
ShutDownTracker.getInstance().waitFor(100, TimeUnit.SECONDS);
}
public static void checkLeak(@NotNull Map<String, Thread> threadsBefore) throws AssertionError {
// compare threads by name because BoundedTaskExecutor reuses application thread pool for different bounded pools,
// leaks of which we want to find
Map<String, Thread> all = getThreads();
Map<String, Thread> after = new HashMap<>(all);
after.keySet().removeAll(threadsBefore.keySet());
Map<Thread, StackTraceElement[]> stackTraces = ContainerUtil.map2Map(
after.values(),
thread -> new Pair<>(thread, thread.getStackTrace())
);
for (Thread thread : after.values()) {
waitForThread(thread, stackTraces, all, after);
}
}
private static void waitForThread(Thread thread,
Map<Thread, StackTraceElement[]> stackTraces,
Map<String, Thread> all,
Map<String, Thread> after) {
if (!shouldWaitForThread(thread)) {
return;
}
long start = System.currentTimeMillis();
StackTraceElement[] traceBeforeWait = thread.getStackTrace();
if (shouldIgnore(thread, traceBeforeWait)) {
return;
}
int WAIT_SEC = 10;
long deadlineMs = start + TimeUnit.SECONDS.toMillis(WAIT_SEC);
StackTraceElement[] stackTrace = traceBeforeWait;
while (System.currentTimeMillis() < deadlineMs) {
// give a blocked thread an opportunity to die if it's stuck doing invokeAndWait()
if (EDT.isCurrentThreadEdt()) {
UIUtil.dispatchAllInvocationEvents();
}
else {
UIUtil.pump();
}
// after some time, the submitted task can finish and the thread can become idle
stackTrace = thread.getStackTrace();
if (shouldIgnore(thread, stackTrace)) break;
}
// check once more because the thread name may be set via race
stackTraces.put(thread, stackTrace);
if (shouldIgnore(thread, stackTrace)) {
return;
}
all.keySet().removeAll(after.keySet());
Map<Thread, StackTraceElement[]> otherStackTraces = ContainerUtil.map2Map(all.values(), t -> Pair.create(t, t.getStackTrace()));
String trace = PerformanceWatcher.printStacktrace("", thread, stackTrace);
String traceBefore = PerformanceWatcher.printStacktrace("", thread, traceBeforeWait);
String internalDiagnostic = internalDiagnostic(stackTrace);
throw new AssertionError(
"Thread leaked: " + traceBefore + (trace.equals(traceBefore) ? "" : "(its trace after " + WAIT_SEC + " seconds wait:) " + trace) +
internalDiagnostic +
"\n\nLeaking threads dump:\n" + dumpThreadsToString(after, stackTraces) +
"\n----\nAll other threads dump:\n" + dumpThreadsToString(all, otherStackTraces)
);
}
private static boolean shouldWaitForThread(Thread thread) {
if (thread == Thread.currentThread()) {
return false;
}
ThreadGroup group = thread.getThreadGroup();
if (group != null && "system".equals(group.getName()) || !thread.isAlive()) {
return false;
}
return true;
}
private static boolean shouldIgnore(Thread thread, StackTraceElement[] stackTrace) {
if (!thread.isAlive()) return true;
if (stackTrace.length == 0) return true;
if (isWellKnownOffender(thread.getName())) return true;
return isIdleApplicationPoolThread(stackTrace)
|| isIdleCommonPoolThread(thread, stackTrace)
|| isFutureTaskAboutToFinish(stackTrace)
|| isIdleDefaultCoroutineExecutorThread(thread, stackTrace)
|| isCoroutineSchedulerPoolThread(thread, stackTrace)
|| isKotlinCIOSelector(stackTrace)
|| isStarterTestFramework(stackTrace)
|| isJMXRemoteCall(stackTrace)
|| isBuildLogCall(stackTrace);
}
private static boolean isWellKnownOffender(String threadName) {
for (String t : wellKnownOffenders) {
if (threadName.contains(t)) {
return true;
}
}
return false;
}
// true, if somebody started a new thread via "executeInPooledThread()" and then the thread is waiting for the next task
private static boolean isIdleApplicationPoolThread(StackTraceElement[] stackTrace) {
return ContainerUtil.exists(stackTrace, element -> element.getMethodName().equals("getTask")
&& element.getClassName().equals("java.util.concurrent.ThreadPoolExecutor"));
}
private static boolean isKotlinCIOSelector(StackTraceElement[] stackTrace) {
return ContainerUtil.exists(stackTrace, element -> element.getMethodName().equals("select")
&& element.getClassName().equals("io.ktor.network.selector.ActorSelectorManager"));
}
private static boolean isIdleCommonPoolThread(Thread thread, StackTraceElement[] stackTrace) {
if (!ForkJoinWorkerThread.class.isAssignableFrom(thread.getClass())) {
return false;
}
boolean insideAwaitWork = ContainerUtil.exists(
stackTrace,
element -> element.getMethodName().equals("awaitWork")
&& element.getClassName().equals("java.util.concurrent.ForkJoinPool")
);
if (insideAwaitWork) return true;
//java.lang.AssertionError: Thread leaked: Thread[ForkJoinPool.commonPool-worker-13,4,main] (alive) WAITING
//--- its stacktrace:
// at [email protected]/jdk.internal.misc.Unsafe.park(Native Method)
// at [email protected]/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
// at [email protected]/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1628)
// at [email protected]/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
return stackTrace.length > 2
// can be both sun.misc.Unsafe and jdk.internal.misc.Unsafe on depending on the jdk
&& stackTrace[0].getClassName().endsWith(".Unsafe") && stackTrace[0].getMethodName().equals("park")
&& stackTrace[1].getClassName().equals("java.util.concurrent.locks.LockSupport") && stackTrace[1].getMethodName().equals("park")
&& stackTrace[2].getClassName().equals("java.util.concurrent.ForkJoinPool") && stackTrace[2].getMethodName().equals("runWorker");
}
// in newer JDKs strange long hangups observed in Unsafe.unpark:
// "Document Committing Pool" (alive) TIMED_WAITING
// at sun.misc.Unsafe.unpark(Native Method)
// at java.util.concurrent.locks.LockSupport.unpark(LockSupport.java:141)
// at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:372)
// at java.util.concurrent.FutureTask.set(FutureTask.java:233)
// at java.util.concurrent.FutureTask.run(FutureTask.java:274)
// at com.intellij.util.concurrency.BoundedTaskExecutor.doRun(BoundedTaskExecutor.java:207)
// at com.intellij.util.concurrency.BoundedTaskExecutor.access$100(BoundedTaskExecutor.java:29)
// at com.intellij.util.concurrency.BoundedTaskExecutor$1.lambda$run$0(BoundedTaskExecutor.java:185)
// at com.intellij.util.concurrency.BoundedTaskExecutor$1$$Lambda$157/1473781324.run(Unknown Source)
// at com.intellij.util.ConcurrencyUtil.runUnderThreadName(ConcurrencyUtil.java:208)
// at com.intellij.util.concurrency.BoundedTaskExecutor$1.run(BoundedTaskExecutor.java:181)
// at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
// at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
// at java.lang.Thread.run(Thread.java:748)
private static boolean isFutureTaskAboutToFinish(StackTraceElement[] stackTrace) {
if (stackTrace.length < 5) {
return false;
}
return stackTrace[0].getClassName().equals("sun.misc.Unsafe")
&& stackTrace[0].getMethodName().equals("unpark")
&& stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask")
&& stackTrace[2].getMethodName().equals("finishCompletion");
}
/**
* at sun.misc.Unsafe.park(Native Method)
* at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
* at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:83)
* at java.lang.Thread.run(Thread.java:748)
*/
private static boolean isIdleDefaultCoroutineExecutorThread(Thread thread, StackTraceElement[] stackTrace) {
if (stackTrace.length != 4) {
return false;
}
return "kotlinx.coroutines.DefaultExecutor".equals(thread.getName())
&& (stackTrace[0].getClassName().equals("sun.misc.Unsafe") || stackTrace[0].getClassName().equals("jdk.internal.misc.Unsafe"))
&& stackTrace[0].getMethodName().equals("park")
&& stackTrace[2].getClassName().equals("kotlinx.coroutines.DefaultExecutor")
&& stackTrace[2].getMethodName().equals("run");
}
private static boolean isCoroutineSchedulerPoolThread(Thread thread, StackTraceElement[] stackTrace) {
if (!"kotlinx.coroutines.scheduling.CoroutineScheduler$Worker".equals(thread.getClass().getName())) {
return false;
}
//noinspection UnnecessaryLocalVariable
boolean insideCpuWorkerIdle = ContainerUtil.exists(
stackTrace,
element -> element.getMethodName().equals("park")
&& element.getClassName().equals("kotlinx.coroutines.scheduling.CoroutineScheduler$Worker")
);
return insideCpuWorkerIdle;
}
/**
* Starter framework [intellij.ide.starter] / [intellij.ide.starter.extended] registers its own JUnit listeners.
* A listener's order of execution isn't defined, so when the thread leak detector detects a leak,
* the listener from starter might not have a chance to clean up after tests.
*/
private static boolean isStarterTestFramework(StackTraceElement[] stackTrace) {
// java.lang.AssertionError: Thread leaked: Thread[Redirect stderr,5,main] (alive) RUNNABLE
//--- its stacktrace:
// ...
// at app//com.intellij.ide.starter.process.exec.ProcessExecutor$redirectProcessOutput$1.invoke(ProcessExecutor.kt:40)
// at app//kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
return ContainerUtil.exists(
stackTrace,
element -> element.getClassName().contains("com.intellij.ide.starter")
);
}
/**
* {@code com.intellij.driver.client.*} is using JMX. That might lead to long-living tasks.
*/
private static boolean isJMXRemoteCall(StackTraceElement[] stackTrace) {
// Thread leaked: Thread[JMX client heartbeat 3,5,main] (alive) TIMED_WAITING
// --- its stacktrace:
// at [email protected]/java.lang.Thread.sleep(Native Method)
// at [email protected]/com.sun.jmx.remote.internal.ClientCommunicatorAdmin$Checker.run(ClientCommunicatorAdmin.java:180)
// at [email protected]/java.lang.Thread.run(Thread.java:840)
return ContainerUtil.exists(stackTrace, element -> element.getClassName().contains("com.sun.jmx.remote"));
}
/**
* <a href="https://youtrack.jetbrains.com/issue/IDEA-349419/Flaky-thread-leak-in-ConsoleSpanExporter">IDEA-349419</a>
*/
private static boolean isBuildLogCall(StackTraceElement[] stackTrace) {
//java.lang.AssertionError: Thread leaked: Thread[#204,DefaultDispatcher-worker-6,5,main] (alive) RUNNABLE
// --- its stacktrace:
//at java.base/java.io.FileOutputStream.writeBytes(Native Method)
//at org.jetbrains.intellij.build.ConsoleSpanExporter.export(ConsoleSpanExporter.kt:44)
//at com.intellij.platform.diagnostic.telemetry.exporters.BatchSpanProcessor$exportCurrentBatch$2.invokeSuspend(BatchSpanProcessor.kt:155)
return ContainerUtil.exists(stackTrace, element -> element.getClassName().contains("org.jetbrains.intellij.build.ConsoleSpanExporter"));
}
private static CharSequence dumpThreadsToString(Map<String, Thread> after, Map<Thread, StackTraceElement[]> stackTraces) {
StringBuilder f = new StringBuilder();
for (Map.Entry<String, Thread> entry : after.entrySet()) {
Thread t = entry.getValue();
f.append('"').append(entry.getKey()).append("\" (").append(t.isAlive() ? "alive" : "dead").append(") ").append(t.getState())
.append('\n');
for (StackTraceElement element : stackTraces.get(t)) {
f.append("\tat ").append(element).append('\n');
}
f.append('\n');
}
return f;
}
private static String internalDiagnostic(StackTraceElement[] stackTrace) {
return stackTrace.length < 5
? "stackTrace.length: " + stackTrace.length
: "(diagnostic: " +
"0: " + stackTrace[0].getClassName() +
" : " + stackTrace[0].getClassName().equals("sun.misc.Unsafe") +
" . " + stackTrace[0].getMethodName() +
" : " + stackTrace[0].getMethodName().equals("unpark") +
" 2: " + stackTrace[2].getClassName() +
" : " + stackTrace[2].getClassName().equals("java.util.concurrent.FutureTask") +
" . " + stackTrace[2].getMethodName() +
" : " + stackTrace[2].getMethodName().equals("finishCompletion") +
")";
}
private static MethodHandle getThreadsMethodHandle() {
try {
return MethodHandles.privateLookupIn(Thread.class, MethodHandles.lookup())
.findStatic(Thread.class, "getThreads", MethodType.methodType(Thread[].class));
}
catch (Throwable e) {
throw new IllegalStateException("Unable to access the Thread#getThreads method", e);
}
}
private static void validateWhitelistedThreads(List<String> offenders) {
List<String> sorted = new ArrayList<>(offenders);
sorted.sort(String::compareToIgnoreCase);
if (offenders.equals(sorted)) {
return;
}
@SuppressWarnings("deprecation") String proper = String
.join(",\n", ContainerUtil.map(sorted, s -> '"' + s + '"'))
.replaceAll('"' + FlushingDaemon.NAME + '"', "FlushingDaemon.NAME")
.replaceAll('"' + ProcessIOExecutorService.POOLED_THREAD_PREFIX + '"', "ProcessIOExecutorService.POOLED_THREAD_PREFIX");
throw new AssertionError("Thread names must be sorted (for ease of maintenance). Something like this will do:\n" + proper);
}
}
| JetBrains/intellij-community | platform/testFramework/common/src/common/ThreadLeakTracker.java |
180,192 | package cn.nukkit.block;
import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.entity.Entity;
import cn.nukkit.item.Item;
import cn.nukkit.item.ItemBlock;
import cn.nukkit.item.ItemTool;
import cn.nukkit.item.enchantment.Enchantment;
import cn.nukkit.level.Level;
import cn.nukkit.level.MovingObjectPosition;
import cn.nukkit.level.Position;
import cn.nukkit.math.AxisAlignedBB;
import cn.nukkit.math.BlockFace;
import cn.nukkit.math.Vector3;
import cn.nukkit.metadata.MetadataValue;
import cn.nukkit.metadata.Metadatable;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.potion.Effect;
import cn.nukkit.utils.BlockColor;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* author: MagicDroidX
* Nukkit Project
*/
public abstract class Block extends Position implements Metadatable, Cloneable, AxisAlignedBB, BlockID {
public static Class[] list = null;
public static Block[] fullList = null;
public static int[] light = null;
public static int[] lightFilter = null;
public static boolean[] solid = null;
public static double[] hardness = null;
public static boolean[] transparent = null;
/**
* if a block has can have variants
*/
public static boolean[] hasMeta = null;
protected Block() {}
@SuppressWarnings("unchecked")
public static void init() {
if (list == null) {
list = new Class[256];
fullList = new Block[4096];
light = new int[256];
lightFilter = new int[256];
solid = new boolean[256];
hardness = new double[256];
transparent = new boolean[256];
hasMeta = new boolean[256];
list[AIR] = BlockAir.class; //0
list[STONE] = BlockStone.class; //1
list[GRASS] = BlockGrass.class; //2
list[DIRT] = BlockDirt.class; //3
list[COBBLESTONE] = BlockCobblestone.class; //4
list[PLANKS] = BlockPlanks.class; //5
list[SAPLING] = BlockSapling.class; //6
list[BEDROCK] = BlockBedrock.class; //7
list[WATER] = BlockWater.class; //8
list[STILL_WATER] = BlockWaterStill.class; //9
list[LAVA] = BlockLava.class; //10
list[STILL_LAVA] = BlockLavaStill.class; //11
list[SAND] = BlockSand.class; //12
list[GRAVEL] = BlockGravel.class; //13
list[GOLD_ORE] = BlockOreGold.class; //14
list[IRON_ORE] = BlockOreIron.class; //15
list[COAL_ORE] = BlockOreCoal.class; //16
list[WOOD] = BlockWood.class; //17
list[LEAVES] = BlockLeaves.class; //18
list[SPONGE] = BlockSponge.class; //19
list[GLASS] = BlockGlass.class; //20
list[LAPIS_ORE] = BlockOreLapis.class; //21
list[LAPIS_BLOCK] = BlockLapis.class; //22
list[DISPENSER] = BlockDispenser.class; //23
list[SANDSTONE] = BlockSandstone.class; //24
list[NOTEBLOCK] = BlockNoteblock.class; //25
list[BED_BLOCK] = BlockBed.class; //26
list[POWERED_RAIL] = BlockRailPowered.class; //27
list[DETECTOR_RAIL] = BlockRailDetector.class; //28
list[STICKY_PISTON] = BlockPistonSticky.class; //29
list[COBWEB] = BlockCobweb.class; //30
list[TALL_GRASS] = BlockTallGrass.class; //31
list[DEAD_BUSH] = BlockDeadBush.class; //32
list[PISTON] = BlockPiston.class; //33
list[PISTON_HEAD] = BlockPistonHead.class; //34
list[WOOL] = BlockWool.class; //35
list[DANDELION] = BlockDandelion.class; //37
list[FLOWER] = BlockFlower.class; //38
list[BROWN_MUSHROOM] = BlockMushroomBrown.class; //39
list[RED_MUSHROOM] = BlockMushroomRed.class; //40
list[GOLD_BLOCK] = BlockGold.class; //41
list[IRON_BLOCK] = BlockIron.class; //42
list[DOUBLE_STONE_SLAB] = BlockDoubleSlabStone.class; //43
list[STONE_SLAB] = BlockSlabStone.class; //44
list[BRICKS_BLOCK] = BlockBricks.class; //45
list[TNT] = BlockTNT.class; //46
list[BOOKSHELF] = BlockBookshelf.class; //47
list[MOSS_STONE] = BlockMossStone.class; //48
list[OBSIDIAN] = BlockObsidian.class; //49
list[TORCH] = BlockTorch.class; //50
list[FIRE] = BlockFire.class; //51
list[MONSTER_SPAWNER] = BlockMobSpawner.class; //52
list[WOOD_STAIRS] = BlockStairsWood.class; //53
list[CHEST] = BlockChest.class; //54
list[REDSTONE_WIRE] = BlockRedstoneWire.class; //55
list[DIAMOND_ORE] = BlockOreDiamond.class; //56
list[DIAMOND_BLOCK] = BlockDiamond.class; //57
list[WORKBENCH] = BlockCraftingTable.class; //58
list[WHEAT_BLOCK] = BlockWheat.class; //59
list[FARMLAND] = BlockFarmland.class; //60
list[FURNACE] = BlockFurnace.class; //61
list[BURNING_FURNACE] = BlockFurnaceBurning.class; //62
list[SIGN_POST] = BlockSignPost.class; //63
list[WOOD_DOOR_BLOCK] = BlockDoorWood.class; //64
list[LADDER] = BlockLadder.class; //65
list[RAIL] = BlockRail.class; //66
list[COBBLESTONE_STAIRS] = BlockStairsCobblestone.class; //67
list[WALL_SIGN] = BlockWallSign.class; //68
list[LEVER] = BlockLever.class; //69
list[STONE_PRESSURE_PLATE] = BlockPressurePlateStone.class; //70
list[IRON_DOOR_BLOCK] = BlockDoorIron.class; //71
list[WOODEN_PRESSURE_PLATE] = BlockPressurePlateWood.class; //72
list[REDSTONE_ORE] = BlockOreRedstone.class; //73
list[GLOWING_REDSTONE_ORE] = BlockOreRedstoneGlowing.class; //74
list[UNLIT_REDSTONE_TORCH] = BlockRedstoneTorchUnlit.class;
list[REDSTONE_TORCH] = BlockRedstoneTorch.class; //76
list[STONE_BUTTON] = BlockButtonStone.class; //77
list[SNOW_LAYER] = BlockSnowLayer.class; //78
list[ICE] = BlockIce.class; //79
list[SNOW_BLOCK] = BlockSnow.class; //80
list[CACTUS] = BlockCactus.class; //81
list[CLAY_BLOCK] = BlockClay.class; //82
list[SUGARCANE_BLOCK] = BlockSugarcane.class; //83
list[JUKEBOX] = BlockJukebox.class; //84
list[FENCE] = BlockFence.class; //85
list[PUMPKIN] = BlockPumpkin.class; //86
list[NETHERRACK] = BlockNetherrack.class; //87
list[SOUL_SAND] = BlockSoulSand.class; //88
list[GLOWSTONE_BLOCK] = BlockGlowstone.class; //89
list[NETHER_PORTAL] = BlockNetherPortal.class; //90
list[LIT_PUMPKIN] = BlockPumpkinLit.class; //91
list[CAKE_BLOCK] = BlockCake.class; //92
list[UNPOWERED_REPEATER] = BlockRedstoneRepeaterUnpowered.class; //93
list[POWERED_REPEATER] = BlockRedstoneRepeaterPowered.class; //94
list[INVISIBLE_BEDROCK] = BlockBedrockInvisible.class; //95
list[TRAPDOOR] = BlockTrapdoor.class; //96
list[MONSTER_EGG] = BlockMonsterEgg.class; //97
list[STONE_BRICKS] = BlockBricksStone.class; //98
list[BROWN_MUSHROOM_BLOCK] = BlockHugeMushroomBrown.class; //99
list[RED_MUSHROOM_BLOCK] = BlockHugeMushroomRed.class; //100
list[IRON_BARS] = BlockIronBars.class; //101
list[GLASS_PANE] = BlockGlassPane.class; //102
list[MELON_BLOCK] = BlockMelon.class; //103
list[PUMPKIN_STEM] = BlockStemPumpkin.class; //104
list[MELON_STEM] = BlockStemMelon.class; //105
list[VINE] = BlockVine.class; //106
list[FENCE_GATE] = BlockFenceGate.class; //107
list[BRICK_STAIRS] = BlockStairsBrick.class; //108
list[STONE_BRICK_STAIRS] = BlockStairsStoneBrick.class; //109
list[MYCELIUM] = BlockMycelium.class; //110
list[WATER_LILY] = BlockWaterLily.class; //111
list[NETHER_BRICKS] = BlockBricksNether.class; //112
list[NETHER_BRICK_FENCE] = BlockFenceNetherBrick.class; //113
list[NETHER_BRICKS_STAIRS] = BlockStairsNetherBrick.class; //114
list[NETHER_WART_BLOCK] = BlockNetherWart.class; //115
list[ENCHANTING_TABLE] = BlockEnchantingTable.class; //116
list[BREWING_STAND_BLOCK] = BlockBrewingStand.class; //117
list[CAULDRON_BLOCK] = BlockCauldron.class; //118
list[END_PORTAL] = BlockEndPortal.class; //119
list[END_PORTAL_FRAME] = BlockEndPortalFrame.class; //120
list[END_STONE] = BlockEndStone.class; //121
list[DRAGON_EGG] = BlockDragonEgg.class; //122
list[REDSTONE_LAMP] = BlockRedstoneLamp.class; //123
list[LIT_REDSTONE_LAMP] = BlockRedstoneLampLit.class; //124
//TODO: list[DROPPER] = BlockDropper.class; //125
list[ACTIVATOR_RAIL] = BlockRailActivator.class; //126
list[COCOA] = BlockCocoa.class; //127
list[SANDSTONE_STAIRS] = BlockStairsSandstone.class; //128
list[EMERALD_ORE] = BlockOreEmerald.class; //129
list[ENDER_CHEST] = BlockEnderChest.class; //130
list[TRIPWIRE_HOOK] = BlockTripWireHook.class;
list[TRIPWIRE] = BlockTripWire.class; //132
list[EMERALD_BLOCK] = BlockEmerald.class; //133
list[SPRUCE_WOOD_STAIRS] = BlockStairsSpruce.class; //134
list[BIRCH_WOOD_STAIRS] = BlockStairsBirch.class; //135
list[JUNGLE_WOOD_STAIRS] = BlockStairsJungle.class; //136
list[BEACON] = BlockBeacon.class; //138
list[STONE_WALL] = BlockWall.class; //139
list[FLOWER_POT_BLOCK] = BlockFlowerPot.class; //140
list[CARROT_BLOCK] = BlockCarrot.class; //141
list[POTATO_BLOCK] = BlockPotato.class; //142
list[WOODEN_BUTTON] = BlockButtonWooden.class; //143
list[SKULL_BLOCK] = BlockSkull.class; //144
list[ANVIL] = BlockAnvil.class; //145
list[TRAPPED_CHEST] = BlockTrappedChest.class; //146
list[LIGHT_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateLight.class; //147
list[HEAVY_WEIGHTED_PRESSURE_PLATE] = BlockWeightedPressurePlateHeavy.class; //148
list[UNPOWERED_COMPARATOR] = BlockRedstoneComparatorUnpowered.class; //149
list[POWERED_COMPARATOR] = BlockRedstoneComparatorPowered.class; //149
list[DAYLIGHT_DETECTOR] = BlockDaylightDetector.class; //151
list[REDSTONE_BLOCK] = BlockRedstone.class; //152
list[QUARTZ_ORE] = BlockOreQuartz.class; //153
list[HOPPER_BLOCK] = BlockHopper.class; //154
list[QUARTZ_BLOCK] = BlockQuartz.class; //155
list[QUARTZ_STAIRS] = BlockStairsQuartz.class; //156
list[DOUBLE_WOOD_SLAB] = BlockDoubleSlabWood.class; //157
list[WOOD_SLAB] = BlockSlabWood.class; //158
list[STAINED_TERRACOTTA] = BlockTerracottaStained.class; //159
list[STAINED_GLASS_PANE] = BlockGlassPaneStained.class; //160
list[LEAVES2] = BlockLeaves2.class; //161
list[WOOD2] = BlockWood2.class; //162
list[ACACIA_WOOD_STAIRS] = BlockStairsAcacia.class; //163
list[DARK_OAK_WOOD_STAIRS] = BlockStairsDarkOak.class; //164
list[SLIME_BLOCK] = BlockSlime.class; //165
list[IRON_TRAPDOOR] = BlockTrapdoorIron.class; //167
list[PRISMARINE] = BlockPrismarine.class; //168
list[SEA_LANTERN] = BlockSeaLantern.class; //169
list[HAY_BALE] = BlockHayBale.class; //170
list[CARPET] = BlockCarpet.class; //171
list[TERRACOTTA] = BlockTerracotta.class; //172
list[COAL_BLOCK] = BlockCoal.class; //173
list[PACKED_ICE] = BlockIcePacked.class; //174
list[DOUBLE_PLANT] = BlockDoublePlant.class; //175
list[STANDING_BANNER] = BlockBanner.class; //176
list[WALL_BANNER] = BlockWallBanner.class; //177
list[DAYLIGHT_DETECTOR_INVERTED] = BlockDaylightDetectorInverted.class; //178
list[RED_SANDSTONE] = BlockRedSandstone.class; //179
list[RED_SANDSTONE_STAIRS] = BlockStairsRedSandstone.class; //180
list[DOUBLE_RED_SANDSTONE_SLAB] = BlockDoubleSlabRedSandstone.class; //181
list[RED_SANDSTONE_SLAB] = BlockSlabRedSandstone.class; //182
list[FENCE_GATE_SPRUCE] = BlockFenceGateSpruce.class; //183
list[FENCE_GATE_BIRCH] = BlockFenceGateBirch.class; //184
list[FENCE_GATE_JUNGLE] = BlockFenceGateJungle.class; //185
list[FENCE_GATE_DARK_OAK] = BlockFenceGateDarkOak.class; //186
list[FENCE_GATE_ACACIA] = BlockFenceGateAcacia.class; //187
list[SPRUCE_DOOR_BLOCK] = BlockDoorSpruce.class; //193
list[BIRCH_DOOR_BLOCK] = BlockDoorBirch.class; //194
list[JUNGLE_DOOR_BLOCK] = BlockDoorJungle.class; //195
list[ACACIA_DOOR_BLOCK] = BlockDoorAcacia.class; //196
list[DARK_OAK_DOOR_BLOCK] = BlockDoorDarkOak.class; //197
list[GRASS_PATH] = BlockGrassPath.class; //198
list[ITEM_FRAME_BLOCK] = BlockItemFrame.class; //199
list[CHORUS_FLOWER] = BlockChorusFlower.class; //200
list[PURPUR_BLOCK] = BlockPurpur.class; //201
list[PURPUR_STAIRS] = BlockStairsPurpur.class; //203
list[UNDYED_SHULKER_BOX] = BlockUndyedShulkerBox.class; //205
list[END_BRICKS] = BlockBricksEndStone.class; //206
list[END_ROD] = BlockEndRod.class; //208
list[END_GATEWAY] = BlockEndGateway.class; //209
list[MAGMA] = BlockMagma.class; //213
list[BLOCK_NETHER_WART_BLOCK] = BlockNetherWartBlock.class; //214
list[RED_NETHER_BRICK] = BlockBricksRedNether.class; //215
list[BONE_BLOCK] = BlockBone.class; //216
list[SHULKER_BOX] = BlockShulkerBox.class; //218
list[PURPLE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPurple.class; //219
list[WHITE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedWhite.class; //220
list[ORANGE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedOrange.class; //221
list[MAGENTA_GLAZED_TERRACOTTA] = BlockTerracottaGlazedMagenta.class; //222
list[LIGHT_BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLightBlue.class; //223
list[YELLOW_GLAZED_TERRACOTTA] = BlockTerracottaGlazedYellow.class; //224
list[LIME_GLAZED_TERRACOTTA] = BlockTerracottaGlazedLime.class; //225
list[PINK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedPink.class; //226
list[GRAY_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGray.class; //227
list[SILVER_GLAZED_TERRACOTTA] = BlockTerracottaGlazedSilver.class; //228
list[CYAN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedCyan.class; //229
list[BLUE_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlue.class; //231
list[BROWN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBrown.class; //232
list[GREEN_GLAZED_TERRACOTTA] = BlockTerracottaGlazedGreen.class; //233
list[RED_GLAZED_TERRACOTTA] = BlockTerracottaGlazedRed.class; //234
list[BLACK_GLAZED_TERRACOTTA] = BlockTerracottaGlazedBlack.class; //235
list[CONCRETE] = BlockConcrete.class; //236
list[CONCRETE_POWDER] = BlockConcretePowder.class; //237
list[CHORUS_PLANT] = BlockChorusPlant.class; //240
list[STAINED_GLASS] = BlockGlassStained.class; //241
list[PODZOL] = BlockPodzol.class; //243
list[BEETROOT_BLOCK] = BlockBeetroot.class; //244
list[STONECUTTER] = BlockStonecutter.class; //245
list[GLOWING_OBSIDIAN] = BlockObsidianGlowing.class; //246
//list[NETHER_REACTOR] = BlockNetherReactor.class; //247 Should not be removed
//TODO: list[PISTON_EXTENSION] = BlockPistonExtension.class; //250
list[OBSERVER] = BlockObserver.class; //251
for (int id = 0; id < 256; id++) {
Class c = list[id];
if (c != null) {
Block block;
try {
block = (Block) c.newInstance();
try {
Constructor constructor = c.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
for (int data = 0; data < 16; ++data) {
fullList[(id << 4) | data] = (Block) constructor.newInstance(data);
}
hasMeta[id] = true;
} catch (NoSuchMethodException ignore) {
for (int data = 0; data < 16; ++data) {
fullList[(id << 4) | data] = block;
}
}
} catch (Exception e) {
Server.getInstance().getLogger().error("Error while registering " + c.getName(), e);
for (int data = 0; data < 16; ++data) {
fullList[(id << 4) | data] = new BlockUnknown(id, data);
}
return;
}
solid[id] = block.isSolid();
transparent[id] = block.isTransparent();
hardness[id] = block.getHardness();
light[id] = block.getLightLevel();
if (block.isSolid()) {
if (block.isTransparent()) {
if (block instanceof BlockLiquid || block instanceof BlockIce) {
lightFilter[id] = 2;
} else {
lightFilter[id] = 1;
}
} else {
lightFilter[id] = 15;
}
} else {
lightFilter[id] = 1;
}
} else {
lightFilter[id] = 1;
for (int data = 0; data < 16; ++data) {
fullList[(id << 4) | data] = new BlockUnknown(id, data);
}
}
}
}
}
public static Block get(int id) {
return fullList[id << 4].clone();
}
public static Block get(int id, Integer meta) {
if (meta != null) {
return fullList[(id << 4) + meta].clone();
} else {
return fullList[id << 4].clone();
}
}
public static Block get(int id, Integer meta, Position pos) {
Block block = fullList[(id << 4) | (meta == null ? 0 : meta)].clone();
if (pos != null) {
block.x = pos.x;
block.y = pos.y;
block.z = pos.z;
block.level = pos.level;
}
return block;
}
public static Block get(int id, int data) {
return fullList[(id << 4) + data].clone();
}
public static Block get(int fullId, Level level, int x, int y, int z) {
Block block = fullList[fullId].clone();
block.x = x;
block.y = y;
block.z = z;
block.level = level;
return block;
}
public boolean place(Item item, Block block, Block target, BlockFace face, double fx, double fy, double fz, Player player) {
return this.getLevel().setBlock(this, this, true, true);
}
//http://minecraft.gamepedia.com/Breaking
public boolean canHarvestWithHand() { //used for calculating breaking time
return true;
}
public boolean isBreakable(Item item) {
return true;
}
public int tickRate() {
return 10;
}
public boolean onBreak(Item item) {
return this.getLevel().setBlock(this, Block.get(BlockID.AIR), true, true);
}
public int onUpdate(int type) {
return 0;
}
public boolean onActivate(Item item) {
return this.onActivate(item, null);
}
public boolean onActivate(Item item, Player player) {
return false;
}
public double getHardness() {
return 10;
}
public double getResistance() {
return 1;
}
public int getBurnChance() {
return 0;
}
public int getBurnAbility() {
return 0;
}
public int getToolType() {
return ItemTool.TYPE_NONE;
}
public double getFrictionFactor() {
return 0.6;
}
public int getLightLevel() {
return 0;
}
public boolean canBePlaced() {
return true;
}
public boolean canBeReplaced() {
return false;
}
public boolean isTransparent() {
return false;
}
public boolean isSolid() {
return true;
}
public boolean canBeFlowedInto() {
return false;
}
public boolean canBeActivated() {
return false;
}
public boolean hasEntityCollision() {
return false;
}
public boolean canPassThrough() {
return false;
}
public boolean canBePushed() {
return true;
}
public boolean hasComparatorInputOverride() {
return false;
}
public int getComparatorInputOverride() {
return 0;
}
public boolean canBeClimbed() {
return false;
}
public BlockColor getColor() {
return BlockColor.VOID_BLOCK_COLOR;
}
public abstract String getName();
public abstract int getId();
/**
* The full id is a combination of the id and data.
* @return full id
*/
public int getFullId() {
return (getId() << 4);
}
public void addVelocityToEntity(Entity entity, Vector3 vector) {
}
public int getDamage() {
return 0;
}
public void setDamage(int meta) {
// Do nothing
}
public final void setDamage(Integer meta) {
setDamage((meta == null ? 0 : meta & 0x0f));
}
final public void position(Position v) {
this.x = (int) v.x;
this.y = (int) v.y;
this.z = (int) v.z;
this.level = v.level;
}
public Item[] getDrops(Item item) {
if (this.getId() < 0 || this.getId() > list.length) { //Unknown blocks
return new Item[0];
} else {
return new Item[]{
this.toItem()
};
}
}
private static double toolBreakTimeBonus0(int toolType, int toolTier, int blockId) {
if (toolType == ItemTool.TYPE_SWORD) return blockId == Block.COBWEB ? 15.0 : 1.0;
if (toolType == ItemTool.TYPE_SHEARS) {
if (blockId == Block.WOOL || blockId == LEAVES || blockId == LEAVES2) {
return 5.0;
} else if (blockId == COBWEB) {
return 15.0;
}
return 1.0;
}
if (toolType == ItemTool.TYPE_NONE) return 1.0;
switch (toolTier) {
case ItemTool.TIER_WOODEN:
return 2.0;
case ItemTool.TIER_STONE:
return 4.0;
case ItemTool.TIER_IRON:
return 6.0;
case ItemTool.TIER_DIAMOND:
return 8.0;
case ItemTool.TIER_NETHERITE:
return 9.0;
case ItemTool.TIER_GOLD:
return 12.0;
default:
return 1.0;
}
}
private static double speedBonusByEfficiencyLore0(int efficiencyLoreLevel) {
if (efficiencyLoreLevel == 0) return 0;
return efficiencyLoreLevel * efficiencyLoreLevel + 1;
}
private static double speedRateByHasteLore0(int hasteLoreLevel) {
return 1.0 + (0.2 * hasteLoreLevel);
}
private static int toolType0(Item item) {
if (item.isSword()) return ItemTool.TYPE_SWORD;
if (item.isShovel()) return ItemTool.TYPE_SHOVEL;
if (item.isPickaxe()) return ItemTool.TYPE_PICKAXE;
if (item.isAxe()) return ItemTool.TYPE_AXE;
if (item.isHoe()) return ItemTool.TYPE_HOE;
if (item.isShears()) return ItemTool.TYPE_SHEARS;
return ItemTool.TYPE_NONE;
}
private static boolean correctTool0(int blockToolType, Item item) {
return (blockToolType == ItemTool.TYPE_SWORD && item.isSword()) ||
(blockToolType == ItemTool.TYPE_SHOVEL && item.isShovel()) ||
(blockToolType == ItemTool.TYPE_PICKAXE && item.isPickaxe()) ||
(blockToolType == ItemTool.TYPE_AXE && item.isAxe()) ||
(blockToolType == ItemTool.TYPE_HOE && item.isHoe()) ||
(blockToolType == ItemTool.TYPE_SHEARS && item.isShears()) ||
blockToolType == ItemTool.TYPE_NONE;
}
//http://minecraft.gamepedia.com/Breaking
private static double breakTime0(double blockHardness, boolean correctTool, boolean canHarvestWithHand,
int blockId, int toolType, int toolTier, int efficiencyLoreLevel, int hasteEffectLevel,
boolean insideOfWaterWithoutAquaAffinity, boolean outOfWaterButNotOnGround) {
double baseTime = ((correctTool || canHarvestWithHand) ? 1.5 : 5.0) * blockHardness;
double speed = 1.0 / baseTime;
if (correctTool) speed *= toolBreakTimeBonus0(toolType, toolTier, blockId);
speed += correctTool ? speedBonusByEfficiencyLore0(efficiencyLoreLevel) : 0;
speed *= speedRateByHasteLore0(hasteEffectLevel);
if (insideOfWaterWithoutAquaAffinity) speed *= 0.2;
if (outOfWaterButNotOnGround) speed *= 0.2;
return 1.0 / speed;
}
public double getBreakTime(Item item, Player player) {
Objects.requireNonNull(item, "getBreakTime: Item can not be null");
Objects.requireNonNull(player, "getBreakTime: Player can not be null");
double blockHardness = getHardness();
if (blockHardness == 0) {
return 0;
}
int blockId = getId();
boolean correctTool = correctTool0(getToolType(), item)
|| item.isShears() && (blockId == COBWEB || blockId == LEAVES || blockId == LEAVES2);
boolean canHarvestWithHand = canHarvestWithHand();
int itemToolType = toolType0(item);
int itemTier = item.getTier();
int efficiencyLoreLevel = Optional.ofNullable(item.getEnchantment(Enchantment.ID_EFFICIENCY))
.map(Enchantment::getLevel).orElse(0);
int hasteEffectLevel = Optional.ofNullable(player.getEffect(Effect.HASTE))
.map(Effect::getAmplifier).orElse(0);
boolean insideOfWaterWithoutAquaAffinity = player.isInsideOfWater() &&
Optional.ofNullable(player.getInventory().getHelmet().getEnchantment(Enchantment.ID_WATER_WORKER))
.map(Enchantment::getLevel).map(l -> l >= 1).orElse(false);
boolean outOfWaterButNotOnGround = (!player.isInsideOfWater()) && (!player.isOnGround());
return breakTime0(blockHardness, correctTool, canHarvestWithHand, blockId, itemToolType, itemTier,
efficiencyLoreLevel, hasteEffectLevel, insideOfWaterWithoutAquaAffinity, outOfWaterButNotOnGround);
}
/**
* @deprecated This function is lack of Player class and is not accurate enough, use #getBreakTime(Item, Player)
* @param item item used
* @return break time
*/
@Deprecated
public double getBreakTime(Item item) {
double base = this.getHardness() * 1.5;
if (this.canBeBrokenWith(item)) {
if (this.getToolType() == ItemTool.TYPE_SHEARS && item.isShears()) {
base /= 15;
} else if (
(this.getToolType() == ItemTool.TYPE_PICKAXE && item.isPickaxe()) ||
(this.getToolType() == ItemTool.TYPE_AXE && item.isAxe()) ||
(this.getToolType() == ItemTool.TYPE_SHOVEL && item.isShovel()) ||
(this.getToolType() == ItemTool.TYPE_HOE && item.isHoe())
) {
int tier = item.getTier();
switch (tier) {
case ItemTool.TIER_WOODEN:
base /= 2;
break;
case ItemTool.TIER_STONE:
base /= 4;
break;
case ItemTool.TIER_IRON:
base /= 6;
break;
case ItemTool.TIER_DIAMOND:
base /= 8;
break;
case ItemTool.TIER_NETHERITE:
base /= 9;
break;
case ItemTool.TIER_GOLD:
base /= 12;
break;
}
}
} else {
base *= 3.33;
}
if (item.isSword()) {
base *= 0.5;
}
return base;
}
public boolean canBeBrokenWith(Item item) {
return this.getHardness() != -1;
}
public Block getSide(BlockFace face) {
if (this.isValid()) {
return this.getLevel().getBlock((int) x + face.getXOffset(), (int) y + face.getYOffset(), (int) z + face.getZOffset());
}
return this.getSide(face, 1);
}
public Block getSide(BlockFace face, int step) {
if (this.isValid()) {
if (step == 1) {
return this.getLevel().getBlock((int) x + face.getXOffset(), (int) y + face.getYOffset(), (int) z + face.getZOffset());
} else {
return this.getLevel().getBlock((int) x + face.getXOffset() * step, (int) y + face.getYOffset() * step, (int) z + face.getZOffset() * step);
}
}
Block block = Block.get(Item.AIR, 0);
block.x = (int) x + face.getXOffset() * step;
block.y = (int) y + face.getYOffset() * step;
block.z = (int) z + face.getZOffset() * step;
return block;
}
public Block up() {
return up(1);
}
public Block up(int step) {
return getSide(BlockFace.UP, step);
}
public Block down() {
return down(1);
}
public Block down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Block north() {
return north(1);
}
public Block north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Block south() {
return south(1);
}
public Block south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Block east() {
return east(1);
}
public Block east(int step) {
return getSide(BlockFace.EAST, step);
}
public Block west() {
return west(1);
}
public Block west(int step) {
return getSide(BlockFace.WEST, step);
}
@Override
public String toString() {
return "Block[" + this.getName() + "] (" + this.getId() + ":" + this.getDamage() + ")";
}
public boolean collidesWithBB(AxisAlignedBB bb) {
return collidesWithBB(bb, false);
}
public boolean collidesWithBB(AxisAlignedBB bb, boolean collisionBB) {
AxisAlignedBB bb1 = collisionBB ? this.getCollisionBoundingBox() : this.getBoundingBox();
return bb1 != null && bb.intersectsWith(bb1);
}
public void onEntityCollide(Entity entity) {
}
public AxisAlignedBB getBoundingBox() {
return this.recalculateBoundingBox();
}
public AxisAlignedBB getCollisionBoundingBox() {
return this.recalculateCollisionBoundingBox();
}
protected AxisAlignedBB recalculateBoundingBox() {
return this;
}
@Override
public double getMinX() {
return this.x;
}
@Override
public double getMinY() {
return this.y;
}
@Override
public double getMinZ() {
return this.z;
}
@Override
public double getMaxX() {
return this.x + 1;
}
@Override
public double getMaxY() {
return this.y + 1;
}
@Override
public double getMaxZ() {
return this.z + 1;
}
protected AxisAlignedBB recalculateCollisionBoundingBox() {
return getBoundingBox();
}
public MovingObjectPosition calculateIntercept(Vector3 pos1, Vector3 pos2) {
AxisAlignedBB bb = this.getBoundingBox();
if (bb == null) {
return null;
}
Vector3 v1 = pos1.getIntermediateWithXValue(pos2, bb.getMinX());
Vector3 v2 = pos1.getIntermediateWithXValue(pos2, bb.getMaxX());
Vector3 v3 = pos1.getIntermediateWithYValue(pos2, bb.getMinY());
Vector3 v4 = pos1.getIntermediateWithYValue(pos2, bb.getMaxY());
Vector3 v5 = pos1.getIntermediateWithZValue(pos2, bb.getMinZ());
Vector3 v6 = pos1.getIntermediateWithZValue(pos2, bb.getMaxZ());
if (v1 != null && !bb.isVectorInYZ(v1)) {
v1 = null;
}
if (v2 != null && !bb.isVectorInYZ(v2)) {
v2 = null;
}
if (v3 != null && !bb.isVectorInXZ(v3)) {
v3 = null;
}
if (v4 != null && !bb.isVectorInXZ(v4)) {
v4 = null;
}
if (v5 != null && !bb.isVectorInXY(v5)) {
v5 = null;
}
if (v6 != null && !bb.isVectorInXY(v6)) {
v6 = null;
}
Vector3 vector = v1;
if (v2 != null && (vector == null || pos1.distanceSquared(v2) < pos1.distanceSquared(vector))) {
vector = v2;
}
if (v3 != null && (vector == null || pos1.distanceSquared(v3) < pos1.distanceSquared(vector))) {
vector = v3;
}
if (v4 != null && (vector == null || pos1.distanceSquared(v4) < pos1.distanceSquared(vector))) {
vector = v4;
}
if (v5 != null && (vector == null || pos1.distanceSquared(v5) < pos1.distanceSquared(vector))) {
vector = v5;
}
if (v6 != null && (vector == null || pos1.distanceSquared(v6) < pos1.distanceSquared(vector))) {
vector = v6;
}
if (vector == null) {
return null;
}
int f = -1;
if (vector == v1) {
f = 4;
} else if (vector == v2) {
f = 5;
} else if (vector == v3) {
f = 0;
} else if (vector == v4) {
f = 1;
} else if (vector == v5) {
f = 2;
} else if (vector == v6) {
f = 3;
}
return MovingObjectPosition.fromBlock((int) this.x, (int) this.y, (int) this.z, f, vector.add(this.x, this.y, this.z));
}
public String getSaveId() {
String name = getClass().getName();
return name.substring(16);
}
@Override
public void setMetadata(String metadataKey, MetadataValue newMetadataValue) throws Exception {
if (this.getLevel() != null) {
this.getLevel().getBlockMetadata().setMetadata(this, metadataKey, newMetadataValue);
}
}
@Override
public List<MetadataValue> getMetadata(String metadataKey) throws Exception {
if (this.getLevel() != null) {
return this.getLevel().getBlockMetadata().getMetadata(this, metadataKey);
}
return null;
}
@Override
public boolean hasMetadata(String metadataKey) throws Exception {
return this.getLevel() != null && this.getLevel().getBlockMetadata().hasMetadata(this, metadataKey);
}
@Override
public void removeMetadata(String metadataKey, Plugin owningPlugin) throws Exception {
if (this.getLevel() != null) {
this.getLevel().getBlockMetadata().removeMetadata(this, metadataKey, owningPlugin);
}
}
public Block clone() {
return (Block) super.clone();
}
public int getWeakPower(BlockFace face) {
return 0;
}
public int getStrongPower(BlockFace side) {
return 0;
}
public boolean isPowerSource() {
return false;
}
public String getLocationHash() {
return this.getFloorX() + ":" + this.getFloorY() + ":" + this.getFloorZ();
}
public int getDropExp() {
return 0;
}
public boolean isNormalBlock() {
return !isTransparent() && isSolid() && !isPowerSource();
}
public static boolean equals(Block b1, Block b2) {
return equals(b1, b2, true);
}
public static boolean equals(Block b1, Block b2, boolean checkDamage) {
return b1 != null && b2 != null && b1.getId() == b2.getId() && (!checkDamage || b1.getDamage() == b2.getDamage());
}
public Item toItem() {
return new ItemBlock(this, this.getDamage(), 1);
}
public boolean canSilkTouch() {
return false;
}
}
| CloudburstMC/Nukkit | src/main/java/cn/nukkit/block/Block.java |
180,193 | /*
* 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 java.lang.management;
import java.util.List;
import java.util.Map;
/**
* Stub implementation of ThreadMXBean.
*/
public interface ThreadMXBean {
long[] findMonitorDeadlockedThreads();
long[] getAllThreadIds();
long getCurrentThreadCpuTime();
long getCurrentThreadUserTime();
int getDaemonThreadCount();
int getPeakThreadCount();
int getThreadCount();
long getThreadCpuTime(long l);
ThreadInfo getThreadInfo(long l);
ThreadInfo getThreadInfo(long l, int i);
ThreadInfo[] getThreadInfo(long[] l);
ThreadInfo[] getThreadInfo(long[] l, int i);
long getThreadUserTime(long l);
long getTotalStartedThreadCount();
boolean isCurrentThreadCpuTimeSupported();
boolean isThreadContentionMonitoringEnabled();
boolean isThreadContentionMonitoringSupported();
boolean isThreadCpuTimeEnabled();
boolean isThreadCpuTimeSupported();
void resetPeakThreadCount();
void setThreadContentionMonitoringEnabled(boolean b);
void setThreadCpuTimeEnabled(boolean b);
}
| google/j2objc | jre_emul/Classes/java/lang/management/ThreadMXBean.java |
180,194 | package net.i2p.router.peermanager;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.i2p.data.Hash;
import net.i2p.router.CommSystemFacade;
import net.i2p.router.RouterContext;
import net.i2p.stat.RateStat;
import net.i2p.util.Log;
/**
* Copied from http://www.i2p2.i2p/how_peerselection.html
*
* See also main() below for additional commentary by zzz.
*
* Currently, there is no 'ejection' strategy to get rid of the profiles for peers that
* are no longer active (or when the network consists of thousands of peers, to get rid
* of peers that are performing poorly). However, the size of each profile is fairly small,
* and is unrelated to how much data is collected about the peer, so that a router can
* keep a few thousand active peer profiles before the overhead becomes a serious concern.
* Once it becomes necessary, we can simply compact the poorly performing profiles
* (keeping only the most basic data) and maintain hundreds of thousands of profiles
* in memory. Beyond that size, we can simply eject the peers (e.g. keeping the best 100,000).
*
* TODO most of the methods should be synchronized.
*
*/
public class PeerProfile {
private final Log _log;
private final RouterContext _context;
// whoozaat?
private final Hash _peer;
// general peer stats
private long _firstHeardAbout;
private long _lastHeardAbout;
private long _lastSentToSuccessfully;
private long _lastFailedSend;
private long _lastHeardFrom;
// unused
private float _tunnelTestResponseTimeAvg;
// periodic rates
//private RateStat _sendSuccessSize = null;
//private RateStat _receiveSize = null;
private RateStat _dbResponseTime;
private RateStat _tunnelCreateResponseTime;
// unused
private RateStat _tunnelTestResponseTime;
private RateStat _dbIntroduction;
// calculation bonuses
// ints to save some space
private int _speedBonus;
private int _capacityBonus;
private int _integrationBonus;
// calculation values
// floats to save some space
private float _speedValue;
private float _capacityValue;
private float _integrationValue;
// new calculation values, to be updated
// floats to save some space
private float _speedValueNew;
private float _capacityValueNew;
// are we in coalescing state?
private boolean _coalescing;
// good vs bad behavior
private TunnelHistory _tunnelHistory;
private DBHistory _dbHistory;
// does this peer profile contain expanded data, or just the basics?
private boolean _expanded;
private boolean _expandedDB;
//private int _consecutiveBanlists;
private final int _distance;
/** keep track of the fastest 3 throughputs */
private static final int THROUGHPUT_COUNT = 3;
/**
* fastest 1 minute throughput, in bytes per minute, ordered with fastest
* first. this is not synchronized, as we don't *need* perfection, and we only
* reorder/insert values on coallesce
*/
private final float _peakThroughput[] = new float[THROUGHPUT_COUNT];
private volatile long _peakThroughputCurrentTotal;
private final float _peakTunnelThroughput[] = new float[THROUGHPUT_COUNT];
/** total number of bytes pushed through a single tunnel in a 1 minute period */
private final float _peakTunnel1mThroughput[] = new float[THROUGHPUT_COUNT];
/** periodically cut the measured throughput values */
private static final int DEGRADES_PER_DAY = 4;
// one in this many times, ~= 61
private static final int DEGRADE_PROBABILITY = PeerManager.REORGANIZES_PER_DAY / DEGRADES_PER_DAY;
private static final double TOTAL_DEGRADE_PER_DAY = 0.5d;
// the goal is to cut an unchanged profile in half in 24 hours.
// x**4 = .5; x = 4th root of .5, x = .5**(1/4), x ~= 0.84
private static final float DEGRADE_FACTOR = (float) Math.pow(TOTAL_DEGRADE_PER_DAY, 1.0d / DEGRADES_PER_DAY);
//static { System.out.println("Degrade factor is " + DEGRADE_FACTOR); }
static final boolean ENABLE_TUNNEL_TEST_RESPONSE_TIME = false;
private long _lastCoalesceDate = System.currentTimeMillis();
/**
* Countries with more than about a 2% share of the netdb.
* Only routers in these countries will use a same-country metric.
* Yes this is an arbitrary cutoff.
*/
private static final Set<String> _bigCountries = new HashSet<String>();
static {
String[] big = new String[] { "fr", "de", "ru", "au", "us", "ca", "gb", "jp", "nl" };
_bigCountries.addAll(Arrays.asList(big));
}
/**
* Caller should call setLastHeardAbout() and setFirstHeardAbout()
*
* @param peer non-null
*/
public PeerProfile(RouterContext context, Hash peer) {
this(context, peer, true);
}
/**
* Caller should call setLastHeardAbout() and setFirstHeardAbout()
*
* @param peer non-null
* @param expand must be true (see below)
*/
private PeerProfile(RouterContext context, Hash peer, boolean expand) {
if (peer == null)
throw new NullPointerException();
_context = context;
_log = context.logManager().getLog(PeerProfile.class);
_peer = peer;
_firstHeardAbout = _context.clock().now();
// this is always true, and there are several places in the router that will NPE
// if it is false, so all need to be fixed before we can have non-expanded profiles
if (expand)
expandProfile();
Hash us = _context.routerHash();
if (us != null)
_distance = ((_peer.getData()[0] & 0xff) ^ (us.getData()[0] & 0xff)) - 127;
else
_distance = 0;
}
/** what peer is being profiled, non-null */
public Hash getPeer() { return _peer; }
/**
* are we keeping an expanded profile on the peer, or just the bare minimum.
* If we aren't keeping the expanded profile, all of the rates as well as the
* TunnelHistory and DBHistory will not be available.
*
*/
public boolean getIsExpanded() { return _expanded; }
public boolean getIsExpandedDB() { return _expandedDB; }
//public int incrementBanlists() { return _consecutiveBanlists++; }
//public void unbanlist() { _consecutiveBanlists = 0; }
/**
* Is this peer active at the moment (sending/receiving messages within the last
* 5 minutes)
*/
public boolean getIsActive() {
return getIsActive(5*60*1000, _context.clock().now());
}
/**
* Is this peer active at the moment (sending/receiving messages within the last
* 5 minutes)
*
* @since 0.9.58
*/
public boolean getIsActive(long now) {
return getIsActive(5*60*1000, now);
}
/** @since 0.8.11 */
boolean isEstablished() {
// null for tests
CommSystemFacade cs = _context.commSystem();
if (cs == null)
return false;
return cs.isEstablished(_peer);
}
/** @since 0.8.11 */
boolean wasUnreachable() {
// null for tests
CommSystemFacade cs = _context.commSystem();
if (cs == null)
return false;
return cs.wasUnreachable(_peer);
}
/** @since 0.8.11 */
boolean isSameCountry() {
// null for tests
CommSystemFacade cs = _context.commSystem();
if (cs == null)
return false;
String us = cs.getOurCountry();
return us != null &&
(_bigCountries.contains(us) ||
_context.getProperty(CapacityCalculator.PROP_COUNTRY_BONUS) != null) &&
us.equals(cs.getCountry(_peer));
}
/**
* For now, just a one-byte comparison
* @return -127 to +128, lower is closer
* @since 0.8.11
*/
int getXORDistance() {
return _distance;
}
/**
* Is this peer active at the moment (sending/receiving messages within the
* given period?)
* Also mark active if it is connected, as this will tend to encourage use
* of already-connected peers.
*
* Note: this appears to be the only use for these two RateStats.
*
* Update: Rewritten so we can get rid of the two RateStats.
* This also helps by not having it depend on coalesce boundaries.
*
* @param period must be one of the periods in the RateStat constructors below
* (5*60*1000 or 60*60*1000)
*
* @since 0.9.58
*/
public boolean getIsActive(long period, long now) {
long before = now - period;
return getLastHeardFrom() < before ||
getLastSendSuccessful() < before ||
isEstablished();
}
/**
* When did we first hear about this peer?
* @return greater than zero, set to now in constructor
*/
public synchronized long getFirstHeardAbout() { return _firstHeardAbout; }
/**
* Set when did we first heard about this peer, only if older.
* Package private, only set by profile management subsystem.
*/
synchronized void setFirstHeardAbout(long when) {
if (when < _firstHeardAbout)
_firstHeardAbout = when;
}
/**
* when did we last hear about this peer?
* @return 0 if unset
*/
public synchronized long getLastHeardAbout() { return _lastHeardAbout; }
/**
* Set when did we last hear about this peer, only if unset or newer
* Also sets FirstHeardAbout if earlier
*/
public synchronized void setLastHeardAbout(long when) {
if (when > _lastHeardAbout)
_lastHeardAbout = when;
// this is called by netdb PersistentDataStore, so fixup first heard
if (when < _firstHeardAbout)
_firstHeardAbout = when;
}
/** when did we last send to this peer successfully? */
public long getLastSendSuccessful() { return _lastSentToSuccessfully; }
public void setLastSendSuccessful(long when) { _lastSentToSuccessfully = when; }
/** when did we last have a problem sending to this peer? */
public long getLastSendFailed() { return _lastFailedSend; }
public void setLastSendFailed(long when) { _lastFailedSend = when; }
/** when did we last hear from the peer? */
public long getLastHeardFrom() { return _lastHeardFrom; }
public void setLastHeardFrom(long when) { _lastHeardFrom = when; }
/** history of tunnel activity with the peer
Warning - may return null if !getIsExpanded() */
public TunnelHistory getTunnelHistory() { return _tunnelHistory; }
public void setTunnelHistory(TunnelHistory history) { _tunnelHistory = history; }
/** history of db activity with the peer
Warning - may return null if !getIsExpandedDB() */
public DBHistory getDBHistory() { return _dbHistory; }
public void setDBHistory(DBHistory hist) { _dbHistory = hist; }
/** how large successfully sent messages are, calculated over a 1 minute, 1 hour, and 1 day period */
//public RateStat getSendSuccessSize() { return _sendSuccessSize; }
/** how large received messages are, calculated over a 1 minute, 1 hour, and 1 day period */
//public RateStat getReceiveSize() { return _receiveSize; }
/** how long it takes to get a db response from the peer (in milliseconds), calculated over a 1 minute, 1 hour, and 1 day period
Warning - may return null if !getIsExpandedDB() */
public RateStat getDbResponseTime() { return _dbResponseTime; }
/** how long it takes to get a tunnel create response from the peer (in milliseconds), calculated over a 1 minute, 1 hour, and 1 day period
Warning - may return null if !getIsExpanded() */
public RateStat getTunnelCreateResponseTime() { return _tunnelCreateResponseTime; }
/**
* How long it takes to successfully test a tunnel this peer participates in (in milliseconds),
* calculated over a 10 minute, 1 hour, and 1 day period
* Warning - may return null if !getIsExpanded()
*
* @deprecated unused
* @return null always
*/
@Deprecated
public RateStat getTunnelTestResponseTime() { return _tunnelTestResponseTime; }
/** how many new peers we get from dbSearchReplyMessages or dbStore messages, calculated over a 1 hour, 1 day, and 1 week period
Warning - may return null if !getIsExpandedDB() */
public RateStat getDbIntroduction() { return _dbIntroduction; }
/**
* extra factor added to the speed ranking - this can be updated in the profile
* written to disk to affect how the algorithm ranks speed. Negative values are
* penalties
*/
public int getSpeedBonus() { return _speedBonus; }
public void setSpeedBonus(int bonus) { _speedBonus = bonus; }
/**
* extra factor added to the capacity ranking - this can be updated in the profile
* written to disk to affect how the algorithm ranks capacity. Negative values are
* penalties
*/
public int getCapacityBonus() { return _capacityBonus; }
public void setCapacityBonus(int bonus) { _capacityBonus = bonus; }
/**
* extra factor added to the integration ranking - this can be updated in the profile
* written to disk to affect how the algorithm ranks integration. Negative values are
* penalties
*/
public int getIntegrationBonus() { return _integrationBonus; }
public void setIntegrationBonus(int bonus) { _integrationBonus = bonus; }
/**
* How fast is the peer, taking into consideration both throughput and latency.
* This may even be made to take into consideration current rates vs. estimated
* (or measured) max rates, allowing this speed to reflect the speed /available/.
*
*/
public float getSpeedValue() { return _speedValue; }
/**
* How many tunnels do we think this peer can handle over the next hour?
*
*/
public float getCapacityValue() { return _capacityValue; }
/**
* How well integrated into the network is this peer (as measured by how much they've
* told us that we didn't already know). Higher numbers means better integrated
*
*/
public float getIntegrationValue() { return _integrationValue; }
/**
* is this peer actively failing (aka not worth touching)?
* @deprecated - unused - always false
*/
@Deprecated
public boolean getIsFailing() { return false; }
/**
* @deprecated unused
* @return 0 always
*/
@Deprecated
public float getTunnelTestTimeAverage() { return _tunnelTestResponseTimeAvg; }
/**
* @deprecated unused
*/
@Deprecated
void setTunnelTestTimeAverage(float avg) { /* _tunnelTestResponseTimeAvg = avg; */ }
/**
* @deprecated unused
*/
@Deprecated
void updateTunnelTestTimeAverage(long ms) {
/*
if (_tunnelTestResponseTimeAvg <= 0)
_tunnelTestResponseTimeAvg = 30*1000; // should we instead start at $ms?
// weighted since we want to let the average grow quickly and shrink slowly
if (ms < _tunnelTestResponseTimeAvg)
_tunnelTestResponseTimeAvg = 0.95f * _tunnelTestResponseTimeAvg + .05f * ms;
else
_tunnelTestResponseTimeAvg = 0.75f * _tunnelTestResponseTimeAvg + .25f * ms;
if (_log.shouldLog(Log.INFO))
_log.info("Updating tunnel test time for " + _peer.toBase64().substring(0,6)
+ " to " + _tunnelTestResponseTimeAvg + " via " + ms);
*/
}
public float getPeakThroughputKBps() {
float rv = 0;
for (int i = 0; i < THROUGHPUT_COUNT; i++)
rv += _peakThroughput[i];
rv /= (60 * 1024 * THROUGHPUT_COUNT);
return rv;
}
/**
* Only for restoration from persisted profile.
*/
void setPeakThroughputKBps(float kBps) {
// Set all so the average remains the same
float speed = kBps * (60 * 1024);
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
_peakThroughput[i] = speed;
}
}
void dataPushed(int size) { _peakThroughputCurrentTotal += size; }
/** the tunnel pushed that much data in its lifetime */
void tunnelDataTransferred(long tunnelByteLifetime) {
float lowPeak = _peakTunnelThroughput[THROUGHPUT_COUNT-1];
if (tunnelByteLifetime > lowPeak) {
synchronized (_peakTunnelThroughput) {
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
if (tunnelByteLifetime > _peakTunnelThroughput[i]) {
for (int j = THROUGHPUT_COUNT-1; j > i; j--)
_peakTunnelThroughput[j] = _peakTunnelThroughput[j-1];
_peakTunnelThroughput[i] = tunnelByteLifetime;
break;
}
}
}
}
}
public float getPeakTunnelThroughputKBps() {
float rv = 0;
for (int i = 0; i < THROUGHPUT_COUNT; i++)
rv += _peakTunnelThroughput[i];
rv /= (10 * 60 * 1024 * THROUGHPUT_COUNT);
return rv;
}
/**
* Only for restoration from persisted profile.
*/
void setPeakTunnelThroughputKBps(float kBps) {
// Set all so the average remains the same
float speed = kBps * (60 * 10 * 1024);
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
_peakTunnelThroughput[i] = speed;
}
}
/** the tunnel pushed that much data in a 1 minute period */
void dataPushed1m(int size) {
float lowPeak = _peakTunnel1mThroughput[THROUGHPUT_COUNT-1];
if (size > lowPeak) {
synchronized (_peakTunnel1mThroughput) {
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
if (size > _peakTunnel1mThroughput[i]) {
for (int j = THROUGHPUT_COUNT-1; j > i; j--)
_peakTunnel1mThroughput[j] = _peakTunnel1mThroughput[j-1];
_peakTunnel1mThroughput[i] = size;
break;
}
}
}
if (_log.shouldLog(Log.DEBUG) ) {
StringBuilder buf = new StringBuilder(128);
buf.append("Updating 1m throughput after ").append(size).append(" to ");
for (int i = 0; i < THROUGHPUT_COUNT; i++)
buf.append(_peakTunnel1mThroughput[i]).append(',');
buf.append(" for ").append(_peer.toBase64());
_log.debug(buf.toString());
}
}
}
/**
* This is the speed value
*
* @return the average of the three fastest one-minute data transfers, on a per-tunnel basis,
* through this peer. Ever. Except that the peak values are cut in half
* periodically by coalesceThroughput().
*/
public float getPeakTunnel1mThroughputKBps() {
float rv = 0;
for (int i = 0; i < THROUGHPUT_COUNT; i++)
rv += _peakTunnel1mThroughput[i];
rv /= (60 * 1024 * THROUGHPUT_COUNT);
return rv;
}
/**
* Only for restoration from persisted profile.
*/
void setPeakTunnel1mThroughputKBps(float kBps) {
// Set all so the average remains the same
float speed = kBps * (60 * 1024);
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
_peakTunnel1mThroughput[i] = speed;
}
}
/**
* when the given peer is performing so poorly that we don't want to bother keeping
* extensive stats on them, call this to discard excess data points. Specifically,
* this drops the rates, the tunnelHistory, and the dbHistory.
*
* UNUSED for now, will cause NPEs elsewhere
*/
/*****
public void shrinkProfile() {
//_sendSuccessSize = null;
//_receiveSize = null;
_dbResponseTime = null;
_tunnelCreateResponseTime = null;
_tunnelTestResponseTime = null;
_dbIntroduction = null;
_tunnelHistory = null;
_dbHistory = null;
_expanded = false;
_expandedDB = false;
}
******/
/**
* When the given peer is performing well enough that we want to keep detailed
* stats on them again, call this to set up the info we dropped during shrinkProfile.
* This will not however overwrite any existing data, so it can be safely called
* repeatedly
*
*/
public synchronized void expandProfile() {
String group = (null == _peer ? "profileUnknown" : _peer.toBase64().substring(0,6));
if (_tunnelCreateResponseTime == null)
_tunnelCreateResponseTime = new RateStat("tunnelCreateResponseTime", "how long it takes to get a tunnel create response from the peer (ms)", group, TunnelHistory.RATES);
if (ENABLE_TUNNEL_TEST_RESPONSE_TIME && _tunnelTestResponseTime == null)
_tunnelTestResponseTime = new RateStat("tunnelTestResponseTime", "how long it takes to successfully test a tunnel this peer participates in (in milliseconds)", group, new long[] { 10*60*1000l, 30*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 } );
if (_tunnelHistory == null)
_tunnelHistory = new TunnelHistory(_context, group);
_expanded = true;
}
/**
* For floodfills
*/
public synchronized void expandDBProfile() {
String group = (null == _peer ? "profileUnknown" : _peer.toBase64().substring(0,6));
if (_dbResponseTime == null)
_dbResponseTime = new RateStat("dbResponseTime", "how long it takes to get a db response from the peer (in milliseconds)", group, new long[] { 10*60*1000l, 60*60*1000l, 24*60*60*1000 } );
if (_dbIntroduction == null)
_dbIntroduction = new RateStat("dbIntroduction", "how many new peers we get from dbSearchReplyMessages or dbStore messages", group, new long[] { 60*60*1000l, 6*60*60*1000l, 24*60*60*1000l });
if (_dbHistory == null)
_dbHistory = new DBHistory(_context, group);
_expandedDB = true;
}
private void coalesceThroughput(boolean decay) {
long now = System.currentTimeMillis();
long measuredPeriod = now - _lastCoalesceDate;
if (measuredPeriod >= 60*1000) {
// so we don't call random() twice
boolean shouldDecay = decay && _context.random().nextInt(DEGRADE_PROBABILITY) <= 0;
long tot = _peakThroughputCurrentTotal;
float lowPeak = _peakThroughput[THROUGHPUT_COUNT-1];
if (tot > lowPeak) {
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
if (tot > _peakThroughput[i]) {
for (int j = THROUGHPUT_COUNT-1; j > i; j--)
_peakThroughput[j] = _peakThroughput[j-1];
_peakThroughput[i] = tot;
break;
}
}
} else {
if (shouldDecay) {
for (int i = 0; i < THROUGHPUT_COUNT; i++)
_peakThroughput[i] *= DEGRADE_FACTOR;
}
}
// we degrade the tunnel throughput here too, regardless of the current
// activity
if (shouldDecay) {
for (int i = 0; i < THROUGHPUT_COUNT; i++) {
_peakTunnelThroughput[i] *= DEGRADE_FACTOR;
_peakTunnel1mThroughput[i] *= DEGRADE_FACTOR;
}
}
_peakThroughputCurrentTotal = 0;
_lastCoalesceDate = now;
}
}
/**
* Update the stats and rates. This is only called by addProfile()
*/
void coalesceStats() {
if (!_expanded) return;
coalesceOnly(false);
updateValues();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Coalesced: speed [" + _speedValue + "] capacity [" + _capacityValue + "] integration [" + _integrationValue + ']');
}
/**
* Caller must next call updateValues()
* @since 0.9.4
*/
void coalesceOnly(boolean shouldDecay) {
_coalescing = true;
//_receiveSize.coalesceStats();
//_sendSuccessSize.coalesceStats();
_tunnelCreateResponseTime.coalesceStats();
if (_tunnelTestResponseTime != null)
_tunnelTestResponseTime.coalesceStats();
_tunnelHistory.coalesceStats();
if (_expandedDB) {
_dbIntroduction.coalesceStats();
_dbResponseTime.coalesceStats();
_dbHistory.coalesceStats();
}
coalesceThroughput(shouldDecay);
_speedValueNew = calculateSpeed();
_capacityValueNew = calculateCapacity();
// These two are not used by InverseCapacityComparator
// to sort _strictCapacityOrder in ProfileOrganizer
// (in fact aren't really used at all), so we can
// update them directly
_integrationValue = calculateIntegration();
}
/**
* Copy over the new values generated by coalesceOnly()
* @since 0.9.4
*/
void updateValues() {
if (!_coalescing) // can happen
coalesceOnly(false);
_coalescing = false;
_speedValue = _speedValueNew;
_capacityValue = _capacityValueNew;
}
private float calculateSpeed() { return (float) SpeedCalculator.calc(this); }
private float calculateCapacity() { return (float) CapacityCalculator.calc(this); }
private float calculateIntegration() { return (float) IntegrationCalculator.calc(this); }
/**
* @deprecated - unused - always false
*/
@Deprecated
void setIsFailing(boolean val) {}
/**
* Helper for calculators
* @since 0.9.2
*/
RouterContext getContext() {
return _context;
}
@Override
public int hashCode() { return _peer.hashCode(); }
@Override
public boolean equals(Object obj) {
if (obj == null ||
!(obj instanceof PeerProfile))
return false;
PeerProfile prof = (PeerProfile)obj;
return _peer.equals(prof._peer);
}
@Override
public String toString() { return "Profile: " + _peer; }
/**
* New measurement is 12KB per expanded profile. (2009-03 zzz)
* And nowhere in the code is shrinkProfile() called so
* the size of compact profiles doesn't matter right now.
* This is far bigger than the NetDB entry, which is only about 1.5KB
* now that most of the stats have been removed.
*
* The biggest user in the profile is the Rates. (144 bytes per according to jhat).
* PeerProfile: 9 RateStats, 3-5 Rates each - 35 total
* DBHistory: 2 RateStats, 3 each - 6 total
* TunnelHistory: 4 RateStats, 5 each - 20 total
* --- ---------
* 15 61 total
* *60 bytes *144 bytes
* --- ---------
* 900 bytes 8784 bytes
*
* The RateStat itself is 32 bytes and the Rate[] is 28 so that adds
* about 1KB.
*
* So two obvious things to do are cut out some of the Rates,
* and call shrinkProfile().
*
* Obsolete calculation follows:
*
* Calculate the memory consumption of profiles. Measured to be ~3739 bytes
* for an expanded profile, and ~212 bytes for a compacted one.
*
*/
/****
public static void main(String args[]) {
RouterContext ctx = new RouterContext(new net.i2p.router.Router());
testProfileSize(ctx, 100, 0); // 560KB
testProfileSize(ctx, 1000, 0); // 3.9MB
testProfileSize(ctx, 10000, 0); // 37MB
testProfileSize(ctx, 0, 10000); // 2.2MB
testProfileSize(ctx, 0, 100000); // 21MB
testProfileSize(ctx, 0, 300000); // 63MB
}
****/
/**
* Read in all of the profiles specified and print out
* their calculated values. Usage: <pre>
* PeerProfile [filename]*
* </pre>
*/
/****
public static void main2(String args[]) {
RouterContext ctx = new RouterContext(new net.i2p.router.Router());
DecimalFormat fmt = new DecimalFormat("0,000.0");
fmt.setPositivePrefix("+");
ProfilePersistenceHelper helper = new ProfilePersistenceHelper(ctx);
try { Thread.sleep(5*1000); } catch (InterruptedException e) {}
StringBuilder buf = new StringBuilder(1024);
for (int i = 0; i < args.length; i++) {
PeerProfile profile = helper.readProfile(new File(args[i]));
if (profile == null) {
buf.append("Could not load profile ").append(args[i]).append('\n');
continue;
}
//profile.coalesceStats();
buf.append("Peer " + profile.getPeer().toBase64()
+ ":\t Speed:\t" + fmt.format(profile.calculateSpeed())
+ " Capacity:\t" + fmt.format(profile.calculateCapacity())
+ " Integration:\t" + fmt.format(profile.calculateIntegration())
+ " Active?\t" + profile.getIsActive()
+ " Failing?\t" + profile.calculateIsFailing()
+ '\n');
}
try { Thread.sleep(5*1000); } catch (InterruptedException e) {}
System.out.println(buf.toString());
}
private static void testProfileSize(RouterContext ctx, int numExpanded, int numCompact) {
Runtime.getRuntime().gc();
PeerProfile profs[] = new PeerProfile[numExpanded];
PeerProfile profsCompact[] = new PeerProfile[numCompact];
long used = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
long usedPer = used / (numExpanded+numCompact);
System.out.println(numExpanded + "/" + numCompact + ": create array - Used: " + used + " bytes (or " + usedPer + " bytes per array entry)");
int i = 0;
try {
for (; i < numExpanded; i++)
profs[i] = new PeerProfile(ctx, new Hash(new byte[Hash.HASH_LENGTH]));
} catch (OutOfMemoryError oom) {
profs = null;
profsCompact = null;
Runtime.getRuntime().gc();
System.out.println("Ran out of memory when creating profile " + i);
return;
}
try {
for (; i < numCompact; i++)
profsCompact[i] = new PeerProfile(ctx, new Hash(new byte[Hash.HASH_LENGTH]), false);
} catch (OutOfMemoryError oom) {
profs = null;
profsCompact = null;
Runtime.getRuntime().gc();
System.out.println("Ran out of memory when creating compacted profile " + i);
return;
}
Runtime.getRuntime().gc();
long usedObjects = Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory();
usedPer = usedObjects / (numExpanded+numCompact);
System.out.println(numExpanded + "/" + numCompact + ": create objects - Used: " + usedObjects + " bytes (or " + usedPer + " bytes per profile)");
profs = null;
profsCompact = null;
Runtime.getRuntime().gc();
}
****/
}
| i2p/i2p.i2p | router/java/src/net/i2p/router/peermanager/PeerProfile.java |
180,195 | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.Language;
import org.languagetool.LinguServices;
import org.languagetool.UserConfig;
/**
* An abstract rule checks the appearance of same words in a sentence or in two consecutive sentences.
* The isTokenToCheck method can be used to check only specific words (e.g. substantive, verbs and adjectives).
* This rule detects no grammar error but a stylistic problem (default off)
* @author Fred Kruse
* @since 4.1
*/
public abstract class AbstractStyleRepeatedWordRule extends TextLevelRule {
private static final Pattern OPENING_QUOTES = Pattern.compile("[\"“„»«]");
private static final Pattern ENDING_QUOTES = Pattern.compile("[\"“”»«]");
private static final int MAX_TOKEN_TO_CHECK = 5;
protected final LinguServices linguServices;
protected final Language lang;
protected int maxDistanceOfSentences = 1;
public AbstractStyleRepeatedWordRule(ResourceBundle messages, Language lang, UserConfig userConfig) {
super(messages);
super.setCategory(Categories.STYLE.getCategory(messages));
setLocQualityIssueType(ITSIssueType.Style);
setDefaultOff();
this.lang = lang;
if (userConfig != null) {
linguServices = userConfig.getLinguServices();
if (linguServices != null) {
linguServices.setThesaurusRelevantRule(this);
}
Object[] cf = userConfig.getConfigValueByID(getId());
if (cf != null) {
this.maxDistanceOfSentences = (int) cf[0];
}
} else {
linguServices = null;
}
}
/**
* Override this ID by adding a language acronym (e.g. STYLE_REPEATED_WORD_RULE_DE)
* to use adjustment of maxWords by option panel
* @since 4.1
*/
@Override
public String getId() {
return "STYLE_REPEATED_WORD_RULE";
}
@Override
public String getDescription() {
return "Repeated words in consecutive sentences";
}
/*
* Message for repeated word in same sentence
*/
protected abstract String messageSameSentence();
/*
* Message for repeated word in sentence before
*/
protected abstract String messageSentenceBefore();
/*
* Message for repeated word in sentence after
*/
protected abstract String messageSentenceAfter();
/**
* give the user the possibility to configure the function
*/
@Override
public RuleOption[] getRuleOptions() {
RuleOption[] ruleOptions = { new RuleOption(maxDistanceOfSentences, messages.getString("guiStyleRepeatedWordText"), 0, 5) };
return ruleOptions;
}
/*
* Check only special words (e.g substantive, verbs, adjectives)
* (German example: return (token.matchesPosTagRegex("(SUB|EIG|VER|ADJ):.*")
* && !token.matchesPosTagRegex("ART:.*|ADV:.*|VER:(AUX|MOD):.*"));
*/
protected abstract boolean isTokenToCheck(AnalyzedTokenReadings token);
/*
* Is checked word part of pairs like "arm in arm", "side by side", etc. (exclude such pairs)
*/
protected abstract boolean isTokenPair(AnalyzedTokenReadings[] tokens, int n, boolean before);
/*
* listings are excluded
*/
private static boolean hasBreakToken(AnalyzedTokenReadings[] tokens) {
for (int i = 0; i < tokens.length && i < MAX_TOKEN_TO_CHECK; i++) {
if (tokens[i].getToken().equals("-") || tokens[i].getToken().equals("—") || tokens[i].getToken().equals("–")) {
return true;
}
}
return false;
}
/*
* question - response - pairs are excluded
*/
private static boolean isQuestionResponse(int nAct, int nTest, List<AnalyzedTokenReadings[]> tokenList) {
int dist = nAct - nTest;
if (dist != 1 && dist != -1) {
return false;
}
AnalyzedTokenReadings[] actTokens = tokenList.get(nAct);
AnalyzedTokenReadings[] testTokens = tokenList.get(nTest);
if (actTokens.length < 2 || testTokens.length < 2) {
return false;
}
String actToken;
if (ENDING_QUOTES.matcher(actTokens[actTokens.length - 1].getToken()).matches()) {
actToken = actTokens[actTokens.length - 2].getToken();
} else {
actToken = actTokens[actTokens.length - 1].getToken();
}
String testToken;
if (ENDING_QUOTES.matcher(testTokens[testTokens.length - 1].getToken()).matches()) {
testToken = testTokens[testTokens.length - 2].getToken();
} else {
testToken = testTokens[testTokens.length - 1].getToken();
}
return ((actToken.equals("?") && !testToken.equals("?")) || (testToken.equals("?") && !actToken.equals("?")));
}
private boolean isTokenInSentence(AnalyzedTokenReadings testToken, AnalyzedTokenReadings[] tokens) {
return isTokenInSentence(testToken, tokens, -1);
}
/*
* true if token is part of composite word in sentence
* override for languages like German which contents composed words
*/
protected boolean isPartOfWord(String testTokenText, String tokenText) {
return false;
}
/*
* true if is an exception of token pair
* note: method is called after two tokens are tested to share the same lemma
*/
protected boolean isExceptionPair(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2) {
return false;
}
/*
* Set a URL to a synonym dictionary for a token
*/
protected URL setURL(AnalyzedTokenReadings token ) throws MalformedURLException {
return null;
}
/*
* true if token is found in sentence
*/
private boolean isTokenInSentence(AnalyzedTokenReadings testToken, AnalyzedTokenReadings[] tokens, int notCheck) {
if (testToken == null || tokens == null) {
return false;
}
List<AnalyzedToken> readings = testToken.getReadings();
List<String> lemmas = new ArrayList<>();
for (AnalyzedToken reading : readings) {
if (reading.getLemma() != null) {
lemmas.add(reading.getLemma());
}
}
for (int i = 0; i < tokens.length; i++) {
if (i != notCheck && isTokenToCheck(tokens[i])) {
if ((!lemmas.isEmpty() && tokens[i].hasAnyLemma(lemmas.toArray(new String[0])) && !isExceptionPair(testToken, tokens[i]))
|| isPartOfWord(testToken.getToken(), tokens[i].getToken())) {
if (notCheck >= 0) {
if (notCheck == i - 2) {
return !isTokenPair(tokens, i, true);
} else if (notCheck == i + 2) {
return !isTokenPair(tokens, i, false);
} else if ((notCheck == i + 1 || notCheck == i - 1)
&& testToken.getToken().equals(tokens[i].getToken())) {
return false;
}
}
return true;
}
}
}
return false;
}
@Override
public RuleMatch[] match(List<AnalyzedSentence> sentences) throws IOException {
List<RuleMatch> ruleMatches = new ArrayList<>();
List<AnalyzedTokenReadings[]> tokenList = new ArrayList<>();
int pos = 0;
for (int n = 0; n < maxDistanceOfSentences && n < sentences.size(); n++) {
tokenList.add(sentences.get(n).getTokensWithoutWhitespace());
}
for (int n = 0; n < sentences.size(); n++) {
if (n + maxDistanceOfSentences < sentences.size()) {
tokenList.add(sentences.get(n + maxDistanceOfSentences).getTokensWithoutWhitespace());
}
if (tokenList.size() > 2 * maxDistanceOfSentences + 1) {
tokenList.remove(0);
}
int nTok = maxDistanceOfSentences;
if (n < maxDistanceOfSentences) {
nTok = n;
} else if (n >= sentences.size() - maxDistanceOfSentences) {
nTok = tokenList.size() - (sentences.size() - n);
}
if (!hasBreakToken(tokenList.get(nTok))) {
for (int i = 0; i < tokenList.get(nTok).length; i++) {
AnalyzedTokenReadings token = tokenList.get(nTok)[i];
boolean isInQuotes = i > 0 && OPENING_QUOTES.matcher(tokenList.get(nTok)[i - 1].getToken()).matches()
&& i < tokenList.get(nTok).length - 1 && ENDING_QUOTES.matcher(tokenList.get(nTok)[i + 1].getToken()).matches();
if (!isInQuotes && isTokenToCheck(token)) {
int isRepeated = 0;
if (isTokenInSentence(token, tokenList.get(nTok), i)) {
isRepeated = 1;
}
for(int j = nTok - 1; isRepeated == 0 && j >= 0 && j >= nTok - maxDistanceOfSentences; j--) {
if (!isQuestionResponse(nTok, j, tokenList) && isTokenInSentence(token, tokenList.get(j))) {
isRepeated = 2;
}
}
for(int j = nTok + 1; isRepeated == 0 && j < tokenList.size() && j <= nTok + maxDistanceOfSentences; j++) {
if (!isQuestionResponse(nTok, j, tokenList) && isTokenInSentence(token, tokenList.get(j))) {
isRepeated = 3;
}
}
if (isRepeated != 0) {
String msg;
if (isRepeated == 1) {
msg = messageSameSentence();
} else if (isRepeated == 2) {
msg = messageSentenceBefore();
} else {
msg = messageSentenceAfter();
}
int startPos = pos + token.getStartPos();
int endPos = pos + token.getEndPos();
RuleMatch ruleMatch = new RuleMatch(this, null, startPos, endPos, msg);
URL url = setURL(token);
if(url != null) {
ruleMatch.setUrl(url);
}
ruleMatches.add(ruleMatch);
}
}
}
}
pos += sentences.get(n).getCorrectedTextLength();
}
return toRuleMatchArray(ruleMatches);
}
@Override
public int minToCheckParagraph() {
return maxDistanceOfSentences;
}
}
| languagetool-org/languagetool | languagetool-core/src/main/java/org/languagetool/rules/AbstractStyleRepeatedWordRule.java |
180,196 | /*
* Copyright (c) 2008-2024, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.internal.diagnostics;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.instance.impl.NodeState;
import com.hazelcast.instance.impl.OutOfMemoryErrorDispatcher;
import com.hazelcast.internal.memory.MemoryStats;
import com.hazelcast.internal.metrics.DoubleGauge;
import com.hazelcast.internal.metrics.LongGauge;
import com.hazelcast.internal.metrics.MetricsRegistry;
import com.hazelcast.logging.ILogger;
import com.hazelcast.spi.properties.ClusterProperty;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.OFF;
import static com.hazelcast.internal.diagnostics.HealthMonitorLevel.valueOf;
import static com.hazelcast.internal.util.ThreadUtil.createThreadName;
import static com.hazelcast.spi.properties.ClusterProperty.HEALTH_MONITORING_DELAY_SECONDS;
import static com.hazelcast.spi.properties.ClusterProperty.HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE;
import static com.hazelcast.spi.properties.ClusterProperty.HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Health monitor periodically prints logs about related internal metrics using the {@link MetricsRegistry}
* to provide some clues about the internal Hazelcast state.
* <p>
* Health monitor can be configured with system properties.
* <ul>
* <li>{@link ClusterProperty#HEALTH_MONITORING_LEVEL} This property can be one of the following:
* <ul>
* <li>{@link HealthMonitorLevel#NOISY} => does not check threshold, always prints</li>
* <li>{@link HealthMonitorLevel#SILENT} => prints only if metrics are above threshold (default)</li>
* <li>{@link HealthMonitorLevel#OFF} => does not print anything</li>
* </ul>
* </li>
* <li>{@link ClusterProperty#HEALTH_MONITORING_DELAY_SECONDS}
* Time between printing two logs of health monitor. Default values is 30 seconds.</li>
* <li>{@link ClusterProperty#HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE}
* Threshold: Percentage of max memory currently in use</li>
* <li>{@link ClusterProperty#HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE}
* Threshold: CPU system/process load</li>
* </ul>
*/
public class HealthMonitor {
private static final String[] UNITS = new String[]{"", "K", "M", "G", "T", "P", "E"};
private static final double PERCENTAGE_MULTIPLIER = 100d;
private static final double THRESHOLD_PERCENTAGE_INVOCATIONS = 70;
private static final double THRESHOLD_INVOCATIONS = 1000;
final HealthMetrics healthMetrics;
private final ILogger logger;
private final Node node;
private final HealthMonitorLevel monitorLevel;
private final int thresholdMemoryPercentage;
private final int thresholdCPUPercentage;
private final MetricsRegistry metricRegistry;
private final HealthMonitorThread monitorThread;
public HealthMonitor(Node node) {
this.node = node;
this.logger = node.getLogger(HealthMonitor.class);
this.metricRegistry = node.nodeEngine.getMetricsRegistry();
this.monitorLevel = getHealthMonitorLevel();
this.thresholdMemoryPercentage = node.getProperties().getInteger(HEALTH_MONITORING_THRESHOLD_MEMORY_PERCENTAGE);
this.thresholdCPUPercentage = node.getProperties().getInteger(HEALTH_MONITORING_THRESHOLD_CPU_PERCENTAGE);
this.monitorThread = initMonitorThread();
this.healthMetrics = new HealthMetrics();
}
private HealthMonitorThread initMonitorThread() {
if (monitorLevel == OFF) {
return null;
}
int delaySeconds = node.getProperties().getSeconds(HEALTH_MONITORING_DELAY_SECONDS);
return new HealthMonitorThread(delaySeconds);
}
public HealthMonitor start() {
if (monitorLevel == OFF) {
logger.finest("HealthMonitor is disabled");
return this;
}
monitorThread.start();
logger.finest("HealthMonitor started");
return this;
}
public void stop() {
if (monitorLevel == OFF) {
return;
}
monitorThread.interrupt();
try {
monitorThread.join();
} catch (InterruptedException e) {
currentThread().interrupt();
}
logger.finest("HealthMonitor stopped");
}
private HealthMonitorLevel getHealthMonitorLevel() {
String healthMonitorLevel = node.getProperties().getString(ClusterProperty.HEALTH_MONITORING_LEVEL);
return valueOf(healthMonitorLevel);
}
private final class HealthMonitorThread extends Thread {
private final int delaySeconds;
private boolean showPerformanceLogHint;
private HealthMonitorThread(int delaySeconds) {
super(createThreadName(node.hazelcastInstance.getName(), "HealthMonitor"));
setDaemon(true);
this.delaySeconds = delaySeconds;
// Show the hint if diagnostics are disabled; if already enabled, don't show it
this.showPerformanceLogHint = !node.getProperties().getBoolean(Diagnostics.ENABLED);
}
@Override
public void run() {
try {
while (node.getState() == NodeState.ACTIVE) {
healthMetrics.update();
switch (monitorLevel) {
case NOISY:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
}
logger.info(healthMetrics.render());
break;
case SILENT:
if (healthMetrics.exceedsThreshold()) {
logDiagnosticsHint();
logger.info(healthMetrics.render());
}
break;
default:
throw new IllegalStateException("Unrecognized HealthMonitorLevel: " + monitorLevel);
}
try {
SECONDS.sleep(delaySeconds);
} catch (InterruptedException e) {
currentThread().interrupt();
return;
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (Throwable t) {
logger.warning("Health Monitor failed", t);
}
}
private void logDiagnosticsHint() {
if (!showPerformanceLogHint) {
return;
}
// we only log the hint once
showPerformanceLogHint = false;
logger.info(format("The HealthMonitor has detected a high load on the system. For more detailed information,%n"
+ "enable Diagnostics by adding the property -D%s=true", Diagnostics.ENABLED));
}
}
class HealthMetrics {
final LongGauge clientEndpointCount
= metricRegistry.newLongGauge("client.endpoint.count");
final LongGauge clusterTimeDiff
= metricRegistry.newLongGauge("cluster.clock.clusterTimeDiff");
final LongGauge executorAsyncQueueSize
= metricRegistry.newLongGauge("executor.hz:async.queueSize");
final LongGauge executorClientQueueSize
= metricRegistry.newLongGauge("executor.hz:client.queueSize");
final LongGauge executorQueryClientQueueSize
= metricRegistry.newLongGauge("executor.hz:client.query.queueSize");
final LongGauge executorBlockingClientQueueSize
= metricRegistry.newLongGauge("executor.hz:client.blocking.queueSize");
final LongGauge executorClusterQueueSize
= metricRegistry.newLongGauge("executor.hz:cluster.queueSize");
final LongGauge executorScheduledQueueSize
= metricRegistry.newLongGauge("executor.hz:scheduled.queueSize");
final LongGauge executorSystemQueueSize
= metricRegistry.newLongGauge("executor.hz:system.queueSize");
final LongGauge executorIoQueueSize
= metricRegistry.newLongGauge("executor.hz:io.queueSize");
final LongGauge executorQueryQueueSize
= metricRegistry.newLongGauge("executor.hz:query.queueSize");
final LongGauge executorMapLoadQueueSize
= metricRegistry.newLongGauge("executor.hz:map-load.queueSize");
final LongGauge executorMapLoadAllKeysQueueSize
= metricRegistry.newLongGauge("executor.hz:map-loadAllKeys.queueSize");
final LongGauge eventQueueSize
= metricRegistry.newLongGauge("event.eventQueueSize");
final LongGauge gcMinorCount
= metricRegistry.newLongGauge("gc.minorCount");
final LongGauge gcMinorTime
= metricRegistry.newLongGauge("gc.minorTime");
final LongGauge gcMajorCount
= metricRegistry.newLongGauge("gc.majorCount");
final LongGauge gcMajorTime
= metricRegistry.newLongGauge("gc.majorTime");
final LongGauge gcUnknownCount
= metricRegistry.newLongGauge("gc.unknownCount");
final LongGauge gcUnknownTime
= metricRegistry.newLongGauge("gc.unknownTime");
final LongGauge runtimeAvailableProcessors
= metricRegistry.newLongGauge("runtime.availableProcessors");
final LongGauge runtimeMaxMemory
= metricRegistry.newLongGauge("runtime.maxMemory");
final LongGauge runtimeFreeMemory
= metricRegistry.newLongGauge("runtime.freeMemory");
final LongGauge runtimeTotalMemory
= metricRegistry.newLongGauge("runtime.totalMemory");
final LongGauge runtimeUsedMemory
= metricRegistry.newLongGauge("runtime.usedMemory");
final LongGauge threadPeakThreadCount
= metricRegistry.newLongGauge("thread.peakThreadCount");
final LongGauge threadThreadCount
= metricRegistry.newLongGauge("thread.threadCount");
final DoubleGauge osProcessCpuLoad
= metricRegistry.newDoubleGauge("os.processCpuLoad");
final DoubleGauge osSystemLoadAverage
= metricRegistry.newDoubleGauge("os.systemLoadAverage");
final DoubleGauge osSystemCpuLoad
= metricRegistry.newDoubleGauge("os.systemCpuLoad");
final LongGauge osTotalPhysicalMemorySize
= metricRegistry.newLongGauge("os.totalPhysicalMemorySize");
final LongGauge osFreePhysicalMemorySize
= metricRegistry.newLongGauge("os.freePhysicalMemorySize");
final LongGauge osTotalSwapSpaceSize
= metricRegistry.newLongGauge("os.totalSwapSpaceSize");
final LongGauge osFreeSwapSpaceSize
= metricRegistry.newLongGauge("os.freeSwapSpaceSize");
final LongGauge operationServiceExecutorQueueSize
= metricRegistry.newLongGauge("operation.queueSize");
final LongGauge operationServiceExecutorPriorityQueueSize
= metricRegistry.newLongGauge("operation.priorityQueueSize");
final LongGauge operationServiceResponseQueueSize
= metricRegistry.newLongGauge("operation.responseQueueSize");
final LongGauge operationServiceRunningOperationsCount
= metricRegistry.newLongGauge("operation.runningCount");
final LongGauge operationServiceCompletedOperationsCount
= metricRegistry.newLongGauge("operation.completedCount");
final LongGauge operationServicePendingInvocationsCount
= metricRegistry.newLongGauge("operation.invocations.pending");
final DoubleGauge operationServicePendingInvocationsPercentage
= metricRegistry.newDoubleGauge("operation.invocations.usedPercentage");
final LongGauge proxyCount
= metricRegistry.newLongGauge("proxy.proxyCount");
final LongGauge tcpConnectionActiveCount
= metricRegistry.newLongGauge("tcp.connection.activeCount");
final LongGauge tcpConnectionCount
= metricRegistry.newLongGauge("tcp.connection.count");
final LongGauge tcpConnectionClientCount
= metricRegistry.newLongGauge("tcp.connection.clientCount");
private final StringBuilder sb = new StringBuilder();
private double memoryUsedOfTotalPercentage;
private double memoryUsedOfMaxPercentage;
private long runtimeUsedMemory0;
private long runtimeTotalMemory0;
private long runtimeMaxMemory0;
private double osProcessCpuLoad0;
private double osSystemCpuLoad0;
private double operationServicePendingInvocationsPercentage0;
private long operationServicePendingInvocationsCount0;
public void update() {
runtimeUsedMemory0 = runtimeUsedMemory.read();
runtimeTotalMemory0 = runtimeTotalMemory.read();
runtimeMaxMemory0 = runtimeMaxMemory.read();
osProcessCpuLoad0 = osProcessCpuLoad.read();
osSystemCpuLoad0 = osSystemCpuLoad.read();
operationServicePendingInvocationsPercentage0 = operationServicePendingInvocationsPercentage.read();
operationServicePendingInvocationsCount0 = operationServicePendingInvocationsCount.read();
memoryUsedOfTotalPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory0) / runtimeTotalMemory0;
memoryUsedOfMaxPercentage = (PERCENTAGE_MULTIPLIER * runtimeUsedMemory0) / runtimeMaxMemory0;
}
boolean exceedsThreshold() {
if (memoryUsedOfMaxPercentage > thresholdMemoryPercentage) {
return true;
}
if (osProcessCpuLoad0 > thresholdCPUPercentage) {
return true;
}
if (osSystemCpuLoad0 > thresholdCPUPercentage) {
return true;
}
if (operationServicePendingInvocationsPercentage0 > THRESHOLD_PERCENTAGE_INVOCATIONS) {
return true;
}
if (operationServicePendingInvocationsCount0 > THRESHOLD_INVOCATIONS) {
return true;
}
return false;
}
public String render() {
sb.setLength(0);
renderProcessors();
renderPhysicalMemory();
renderSwap();
renderHeap();
renderNativeMemory();
renderGc();
renderLoad();
renderThread();
renderCluster();
renderEvents();
renderExecutors();
renderOperationService();
renderProxy();
renderClient();
renderConnection();
return sb.toString();
}
private void renderConnection() {
sb.append("connection.active.count=")
.append(tcpConnectionActiveCount.read()).append(", ");
sb.append("client.connection.count=")
.append(tcpConnectionClientCount.read()).append(", ");
sb.append("connection.count=")
.append(tcpConnectionCount.read());
}
private void renderClient() {
sb.append("clientEndpoint.count=")
.append(clientEndpointCount.read()).append(", ");
}
private void renderProxy() {
sb.append("proxy.count=")
.append(proxyCount.read()).append(", ");
}
private void renderLoad() {
sb.append("load.process").append('=')
.append(format("%.2f", osProcessCpuLoad0)).append("%, ");
sb.append("load.system").append('=')
.append(format("%.2f", osSystemCpuLoad0)).append("%, ");
double value = osSystemLoadAverage.read();
if (value < 0) {
sb.append("load.systemAverage").append("=n/a ");
} else {
sb.append("load.systemAverage").append('=')
.append(format("%.2f", value)).append(", ");
}
}
private void renderProcessors() {
sb.append("processors=")
.append(runtimeAvailableProcessors.read()).append(", ");
}
private void renderPhysicalMemory() {
sb.append("physical.memory.total=")
.append(numberToUnit(osTotalPhysicalMemorySize.read())).append(", ");
sb.append("physical.memory.free=")
.append(numberToUnit(osFreePhysicalMemorySize.read())).append(", ");
}
private void renderSwap() {
sb.append("swap.space.total=")
.append(numberToUnit(osTotalSwapSpaceSize.read())).append(", ");
sb.append("swap.space.free=")
.append(numberToUnit(osFreeSwapSpaceSize.read())).append(", ");
}
private void renderHeap() {
sb.append("heap.memory.used=")
.append(numberToUnit(runtimeUsedMemory0)).append(", ");
sb.append("heap.memory.free=")
.append(numberToUnit(runtimeFreeMemory.read())).append(", ");
sb.append("heap.memory.total=")
.append(numberToUnit(runtimeTotalMemory0)).append(", ");
sb.append("heap.memory.max=")
.append(numberToUnit(runtimeMaxMemory0)).append(", ");
sb.append("heap.memory.used/total=")
.append(percentageString(memoryUsedOfTotalPercentage)).append(", ");
sb.append("heap.memory.used/max=")
.append(percentageString(memoryUsedOfMaxPercentage)).append((", "));
}
private void renderEvents() {
sb.append("event.q.size=")
.append(eventQueueSize.read()).append(", ");
}
private void renderCluster() {
sb.append("cluster.timeDiff=")
.append(clusterTimeDiff.read()).append(", ");
}
private void renderThread() {
sb.append("thread.count=")
.append(threadThreadCount.read()).append(", ");
sb.append("thread.peakCount=")
.append(threadPeakThreadCount.read()).append(", ");
}
private void renderGc() {
sb.append("minor.gc.count=")
.append(gcMinorCount.read()).append(", ");
sb.append("minor.gc.time=")
.append(gcMinorTime.read()).append("ms, ");
sb.append("major.gc.count=")
.append(gcMajorCount.read()).append(", ");
sb.append("major.gc.time=")
.append(gcMajorTime.read()).append("ms, ");
if (gcUnknownCount.read() > 0) {
sb.append("unknown.gc.count=")
.append(gcUnknownCount.read()).append(", ");
sb.append("unknown.gc.time=")
.append(gcUnknownTime.read()).append("ms, ");
}
}
private void renderNativeMemory() {
MemoryStats memoryStats = node.getNodeExtension().getMemoryStats();
if (memoryStats.getMaxNative() <= 0L) {
return;
}
final long maxNative = memoryStats.getMaxNative();
final long usedNative = memoryStats.getUsedNative();
final long usedMeta = memoryStats.getUsedMetadata();
sb.append("native.memory.used=")
.append(numberToUnit(usedNative)).append(", ");
sb.append("native.memory.free=")
.append(numberToUnit(memoryStats.getFreeNative())).append(", ");
sb.append("native.memory.total=")
.append(numberToUnit(memoryStats.getCommittedNative())).append(", ");
sb.append("native.memory.max=")
.append(numberToUnit(maxNative)).append(", ");
sb.append("native.meta.memory.used=")
.append(numberToUnit(usedMeta)).append(", ");
sb.append("native.meta.memory.free=")
.append(numberToUnit(maxNative - usedMeta)).append(", ");
sb.append("native.meta.memory.percentage=")
.append(percentageString(PERCENTAGE_MULTIPLIER * usedMeta / maxNative)).append(", ");
}
private void renderExecutors() {
sb.append("executor.q.async.size=")
.append(executorAsyncQueueSize.read()).append(", ");
sb.append("executor.q.client.size=")
.append(executorClientQueueSize.read()).append(", ");
sb.append("executor.q.client.query.size=")
.append(executorQueryClientQueueSize.read()).append(", ");
sb.append("executor.q.client.blocking.size=")
.append(executorBlockingClientQueueSize.read()).append(", ");
sb.append("executor.q.query.size=")
.append(executorQueryQueueSize.read()).append(", ");
sb.append("executor.q.scheduled.size=")
.append(executorScheduledQueueSize.read()).append(", ");
sb.append("executor.q.io.size=")
.append(executorIoQueueSize.read()).append(", ");
sb.append("executor.q.system.size=")
.append(executorSystemQueueSize.read()).append(", ");
sb.append("executor.q.operations.size=")
.append(operationServiceExecutorQueueSize.read()).append(", ");
sb.append("executor.q.priorityOperation.size=").
append(operationServiceExecutorPriorityQueueSize.read()).append(", ");
sb.append("operations.completed.count=")
.append(operationServiceCompletedOperationsCount.read()).append(", ");
sb.append("executor.q.mapLoad.size=")
.append(executorMapLoadQueueSize.read()).append(", ");
sb.append("executor.q.mapLoadAllKeys.size=")
.append(executorMapLoadAllKeysQueueSize.read()).append(", ");
sb.append("executor.q.cluster.size=")
.append(executorClusterQueueSize.read()).append(", ");
}
private void renderOperationService() {
sb.append("executor.q.response.size=")
.append(operationServiceResponseQueueSize.read()).append(", ");
sb.append("operations.running.count=")
.append(operationServiceRunningOperationsCount.read()).append(", ");
sb.append("operations.pending.invocations.percentage=")
.append(format("%.2f", operationServicePendingInvocationsPercentage0)).append("%, ");
sb.append("operations.pending.invocations.count=")
.append(operationServicePendingInvocationsCount0).append(", ");
}
}
/**
* Given a number, returns that number as a percentage string.
*
* @param p the given number
* @return a string of the given number as a format float with two decimal places and a period
*/
private static String percentageString(double p) {
return format("%.2f%%", p);
}
@SuppressWarnings("checkstyle:magicnumber")
private static String numberToUnit(long number) {
for (int i = 6; i > 0; i--) {
// 1024 is for 1024 kb is 1 MB etc
double step = Math.pow(1024, i);
if (number > step) {
return format("%3.1f%s", number / step, UNITS[i]);
}
}
return Long.toString(number);
}
}
| hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/diagnostics/HealthMonitor.java |
180,198 | /*
* 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") {
return null;
} 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 java.lang.management;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Stub implementation of ManagementFactory. */
public class ManagementFactory {
public static RuntimeMXBean getRuntimeMXBean() {
return new StubRuntimeMXBean();
}
public static ThreadMXBean getThreadMXBean() {
return new StubThreadMXBean();
}
private static class StubRuntimeMXBean implements RuntimeMXBean {
@Override
public String getBootClassPath() {
return null;
}
@Override
public String getClassPath() {
return null;
}
@Override
public List<String> getInputArguments() {
return Collections.EMPTY_LIST;
}
@Override
public String getLibraryPath() {
return null;
}
@Override
public String getManagementSpecVersion() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getSpecName() {
return null;
}
@Override
public String getSpecVendor() {
return null;
}
@Override
public String getSpecVersion() {
return null;
}
@Override
public long getStartTime() {
return 0;
}
@Override
public Map<String, String> getSystemProperties() {
return Collections.EMPTY_MAP;
}
@Override
public long getUptime() {
return 0;
}
@Override
public String getVmName() {
return null;
}
@Override
public String getVmVendor() {
return null;
}
@Override
public String getVmVersion() {
return null;
}
@Override
public boolean isBootClassPathSupported() {
return false;
}
}
private static class StubThreadMXBean implements ThreadMXBean {
@Override
public long[] findMonitorDeadlockedThreads() {
return new long[0];
}
@Override
public long[] getAllThreadIds() {
return new long[0];
}
@Override
public long getCurrentThreadCpuTime() {
return 0;
}
@Override
public long getCurrentThreadUserTime() {
return 0;
}
@Override
public int getDaemonThreadCount() {
return 0;
}
@Override
public int getPeakThreadCount() {
return 0;
}
@Override
public int getThreadCount() {
return 0;
}
@Override
public long getThreadCpuTime(long l) {
return 0;
}
@Override
public ThreadInfo getThreadInfo(long l) {
return null;
}
@Override
public ThreadInfo getThreadInfo(long l, int i) {
return null;
}
@Override
public ThreadInfo[] getThreadInfo(long[] l) {
return new ThreadInfo[0];
}
@Override
public ThreadInfo[] getThreadInfo(long[] l, int i) {
return new ThreadInfo[0];
}
@Override
public long getThreadUserTime(long l) {
return 0;
}
@Override
public long getTotalStartedThreadCount() {
return 0;
}
@Override
public boolean isCurrentThreadCpuTimeSupported() {
return false;
}
@Override
public boolean isThreadContentionMonitoringEnabled() {
return false;
}
@Override
public boolean isThreadContentionMonitoringSupported() {
return false;
}
@Override
public boolean isThreadCpuTimeEnabled() {
return false;
}
@Override
public boolean isThreadCpuTimeSupported() {
return false;
}
@Override
public void resetPeakThreadCount() {
}
@Override
public void setThreadContentionMonitoringEnabled(boolean b) {
}
@Override
public void setThreadCpuTimeEnabled(boolean b) {
}
}
}
| google/j2objc | jre_emul/Classes/java/lang/management/ManagementFactory.java |
180,199 | /*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.management;
import java.util.Map;
/**
* The management interface for the thread system of
* the Java virtual machine.
*
* <p> A Java virtual machine has a single instance of the implementation
* class of this interface. This instance implementing this interface is
* an <a href="ManagementFactory.html#MXBean">MXBean</a>
* that can be obtained by calling
* the {@link ManagementFactory#getThreadMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method.
*
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the thread system within an MBeanServer is:
* <blockquote>
* {@link ManagementFactory#THREAD_MXBEAN_NAME
* <tt>java.lang:type=Threading</tt>}
* </blockquote>
*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h3>Thread ID</h3>
* Thread ID is a positive long value returned by calling the
* {@link java.lang.Thread#getId} method for a thread.
* The thread ID is unique during its lifetime. When a thread
* is terminated, this thread ID may be reused.
*
* <p> Some methods in this interface take a thread ID or an array
* of thread IDs as the input parameter and return per-thread information.
*
* <h3>Thread CPU time</h3>
* A Java virtual machine implementation may support measuring
* the CPU time for the current thread, for any thread, or for no threads.
*
* <p>
* The {@link #isThreadCpuTimeSupported} method can be used to determine
* if a Java virtual machine supports measuring of the CPU time for any
* thread. The {@link #isCurrentThreadCpuTimeSupported} method can
* be used to determine if a Java virtual machine supports measuring of
* the CPU time for the current thread.
* A Java virtual machine implementation that supports CPU time measurement
* for any thread will also support that for the current thread.
*
* <p> The CPU time provided by this interface has nanosecond precision
* but not necessarily nanosecond accuracy.
*
* <p>
* A Java virtual machine may disable CPU time measurement
* by default.
* The {@link #isThreadCpuTimeEnabled} and {@link #setThreadCpuTimeEnabled}
* methods can be used to test if CPU time measurement is enabled
* and to enable/disable this support respectively.
* Enabling thread CPU measurement could be expensive in some
* Java virtual machine implementations.
*
* <h3>Thread Contention Monitoring</h3>
* Some Java virtual machines may support thread contention monitoring.
* When thread contention monitoring is enabled, the accumulated elapsed
* time that the thread has blocked for synchronization or waited for
* notification will be collected and returned in the
* <a href="ThreadInfo.html#SyncStats"><tt>ThreadInfo</tt></a> object.
* <p>
* The {@link #isThreadContentionMonitoringSupported} method can be used to
* determine if a Java virtual machine supports thread contention monitoring.
* The thread contention monitoring is disabled by default. The
* {@link #setThreadContentionMonitoringEnabled} method can be used to enable
* thread contention monitoring.
*
* <h3>Synchronization Information and Deadlock Detection</h3>
* Some Java virtual machines may support monitoring of
* {@linkplain #isObjectMonitorUsageSupported object monitor usage} and
* {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}.
* The {@link #getThreadInfo(long[], boolean, boolean)} and
* {@link #dumpAllThreads} methods can be used to obtain the thread stack trace
* and synchronization information including which
* {@linkplain LockInfo <i>lock</i>} a thread is blocked to
* acquire or waiting on and which locks the thread currently owns.
* <p>
* The <tt>ThreadMXBean</tt> interface provides the
* {@link #findMonitorDeadlockedThreads} and
* {@link #findDeadlockedThreads} methods to find deadlocks in
* the running application.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a>
* @see <a href="package-summary.html#examples">
* Ways to Access MXBeans</a>
*
* @author Mandy Chung
* @since 1.5
*/
public interface ThreadMXBean extends PlatformManagedObject {
/**
* Returns the current number of live threads including both
* daemon and non-daemon threads.
*
* @return the current number of live threads.
*/
public int getThreadCount();
/**
* Returns the peak live thread count since the Java virtual machine
* started or peak was reset.
*
* @return the peak live thread count.
*/
public int getPeakThreadCount();
/**
* Returns the total number of threads created and also started
* since the Java virtual machine started.
*
* @return the total number of threads started.
*/
public long getTotalStartedThreadCount();
/**
* Returns the current number of live daemon threads.
*
* @return the current number of live daemon threads.
*/
public int getDaemonThreadCount();
/**
* Returns all live thread IDs.
* Some threads included in the returned array
* may have been terminated when this method returns.
*
* @return an array of <tt>long</tt>, each is a thread ID.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public long[] getAllThreadIds();
/**
* Returns the thread info for a thread of the specified
* <tt>id</tt> with no stack trace.
* This method is equivalent to calling:
* <blockquote>
* {@link #getThreadInfo(long, int) getThreadInfo(id, 0);}
* </blockquote>
*
* <p>
* This method returns a <tt>ThreadInfo</tt> object representing
* the thread information for the thread of the specified ID.
* The stack trace, locked monitors, and locked synchronizers
* in the returned <tt>ThreadInfo</tt> object will
* be empty.
*
* If a thread of the given ID is not alive or does not exist,
* this method will return <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param id the thread ID of the thread. Must be positive.
*
* @return a {@link ThreadInfo} object for the thread of the given ID
* with no stack trace, no locked monitor and no synchronizer info;
* <tt>null</tt> if the thread of the given ID is not alive or
* it does not exist.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public ThreadInfo getThreadInfo(long id);
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt> with no stack trace.
* This method is equivalent to calling:
* <blockquote><pre>
* {@link #getThreadInfo(long[], int) getThreadInfo}(ids, 0);
* </pre></blockquote>
*
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects.
* The stack trace, locked monitors, and locked synchronizers
* in each <tt>ThreadInfo</tt> object will be empty.
*
* If a thread of a given ID is not alive or does not exist,
* the corresponding element in the returned array will
* contain <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs.
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs
* with no stack trace, no locked monitor and no synchronizer info.
*
* @throws IllegalArgumentException if any element in the input array
* <tt>ids</tt> is {@code <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*/
public ThreadInfo[] getThreadInfo(long[] ids);
/**
* Returns a thread info for a thread of the specified <tt>id</tt>,
* with stack trace of a specified number of stack trace elements.
* The <tt>maxDepth</tt> parameter indicates the maximum number of
* {@link StackTraceElement} to be retrieved from the stack trace.
* If <tt>maxDepth == Integer.MAX_VALUE</tt>, the entire stack trace of
* the thread will be dumped.
* If <tt>maxDepth == 0</tt>, no stack trace of the thread
* will be dumped.
* This method does not obtain the locked monitors and locked
* synchronizers of the thread.
* <p>
* When the Java virtual machine has no stack trace information
* about a thread or <tt>maxDepth == 0</tt>,
* the stack trace in the
* <tt>ThreadInfo</tt> object will be an empty array of
* <tt>StackTraceElement</tt>.
*
* <p>
* If a thread of the given ID is not alive or does not exist,
* this method will return <tt>null</tt>. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param id the thread ID of the thread. Must be positive.
* @param maxDepth the maximum number of entries in the stack trace
* to be dumped. <tt>Integer.MAX_VALUE</tt> could be used to request
* the entire stack to be dumped.
*
* @return a {@link ThreadInfo} of the thread of the given ID
* with no locked monitor and synchronizer info.
* <tt>null</tt> if the thread of the given ID is not alive or
* it does not exist.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
*/
public ThreadInfo getThreadInfo(long id, int maxDepth);
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt>,
* with stack trace of a specified number of stack trace elements.
* The <tt>maxDepth</tt> parameter indicates the maximum number of
* {@link StackTraceElement} to be retrieved from the stack trace.
* If <tt>maxDepth == Integer.MAX_VALUE</tt>, the entire stack trace of
* the thread will be dumped.
* If <tt>maxDepth == 0</tt>, no stack trace of the thread
* will be dumped.
* This method does not obtain the locked monitors and locked
* synchronizers of the threads.
* <p>
* When the Java virtual machine has no stack trace information
* about a thread or <tt>maxDepth == 0</tt>,
* the stack trace in the
* <tt>ThreadInfo</tt> object will be an empty array of
* <tt>StackTraceElement</tt>.
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects,
* each is the thread information about the thread with the same index
* as in the <tt>ids</tt> array.
* If a thread of the given ID is not alive or does not exist,
* <tt>null</tt> will be set in the corresponding element
* in the returned array. A thread is alive if
* it has been started and has not yet died.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs
* @param maxDepth the maximum number of entries in the stack trace
* to be dumped. <tt>Integer.MAX_VALUE</tt> could be used to request
* the entire stack to be dumped.
*
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs with no locked monitor and
* synchronizer info.
*
* @throws IllegalArgumentException if <tt>maxDepth is negative</tt>.
* @throws IllegalArgumentException if any element in the input array
* <tt>ids</tt> is {@code <= 0}.
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
*/
public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth);
/**
* Tests if the Java virtual machine supports thread contention monitoring.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports thread contention monitoring;
* <tt>false</tt> otherwise.
*/
public boolean isThreadContentionMonitoringSupported();
/**
* Tests if thread contention monitoring is enabled.
*
* @return <tt>true</tt> if thread contention monitoring is enabled;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java virtual
* machine does not support thread contention monitoring.
*
* @see #isThreadContentionMonitoringSupported
*/
public boolean isThreadContentionMonitoringEnabled();
/**
* Enables or disables thread contention monitoring.
* Thread contention monitoring is disabled by default.
*
* @param enable <tt>true</tt> to enable;
* <tt>false</tt> to disable.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support thread contention monitoring.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isThreadContentionMonitoringSupported
*/
public void setThreadContentionMonitoringEnabled(boolean enable);
/**
* Returns the total CPU time for the current thread in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
* If the implementation distinguishes between user mode time and system
* mode time, the returned CPU time is the amount of time that
* the current thread has executed in user mode or system mode.
*
* <p>
* This is a convenience method for local management use and is
* equivalent to calling:
* <blockquote><pre>
* {@link #getThreadCpuTime getThreadCpuTime}(Thread.currentThread().getId());
* </pre></blockquote>
*
* @return the total CPU time for the current thread if CPU time
* measurement is enabled; <tt>-1</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* the current thread.
*
* @see #getCurrentThreadUserTime
* @see #isCurrentThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getCurrentThreadCpuTime();
/**
* Returns the CPU time that the current thread has executed
* in user mode in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
*
* <p>
* This is a convenience method for local management use and is
* equivalent to calling:
* <blockquote><pre>
* {@link #getThreadUserTime getThreadUserTime}(Thread.currentThread().getId());
* </pre></blockquote>
*
* @return the user-level CPU time for the current thread if CPU time
* measurement is enabled; <tt>-1</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* the current thread.
*
* @see #getCurrentThreadCpuTime
* @see #isCurrentThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getCurrentThreadUserTime();
/**
* Returns the total CPU time for a thread of the specified ID in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
* If the implementation distinguishes between user mode time and system
* mode time, the returned CPU time is the amount of time that
* the thread has executed in user mode or system mode.
*
* <p>
* If the thread of the specified ID is not alive or does not exist,
* this method returns <tt>-1</tt>. If CPU time measurement
* is disabled, this method returns <tt>-1</tt>.
* A thread is alive if it has been started and has not yet died.
* <p>
* If CPU time measurement is enabled after the thread has started,
* the Java virtual machine implementation may choose any time up to
* and including the time that the capability is enabled as the point
* where CPU time measurement starts.
*
* @param id the thread ID of a thread
* @return the total CPU time for a thread of the specified ID
* if the thread of the specified ID exists, the thread is alive,
* and CPU time measurement is enabled;
* <tt>-1</tt> otherwise.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* other threads.
*
* @see #getThreadUserTime
* @see #isThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getThreadCpuTime(long id);
/**
* Returns the CPU time that a thread of the specified ID
* has executed in user mode in nanoseconds.
* The returned value is of nanoseconds precision but
* not necessarily nanoseconds accuracy.
*
* <p>
* If the thread of the specified ID is not alive or does not exist,
* this method returns <tt>-1</tt>. If CPU time measurement
* is disabled, this method returns <tt>-1</tt>.
* A thread is alive if it has been started and has not yet died.
* <p>
* If CPU time measurement is enabled after the thread has started,
* the Java virtual machine implementation may choose any time up to
* and including the time that the capability is enabled as the point
* where CPU time measurement starts.
*
* @param id the thread ID of a thread
* @return the user-level CPU time for a thread of the specified ID
* if the thread of the specified ID exists, the thread is alive,
* and CPU time measurement is enabled;
* <tt>-1</tt> otherwise.
*
* @throws IllegalArgumentException if {@code id <= 0}.
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* other threads.
*
* @see #getThreadCpuTime
* @see #isThreadCpuTimeSupported
* @see #isThreadCpuTimeEnabled
* @see #setThreadCpuTimeEnabled
*/
public long getThreadUserTime(long id);
/**
* Tests if the Java virtual machine implementation supports CPU time
* measurement for any thread.
* A Java virtual machine implementation that supports CPU time
* measurement for any thread will also support CPU time
* measurement for the current thread.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports CPU time
* measurement for any thread;
* <tt>false</tt> otherwise.
*/
public boolean isThreadCpuTimeSupported();
/**
* Tests if the Java virtual machine supports CPU time
* measurement for the current thread.
* This method returns <tt>true</tt> if {@link #isThreadCpuTimeSupported}
* returns <tt>true</tt>.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports CPU time
* measurement for current thread;
* <tt>false</tt> otherwise.
*/
public boolean isCurrentThreadCpuTimeSupported();
/**
* Tests if thread CPU time measurement is enabled.
*
* @return <tt>true</tt> if thread CPU time measurement is enabled;
* <tt>false</tt> otherwise.
*
* @throws UnsupportedOperationException if the Java virtual
* machine does not support CPU time measurement for other threads
* nor for the current thread.
*
* @see #isThreadCpuTimeSupported
* @see #isCurrentThreadCpuTimeSupported
*/
public boolean isThreadCpuTimeEnabled();
/**
* Enables or disables thread CPU time measurement. The default
* is platform dependent.
*
* @param enable <tt>true</tt> to enable;
* <tt>false</tt> to disable.
*
* @throws UnsupportedOperationException if the Java
* virtual machine does not support CPU time measurement for
* any threads nor for the current thread.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #isThreadCpuTimeSupported
* @see #isCurrentThreadCpuTimeSupported
*/
public void setThreadCpuTimeEnabled(boolean enable);
/**
* Finds cycles of threads that are in deadlock waiting to acquire
* object monitors. That is, threads that are blocked waiting to enter a
* synchronization block or waiting to reenter a synchronization block
* after an {@link Object#wait Object.wait} call,
* where each thread owns one monitor while
* trying to obtain another monitor already held by another thread
* in a cycle.
* <p>
* More formally, a thread is <em>monitor deadlocked</em> if it is
* part of a cycle in the relation "is waiting for an object monitor
* owned by". In the simplest case, thread A is blocked waiting
* for a monitor owned by thread B, and thread B is blocked waiting
* for a monitor owned by thread A.
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
* <p>
* This method finds deadlocks involving only object monitors.
* To find deadlocks involving both object monitors and
* <a href="LockInfo.html#OwnableSynchronizer">ownable synchronizers</a>,
* the {@link #findDeadlockedThreads findDeadlockedThreads} method
* should be used.
*
* @return an array of IDs of the threads that are monitor
* deadlocked, if any; <tt>null</tt> otherwise.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
*
* @see #findDeadlockedThreads
*/
public long[] findMonitorDeadlockedThreads();
/**
* Resets the peak thread count to the current number of
* live threads.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("control").
*
* @see #getPeakThreadCount
* @see #getThreadCount
*/
public void resetPeakThreadCount();
/**
* Finds cycles of threads that are in deadlock waiting to acquire
* object monitors or
* <a href="LockInfo.html#OwnableSynchronizer">ownable synchronizers</a>.
*
* Threads are <em>deadlocked</em> in a cycle waiting for a lock of
* these two types if each thread owns one lock while
* trying to acquire another lock already held
* by another thread in the cycle.
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
*
* @return an array of IDs of the threads that are
* deadlocked waiting for object monitors or ownable synchronizers, if any;
* <tt>null</tt> otherwise.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException if the Java virtual
* machine does not support monitoring of ownable synchronizer usage.
*
* @see #isSynchronizerUsageSupported
* @see #findMonitorDeadlockedThreads
* @since 1.6
*/
public long[] findDeadlockedThreads();
/**
* Tests if the Java virtual machine supports monitoring of
* object monitor usage.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports monitoring of
* object monitor usage;
* <tt>false</tt> otherwise.
*
* @see #dumpAllThreads
* @since 1.6
*/
public boolean isObjectMonitorUsageSupported();
/**
* Tests if the Java virtual machine supports monitoring of
* <a href="LockInfo.html#OwnableSynchronizer">
* ownable synchronizer</a> usage.
*
* @return
* <tt>true</tt>
* if the Java virtual machine supports monitoring of ownable
* synchronizer usage;
* <tt>false</tt> otherwise.
*
* @see #dumpAllThreads
* @since 1.6
*/
public boolean isSynchronizerUsageSupported();
/**
* Returns the thread info for each thread
* whose ID is in the input array <tt>ids</tt>, with stack trace
* and synchronization information.
*
* <p>
* This method obtains a snapshot of the thread information
* for each thread including:
* <ul>
* <li>the entire stack trace,</li>
* <li>the object monitors currently locked by the thread
* if <tt>lockedMonitors</tt> is <tt>true</tt>, and</li>
* <li>the <a href="LockInfo.html#OwnableSynchronizer">
* ownable synchronizers</a> currently locked by the thread
* if <tt>lockedSynchronizers</tt> is <tt>true</tt>.</li>
* </ul>
* <p>
* This method returns an array of the <tt>ThreadInfo</tt> objects,
* each is the thread information about the thread with the same index
* as in the <tt>ids</tt> array.
* If a thread of the given ID is not alive or does not exist,
* <tt>null</tt> will be set in the corresponding element
* in the returned array. A thread is alive if
* it has been started and has not yet died.
* <p>
* If a thread does not lock any object monitor or <tt>lockedMonitors</tt>
* is <tt>false</tt>, the returned <tt>ThreadInfo</tt> object will have an
* empty <tt>MonitorInfo</tt> array. Similarly, if a thread does not
* lock any synchronizer or <tt>lockedSynchronizers</tt> is <tt>false</tt>,
* the returned <tt>ThreadInfo</tt> object
* will have an empty <tt>LockInfo</tt> array.
*
* <p>
* When both <tt>lockedMonitors</tt> and <tt>lockedSynchronizers</tt>
* parameters are <tt>false</tt>, it is equivalent to calling:
* <blockquote><pre>
* {@link #getThreadInfo(long[], int) getThreadInfo(ids, Integer.MAX_VALUE)}
* </pre></blockquote>
*
* <p>
* This method is designed for troubleshooting use, but not for
* synchronization control. It might be an expensive operation.
*
* <p>
* <b>MBeanServer access</b>:<br>
* The mapped type of <tt>ThreadInfo</tt> is
* <tt>CompositeData</tt> with attributes as specified in the
* {@link ThreadInfo#from ThreadInfo.from} method.
*
* @param ids an array of thread IDs.
* @param lockedMonitors if <tt>true</tt>, retrieves all locked monitors.
* @param lockedSynchronizers if <tt>true</tt>, retrieves all locked
* ownable synchronizers.
*
* @return an array of the {@link ThreadInfo} objects, each containing
* information about a thread whose ID is in the corresponding
* element of the input array of IDs.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException
* <ul>
* <li>if <tt>lockedMonitors</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isObjectMonitorUsageSupported
* object monitor usage}; or</li>
* <li>if <tt>lockedSynchronizers</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isSynchronizerUsageSupported
* ownable synchronizer usage}.</li>
* </ul>
*
* @see #isObjectMonitorUsageSupported
* @see #isSynchronizerUsageSupported
*
* @since 1.6
*/
public ThreadInfo[] getThreadInfo(long[] ids, boolean lockedMonitors, boolean lockedSynchronizers);
/**
* Returns the thread info for all live threads with stack trace
* and synchronization information.
* Some threads included in the returned array
* may have been terminated when this method returns.
*
* <p>
* This method returns an array of {@link ThreadInfo} objects
* as specified in the {@link #getThreadInfo(long[], boolean, boolean)}
* method.
*
* @param lockedMonitors if <tt>true</tt>, dump all locked monitors.
* @param lockedSynchronizers if <tt>true</tt>, dump all locked
* ownable synchronizers.
*
* @return an array of {@link ThreadInfo} for all live threads.
*
* @throws SecurityException if a security manager
* exists and the caller does not have
* ManagementPermission("monitor").
* @throws UnsupportedOperationException
* <ul>
* <li>if <tt>lockedMonitors</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isObjectMonitorUsageSupported
* object monitor usage}; or</li>
* <li>if <tt>lockedSynchronizers</tt> is <tt>true</tt> but
* the Java virtual machine does not support monitoring
* of {@linkplain #isSynchronizerUsageSupported
* ownable synchronizer usage}.</li>
* </ul>
*
* @see #isObjectMonitorUsageSupported
* @see #isSynchronizerUsageSupported
*
* @since 1.6
*/
public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers);
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/java/lang/management/ThreadMXBean.java |
180,201 | /*
* The contents of this file is dual-licensed under 2
* alternative Open Source/Free licenses: LGPL 2.1 or later and
* Apache License 2.0. (starting with JNA version 4.0.0).
*
* You can freely decide which license you want to apply to
* the project.
*
* You may obtain a copy of the LGPL License at:
*
* http://www.gnu.org/licenses/licenses.html
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "LGPL2.1".
*
* You may obtain a copy of the Apache License at:
*
* http://www.apache.org/licenses/
*
* A copy is also included in the downloadable source code package
* containing JNA, in file "AL2.0".
*/
package com.sun.jna.platform.win32.COM.util.office.word;
import com.sun.jna.platform.win32.COM.util.IComEnum;
/**
* <p>uuid({58B14C6F-0FE6-3BCA-880E-E3A9C039E588})</p>
*/
public enum WdBreakType implements IComEnum {
/**
* (2)
*/
wdSectionBreakNextPage(2),
/**
* (3)
*/
wdSectionBreakContinuous(3),
/**
* (4)
*/
wdSectionBreakEvenPage(4),
/**
* (5)
*/
wdSectionBreakOddPage(5),
/**
* (6)
*/
wdLineBreak(6),
/**
* (7)
*/
wdPageBreak(7),
/**
* (8)
*/
wdColumnBreak(8),
/**
* (9)
*/
wdLineBreakClearLeft(9),
/**
* (10)
*/
wdLineBreakClearRight(10),
/**
* (11)
*/
wdTextWrappingBreak(11),
;
private WdBreakType(long value) {
this.value = value;
}
private long value;
public long getValue() {
return this.value;
}
} | java-native-access/jna | contrib/msoffice/src/com/sun/jna/platform/win32/COM/util/office/word/WdBreakType.java |
180,203 | /*
* Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.espresso.runtime;
import static com.oracle.truffle.espresso.jni.JniEnv.JNI_OK;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.ReferenceQueue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.stream.Collectors;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.TruffleFile;
import com.oracle.truffle.api.TruffleLanguage;
import com.oracle.truffle.api.TruffleLanguage.ContextReference;
import com.oracle.truffle.api.TruffleLogger;
import com.oracle.truffle.api.dsl.Idempotent;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.espresso.EspressoBindings;
import com.oracle.truffle.espresso.EspressoLanguage;
import com.oracle.truffle.espresso.EspressoOptions;
import com.oracle.truffle.espresso.analysis.hierarchy.ClassHierarchyOracle;
import com.oracle.truffle.espresso.blocking.BlockingSupport;
import com.oracle.truffle.espresso.blocking.EspressoLock;
import com.oracle.truffle.espresso.descriptors.Names;
import com.oracle.truffle.espresso.descriptors.Signatures;
import com.oracle.truffle.espresso.descriptors.Symbol;
import com.oracle.truffle.espresso.descriptors.Symbol.Name;
import com.oracle.truffle.espresso.descriptors.Symbol.Signature;
import com.oracle.truffle.espresso.descriptors.Symbol.Type;
import com.oracle.truffle.espresso.descriptors.Types;
import com.oracle.truffle.espresso.ffi.NativeAccess;
import com.oracle.truffle.espresso.ffi.NativeAccessCollector;
import com.oracle.truffle.espresso.ffi.nfi.NFIIsolatedNativeAccess;
import com.oracle.truffle.espresso.ffi.nfi.NFINativeAccess;
import com.oracle.truffle.espresso.ffi.nfi.NFISulongNativeAccess;
import com.oracle.truffle.espresso.impl.ClassLoadingEnv;
import com.oracle.truffle.espresso.impl.ClassRegistries;
import com.oracle.truffle.espresso.impl.Field;
import com.oracle.truffle.espresso.impl.Klass;
import com.oracle.truffle.espresso.impl.Method;
import com.oracle.truffle.espresso.impl.ObjectKlass;
import com.oracle.truffle.espresso.jdwp.api.Ids;
import com.oracle.truffle.espresso.jdwp.impl.DebuggerController;
import com.oracle.truffle.espresso.jni.JniEnv;
import com.oracle.truffle.espresso.meta.EspressoError;
import com.oracle.truffle.espresso.meta.Meta;
import com.oracle.truffle.espresso.nodes.interop.EspressoForeignProxyGenerator;
import com.oracle.truffle.espresso.nodes.interop.PolyglotTypeMappings;
import com.oracle.truffle.espresso.perf.DebugCloseable;
import com.oracle.truffle.espresso.perf.DebugTimer;
import com.oracle.truffle.espresso.perf.TimerCollection;
import com.oracle.truffle.espresso.preinit.ContextPatchingException;
import com.oracle.truffle.espresso.preinit.EspressoLanguageCache;
import com.oracle.truffle.espresso.redefinition.ClassRedefinition;
import com.oracle.truffle.espresso.redefinition.plugins.api.InternalRedefinitionPlugin;
import com.oracle.truffle.espresso.redefinition.plugins.impl.RedefinitionPluginHandler;
import com.oracle.truffle.espresso.ref.FinalizationSupport;
import com.oracle.truffle.espresso.runtime.jimage.BasicImageReader;
import com.oracle.truffle.espresso.runtime.panama.DowncallStubs;
import com.oracle.truffle.espresso.runtime.panama.Platform;
import com.oracle.truffle.espresso.runtime.panama.UpcallStubs;
import com.oracle.truffle.espresso.runtime.staticobject.StaticObject;
import com.oracle.truffle.espresso.substitutions.Substitutions;
import com.oracle.truffle.espresso.threads.ThreadsAccess;
import com.oracle.truffle.espresso.vm.InterpreterToVM;
import com.oracle.truffle.espresso.vm.UnsafeAccess;
import com.oracle.truffle.espresso.vm.VM;
import sun.misc.SignalHandler;
public final class EspressoContext {
// MaxJavaStackTraceDepth is 1024 by default
public static final int DEFAULT_STACK_SIZE = 32;
public static final StackTraceElement[] EMPTY_STACK = new StackTraceElement[0];
private static final DebugTimer SPAWN_VM = DebugTimer.create("spawnVM");
private static final DebugTimer SYSTEM_INIT = DebugTimer.create("system init", SPAWN_VM);
private static final DebugTimer KNOWN_CLASS_INIT = DebugTimer.create("known class init", SPAWN_VM);
private static final DebugTimer META_INIT = DebugTimer.create("meta init", SPAWN_VM);
private static final DebugTimer VM_INIT = DebugTimer.create("vm init", SPAWN_VM);
private static final DebugTimer SYSTEM_CLASSLOADER = DebugTimer.create("system classloader", SPAWN_VM);
private final TruffleLogger logger = TruffleLogger.getLogger(EspressoLanguage.ID);
private final EspressoLanguage language;
@CompilationFinal private EspressoEnv espressoEnv;
private String[] mainArguments;
private long startupClockNanos = 0;
// region Runtime
private final StringTable strings;
@CompilationFinal private ClassRegistries registries;
private final Substitutions substitutions;
private final MethodHandleIntrinsics methodHandleIntrinsics;
// endregion Runtime
// region Helpers
@CompilationFinal private ThreadsAccess threads;
@CompilationFinal private BlockingSupport<StaticObject> blockingSupport;
@CompilationFinal private EspressoShutdownHandler shutdownManager;
// endregion Helpers
// region ID
@CompilationFinal private long bootClassLoaderID;
// endregion ID
// region InitControl
public long initDoneTimeNanos;
@CompilationFinal private boolean modulesInitialized = false;
@CompilationFinal private boolean metaInitialized = false;
private boolean initialized = false;
private boolean disposeCalled = false;
private Classpath bootClasspath;
@CompilationFinal private ClassLoadingEnv classLoadingEnv;
// endregion InitControl
// region JDWP
private ClassRedefinition classRedefinition;
private final Assumption anyHierarchyChanges = Truffle.getRuntime().createAssumption();
// endregion JDWP
@CompilationFinal private volatile LazyContextCaches lazyCaches;
private Map<Class<? extends InternalRedefinitionPlugin>, InternalRedefinitionPlugin> redefinitionPlugins;
// After a context is finalized, guest code cannot be executed.
private volatile boolean isFinalized;
// Must be initialized after the context instance creation.
// region VM
@CompilationFinal private Meta meta;
@CompilationFinal private VM vm;
@CompilationFinal private JniEnv jniEnv;
@CompilationFinal private InterpreterToVM interpreterToVM;
@CompilationFinal private JImageLibrary jimageLibrary;
@CompilationFinal private EspressoProperties vmProperties;
@CompilationFinal private AgentLibraries agents;
@CompilationFinal private NativeAccess nativeAccess;
// endregion VM
@CompilationFinal private EspressoException stackOverflow;
@CompilationFinal private EspressoException outOfMemory;
@CompilationFinal private EspressoBindings topBindings;
@CompilationFinal private StaticObject bindingsLoader;
private final WeakHashMap<StaticObject, SignalHandler> hostSignalHandlers = new WeakHashMap<>();
@CompilationFinal private DowncallStubs downcallStubs;
@CompilationFinal private UpcallStubs upcallStubs;
public TruffleLogger getLogger() {
return logger;
}
public long getBootClassLoaderID() {
return bootClassLoaderID;
}
public EspressoContext(TruffleLanguage.Env env, EspressoLanguage language) {
this.language = language;
this.strings = new StringTable(this);
this.substitutions = new Substitutions(this);
this.methodHandleIntrinsics = new MethodHandleIntrinsics();
this.espressoEnv = new EspressoEnv(this, env);
this.classLoadingEnv = new ClassLoadingEnv(getLanguage(), getLogger(), getTimers());
this.bootClassLoaderID = classLoadingEnv.getNewLoaderId();
}
public ClassRegistries getRegistries() {
return registries;
}
public InputStream in() {
return getEnv().in();
}
public OutputStream out() {
return getEnv().out();
}
public OutputStream err() {
return getEnv().err();
}
public StringTable getStrings() {
return strings;
}
public TruffleLanguage.Env getEnv() {
return espressoEnv.env();
}
public EspressoEnv getEspressoEnv() {
return espressoEnv;
}
public EspressoLanguage getLanguage() {
return language;
}
public boolean multiThreadingEnabled() {
return espressoEnv.multiThreadingEnabled();
}
public String getMultiThreadingDisabledReason() {
return espressoEnv.getMultiThreadingDisabledReason();
}
/**
* @return The {@link String}[] array passed to the main function.
*/
public String[] getMainArguments() {
return mainArguments;
}
public void setMainArguments(String[] mainArguments) {
this.mainArguments = mainArguments;
}
public String[] getVmArguments() {
return espressoEnv.getVmArguments();
}
public long getStartupClockNanos() {
return startupClockNanos;
}
public EspressoLanguageCache getLanguageCache() {
return getLanguage().getLanguageCache();
}
public Classpath getBootClasspath() {
if (bootClasspath == null) {
CompilerAsserts.neverPartOfCompilation();
bootClasspath = new Classpath(
getVmProperties().bootClasspath().stream().map(new Function<Path, String>() {
@Override
public String apply(Path path) {
return path.toString();
}
}).collect(Collectors.joining(File.pathSeparator)));
}
return bootClasspath;
}
public ClassLoadingEnv getClassLoadingEnv() {
return classLoadingEnv;
}
public void setBootClassPath(Classpath classPath) {
this.bootClasspath = classPath;
}
public EspressoProperties getVmProperties() {
assert vmProperties != null;
return vmProperties;
}
public void initializeContext() throws ContextPatchingException {
EspressoError.guarantee(getEnv().isNativeAccessAllowed(),
"Native access is not allowed by the host environment but it's required to load Espresso/Java native libraries. " +
"Allow native access on context creation e.g. contextBuilder.allowNativeAccess(true). If you are attempting to pre-initialize " +
"an Espresso context, allow native access for pre-initialized languages through Truffle's image-build-time options.");
assert !this.initialized;
startupClockNanos = System.nanoTime();
// Setup finalization support in the host VM.
FinalizationSupport.ensureInitialized();
spawnVM();
getEspressoEnv().getPolyglotTypeMappings().resolve(this);
this.initialized = true;
getEspressoEnv().getReferenceDrainer().startReferenceDrain();
// enable JDWP instrumenter only if options are set (assumed valid if non-null)
if (espressoEnv.JDWPOptions != null) {
espressoEnv.getJdwpContext().jdwpInit(getEnv(), getMainThread(), espressoEnv.getEventListener());
}
}
public void patchContext(TruffleLanguage.Env newEnv) {
this.espressoEnv = new EspressoEnv(this, newEnv);
}
@TruffleBoundary
public Source findOrCreateSource(ObjectKlass klass) {
String sourceFile = klass.getSourceFile();
if (sourceFile == null) {
return null;
}
if (!sourceFile.contains("/") && !sourceFile.contains("\\")) {
// try to come up with a more unique name
Symbol<Name> runtimePackage = klass.getRuntimePackage();
if (runtimePackage != null && runtimePackage.length() > 0) {
sourceFile = runtimePackage + "/" + sourceFile;
}
}
TruffleFile file = getEnv().getInternalTruffleFile(sourceFile);
// sources are interned so no cache needed (hopefully)
return Source.newBuilder("java", file).content(Source.CONTENT_NONE).build();
}
public Meta getMeta() {
return meta;
}
public GuestAllocator getAllocator() {
return getLanguage().getAllocator();
}
public NativeAccess getNativeAccess() {
return nativeAccess;
}
@SuppressWarnings("try")
private void spawnVM() throws ContextPatchingException {
try (DebugCloseable spawn = SPAWN_VM.scope(espressoEnv.getTimers())) {
long initStartTimeNanos = System.nanoTime();
this.nativeAccess = spawnNativeAccess();
initVmProperties();
// Find guest java version
JavaVersion contextJavaVersion = javaVersionFromReleaseFile(vmProperties.javaHome());
if (contextJavaVersion == null) {
contextJavaVersion = JavaVersion.latestSupported();
getLogger().warning(() -> "Couldn't find Java version for %s / %s: defaulting to %s".formatted(
vmProperties.javaHome(), vmProperties.bootLibraryPath(), JavaVersion.latestSupported()));
} else if (contextJavaVersion.compareTo(JavaVersion.latestSupported()) > 0) {
throw EspressoError.fatal("Unsupported Java version: " + contextJavaVersion);
}
// Ensure that the extracted Java version equals the language's Java version, if it
// is set
JavaVersion languageJavaVersion = getLanguage().getJavaVersion();
if (languageJavaVersion != null) {
if (!contextJavaVersion.equals(languageJavaVersion)) {
throw ContextPatchingException.javaVersionMismatch(languageJavaVersion, contextJavaVersion);
}
} else {
getLanguage().tryInitializeJavaVersion(contextJavaVersion);
}
if (!contextJavaVersion.java21OrLater() && getEspressoEnv().RegexSubstitutions) {
logger.warning("UseTRegex is not available for context running Java version < 21");
}
// Spawn JNI first, then the VM.
try (DebugCloseable vmInit = VM_INIT.scope(espressoEnv.getTimers())) {
this.jniEnv = JniEnv.create(this); // libnespresso
this.vm = VM.create(this.jniEnv); // libjvm
vm.attachThread(Thread.currentThread());
vm.loadJavaLibrary(vmProperties.bootLibraryPath()); // libjava
this.downcallStubs = new DowncallStubs(Platform.getHostPlatform());
this.upcallStubs = new UpcallStubs(Platform.getHostPlatform(), nativeAccess, language);
vm.initializeJavaLibrary();
EspressoError.guarantee(getJavaVersion() != null, "Java version");
}
this.registries = new ClassRegistries(this);
if (getJavaVersion().modulesEnabled()) {
registries.initJavaBaseModule();
registries.getBootClassRegistry().initUnnamedModule(StaticObject.NULL);
}
// TODO: link libjimage
initializeAgents();
try (DebugCloseable metaInit = META_INIT.scope(espressoEnv.getTimers())) {
this.meta = new Meta(this);
}
this.classLoadingEnv.setMeta(meta);
this.metaInitialized = true;
this.threads = new ThreadsAccess(meta);
this.blockingSupport = BlockingSupport.create(threads);
this.shutdownManager = new EspressoShutdownHandler(this, espressoEnv.getThreadRegistry(), espressoEnv.getReferenceDrainer(), espressoEnv.SoftExit);
this.interpreterToVM = new InterpreterToVM(this);
this.lazyCaches = new LazyContextCaches(this);
try (DebugCloseable knownClassInit = KNOWN_CLASS_INIT.scope(espressoEnv.getTimers())) {
initializeKnownClass(Type.java_lang_Object);
for (Symbol<Type> type : Arrays.asList(
Type.java_lang_String,
Type.java_lang_System,
Type.java_lang_Class, // JDK-8069005
Type.java_lang_ThreadGroup,
Type.java_lang_Thread)) {
initializeKnownClass(type);
}
}
if (meta.jdk_internal_misc_UnsafeConstants != null) {
initializeKnownClass(Type.jdk_internal_misc_UnsafeConstants);
UnsafeAccess.initializeGuestUnsafeConstants(meta);
}
// Create main thread as soon as Thread class is initialized.
espressoEnv.getThreadRegistry().createMainThread(meta);
try (DebugCloseable knownClassInit = KNOWN_CLASS_INIT.scope(espressoEnv.getTimers())) {
for (Symbol<Type> type : Arrays.asList(
Type.java_lang_reflect_Method,
Type.java_lang_ref_Finalizer)) {
initializeKnownClass(type);
}
}
espressoEnv.getReferenceDrainer().initReferenceDrain();
try (DebugCloseable systemInit = SYSTEM_INIT.scope(espressoEnv.getTimers())) {
// Call guest initialization
if (getJavaVersion().java8OrEarlier()) {
meta.java_lang_System_initializeSystemClass.invokeDirect(null);
} else {
assert getJavaVersion().java9OrLater();
meta.java_lang_System_initPhase1.invokeDirect(null);
for (Symbol<Type> type : Arrays.asList(
Type.java_lang_invoke_MethodHandle,
Type.java_lang_invoke_MemberName,
Type.java_lang_invoke_MethodHandleNatives)) {
// Type.java_lang_invoke_ResolvedMethodName is not used atm
initializeKnownClass(type);
}
int e = (int) meta.java_lang_System_initPhase2.invokeDirect(null, false, logger.isLoggable(Level.FINE));
if (e != 0) {
throw EspressoError.shouldNotReachHere();
}
getVM().getJvmti().postVmStart();
modulesInitialized = true;
meta.java_lang_System_initPhase3.invokeDirect(null);
}
}
getVM().getJvmti().postVmInit();
meta.postSystemInit();
try (DebugCloseable knownClassInit = KNOWN_CLASS_INIT.scope(espressoEnv.getTimers())) {
// System exceptions.
for (Symbol<Type> type : Arrays.asList(
Type.java_lang_OutOfMemoryError,
Type.java_lang_NullPointerException,
Type.java_lang_ClassCastException,
Type.java_lang_ArrayStoreException,
Type.java_lang_ArithmeticException,
Type.java_lang_StackOverflowError,
Type.java_lang_IllegalMonitorStateException,
Type.java_lang_IllegalArgumentException)) {
initializeKnownClass(type);
}
}
// Init memoryError instances
StaticObject stackOverflowErrorInstance = meta.java_lang_StackOverflowError.allocateInstance(this);
StaticObject outOfMemoryErrorInstance = meta.java_lang_OutOfMemoryError.allocateInstance(this);
// Preemptively set stack trace.
meta.HIDDEN_FRAMES.setHiddenObject(stackOverflowErrorInstance, VM.StackTrace.EMPTY_STACK_TRACE);
meta.java_lang_Throwable_backtrace.setObject(stackOverflowErrorInstance, stackOverflowErrorInstance);
meta.HIDDEN_FRAMES.setHiddenObject(outOfMemoryErrorInstance, VM.StackTrace.EMPTY_STACK_TRACE);
meta.java_lang_Throwable_backtrace.setObject(outOfMemoryErrorInstance, outOfMemoryErrorInstance);
this.stackOverflow = EspressoException.wrap(stackOverflowErrorInstance, meta);
this.outOfMemory = EspressoException.wrap(outOfMemoryErrorInstance, meta);
meta.java_lang_StackOverflowError.lookupDeclaredMethod(Name._init_, Signature._void_String).invokeDirect(stackOverflowErrorInstance, meta.toGuestString("VM StackOverFlow"));
meta.java_lang_OutOfMemoryError.lookupDeclaredMethod(Name._init_, Signature._void_String).invokeDirect(outOfMemoryErrorInstance, meta.toGuestString("VM OutOfMemory"));
// Create application (system) class loader.
StaticObject systemClassLoader = null;
try (DebugCloseable systemLoader = SYSTEM_CLASSLOADER.scope(espressoEnv.getTimers())) {
systemClassLoader = (StaticObject) meta.java_lang_ClassLoader_getSystemClassLoader.invokeDirect(null);
}
bindingsLoader = createBindingsLoader(systemClassLoader);
topBindings = new EspressoBindings(
getEnv().getOptions().get(EspressoOptions.ExposeNativeJavaVM),
bindingsLoader != systemClassLoader);
initDoneTimeNanos = System.nanoTime();
long elapsedNanos = initDoneTimeNanos - initStartTimeNanos;
getLogger().log(Level.FINE, "VM booted in {0} ms", TimeUnit.NANOSECONDS.toMillis(elapsedNanos));
}
}
private JavaVersion javaVersionFromReleaseFile(Path javaHome) {
Path releaseFilePath = javaHome.resolve("release");
if (!Files.isRegularFile(releaseFilePath)) {
Path maybeJre = javaHome.getFileName();
if (maybeJre == null || !"jre".equals(maybeJre.toString())) {
return null;
}
Path parent = javaHome.getParent();
if (parent == null) {
return null;
}
// pre-jdk9 layout
releaseFilePath = parent.resolve("release");
if (!Files.isRegularFile(releaseFilePath)) {
return null;
}
}
try {
for (String line : Files.readAllLines(releaseFilePath)) {
if (line.startsWith("JAVA_VERSION=")) {
String version = line.substring("JAVA_VERSION=".length()).trim();
// JAVA_VERSION=<value> may be quoted or unquoted, both cases are supported.
if (version.length() > 2 && version.startsWith("\"") && version.endsWith("\"")) {
version = version.substring(1, version.length() - 1);
}
return JavaVersion.forVersion(version);
}
}
} catch (IOException | NumberFormatException e) {
getLogger().log(Level.WARNING, "Error while trying to read Java version from release file", e);
// cannot read file, skip
}
return null; // JAVA_VERSION not found
}
public void preInitializeContext() {
assert isInitialized();
long initStartTimeNanos = System.nanoTime();
getLogger().fine("Loading classes from lib/classlist");
Path classlistPath = getVmProperties().javaHome().resolve("lib").resolve("classlist");
List<Symbol<Type>> classlist = readClasslist(classlistPath);
for (Symbol<Type> type : classlist) {
getMeta().loadKlassOrFail(type, StaticObject.NULL, StaticObject.NULL);
}
long elapsedNanos = System.nanoTime() - initStartTimeNanos;
getLogger().log(Level.FINE, "Loaded lib/classlist in {0} ms", TimeUnit.NANOSECONDS.toMillis(elapsedNanos));
Path userClasslistPath = getEnv().getOptions().get(EspressoOptions.PreInitializationClasslist);
if (!userClasslistPath.toString().isEmpty()) {
getLanguageCache().logCacheStatus();
getLogger().fine(() -> "Loading classes from user-specified classlist: " + userClasslistPath);
initStartTimeNanos = System.nanoTime();
List<Symbol<Type>> additionalClasslist = readClasslist(userClasslistPath);
StaticObject systemClassLoader = (StaticObject) meta.java_lang_ClassLoader_getSystemClassLoader.invokeDirect(null);
for (Symbol<Type> type : additionalClasslist) {
Klass klass = getMeta().loadKlassOrNull(type, systemClassLoader, StaticObject.NULL);
if (Objects.isNull(klass)) {
getLogger().warning(() -> "Failed to load class from user-specified classlist: " + type);
}
}
elapsedNanos = System.nanoTime() - initStartTimeNanos;
getLogger().log(Level.FINE, "Loaded user-specified classlist in {0} ms", TimeUnit.NANOSECONDS.toMillis(elapsedNanos));
}
}
private List<Symbol<Type>> readClasslist(Path classlistFilePath) {
try {
List<Symbol<Type>> classlist = Files.readAllLines(classlistFilePath) //
.stream() //
.filter(line -> !line.isBlank() && !line.startsWith("#") && !line.startsWith("@")) //
.map(Types::internalFromClassName) //
.map(t -> getTypes().getOrCreate(t)) //
.filter(Objects::nonNull) //
.collect(Collectors.toList());
return classlist;
} catch (IOException e) {
getLogger().log(Level.WARNING, "Failed to read classlist", e);
return List.of();
}
}
private StaticObject createBindingsLoader(StaticObject systemClassLoader) {
if (!getEspressoEnv().UseBindingsLoader) {
return systemClassLoader;
}
Klass k = getMeta().loadKlassOrNull(Type.java_net_URLClassLoader, StaticObject.NULL, StaticObject.NULL);
if (k == null) {
return systemClassLoader;
}
Method init = k.lookupDeclaredMethod(Name._init_, Signature._void_URL_array_ClassLoader);
if (init == null) {
return systemClassLoader;
}
StaticObject loader = k.allocateInstance();
init.invokeDirect(loader,
/* URLs */ getMeta().java_net_URL.allocateReferenceArray(0),
/* parent */ systemClassLoader);
return loader;
}
private NativeAccess spawnNativeAccess() {
String nativeBackend;
if (getEnv().getOptions().hasBeenSet(EspressoOptions.NativeBackend)) {
nativeBackend = getEnv().getOptions().get(EspressoOptions.NativeBackend);
} else {
// Pick a sane "default" native backend depending on the platform.
boolean isInPreInit = (boolean) getEnv().getConfig().getOrDefault("preinit", false);
if (isInPreInit || !EspressoOptions.RUNNING_ON_SVM) {
if (OS.getCurrent() == OS.Linux) {
nativeBackend = NFIIsolatedNativeAccess.Provider.ID;
} else {
nativeBackend = NFISulongNativeAccess.Provider.ID;
}
} else {
nativeBackend = NFINativeAccess.Provider.ID;
}
}
List<String> available = new ArrayList<>();
for (NativeAccess.Provider provider : NativeAccessCollector.getInstances(NativeAccess.Provider.class)) {
available.add(provider.id());
if (nativeBackend.equals(provider.id())) {
getLogger().fine("Native backend: " + nativeBackend);
return provider.create(getEnv());
}
}
throw abort("Cannot find native backend '" + nativeBackend + "'. Available backends: " + available);
}
private void initializeAgents() {
agents = new AgentLibraries(this);
if (getEnv().getOptions().hasBeenSet(EspressoOptions.AgentLib)) {
agents.registerAgents(getEnv().getOptions().get(EspressoOptions.AgentLib), false);
}
if (getEnv().getOptions().hasBeenSet(EspressoOptions.AgentPath)) {
agents.registerAgents(getEnv().getOptions().get(EspressoOptions.AgentPath), true);
}
if (getEnv().getOptions().hasBeenSet(EspressoOptions.JavaAgent)) {
agents.registerAgent("instrument", getEnv().getOptions().get(EspressoOptions.JavaAgent), false);
}
if (espressoEnv.EnableAgents) {
agents.initialize();
} else {
if (!agents.isEmpty()) {
getLogger().warning("Agents support is currently disabled in Espresso. Ignoring passed agent options.");
}
}
}
private void initVmProperties() {
EspressoProperties.Builder builder = EspressoProperties.newPlatformBuilder(getEspressoLibs());
builder.javaHome(getEspressoRuntime());
EspressoProperties.processOptions(builder, getEnv().getOptions(), this);
getNativeAccess().updateEspressoProperties(builder, getEnv().getOptions());
vmProperties = builder.build();
}
private void initializeKnownClass(Symbol<Type> type) {
Klass klass = getMeta().loadKlassOrFail(type, StaticObject.NULL, StaticObject.NULL);
klass.safeInitialize();
}
public boolean metaInitialized() {
return metaInitialized;
}
public boolean modulesInitialized() {
return modulesInitialized;
}
public boolean isInitialized() {
return initialized;
}
public InterpreterToVM getInterpreterToVM() {
return interpreterToVM;
}
public VM getVM() {
return vm;
}
private JImageLibrary jimageLibrary() {
if (jimageLibrary == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
EspressoError.guarantee(getJavaVersion().modulesEnabled(), "Jimage available for java >= 9");
this.jimageLibrary = new JImageLibrary(this);
}
return jimageLibrary;
}
public JImageHelper createJImageHelper(String jimagePath) {
if (espressoEnv.JImageMode == EspressoOptions.JImageMode.NATIVE) {
JImageLibrary library = jimageLibrary();
TruffleObject image = library.open(jimagePath);
if (InteropLibrary.getUncached().isNull(image)) {
return null;
}
return new NativeJImageHelper(library, image);
} else {
assert espressoEnv.JImageMode == EspressoOptions.JImageMode.JAVA;
try {
return new JavaJImageHelper(BasicImageReader.open(Paths.get(jimagePath)), this);
} catch (BasicImageReader.NotAnImageFile e) {
return null;
} catch (IOException e) {
logger.log(Level.SEVERE, "failed to open jimage", e);
return null;
}
}
}
public JavaVersion getJavaVersion() {
return getLanguage().getJavaVersion();
}
public boolean advancedRedefinitionEnabled() {
return espressoEnv.JDWPOptions != null;
}
public Types getTypes() {
return getLanguage().getTypes();
}
public Signatures getSignatures() {
return getLanguage().getSignatures();
}
public JniEnv getJNI() {
if (jniEnv == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
jniEnv = JniEnv.create(this);
}
return jniEnv;
}
public void disposeContext() {
synchronized (this) {
if (disposeCalled) {
getLogger().warning("Context is being disposed multiple times");
return;
}
disposeCalled = true;
}
}
public void cleanupNativeEnv() {
if (initialized) {
getVM().dispose();
getJNI().dispose();
}
}
public Substitutions getSubstitutions() {
return substitutions;
}
public void setBootstrapMeta(Meta meta) {
this.meta = meta;
}
public Names getNames() {
return getLanguage().getNames();
}
public MethodHandleIntrinsics getMethodHandleIntrinsics() {
return methodHandleIntrinsics;
}
public EspressoException getStackOverflow() {
return stackOverflow;
}
public EspressoException getOutOfMemory() {
return outOfMemory;
}
public LazyContextCaches getLazyCaches() {
LazyContextCaches cache = this.lazyCaches;
if (cache == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
throw EspressoError.fatal("Accessing lazy context cache before context initialization");
}
return cache;
}
public void prepareDispose() {
if (espressoEnv.getJdwpContext() != null) {
espressoEnv.getJdwpContext().finalizeContext();
}
}
public void registerRedefinitionPlugin(InternalRedefinitionPlugin plugin) {
// lazy initialization
if (redefinitionPlugins == null) {
redefinitionPlugins = Collections.synchronizedMap(new HashMap<>(2));
}
redefinitionPlugins.put(plugin.getClass(), plugin);
}
@SuppressWarnings("unchecked")
@TruffleBoundary
public <T> T lookup(Class<? extends InternalRedefinitionPlugin> pluginType) {
if (redefinitionPlugins == null) {
return null;
}
return (T) redefinitionPlugins.get(pluginType);
}
// region Agents
public TruffleObject bindToAgent(Method method, String mangledName) {
if (espressoEnv.EnableAgents) {
return agents.bind(method, mangledName);
}
return null;
}
// endregion Agents
// region Thread management
public ThreadsAccess getThreadAccess() {
return threads;
}
public BlockingSupport<StaticObject> getBlockingSupport() {
return blockingSupport;
}
/**
* Creates a new guest thread from the host thread, and adds it to the main thread group. This
* thread is not in Espresso's control.
*/
public StaticObject createThread(Thread hostThread) {
return createThread(hostThread, getMainThreadGroup(), null, false);
}
public StaticObject createThread(Thread hostThread, StaticObject group, String name) {
return createThread(hostThread, group, name, true);
}
public StaticObject createThread(Thread hostThread, StaticObject group, String name, boolean managedByEspresso) {
return espressoEnv.getThreadRegistry().createGuestThreadFromHost(hostThread, meta, vm, name, group, managedByEspresso);
}
public void disposeThread(Thread hostThread) {
StaticObject guestThread = getGuestThreadFromHost(hostThread);
if (guestThread == null) {
return;
}
try {
// Cannot run guest code after finalizeContext was called (GR-35712).
if (isFinalized()) {
return;
}
if (hostThread != Thread.currentThread()) {
String guestName = threads.getThreadName(guestThread);
getLogger().warning("unimplemented: disposeThread for non-current thread: " + hostThread + " / " + guestName + ". Called from thread: " + Thread.currentThread());
return;
}
if (vm.DetachCurrentThread(this) != JNI_OK) {
throw new RuntimeException("Could not detach thread correctly");
}
} finally {
unregisterThread(guestThread);
}
}
public StaticObject getGuestThreadFromHost(Thread host) {
return espressoEnv.getThreadRegistry().getGuestThreadFromHost(host);
}
public void registerCurrentThread(StaticObject guestThread) {
getLanguage().getThreadLocalState().initializeCurrentThread(guestThread);
}
public StaticObject getCurrentPlatformThread() {
return getLanguage().getThreadLocalState().getCurrentPlatformThread(this);
}
/**
* Returns the maximum number of alive (registered) threads at any point, since the VM started.
*/
public long getPeakThreadCount() {
return espressoEnv.getThreadRegistry().peakThreadCount.get();
}
public void resetPeakThreadCount() {
espressoEnv.getThreadRegistry().resetPeakThreadCount();
}
/**
* Returns the number of created threads since the VM started.
*/
public long getCreatedThreadCount() {
return espressoEnv.getThreadRegistry().createdThreadCount.get();
}
public StaticObject[] getActiveThreads() {
return espressoEnv.getThreadRegistry().activeThreads();
}
public void registerThread(Thread host, StaticObject self) {
espressoEnv.getThreadRegistry().registerThread(host, self);
if (shouldReportVMEvents()) {
espressoEnv.getEventListener().threadStarted(self);
}
}
public void unregisterThread(StaticObject self) {
boolean unregistered = getEspressoEnv().getThreadRegistry().unregisterThread(self);
if (shouldReportVMEvents() && unregistered) {
getEspressoEnv().getEventListener().threadDied(self);
}
}
public void interruptThread(StaticObject guestThread) {
threads.callInterrupt(guestThread);
}
public boolean isMainThreadCreated() {
return espressoEnv.getThreadRegistry().isMainThreadCreated();
}
public StaticObject getMainThread() {
return espressoEnv.getThreadRegistry().getMainThread();
}
public StaticObject getMainThreadGroup() {
return espressoEnv.getThreadRegistry().getMainThreadGroup();
}
// endregion Thread management
// region Shutdown
public void notifyShutdownSynchronizer() {
EspressoLock lock = shutdownManager.getShutdownSynchronizer();
lock.lock();
try {
lock.signalAll();
} finally {
lock.unlock();
}
}
public void truffleExit(Node location, int exitCode) {
getEnv().getContext().closeExited(location, exitCode);
}
public void doExit(int code) {
shutdownManager.doExit(code);
}
public void destroyVM() {
shutdownManager.destroyVM();
}
public void ensureThreadsJoined() {
// shutdownManager could be null if we are closing a pre-initialized context
if (shutdownManager != null) {
shutdownManager.ensureThreadsJoined();
}
}
public boolean isClosing() {
return shutdownManager.isClosing();
}
public boolean isTruffleClosed() {
return getEnv().getContext().isClosed();
}
public int getExitStatus() {
return shutdownManager.getExitStatus();
}
public EspressoError abort(String message) {
getLogger().severe(message);
throw new EspressoExitException(1);
}
// endregion Shutdown
// region ReferenceDrain
public ReferenceQueue<StaticObject> getReferenceQueue() {
return espressoEnv.getReferenceDrainer().getReferenceQueue();
}
public StaticObject getAndClearReferencePendingList() {
return espressoEnv.getReferenceDrainer().getAndClearReferencePendingList();
}
public boolean hasReferencePendingList() {
return espressoEnv.getReferenceDrainer().hasReferencePendingList();
}
public void waitForReferencePendingList() {
espressoEnv.getReferenceDrainer().waitForReferencePendingList();
}
public void triggerDrain() {
espressoEnv.getReferenceDrainer().triggerDrain();
}
// endregion ReferenceDrain
// region DebugAccess
public TimerCollection getTimers() {
return espressoEnv.getTimers();
}
public EspressoBindings getBindings() {
return topBindings;
}
public StaticObject getBindingsLoader() {
return bindingsLoader;
}
public WeakHashMap<StaticObject, SignalHandler> getHostSignalHandlers() {
return hostSignalHandlers;
}
// endregion DebugAccess
// region VM event reporting
public boolean shouldReportVMEvents() {
return espressoEnv.shouldReportVMEvents();
}
public void reportMonitorWait(StaticObject monitor, long timeout) {
assert shouldReportVMEvents();
espressoEnv.getEventListener().monitorWait(monitor, timeout);
}
public void reportMonitorWaited(StaticObject monitor, boolean timedOut) {
assert shouldReportVMEvents();
espressoEnv.getEventListener().monitorWaited(monitor, timedOut);
}
public void reportClassPrepared(ObjectKlass objectKlass, Object prepareThread) {
assert shouldReportVMEvents();
espressoEnv.getEventListener().classPrepared(objectKlass, prepareThread);
}
public void reportOnContendedMonitorEnter(StaticObject obj) {
assert shouldReportVMEvents();
espressoEnv.getEventListener().onContendedMonitorEnter(obj);
}
public void reportOnContendedMonitorEntered(StaticObject obj) {
assert shouldReportVMEvents();
espressoEnv.getEventListener().onContendedMonitorEntered(obj);
}
public boolean reportOnMethodEntry(Method.MethodVersion method, Object scope) {
assert shouldReportVMEvents();
return espressoEnv.getEventListener().onMethodEntry(method, scope);
}
public boolean reportOnMethodReturn(Method.MethodVersion method, Object returnValue) {
assert shouldReportVMEvents();
return espressoEnv.getEventListener().onMethodReturn(method, returnValue);
}
public boolean reportOnFieldModification(Field field, StaticObject receiver, Object value) {
assert shouldReportVMEvents();
return espressoEnv.getEventListener().onFieldModification(field, receiver, value);
}
public boolean reportOnFieldAccess(Field field, StaticObject receiver) {
assert shouldReportVMEvents();
return espressoEnv.getEventListener().onFieldAccess(field, receiver);
}
// endregion VM event reporting
public void registerExternalHotSwapHandler(StaticObject handler) {
espressoEnv.getJdwpContext().registerExternalHotSwapHandler(handler);
}
public void rerunclinit(ObjectKlass oldKlass) {
espressoEnv.getJdwpContext().rerunclinit(oldKlass);
}
private static final ContextReference<EspressoContext> REFERENCE = ContextReference.create(EspressoLanguage.class);
/**
* Returns the <em>current</em>, thread-local, context.
*/
public static EspressoContext get(Node node) {
return REFERENCE.get(node);
}
public synchronized ClassRedefinition createClassRedefinition(Ids<Object> ids, RedefinitionPluginHandler redefinitionPluginHandler, DebuggerController controller) {
if (classRedefinition == null) {
classRedefinition = new ClassRedefinition(this, ids, redefinitionPluginHandler, controller);
}
return classRedefinition;
}
public ClassRedefinition getClassRedefinition() {
return classRedefinition;
}
public boolean anyHierarchyChanged() {
return !anyHierarchyChanges.isValid();
}
public void markChangedHierarchy() {
anyHierarchyChanges.invalidate();
}
public ClassHierarchyOracle getClassHierarchyOracle() {
return espressoEnv.getClassHierarchyOracle();
}
public boolean isFinalized() {
return isFinalized;
}
public void setFinalized() {
isFinalized = true;
}
public boolean explicitTypeMappingsEnabled() {
return getEspressoEnv().getPolyglotTypeMappings().hasMappings();
}
public boolean interfaceMappingsEnabled() {
return getEspressoEnv().getPolyglotTypeMappings().hasInterfaceMappings();
}
@Idempotent
public boolean regexSubstitutionsEnabled() {
return getEspressoEnv().RegexSubstitutions && getJavaVersion().java21OrLater();
}
public PolyglotTypeMappings getPolyglotTypeMappings() {
return getEspressoEnv().getPolyglotTypeMappings();
}
public EspressoForeignProxyGenerator.GeneratedProxyBytes getProxyBytesOrNull(String metaName) {
if (getEspressoEnv().getProxyCache() != null) {
return getEspressoEnv().getProxyCache().get(metaName);
} else {
return null;
}
}
public void registerProxyBytes(String metaName, EspressoForeignProxyGenerator.GeneratedProxyBytes generatedProxyBytes) {
if (getEspressoEnv().getProxyCache() != null) {
getEspressoEnv().getProxyCache().put(metaName, generatedProxyBytes);
} else {
throw EspressoError.shouldNotReachHere();
}
}
public long nextThreadId() {
return espressoEnv.getThreadRegistry().nextThreadId();
}
public DowncallStubs getDowncallStubs() {
return downcallStubs;
}
public UpcallStubs getUpcallStubs() {
return upcallStubs;
}
public Path getEspressoLibs() {
return EspressoLanguage.getEspressoLibs(getEnv());
}
public Path getEspressoRuntime() {
return EspressoLanguage.getEspressoRuntime(getEnv());
}
}
| oracle/graal | espresso/src/com.oracle.truffle.espresso/src/com/oracle/truffle/espresso/runtime/EspressoContext.java |
180,204 | /*
* Copyright 2014 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc.testing.integration;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.OAuth2Credentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
import com.google.protobuf.MessageLite;
import com.google.protobuf.StringValue;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ClientInterceptors;
import io.grpc.ClientStreamTracer;
import io.grpc.Context;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.ServerStreamTracer;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.auth.MoreCallCredentials;
import io.grpc.census.InternalCensusStatsAccessor;
import io.grpc.census.internal.DeprecatedCensusConstants;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.testing.StatsTestUtils;
import io.grpc.internal.testing.StatsTestUtils.FakeStatsRecorder;
import io.grpc.internal.testing.StatsTestUtils.FakeTagContext;
import io.grpc.internal.testing.StatsTestUtils.FakeTagContextBinarySerializer;
import io.grpc.internal.testing.StatsTestUtils.FakeTagger;
import io.grpc.internal.testing.StatsTestUtils.MetricsRecord;
import io.grpc.internal.testing.StreamRecorder;
import io.grpc.internal.testing.TestClientStreamTracer;
import io.grpc.internal.testing.TestServerStreamTracer;
import io.grpc.internal.testing.TestStreamTracer;
import io.grpc.stub.ClientCallStreamObserver;
import io.grpc.stub.ClientCalls;
import io.grpc.stub.MetadataUtils;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.TestUtils;
import io.grpc.testing.integration.EmptyProtos.Empty;
import io.grpc.testing.integration.Messages.BoolValue;
import io.grpc.testing.integration.Messages.EchoStatus;
import io.grpc.testing.integration.Messages.Payload;
import io.grpc.testing.integration.Messages.ResponseParameters;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import io.grpc.testing.integration.Messages.StreamingInputCallRequest;
import io.grpc.testing.integration.Messages.StreamingInputCallResponse;
import io.grpc.testing.integration.Messages.StreamingOutputCallRequest;
import io.grpc.testing.integration.Messages.StreamingOutputCallResponse;
import io.grpc.testing.integration.Messages.TestOrcaReport;
import io.opencensus.contrib.grpc.metrics.RpcMeasureConstants;
import io.opencensus.stats.Measure;
import io.opencensus.stats.Measure.MeasureDouble;
import io.opencensus.stats.Measure.MeasureLong;
import io.opencensus.tags.TagKey;
import io.opencensus.tags.TagValue;
import io.opencensus.trace.Span;
import io.opencensus.trace.SpanContext;
import io.opencensus.trace.Tracing;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketAddress;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import org.HdrHistogram.Histogram;
import org.junit.After;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
/**
* Abstract base class for all GRPC transport tests.
*
* <p> New tests should avoid using Mockito to support running on AppEngine.</p>
*/
public abstract class AbstractInteropTest {
private static Logger logger = Logger.getLogger(AbstractInteropTest.class.getName());
@Rule public final TestRule globalTimeout;
/** Must be at least {@link #unaryPayloadLength()}, plus some to account for encoding overhead. */
public static final int MAX_MESSAGE_SIZE = 16 * 1024 * 1024;
/**
* Use a small flow control to help detect flow control bugs. Don't use 64KiB to test
* SETTINGS/WINDOW_UPDATE exchange.
*/
public static final int TEST_FLOW_CONTROL_WINDOW = 65 * 1024;
private static final MeasureLong RETRIES_PER_CALL =
Measure.MeasureLong.create(
"grpc.io/client/retries_per_call", "Number of retries per call", "1");
private static final MeasureLong TRANSPARENT_RETRIES_PER_CALL =
Measure.MeasureLong.create(
"grpc.io/client/transparent_retries_per_call", "Transparent retries per call", "1");
private static final MeasureDouble RETRY_DELAY_PER_CALL =
Measure.MeasureDouble.create(
"grpc.io/client/retry_delay_per_call", "Retry delay per call", "ms");
private static final FakeTagger tagger = new FakeTagger();
private static final FakeTagContextBinarySerializer tagContextBinarySerializer =
new FakeTagContextBinarySerializer();
private final AtomicReference<ServerCall<?, ?>> serverCallCapture =
new AtomicReference<>();
private final AtomicReference<ClientCall<?, ?>> clientCallCapture =
new AtomicReference<>();
private final AtomicReference<Metadata> requestHeadersCapture =
new AtomicReference<>();
private final AtomicReference<Context> contextCapture =
new AtomicReference<>();
private final FakeStatsRecorder clientStatsRecorder = new FakeStatsRecorder();
private final FakeStatsRecorder serverStatsRecorder = new FakeStatsRecorder();
private ScheduledExecutorService testServiceExecutor;
private Server server;
private Server handshakerServer;
private final LinkedBlockingQueue<ServerStreamTracerInfo> serverStreamTracers =
new LinkedBlockingQueue<>();
static final CallOptions.Key<AtomicReference<TestOrcaReport>>
ORCA_RPC_REPORT_KEY = CallOptions.Key.create("orca-rpc-report");
static final CallOptions.Key<AtomicReference<TestOrcaReport>>
ORCA_OOB_REPORT_KEY = CallOptions.Key.create("orca-oob-report");
private static final class ServerStreamTracerInfo {
final String fullMethodName;
final InteropServerStreamTracer tracer;
ServerStreamTracerInfo(String fullMethodName, InteropServerStreamTracer tracer) {
this.fullMethodName = fullMethodName;
this.tracer = tracer;
}
private static final class InteropServerStreamTracer extends TestServerStreamTracer {
private volatile Context contextCapture;
@Override
public Context filterContext(Context context) {
contextCapture = context;
return super.filterContext(context);
}
}
}
/**
* Constructor for tests.
*/
protected AbstractInteropTest() {
TestRule timeout = Timeout.seconds(90);
try {
timeout = new DisableOnDebug(timeout);
} catch (Throwable t) {
// This can happen on Android, which lacks some standard Java class.
// Seen at https://github.com/grpc/grpc-java/pull/5832#issuecomment-499698086
logger.log(Level.FINE, "Debugging not disabled.", t);
}
globalTimeout = timeout;
}
private final ServerStreamTracer.Factory serverStreamTracerFactory =
new ServerStreamTracer.Factory() {
@Override
public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) {
ServerStreamTracerInfo.InteropServerStreamTracer tracer
= new ServerStreamTracerInfo.InteropServerStreamTracer();
serverStreamTracers.add(new ServerStreamTracerInfo(fullMethodName, tracer));
return tracer;
}
};
protected static final Empty EMPTY = Empty.getDefaultInstance();
private void configBuilder(@Nullable ServerBuilder<?> builder) {
if (builder == null) {
return;
}
testServiceExecutor = Executors.newScheduledThreadPool(2);
List<ServerInterceptor> allInterceptors = ImmutableList.<ServerInterceptor>builder()
.add(recordServerCallInterceptor(serverCallCapture))
.add(TestUtils.recordRequestHeadersInterceptor(requestHeadersCapture))
.add(recordContextInterceptor(contextCapture))
.addAll(TestServiceImpl.interceptors())
.build();
builder
.addService(
ServerInterceptors.intercept(
new TestServiceImpl(testServiceExecutor),
allInterceptors))
.addStreamTracerFactory(serverStreamTracerFactory);
}
protected void startServer(@Nullable ServerBuilder<?> builder) {
maybeStartHandshakerServer();
if (builder == null) {
server = null;
return;
}
try {
server = builder.build().start();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private void maybeStartHandshakerServer() {
ServerBuilder<?> handshakerServerBuilder = getHandshakerServerBuilder();
if (handshakerServerBuilder != null) {
try {
handshakerServer = handshakerServerBuilder.build().start();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
private void stopServer() {
if (server != null) {
server.shutdownNow();
}
if (testServiceExecutor != null) {
testServiceExecutor.shutdown();
}
if (handshakerServer != null) {
handshakerServer.shutdownNow();
}
}
@VisibleForTesting
final SocketAddress getListenAddress() {
return server.getListenSockets().iterator().next();
}
protected ManagedChannel channel;
protected TestServiceGrpc.TestServiceBlockingStub blockingStub;
protected TestServiceGrpc.TestServiceStub asyncStub;
private final LinkedBlockingQueue<TestClientStreamTracer> clientStreamTracers =
new LinkedBlockingQueue<>();
private boolean enableClientStreamTracers = true;
void setEnableClientStreamTracers(boolean enableClientStreamTracers) {
this.enableClientStreamTracers = enableClientStreamTracers;
}
private final ClientStreamTracer.Factory clientStreamTracerFactory =
new ClientStreamTracer.Factory() {
@Override
public ClientStreamTracer newClientStreamTracer(
ClientStreamTracer.StreamInfo info, Metadata headers) {
TestClientStreamTracer tracer = new TestClientStreamTracer();
clientStreamTracers.add(tracer);
return tracer;
}
};
private final ClientInterceptor tracerSetupInterceptor = new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return next.newCall(
method, callOptions.withStreamTracerFactory(clientStreamTracerFactory));
}
};
/**
* Must be called by the subclass setup method if overridden.
*/
@Before
public void setUp() {
ServerBuilder<?> serverBuilder = getServerBuilder();
configBuilder(serverBuilder);
startServer(serverBuilder);
channel = createChannel();
if (enableClientStreamTracers) {
blockingStub =
TestServiceGrpc.newBlockingStub(channel).withInterceptors(tracerSetupInterceptor);
asyncStub = TestServiceGrpc.newStub(channel).withInterceptors(tracerSetupInterceptor);
} else {
blockingStub = TestServiceGrpc.newBlockingStub(channel);
asyncStub = TestServiceGrpc.newStub(channel);
}
ClientInterceptor[] additionalInterceptors = getAdditionalInterceptors();
if (additionalInterceptors != null) {
blockingStub = blockingStub.withInterceptors(additionalInterceptors);
asyncStub = asyncStub.withInterceptors(additionalInterceptors);
}
requestHeadersCapture.set(null);
}
/** Clean up. */
@After
public void tearDown() {
if (channel != null) {
channel.shutdownNow();
try {
channel.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
logger.log(Level.FINE, "Interrupted while waiting for channel termination", ie);
// Best effort. If there is an interruption, we want to continue cleaning up, but quickly
Thread.currentThread().interrupt();
}
}
stopServer();
}
protected ManagedChannel createChannel() {
return createChannelBuilder().build();
}
protected abstract ManagedChannelBuilder<?> createChannelBuilder();
@Nullable
protected ClientInterceptor[] getAdditionalInterceptors() {
return null;
}
/**
* Returns the server builder used to create server for each test run. Return {@code null} if
* it shouldn't start a server in the same process.
*/
@Nullable
protected ServerBuilder<?> getServerBuilder() {
return null;
}
@Nullable
protected ServerBuilder<?> getHandshakerServerBuilder() {
return null;
}
protected final ClientInterceptor createCensusStatsClientInterceptor() {
return
InternalCensusStatsAccessor
.getClientInterceptor(
tagger, tagContextBinarySerializer, clientStatsRecorder,
GrpcUtil.STOPWATCH_SUPPLIER,
true, true, true,
/* recordRealTimeMetrics= */ false,
/* recordRetryMetrics= */ true);
}
protected final ServerStreamTracer.Factory createCustomCensusTracerFactory() {
return InternalCensusStatsAccessor.getServerStreamTracerFactory(
tagger, tagContextBinarySerializer, serverStatsRecorder,
GrpcUtil.STOPWATCH_SUPPLIER,
true, true, true, false /* real-time metrics */);
}
/**
* Override this when custom census module presence is different from {@link #metricsExpected()}.
*/
protected boolean customCensusModulePresent() {
return metricsExpected();
}
/**
* Return true if exact metric values should be checked.
*/
protected boolean metricsExpected() {
return true;
}
@Test
public void emptyUnary() throws Exception {
assertEquals(EMPTY, blockingStub.emptyCall(EMPTY));
}
@Test
public void emptyUnaryWithRetriableStream() throws Exception {
channel.shutdown();
channel = createChannelBuilder().enableRetry().build();
assertEquals(EMPTY, TestServiceGrpc.newBlockingStub(channel).emptyCall(EMPTY));
}
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */
public void cacheableUnary() {
// THIS TEST IS BROKEN. Enabling safe just on the MethodDescriptor does nothing by itself. This
// test would need to enable GET on the channel.
// Set safe to true.
MethodDescriptor<SimpleRequest, SimpleResponse> safeCacheableUnaryCallMethod =
TestServiceGrpc.getCacheableUnaryCallMethod().toBuilder().setSafe(true).build();
// Set fake user IP since some proxies (GFE) won't cache requests from localhost.
Metadata.Key<String> userIpKey = Metadata.Key.of("x-user-ip", Metadata.ASCII_STRING_MARSHALLER);
Metadata metadata = new Metadata();
metadata.put(userIpKey, "1.2.3.4");
Channel channelWithUserIpKey =
ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata));
SimpleRequest requests1And2 =
SimpleRequest.newBuilder()
.setPayload(
Payload.newBuilder()
.setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
.build();
SimpleRequest request3 =
SimpleRequest.newBuilder()
.setPayload(
Payload.newBuilder()
.setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
.build();
SimpleResponse response1 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
SimpleResponse response2 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
SimpleResponse response3 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, request3);
assertEquals(response1, response2);
assertNotEquals(response1, response3);
// THIS TEST IS BROKEN. See comment at start of method.
}
@Test
public void largeUnary() throws Exception {
assumeEnoughMemory();
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, blockingStub.unaryCall(request));
assertStatsTrace("grpc.testing.TestService/UnaryCall", Status.Code.OK,
Collections.singleton(request), Collections.singleton(goldenResponse));
}
/**
* Tests client per-message compression for unary calls. The Java API does not support inspecting
* a message's compression level, so this is primarily intended to run against a gRPC C++ server.
*/
public void clientCompressedUnary(boolean probe) throws Exception {
assumeEnoughMemory();
final SimpleRequest expectCompressedRequest =
SimpleRequest.newBuilder()
.setExpectCompressed(BoolValue.newBuilder().setValue(true))
.setResponseSize(314159)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleRequest expectUncompressedRequest =
SimpleRequest.newBuilder()
.setExpectCompressed(BoolValue.newBuilder().setValue(false))
.setResponseSize(314159)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse =
SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[314159])))
.build();
if (probe) {
// Send a non-compressed message with expectCompress=true. Servers supporting this test case
// should return INVALID_ARGUMENT.
try {
blockingStub.unaryCall(expectCompressedRequest);
fail("expected INVALID_ARGUMENT");
} catch (StatusRuntimeException e) {
assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatus().getCode());
}
assertStatsTrace("grpc.testing.TestService/UnaryCall", Status.Code.INVALID_ARGUMENT);
}
assertResponse(
goldenResponse, blockingStub.withCompression("gzip").unaryCall(expectCompressedRequest));
assertStatsTrace(
"grpc.testing.TestService/UnaryCall",
Status.Code.OK,
Collections.singleton(expectCompressedRequest),
Collections.singleton(goldenResponse));
assertResponse(goldenResponse, blockingStub.unaryCall(expectUncompressedRequest));
assertStatsTrace(
"grpc.testing.TestService/UnaryCall",
Status.Code.OK,
Collections.singleton(expectUncompressedRequest),
Collections.singleton(goldenResponse));
}
/**
* Tests if the server can send a compressed unary response. Ideally we would assert that the
* responses have the requested compression, but this is not supported by the API. Given a
* compliant server, this test will exercise the code path for receiving a compressed response but
* cannot itself verify that the response was compressed.
*/
@Test
public void serverCompressedUnary() throws Exception {
assumeEnoughMemory();
final SimpleRequest responseShouldBeCompressed =
SimpleRequest.newBuilder()
.setResponseCompressed(BoolValue.newBuilder().setValue(true))
.setResponseSize(314159)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleRequest responseShouldBeUncompressed =
SimpleRequest.newBuilder()
.setResponseCompressed(BoolValue.newBuilder().setValue(false))
.setResponseSize(314159)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse goldenResponse =
SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, blockingStub.unaryCall(responseShouldBeCompressed));
assertStatsTrace(
"grpc.testing.TestService/UnaryCall",
Status.Code.OK,
Collections.singleton(responseShouldBeCompressed),
Collections.singleton(goldenResponse));
assertResponse(goldenResponse, blockingStub.unaryCall(responseShouldBeUncompressed));
assertStatsTrace(
"grpc.testing.TestService/UnaryCall",
Status.Code.OK,
Collections.singleton(responseShouldBeUncompressed),
Collections.singleton(goldenResponse));
}
/**
* Assuming "pick_first" policy is used, tests that all requests are sent to the same server.
*/
public void pickFirstUnary() throws Exception {
SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(1)
.setFillServerId(true)
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[1])))
.build();
SimpleResponse firstResponse = blockingStub.unaryCall(request);
// Increase the chance of all servers are connected, in case the channel should be doing
// round_robin instead.
Thread.sleep(5000);
for (int i = 0; i < 100; i++) {
SimpleResponse response = blockingStub.unaryCall(request);
assertThat(response.getServerId()).isEqualTo(firstResponse.getServerId());
}
}
@Test
public void serverStreaming() throws Exception {
final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(31415))
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(9))
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(2653))
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(58979))
.build();
final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[31415])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[9])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[2653])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[58979])))
.build());
StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
asyncStub.streamingOutputCall(request, recorder);
recorder.awaitCompletion();
assertSuccess(recorder);
assertResponses(goldenResponses, recorder.getValues());
}
@Test
public void clientStreaming() throws Exception {
final List<StreamingInputCallRequest> requests = Arrays.asList(
StreamingInputCallRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[27182])))
.build(),
StreamingInputCallRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[8])))
.build(),
StreamingInputCallRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[1828])))
.build(),
StreamingInputCallRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[45904])))
.build());
final StreamingInputCallResponse goldenResponse = StreamingInputCallResponse.newBuilder()
.setAggregatedPayloadSize(74922)
.build();
StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingInputCallRequest> requestObserver =
asyncStub.streamingInputCall(responseObserver);
for (StreamingInputCallRequest request : requests) {
requestObserver.onNext(request);
}
requestObserver.onCompleted();
assertEquals(goldenResponse, responseObserver.firstValue().get());
responseObserver.awaitCompletion();
assertThat(responseObserver.getValues()).hasSize(1);
Throwable t = responseObserver.getError();
if (t != null) {
throw new AssertionError(t);
}
}
/**
* Tests client per-message compression for streaming calls. The Java API does not support
* inspecting a message's compression level, so this is primarily intended to run against a gRPC
* C++ server.
*/
public void clientCompressedStreaming(boolean probe) throws Exception {
final StreamingInputCallRequest expectCompressedRequest =
StreamingInputCallRequest.newBuilder()
.setExpectCompressed(BoolValue.newBuilder().setValue(true))
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[27182])))
.build();
final StreamingInputCallRequest expectUncompressedRequest =
StreamingInputCallRequest.newBuilder()
.setExpectCompressed(BoolValue.newBuilder().setValue(false))
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[45904])))
.build();
final StreamingInputCallResponse goldenResponse =
StreamingInputCallResponse.newBuilder().setAggregatedPayloadSize(73086).build();
StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingInputCallRequest> requestObserver =
asyncStub.streamingInputCall(responseObserver);
if (probe) {
// Send a non-compressed message with expectCompress=true. Servers supporting this test case
// should return INVALID_ARGUMENT.
requestObserver.onNext(expectCompressedRequest);
responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
Throwable e = responseObserver.getError();
assertNotNull("expected INVALID_ARGUMENT", e);
assertEquals(Status.INVALID_ARGUMENT.getCode(), Status.fromThrowable(e).getCode());
}
// Start a new stream
responseObserver = StreamRecorder.create();
@SuppressWarnings("unchecked")
ClientCallStreamObserver<StreamingInputCallRequest> clientCallStreamObserver =
(ClientCallStreamObserver)
asyncStub.withCompression("gzip").streamingInputCall(responseObserver);
clientCallStreamObserver.setMessageCompression(true);
clientCallStreamObserver.onNext(expectCompressedRequest);
clientCallStreamObserver.setMessageCompression(false);
clientCallStreamObserver.onNext(expectUncompressedRequest);
clientCallStreamObserver.onCompleted();
responseObserver.awaitCompletion();
assertSuccess(responseObserver);
assertEquals(goldenResponse, responseObserver.firstValue().get());
}
/**
* Tests server per-message compression in a streaming response. Ideally we would assert that the
* responses have the requested compression, but this is not supported by the API. Given a
* compliant server, this test will exercise the code path for receiving a compressed response but
* cannot itself verify that the response was compressed.
*/
public void serverCompressedStreaming() throws Exception {
final StreamingOutputCallRequest request =
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(
ResponseParameters.newBuilder()
.setCompressed(BoolValue.newBuilder().setValue(true))
.setSize(31415))
.addResponseParameters(
ResponseParameters.newBuilder()
.setCompressed(BoolValue.newBuilder().setValue(false))
.setSize(92653))
.build();
final List<StreamingOutputCallResponse> goldenResponses =
Arrays.asList(
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[31415])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[92653])))
.build());
StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
asyncStub.streamingOutputCall(request, recorder);
recorder.awaitCompletion();
assertSuccess(recorder);
assertResponses(goldenResponses, recorder.getValues());
}
@Test
public void pingPong() throws Exception {
final List<StreamingOutputCallRequest> requests = Arrays.asList(
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(31415))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[27182])))
.build(),
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(9))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[8])))
.build(),
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(2653))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[1828])))
.build(),
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(58979))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[45904])))
.build());
final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[31415])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[9])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[2653])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[58979])))
.build());
final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(5);
StreamObserver<StreamingOutputCallRequest> requestObserver
= asyncStub.fullDuplexCall(new StreamObserver<StreamingOutputCallResponse>() {
@Override
public void onNext(StreamingOutputCallResponse response) {
queue.add(response);
}
@Override
public void onError(Throwable t) {
queue.add(t);
}
@Override
public void onCompleted() {
queue.add("Completed");
}
});
for (int i = 0; i < requests.size(); i++) {
assertNull(queue.peek());
requestObserver.onNext(requests.get(i));
Object actualResponse = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertNotNull("Timed out waiting for response", actualResponse);
if (actualResponse instanceof Throwable) {
throw new AssertionError(actualResponse);
}
assertResponse(goldenResponses.get(i), (StreamingOutputCallResponse) actualResponse);
}
requestObserver.onCompleted();
assertEquals("Completed", queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
}
@Test
public void emptyStream() throws Exception {
StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestObserver
= asyncStub.fullDuplexCall(responseObserver);
requestObserver.onCompleted();
responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertSuccess(responseObserver);
assertTrue("Expected an empty stream", responseObserver.getValues().isEmpty());
}
@Test
public void cancelAfterBegin() throws Exception {
StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingInputCallRequest> requestObserver =
asyncStub.streamingInputCall(responseObserver);
requestObserver.onError(new RuntimeException());
responseObserver.awaitCompletion();
assertEquals(Arrays.<StreamingInputCallResponse>asList(), responseObserver.getValues());
assertEquals(Status.Code.CANCELLED,
Status.fromThrowable(responseObserver.getError()).getCode());
if (metricsExpected()) {
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(clientStartRecord, "grpc.testing.TestService/StreamingInputCall", true);
// CensusStreamTracerModule record final status in the interceptor, thus is guaranteed to be
// recorded. The tracer stats rely on the stream being created, which is not always the case
// in this test. Therefore we don't check the tracer stats.
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord, "grpc.testing.TestService/StreamingInputCall",
Status.CANCELLED.getCode(), true);
// Do not check server-side metrics, because the status on the server side is undetermined.
}
}
@Test
public void cancelAfterFirstResponse() throws Exception {
final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(31415))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[27182])))
.build();
final StreamingOutputCallResponse goldenResponse = StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[31415])))
.build();
StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestObserver
= asyncStub.fullDuplexCall(responseObserver);
requestObserver.onNext(request);
assertResponse(goldenResponse, responseObserver.firstValue().get());
requestObserver.onError(new RuntimeException());
responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertEquals(1, responseObserver.getValues().size());
assertEquals(Status.Code.CANCELLED,
Status.fromThrowable(responseObserver.getError()).getCode());
assertStatsTrace("grpc.testing.TestService/FullDuplexCall", Status.Code.CANCELLED);
}
@Test
public void fullDuplexCallShouldSucceed() throws Exception {
// Build the request.
List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
StreamingOutputCallRequest.Builder streamingOutputBuilder =
StreamingOutputCallRequest.newBuilder();
for (Integer size : responseSizes) {
streamingOutputBuilder.addResponseParameters(
ResponseParameters.newBuilder().setSize(size).setIntervalUs(0));
}
final StreamingOutputCallRequest request = streamingOutputBuilder.build();
StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestStream =
asyncStub.fullDuplexCall(recorder);
final int numRequests = 10;
List<StreamingOutputCallRequest> requests =
new ArrayList<>(numRequests);
for (int ix = numRequests; ix > 0; --ix) {
requests.add(request);
requestStream.onNext(request);
}
requestStream.onCompleted();
recorder.awaitCompletion();
assertSuccess(recorder);
assertEquals(responseSizes.size() * (long) numRequests, recorder.getValues().size());
for (int ix = 0; ix < recorder.getValues().size(); ++ix) {
StreamingOutputCallResponse response = recorder.getValues().get(ix);
int length = response.getPayload().getBody().size();
int expectedSize = responseSizes.get(ix % responseSizes.size());
assertEquals("comparison failed at index " + ix, expectedSize, length);
}
assertStatsTrace("grpc.testing.TestService/FullDuplexCall", Status.Code.OK, requests,
recorder.getValues());
}
@Test
public void halfDuplexCallShouldSucceed() throws Exception {
// Build the request.
List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
StreamingOutputCallRequest.Builder streamingOutputBuilder =
StreamingOutputCallRequest.newBuilder();
for (Integer size : responseSizes) {
streamingOutputBuilder.addResponseParameters(
ResponseParameters.newBuilder().setSize(size).setIntervalUs(0));
}
final StreamingOutputCallRequest request = streamingOutputBuilder.build();
StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestStream = asyncStub.halfDuplexCall(recorder);
final int numRequests = 10;
for (int ix = numRequests; ix > 0; --ix) {
requestStream.onNext(request);
}
requestStream.onCompleted();
recorder.awaitCompletion();
assertSuccess(recorder);
assertEquals(responseSizes.size() * (long) numRequests, recorder.getValues().size());
for (int ix = 0; ix < recorder.getValues().size(); ++ix) {
StreamingOutputCallResponse response = recorder.getValues().get(ix);
int length = response.getPayload().getBody().size();
int expectedSize = responseSizes.get(ix % responseSizes.size());
assertEquals("comparison failed at index " + ix, expectedSize, length);
}
}
@Test
public void serverStreamingShouldBeFlowControlled() throws Exception {
final StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(100000))
.addResponseParameters(ResponseParameters.newBuilder().setSize(100001))
.build();
final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[100000]))).build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[100001]))).build());
long start = System.nanoTime();
final ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<>(10);
ClientCall<StreamingOutputCallRequest, StreamingOutputCallResponse> call =
channel.newCall(TestServiceGrpc.getStreamingOutputCallMethod(), CallOptions.DEFAULT);
call.start(new ClientCall.Listener<StreamingOutputCallResponse>() {
@Override
public void onHeaders(Metadata headers) {}
@Override
public void onMessage(final StreamingOutputCallResponse message) {
queue.add(message);
}
@Override
public void onClose(Status status, Metadata trailers) {
queue.add(status);
}
}, new Metadata());
call.sendMessage(request);
call.halfClose();
// Time how long it takes to get the first response.
call.request(1);
Object response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertTrue(response instanceof StreamingOutputCallResponse);
assertResponse(goldenResponses.get(0), (StreamingOutputCallResponse) response);
long firstCallDuration = System.nanoTime() - start;
// Without giving additional flow control, make sure that we don't get another response. We wait
// until we are comfortable the next message isn't coming. We may have very low nanoTime
// resolution (like on Windows) or be using a testing, in-process transport where message
// handling is instantaneous. In both cases, firstCallDuration may be 0, so round up sleep time
// to at least 1ms.
assertNull(queue.poll(Math.max(firstCallDuration * 4, 1 * 1000 * 1000), TimeUnit.NANOSECONDS));
// Make sure that everything still completes.
call.request(1);
response = queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertTrue(response instanceof StreamingOutputCallResponse);
assertResponse(goldenResponses.get(1), (StreamingOutputCallResponse) response);
assertEquals(Status.OK, queue.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
}
@Test
public void veryLargeRequest() throws Exception {
assumeEnoughMemory();
final SimpleRequest request = SimpleRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[unaryPayloadLength()])))
.setResponseSize(10)
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[10])))
.build();
assertResponse(goldenResponse, blockingStub.unaryCall(request));
}
@Test
public void veryLargeResponse() throws Exception {
assumeEnoughMemory();
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(unaryPayloadLength())
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[unaryPayloadLength()])))
.build();
assertResponse(goldenResponse, blockingStub.unaryCall(request));
}
@Test
public void exchangeMetadataUnaryCall() throws Exception {
// Capture the metadata exchange
Metadata fixedHeaders = new Metadata();
// Send a metadata proto
StringValue metadataValue = StringValue.newBuilder().setValue("dog").build();
fixedHeaders.put(Util.METADATA_KEY, metadataValue);
// .. and expect it to be echoed back in trailers
AtomicReference<Metadata> trailersCapture = new AtomicReference<>();
AtomicReference<Metadata> headersCapture = new AtomicReference<>();
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub.withInterceptors(
MetadataUtils.newAttachHeadersInterceptor(fixedHeaders),
MetadataUtils.newCaptureMetadataInterceptor(headersCapture, trailersCapture));
assertNotNull(stub.emptyCall(EMPTY));
// Assert that our side channel object is echoed back in both headers and trailers
Assert.assertEquals(metadataValue, headersCapture.get().get(Util.METADATA_KEY));
Assert.assertEquals(metadataValue, trailersCapture.get().get(Util.METADATA_KEY));
}
@Test
public void exchangeMetadataStreamingCall() throws Exception {
// Capture the metadata exchange
Metadata fixedHeaders = new Metadata();
// Send a metadata proto
StringValue metadataValue = StringValue.newBuilder().setValue("dog").build();
fixedHeaders.put(Util.METADATA_KEY, metadataValue);
// .. and expect it to be echoed back in trailers
AtomicReference<Metadata> trailersCapture = new AtomicReference<>();
AtomicReference<Metadata> headersCapture = new AtomicReference<>();
TestServiceGrpc.TestServiceStub stub = asyncStub.withInterceptors(
MetadataUtils.newAttachHeadersInterceptor(fixedHeaders),
MetadataUtils.newCaptureMetadataInterceptor(headersCapture, trailersCapture));
List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200);
Messages.StreamingOutputCallRequest.Builder streamingOutputBuilder =
Messages.StreamingOutputCallRequest.newBuilder();
for (Integer size : responseSizes) {
streamingOutputBuilder.addResponseParameters(
ResponseParameters.newBuilder().setSize(size).setIntervalUs(0));
}
final Messages.StreamingOutputCallRequest request = streamingOutputBuilder.build();
StreamRecorder<Messages.StreamingOutputCallResponse> recorder = StreamRecorder.create();
StreamObserver<Messages.StreamingOutputCallRequest> requestStream =
stub.fullDuplexCall(recorder);
final int numRequests = 10;
for (int ix = numRequests; ix > 0; --ix) {
requestStream.onNext(request);
}
requestStream.onCompleted();
recorder.awaitCompletion();
assertSuccess(recorder);
org.junit.Assert.assertEquals(
responseSizes.size() * (long) numRequests, recorder.getValues().size());
// Assert that our side channel object is echoed back in both headers and trailers
Assert.assertEquals(metadataValue, headersCapture.get().get(Util.METADATA_KEY));
Assert.assertEquals(metadataValue, trailersCapture.get().get(Util.METADATA_KEY));
}
@Test
public void sendsTimeoutHeader() {
Assume.assumeTrue("can not capture request headers on server side", server != null);
long configuredTimeoutMinutes = 100;
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(configuredTimeoutMinutes, TimeUnit.MINUTES);
stub.emptyCall(EMPTY);
long transferredTimeoutMinutes = TimeUnit.NANOSECONDS.toMinutes(
requestHeadersCapture.get().get(GrpcUtil.TIMEOUT_KEY));
Assert.assertTrue(
"configuredTimeoutMinutes=" + configuredTimeoutMinutes
+ ", transferredTimeoutMinutes=" + transferredTimeoutMinutes,
configuredTimeoutMinutes - transferredTimeoutMinutes >= 0
&& configuredTimeoutMinutes - transferredTimeoutMinutes <= 1);
}
@Test
public void deadlineNotExceeded() {
// warm up the channel and JVM
blockingStub.emptyCall(Empty.getDefaultInstance());
blockingStub
.withDeadlineAfter(10, TimeUnit.SECONDS)
.streamingOutputCall(StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setIntervalUs(0))
.build()).next();
}
@Test
public void deadlineExceeded() throws Exception {
// warm up the channel and JVM
blockingStub.emptyCall(Empty.getDefaultInstance());
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(1, TimeUnit.SECONDS);
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setIntervalUs((int) TimeUnit.SECONDS.toMicros(20)))
.build();
try {
stub.streamingOutputCall(request).next();
fail("Expected deadline to be exceeded");
} catch (StatusRuntimeException ex) {
assertEquals(Status.DEADLINE_EXCEEDED.getCode(), ex.getStatus().getCode());
String desc = ex.getStatus().getDescription();
assertTrue(desc,
// There is a race between client and server-side deadline expiration.
// If client expires first, it'd generate this message
Pattern.matches("CallOptions deadline exceeded after .*s. \\[.*\\]", desc)
// If server expires first, it'd reset the stream and client would generate a different
// message
|| desc.startsWith("ClientCall was cancelled at or after deadline."));
}
assertStatsTrace("grpc.testing.TestService/EmptyCall", Status.Code.OK);
if (metricsExpected()) {
// Stream may not have been created before deadline is exceeded, thus we don't test the tracer
// stats.
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(
clientStartRecord, "grpc.testing.TestService/StreamingOutputCall", true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord,
"grpc.testing.TestService/StreamingOutputCall",
Status.Code.DEADLINE_EXCEEDED, true);
// Do not check server-side metrics, because the status on the server side is undetermined.
}
}
@Test
public void deadlineExceededServerStreaming() throws Exception {
// warm up the channel and JVM
blockingStub.emptyCall(Empty.getDefaultInstance());
assertStatsTrace("grpc.testing.TestService/EmptyCall", Status.Code.OK);
ResponseParameters.Builder responseParameters = ResponseParameters.newBuilder()
.setSize(1)
.setIntervalUs(10000);
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(responseParameters)
.addResponseParameters(responseParameters)
.addResponseParameters(responseParameters)
.addResponseParameters(responseParameters)
.build();
StreamRecorder<StreamingOutputCallResponse> recorder = StreamRecorder.create();
asyncStub
.withDeadlineAfter(30, TimeUnit.MILLISECONDS)
.streamingOutputCall(request, recorder);
recorder.awaitCompletion();
assertEquals(Status.DEADLINE_EXCEEDED.getCode(),
Status.fromThrowable(recorder.getError()).getCode());
if (metricsExpected()) {
// Stream may not have been created when deadline is exceeded, thus we don't check tracer
// stats.
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(
clientStartRecord, "grpc.testing.TestService/StreamingOutputCall", true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord,
"grpc.testing.TestService/StreamingOutputCall",
Status.Code.DEADLINE_EXCEEDED, true);
// Do not check server-side metrics, because the status on the server side is undetermined.
}
}
@Test
public void deadlineInPast() throws Exception {
// Test once with idle channel and once with active channel
try {
blockingStub
.withDeadlineAfter(-10, TimeUnit.SECONDS)
.emptyCall(Empty.getDefaultInstance());
fail("Should have thrown");
} catch (StatusRuntimeException ex) {
assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
assertThat(ex.getStatus().getDescription())
.startsWith("ClientCall started after CallOptions deadline was exceeded");
}
// CensusStreamTracerModule record final status in the interceptor, thus is guaranteed to be
// recorded. The tracer stats rely on the stream being created, which is not the case if
// deadline is exceeded before the call is created. Therefore we don't check the tracer stats.
if (metricsExpected()) {
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(clientStartRecord, "grpc.testing.TestService/EmptyCall", true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord, "grpc.testing.TestService/EmptyCall",
Status.DEADLINE_EXCEEDED.getCode(), true);
assertZeroRetryRecorded();
}
// warm up the channel
blockingStub.emptyCall(Empty.getDefaultInstance());
if (metricsExpected()) {
// clientStartRecord
clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
// clientEndRecord
clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
assertZeroRetryRecorded();
}
try {
blockingStub
.withDeadlineAfter(-10, TimeUnit.SECONDS)
.emptyCall(Empty.getDefaultInstance());
fail("Should have thrown");
} catch (StatusRuntimeException ex) {
assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
assertThat(ex.getStatus().getDescription())
.startsWith("ClientCall started after CallOptions deadline was exceeded");
}
if (metricsExpected()) {
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(clientStartRecord, "grpc.testing.TestService/EmptyCall", true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord, "grpc.testing.TestService/EmptyCall",
Status.DEADLINE_EXCEEDED.getCode(), true);
assertZeroRetryRecorded();
}
}
@Test
public void maxInboundSize_exact() {
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(1))
.build();
MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
TestServiceGrpc.getStreamingOutputCallMethod();
ByteSizeMarshaller<StreamingOutputCallResponse> mar =
new ByteSizeMarshaller<>(md.getResponseMarshaller());
blockingServerStreamingCall(
blockingStub.getChannel(),
md.toBuilder(md.getRequestMarshaller(), mar).build(),
blockingStub.getCallOptions(),
request)
.next();
int size = mar.lastInSize;
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withMaxInboundMessageSize(size);
stub.streamingOutputCall(request).next();
}
@Test
public void maxInboundSize_tooBig() {
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(1))
.build();
MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
TestServiceGrpc.getStreamingOutputCallMethod();
ByteSizeMarshaller<StreamingOutputCallRequest> mar =
new ByteSizeMarshaller<>(md.getRequestMarshaller());
blockingServerStreamingCall(
blockingStub.getChannel(),
md.toBuilder(mar, md.getResponseMarshaller()).build(),
blockingStub.getCallOptions(),
request)
.next();
int size = mar.lastOutSize;
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withMaxInboundMessageSize(size - 1);
try {
stub.streamingOutputCall(request).next();
fail();
} catch (StatusRuntimeException ex) {
Status s = ex.getStatus();
assertWithMessage(s.toString()).that(s.getCode()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED);
assertThat(Throwables.getStackTraceAsString(ex)).contains("exceeds maximum");
}
}
@Test
public void maxOutboundSize_exact() {
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(1))
.build();
MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
TestServiceGrpc.getStreamingOutputCallMethod();
ByteSizeMarshaller<StreamingOutputCallRequest> mar =
new ByteSizeMarshaller<>(md.getRequestMarshaller());
blockingServerStreamingCall(
blockingStub.getChannel(),
md.toBuilder(mar, md.getResponseMarshaller()).build(),
blockingStub.getCallOptions(),
request)
.next();
int size = mar.lastOutSize;
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withMaxOutboundMessageSize(size);
stub.streamingOutputCall(request).next();
}
@Test
public void maxOutboundSize_tooBig() {
// set at least one field to ensure the size is non-zero.
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(1))
.build();
MethodDescriptor<StreamingOutputCallRequest, StreamingOutputCallResponse> md =
TestServiceGrpc.getStreamingOutputCallMethod();
ByteSizeMarshaller<StreamingOutputCallRequest> mar =
new ByteSizeMarshaller<>(md.getRequestMarshaller());
blockingServerStreamingCall(
blockingStub.getChannel(),
md.toBuilder(mar, md.getResponseMarshaller()).build(),
blockingStub.getCallOptions(),
request)
.next();
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withMaxOutboundMessageSize(mar.lastOutSize - 1);
try {
stub.streamingOutputCall(request).next();
fail();
} catch (StatusRuntimeException ex) {
Status s = ex.getStatus();
assertWithMessage(s.toString()).that(s.getCode()).isEqualTo(Status.Code.CANCELLED);
assertThat(Throwables.getStackTraceAsString(ex)).contains("message too large");
}
}
protected int unaryPayloadLength() {
// 10MiB.
return 10485760;
}
@Test
public void gracefulShutdown() throws Exception {
final List<StreamingOutputCallRequest> requests = Arrays.asList(
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(3))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[2])))
.build(),
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(1))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[7])))
.build(),
StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder()
.setSize(4))
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[1])))
.build());
final List<StreamingOutputCallResponse> goldenResponses = Arrays.asList(
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[3])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[1])))
.build(),
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[4])))
.build());
final ArrayBlockingQueue<StreamingOutputCallResponse> responses =
new ArrayBlockingQueue<>(3);
final SettableFuture<Void> completed = SettableFuture.create();
final SettableFuture<Void> errorSeen = SettableFuture.create();
StreamObserver<StreamingOutputCallResponse> responseObserver =
new StreamObserver<StreamingOutputCallResponse>() {
@Override
public void onNext(StreamingOutputCallResponse value) {
responses.add(value);
}
@Override
public void onError(Throwable t) {
errorSeen.set(null);
}
@Override
public void onCompleted() {
completed.set(null);
}
};
StreamObserver<StreamingOutputCallRequest> requestObserver
= asyncStub.fullDuplexCall(responseObserver);
requestObserver.onNext(requests.get(0));
assertResponse(
goldenResponses.get(0), responses.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
// Initiate graceful shutdown.
channel.shutdown();
requestObserver.onNext(requests.get(1));
assertResponse(
goldenResponses.get(1), responses.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
// The previous ping-pong could have raced with the shutdown, but this one certainly shouldn't.
requestObserver.onNext(requests.get(2));
assertResponse(
goldenResponses.get(2), responses.poll(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
assertFalse(completed.isDone());
requestObserver.onCompleted();
completed.get(operationTimeoutMillis(), TimeUnit.MILLISECONDS);
assertFalse(errorSeen.isDone());
}
@Test
public void customMetadata() throws Exception {
final int responseSize = 314159;
final int requestSize = 271828;
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(responseSize)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[requestSize])))
.build();
final StreamingOutputCallRequest streamingRequest = StreamingOutputCallRequest.newBuilder()
.addResponseParameters(ResponseParameters.newBuilder().setSize(responseSize))
.setPayload(Payload.newBuilder().setBody(ByteString.copyFrom(new byte[requestSize])))
.build();
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[responseSize])))
.build();
final StreamingOutputCallResponse goldenStreamingResponse =
StreamingOutputCallResponse.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[responseSize])))
.build();
final byte[] trailingBytes =
{(byte) 0xa, (byte) 0xb, (byte) 0xa, (byte) 0xb, (byte) 0xa, (byte) 0xb};
// Test UnaryCall
Metadata metadata = new Metadata();
metadata.put(Util.ECHO_INITIAL_METADATA_KEY, "test_initial_metadata_value");
metadata.put(Util.ECHO_TRAILING_METADATA_KEY, trailingBytes);
AtomicReference<Metadata> headersCapture = new AtomicReference<>();
AtomicReference<Metadata> trailersCapture = new AtomicReference<>();
TestServiceGrpc.TestServiceBlockingStub blockingStub = this.blockingStub.withInterceptors(
MetadataUtils.newAttachHeadersInterceptor(metadata),
MetadataUtils.newCaptureMetadataInterceptor(headersCapture, trailersCapture));
SimpleResponse response = blockingStub.unaryCall(request);
assertResponse(goldenResponse, response);
assertEquals("test_initial_metadata_value",
headersCapture.get().get(Util.ECHO_INITIAL_METADATA_KEY));
assertTrue(
Arrays.equals(trailingBytes, trailersCapture.get().get(Util.ECHO_TRAILING_METADATA_KEY)));
assertStatsTrace("grpc.testing.TestService/UnaryCall", Status.Code.OK,
Collections.singleton(request), Collections.singleton(goldenResponse));
// Test FullDuplexCall
metadata = new Metadata();
metadata.put(Util.ECHO_INITIAL_METADATA_KEY, "test_initial_metadata_value");
metadata.put(Util.ECHO_TRAILING_METADATA_KEY, trailingBytes);
headersCapture = new AtomicReference<>();
trailersCapture = new AtomicReference<>();
TestServiceGrpc.TestServiceStub stub = asyncStub.withInterceptors(
MetadataUtils.newAttachHeadersInterceptor(metadata),
MetadataUtils.newCaptureMetadataInterceptor(headersCapture, trailersCapture));
StreamRecorder<Messages.StreamingOutputCallResponse> recorder = StreamRecorder.create();
StreamObserver<Messages.StreamingOutputCallRequest> requestStream =
stub.fullDuplexCall(recorder);
requestStream.onNext(streamingRequest);
requestStream.onCompleted();
recorder.awaitCompletion();
assertSuccess(recorder);
assertResponse(goldenStreamingResponse, recorder.firstValue().get());
assertEquals("test_initial_metadata_value",
headersCapture.get().get(Util.ECHO_INITIAL_METADATA_KEY));
assertTrue(
Arrays.equals(trailingBytes, trailersCapture.get().get(Util.ECHO_TRAILING_METADATA_KEY)));
assertStatsTrace("grpc.testing.TestService/FullDuplexCall", Status.Code.OK,
Collections.singleton(streamingRequest), Collections.singleton(goldenStreamingResponse));
}
@SuppressWarnings("deprecation")
@Test(timeout = 10000)
public void censusContextsPropagated() {
Assume.assumeTrue("Skip the test because server is not in the same process.", server != null);
Assume.assumeTrue(customCensusModulePresent());
Span clientParentSpan = Tracing.getTracer().spanBuilder("Test.interopTest").startSpan();
// A valid ID is guaranteed to be unique, so we can verify it is actually propagated.
assertTrue(clientParentSpan.getContext().getTraceId().isValid());
Context ctx =
io.opencensus.tags.unsafe.ContextUtils.withValue(
Context.ROOT,
tagger
.emptyBuilder()
.putLocal(StatsTestUtils.EXTRA_TAG, TagValue.create("extra value"))
.build());
ctx = io.opencensus.trace.unsafe.ContextUtils.withValue(ctx, clientParentSpan);
Context origCtx = ctx.attach();
try {
blockingStub.unaryCall(SimpleRequest.getDefaultInstance());
Context serverCtx = contextCapture.get();
assertNotNull(serverCtx);
FakeTagContext statsCtx =
(FakeTagContext) io.opencensus.tags.unsafe.ContextUtils.getValue(serverCtx);
assertNotNull(statsCtx);
Map<TagKey, TagValue> tags = statsCtx.getTags();
boolean tagFound = false;
for (Map.Entry<TagKey, TagValue> tag : tags.entrySet()) {
if (tag.getKey().equals(StatsTestUtils.EXTRA_TAG)) {
assertEquals(TagValue.create("extra value"), tag.getValue());
tagFound = true;
}
}
assertTrue("tag not found", tagFound);
Span span = io.opencensus.trace.unsafe.ContextUtils.getValue(serverCtx);
assertNotNull(span);
SpanContext spanContext = span.getContext();
assertEquals(clientParentSpan.getContext().getTraceId(), spanContext.getTraceId());
} finally {
ctx.detach(origCtx);
}
}
@Test
public void statusCodeAndMessage() throws Exception {
int errorCode = 2;
String errorMessage = "test status message";
EchoStatus responseStatus = EchoStatus.newBuilder()
.setCode(errorCode)
.setMessage(errorMessage)
.build();
SimpleRequest simpleRequest = SimpleRequest.newBuilder()
.setResponseStatus(responseStatus)
.build();
StreamingOutputCallRequest streamingRequest = StreamingOutputCallRequest.newBuilder()
.setResponseStatus(responseStatus)
.build();
// Test UnaryCall
try {
blockingStub.unaryCall(simpleRequest);
fail();
} catch (StatusRuntimeException e) {
assertEquals(Status.UNKNOWN.getCode(), e.getStatus().getCode());
assertEquals(errorMessage, e.getStatus().getDescription());
}
assertStatsTrace("grpc.testing.TestService/UnaryCall", Status.Code.UNKNOWN);
// Test FullDuplexCall
StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestObserver
= asyncStub.fullDuplexCall(responseObserver);
requestObserver.onNext(streamingRequest);
requestObserver.onCompleted();
assertThat(responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS))
.isTrue();
assertThat(responseObserver.getError()).isNotNull();
Status status = Status.fromThrowable(responseObserver.getError());
assertEquals(Status.UNKNOWN.getCode(), status.getCode());
assertEquals(errorMessage, status.getDescription());
assertStatsTrace("grpc.testing.TestService/FullDuplexCall", Status.Code.UNKNOWN);
}
@Test
public void specialStatusMessage() throws Exception {
int errorCode = 2;
String errorMessage = "\t\ntest with whitespace\r\nand Unicode BMP ☺ and non-BMP 😈\t\n";
SimpleRequest simpleRequest = SimpleRequest.newBuilder()
.setResponseStatus(EchoStatus.newBuilder()
.setCode(errorCode)
.setMessage(errorMessage)
.build())
.build();
try {
blockingStub.unaryCall(simpleRequest);
fail();
} catch (StatusRuntimeException e) {
assertEquals(Status.UNKNOWN.getCode(), e.getStatus().getCode());
assertEquals(errorMessage, e.getStatus().getDescription());
}
assertStatsTrace("grpc.testing.TestService/UnaryCall", Status.Code.UNKNOWN);
}
/** Sends an rpc to an unimplemented method within TestService. */
@Test
public void unimplementedMethod() {
try {
blockingStub.unimplementedCall(Empty.getDefaultInstance());
fail();
} catch (StatusRuntimeException e) {
assertEquals(Status.UNIMPLEMENTED.getCode(), e.getStatus().getCode());
}
assertClientStatsTrace("grpc.testing.TestService/UnimplementedCall",
Status.Code.UNIMPLEMENTED);
}
/** Sends an rpc to an unimplemented service on the server. */
@Test
public void unimplementedService() {
UnimplementedServiceGrpc.UnimplementedServiceBlockingStub stub =
UnimplementedServiceGrpc.newBlockingStub(channel).withInterceptors(tracerSetupInterceptor);
try {
stub.unimplementedCall(Empty.getDefaultInstance());
fail();
} catch (StatusRuntimeException e) {
assertEquals(Status.UNIMPLEMENTED.getCode(), e.getStatus().getCode());
}
assertStatsTrace("grpc.testing.UnimplementedService/UnimplementedCall",
Status.Code.UNIMPLEMENTED);
}
/** Start a fullDuplexCall which the server will not respond, and verify the deadline expires. */
@SuppressWarnings("MissingFail")
@Test
public void timeoutOnSleepingServer() throws Exception {
TestServiceGrpc.TestServiceStub stub =
asyncStub.withDeadlineAfter(1, TimeUnit.MILLISECONDS);
StreamRecorder<StreamingOutputCallResponse> responseObserver = StreamRecorder.create();
StreamObserver<StreamingOutputCallRequest> requestObserver
= stub.fullDuplexCall(responseObserver);
StreamingOutputCallRequest request = StreamingOutputCallRequest.newBuilder()
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[27182])))
.build();
try {
requestObserver.onNext(request);
} catch (IllegalStateException expected) {
// This can happen if the stream has already been terminated due to deadline exceeded.
}
assertTrue(responseObserver.awaitCompletion(operationTimeoutMillis(), TimeUnit.MILLISECONDS));
assertEquals(0, responseObserver.getValues().size());
assertEquals(Status.DEADLINE_EXCEEDED.getCode(),
Status.fromThrowable(responseObserver.getError()).getCode());
if (metricsExpected()) {
// CensusStreamTracerModule record final status in the interceptor, thus is guaranteed to be
// recorded. The tracer stats rely on the stream being created, which is not always the case
// in this test, thus we will not check that.
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkStartTags(clientStartRecord, "grpc.testing.TestService/FullDuplexCall", true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
checkEndTags(
clientEndRecord,
"grpc.testing.TestService/FullDuplexCall",
Status.DEADLINE_EXCEEDED.getCode(), true);
}
}
/**
* Verifies remote server address and local client address are available from ClientCall
* Attributes via ClientInterceptor.
*/
@Test
public void getServerAddressAndLocalAddressFromClient() {
assertNotNull(obtainRemoteServerAddr());
assertNotNull(obtainLocalClientAddr());
}
/**
* Test backend metrics per query reporting: expect the test client LB policy to receive load
* reports.
*/
public void testOrcaPerRpc() throws Exception {
AtomicReference<TestOrcaReport> reportHolder = new AtomicReference<>();
TestOrcaReport answer = TestOrcaReport.newBuilder()
.setCpuUtilization(0.8210)
.setMemoryUtilization(0.5847)
.putRequestCost("cost", 3456.32)
.putUtilization("util", 0.30499)
.build();
blockingStub.withOption(ORCA_RPC_REPORT_KEY, reportHolder).unaryCall(
SimpleRequest.newBuilder().setOrcaPerQueryReport(answer).build());
assertThat(reportHolder.get()).isEqualTo(answer);
}
/**
* Test backend metrics OOB reporting: expect the test client LB policy to receive load reports.
*/
public void testOrcaOob() throws Exception {
AtomicReference<TestOrcaReport> reportHolder = new AtomicReference<>();
final TestOrcaReport answer = TestOrcaReport.newBuilder()
.setCpuUtilization(0.8210)
.setMemoryUtilization(0.5847)
.putUtilization("util", 0.30499)
.build();
final TestOrcaReport answer2 = TestOrcaReport.newBuilder()
.setCpuUtilization(0.29309)
.setMemoryUtilization(0.2)
.putUtilization("util", 0.2039)
.build();
final int retryLimit = 5;
BlockingQueue<Object> queue = new LinkedBlockingQueue<>();
final Object lastItem = new Object();
StreamObserver<StreamingOutputCallRequest> streamObserver =
asyncStub.fullDuplexCall(new StreamObserver<StreamingOutputCallResponse>() {
@Override
public void onNext(StreamingOutputCallResponse value) {
queue.add(value);
}
@Override
public void onError(Throwable t) {
queue.add(t);
}
@Override
public void onCompleted() {
queue.add(lastItem);
}
});
streamObserver.onNext(StreamingOutputCallRequest.newBuilder()
.setOrcaOobReport(answer)
.addResponseParameters(ResponseParameters.newBuilder().setSize(1).build()).build());
assertThat(queue.take()).isInstanceOf(StreamingOutputCallResponse.class);
int i = 0;
for (; i < retryLimit; i++) {
Thread.sleep(1000);
blockingStub.withOption(ORCA_OOB_REPORT_KEY, reportHolder).emptyCall(EMPTY);
if (answer.equals(reportHolder.get())) {
break;
}
}
assertThat(i).isLessThan(retryLimit);
streamObserver.onNext(StreamingOutputCallRequest.newBuilder()
.setOrcaOobReport(answer2)
.addResponseParameters(ResponseParameters.newBuilder().setSize(1).build()).build());
assertThat(queue.take()).isInstanceOf(StreamingOutputCallResponse.class);
for (i = 0; i < retryLimit; i++) {
Thread.sleep(1000);
blockingStub.withOption(ORCA_OOB_REPORT_KEY, reportHolder).emptyCall(EMPTY);
if (reportHolder.get().equals(answer2)) {
break;
}
}
assertThat(i).isLessThan(retryLimit);
streamObserver.onCompleted();
assertThat(queue.take()).isSameInstanceAs(lastItem);
}
/** Sends a large unary rpc with service account credentials. */
public void serviceAccountCreds(String jsonKey, InputStream credentialsStream, String authScope)
throws Exception {
// cast to ServiceAccountCredentials to double-check the right type of object was created.
GoogleCredentials credentials =
ServiceAccountCredentials.class.cast(GoogleCredentials.fromStream(credentialsStream));
credentials = credentials.createScoped(Arrays.asList(authScope));
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withCallCredentials(MoreCallCredentials.from(credentials));
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setFillOauthScope(true)
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse response = stub.unaryCall(request);
assertFalse(response.getUsername().isEmpty());
assertTrue("Received username: " + response.getUsername(),
jsonKey.contains(response.getUsername()));
assertFalse(response.getOauthScope().isEmpty());
assertTrue("Received oauth scope: " + response.getOauthScope(),
authScope.contains(response.getOauthScope()));
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setOauthScope(response.getOauthScope())
.setUsername(response.getUsername())
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, response);
}
/** Sends a large unary rpc with compute engine credentials. */
public void computeEngineCreds(String serviceAccount, String oauthScope) throws Exception {
ComputeEngineCredentials credentials = ComputeEngineCredentials.create();
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withCallCredentials(MoreCallCredentials.from(credentials));
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setFillOauthScope(true)
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse response = stub.unaryCall(request);
assertEquals(serviceAccount, response.getUsername());
assertFalse(response.getOauthScope().isEmpty());
assertTrue("Received oauth scope: " + response.getOauthScope(),
oauthScope.contains(response.getOauthScope()));
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setOauthScope(response.getOauthScope())
.setUsername(response.getUsername())
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, response);
}
/** Sends an unary rpc with ComputeEngineChannelBuilder. */
public void computeEngineChannelCredentials(
String defaultServiceAccount,
TestServiceGrpc.TestServiceBlockingStub computeEngineStub) throws Exception {
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse response = computeEngineStub.unaryCall(request);
assertEquals(defaultServiceAccount, response.getUsername());
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setUsername(defaultServiceAccount)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, response);
}
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
final SimpleRequest request = SimpleRequest.newBuilder()
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.setFillUsername(true)
.build();
ServiceAccountCredentials credentials = (ServiceAccountCredentials)
GoogleCredentials.fromStream(serviceAccountJson);
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withCallCredentials(MoreCallCredentials.from(credentials));
SimpleResponse response = stub.unaryCall(request);
assertEquals(credentials.getClientEmail(), response.getUsername());
assertEquals(314159, response.getPayload().getBody().size());
}
/** Sends a unary rpc with raw oauth2 access token credentials. */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope)
throws Exception {
GoogleCredentials utilCredentials =
GoogleCredentials.fromStream(credentialsStream);
utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
AccessToken accessToken = utilCredentials.refreshAccessToken();
OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withCallCredentials(MoreCallCredentials.from(credentials));
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setFillOauthScope(true)
.build();
final SimpleResponse response = stub.unaryCall(request);
assertFalse(response.getUsername().isEmpty());
assertTrue("Received username: " + response.getUsername(),
jsonKey.contains(response.getUsername()));
assertFalse(response.getOauthScope().isEmpty());
assertTrue("Received oauth scope: " + response.getOauthScope(),
authScope.contains(response.getOauthScope()));
}
/** Sends a unary rpc with "per rpc" raw oauth2 access token credentials. */
public void perRpcCreds(String jsonKey, InputStream credentialsStream, String oauthScope)
throws Exception {
// In gRpc Java, we don't have per Rpc credentials, user can use an intercepted stub only once
// for that purpose.
// So, this test is identical to oauth2_auth_token test.
oauth2AuthToken(jsonKey, credentialsStream, oauthScope);
}
/** Sends an unary rpc with "google default credentials". */
public void googleDefaultCredentials(
String defaultServiceAccount,
TestServiceGrpc.TestServiceBlockingStub googleDefaultStub) throws Exception {
final SimpleRequest request = SimpleRequest.newBuilder()
.setFillUsername(true)
.setResponseSize(314159)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[271828])))
.build();
final SimpleResponse response = googleDefaultStub.unaryCall(request);
assertEquals(defaultServiceAccount, response.getUsername());
final SimpleResponse goldenResponse = SimpleResponse.newBuilder()
.setUsername(defaultServiceAccount)
.setPayload(Payload.newBuilder()
.setBody(ByteString.copyFrom(new byte[314159])))
.build();
assertResponse(goldenResponse, response);
}
private static class SoakIterationResult {
public SoakIterationResult(long latencyMs, Status status) {
this.latencyMs = latencyMs;
this.status = status;
}
public long getLatencyMs() {
return latencyMs;
}
public Status getStatus() {
return status;
}
private long latencyMs = -1;
private Status status = Status.OK;
}
private SoakIterationResult performOneSoakIteration(
TestServiceGrpc.TestServiceBlockingStub soakStub, int soakRequestSize, int soakResponseSize)
throws Exception {
long startNs = System.nanoTime();
Status status = Status.OK;
try {
final SimpleRequest request =
SimpleRequest.newBuilder()
.setResponseSize(soakResponseSize)
.setPayload(
Payload.newBuilder().setBody(ByteString.copyFrom(new byte[soakRequestSize])))
.build();
final SimpleResponse goldenResponse =
SimpleResponse.newBuilder()
.setPayload(
Payload.newBuilder().setBody(ByteString.copyFrom(new byte[soakResponseSize])))
.build();
assertResponse(goldenResponse, soakStub.unaryCall(request));
} catch (StatusRuntimeException e) {
status = e.getStatus();
}
long elapsedNs = System.nanoTime() - startNs;
return new SoakIterationResult(TimeUnit.NANOSECONDS.toMillis(elapsedNs), status);
}
/**
* Runs large unary RPCs in a loop with configurable failure thresholds
* and channel creation behavior.
*/
public void performSoakTest(
String serverUri,
boolean resetChannelPerIteration,
int soakIterations,
int maxFailures,
int maxAcceptablePerIterationLatencyMs,
int minTimeMsBetweenRpcs,
int overallTimeoutSeconds,
int soakRequestSize,
int soakResponseSize)
throws Exception {
int iterationsDone = 0;
int totalFailures = 0;
Histogram latencies = new Histogram(4 /* number of significant value digits */);
long startNs = System.nanoTime();
ManagedChannel soakChannel = createChannel();
TestServiceGrpc.TestServiceBlockingStub soakStub = TestServiceGrpc
.newBlockingStub(soakChannel)
.withInterceptors(recordClientCallInterceptor(clientCallCapture));
for (int i = 0; i < soakIterations; i++) {
if (System.nanoTime() - startNs >= TimeUnit.SECONDS.toNanos(overallTimeoutSeconds)) {
break;
}
long earliestNextStartNs = System.nanoTime()
+ TimeUnit.MILLISECONDS.toNanos(minTimeMsBetweenRpcs);
if (resetChannelPerIteration) {
soakChannel.shutdownNow();
soakChannel.awaitTermination(10, TimeUnit.SECONDS);
soakChannel = createChannel();
soakStub = TestServiceGrpc
.newBlockingStub(soakChannel)
.withInterceptors(recordClientCallInterceptor(clientCallCapture));
}
SoakIterationResult result =
performOneSoakIteration(soakStub, soakRequestSize, soakResponseSize);
SocketAddress peer = clientCallCapture
.get().getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
StringBuilder logStr = new StringBuilder(
String.format(
Locale.US,
"soak iteration: %d elapsed_ms: %d peer: %s server_uri: %s",
i, result.getLatencyMs(), peer != null ? peer.toString() : "null", serverUri));
if (!result.getStatus().equals(Status.OK)) {
totalFailures++;
logStr.append(String.format(" failed: %s", result.getStatus()));
} else if (result.getLatencyMs() > maxAcceptablePerIterationLatencyMs) {
totalFailures++;
logStr.append(
" exceeds max acceptable latency: " + maxAcceptablePerIterationLatencyMs);
} else {
logStr.append(" succeeded");
}
System.err.println(logStr.toString());
iterationsDone++;
latencies.recordValue(result.getLatencyMs());
long remainingNs = earliestNextStartNs - System.nanoTime();
if (remainingNs > 0) {
TimeUnit.NANOSECONDS.sleep(remainingNs);
}
}
soakChannel.shutdownNow();
soakChannel.awaitTermination(10, TimeUnit.SECONDS);
System.err.println(
String.format(
Locale.US,
"(server_uri: %s) soak test ran: %d / %d iterations. total failures: %d. "
+ "p50: %d ms, p90: %d ms, p100: %d ms",
serverUri,
iterationsDone,
soakIterations,
totalFailures,
latencies.getValueAtPercentile(50),
latencies.getValueAtPercentile(90),
latencies.getValueAtPercentile(100)));
// check if we timed out
String timeoutErrorMessage =
String.format(
Locale.US,
"(server_uri: %s) soak test consumed all %d seconds of time and quit early, "
+ "only having ran %d out of desired %d iterations.",
serverUri,
overallTimeoutSeconds,
iterationsDone,
soakIterations);
assertEquals(timeoutErrorMessage, iterationsDone, soakIterations);
// check if we had too many failures
String tooManyFailuresErrorMessage =
String.format(
Locale.US,
"(server_uri: %s) soak test total failures: %d exceeds max failures "
+ "threshold: %d.",
serverUri, totalFailures, maxFailures);
assertTrue(tooManyFailuresErrorMessage, totalFailures <= maxFailures);
}
private static void assertSuccess(StreamRecorder<?> recorder) {
if (recorder.getError() != null) {
throw new AssertionError(recorder.getError());
}
}
/** Helper for getting remote address from {@link io.grpc.ServerCall#getAttributes()}. */
protected SocketAddress obtainRemoteClientAddr() {
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(5, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
return serverCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
}
/** Helper for getting remote address from {@link io.grpc.ClientCall#getAttributes()}. */
protected SocketAddress obtainRemoteServerAddr() {
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withInterceptors(recordClientCallInterceptor(clientCallCapture))
.withDeadlineAfter(5, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
return clientCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR);
}
/** Helper for getting local address from {@link io.grpc.ServerCall#getAttributes()}. */
protected SocketAddress obtainLocalServerAddr() {
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(5, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
return serverCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR);
}
/** Helper for getting local address from {@link io.grpc.ClientCall#getAttributes()}. */
protected SocketAddress obtainLocalClientAddr() {
TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
.withInterceptors(recordClientCallInterceptor(clientCallCapture))
.withDeadlineAfter(5, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
return clientCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_LOCAL_ADDR);
}
/** Helper for asserting TLS info in SSLSession {@link io.grpc.ServerCall#getAttributes()}. */
protected void assertX500SubjectDn(String tlsInfo) {
TestServiceGrpc.TestServiceBlockingStub stub =
blockingStub.withDeadlineAfter(10, TimeUnit.SECONDS);
stub.unaryCall(SimpleRequest.getDefaultInstance());
List<Certificate> certificates;
SSLSession sslSession =
serverCallCapture.get().getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
try {
certificates = Arrays.asList(sslSession.getPeerCertificates());
} catch (SSLPeerUnverifiedException e) {
// Should never happen
throw new AssertionError(e);
}
X509Certificate x509cert = (X509Certificate) certificates.get(0);
assertEquals(1, certificates.size());
assertEquals(tlsInfo, x509cert.getSubjectX500Principal().toString());
}
protected int operationTimeoutMillis() {
return 7000;
}
/**
* Some tests run on memory constrained environments. Rather than OOM, just give up. 64 is
* chosen as a maximum amount of memory a large test would need.
*/
protected static void assumeEnoughMemory() {
Runtime r = Runtime.getRuntime();
long usedMem = r.totalMemory() - r.freeMemory();
long actuallyFreeMemory = r.maxMemory() - usedMem;
Assume.assumeTrue(
actuallyFreeMemory + " is not sufficient to run this test",
actuallyFreeMemory >= 64 * 1024 * 1024);
}
/**
* Poll the next metrics record and check it against the provided information, including the
* message sizes.
*/
private void assertStatsTrace(String method, Status.Code status,
Collection<? extends MessageLite> requests,
Collection<? extends MessageLite> responses) {
assertClientStatsTrace(method, status, requests, responses);
assertServerStatsTrace(method, status, requests, responses);
}
/**
* Poll the next metrics record and check it against the provided information, without checking
* the message sizes.
*/
private void assertStatsTrace(String method, Status.Code status) {
assertStatsTrace(method, status, null, null);
}
private void assertZeroRetryRecorded() {
MetricsRecord retryRecord = clientStatsRecorder.pollRecord();
assertThat(retryRecord.getMetric(RETRIES_PER_CALL)).isEqualTo(0);
assertThat(retryRecord.getMetric(TRANSPARENT_RETRIES_PER_CALL)).isEqualTo(0);
assertThat(retryRecord.getMetric(RETRY_DELAY_PER_CALL)).isEqualTo(0D);
}
private void assertClientStatsTrace(String method, Status.Code code,
Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
// Tracer-based stats
TestClientStreamTracer tracer = clientStreamTracers.poll();
assertNotNull(tracer);
assertTrue(tracer.getOutboundHeaders());
// assertClientStatsTrace() is called right after application receives status,
// but streamClosed() may be called slightly later than that. So we need a timeout.
try {
assertTrue(tracer.await(5, TimeUnit.SECONDS));
} catch (InterruptedException e) {
throw new AssertionError(e);
}
assertEquals(code, tracer.getStatus().getCode());
if (requests != null && responses != null) {
checkTracers(tracer, requests, responses);
}
if (metricsExpected()) {
// CensusStreamTracerModule records final status in interceptor, which is guaranteed to be
// done before application receives status.
MetricsRecord clientStartRecord = clientStatsRecorder.pollRecord();
checkStartTags(clientStartRecord, method, true);
MetricsRecord clientEndRecord = clientStatsRecorder.pollRecord();
checkEndTags(clientEndRecord, method, code, true);
if (requests != null && responses != null) {
checkCensus(clientEndRecord, false, requests, responses);
}
assertZeroRetryRecorded();
}
}
private void assertClientStatsTrace(String method, Status.Code status) {
assertClientStatsTrace(method, status, null, null);
}
@SuppressWarnings("AssertionFailureIgnored") // Failure is checked in the end by the passed flag.
private void assertServerStatsTrace(String method, Status.Code code,
Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
if (server == null) {
// Server is not in the same process. We can't check server-side stats.
return;
}
if (metricsExpected()) {
MetricsRecord serverStartRecord;
MetricsRecord serverEndRecord;
try {
// On the server, the stats is finalized in ServerStreamListener.closed(), which can be
// run after the client receives the final status. So we use a timeout.
serverStartRecord = serverStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
serverEndRecord = serverStatsRecorder.pollRecord(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
assertNotNull(serverStartRecord);
assertNotNull(serverEndRecord);
checkStartTags(serverStartRecord, method, false);
checkEndTags(serverEndRecord, method, code, false);
if (requests != null && responses != null) {
checkCensus(serverEndRecord, true, requests, responses);
}
}
ServerStreamTracerInfo tracerInfo;
tracerInfo = serverStreamTracers.poll();
assertNotNull(tracerInfo);
assertEquals(method, tracerInfo.fullMethodName);
assertNotNull(tracerInfo.tracer.contextCapture);
// On the server, streamClosed() may be called after the client receives the final status.
// So we use a timeout.
try {
assertTrue(tracerInfo.tracer.await(1, TimeUnit.SECONDS));
} catch (InterruptedException e) {
throw new AssertionError(e);
}
assertEquals(code, tracerInfo.tracer.getStatus().getCode());
if (requests != null && responses != null) {
checkTracers(tracerInfo.tracer, responses, requests);
}
}
private static void checkStartTags(MetricsRecord record, String methodName, boolean clientSide) {
assertNotNull("record is not null", record);
TagKey methodNameTagKey = clientSide
? RpcMeasureConstants.GRPC_CLIENT_METHOD
: RpcMeasureConstants.GRPC_SERVER_METHOD;
TagValue methodNameTag = record.tags.get(methodNameTagKey);
assertNotNull("method name tagged", methodNameTag);
assertEquals("method names match", methodName, methodNameTag.asString());
}
private static void checkEndTags(
MetricsRecord record, String methodName, Status.Code status, boolean clientSide) {
assertNotNull("record is not null", record);
TagKey methodNameTagKey = clientSide
? RpcMeasureConstants.GRPC_CLIENT_METHOD
: RpcMeasureConstants.GRPC_SERVER_METHOD;
TagValue methodNameTag = record.tags.get(methodNameTagKey);
assertNotNull("method name tagged", methodNameTag);
assertEquals("method names match", methodName, methodNameTag.asString());
TagKey statusTagKey = clientSide
? RpcMeasureConstants.GRPC_CLIENT_STATUS
: RpcMeasureConstants.GRPC_SERVER_STATUS;
TagValue statusTag = record.tags.get(statusTagKey);
assertNotNull("status tagged", statusTag);
assertEquals(status.toString(), statusTag.asString());
}
/**
* Check information recorded by tracers.
*/
private void checkTracers(
TestStreamTracer tracer,
Collection<? extends MessageLite> sentMessages,
Collection<? extends MessageLite> receivedMessages) {
long uncompressedSentSize = 0;
int seqNo = 0;
for (MessageLite msg : sentMessages) {
assertThat(tracer.nextOutboundEvent())
.isEqualTo(String.format(Locale.US, "outboundMessage(%d)", seqNo));
assertThat(tracer.nextOutboundEvent()).matches(
String.format(Locale.US, "outboundMessageSent\\(%d, -?[0-9]+, -?[0-9]+\\)", seqNo));
seqNo++;
uncompressedSentSize += msg.getSerializedSize();
}
assertNull(tracer.nextOutboundEvent());
long uncompressedReceivedSize = 0;
seqNo = 0;
for (MessageLite msg : receivedMessages) {
assertThat(tracer.nextInboundEvent())
.isEqualTo(String.format(Locale.US, "inboundMessage(%d)", seqNo));
assertThat(tracer.nextInboundEvent()).matches(
String.format(Locale.US, "inboundMessageRead\\(%d, -?[0-9]+, -?[0-9]+\\)", seqNo));
uncompressedReceivedSize += msg.getSerializedSize();
seqNo++;
}
assertNull(tracer.nextInboundEvent());
if (metricsExpected()) {
assertEquals(uncompressedSentSize, tracer.getOutboundUncompressedSize());
assertEquals(uncompressedReceivedSize, tracer.getInboundUncompressedSize());
}
}
/**
* Check information recorded by Census.
*/
private void checkCensus(MetricsRecord record, boolean isServer,
Collection<? extends MessageLite> requests, Collection<? extends MessageLite> responses) {
int uncompressedRequestsSize = 0;
for (MessageLite request : requests) {
uncompressedRequestsSize += request.getSerializedSize();
}
int uncompressedResponsesSize = 0;
for (MessageLite response : responses) {
uncompressedResponsesSize += response.getSerializedSize();
}
if (isServer) {
assertEquals(
requests.size(),
record.getMetricAsLongOrFail(RpcMeasureConstants.GRPC_SERVER_RECEIVED_MESSAGES_PER_RPC));
assertEquals(
responses.size(),
record.getMetricAsLongOrFail(RpcMeasureConstants.GRPC_SERVER_SENT_MESSAGES_PER_RPC));
assertEquals(
uncompressedRequestsSize,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
uncompressedResponsesSize,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_SERVER_UNCOMPRESSED_RESPONSE_BYTES));
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_SERVER_SERVER_LATENCY));
// It's impossible to get the expected wire sizes because it may be compressed, so we just
// check if they are recorded.
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_SERVER_RECEIVED_BYTES_PER_RPC));
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_SERVER_SENT_BYTES_PER_RPC));
} else {
assertEquals(
requests.size(),
record.getMetricAsLongOrFail(RpcMeasureConstants.GRPC_CLIENT_SENT_MESSAGES_PER_RPC));
assertEquals(
responses.size(),
record.getMetricAsLongOrFail(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_MESSAGES_PER_RPC));
assertEquals(
uncompressedRequestsSize,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_REQUEST_BYTES));
assertEquals(
uncompressedResponsesSize,
record.getMetricAsLongOrFail(
DeprecatedCensusConstants.RPC_CLIENT_UNCOMPRESSED_RESPONSE_BYTES));
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_CLIENT_ROUNDTRIP_LATENCY));
// It's impossible to get the expected wire sizes because it may be compressed, so we just
// check if they are recorded.
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_CLIENT_SENT_BYTES_PER_RPC));
assertNotNull(record.getMetric(RpcMeasureConstants.GRPC_CLIENT_RECEIVED_BYTES_PER_RPC));
}
}
// Helper methods for responses containing Payload since proto equals does not ignore deprecated
// fields (PayloadType).
private void assertResponses(
Collection<StreamingOutputCallResponse> expected,
Collection<StreamingOutputCallResponse> actual) {
assertSame(expected.size(), actual.size());
Iterator<StreamingOutputCallResponse> expectedIter = expected.iterator();
Iterator<StreamingOutputCallResponse> actualIter = actual.iterator();
while (expectedIter.hasNext()) {
assertResponse(expectedIter.next(), actualIter.next());
}
}
private void assertResponse(
StreamingOutputCallResponse expected, StreamingOutputCallResponse actual) {
if (expected == null || actual == null) {
assertEquals(expected, actual);
} else {
assertPayload(expected.getPayload(), actual.getPayload());
}
}
private void assertResponse(SimpleResponse expected, SimpleResponse actual) {
assertPayload(expected.getPayload(), actual.getPayload());
assertEquals(expected.getUsername(), actual.getUsername());
assertEquals(expected.getOauthScope(), actual.getOauthScope());
}
private void assertPayload(Payload expected, Payload actual) {
// Compare non deprecated fields in Payload, to make this test forward compatible.
if (expected == null || actual == null) {
assertEquals(expected, actual);
} else {
assertEquals(expected.getBody(), actual.getBody());
}
}
/**
* Captures the request attributes. Useful for testing ServerCalls.
* {@link ServerCall#getAttributes()}
*/
private static ServerInterceptor recordServerCallInterceptor(
final AtomicReference<ServerCall<?, ?>> serverCallCapture) {
return new ServerInterceptor() {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
serverCallCapture.set(call);
return next.startCall(call, requestHeaders);
}
};
}
/**
* Captures the request attributes. Useful for testing ClientCalls.
* {@link ClientCall#getAttributes()}
*/
private static ClientInterceptor recordClientCallInterceptor(
final AtomicReference<ClientCall<?, ?>> clientCallCapture) {
return new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
ClientCall<ReqT, RespT> clientCall = next.newCall(method,callOptions);
clientCallCapture.set(clientCall);
return clientCall;
}
};
}
private static ServerInterceptor recordContextInterceptor(
final AtomicReference<Context> contextCapture) {
return new ServerInterceptor() {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
ServerCall<ReqT, RespT> call,
Metadata requestHeaders,
ServerCallHandler<ReqT, RespT> next) {
contextCapture.set(Context.current());
return next.startCall(call, requestHeaders);
}
};
}
/**
* A marshaller that record input and output sizes.
*/
private static final class ByteSizeMarshaller<T> implements MethodDescriptor.Marshaller<T> {
private final MethodDescriptor.Marshaller<T> delegate;
volatile int lastOutSize;
volatile int lastInSize;
ByteSizeMarshaller(MethodDescriptor.Marshaller<T> delegate) {
this.delegate = delegate;
}
@Override
public InputStream stream(T value) {
InputStream is = delegate.stream(value);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
lastOutSize = (int) ByteStreams.copy(is, baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new ByteArrayInputStream(baos.toByteArray());
}
@Override
public T parse(InputStream stream) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
lastInSize = (int) ByteStreams.copy(stream, baos);
} catch (IOException e) {
throw new RuntimeException(e);
}
return delegate.parse(new ByteArrayInputStream(baos.toByteArray()));
}
}
}
| grpc/grpc-java | interop-testing/src/main/java/io/grpc/testing/integration/AbstractInteropTest.java |
180,205 | /*
* 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.netbeans.editor;
import java.lang.ref.WeakReference;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
/**
* Action listener that has a weak reference
* to the source action listener so it doesn't prevent
* it to be garbage collected.
* The calls to the <code>actionPerformed</code> are automatically
* propagated to the source action listener.
*
* @author Miloslav Metelka
* @version 1.00
*/
public class WeakTimerListener implements ActionListener {
private WeakReference ref;
private boolean stopTimer;
/** Construct new listener with automatic timer stopping.
*/
public WeakTimerListener(ActionListener source) {
this(source, true);
}
/** Construct new listener.
* @param source source action listener to which this listener delegates.
* @param stopTimer whether the timer should be stopped automatically when
* the timer fires and the source listener was garbage collected.
*/
public WeakTimerListener(ActionListener source, boolean stopTimer) {
this.ref = new WeakReference(source);
this.stopTimer = stopTimer;
}
public void actionPerformed(ActionEvent evt) {
ActionListener src = (ActionListener)ref.get();
if (src != null) {
src.actionPerformed(evt);
} else { // source listener was garbage collected
if (evt.getSource() instanceof Timer) {
Timer timer = (Timer)evt.getSource();
timer.removeActionListener(this);
if (stopTimer) {
timer.stop();
}
}
}
}
}
| apache/netbeans | ide/editor.lib/src/org/netbeans/editor/WeakTimerListener.java |
180,206 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-10 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import processing.app.debug.Compiler;
import processing.app.debug.Target;
import processing.core.*;
import static processing.app.I18n._;
/**
* The base class for the main processing application.
* Primary role of this class is for platform identification and
* general interaction with the system (launching URLs, loading
* files and images, etc) that comes from that.
*/
public class Base {
public static final int REVISION = 101;
public static final int EREVISION = 17;
/** This might be replaced by main() if there's a lib/version.txt file. */
static String VERSION_NAME = "0101E0017";
/** Set true if this a proper release rather than a numbered revision. */
static public boolean RELEASE = false;
static HashMap<Integer, String> platformNames = new HashMap<Integer, String>();
static {
platformNames.put(PConstants.WINDOWS, "windows");
platformNames.put(PConstants.MACOSX, "macosx");
platformNames.put(PConstants.LINUX, "linux");
}
static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>();
static {
platformIndices.put("windows", PConstants.WINDOWS);
platformIndices.put("macosx", PConstants.MACOSX);
platformIndices.put("linux", PConstants.LINUX);
}
static Map<String,String> archMap = new HashMap<String, String>();
static {
archMap.put("arduino", "avr");
archMap.put("msp430", "msp430");
archMap.put("lm4f", "lm4f");
archMap.put("c2000", "c2000");
archMap.put("cc3200", "cc3200");
archMap.put("cc3200emt", "cc3200emt");
archMap.put("msp432", "msp432");
archMap.put("msp432e", "msp432e");
archMap.put("cc2600emt", "cc2600emt");
}
static Platform platform;
static private boolean commandLine;
// A single instance of the preferences window
Preferences preferencesFrame;
// set to true after the first time the menu is built.
// so that the errors while building don't show up again.
boolean builtOnce;
static File buildFolder;
// these are static because they're used by Sketch
static private File examplesFolder;
static private File librariesFolder;
static private File toolsFolder;
static private File hardwareFolder;
static HashSet<File> libraries;
// maps imported packages to their library folder
static HashMap<String, File> importToLibraryTable;
// classpath for all known libraries for p5
// (both those in the p5/libs folder and those with lib subfolders
// found in the sketchbook)
static public String librariesClassPath;
static public HashMap<String, Target> targetsTable;
// Location for untitled items
static File untitledFolder;
// p5 icon for the window
// static Image icon;
// int editorCount;
// Editor[] editors;
java.util.List<Editor> editors =
Collections.synchronizedList(new ArrayList<Editor>());
// ArrayList editors = Collections.synchronizedList(new ArrayList<Editor>());
Editor activeEditor;
static public void main(String args[]) {
try {
File versionFile = getContentFile("lib/version.txt");
if (versionFile.exists()) {
String version = PApplet.loadStrings(versionFile)[0];
if (!version.equals(VERSION_NAME)) {
VERSION_NAME = version;
RELEASE = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
// if (System.getProperty("mrj.version") != null) {
// //String jv = System.getProperty("java.version");
// String ov = System.getProperty("os.version");
// if (ov.startsWith("10.5")) {
// System.setProperty("apple.laf.useScreenMenuBar", "true");
// }
// }
/*
commandLine = false;
if (args.length >= 2) {
if (args[0].startsWith("--")) {
commandLine = true;
}
}
if (PApplet.javaVersion < 1.5f) {
//System.err.println("no way man");
Base.showError("Need to install Java 1.5",
"This version of Processing requires \n" +
"Java 1.5 or later to run properly.\n" +
"Please visit java.com to upgrade.", null);
}
*/
initPlatform();
// // Set the look and feel before opening the window
// try {
// platform.setLookAndFeel();
// } catch (Exception e) {
// System.err.println("Non-fatal error while setting the Look & Feel.");
// System.err.println("The error message follows, however Processing should run fine.");
// System.err.println(e.getMessage());
// //e.printStackTrace();
// }
// Use native popups so they don't look so crappy on osx
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
// Don't put anything above this line that might make GUI,
// because the platform has to be inited properly first.
// Make sure a full JDK is installed
//initRequirements();
// run static initialization that grabs all the prefs
Preferences.init(null);
// setup the theme coloring fun
Theme.init();
// Set the look and feel before opening the window
try {
platform.setLookAndFeel();
} catch (Exception e) {
String mess = e.getMessage();
if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) {
System.err.println(_("Non-fatal error while setting the Look & Feel."));
System.err.println(_("The error message follows, however Energia should run fine."));
System.err.println(mess);
}
}
// Create a location for untitled sketches
untitledFolder = createTempFolder("untitled");
untitledFolder.deleteOnExit();
new Base(args);
}
static protected void setCommandLine() {
commandLine = true;
}
static protected boolean isCommandLine() {
return commandLine;
}
static protected void initPlatform() {
try {
Class<?> platformClass = Class.forName("processing.app.Platform");
if (Base.isMacOS()) {
platformClass = Class.forName("processing.app.macosx.Platform");
} else if (Base.isWindows()) {
platformClass = Class.forName("processing.app.windows.Platform");
} else if (Base.isLinux()) {
platformClass = Class.forName("processing.app.linux.Platform");
}
platform = (Platform) platformClass.newInstance();
} catch (Exception e) {
Base.showError(_("Problem Setting the Platform"),
_("An unknown error occurred while trying to load\n" +
"platform-specific code for your machine."), e);
}
}
static protected void initRequirements() {
try {
Class.forName("com.sun.jdi.VirtualMachine");
} catch (ClassNotFoundException cnfe) {
Base.showPlatforms();
Base.showError(_("Please install JDK 1.5 or later"),
_("Energia requires a full JDK (not just a JRE)\n" +
"to run. Please install JDK 1.5 or later.\n" +
"More information can be found in the reference."), cnfe);
}
}
public Base(String[] args) {
platform.init(this);
// Get paths for the libraries and examples in the Processing folder
//String workingDirectory = System.getProperty("user.dir");
examplesFolder = getContentFile("examples");
String targetLibDir = new String("");
if(Preferences.get("target").equals("msp430"))
targetLibDir = "hardware/msp430/";
else if (Preferences.get("target").equals("lm4f"))
targetLibDir = "hardware/lm4f/";
else if (Preferences.get("target").equals("c2000"))
targetLibDir = "hardware/c2000/";
else if (Preferences.get("target").equals("cc3200"))
targetLibDir = "hardware/cc3200/";
else if (Preferences.get("target").equals("cc3200emt"))
targetLibDir = "hardware/cc3200emt/";
else if (Preferences.get("target").equals("msp432"))
targetLibDir = "hardware/msp432/";
else if (Preferences.get("target").equals("cc2600emt"))
targetLibDir = "hardware/cc2600emt/";
librariesFolder = getContentFile(targetLibDir + "libraries");
toolsFolder = getContentFile("tools");
// Get the sketchbook path, and make sure it's set properly
String sketchbookPath = Preferences.get("sketchbook.path");
// If a value is at least set, first check to see if the folder exists.
// If it doesn't, warn the user that the sketchbook folder is being reset.
if (sketchbookPath != null) {
File skechbookFolder = new File(sketchbookPath);
if (!skechbookFolder.exists()) {
Base.showWarning(_("Sketchbook folder disappeared"),
_("The sketchbook folder no longer exists.\n" +
"Energia will switch to the default sketchbook\n" +
"location, and create a new sketchbook folder if\n" +
"necessary. Energia will then stop talking about\n" +
"himself in the third person."), null);
sketchbookPath = null;
}
}
// If no path is set, get the default sketchbook folder for this platform
if (sketchbookPath == null) {
File defaultFolder = getDefaultSketchbookFolder();
Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath());
if (!defaultFolder.exists()) {
defaultFolder.mkdirs();
}
}
targetsTable = new HashMap<String, Target>();
loadHardware(getHardwareFolder());
loadHardware(getSketchbookHardwareFolder());
// Check if there were previously opened sketches to be restored
boolean opened = restoreSketches();
// Check if any files were passed in on the command line
for (int i = 0; i < args.length; i++) {
String path = args[i];
// Fix a problem with systems that use a non-ASCII languages. Paths are
// being passed in with 8.3 syntax, which makes the sketch loader code
// unhappy, since the sketch folder naming doesn't match up correctly.
// http://dev.processing.org/bugs/show_bug.cgi?id=1089
if (isWindows()) {
try {
File file = new File(args[i]);
path = file.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
}
if (handleOpen(path) != null) {
opened = true;
}
}
// Create a new empty window (will be replaced with any files to be opened)
if (!opened) {
handleNew();
}
// check for updates
if (Preferences.getBoolean("update.check")) {
new UpdateCheck(this);
}
}
/**
* Post-constructor setup for the editor area. Loads the last
* sketch that was used (if any), and restores other Editor settings.
* The complement to "storePreferences", this is called when the
* application is first launched.
*/
protected boolean restoreSketches() {
// figure out window placement
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
boolean windowPositionValid = true;
if (Preferences.get("last.screen.height") != null) {
// if screen size has changed, the window coordinates no longer
// make sense, so don't use them unless they're identical
int screenW = Preferences.getInteger("last.screen.width");
int screenH = Preferences.getInteger("last.screen.height");
if ((screen.width != screenW) || (screen.height != screenH)) {
windowPositionValid = false;
}
/*
int windowX = Preferences.getInteger("last.window.x");
int windowY = Preferences.getInteger("last.window.y");
if ((windowX < 0) || (windowY < 0) ||
(windowX > screenW) || (windowY > screenH)) {
windowPositionValid = false;
}
*/
} else {
windowPositionValid = false;
}
// Iterate through all sketches that were open last time p5 was running.
// If !windowPositionValid, then ignore the coordinates found for each.
// Save the sketch path and window placement for each open sketch
int count = Preferences.getInteger("last.sketch.count");
int opened = 0;
for (int i = 0; i < count; i++) {
String path = Preferences.get("last.sketch" + i + ".path");
int[] location;
if (windowPositionValid) {
String locationStr = Preferences.get("last.sketch" + i + ".location");
location = PApplet.parseInt(PApplet.split(locationStr, ','));
} else {
location = nextEditorLocation();
}
// If file did not exist, null will be returned for the Editor
if (handleOpen(path, location) != null) {
opened++;
}
}
return (opened > 0);
}
/**
* Store list of sketches that are currently open.
* Called when the application is quitting and documents are still open.
*/
protected void storeSketches() {
// Save the width and height of the screen
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Preferences.setInteger("last.screen.width", screen.width);
Preferences.setInteger("last.screen.height", screen.height);
String untitledPath = untitledFolder.getAbsolutePath();
// Save the sketch path and window placement for each open sketch
int index = 0;
for (Editor editor : editors) {
String path = editor.getSketch().getMainFilePath();
// In case of a crash, save untitled sketches if they contain changes.
// (Added this for release 0158, may not be a good idea.)
if (path.startsWith(untitledPath) &&
!editor.getSketch().isModified()) {
continue;
}
Preferences.set("last.sketch" + index + ".path", path);
int[] location = editor.getPlacement();
String locationStr = PApplet.join(PApplet.str(location), ",");
Preferences.set("last.sketch" + index + ".location", locationStr);
index++;
}
Preferences.setInteger("last.sketch.count", index);
}
// If a sketch is untitled on quit, may need to store the new name
// rather than the location from the temp folder.
protected void storeSketchPath(Editor editor, int index) {
String path = editor.getSketch().getMainFilePath();
String untitledPath = untitledFolder.getAbsolutePath();
if (path.startsWith(untitledPath)) {
path = "";
}
Preferences.set("last.sketch" + index + ".path", path);
}
/*
public void storeSketch(Editor editor) {
int index = -1;
for (int i = 0; i < editorCount; i++) {
if (editors[i] == editor) {
index = i;
break;
}
}
if (index == -1) {
System.err.println("Problem storing sketch " + editor.sketch.name);
} else {
String path = editor.sketch.getMainFilePath();
Preferences.set("last.sketch" + index + ".path", path);
}
}
*/
// .................................................................
// Because of variations in native windowing systems, no guarantees about
// changes to the focused and active Windows can be made. Developers must
// never assume that this Window is the focused or active Window until this
// Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
protected void handleActivated(Editor whichEditor) {
activeEditor = whichEditor;
// set the current window to be the console that's getting output
EditorConsole.setEditor(activeEditor);
}
protected int[] nextEditorLocation() {
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int defaultWidth = Preferences.getInteger("editor.window.width.default");
int defaultHeight = Preferences.getInteger("editor.window.height.default");
if (activeEditor == null) {
// If no current active editor, use default placement
return new int[] {
(screen.width - defaultWidth) / 2,
(screen.height - defaultHeight) / 2,
defaultWidth, defaultHeight, 0
};
} else {
// With a currently active editor, open the new window
// using the same dimensions, but offset slightly.
synchronized (editors) {
final int OVER = 50;
// In release 0160, don't
//location = activeEditor.getPlacement();
Editor lastOpened = editors.get(editors.size() - 1);
int[] location = lastOpened.getPlacement();
// Just in case the bounds for that window are bad
location[0] += OVER;
location[1] += OVER;
if (location[0] == OVER ||
location[2] == OVER ||
location[0] + location[2] > screen.width ||
location[1] + location[3] > screen.height) {
// Warp the next window to a randomish location on screen.
return new int[] {
(int) (Math.random() * (screen.width - defaultWidth)),
(int) (Math.random() * (screen.height - defaultHeight)),
defaultWidth, defaultHeight, 0
};
}
return location;
}
}
}
// .................................................................
boolean breakTime = false;
String[] months = {
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"
};
/**
* Handle creating a sketch folder, return its base .pde file
* or null if the operation was canceled.
* @param shift whether shift is pressed, which will invert prompt setting
* @param noPrompt disable prompt, no matter the setting
*/
protected String createNewUntitled() throws IOException {
File newbieDir = null;
String newbieName = null;
// In 0126, untitled sketches will begin in the temp folder,
// and then moved to a new location because Save will default to Save As.
File sketchbookDir = getSketchbookFolder();
File newbieParentDir = untitledFolder;
// Use a generic name like sketch_031008a, the date plus a char
int index = 0;
//SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
//SimpleDateFormat formatter = new SimpleDateFormat("MMMdd");
//String purty = formatter.format(new Date()).toLowerCase();
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31
int month = cal.get(Calendar.MONTH); // 0..11
String purty = months[month] + PApplet.nf(day, 2);
do {
if (index == 26) {
// In 0159, avoid running past z by sending people outdoors.
if (!breakTime) {
Base.showWarning(_("Time for a Break"),
_("You've reached the limit for auto naming of new sketches\n" +
"for the day. How about going for a walk instead?"), null);
breakTime = true;
} else {
Base.showWarning(_("Sunshine"),
_("No really, time for some fresh air for you."), null);
}
return null;
}
newbieName = "sketch_" + purty + ((char) ('a' + index));
newbieDir = new File(newbieParentDir, newbieName);
index++;
// Make sure it's not in the temp folder *and* it's not in the sketchbook
} while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists());
// Make the directory for the new sketch
newbieDir.mkdirs();
// Make an empty pde file
File newbieFile = new File(newbieDir, newbieName + ".ino");
FileOutputStream f = new FileOutputStream(newbieFile); // create the file
f.write(("void setup()\n{\n // put your setup code here, to run once:\n "+
"\n}\n\nvoid loop()\n{\n // put your main code here, to run repeatedly:\n \n}").getBytes());
f.close();
return newbieFile.getAbsolutePath();
}
/**
* Create a new untitled document in a new sketch window.
*/
public void handleNew() {
try {
String path = createNewUntitled();
if (path != null) {
Editor editor = handleOpen(path);
editor.untitled = true;
}
} catch (IOException e) {
if (activeEditor != null) {
activeEditor.statusError(e);
}
}
}
private void findInsertPoint(Editor editor)
{
// Find the start point
String t = editor.getText();
try {
Pattern regex = Pattern.compile("void\\s+setup\\s*\\(\\s*\\)");
Matcher regexMatcher = regex.matcher(t);
while (regexMatcher.find())
{
int totalLeftBracketsOpened = 0;
for(int i = regexMatcher.end(); i<t.length(); i++)
{
// Search the closing bracket
if(t.charAt(i)=='{')
totalLeftBracketsOpened++;
else
if(t.charAt(i)=='}')
{
if(--totalLeftBracketsOpened==0)
{
// Find input point here
for(int j = i-1; j > regexMatcher.end();j--)
{
int c = t.charAt(j);
if(c!=10 && c!=13)
{
editor.setSelection(++j,j);
break;
}
}
break;
}
}
}
break;
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
}
/**
* Replace the sketch in the current window with a new untitled document.
*/
public void handleNewReplace() {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
// Actually replace things
handleNewReplaceImpl();
}
protected void handleNewReplaceImpl() {
try {
String path = createNewUntitled();
if (path != null) {
activeEditor.handleOpenInternal(path);
findInsertPoint(activeEditor);
activeEditor.untitled = true;
}
// return true;
} catch (IOException e) {
activeEditor.statusError(e);
// return false;
}
}
/**
* Open a sketch, replacing the sketch in the current window.
* @param path Location of the primary pde file for the sketch.
*/
public void handleOpenReplace(String path) {
if (!activeEditor.checkModified()) {
return; // sketch was modified, and user canceled
}
// Close the running window, avoid window boogers with multiple sketches
activeEditor.internalCloseRunner();
boolean loaded = activeEditor.handleOpenInternal(path);
findInsertPoint(activeEditor);
if (!loaded) {
// replace the document without checking if that's ok
handleNewReplaceImpl();
}
}
/**
* Prompt for a sketch to open, and open it in a new window.
*/
public void handleOpenPrompt() {
// get the frontmost window frame for placing file dialog
FileDialog fd = new FileDialog(activeEditor,
_("Open an Energia sketch..."),
FileDialog.LOAD);
// This was annoying people, so disabled it in 0125.
//fd.setDirectory(Preferences.get("sketchbook.path"));
//fd.setDirectory(getSketchbookPath());
// Only show .pde files as eligible bachelors
fd.setFilenameFilter(new FilenameFilter() {
public boolean accept(File dir, String name) {
// TODO this doesn't seem to ever be used. AWESOME.
//System.out.println("check filter on " + dir + " " + name);
return name.toLowerCase().endsWith(".ino")
|| name.toLowerCase().endsWith(".pde");
}
});
fd.setVisible(true);
String directory = fd.getDirectory();
String filename = fd.getFile();
// User canceled selection
if (filename == null) return;
File inputFile = new File(directory, filename);
handleOpen(inputFile.getAbsolutePath());
}
/**
* Open a sketch in a new window.
* @param path Path to the pde file for the sketch in question
* @return the Editor object, so that properties (like 'untitled')
* can be set by the caller
*/
public Editor handleOpen(String path) {
return handleOpen(path, nextEditorLocation());
}
protected Editor handleOpen(String path, int[] location) {
// System.err.println("entering handleOpen " + path);
File file = new File(path);
if (!file.exists()) return null;
// System.err.println(" editors: " + editors);
// Cycle through open windows to make sure that it's not already open.
for (Editor editor : editors) {
if (editor.getSketch().getMainFilePath().equals(path)) {
editor.toFront();
// System.err.println(" handleOpen: already opened");
return editor;
}
}
// If the active editor window is an untitled, and un-modified document,
// just replace it with the file that's being opened.
// if (activeEditor != null) {
// Sketch activeSketch = activeEditor.sketch;
// if (activeSketch.isUntitled() && !activeSketch.isModified()) {
// // if it's an untitled, unmodified document, it can be replaced.
// // except in cases where a second blank window is being opened.
// if (!path.startsWith(untitledFolder.getAbsolutePath())) {
// activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0);
// return activeEditor;
// }
// }
// }
// System.err.println(" creating new editor");
Editor editor = new Editor(this, path, location);
// Editor editor = null;
// try {
// editor = new Editor(this, path, location);
// } catch (Exception e) {
// e.printStackTrace();
// System.err.flush();
// System.out.flush();
// System.exit(1);
// }
// System.err.println(" done creating new editor");
// EditorConsole.systemErr.println(" done creating new editor");
// Make sure that the sketch actually loaded
if (editor.getSketch() == null) {
// System.err.println("sketch was null, getting out of handleOpen");
return null; // Just walk away quietly
}
// if (editors == null) {
// editors = new Editor[5];
// }
// if (editorCount == editors.length) {
// editors = (Editor[]) PApplet.expand(editors);
// }
// editors[editorCount++] = editor;
editors.add(editor);
// if (markedForClose != null) {
// Point p = markedForClose.getLocation();
// handleClose(markedForClose, false);
// // open the new window in
// editor.setLocation(p);
// }
// now that we're ready, show the window
// (don't do earlier, cuz we might move it based on a window being closed)
editor.setVisible(true);
// System.err.println("exiting handleOpen");
findInsertPoint(editor);
return editor;
}
/**
* Close a sketch as specified by its editor window.
* @param editor Editor object of the sketch to be closed.
* @return true if succeeded in closing, false if canceled.
*/
public boolean handleClose(Editor editor) {
// Check if modified
// boolean immediate = editors.size() == 1;
if (!editor.checkModified()) {
return false;
}
// Close the running window, avoid window boogers with multiple sketches
editor.internalCloseRunner();
if (editors.size() == 1) {
// For 0158, when closing the last window /and/ it was already an
// untitled sketch, just give up and let the user quit.
// if (Preferences.getBoolean("sketchbook.closing_last_window_quits") ||
// (editor.untitled && !editor.getSketch().isModified())) {
if (Base.isMacOS()) {
Object[] options = { "OK", "Cancel" };
String prompt =
_("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Are you sure you want to Quit?</b>" +
"<p>Closing the last open sketch will quit Energia.");
int result = JOptionPane.showOptionDialog(editor,
prompt,
_("Quit"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.NO_OPTION ||
result == JOptionPane.CLOSED_OPTION) {
return false;
}
}
// This will store the sketch count as zero
editors.remove(editor);
Editor.serialMonitor.closeSerialPort();
storeSketches();
// Save out the current prefs state
Preferences.save();
// Since this wasn't an actual Quit event, call System.exit()
System.exit(0);
} else {
// More than one editor window open,
// proceed with closing the current window.
editor.setVisible(false);
editor.dispose();
// for (int i = 0; i < editorCount; i++) {
// if (editor == editors[i]) {
// for (int j = i; j < editorCount-1; j++) {
// editors[j] = editors[j+1];
// }
// editorCount--;
// // Set to null so that garbage collection occurs
// editors[editorCount] = null;
// }
// }
editors.remove(editor);
}
return true;
}
/**
* Handler for File → Quit.
* @return false if canceled, true otherwise.
*/
public boolean handleQuit() {
// If quit is canceled, this will be replaced anyway
// by a later handleQuit() that is not canceled.
storeSketches();
Editor.serialMonitor.closeSerialPort();
if (handleQuitEach()) {
// make sure running sketches close before quitting
for (Editor editor : editors) {
editor.internalCloseRunner();
}
// Save out the current prefs state
Preferences.save();
if (!Base.isMacOS()) {
// If this was fired from the menu or an AppleEvent (the Finder),
// then Mac OS X will send the terminate signal itself.
System.exit(0);
}
return true;
}
return false;
}
/**
* Attempt to close each open sketch in preparation for quitting.
* @return false if canceled along the way
*/
protected boolean handleQuitEach() {
int index = 0;
for (Editor editor : editors) {
if (editor.checkModified()) {
// Update to the new/final sketch path for this fella
storeSketchPath(editor, index);
index++;
} else {
return false;
}
}
return true;
}
// .................................................................
/**
* Asynchronous version of menu rebuild to be used on save and rename
* to prevent the interface from locking up until the menus are done.
*/
protected void rebuildSketchbookMenus() {
//System.out.println("async enter");
//new Exception().printStackTrace();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//System.out.println("starting rebuild");
rebuildSketchbookMenu(Editor.sketchbookMenu);
rebuildToolbarMenu(Editor.toolbarMenu);
//System.out.println("done with rebuild");
}
});
//System.out.println("async exit");
}
protected int rebuildToolbarMenu(JMenu menu) {
JMenuItem item;
menu.removeAll();
//System.out.println("rebuilding toolbar menu");
// Add the single "Open" item
item = Editor.newJMenuItem(_("Open..."), 'O');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleOpenPrompt();
}
});
menu.add(item);
menu.addSeparator();
// Add a list of all sketches and subfolders
try {
boolean sketches = addSketches(menu, getSketchbookFolder(), true);
//boolean sketches = addSketches(menu, getSketchbookFolder());
if (sketches) menu.addSeparator();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("rebuilding examples menu");
// Add each of the subfolders of examples directly to the menu
int n = 0;
try {
JMenu temp = new JMenu("Examples");
boolean found = addSketches(temp, examplesFolder, true);
if (found) {menu.add(temp); n++;};
temp = new JMenu("Contributed Libraries");
found = addSketches(temp, getSketchbookLibrariesFolder(), true);
if (found) {menu.add(temp); n++;};
temp = new JMenu("Libraries");
addSketches(temp, librariesFolder, true);
menu.add(temp);
n++;
} catch (IOException e) {
e.printStackTrace();
}
return n;
}
protected void rebuildSketchbookMenu(JMenu menu) {
//System.out.println("rebuilding sketchbook menu");
//new Exception().printStackTrace();
try {
menu.removeAll();
addSketches(menu, getSketchbookFolder(), false);
//addSketches(menu, getSketchbookFolder());
} catch (IOException e) {
e.printStackTrace();
}
}
public int rebuildImportMenu(JMenu importMenu) {
//System.out.println("rebuilding import menu");
importMenu.removeAll();
// reset the set of libraries
libraries = new HashSet<File>();
// reset the table mapping imports to libraries
importToLibraryTable = new HashMap<String, File>();
// Add from the "libraries" subfolder in the Processing directory
try {
addLibraries(importMenu, librariesFolder);
} catch (IOException e) {
e.printStackTrace();
}
// Add libraries found in the sketchbook folder
int separatorIndex = importMenu.getItemCount();
try {
File sketchbookLibraries = getSketchbookLibrariesFolder();
boolean found = addLibraries(importMenu, sketchbookLibraries);
if (found) {
/*JMenuItem contrib = new JMenuItem(_("Contributed"));
contrib.setEnabled(false);
importMenu.insert(contrib, separatorIndex);*/
importMenu.insertSeparator(separatorIndex);
}
} catch (IOException e) {
e.printStackTrace();
}
return separatorIndex;
}
public void rebuildExamplesMenu(JMenu menu) {
//System.out.println("rebuilding examples menu");
try {
menu.removeAll();
boolean found = addSketches(menu, examplesFolder, false);
if (found) menu.addSeparator();
found = addSketches(menu, getSketchbookLibrariesFolder(), false);
if (found) menu.addSeparator();
addSketches(menu, librariesFolder, false);
} catch (IOException e) {
e.printStackTrace();
}
}
public void onBoardOrPortChange() {
for (Editor editor : editors) {
editor.onBoardOrPortChange();
}
}
public void onArchChanged() {
for (Editor editor : editors) {
editor.onArchChanged();
}
}
public void rebuildBoardsMenu(JMenu menu) {
//System.out.println("rebuilding boards menu");
menu.removeAll();
ButtonGroup group = new ButtonGroup();
for (Target target : targetsTable.values()) {
for (String board : target.getBoards().keySet()) {
AbstractAction action =
new AbstractAction(target.getBoards().get(board).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
//System.out.println("Switching to " + target + ":" + board);
String n = (String)getValue("target");
String o = Preferences.get("target");
if(!n.equals(o)) {
String targetLibDir = new String("");
if(n.equals("msp430"))
targetLibDir = "hardware/msp430/";
else if(n.equals("lm4f"))
targetLibDir = "hardware/lm4f/";
else if(n.equals("c2000"))
targetLibDir = "hardware/c2000/";
else if(n.equals("cc3200"))
targetLibDir = "hardware/cc3200/";
else if(n.equals("msp432"))
targetLibDir = "hardware/msp432/";
else if(n.equals("cc3200emt"))
targetLibDir = "hardware/cc3200emt/";
else if(n.equals("cc2600emt"))
targetLibDir = "hardware/cc2600emt/";
librariesFolder = getContentFile(targetLibDir + "libraries");
onArchChanged();
}
Preferences.set("target", (String) getValue("target"));
Preferences.set("board", (String) getValue("board"));
onBoardOrPortChange();
Sketch.buildSettingChanged();
}
};
action.putValue("target", target.getName());
action.putValue("board", board);
JMenuItem item = new JRadioButtonMenuItem(action);
if (target.getName().equals(Preferences.get("target")) &&
board.equals(Preferences.get("board"))) {
item.setSelected(true);
}
group.add(item);
menu.add(item);
}
}
}
/*
public void rebuildProgrammerMenu(JMenu menu) {
//System.out.println("rebuilding programmer menu");
menu.removeAll();
ButtonGroup group = new ButtonGroup();
for (Target target : targetsTable.values()) {
for (String programmer : target.getProgrammers().keySet()) {
AbstractAction action =
new AbstractAction(
target.getProgrammers().get(programmer).get("name")) {
public void actionPerformed(ActionEvent actionevent) {
Preferences.set("programmer", getValue("target") + ":" +
getValue("programmer"));
}
};
action.putValue("target", target.getName());
action.putValue("programmer", programmer);
JMenuItem item = new JRadioButtonMenuItem(action);
if (Preferences.get("programmer").equals(target.getName() + ":" +
programmer)) {
item.setSelected(true);
}
group.add(item);
menu.add(item);
}
}
}
*/
/**
* Scan a folder recursively, and add any sketches found to the menu
* specified. Set the openReplaces parameter to true when opening the sketch
* should replace the sketch in the current window, or false when the
* sketch should open in a new window.
*/
protected boolean addSketches(JMenu menu, File folder,
final boolean replaceExisting) throws IOException {
// skip .DS_Store files, etc (this shouldn't actually be necessary)
if (!folder.isDirectory()) return false;
String[] list = folder.list();
// If a bad folder or unreadable or whatever, this will come back null
if (list == null) return false;
// Alphabetize list, since it's not always alpha order
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
//processing.core.PApplet.println("adding sketches " + folder.getAbsolutePath());
//PApplet.println(list);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = e.getActionCommand();
if (new File(path).exists()) {
boolean replace = replaceExisting;
if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
replace = !replace;
}
if (replace) {
handleOpenReplace(path);
} else {
handleOpen(path);
}
} else {
showWarning(_("Sketch Does Not Exist"),
_("The selected sketch no longer exists.\n" +
"You may need to restart Energia to update\n" +
"the sketchbook menu."), null);
}
}
};
// offers no speed improvement
//menu.addActionListener(listener);
boolean ifound = false;
boolean skipLibraryFolder = folder.equals((Base.getSketchbookFolder()));
for (int i = 0; i < list.length; i++) {
if ((list[i].charAt(0) == '.') || list[i].startsWith("__disabled_") || list[i].equals("CVS") ||
(skipLibraryFolder && list[i].compareToIgnoreCase("libraries")==0)) continue;
File subfolder = new File(folder, list[i]);
if (!subfolder.isDirectory()) continue;
File entry = new File(subfolder, list[i] + ".ino");
if (!entry.exists() && (new File(subfolder, list[i] + ".pde")).exists()) {
entry = new File(subfolder, list[i] + ".pde");
}
// if a .pde file of the same prefix as the folder exists..
if (entry.exists()) {
//String sanityCheck = sanitizedName(list[i]);
//if (!sanityCheck.equals(list[i])) {
if (!Sketch.isSanitaryName(list[i])) {
if (!builtOnce) {
String complaining = I18n.format(
_("The sketch \"{0}\" cannot be used.\n" +
"Sketch names must contain only basic letters and numbers\n" +
"(ASCII-only with no spaces, " +
"and it cannot start with a number).\n" +
"To get rid of this message, remove the sketch from\n" +
"{1}"), list[i], entry.getAbsolutePath()
);
Base.showMessage(_("Ignoring sketch with bad name"), complaining);
}
continue;
}
JMenuItem item = new JMenuItem(list[i]);
item.addActionListener(listener);
item.setActionCommand(entry.getAbsolutePath());
menu.add(item);
ifound = true;
} else {
// don't create an extra menu level for a folder named "examples"
if (subfolder.getName().equals("examples")) {
boolean found = addSketches(menu, subfolder, replaceExisting);
if (found) ifound = true;
} else {
// not a sketch folder, but maybe a subfolder containing sketches
JMenu submenu = new JMenu(list[i]);
// needs to be separate var
// otherwise would set ifound to false
boolean found = addSketches(submenu, subfolder, replaceExisting);
//boolean found = addSketches(submenu, subfolder); //, false);
if (found) {
menu.add(submenu);
ifound = true;
}
}
}
}
return ifound; // actually ignored, but..
}
protected boolean addLibraries(JMenu menu, File folder) throws IOException {
if (!folder.isDirectory()) return false;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.') return false;
if (name.startsWith("__disabled_")) return false;
if (name.equals("CVS")) return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null) return false;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
activeEditor.getSketch().importLibrary(e.getActionCommand());
}
};
boolean ifound = false;
for (String potentialName : list) {
File subfolder = new File(folder, potentialName);
// File libraryFolder = new File(subfolder, "library");
// File libraryJar = new File(libraryFolder, potentialName + ".jar");
// // If a .jar file of the same prefix as the folder exists
// // inside the 'library' subfolder of the sketch
// if (libraryJar.exists()) {
String sanityCheck = Sketch.sanitizeName(potentialName);
if (!sanityCheck.equals(potentialName)) {
String mess = I18n.format(
_("The library \"{0}\" cannot be used.\n" +
"Library names must contain only basic letters and numbers.\n" +
"(ASCII only and no spaces, and it cannot start with a number)"),
potentialName
);
Base.showMessage(_("Ignoring bad library name"), mess);
continue;
}
String libraryName = potentialName;
// // get the path for all .jar files in this code folder
// String libraryClassPath =
// Compiler.contentsToClassPath(libraryFolder);
// // grab all jars and classes from this folder,
// // and append them to the library classpath
// librariesClassPath +=
// File.pathSeparatorChar + libraryClassPath;
// // need to associate each import with a library folder
// String packages[] =
// Compiler.packageListFromClassPath(libraryClassPath);
libraries.add(subfolder);
String packages[] =
Compiler.headerListFromIncludePath(subfolder.getAbsolutePath());
for (String pkg : packages) {
importToLibraryTable.put(pkg, subfolder);
}
JMenuItem item = new JMenuItem(libraryName);
item.addActionListener(listener);
item.setActionCommand(subfolder.getAbsolutePath());
menu.add(item);
ifound = true;
// XXX: DAM: should recurse here so that library folders can be nested
// } else { // not a library, but is still a folder, so recurse
// JMenu submenu = new JMenu(libraryName);
// // needs to be separate var, otherwise would set ifound to false
// boolean found = addLibraries(submenu, subfolder);
// if (found) {
// menu.add(submenu);
// ifound = true;
// }
// }
}
return ifound;
}
protected void loadHardware(File folder) {
if (!folder.isDirectory()) return;
String list[] = folder.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
// skip .DS_Store files, .svn folders, etc
if (name.charAt(0) == '.') return false;
if (name.equals("CVS")) return false;
return (new File(dir, name).isDirectory());
}
});
// if a bad folder or something like that, this might come back null
if (list == null) return;
// alphabetize list, since it's not always alpha order
// replaced hella slow bubble sort with this feller for 0093
Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String target : list) {
//Check to ensure compiler is installed before displaying C2000 Support
if(target.equals("c2000")){
if(Base.getC2000BasePath() != ""){
File subfolder = new File(folder, target);
targetsTable.put(target, new Target(target, subfolder));
}
}else{
File subfolder = new File(folder, target);
targetsTable.put(target, new Target(target, subfolder));
}
}
}
// .................................................................
/**
* Show the About box.
*/
public void handleAbout() {
final Image image = Base.getLibImage("about.jpg", activeEditor);
final Window window = new Window(activeEditor) {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
g.setFont(new Font("SansSerif", Font.PLAIN, 11));
g.setColor(Color.white);
g.drawString(Base.VERSION_NAME, 50, 30);
}
};
window.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
window.dispose();
}
});
int w = image.getWidth(activeEditor);
int h = image.getHeight(activeEditor);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h);
window.setVisible(true);
}
/**
* Show the Preferences window.
*/
public void handlePrefs() {
if (preferencesFrame == null) preferencesFrame = new Preferences();
preferencesFrame.showFrame(activeEditor);
}
// ...................................................................
/**
* Get list of platform constants.
*/
// static public int[] getPlatforms() {
// return platforms;
// }
// static public int getPlatform() {
// String osname = System.getProperty("os.name");
//
// if (osname.indexOf("Mac") != -1) {
// return PConstants.MACOSX;
//
// } else if (osname.indexOf("Windows") != -1) {
// return PConstants.WINDOWS;
//
// } else if (osname.equals("Linux")) { // true for the ibm vm
// return PConstants.LINUX;
//
// } else {
// return PConstants.OTHER;
// }
// }
static public Platform getPlatform() {
return platform;
}
static public String getPlatformName() {
String osname = System.getProperty("os.name");
if (osname.indexOf("Mac") != -1) {
return "macosx";
} else if (osname.indexOf("Windows") != -1) {
return "windows";
} else if (osname.equals("Linux")) { // true for the ibm vm
return "linux";
} else {
return "other";
}
}
/**
* Map a platform constant to its name.
* @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX
* @return one of "windows", "macosx", or "linux"
*/
static public String getPlatformName(int which) {
return platformNames.get(which);
}
static public int getPlatformIndex(String what) {
Integer entry = platformIndices.get(what);
return (entry == null) ? -1 : entry.intValue();
}
// These were changed to no longer rely on PApplet and PConstants because
// of conflicts that could happen with older versions of core.jar, where
// the MACOSX constant would instead read as the LINUX constant.
/**
* returns true if Processing is running on a Mac OS X machine.
*/
static public boolean isMacOS() {
//return PApplet.platform == PConstants.MACOSX;
return System.getProperty("os.name").indexOf("Mac") != -1;
}
/**
* returns true if running on windows.
*/
static public boolean isWindows() {
//return PApplet.platform == PConstants.WINDOWS;
return System.getProperty("os.name").indexOf("Windows") != -1;
}
/**
* true if running on linux.
*/
static public boolean isLinux() {
//return PApplet.platform == PConstants.LINUX;
return System.getProperty("os.name").indexOf("Linux") != -1;
}
// .................................................................
static public File getSettingsFolder() {
File settingsFolder = null;
String preferencesPath = Preferences.get("settings.path");
if (preferencesPath != null) {
settingsFolder = new File(preferencesPath);
} else {
try {
settingsFolder = platform.getSettingsFolder();
} catch (Exception e) {
showError(_("Problem getting data folder"),
_("Error getting the Energia data folder."), e);
}
}
// create the folder if it doesn't exist already
if (!settingsFolder.exists()) {
if (!settingsFolder.mkdirs()) {
showError(_("Settings issues"),
_("Energia cannot run because it could not\n" +
"create a folder to store your settings."), null);
}
}
return settingsFolder;
}
/**
* Convenience method to get a File object for the specified filename inside
* the settings folder.
* For now, only used by Preferences to get the preferences.txt file.
* @param filename A file inside the settings folder.
* @return filename wrapped as a File object inside the settings folder
*/
static public File getSettingsFile(String filename) {
return new File(getSettingsFolder(), filename);
}
static public File getBuildFolder() {
if (buildFolder == null) {
String buildPath = Preferences.get("build.path");
if (buildPath != null) {
buildFolder = new File(buildPath);
} else {
//File folder = new File(getTempFolder(), "build");
//if (!folder.exists()) folder.mkdirs();
buildFolder = createTempFolder("build");
buildFolder.deleteOnExit();
}
}
return buildFolder;
}
/**
* Get the path to the platform's temporary folder, by creating
* a temporary temporary file and getting its parent folder.
* <br/>
* Modified for revision 0094 to actually make the folder randomized
* to avoid conflicts in multi-user environments. (Bug 177)
*/
static public File createTempFolder(String name) {
try {
File folder = File.createTempFile(name, null);
//String tempPath = ignored.getParent();
//return new File(tempPath);
folder.delete();
folder.mkdirs();
return folder;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static public Set<File> getLibraries() {
return libraries;
}
static public String getExamplesPath() {
return examplesFolder.getAbsolutePath();
}
static public String getLibrariesPath() {
return librariesFolder.getAbsolutePath();
}
static public File getToolsFolder() {
return toolsFolder;
}
static public String getToolsPath() {
return toolsFolder.getAbsolutePath();
}
static public File getHardwareFolder() {
// calculate on the fly because it's needed by Preferences.init() to find
// the boards.txt and programmers.txt preferences files (which happens
// before the other folders / paths get cached).
return getContentFile("hardware");
}
static public String getHardwarePath() {
return getHardwareFolder().getAbsolutePath();
}
static public String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
static public String getArchCorePath() {
String arch = getArch();
String path = getHardwarePath() + File.separator + arch + File.separator +
"cores" + File.separator + arch + File.separator;
return path;
}
static public String getAvrBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "avr" + File.separator + "bin" + File.separator;
if (Base.isLinux() && !(new File(path)).exists()) {
return ""; // use distribution provided avr tools if bundled tools missing
}
return path;
}
static public String getMSP430BasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "msp430" + File.separator + "bin" + File.separator;
if (Base.isLinux() && !(new File(path)).exists()) {
return ""; // use msp430-gcc and mspdebug in PATH instead of platform version
}
return path;
}
static public String getLM4FBasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "lm4f" + File.separator + "bin" + File.separator;
if (Base.isLinux() && !(new File(path)).exists()) {
return ""; // use lm4f-gcc and mspdebug in PATH instead of platform version
}
return path;
}
//TODO: check tools path
static public String getC2000BasePath() {
String path = getHardwarePath() + File.separator + "tools" +
File.separator + "c2000" + File.separator + "bin" + File.separator;
if(!(new File(path)).exists()){
return ""; // use msp430-gcc and mspdebug in PATH instead of platform version
}
return path;
}
static public String getArch() {
return archMap.get(Preferences.get("target"));
}
static public String toShortPath(String longpath) {
String shortpath = "", sub = "";
//longpath = longpath.replaceAll("\\s", "");
longpath = longpath.toUpperCase();
StringTokenizer tokenizer = new StringTokenizer(longpath, "\\");
while(tokenizer.hasMoreTokens() == true) {
String temp = tokenizer.nextToken();
if(temp.length() > 8 && temp.indexOf(" ")>-1) // Long and with spaces
{
int thisFile = 1;
sub = temp.substring(0, 6);
// Find if there are more files
File dir = new File(shortpath);
for (File child : dir.listFiles())
{
String originalName = child.getName().toUpperCase();
String tempName = originalName.replaceAll("\\s", "");
int l = tempName.length();
if(tempName.substring(0, l>6 ? 6:l).compareTo(sub)==0)
{
if(originalName.compareTo(temp)==0)
break;
else
thisFile++;
}
}
String ext = "";
if(temp.indexOf(".")>0) // There is an extension to add
{
ext = temp.substring(temp.lastIndexOf(".")+1);
ext = "." + ext.substring(0,ext.length()>3?3:ext.length());
}
temp = sub + "~" + thisFile + ext;
}
shortpath += temp + "\\";
}
return shortpath;
}
static public String getBasePath() {
if (Base.isLinux()) {
if (getArch() == "msp430") {
String hwPath = getMSP430BasePath();
return hwPath;
}
else if (getArch() == "lm4f" || getArch() == "cc3200" || getArch() == "msp432") {
String hwPath = getLM4FBasePath();
return hwPath;
}
else if (getArch() == "c2000") {
String hwPath = getC2000BasePath();
return hwPath;
}
else {
return getHardwarePath() + File.separator + "tools" + File.separator
+ getArch() + File.separator + "bin" + File.separator;
}
} else if (Base.isWindows()) {
String arch = getArch();
if (arch == "cc3200" || arch == "msp432" || arch == "cc3200emt")
arch = "lm4f";
String ret = getHardwarePath() + File.separator + "tools"
+ File.separator + arch + File.separator + "bin"
+ File.separator;
return ret;
} else {
String arch = getArch();
if (arch == "cc3200" || arch == "cc3200emt" || arch == "msp432")
arch = "lm4f";
return getHardwarePath() + File.separator + "tools" + File.separator
+ arch + File.separator + "bin" + File.separator;
}
}
static public String getCommonBasePath() {
return getToolsPath() +
File.separator + "common" + File.separator + "bin" + File.separator;
}
static public Target getTarget() {
return Base.targetsTable.get(Preferences.get("target"));
}
static public Map<String, String> getBoardPreferences() {
Target target = getTarget();
if (target == null) return new LinkedHashMap();
Map map = target.getBoards();
if (map == null) return new LinkedHashMap();
map = (Map) map.get(Preferences.get("board"));
if (map == null) return new LinkedHashMap();
return map;
}
static public File getSketchbookFolder() {
return new File(Preferences.get("sketchbook.path"));
}
static public File getSketchbookLibrariesFolder() {
File libdir = new File(getSketchbookFolder(), "libraries");
if (!libdir.exists()) {
try {
libdir.mkdirs();
/*File readme = new File(libdir, "readme.txt");
FileWriter freadme = new FileWriter(readme);
freadme.write(_("For information on installing libraries, see: " +
"http://arduino.cc/en/Guide/Libraries\n"));
freadme.close();*/
} catch (Exception e) {
}
}
return libdir;
}
static public String getSketchbookLibrariesPath() {
return getSketchbookLibrariesFolder().getAbsolutePath();
}
static public File getSketchbookHardwareFolder() {
return new File(getSketchbookFolder(), "hardware");
}
protected File getDefaultSketchbookFolder() {
File sketchbookFolder = null;
try {
sketchbookFolder = platform.getDefaultSketchbookFolder();
} catch (Exception e) { }
if (sketchbookFolder == null) {
sketchbookFolder = promptSketchbookLocation();
}
// create the folder if it doesn't exist already
boolean result = true;
if (!sketchbookFolder.exists()) {
result = sketchbookFolder.mkdirs();
}
if (!result) {
showError(_("You forgot your sketchbook"),
_("Energia cannot run because it could not\n" +
"create a folder to store your sketchbook."), null);
}
return sketchbookFolder;
}
/**
* Check for a new sketchbook location.
*/
static protected File promptSketchbookLocation() {
File folder = null;
folder = new File(System.getProperty("user.home"), "sketchbook");
if (!folder.exists()) {
folder.mkdirs();
return folder;
}
String prompt = _("Select (or create new) folder for sketches...");
folder = Base.selectFolder(prompt, null, null);
if (folder == null) {
System.exit(0);
}
return folder;
}
// .................................................................
/**
* Implements the cross-platform headache of opening URLs
* TODO This code should be replaced by PApplet.link(),
* however that's not a static method (because it requires
* an AppletContext when used as an applet), so it's mildly
* trickier than just removing this method.
*/
static public void openURL(String url) {
try {
platform.openURL(url);
} catch (Exception e) {
showWarning(_("Problem Opening URL"),
I18n.format(_("Could not open the URL\n{0}"), url), e);
}
}
/**
* Used to determine whether to disable the "Show Sketch Folder" option.
* @return true If a means of opening a folder is known to be available.
*/
static protected boolean openFolderAvailable() {
return platform.openFolderAvailable();
}
/**
* Implements the other cross-platform headache of opening
* a folder in the machine's native file browser.
*/
static public void openFolder(File file) {
try {
platform.openFolder(file);
} catch (Exception e) {
showWarning(_("Problem Opening Folder"),
I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e);
}
}
// .................................................................
/**
* Prompt for a fodler and return it as a File object (or null).
* Implementation for choosing directories that handles both the
* Mac OS X hack to allow the native AWT file dialog, or uses
* the JFileChooser on other platforms. Mac AWT trick obtained from
* <A HREF="http://lists.apple.com/archives/java-dev/2003/Jul/msg00243.html">this post</A>
* on the OS X Java dev archive which explains the cryptic note in
* Apple's Java 1.4 release docs about the special System property.
*/
static public File selectFolder(String prompt, File folder, Frame frame) {
if (Base.isMacOS()) {
if (frame == null) frame = new Frame(); //.pack();
FileDialog fd = new FileDialog(frame, prompt, FileDialog.LOAD);
if (folder != null) {
fd.setDirectory(folder.getParent());
//fd.setFile(folder.getName());
}
System.setProperty("apple.awt.fileDialogForDirectories", "true");
fd.setVisible(true);
System.setProperty("apple.awt.fileDialogForDirectories", "false");
if (fd.getFile() == null) {
return null;
}
return new File(fd.getDirectory(), fd.getFile());
} else {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(prompt);
if (folder != null) {
fc.setSelectedFile(folder);
}
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returned = fc.showOpenDialog(new JDialog());
if (returned == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile();
}
}
return null;
}
// .................................................................
/**
* Give this Frame a Processing icon.
*/
static public void setIcon(Frame frame) {
// don't use the low-res icon on Mac OS X; the window should
// already have the right icon from the .app file.
if (Base.isMacOS()) return;
ArrayList<Image> images = new ArrayList<Image>();
images.add(createImageFromLib("energia_16.png"));
images.add(createImageFromLib("energia_24.png"));
images.add(createImageFromLib("energia_32.png"));
images.add(createImageFromLib("energia_48.png"));
frame.setIconImages(images);
}
static private Image createImageFromLib(String filename)
{
return Toolkit.getDefaultToolkit().createImage(new File("lib/" + filename).getAbsolutePath());
}
// someone needs to be slapped
//static KeyStroke closeWindowKeyStroke;
/**
* Return true if the key event was a Ctrl-W or an ESC,
* both indicators to close the window.
* Use as part of a keyPressed() event handler for frames.
*/
/*
static public boolean isCloseWindowEvent(KeyEvent e) {
if (closeWindowKeyStroke == null) {
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers);
}
return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) ||
KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke));
}
*/
/**
* Registers key events for a Ctrl-W and ESC with an ActionListener
* that will take care of disposing the window.
*/
static public void registerWindowCloseKeys(JRootPane root,
ActionListener disposer) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
stroke = KeyStroke.getKeyStroke('W', modifiers);
root.registerKeyboardAction(disposer, stroke,
JComponent.WHEN_IN_FOCUSED_WINDOW);
}
// .................................................................
static public void showReference(String filename) {
File referenceFolder = Base.getContentFile("reference");
File referenceFile = new File(referenceFolder, filename);
openURL(referenceFile.getAbsolutePath());
}
static public void showGettingStarted() {
if (Base.isMacOS()) {
Base.showReference(_("Guide_MacOSX.html"));
} else if (Base.isWindows()) {
Base.showReference(_("Guide_Windows.html"));
} else {
Base.openURL(_("http://www.arduino.cc/playground/Learning/Linux"));
}
}
static public void showReference() {
showReference(_("index.html"));
}
static public void showEnvironment() {
showReference(_("Guide_Environment.html"));
}
static public void showPlatforms() {
showReference(_("environment") + File.separator + _("platforms.html"));
}
static public void showTroubleshooting() {
showReference(_("Guide_Troubleshooting.html"));
}
static public void showFAQ() {
showReference(_("FAQ.html"));
}
// .................................................................
/**
* "No cookie for you" type messages. Nothing fatal or all that
* much of a bummer, but something to notify the user about.
*/
static public void showMessage(String title, String message) {
if (title == null) title = _("Message");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Non-fatal error message with optional stack trace side dish.
*/
static public void showWarning(String title, String message, Exception e) {
if (title == null) title = _("Warning");
if (commandLine) {
System.out.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.WARNING_MESSAGE);
}
if (e != null) e.printStackTrace();
}
/**
* Show an error message that's actually fatal to the program.
* This is an error that can't be recovered. Use showWarning()
* for errors that allow P5 to continue running.
*/
static public void showError(String title, String message, Throwable e) {
if (title == null) title = _("Error");
if (commandLine) {
System.err.println(title + ": " + message);
} else {
JOptionPane.showMessageDialog(new Frame(), message, title,
JOptionPane.ERROR_MESSAGE);
}
if (e != null) e.printStackTrace();
System.exit(1);
}
// ...................................................................
// incomplete
static public int showYesNoCancelQuestion(Editor editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
int result =
JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
return result;
// if (result == JOptionPane.YES_OPTION) {
//
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
//
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
//
// } else {
// throw new IllegalStateException();
// }
} else {
// Pane formatting adapted from the Quaqua guide
// http://www.randelshofer.ch/quaqua/guide/joptionpane.html
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>Do you want to save changes to this sketch<BR>" +
" before closing?</b>" +
"<p>If you don't save, your changes will be lost.",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Save", "Cancel", "Don't Save"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
// on macosx, setting the destructive property places this option
// away from the others at the lefthand side
pane.putClientProperty("Quaqua.OptionPane.destructiveOption",
new Integer(2));
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.CANCEL_OPTION;
} else if (result == options[2]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
//if (result == JOptionPane.YES_OPTION) {
//
// } else if (result == JOptionPane.NO_OPTION) {
// return true; // ok to continue
//
// } else if (result == JOptionPane.CANCEL_OPTION) {
// return false;
//
// } else {
// throw new IllegalStateException();
// }
static public int showYesNoQuestion(Frame editor, String title,
String primary, String secondary) {
if (!Base.isMacOS()) {
return JOptionPane.showConfirmDialog(editor,
"<html><body>" +
"<b>" + primary + "</b>" +
"<br>" + secondary, title,
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
} else {
// Pane formatting adapted from the Quaqua guide
// http://www.randelshofer.ch/quaqua/guide/joptionpane.html
JOptionPane pane =
new JOptionPane("<html> " +
"<head> <style type=\"text/css\">"+
"b { font: 13pt \"Lucida Grande\" }"+
"p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+
"</style> </head>" +
"<b>" + primary + "</b>" +
"<p>" + secondary + "</p>",
JOptionPane.QUESTION_MESSAGE);
String[] options = new String[] {
"Yes", "No"
};
pane.setOptions(options);
// highlight the safest option ala apple hig
pane.setInitialValue(options[0]);
JDialog dialog = pane.createDialog(editor, null);
dialog.setVisible(true);
Object result = pane.getValue();
if (result == options[0]) {
return JOptionPane.YES_OPTION;
} else if (result == options[1]) {
return JOptionPane.NO_OPTION;
} else {
return JOptionPane.CLOSED_OPTION;
}
}
}
/**
* Retrieve a path to something in the Processing folder. Eventually this
* may refer to the Contents subfolder of Processing.app, if we bundle things
* up as a single .app file with no additional folders.
*/
// static public String getContentsPath(String filename) {
// String basePath = System.getProperty("user.dir");
// /*
// // do this later, when moving to .app package
// if (PApplet.platform == PConstants.MACOSX) {
// basePath = System.getProperty("processing.contents");
// }
// */
// return basePath + File.separator + filename;
// }
/**
* Get a path for something in the Processing lib folder.
*/
/*
static public String getLibContentsPath(String filename) {
String libPath = getContentsPath("lib/" + filename);
File libDir = new File(libPath);
if (libDir.exists()) {
return libPath;
}
// was looking into making this run from Eclipse, but still too much mess
// libPath = getContents("build/shared/lib/" + what);
// libDir = new File(libPath);
// if (libDir.exists()) {
// return libPath;
// }
return null;
}
*/
static public File getAppFile() {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
if (Base.isMacOS()) {
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
return new File(path);
//return new File(working, name);
}
static public File getContentFile(String name) {
String path = System.getProperty("user.dir");
// Get a path to somewhere inside the .app folder
if (Base.isMacOS()) {
// <key>javaroot</key>
// <string>$JAVAROOT</string>
String javaroot = System.getProperty("javaroot");
if (javaroot != null) {
path = javaroot;
}
}
File working = new File(path);
return new File(working, name);
}
/**
* Get an image associated with the current color theme.
*/
static public Image getThemeImage(String name, Component who) {
return getLibImage("theme/" + name, who);
}
/**
* Return an Image object from inside the Processing lib folder.
*/
static public Image getLibImage(String name, Component who) {
Image image = null;
Toolkit tk = Toolkit.getDefaultToolkit();
File imageLocation = new File(getContentFile("lib"), name);
image = tk.getImage(imageLocation.getAbsolutePath());
MediaTracker tracker = new MediaTracker(who);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) { }
return image;
}
/**
* Return an InputStream for a file inside the Processing lib folder.
*/
static public InputStream getLibStream(String filename) throws IOException {
return new FileInputStream(new File(getContentFile("lib"), filename));
}
// ...................................................................
/**
* Get the number of lines in a file by counting the number of newline
* characters inside a String (and adding 1).
*/
static public int countLines(String what) {
int count = 1;
for (char c : what.toCharArray()) {
if (c == '\n') count++;
}
return count;
}
/**
* Same as PApplet.loadBytes(), however never does gzip decoding.
*/
static public byte[] loadBytesRaw(File file) throws IOException {
int size = (int) file.length();
FileInputStream input = new FileInputStream(file);
byte buffer[] = new byte[size];
int offset = 0;
int bytesRead;
while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) {
offset += bytesRead;
if (bytesRead == 0) break;
}
input.close(); // weren't properly being closed
input = null;
return buffer;
}
/**
* Read from a file with a bunch of attribute/value pairs
* that are separated by = and ignore comments with #.
*/
static public HashMap<String,String> readSettings(File inputFile) {
HashMap<String,String> outgoing = new HashMap<String,String>();
if (!inputFile.exists()) return outgoing; // return empty hash
String lines[] = PApplet.loadStrings(inputFile);
for (int i = 0; i < lines.length; i++) {
int hash = lines[i].indexOf('#');
String line = (hash == -1) ?
lines[i].trim() : lines[i].substring(0, hash).trim();
if (line.length() == 0) continue;
int equals = line.indexOf('=');
if (equals == -1) {
System.err.println("ignoring illegal line in " + inputFile);
System.err.println(" " + line);
continue;
}
String attr = line.substring(0, equals).trim();
String valu = line.substring(equals + 1).trim();
outgoing.put(attr, valu);
}
return outgoing;
}
static public void copyFile(File sourceFile,
File targetFile) throws IOException {
InputStream from =
new BufferedInputStream(new FileInputStream(sourceFile));
OutputStream to =
new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
to.flush();
from.close(); // ??
from = null;
to.close(); // ??
to = null;
targetFile.setLastModified(sourceFile.lastModified());
}
/**
* Grab the contents of a file as a string.
*/
static public String loadFile(File file) throws IOException {
String[] contents = PApplet.loadStrings(file);
if (contents == null) return null;
return PApplet.join(contents, "\n");
}
/**
* Spew the contents of a String object out to a file.
*/
static public void saveFile(String str, File file) throws IOException {
File temp = File.createTempFile(file.getName(), null, file.getParentFile());
PApplet.saveStrings(temp, new String[] { str });
if (file.exists()) {
boolean result = file.delete();
if (!result) {
throw new IOException(
I18n.format(
_("Could not remove old version of {0}"),
file.getAbsolutePath()
)
);
}
}
boolean result = temp.renameTo(file);
if (!result) {
throw new IOException(
I18n.format(
_("Could not replace {0}"),
file.getAbsolutePath()
)
);
}
}
/**
* Copy a folder from one place to another. This ignores all dot files and
* folders found in the source directory, to avoid copying silly .DS_Store
* files and potentially troublesome .svn folders.
*/
static public void copyDir(File sourceDir,
File targetDir) throws IOException {
targetDir.mkdirs();
String files[] = sourceDir.list();
for (int i = 0; i < files.length; i++) {
// Ignore dot files (.DS_Store), dot folders (.svn) while copying
if (files[i].charAt(0) == '.') continue;
//if (files[i].equals(".") || files[i].equals("..")) continue;
File source = new File(sourceDir, files[i]);
File target = new File(targetDir, files[i]);
if (source.isDirectory()) {
//target.mkdirs();
copyDir(source, target);
target.setLastModified(source.lastModified());
} else {
copyFile(source, target);
}
}
}
/**
* Remove all files in a directory and the directory itself.
*/
static public void removeDir(File dir) {
if (dir.exists()) {
removeDescendants(dir);
if (!dir.delete()) {
System.err.println(I18n.format(_("Could not delete {0}"), dir));
}
}
}
/**
* Recursively remove all files within a directory,
* used with removeDir(), or when the contents of a dir
* should be removed, but not the directory itself.
* (i.e. when cleaning temp files from lib/build)
*/
static public void removeDescendants(File dir) {
if (!dir.exists()) return;
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || files[i].equals("..")) continue;
File dead = new File(dir, files[i]);
if (!dead.isDirectory()) {
if (!Preferences.getBoolean("compiler.save_build_files")) {
if (!dead.delete()) {
// temporarily disabled
System.err.println(I18n.format(_("Could not delete {0}"), dead));
}
}
} else {
removeDir(dead);
//dead.delete();
}
}
}
/**
* Calculate the size of the contents of a folder.
* Used to determine whether sketches are empty or not.
* Note that the function calls itself recursively.
*/
static public int calcFolderSize(File folder) {
int size = 0;
String files[] = folder.list();
// null if folder doesn't exist, happens when deleting sketch
if (files == null) return -1;
for (int i = 0; i < files.length; i++) {
if (files[i].equals(".") || (files[i].equals("..")) ||
files[i].equals(".DS_Store")) continue;
File fella = new File(folder, files[i]);
if (fella.isDirectory()) {
size += calcFolderSize(fella);
} else {
size += (int) fella.length();
}
}
return size;
}
/**
* Recursively creates a list of all files within the specified folder,
* and returns a list of their relative paths.
* Ignores any files/folders prefixed with a dot.
*/
static public String[] listFiles(String path, boolean relative) {
return listFiles(new File(path), relative);
}
static public String[] listFiles(File folder, boolean relative) {
String path = folder.getAbsolutePath();
Vector<String> vector = new Vector<String>();
listFiles(relative ? (path + File.separator) : "", path, vector);
String outgoing[] = new String[vector.size()];
vector.copyInto(outgoing);
return outgoing;
}
static protected void listFiles(String basePath,
String path, Vector<String> vector) {
File folder = new File(path);
String list[] = folder.list();
if (list == null) return;
for (int i = 0; i < list.length; i++) {
if (list[i].charAt(0) == '.') continue;
File file = new File(path, list[i]);
String newPath = file.getAbsolutePath();
if (newPath.startsWith(basePath)) {
newPath = newPath.substring(basePath.length());
}
vector.add(newPath);
if (file.isDirectory()) {
listFiles(basePath, newPath, vector);
}
}
}
}
| energia/Energia | app/src/processing/app/Base.java |
180,207 | /*
* Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.btrace.core;
import com.sun.management.HotSpotDiagnosticMXBean;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.LockInfo;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.MonitorInfo;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.openjdk.btrace.core.aggregation.Aggregation;
import org.openjdk.btrace.core.aggregation.AggregationFunction;
import org.openjdk.btrace.core.aggregation.AggregationKey;
import org.openjdk.btrace.core.comm.Command;
import org.openjdk.btrace.core.comm.EventCommand;
import org.openjdk.btrace.core.comm.GridDataCommand;
import org.openjdk.btrace.core.comm.NumberDataCommand;
import org.openjdk.btrace.core.comm.NumberMapDataCommand;
import org.openjdk.btrace.core.comm.StringMapDataCommand;
import org.openjdk.btrace.core.jfr.JfrEvent;
import org.openjdk.btrace.core.types.AnyType;
import org.openjdk.btrace.core.types.BTraceCollection;
import org.openjdk.btrace.core.types.BTraceDeque;
import org.openjdk.btrace.core.types.BTraceMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Unsafe;
import sun.security.action.GetPropertyAction;
@SuppressWarnings("deprecation")
public final class BTraceRuntime {
private static final Logger log = LoggerFactory.getLogger(BTraceRuntime.class);
public static final String CMD_QUEUE_LIMIT_KEY = "org.openjdk.btrace.core.cmdQueueLimit";
private static final boolean messageTimestamp = false;
private static final String LINE_SEPARATOR;
// perf counter variability - we always variable variability
private static final int V_Variable = 3;
// perf counter units
private static final int V_None = 1;
private static final int V_String = 5;
private static final int PERF_STRING_LIMIT = 256;
// the number of stack frames taking a thread dump adds
private static final int THRD_DUMP_FRAMES = 1;
// we need Unsafe to load BTrace class bytes as
// bootstrap class
private static volatile Unsafe unsafe = null;
private static Properties dotWriterProps;
// this field is 'back-set' by the agent at startup thus needs to remain non-final
private static volatile BTraceRuntimeAccessor rtAccessor = () -> null;
private static final String INDENT = " ";
static {
LINE_SEPARATOR = System.getProperty("line.separator");
}
private BTraceRuntime() {}
private static Impl getRt() {
Impl rt = rtAccessor.getRt();
return rt;
}
public static long parseLong(String value, long deflt) {
if (value == null) {
return deflt;
}
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return deflt;
}
}
public static int parseInt(String value, int deflt) {
if (value == null) {
return deflt;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return deflt;
}
}
// The following constants are copied from VM code
// for jvmstat.
public static Unsafe initUnsafe() {
try {
if (unsafe == null) {
unsafe = Unsafe.getUnsafe();
}
} catch (SecurityException e) {
log.warn("Unable to initialize Unsafe. BTrace will not function properly");
}
return unsafe;
}
static int getInstrumentationLevel() {
return getRt().getInstrumentationLevel();
}
static void setInstrumentationLevel(int level) {
getRt().setInstrumentationLevel(level);
}
public static boolean enter() {
BTraceRuntime.Impl rt = getRt();
return rt == null || rt.enter();
}
/**
* Leave method is called by every probed method just before the probe actions end (and actual
* probed method continues).
*/
public static void leave() {
BTraceRuntime.Impl rt = getRt();
if (rt != null) {
rt.leave();
}
}
/** Handles exception from BTrace probe actions. */
public static void handleException(Throwable th) {
getRt().handleException(th);
}
// package-private interface to BTraceUtils class.
private static String identityStr(Object obj) {
int hashCode = java.lang.System.identityHashCode(obj);
return obj.getClass().getName() + "@" + Integer.toHexString(hashCode);
}
static int speculation() {
return getRt().speculation();
}
static void speculate(int id) {
getRt().speculate(id);
}
static void discard(int id) {
getRt().discard(id);
}
static void commit(int id) {
getRt().commit(id);
}
/**
* Indicates whether two given objects are "equal to" one another. For bootstrap classes, returns
* the result of calling Object.equals() override. For non-bootstrap classes, the reference
* identity comparison is done.
*
* @param obj1 first object to compare equality
* @param obj2 second object to compare equality
* @return <code>true</code> if the given objects are equal; <code>false</code> otherwise.
*/
static boolean compare(Object obj1, Object obj2) {
if (obj1 instanceof String) {
return obj1.equals(obj2);
} else if (obj1.getClass().getClassLoader() == null) {
if (obj2 == null || obj2.getClass().getClassLoader() == null) {
return obj1.equals(obj2);
} // else fall through..
}
return obj1 == obj2;
}
// BTrace map functions
static <K, V> Map<K, V> newHashMap() {
return new BTraceMap<>(new HashMap<>());
}
static <K, V> Map<K, V> newWeakMap() {
return new BTraceMap<>(new WeakHashMap<>());
}
static <V> Deque<V> newDeque() {
return new BTraceDeque<>(new ArrayDeque<>());
}
static Appendable newStringBuilder(boolean threadSafe) {
return threadSafe ? new StringBuffer() : new StringBuilder();
}
static Appendable newStringBuilder() {
return newStringBuilder(false);
}
static <E> int size(Collection<E> coll) {
if (coll instanceof BTraceCollection || coll.getClass().getClassLoader() == null) {
return coll.size();
} else {
throw new IllegalArgumentException();
}
}
public static <E> boolean isEmpty(Collection<E> coll) {
if (coll instanceof BTraceCollection || coll.getClass().getClassLoader() == null) {
return coll.isEmpty();
} else {
throw new IllegalArgumentException();
}
}
static <E> boolean contains(Collection<E> coll, Object obj) {
if (coll instanceof BTraceCollection || coll.getClass().getClassLoader() == null) {
for (E e : coll) {
if (compare(e, obj)) {
return true;
}
}
return false;
} else {
throw new IllegalArgumentException();
}
}
static <E> Object[] toArray(Collection<E> collection) {
if (collection == null) {
return new Object[0];
} else {
return collection.toArray();
}
}
static <K, V> V get(Map<K, V> map, K key) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
return map.get(key);
} else {
throw new IllegalArgumentException();
}
}
static <K, V> boolean containsKey(Map<K, V> map, K key) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
return map.containsKey(key);
} else {
throw new IllegalArgumentException();
}
}
static <K, V> boolean containsValue(Map<K, V> map, V value) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
return map.containsValue(value);
} else {
throw new IllegalArgumentException();
}
}
static <K, V> V put(Map<K, V> map, K key, V value) {
if (map instanceof BTraceMap) {
return map.put(key, value);
} else {
throw new IllegalArgumentException("not a btrace map");
}
}
static <K, V> V remove(Map<K, V> map, K key) {
if (map instanceof BTraceMap) {
return map.remove(key);
} else {
throw new IllegalArgumentException("not a btrace map");
}
}
static <K, V> void clear(Map<K, V> map) {
if (map instanceof BTraceMap) {
map.clear();
} else {
throw new IllegalArgumentException("not a btrace map");
}
}
static <K, V> int size(Map<K, V> map) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
return map.size();
} else {
throw new IllegalArgumentException();
}
}
static <K, V> boolean isEmpty(Map<K, V> map) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
return map.isEmpty();
} else {
throw new IllegalArgumentException();
}
}
static <K, V> void putAll(Map<K, V> src, Map<K, V> dst) {
dst.putAll(src);
}
static <K, V> void copy(Map<K, V> src, Map<K, V> dst) {
dst.clear();
dst.putAll(src);
}
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
static void printMap(Map map) {
if (map instanceof BTraceMap || map.getClass().getClassLoader() == null) {
synchronized (map) {
Map<String, String> m = new HashMap<>();
@SuppressWarnings("unchecked")
Set<Map.Entry<Object, Object>> entries = map.entrySet();
for (Map.Entry<Object, Object> e : entries) {
m.put(BTraceUtils.Strings.str(e.getKey()), BTraceUtils.Strings.str(e.getValue()));
}
printStringMap(null, m);
}
} else {
print(BTraceUtils.Strings.str(map));
}
}
public static <V> void push(Deque<V> queue, V value) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
queue.push(value);
} else {
throw new IllegalArgumentException();
}
}
public static <V> void addLast(Deque<V> queue, V value) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
queue.addLast(value);
} else {
throw new IllegalArgumentException();
}
}
public static <V> V peekFirst(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.peekFirst();
} else {
throw new IllegalArgumentException();
}
}
public static <V> V peekLast(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.peekLast();
} else {
throw new IllegalArgumentException();
}
}
public static <V> V removeLast(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.removeLast();
} else {
throw new IllegalArgumentException();
}
}
public static <V> V removeFirst(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.removeFirst();
} else {
throw new IllegalArgumentException();
}
}
public static <V> V poll(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.poll();
} else {
throw new IllegalArgumentException();
}
}
public static <V> V peek(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
return queue.peek();
} else {
throw new IllegalArgumentException();
}
}
public static <V> void clear(Deque<V> queue) {
if (queue instanceof BTraceDeque || queue.getClass().getClassLoader() == null) {
queue.clear();
} else {
throw new IllegalArgumentException();
}
}
public static Appendable append(Appendable buffer, String strToAppend) {
try {
if (buffer != null && strToAppend != null) {
return buffer.append(strToAppend);
} else {
throw new IllegalArgumentException();
}
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
public static int length(Appendable buffer) {
if (buffer instanceof CharSequence) {
return ((CharSequence) buffer).length();
} else {
throw new IllegalArgumentException();
}
}
static void printNumber(String name, Number value) {
getRt().send(new NumberDataCommand(name, value));
}
static void printNumberMap(String name, Map<String, ? extends Number> data) {
getRt().send(new NumberMapDataCommand(name, data));
}
static void printStringMap(String name, Map<String, String> data) {
getRt().send(new StringMapDataCommand(name, data));
}
// BTrace exit built-in function
static void exit(int exitCode) {
getRt().exit(exitCode);
}
static long sizeof(Object obj) {
return getRt().sizeof(obj);
}
// BTrace command line argument functions
static int $length() {
return getRt().$length();
}
static String $(int n) {
return getRt().$(n);
}
static String $(String key) {
return getRt().$(key);
}
/** @see BTraceUtils#instanceOf(java.lang.Object, java.lang.String) */
static boolean instanceOf(Object obj, String className) {
if (obj instanceof AnyType) {
// the only time we can have AnyType on stack
// is if it was passed in as a placeholder
// for void @Return parameter value
if (className.equalsIgnoreCase("void")) {
return obj.equals(AnyType.VOID);
}
return false;
}
Class<?> objClass = obj.getClass();
ClassLoader cl = objClass.getClassLoader();
cl = cl != null ? cl : ClassLoader.getSystemClassLoader();
try {
Class<?> target = cl.loadClass(className);
return target.isAssignableFrom(objClass);
} catch (ClassNotFoundException e) {
// non-existing class
log.debug("Class {} can not be found by classloader {}", className, cl, e);
return false;
}
}
static AtomicInteger newAtomicInteger(int initVal) {
return new BTraceAtomicInteger(initVal);
}
static int get(AtomicInteger ai) {
if (ai instanceof BTraceAtomicInteger || ai.getClass().getClassLoader() == null) {
return ai.get();
} else {
throw new IllegalArgumentException();
}
}
static void set(AtomicInteger ai, int i) {
if (ai instanceof BTraceAtomicInteger) {
ai.set(i);
} else {
throw new IllegalArgumentException();
}
}
static void lazySet(AtomicInteger ai, int i) {
if (ai instanceof BTraceAtomicInteger) {
ai.lazySet(i);
} else {
throw new IllegalArgumentException();
}
}
static boolean compareAndSet(AtomicInteger ai, int i, int j) {
if (ai instanceof BTraceAtomicInteger) {
return ai.compareAndSet(i, j);
} else {
throw new IllegalArgumentException();
}
}
static boolean weakCompareAndSet(AtomicInteger ai, int i, int j) {
if (ai instanceof BTraceAtomicInteger) {
return ai.weakCompareAndSet(i, j);
} else {
throw new IllegalArgumentException();
}
}
static int getAndIncrement(AtomicInteger ai) {
if (ai instanceof BTraceAtomicInteger) {
return ai.getAndIncrement();
} else {
throw new IllegalArgumentException();
}
}
static int getAndDecrement(AtomicInteger ai) {
if (ai instanceof BTraceAtomicInteger) {
return ai.getAndDecrement();
} else {
throw new IllegalArgumentException();
}
}
static int incrementAndGet(AtomicInteger ai) {
if (ai instanceof BTraceAtomicInteger) {
return ai.incrementAndGet();
} else {
throw new IllegalArgumentException();
}
}
static int decrementAndGet(AtomicInteger ai) {
if (ai instanceof BTraceAtomicInteger) {
return ai.decrementAndGet();
} else {
throw new IllegalArgumentException();
}
}
static int getAndAdd(AtomicInteger ai, int i) {
if (ai instanceof BTraceAtomicInteger) {
return ai.getAndAdd(i);
} else {
throw new IllegalArgumentException();
}
}
static int addAndGet(AtomicInteger ai, int i) {
if (ai instanceof BTraceAtomicInteger) {
return ai.addAndGet(i);
} else {
throw new IllegalArgumentException();
}
}
static int getAndSet(AtomicInteger ai, int i) {
if (ai instanceof BTraceAtomicInteger) {
return ai.getAndSet(i);
} else {
throw new IllegalArgumentException();
}
}
static AtomicLong newAtomicLong(long initVal) {
return new BTraceAtomicLong(initVal);
}
static long get(AtomicLong al) {
if (al instanceof BTraceAtomicLong || al.getClass().getClassLoader() == null) {
return al.get();
} else {
throw new IllegalArgumentException();
}
}
static void set(AtomicLong al, long i) {
if (al instanceof BTraceAtomicLong) {
al.set(i);
} else {
throw new IllegalArgumentException();
}
}
static void lazySet(AtomicLong al, long i) {
if (al instanceof BTraceAtomicLong) {
al.lazySet(i);
} else {
throw new IllegalArgumentException();
}
}
static boolean compareAndSet(AtomicLong al, long i, long j) {
if (al instanceof BTraceAtomicLong) {
return al.compareAndSet(i, j);
} else {
throw new IllegalArgumentException();
}
}
static boolean weakCompareAndSet(AtomicLong al, long i, long j) {
if (al instanceof BTraceAtomicLong) {
return al.weakCompareAndSet(i, j);
} else {
throw new IllegalArgumentException();
}
}
static long getAndIncrement(AtomicLong al) {
if (al instanceof BTraceAtomicLong) {
return al.getAndIncrement();
} else {
throw new IllegalArgumentException();
}
}
static long getAndDecrement(AtomicLong al) {
if (al instanceof BTraceAtomicLong) {
return al.getAndDecrement();
} else {
throw new IllegalArgumentException();
}
}
static long incrementAndGet(AtomicLong al) {
if (al instanceof BTraceAtomicLong) {
return al.incrementAndGet();
} else {
throw new IllegalArgumentException();
}
}
static long decrementAndGet(AtomicLong al) {
if (al instanceof BTraceAtomicLong) {
return al.decrementAndGet();
} else {
throw new IllegalArgumentException();
}
}
static long getAndAdd(AtomicLong al, long i) {
if (al instanceof BTraceAtomicLong) {
return al.getAndAdd(i);
} else {
throw new IllegalArgumentException();
}
}
static long addAndGet(AtomicLong al, long i) {
if (al instanceof BTraceAtomicLong) {
return al.addAndGet(i);
} else {
throw new IllegalArgumentException();
}
}
static long getAndSet(AtomicLong al, long i) {
if (al instanceof BTraceAtomicLong) {
return al.getAndSet(i);
} else {
throw new IllegalArgumentException();
}
}
// BTrace perf counter reading functions
static int perfInt(String name) {
return getRt().perfInt(name);
}
static long perfLong(String name) {
return getRt().perfLong(name);
}
static String perfString(String name) {
return getRt().perfString(name);
}
// stack trace functions
private static String stackTraceAllStr(int numFrames, boolean printWarning) {
Set<Map.Entry<Thread, StackTraceElement[]>> traces = Thread.getAllStackTraces().entrySet();
StringBuilder buf = new StringBuilder();
for (Map.Entry<Thread, StackTraceElement[]> t : traces) {
buf.append(t.getKey());
buf.append(LINE_SEPARATOR);
buf.append(LINE_SEPARATOR);
StackTraceElement[] st = t.getValue();
buf.append(stackTraceStr("\t", st, 0, numFrames, printWarning));
buf.append(LINE_SEPARATOR);
}
return buf.toString();
}
static String stackTraceAllStr(int numFrames) {
return stackTraceAllStr(numFrames, false);
}
static void stackTraceAll(int numFrames) {
getRt().send(stackTraceAllStr(numFrames, true));
}
static String stackTraceStr(StackTraceElement[] st, int strip, int numFrames) {
return stackTraceStr(null, st, strip, numFrames, false);
}
static String stackTraceStr(String prefix, StackTraceElement[] st, int strip, int numFrames) {
return stackTraceStr(prefix, st, strip, numFrames, false);
}
private static String stackTraceStr(
String prefix, StackTraceElement[] st, int strip, int numFrames, boolean printWarning) {
strip = strip > 0 ? strip + THRD_DUMP_FRAMES : 0;
numFrames = numFrames > 0 ? numFrames : st.length - strip;
int limit = strip + numFrames;
limit = Math.min(limit, st.length);
if (prefix == null) {
prefix = "";
}
StringBuilder buf = new StringBuilder();
for (int i = strip; i < limit; i++) {
buf.append(prefix);
buf.append(st[i]);
buf.append(LINE_SEPARATOR);
}
if (printWarning && limit < st.length) {
buf.append(prefix);
buf.append(st.length - limit);
buf.append(" more frame(s) ...");
buf.append(LINE_SEPARATOR);
}
return buf.toString();
}
static void stackTrace(StackTraceElement[] st, int strip, int numFrames) {
stackTrace(null, st, strip, numFrames);
}
static void stackTrace(String prefix, StackTraceElement[] st, int strip, int numFrames) {
getRt().send(stackTraceStr(prefix, st, strip, numFrames, true));
}
// print/println functions
static void print(String str) {
getRt().send(str);
}
static void println(String str) {
getRt().send(str + LINE_SEPARATOR);
}
static void println() {
getRt().send(LINE_SEPARATOR);
}
static String property(String name) {
return AccessController.doPrivileged(new GetPropertyAction(name));
}
static Properties properties() {
return AccessController.doPrivileged(
(PrivilegedAction<Properties>) () -> System.getProperties());
}
static String getenv(String name) {
return AccessController.doPrivileged((PrivilegedAction<String>) () -> System.getenv(name));
}
static Map<String, String> getenv() {
return AccessController.doPrivileged(
(PrivilegedAction<Map<String, String>>) () -> System.getenv());
}
static MemoryUsage heapUsage() {
return getRt().getMemoryMXBean().getHeapMemoryUsage();
}
static MemoryUsage nonHeapUsage() {
return getRt().getMemoryMXBean().getNonHeapMemoryUsage();
}
static long finalizationCount() {
return getRt().getMemoryMXBean().getObjectPendingFinalizationCount();
}
static long vmStartTime() {
return getRt().getRuntimeMXBean().getStartTime();
}
static long vmUptime() {
return getRt().getRuntimeMXBean().getUptime();
}
static List<String> getInputArguments() {
return getRt().getRuntimeMXBean().getInputArguments();
}
static String getVmVersion() {
return getRt().getRuntimeMXBean().getVmVersion();
}
static boolean isBootClassPathSupported() {
return getRt().getRuntimeMXBean().isBootClassPathSupported();
}
static String getBootClassPath() {
return getRt().getRuntimeMXBean().getBootClassPath();
}
static long getThreadCount() {
return getRt().getThreadMXBean().getThreadCount();
}
static long getPeakThreadCount() {
return getRt().getThreadMXBean().getPeakThreadCount();
}
static long getTotalStartedThreadCount() {
return getRt().getThreadMXBean().getTotalStartedThreadCount();
}
static long getDaemonThreadCount() {
return getRt().getThreadMXBean().getDaemonThreadCount();
}
static long getCurrentThreadCpuTime() {
ThreadMXBean threadMXBean = getRt().getThreadMXBean();
threadMXBean.setThreadCpuTimeEnabled(true);
return threadMXBean.getCurrentThreadCpuTime();
}
static long getCurrentThreadUserTime() {
ThreadMXBean threadMXBean = getRt().getThreadMXBean();
threadMXBean.setThreadCpuTimeEnabled(true);
return threadMXBean.getCurrentThreadUserTime();
}
static void dumpHeap(String fileName, boolean live) {
try {
String name = getRt().resolveFileName(fileName);
getRt().getHotspotMBean().dumpHeap(name, live);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
static long getTotalGcTime() {
long totalGcTime = 0;
for (GarbageCollectorMXBean gcBean : getRt().getGCMBeans()) {
totalGcTime += gcBean.getCollectionTime();
}
return totalGcTime;
}
static String getMemoryPoolUsage(String poolFormat) {
if (poolFormat == null) {
poolFormat = "%1$s;%2$d;%3$d;%4$d;%5$d";
}
List<MemoryPoolMXBean> memPoolList = getRt().getMemoryPoolMXBeans();
Object[][] poolOutput = new Object[memPoolList.size()][5];
StringBuilder membuffer = new StringBuilder();
for (int i = 0; i < memPoolList.size(); i++) {
MemoryPoolMXBean memPool = memPoolList.get(i);
poolOutput[i][0] = memPool.getName();
poolOutput[i][1] = memPool.getUsage().getMax();
poolOutput[i][2] = memPool.getUsage().getUsed();
poolOutput[i][3] = memPool.getUsage().getCommitted();
poolOutput[i][4] = memPool.getUsage().getInit();
}
for (Object[] memPoolOutput : poolOutput) {
membuffer.append(String.format(poolFormat, memPoolOutput)).append("\n");
}
return membuffer.toString();
}
static double getSystemLoadAverage() {
return getRt().getOperatingSystemMXBean().getSystemLoadAverage();
}
static long getProcessCPUTime() {
OperatingSystemMXBean mbean = getRt().getOperatingSystemMXBean();
if (mbean instanceof com.sun.management.OperatingSystemMXBean) {
return ((com.sun.management.OperatingSystemMXBean) mbean).getProcessCpuTime();
}
return -1;
}
static void serialize(Object obj, String fileName) {
try {
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(getRt().resolveFileName(fileName)));
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(obj);
}
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
static String toXML(Object obj) {
return getRt().toXML(obj);
}
static void writeXML(Object obj, String fileName) {
getRt().writeXML(obj, fileName);
}
static void writeDOT(Object obj, String fileName) {
getRt().writeDOT(obj, fileName);
}
static void deadlocks(boolean stackTrace) {
ThreadMXBean mbean = getRt().getThreadMXBean();
if (mbean.isSynchronizerUsageSupported()) {
long[] tids = mbean.findDeadlockedThreads();
if (tids != null && tids.length > 0) {
ThreadInfo[] infos = mbean.getThreadInfo(tids, true, true);
StringBuilder sb = new StringBuilder();
for (ThreadInfo ti : infos) {
sb.append("\"")
.append(ti.getThreadName())
.append("\"" + " Id=")
.append(ti.getThreadId())
.append(" in ")
.append(ti.getThreadState());
if (ti.getLockName() != null) {
sb.append(" on lock=").append(ti.getLockName());
}
if (ti.isSuspended()) {
sb.append(" (suspended)");
}
if (ti.isInNative()) {
sb.append(" (running in native)");
}
if (ti.getLockOwnerName() != null) {
sb.append(INDENT)
.append(" owned by ")
.append(ti.getLockOwnerName())
.append(" Id=")
.append(ti.getLockOwnerId());
sb.append(LINE_SEPARATOR);
}
if (stackTrace) {
// print stack trace with locks
StackTraceElement[] stacktrace = ti.getStackTrace();
MonitorInfo[] monitors = ti.getLockedMonitors();
for (int i = 0; i < stacktrace.length; i++) {
StackTraceElement ste = stacktrace[i];
sb.append(INDENT).append("at ").append(ste);
sb.append(LINE_SEPARATOR);
for (MonitorInfo mi : monitors) {
if (mi.getLockedStackDepth() == i) {
sb.append(INDENT).append(" - locked ").append(mi);
sb.append(LINE_SEPARATOR);
}
}
}
sb.append(LINE_SEPARATOR);
}
LockInfo[] locks = ti.getLockedSynchronizers();
sb.append(INDENT).append("Locked synchronizers: count = ").append(locks.length);
sb.append(LINE_SEPARATOR);
for (LockInfo li : locks) {
sb.append(INDENT).append(" - ").append(li);
sb.append(LINE_SEPARATOR);
}
sb.append(LINE_SEPARATOR);
}
getRt().send(sb.toString());
}
}
}
static int dtraceProbe(String s1, String s2, int i1, int i2) {
if (getRt().isDTraceEnabled()) {
return dtraceProbe0(s1, s2, i1, i2);
} else {
return 0;
}
}
// called from instrumentation initialization code
public static JfrEvent.Factory createEventFactory(JfrEvent.Template template) {
return getRt().createEventFactory(template);
}
// BTrace aggregation support
static Aggregation newAggregation(AggregationFunction type) {
return new Aggregation(type);
}
static AggregationKey newAggregationKey(Object... elements) {
return new AggregationKey(elements);
}
static void addToAggregation(Aggregation aggregation, long value) {
aggregation.add(value);
}
static void addToAggregation(Aggregation aggregation, AggregationKey key, long value) {
aggregation.add(key, value);
}
static void clearAggregation(Aggregation aggregation) {
aggregation.clear();
}
static void truncateAggregation(Aggregation aggregation, int count) {
aggregation.truncate(count);
}
static void printAggregation(String name, Aggregation aggregation) {
getRt().send(new GridDataCommand(name, aggregation.getData()));
}
static void printSnapshot(String name, Profiler.Snapshot snapshot) {
getRt().send(new GridDataCommand(name, snapshot.getGridData()));
}
/**
* Prints profiling snapshot using the provided format
*
* @param name The name of the aggregation to be used in the textual output
* @param snapshot The snapshot to print
* @param format The format to use. It mimics {@linkplain String#format(java.lang.String,
* java.lang.Object[]) } behaviour with the addition of the ability to address the key title
* as a 0-indexed item
* @see String#format(java.lang.String, java.lang.Object[])
*/
static void printSnapshot(String name, Profiler.Snapshot snapshot, String format) {
getRt().send(new GridDataCommand(name, snapshot.getGridData(), format));
}
/**
* Precondition: Only values from the first Aggregation are printed. If the subsequent
* aggregations have values for keys which the first aggregation does not have, these rows are
* ignored.
*
* @param name
* @param format
* @param aggregationArray
*/
static void printAggregation(String name, String format, Aggregation[] aggregationArray) {
if (aggregationArray.length > 1 && aggregationArray[0].getKeyData().size() > 1) {
int aggregationDataSize =
aggregationArray[0].getKeyData().get(0).getElements().length + aggregationArray.length;
List<Object[]> aggregationData = new ArrayList<>();
// Iterate through all keys in the first Aggregation and build up an array of aggregationData
for (AggregationKey aggKey : aggregationArray[0].getKeyData()) {
int aggDataIndex = 0;
Object[] currAggregationData = new Object[aggregationDataSize];
// Add the key to the from of the current aggregation Data
for (Object obj : aggKey.getElements()) {
currAggregationData[aggDataIndex] = obj;
aggDataIndex++;
}
for (Aggregation agg : aggregationArray) {
currAggregationData[aggDataIndex] = agg.getValueForKey(aggKey);
aggDataIndex++;
}
aggregationData.add(currAggregationData);
}
getRt().send(new GridDataCommand(name, aggregationData, format));
}
}
/**
* Prints aggregation using the provided format
*
* @param name The name of the aggregation to be used in the textual output
* @param aggregation The aggregation to print
* @param format The format to use. It mimics {@linkplain String#format(java.lang.String,
* java.lang.Object[]) } behaviour with the addition of the ability to address the key title
* as a 0-indexed item
* @see String#format(java.lang.String, java.lang.Object[])
*/
static void printAggregation(String name, Aggregation aggregation, String format) {
getRt().send(new GridDataCommand(name, aggregation.getData(), format));
}
/** @see BTraceUtils.Profiling#newProfiler() */
static Profiler newProfiler() {
return getRt().newProfiler();
}
/** @see BTraceUtils.Profiling#newProfiler(int) */
static Profiler newProfiler(int expectedMethodCnt) {
return getRt().newProfiler(expectedMethodCnt);
}
/** @see BTraceUtils.Profiling#recordEntry(Profiler, java.lang.String) */
static void recordEntry(Profiler profiler, String methodName) {
profiler.recordEntry(methodName);
}
// profiling related methods
/** @see BTraceUtils.Profiling#recordExit(Profiler, java.lang.String, long) */
static void recordExit(Profiler profiler, String methodName, long duration) {
profiler.recordExit(methodName, duration);
}
/** @see BTraceUtils.Profiling#snapshot(Profiler) */
static Profiler.Snapshot snapshot(Profiler profiler) {
return profiler.snapshot();
}
/** @see BTraceUtils.Profiling#snapshotAndReset(Profiler) */
static Profiler.Snapshot snapshotAndReset(Profiler profiler) {
return profiler.snapshot(true);
}
static void resetProfiler(Profiler profiler) {
profiler.reset();
}
static ClassLoader getCallerClassloader(int stackDec) {
return getRt().getCallerClassLoader(stackDec + 1);
}
public static Class<?> getCallerClass(int stackDec) {
return getRt().getCallerClass(stackDec + 1);
}
// private methods below this point
// raise DTrace USDT probe
private static native int dtraceProbe0(String s1, String s2, int i1, int i2);
/**
* Common BTrace runtime interface allowing access from various subsystems (core, runtime,
* instrumentation, clients)
*/
public interface Impl {
void send(String msg);
void send(Command cmd);
boolean enter();
void leave();
int getInstrumentationLevel();
void setInstrumentationLevel(int level);
void handleException(Throwable th);
int speculation();
void speculate(int id);
void commit(int id);
void discard(int id);
void exit(int exitCode);
long sizeof(Object obj);
int $length();
String $(int n);
String $(String key);
String toXML(Object obj);
void writeXML(Object obj, String fileName);
void writeDOT(Object obj, String fileName);
Profiler newProfiler();
Profiler newProfiler(int expectedMethodCnt);
int perfInt(String name);
long perfLong(String name);
String perfString(String name);
String resolveFileName(String name);
boolean isDTraceEnabled();
void handleEvent(EventCommand cmd);
void handleExit(int i);
void shutdownCmdLine();
List<MemoryPoolMXBean> getMemoryPoolMXBeans();
HotSpotDiagnosticMXBean getHotspotMBean();
MemoryMXBean getMemoryMXBean();
RuntimeMXBean getRuntimeMXBean();
ThreadMXBean getThreadMXBean();
OperatingSystemMXBean getOperatingSystemMXBean();
List<GarbageCollectorMXBean> getGCMBeans();
Class<?> defineClass(byte[] code, boolean mustBeBootstrap);
ClassLoader getCallerClassLoader(int stackDec);
Class<?> getCallerClass(int stackDec);
JfrEvent.Factory createEventFactory(JfrEvent.Template template);
int version();
}
public interface BTraceRuntimeAccessor {
Impl getRt();
}
private static final class BTraceAtomicInteger extends AtomicInteger {
BTraceAtomicInteger(int initVal) {
super(initVal);
}
}
private static final class BTraceAtomicLong extends AtomicLong {
BTraceAtomicLong(long initVal) {
super(initVal);
}
}
}
| btraceio/btrace | btrace-core/src/main/java/org/openjdk/btrace/core/BTraceRuntime.java |
180,208 | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.refactoring.inline;
import com.intellij.codeInsight.BlockUtils;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.codeInsight.editorActions.DeclarationJoinLinesHandler;
import com.intellij.java.refactoring.JavaRefactoringBundle;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.InlineUtil;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.ArrayUtil;
import com.intellij.util.CommonJavaRefactoringUtil;
import com.intellij.util.containers.MultiMap;
import com.siyeh.ig.psiutils.*;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.util.ObjectUtils.tryCast;
/**
* Performs inlining of object construction together with a subsequent call.
* E.g. {@code new Point(12, 34).getX()} could be inlined to {@code 12}.
*/
public final class InlineObjectProcessor extends BaseRefactoringProcessor {
private final PsiMethod myMethod;
private final PsiReference myReference;
private final PsiNewExpression myNewExpression;
private final PsiMethodCallExpression myNextCall;
private final PsiMethod myNextMethod;
private InlineObjectProcessor(PsiMethod method, PsiReference reference) {
super(method.getProject());
myMethod = method;
myReference = reference;
PsiElement element = myReference.getElement();
myNewExpression = tryCast(element.getParent(), PsiNewExpression.class);
assert myNewExpression != null;
myNextCall = ExpressionUtils.getCallForQualifier(myNewExpression);
assert myNextCall != null;
PsiMethod nextMethod = myNextCall.resolveMethod();
assert nextMethod != null;
PsiElement nav = nextMethod.getNavigationElement();
if (nav instanceof PsiMethod) {
nextMethod = (PsiMethod)nav;
}
myNextMethod = nextMethod;
}
@NotNull
@Override
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo @NotNull [] usages) {
return new InlineViewDescriptor(myMethod);
}
@NotNull
@Override
protected Collection<? extends PsiElement> getElementsToWrite(@NotNull UsageViewDescriptor descriptor) {
return Collections.singletonList(myReference.getElement());
}
@Override
protected UsageInfo @NotNull [] findUsages() {
return new UsageInfo[]{new UsageInfo(myReference)};
}
@Override
protected void performRefactoring(UsageInfo @NotNull [] usages) {
ChangeContextUtil.encodeContextInfo(myMethod, false);
PsiMethod ctorCopy = (PsiMethod)myMethod.copy();
ChangeContextUtil.clearContextInfo(myMethod);
ChangeContextUtil.encodeContextInfo(myNextMethod, false);
PsiMethod nextCopy = (PsiMethod)myNextMethod.copy();
ChangeContextUtil.clearContextInfo(myNextMethod);
InlineMethodHelper ctorHelper = new InlineMethodHelper(myProject, myMethod, ctorCopy, myNewExpression);
InlineMethodHelper nextHelper = new InlineMethodHelper(myProject, myNextMethod, nextCopy, myNextCall);
PsiClass aClass = myMethod.getContainingClass();
assert aClass != null;
PsiElementFactory factory = JavaPsiFacade.getElementFactory(myProject);
PsiCodeBlock target = factory.createCodeBlock();
List<PsiLocalVariable> fieldLocals = new ArrayList<>();
for (PsiField field : aClass.getFields()) {
if (!field.hasModifierProperty(PsiModifier.STATIC)) {
PsiDeclarationStatement declaration =
factory.createVariableDeclarationStatement(field.getName(), field.getType(), field.getInitializer(), aClass);
fieldLocals.add((PsiLocalVariable)((PsiDeclarationStatement)target.add(declaration)).getDeclaredElements()[0]);
}
}
PsiLocalVariable[] ctorParameters = ctorHelper.declareParameters();
ctorHelper.substituteTypes(ctorParameters);
InlineTransformer ctorTransformer = InlineTransformer.getSuitableTransformer(myMethod).apply(myReference);
ctorTransformer.transformBody(ctorCopy, myReference, PsiTypes.voidType());
PsiCodeBlock ctorBody = Objects.requireNonNull(ctorCopy.getBody());
InlineUtil.solveLocalNameConflicts(ctorBody, target, ctorBody);
updateFieldRefs(ctorCopy, aClass);
ctorParameters = addRange(target, ctorBody, ctorParameters);
PsiLocalVariable[] nextParameters = nextHelper.declareParameters();
nextHelper.substituteTypes(nextParameters);
InlineTransformer nextTransformer = InlineTransformer.getSuitableTransformer(myNextMethod).apply(myNextCall.getMethodExpression());
PsiLocalVariable result = nextTransformer.transformBody(nextCopy, myNextCall.getMethodExpression(), myNextCall.getType());
PsiCodeBlock nextBody = Objects.requireNonNull(nextCopy.getBody());
InlineUtil.solveLocalNameConflicts(nextBody, target, nextBody);
updateFieldRefs(nextCopy, aClass);
if (result != null) {
PsiLocalVariable[] resultAndParameters = ArrayUtil.prepend(result, nextParameters);
resultAndParameters = addRange(target, nextBody, resultAndParameters);
result = resultAndParameters[0];
nextParameters = Arrays.copyOfRange(resultAndParameters, 1, resultAndParameters.length);
}
else {
nextParameters = addRange(target, nextBody, nextParameters);
}
InlineUtil.solveLocalNameConflicts(target, myReference.getElement(), target);
ctorHelper.initializeParameters(ctorParameters);
nextHelper.initializeParameters(nextParameters);
removeRedundantFieldVars(fieldLocals, target);
ctorHelper.inlineParameters(ctorParameters);
nextHelper.inlineParameters(nextParameters);
PsiElement anchor = CommonJavaRefactoringUtil.getParentStatement(myNextCall, true);
assert anchor != null;
PsiElement anchorParent = anchor.getParent();
PsiStatement[] statements = target.getStatements();
PsiElement firstBodyElement = target.getFirstBodyElement();
if (firstBodyElement instanceof PsiWhiteSpace) firstBodyElement = PsiTreeUtil.skipWhitespacesForward(firstBodyElement);
PsiElement firstAdded = null;
if (firstBodyElement != null && firstBodyElement != target.getRBrace()) {
int last = statements.length - 1;
final PsiElement rBraceOrReturnStatement =
last >= 0 ? PsiTreeUtil.skipWhitespacesAndCommentsForward(statements[last]) : target.getLastBodyElement();
assert rBraceOrReturnStatement != null;
final PsiElement beforeRBraceStatement = rBraceOrReturnStatement.getPrevSibling();
assert beforeRBraceStatement != null;
firstAdded = anchorParent.addRangeBefore(firstBodyElement, beforeRBraceStatement, anchor);
ChangeContextUtil.decodeContextInfo(anchorParent, null, null);
}
PsiReferenceExpression resultUsage = InlineMethodProcessor.replaceCall(factory, myNextCall, firstAdded, result);
if (resultUsage != null) {
PsiLocalVariable resultVar = ExpressionUtils.resolveLocalVariable(resultUsage);
if (resultVar != null) {
InlineUtil.tryInlineResultVariable(resultVar, resultUsage);
}
}
}
private static void removeRedundantFieldVars(List<PsiLocalVariable> vars, PsiCodeBlock block) {
for (PsiLocalVariable var : vars) {
List<PsiReferenceExpression> references = VariableAccessUtils.getVariableReferences(var, block);
PsiAssignmentExpression firstAssignment = null;
List<PsiAssignmentExpression> assignments = new ArrayList<>();
for (PsiReferenceExpression reference : references) {
PsiAssignmentExpression assignment = tryCast(PsiUtil.skipParenthesizedExprUp(reference.getParent()), PsiAssignmentExpression.class);
if (assignment != null && assignment.getOperationTokenType().equals(JavaTokenType.EQ) &&
PsiUtil.skipParenthesizedExprDown(assignment.getLExpression()) == reference &&
assignment.getParent() instanceof PsiExpressionStatement) {
assignments.add(assignment);
if (firstAssignment == null && assignment.getParent().getParent() == block) {
firstAssignment = assignment;
}
}
else {
assignments = null;
break;
}
}
if (assignments != null) {
for (PsiAssignmentExpression assignment : assignments) {
PsiExpressionStatement statement = (PsiExpressionStatement)assignment.getParent();
PsiExpression expression = assignment.getRExpression();
CommentTracker ct = new CommentTracker();
if (expression != null) {
List<PsiExpression> sideEffects = SideEffectChecker.extractSideEffectExpressions(expression);
sideEffects.forEach(ct::markUnchanged);
PsiStatement[] statements = StatementExtractor.generateStatements(sideEffects, expression);
if (statements.length > 0) {
BlockUtils.addBefore(statement, statements);
}
}
ct.deleteAndRestoreComments(statement);
}
new CommentTracker().deleteAndRestoreComments(var);
}
else if (firstAssignment != null) {
var = DeclarationJoinLinesHandler.joinDeclarationAndAssignment(var, firstAssignment);
InlineUtil.tryInlineGeneratedLocal(var, false);
}
}
}
private static PsiLocalVariable[] addRange(PsiCodeBlock target, PsiCodeBlock body, PsiLocalVariable[] declaredVars) {
PsiElement firstBodyElement = body.getFirstBodyElement();
PsiElement lastBodyElement = body.getLastBodyElement();
if (firstBodyElement == null || lastBodyElement == null) return declaredVars;
PsiElement firstAdded = target.addRange(firstBodyElement, lastBodyElement);
PsiLocalVariable[] updatedVars = new PsiLocalVariable[declaredVars.length];
int index = 0;
for (PsiElement e = firstAdded; index < updatedVars.length && e != null; e = e.getNextSibling()) {
if (e instanceof PsiDeclarationStatement) {
PsiElement[] elements = ((PsiDeclarationStatement)e).getDeclaredElements();
if (elements.length == 1) {
PsiLocalVariable var = tryCast(elements[0], PsiLocalVariable.class);
if (var != null) {
if (var.getName().equals(declaredVars[index].getName())) {
updatedVars[index++] = var;
}
}
}
}
}
assert index == updatedVars.length;
return updatedVars;
}
private static void updateFieldRefs(PsiMethod method, PsiClass aClass) {
PsiCodeBlock body = method.getBody();
assert body != null;
for (PsiThisExpression thisExpression : PsiTreeUtil.findChildrenOfType(body, PsiThisExpression.class)) {
PsiElement parent = PsiUtil.skipParenthesizedExprUp(thisExpression.getParent());
if (parent instanceof PsiReferenceExpression) {
PsiField field = tryCast(((PsiReferenceExpression)parent).resolve(), PsiField.class);
if (field != null && field.getContainingClass() == aClass) {
thisExpression.delete();
}
}
}
}
@Override
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
final UsageInfo[] usagesIn = refUsages.get();
final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
final ReferencedElementsCollector collector = new ReferencedElementsCollector();
myMethod.accept(collector);
myNextMethod.accept(collector);
final Map<PsiMember, Set<PsiMember>> containersToReferenced = InlineMethodProcessor
.getInaccessible(collector.myReferencedMembers, usagesIn, myMethod);
containersToReferenced.forEach((container, referencedInaccessible) -> {
for (PsiMember referenced : referencedInaccessible) {
if (referenced instanceof PsiField && !referenced.hasModifierProperty(PsiModifier.STATIC) &&
referenced.getContainingClass() == myMethod.getContainingClass()) {
// Instance fields will be inlined
continue;
}
final String referencedDescription = RefactoringUIUtil.getDescription(referenced, true);
final String containerDescription = RefactoringUIUtil.getDescription(container, true);
String message = RefactoringBundle.message("0.that.is.used.in.inlined.method.is.not.accessible.from.call.site.s.in.1",
referencedDescription, containerDescription);
conflicts.putValue(container, StringUtil.capitalize(message));
}
});
return showConflicts(conflicts, usagesIn);
}
@NotNull
@Override
protected String getCommandName() {
return JavaRefactoringBundle.message("inline.object.command.name");
}
@Nullable
public static InlineObjectProcessor create(PsiReference reference, PsiMethod method) {
if (!canInlineConstructorAndChainCall(reference, method)) {
return null;
}
return new InlineObjectProcessor(method, reference);
}
@Contract("null, _ -> false")
private static boolean canInlineConstructorAndChainCall(PsiReference reference, PsiMethod method) {
if (reference == null) return false;
PsiElement element = reference.getElement();
if (!(element instanceof PsiJavaCodeReferenceElement)) return false;
PsiNewExpression expression = tryCast(element.getParent(), PsiNewExpression.class);
if (expression == null) return false;
PsiMethodCallExpression call = ExpressionUtils.getCallForQualifier(expression);
if (call == null) return false;
if (CommonJavaRefactoringUtil.getParentStatement(call, true) == null) return false;
PsiMethod nextMethod = call.resolveMethod();
if (nextMethod == null) return false;
PsiElement nav = nextMethod.getNavigationElement();
if (nav instanceof PsiMethod) {
nextMethod = (PsiMethod)nav;
}
PsiClass aClass = method.getContainingClass();
if (aClass == null) return false;
if (aClass.getContainingClass() != null && !aClass.hasModifierProperty(PsiModifier.STATIC)) return false;
PsiClassType[] supers = aClass.getExtendsListTypes();
if (supers.length > 1) return false;
if (supers.length == 1 && !isStatelessSuperClass(supers[0], new HashSet<>())) return false;
for (PsiField field : aClass.getFields()) {
if (!field.hasModifierProperty(PsiModifier.STATIC)) {
PsiExpression initializer = field.getInitializer();
if (initializer != null && mayLeakThis(initializer)) return false;
}
}
for (PsiClassInitializer initializer : aClass.getInitializers()) {
if (!initializer.hasModifierProperty(PsiModifier.STATIC)) {
return false;
}
}
return !mayLeakThis(method) && !mayLeakThis(nextMethod);
}
private static boolean isStatelessSuperClass(PsiClassType psiType, Set<PsiClass> checked) {
if (TypeUtils.isJavaLangObject(psiType)) return true;
PsiClass psiClass = psiType.resolve();
if (psiClass == null || !checked.add(psiClass)) return false;
PsiMethod[] constructors = psiClass.getConstructors();
for (PsiMethod constructor : constructors) {
if (constructor.getParameterList().isEmpty()) {
PsiElement nav = constructor.getNavigationElement();
if (nav instanceof PsiMethod) {
constructor = (PsiMethod)nav;
}
PsiCodeBlock body = constructor.getBody();
if (body == null || !ControlFlowUtils.isEmptyCodeBlock(body)) return false;
}
}
for (PsiField field : psiClass.getFields()) {
if (!field.hasModifierProperty(PsiModifier.STATIC)) return false;
}
PsiClassType[] supers = psiClass.getExtendsListTypes();
return supers.length == 0 || supers.length == 1 && isStatelessSuperClass(supers[0], checked);
}
private static boolean mayLeakThis(PsiMethod method) {
if (method == null) return true;
PsiCodeBlock body = method.getBody();
if (body == null) return true;
return mayLeakThis(body);
}
private static boolean mayLeakThis(PsiElement body) {
class Visitor extends JavaRecursiveElementWalkingVisitor {
boolean leak = false;
@Override
public void visitMethodCallExpression(@NotNull PsiMethodCallExpression call) {
super.visitMethodCallExpression(call);
PsiExpression qualifier = ExpressionUtils.getEffectiveQualifier(call.getMethodExpression());
if (qualifier instanceof PsiQualifiedExpression) {
leak = true;
stopWalking();
}
}
@Override
public void visitNewExpression(@NotNull PsiNewExpression expression) {
super.visitNewExpression(expression);
if (expression.getQualifier() == null) {
PsiJavaCodeReferenceElement reference = expression.getClassReference();
if (reference != null) {
PsiClass target = tryCast(reference.resolve(), PsiClass.class);
if (target != null && target.getContainingClass() != null && !target.hasModifierProperty(PsiModifier.STATIC)) {
leak = true;
stopWalking();
}
}
}
}
@Override
public void visitThisExpression(@NotNull PsiThisExpression expression) {
super.visitThisExpression(expression);
PsiElement parent = PsiUtil.skipParenthesizedExprUp(expression.getParent());
if (!(parent instanceof PsiReferenceExpression)) {
leak = true;
stopWalking();
}
}
}
Visitor visitor = new Visitor();
body.accept(visitor);
return visitor.leak;
}
}
| JetBrains/intellij-community | java/java-impl-refactorings/src/com/intellij/refactoring/inline/InlineObjectProcessor.java |
180,210 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.googlejavaformat;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Range;
import com.google.googlejavaformat.OpsBuilder.BlankLineWanted;
import java.util.Optional;
/** An output from the formatter. */
public abstract class Output extends InputOutput {
/** Unique identifier for a break. */
public static final class BreakTag {
Optional<Boolean> taken = Optional.empty();
public void recordBroken(boolean broken) {
// TODO(cushon): enforce invariants.
// Currently we rely on setting Breaks multiple times, e.g. when deciding
// whether a Level should be flowed. Using separate data structures
// instead of mutation or adding an explicit 'reset' step would allow
// a useful invariant to be enforced here.
taken = Optional.of(broken);
}
public boolean wasBreakTaken() {
return taken.orElse(false);
}
}
/**
* Indent by outputting {@code indent} spaces.
*
* @param indent the current indent
*/
public abstract void indent(int indent);
/**
* Output a string.
*
* @param text the string
* @param range the {@link Range} corresponding to the string
*/
public abstract void append(String text, Range<Integer> range);
/**
* A blank line is or is not wanted here.
*
* @param k the {@link Input.Tok} index
* @param wanted whether a blank line is wanted here
*/
public abstract void blankLine(int k, BlankLineWanted wanted);
/** Marks a region that can be partially formatted. */
public abstract void markForPartialFormat(Input.Token start, Input.Token end);
/**
* Get the {@link CommentsHelper}.
*
* @return the {@link CommentsHelper}
*/
public abstract CommentsHelper getCommentsHelper();
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("super", super.toString()).toString();
}
}
| google/google-java-format | core/src/main/java/com/google/googlejavaformat/Output.java |
180,212 | /*
* Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the Classpath exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.btrace.core;
import java.io.Serializable;
import java.lang.management.MemoryUsage;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import jdk.jfr.Event;
import org.openjdk.btrace.core.aggregation.Aggregation;
import org.openjdk.btrace.core.aggregation.AggregationFunction;
import org.openjdk.btrace.core.aggregation.AggregationKey;
import org.openjdk.btrace.core.annotations.OnMethod;
import org.openjdk.btrace.core.annotations.ProbeClassName;
import org.openjdk.btrace.core.annotations.ProbeMethodName;
import org.openjdk.btrace.core.annotations.Self;
import org.openjdk.btrace.core.jfr.JfrEvent;
import org.openjdk.btrace.core.types.AnyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is an all-in-one wrapper for BTrace DSL methods
*
* @author A. Sundararajan
* @author Jaroslav Bachorik
*/
public class BTraceUtils {
private static final Logger log = LoggerFactory.getLogger(BTraceUtils.class);
// standard stack depth decrement for figuring out the caller class calls
private static final int STACK_DEC = 2;
static {
BTraceRuntime.initUnsafe();
}
// do not allow object creation!
private BTraceUtils() {}
// Thread and stack access
/**
* Tests whether this thread has been interrupted. The <i>interrupted status</i> of the thread is
* unaffected by this method.
*
* <p>A thread interruption ignored because a thread was not alive at the time of the interrupt
* will be reflected by this method returning false.
*
* @return <code>true</code> if this thread has been interrupted; <code>false</code> otherwise.
*/
public static boolean isInteruppted() {
return Threads.isInteruppted();
}
/** Prints the java stack trace of the current thread. */
public static void jstack() {
Threads.jstack(2, -1);
}
/**
* Prints the java stack trace of the current thread. But, at most given number of frames.
*
* @param numFrames number of frames to be printed. When this is negative all frames are printed.
*/
public static void jstack(int numFrames) {
Threads.jstack(2, numFrames);
}
/** Prints Java stack traces of all the Java threads. */
public static void jstackAll() {
Threads.jstackAll(2, -1);
}
/**
* Prints Java stack traces of all the Java threads. But, at most given number of frames.
*
* @param numFrames number of frames to be printed. When this is negative all frames are printed.
*/
public static void jstackAll(int numFrames) {
Threads.jstackAll(2, numFrames);
}
/**
* Returns the stack trace of current thread as a String.
*
* @return the stack trace as a String.
*/
public static String jstackStr() {
return Threads.jstackStr(2, -1);
}
/**
* Returns the stack trace of the current thread as a String but includes at most the given number
* of frames.
*
* @param numFrames number of frames to be included. When this is negative all frames are
* included.
* @return the stack trace as a String.
*/
public static String jstackStr(int numFrames) {
return Threads.jstackStr(2, numFrames);
}
/**
* Returns the stack traces of all Java threads as a String.
*
* @return the stack traces as a String.
*/
public static String jstackAllStr() {
return Threads.jstackAllStr();
}
/**
* Returns at most given number of frames in stack traces of all threads as a String.
*
* @param numFrames number of frames to be included. When this is negative all frames are
* included.
* @return the stack traces as a String.
*/
public static String jstackAllStr(int numFrames) {
return Threads.jstackAllStr(numFrames);
}
/**
* Prints the stack trace of the given exception object.
*
* @param exception throwable for which stack trace is printed.
*/
public static void jstack(Throwable exception) {
Threads.jstack(exception);
}
/**
* Prints the stack trace of the given exception object. But, prints atmost given number of
* frames.
*
* @param exception throwable for which stack trace is printed.
* @param numFrames maximum number of frames to be printed.
*/
public static void jstack(Throwable exception, int numFrames) {
Threads.jstack(exception, numFrames);
}
/**
* Returns the stack trace of given exception object as a String.
*
* @param exception the throwable for which stack trace is returned.
*/
public static String jstackStr(Throwable exception) {
return Threads.jstackStr(exception);
}
/**
* Returns stack trace of given exception object as a String.
*
* @param exception throwable for which stack trace is returned.
* @param numFrames maximum number of frames to be returned.
*/
public static String jstackStr(Throwable exception, int numFrames) {
return Threads.jstackStr(exception, numFrames);
}
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static Thread currentThread() {
return Threads.currentThread();
}
/**
* Returns the identifier of the given Thread. The thread ID is a positive <tt>long</tt> number
* generated when the given thread was created. The thread ID is unique and remains unchanged
* during its lifetime. When a thread is terminated, the thread ID may be reused.
*/
public static long threadId(Thread thread) {
return Threads.threadId(thread);
}
/**
* Returns the state of the given thread. This method is designed for use in monitoring of the
* system state, not for synchronization control.
*/
public static Thread.State threadState(Thread thread) {
return Threads.threadState(thread);
}
/**
* Returns <tt>true</tt> if and only if the current thread holds the monitor lock on the specified
* object.
*
* <p>This method is designed to allow a program to assert that the current thread already holds a
* specified lock:
*
* <pre>
* assert Thread.holdsLock(obj);
* </pre>
*
* @param obj the object on which to test lock ownership
* @return <tt>true</tt> if the current thread holds the monitor lock on the specified object.
* @throws NullPointerException if obj is <tt>null</tt>
*/
public static boolean holdsLock(Object obj) {
return Threads.holdsLock(obj);
}
/** Prints the Java level deadlocks detected (if any). */
public static void deadlocks() {
Threads.deadlocks();
}
/**
* Prints deadlocks detected (if any). Optionally prints stack trace of the deadlocked threads.
*
* @param stackTrace boolean flag to specify whether to print stack traces of deadlocked threads
* or not.
*/
public static void deadlocks(boolean stackTrace) {
Threads.deadlocks(stackTrace);
}
/**
* Returns the name of the given thread.
*
* @param thread thread whose name is returned
*/
public static String name(Thread thread) {
return Threads.name(thread);
}
// class loader access
/**
* Returns the class loader for the given class. Some implementations may use null to represent
* the bootstrap class loader. This method will return null in such implementations if this class
* was loaded by the bootstrap class loader.
*
* @param clazz the Class for which the class loader is returned
*/
public static ClassLoader loader(Class<?> clazz) {
return clazz.getClassLoader();
}
/**
* Returns the parent class loader of the given loader. Some implementations may use <tt>null</tt>
* to represent the bootstrap class loader. This method will return <tt>null</tt> in such
* implementations if this class loader's parent is the bootstrap class loader.
*
* @param loader the loader for which the parent loader is returned
* @return The parent <tt>ClassLoader</tt>
*/
public static ClassLoader parentLoader(ClassLoader loader) {
return loader.getParent();
}
// java.lang.Object methods
/**
* Returns a string representation of the object. In general, the <code>toString</code> method
* returns a string that "textually represents" this object. The result should be a concise but
* informative representation that is easy for a person to read. For bootstrap classes, returns
* the result of calling Object.toString() override. For non-bootstrap classes, default toString()
* value [className@hashCode] is returned.
*
* @param obj the object whose string representation is returned
* @return a string representation of the given object.
*/
public static String str(Object obj) {
return Strings.str(obj);
}
/**
* Returns identity string of the form class-name@identity-hash
*
* @param obj object for which identity string is returned
* @return identity string
*/
public static String identityStr(Object obj) {
int hashCode = java.lang.System.identityHashCode(obj);
return obj.getClass().getName() + "@" + Integer.toHexString(hashCode);
}
/**
* Returns a hash code value for the object. This method is supported for the benefit of
* hashtables such as those provided by <code>java.util.Hashtable</code>. For bootstrap classes,
* returns the result of calling Object.hashCode() override. For non-bootstrap classes, the
* identity hash code is returned.
*
* @param obj the Object whose hash code is returned.
* @return a hash code value for the given object.
*/
public static int hash(Object obj) {
if (obj.getClass().getClassLoader() == null) {
return obj.hashCode();
} else {
return java.lang.System.identityHashCode(obj);
}
}
/**
* Returns the same hash code for the given object as would be returned by the default method
* hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the
* null reference is zero.
*
* @param obj object for which the hashCode is to be calculated
* @return the hashCode
*/
public static int identityHashCode(Object obj) {
return java.lang.System.identityHashCode(obj);
}
/**
* Indicates whether two given objects are "equal to" one another. For bootstrap classes, returns
* the result of calling Object.equals() override. For non-bootstrap classes, the reference
* identity comparison is done.
*
* @param obj1 first object to compare equality
* @param obj2 second object to compare equality
* @return <code>true</code> if the given objects are equal; <code>false</code> otherwise.
*/
public static boolean compare(Object obj1, Object obj2) {
return BTraceRuntime.compare(obj1, obj2);
}
// reflection
/**
* Returns the runtime class of the given Object.
*
* @param obj the Object whose Class is returned
* @return the Class object of given object
*/
public static Class<?> classOf(Object obj) {
return Reflective.classOf(obj);
}
/**
* Checks whether the provided object is an instance of the named class. <cite>Note: this method
* can be rather CPU intensive, use with caution</cite>
*
* @param obj the object to check
* @param className the class name; as a special case {@code void} can be provided to check
* whether the instance is a void value wrapper - {@linkplain AnyType#VOID}
* @return {@code true} if the object can be assigned to an instance of 'className' type
* @since 1.3.5
*/
public static boolean instanceOf(Object obj, String className) {
return BTraceRuntime.instanceOf(obj, className);
}
/**
* Returns the Class object representing the class or interface that declares the field
* represented by the given Field object.
*
* @param field whose declaring Class is returned
*/
public static Class<?> declaringClass(Field field) {
return Reflective.declaringClass(field);
}
/** Returns the name of the given Class object. */
public static String name(Class<?> clazz) {
return Reflective.name(clazz);
}
/**
* Returns the name of the Field object.
*
* @param field Field for which name is returned
* @return name of the given field
*/
public static String name(Field field) {
return Reflective.name(field);
}
/**
* Returns the type of the Field object.
*
* @param field Field for which type is returned
* @return type of the given field
*/
public static Class<?> type(Field field) {
return Reflective.type(field);
}
/** Returns the access flags of the given Class. */
public static int accessFlags(Class<?> clazz) {
return Reflective.accessFlags(clazz);
}
/** Returns the access flags of the given Field. */
public static int accessFlags(Field field) {
return Reflective.accessFlags(field);
}
/** Returns the current context class loader */
public static ClassLoader contextClassLoader() {
return Reflective.contextClassLoader();
}
// get Class of the given name
/** Returns Class object for given class name. */
public static Class classForName(String name) {
return Reflective.classForName(name);
}
/** Returns the Class for the given class name using the given class loader. */
public static Class classForName(String name, ClassLoader cl) {
return Reflective.classForName(name, cl);
}
/**
* Determines if the class or interface represented by the first <code>Class</code> object is
* either the same as, or is a superclass or superinterface of, the class or interface represented
* by the second <code>Class</code> parameter. It returns <code>true</code> if so; otherwise it
* returns <code>false</code>.
*/
public static boolean isAssignableFrom(Class<?> a, Class<?> b) {
return Reflective.isAssignableFrom(a, b);
}
/**
* Determines if the specified <code>Object</code> is assignment-compatible with the object
* represented by the specified <code>Class</code>. This method is the dynamic equivalent of the
* Java language <code>instanceof</code> operator. The method returns <code>true</code> if the
* specified <code>Object</code> argument is non-null and can be cast to the reference type
* represented by this <code>Class</code> object without raising a <code>ClassCastException.
* </code> It returns <code>false</code> otherwise.
*
* @param clazz the class that is checked.
* @param obj the object to check.
* @return true if <code>obj</code> is an instance of the given class.
*/
public static boolean isInstance(Class<?> clazz, Object obj) {
return Reflective.isInstance(clazz, obj);
}
/**
* Returns the <code>Class</code> representing the superclass of the entity (class, interface,
* primitive type or void) represented by the given <code>Class</code>. If the given <code>Class
* </code> represents either the <code>Object</code> class, an interface, a primitive type, or
* void, then null is returned. If the given object represents an array class then the <code>Class
* </code> object representing the <code>Object</code> class is returned.
*
* @param clazz the Class whose super class is returned.
* @return the superclass of the class represented by the given object.
*/
public static Class<?> getSuperclass(Class<?> clazz) {
return Reflective.getSuperclass(clazz);
}
/**
* Determines if the specified <code>Class</code> object represents an interface type.
*
* @param clazz the Class object to check.
* @return <code>true</code> if the Class represents an interface; <code>false</code> otherwise.
*/
public static boolean isInterface(Class<?> clazz) {
return Reflective.isInterface(clazz);
}
/**
* Determines if the given <code>Class</code> object represents an array class.
*
* @param clazz Class object to check.
* @return <code>true</code> if the given object represents an array class; <code>false</code>
* otherwise.
*/
public static boolean isArray(Class<?> clazz) {
return Reflective.isArray(clazz);
}
/** Returns whether the given Class represent primitive type or not. */
public static boolean isPrimitive(Class<?> clazz) {
return Reflective.isPrimitive(clazz);
}
/** returns component type of an array Class. */
public static Class<?> getComponentType(Class<?> clazz) {
return Reflective.getComponentType(clazz);
}
// Accessing fields by reflection
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class or
* interface represented by the given <code>Class</code> object. The <code>name</code> parameter
* is a <code>String</code> that specifies the simple name of the desired field. Returns <code>
* null</code> on not finding field if throwException parameter is <code>false</code>. Else throws
* a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @param throwException whether to throw exception on failing to find field or not
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(Class<?> clazz, String name, boolean throwException) {
return Reflective.field(clazz, name, throwException);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class or
* interface represented by the given <code>Class</code> object. The <code>name</code> parameter
* is a <code>String</code> that specifies the simple name of the desired field. Throws a <code>
* RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(Class<?> clazz, String name) {
return Reflective.field(clazz, name);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class or
* interface represented by the given <code>Class</code> object. The <code>name</code> parameter
* is a <code>String</code> that specifies the simple name of the desired field. Returns <code>
* null</code> on not finding field if throwException parameter is <code>false</code>. Else throws
* a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @param throwException whether to throw exception on failing to find field or not
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(String clazz, String name, boolean throwException) {
ClassLoader callerLoader = BTraceRuntime.getCallerClassloader(STACK_DEC);
return Reflective.field(classForName(clazz, callerLoader), name, throwException);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class or
* interface represented by the given <code>Class</code> object. The <code>name</code> parameter
* is a <code>String</code> that specifies the simple name of the desired field. Throws a <code>
* RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(String clazz, String name) {
ClassLoader callerLoader = BTraceRuntime.getCallerClassloader(STACK_DEC);
return Reflective.field(classForName(clazz, callerLoader), name);
}
// field value get methods
/**
* Gets the value of a static <code>byte</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>byte</code> field
*/
public static byte getByte(Field field) {
return Reflective.getByte(field);
}
/**
* Gets the value of an instance <code>byte</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>byte</code> value from
* @return the value of the <code>byte</code> field
*/
public static byte getByte(Field field, Object obj) {
return Reflective.getByte(field, obj);
}
/**
* Gets the value of a static <code>short</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>short</code> field
*/
public static short getShort(Field field) {
return Reflective.getShort(field);
}
/**
* Gets the value of an instance <code>short</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>short</code> value from
* @return the value of the <code>short</code> field
*/
public static short getShort(Field field, Object obj) {
return Reflective.getShort(field, obj);
}
/**
* Gets the value of a static <code>int</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>int</code> field
*/
public static int getInt(Field field) {
return Reflective.getInt(field);
}
/**
* Gets the value of an instance <code>int</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>int</code> value from
* @return the value of the <code>int</code> field
*/
public static int getInt(Field field, Object obj) {
return Reflective.getInt(field, obj);
}
/**
* Gets the value of a static <code>long</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>long</code> field
*/
public static long getLong(Field field) {
return Reflective.getLong(field);
}
/**
* Gets the value of an instance <code>long</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>long</code> value from
* @return the value of the <code>long</code> field
*/
public static long getLong(Field field, Object obj) {
return Reflective.getLong(field, obj);
}
/**
* Gets the value of a static <code>float</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>float</code> field
*/
public static float getFloat(Field field) {
return Reflective.getFloat(field);
}
/**
* Gets the value of an instance <code>float</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>float</code> value from
* @return the value of the <code>float</code> field
*/
public static float getFloat(Field field, Object obj) {
return Reflective.getFloat(field, obj);
}
/**
* Gets the value of a static <code>double</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>double</code> field
*/
public static double getDouble(Field field) {
return Reflective.getDouble(field);
}
/**
* Gets the value of an instance <code>double</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>double</code> value from
* @return the value of the <code>double</code> field
*/
public static double getDouble(Field field, Object obj) {
return Reflective.getDouble(field, obj);
}
/**
* Gets the value of a static <code>boolean</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>boolean</code> field
*/
public static boolean getBoolean(Field field) {
return Reflective.getBoolean(field);
}
/**
* Gets the value of an instance <code>boolean</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>boolean</code> value from
* @return the value of the <code>boolean</code> field
*/
public static boolean getBoolean(Field field, Object obj) {
return Reflective.getBoolean(field, obj);
}
/**
* Gets the value of a static <code>char</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>char</code> field
*/
public static char getChar(Field field) {
return Reflective.getChar(field);
}
/**
* Gets the value of an instance <code>char</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>char</code> value from
* @return the value of the <code>char</code> field
*/
public static char getChar(Field field, Object obj) {
return Reflective.getChar(field, obj);
}
/**
* Gets the value of a static reference field.
*
* @param field Field object whose value is returned.
* @return the value of the reference field
*/
public static Object get(Field field) {
return Reflective.get(field);
}
/**
* Gets the value of an instance reference field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the reference value from
* @return the value of the reference field
*/
public static Object get(Field field, Object obj) {
return Reflective.get(field, obj);
}
// weak, soft references
/**
* Creates and returns a weak reference to the given object.
*
* @param obj object for which a weak reference is created.
* @return a weak reference to the given object.
*/
public static WeakReference weakRef(Object obj) {
return References.weakRef(obj);
}
/**
* Creates and returns a soft reference to the given object.
*
* @param obj object for which a soft reference is created.
* @return a soft reference to the given object.
*/
public static SoftReference softRef(Object obj) {
return References.softRef(obj);
}
/**
* Returns the given reference object's referent. If the reference object has been cleared, either
* by the program or by the garbage collector, then this method returns <code>null</code>.
*
* @param ref reference object whose referent is returned.
* @return The object to which the reference refers, or <code>null</code> if the reference object
* has been cleared.
*/
public static Object deref(Reference ref) {
return References.deref(ref);
}
// probe point access
/**
* Returns the Class object of the currently probed (or traced) class.
*
* @deprecated Since 1.1. Use {@linkplain ProbeClassName} and {@linkplain Self} annotations
* instead
*/
@Deprecated
public static Class<?> probeClass() {
return BTraceRuntime.getCallerClass(STACK_DEC);
}
/**
* Returns the currently probed method's name.
*
* @deprecated Since 1.1. Use {@linkplain ProbeMethodName} annotation instead
*/
@Deprecated
public static String probeMethod() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length >= 4) {
return stack[3].getMethodName();
} else {
return null;
}
}
/** Returns the currently probed source line number (if available). */
public static int probeLine() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length >= 4) {
return stack[3].getLineNumber();
} else {
return -1;
}
}
// printing values
/**
* Prints the given Map.
*
* @param map Map that is printed.
*/
public static void printMap(Map map) {
BTraceRuntime.printMap(map);
}
/**
* Prints the given Map.
*
* @param name - the name of the map
* @param data - the map data
*/
public static void printStringMap(String name, Map<String, String> data) {
BTraceRuntime.printStringMap(name, data);
}
/**
* Prints the given Map.
*
* @param name - the name of the map
* @param data - the map data
*/
public static void printNumberMap(String name, Map<String, ? extends Number> data) {
BTraceRuntime.printNumberMap(name, data);
}
/**
* Prints a number.
*
* @param name - name of the number data
* @param value - value of the numerical data
*/
public static void printNumber(String name, Number value) {
BTraceRuntime.printNumber(name, value);
}
/** Prints the elements of the given array as comma separated line bounded by '[' and ']'. */
public static void printArray(Object[] array) {
StringBuilder buf = new StringBuilder();
buf.append('[');
for (Object obj : array) {
buf.append(Strings.str(obj));
buf.append(", ");
}
buf.append(']');
println(buf.toString());
}
/**
* Print all instance fields of an object as name-value pairs. Includes the inherited fields as
* well.
*
* @param obj Object whose fields are printed.
*/
public static void printFields(Object obj) {
Reflective.printFields(obj, false);
}
/**
* Print all instance fields of an object as name-value pairs. Includes the inherited fields as
* well. Optionally, prints name of the declaring class before each field - so that if same named
* field in super class chain may be disambiguated.
*
* @param obj Object whose fields are printed.
* @param classNamePrefix flag to tell whether to prefix field names names by class name or not.
*/
public static void printFields(Object obj, boolean classNamePrefix) {
Reflective.printFields(obj, classNamePrefix);
}
/**
* Print all static fields of the class as name-value pairs. Includes the inherited fields as
* well.
*
* @param clazz Class whose static fields are printed.
*/
public static void printStaticFields(Class<?> clazz) {
Reflective.printStaticFields(clazz, false);
}
/**
* Print all static fields of the class as name-value pairs. Includes the inherited fields as
* well. Optionally, prints name of the declaring class before each field - so that if same named
* field in super class chain may be disambiguated.
*
* @param clazz Class whose static fields are printed.
* @param classNamePrefix flag to tell whether to prefix field names names by class name or not.
*/
public static void printStaticFields(Class<?> clazz, boolean classNamePrefix) {
Reflective.printStaticFields(clazz, classNamePrefix);
}
// various print methods
public static void print(Object obj) {
BTraceRuntime.print(Strings.str(obj));
}
/**
* Prints a boolean value. The string produced by <code>{@link
* java.lang.String#valueOf(boolean)}</code> is sent to BTrace client for "printing".
*
* @param b The <code>boolean</code> to be printed
*/
public static void print(boolean b) {
print(Boolean.valueOf(b));
}
/**
* Prints a character. The string produced by <code>{@link
* java.lang.Character#valueOf(char)}</code> is sent to BTrace client for "printing".
*
* @param c The <code>char</code> to be printed
*/
public static void print(char c) {
print(Character.valueOf(c));
}
/**
* Prints an integer. The string produced by <code>{@link
* java.lang.String#valueOf(int)}</code> is sent to BTrace client for "printing".
*
* @param i The <code>int</code> to be printed
* @see java.lang.Integer#toString(int)
*/
public static void print(int i) {
print(Integer.valueOf(i));
}
/**
* Prints a long integer. The string produced by <code>{@link
* java.lang.String#valueOf(long)}</code> is sent to BTrace client for "printing".
*
* @param l The <code>long</code> to be printed
* @see java.lang.Long#toString(long)
*/
public static void print(long l) {
print(Long.valueOf(l));
}
/**
* Prints a floating-point number. The string produced by <code>{@link
* java.lang.String#valueOf(float)}</code> is sent to BTrace client for "printing".
*
* @param f The <code>float</code> to be printed
* @see java.lang.Float#toString(float)
*/
public static void print(float f) {
print(Float.valueOf(f));
}
/**
* Prints a double-precision floating-point number. The string produced by <code>
* {@link java.lang.String#valueOf(double)}</code> is sent to BTrace client for "printing".
*
* @param d The <code>double</code> to be printed
* @see java.lang.Double#toString(double)
*/
public static void print(double d) {
print(Double.valueOf(d));
}
/** Prints the given object and then prints a newline */
public static void println(Object obj) {
BTraceRuntime.println(Strings.str(obj));
}
/**
* Prints a boolean and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(boolean)}</code> and then <code>{@link #println()}</code>.
*
* @param b The <code>boolean</code> to be printed
*/
public static void println(boolean b) {
println(Boolean.valueOf(b));
}
/**
* Prints a character and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(char)}</code> and then <code>{@link #println()}</code>.
*
* @param c The <code>char</code> to be printed.
*/
public static void println(char c) {
println(Character.valueOf(c));
}
/**
* Prints an integer and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(int)}</code> and then <code>{@link #println()}</code>.
*
* @param i The <code>int</code> to be printed.
*/
public static void println(int i) {
println(Integer.valueOf(i));
}
/**
* Prints a long and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(long)}</code> and then <code>{@link #println()}</code>.
*
* @param l a The <code>long</code> to be printed.
*/
public static void println(long l) {
println(Long.valueOf(l));
}
/**
* Prints a float and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(float)}</code> and then <code>{@link #println()}</code>.
*
* @param f The <code>float</code> to be printed.
*/
public static void println(float f) {
println(Float.valueOf(f));
}
/**
* Prints a double and then terminate the line. This method behaves as though it invokes <code>
* {@link #print(double)}</code> and then <code>{@link #println()}</code>.
*
* @param d The <code>double</code> to be printed.
*/
public static void println(double d) {
println(Double.valueOf(d));
}
/**
* Terminates the current line by writing the line separator string. The line separator string is
* defined by the system property <code>line.separator</code>, and is not necessarily a single
* newline character (<code>'\n'</code>).
*/
public static void println() {
BTraceRuntime.println();
}
/**
* Returns the start time of the Java virtual machine in milliseconds. This method returns the
* approximate time when the Java virtual machine started.
*
* @return start time of the Java virtual machine in milliseconds.
*/
public static long vmStartTime() {
return Sys.VM.vmStartTime();
}
/**
* Returns the uptime of the Java virtual machine in milliseconds.
*
* @return uptime of the Java virtual machine in milliseconds.
*/
public static long vmUptime() {
return Sys.VM.vmUptime();
}
/**
* Returns the current time in milliseconds. Note that while the unit of time of the return value
* is a millisecond, the granularity of the value depends on the underlying operating system and
* may be larger. For example, many operating systems measure time in units of tens of
* milliseconds.
*
* @return the difference, measured in milliseconds, between the current time and midnight,
* January 1, 1970 UTC.
*/
public static long timeMillis() {
return Time.millis();
}
/**
* Returns the current value of the most precise available system timer, in nanoseconds.
*
* <p>This method can only be used to measure elapsed time and is not related to any other notion
* of system or wall-clock time. The value returned represents nanoseconds since some fixed but
* arbitrary time (perhaps in the future, so values may be negative). This method provides
* nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how
* frequently values change. Differences in successive calls that span greater than approximately
* 292 years (2<sup>63</sup> nanoseconds) will not accurately compute elapsed time due to
* numerical overflow.
*
* @return The current value of the system timer, in nanoseconds.
*/
public static long timeNanos() {
return Time.nanos();
}
/**
* Generates a string getTimestamp (current date&time)
*
* @param format The format to be used - see {@linkplain SimpleDateFormat}
* @return Returns a string representing current date&time
* @since 1.1
*/
public static String timestamp(String format) {
return Time.timestamp(format);
}
/**
* Generates a string getTimestamp (current date&time) in the default system format
*
* @return Returns a string representing current date&time
* @since 1.1
*/
public static String timestamp() {
return Time.timestamp();
}
// String utilities
public static boolean startsWith(String s, String start) {
return Strings.startsWith(s, start);
}
public static boolean endsWith(String s, String end) {
return Strings.endsWith(s, end);
}
/**
* This is synonym to "concat".
*
* @see #concat(String, String)
*/
public static String strcat(String str1, String str2) {
return Strings.strcat(str1, str2);
}
/** Concatenates the specified strings together. */
public static String concat(String str1, String str2) {
return Strings.concat(str1, str2);
}
/**
* Compares two strings lexicographically. The comparison is based on the Unicode value of each
* character in the strings. The character sequence represented by the first <code>String</code>
* object is compared lexicographically to the character sequence represented by the second
* string. The result is a negative integer if the first <code>String</code> object
* lexicographically precedes the second string. The result is a positive integer if the first
* <code>String</code> object lexicographically follows the second string. The result is zero if
* the strings are equal; <code>compareTo</code> returns <code>0</code> exactly when the {@link
* String#equals(Object)} method would return <code>true</code>.
*/
public static int compareTo(String str1, String str2) {
return Strings.compareTo(str1, str2);
}
/**
* This is synonym to "compareTo" method.
*
* @see #compareTo
*/
public static int strcmp(String str1, String str2) {
return Strings.strcmp(str1, str2);
}
/**
* Compares two strings lexicographically, ignoring case differences. This method returns an
* integer whose sign is that of calling <code>compareTo</code> with normalized versions of the
* strings where case differences have been eliminated by calling <code>
* Character.toLowerCase(Character.toUpperCase(character))</code> on each character.
*/
public static int compareToIgnoreCase(String str1, String str2) {
return Strings.compareToIgnoreCase(str1, str2);
}
/**
* This is synonym to "compareToIgnoreCase".
*
* @see #compareToIgnoreCase
*/
public static int stricmp(String str1, String str2) {
return Strings.stricmp(str1, str2);
}
/** Find String within String */
public static int strstr(String str1, String str2) {
return Strings.strstr(str1, str2);
}
public static int indexOf(String str1, String str2) {
return Strings.indexOf(str1, str2);
}
public static int lastIndexOf(String str1, String str2) {
return Strings.lastIndexOf(str1, str2);
}
/** Substring */
public static String substr(String str, int start, int length) {
return Strings.substr(str, start, length);
}
public static String substr(String str, int start) {
return Strings.substr(str, start);
}
/**
* Returns the length of the given string. The length is equal to the number of <a
* href="Character.html#unicode">Unicode code units</a> in the string.
*
* @param str String whose length is calculated.
* @return the length of the sequence of characters represented by this object.
*/
public static int length(String str) {
return Strings.length(str);
}
/**
* This is synonym for "length".
*
* @see #length(String)
*/
public static int strlen(String str) {
return Strings.strlen(str);
}
// regular expression matching
/**
* Compiles the given regular expression into a pattern.
*
* @param regex The expression to be compiled
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static Pattern regexp(String regex) {
return Strings.regexp(regex);
}
/**
* This is synonym for "regexp".
*
* @see #regexp(String)
*/
public static Pattern pattern(String regex) {
return Strings.pattern(regex);
}
/**
* Compiles the given regular expression into a pattern with the given flags.
*
* @param regex The expression to be compiled
* @param flags Match flags, a bit mask that may include {@link Pattern#CASE_INSENSITIVE}, {@link
* Pattern#MULTILINE}, {@link Pattern#DOTALL}, {@link Pattern#UNICODE_CASE}, {@link
* Pattern#CANON_EQ}, {@link Pattern#UNIX_LINES}, {@link Pattern#LITERAL} and {@link
* Pattern#COMMENTS}
* @throws IllegalArgumentException If bit values other than those corresponding to the defined
* match flags are set in <tt>flags</tt>
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static Pattern regexp(String regex, int flags) {
return Strings.regexp(regex, flags);
}
/**
* This is synonym for "regexp".
*
* @see #regexp(String, int)
*/
public static Pattern pattern(String regex, int flags) {
return Strings.pattern(regex, flags);
}
/**
* Matches the given (precompiled) regular expression and attempts to match the given input
* against it.
*/
public static boolean matches(Pattern regex, String input) {
return Strings.matches(regex, input);
}
/**
* Compiles the given regular expression and attempts to match the given input against it.
*
* <p>An invocation of this convenience method of the form
*
* <blockquote>
*
* <pre>
* Pattern.matches(regex, input);</pre>
*
* </blockquote>
*
* <p>behaves in exactly the same way as the expression
*
* <blockquote>
*
* <pre>
* Pattern.compile(regex).matcher(input).matches()</pre>
*
* </blockquote>
*
* <p>If a pattern is to be used multiple times, compiling it once and reusing it will be more
* efficient than invoking this method each time.
*
* @param regex The expression to be compiled
* @param input The character sequence to be matched
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static boolean matches(String regex, String input) {
return Strings.matches(regex, input);
}
// Numbers utilities
/**
* Returns a <code>double</code> value with a positive sign, greater than or equal to <code>0.0
* </code> and less than <code>1.0</code>. Returned values are chosen pseudorandomly with
* (approximately) uniform distribution from that range.
*/
public static double random() {
return Numbers.random();
}
/**
* Returns the natural logarithm (base <i>e</i>) of a <code>double</code> value. Special cases:
*
* <ul>
* <li>If the argument is NaN or less than zero, then the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is positive zero or negative zero, then the result is negative infinity.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a a value
* @return the value ln <code>a</code>, the natural logarithm of <code>a</code>.
*/
public static strictfp double log(double a) {
return Numbers.log(a);
}
/**
* Returns the base 10 logarithm of a <code>double</code> value. Special cases:
*
* <ul>
* <li>If the argument is NaN or less than zero, then the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is positive zero or negative zero, then the result is negative infinity.
* <li>If the argument is equal to 10<sup><i>n</i></sup> for integer <i>n</i>, then the result
* is <i>n</i>.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a a value
* @return the base 10 logarithm of <code>a</code>.
*/
public static strictfp double log10(double a) {
return Numbers.log10(a);
}
/**
* Returns Euler's number <i>e</i> raised to the power of a <code>double</code> value. Special
* cases:
*
* <ul>
* <li>If the argument is NaN, the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is negative infinity, then the result is positive zero.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a the exponent to raise <i>e</i> to.
* @return the value <i>e</i><sup><code>a</code></sup>, where <i>e</i> is the base of the natural
* logarithms.
*/
public static strictfp double exp(double a) {
return Numbers.exp(a);
}
/**
* Returns <code>true</code> if the specified number is a Not-a-Number (NaN) value, <code>false
* </code> otherwise.
*
* @param d the value to be tested.
* @return <code>true</code> if the value of the argument is NaN; <code>false</code> otherwise.
*/
public static boolean isNaN(double d) {
return Numbers.isNaN(d);
}
/**
* Returns <code>true</code> if the specified number is a Not-a-Number (NaN) value, <code>false
* </code> otherwise.
*
* @param f the value to be tested.
* @return <code>true</code> if the value of the argument is NaN; <code>false</code> otherwise.
*/
public static boolean isNaN(float f) {
return Numbers.isNaN(f);
}
/**
* Returns <code>true</code> if the specified number is infinitely large in magnitude, <code>false
* </code> otherwise.
*
* @param d the value to be tested.
* @return <code>true</code> if the value of the argument is positive infinity or negative
* infinity; <code>false</code> otherwise.
*/
public static boolean isInfinite(double d) {
return Numbers.isInfinite(d);
}
/**
* Returns <code>true</code> if the specified number is infinitely large in magnitude, <code>false
* </code> otherwise.
*
* @param f the value to be tested.
* @return <code>true</code> if the value of the argument is positive infinity or negative
* infinity; <code>false</code> otherwise.
*/
public static boolean isInfinite(float f) {
return Numbers.isInfinite(f);
}
// string parsing methods
/**
* Parses the string argument as a boolean. The <code>boolean</code> returned represents the value
* <code>true</code> if the string argument is not <code>null</code> and is equal, ignoring case,
* to the string {@code "true"}.
*
* <p>Example: {@code Boolean.parseBoolean("True")} returns <tt>true</tt>.<br>
* Example: {@code Boolean.parseBoolean("yes")} returns <tt>false</tt>.
*
* @param s the <code>String</code> containing the boolean representation to be parsed
* @return the boolean represented by the string argument
*/
public static boolean parseBoolean(String s) {
return Numbers.parseBoolean(s);
}
/**
* Parses the string argument as a signed decimal <code>byte</code>. The characters in the string
* must all be decimal digits, except that the first character may be an ASCII minus sign <code>
* '-'</code> (<code>'\u002D'</code>) to indicate a negative value. The resulting <code>byte
* </code> value is returned.
*
* @param s a <code>String</code> containing the <code>byte</code> representation to be parsed
* @return the <code>byte</code> value represented by the argument in decimal
*/
public static byte parseByte(String s) {
return Numbers.parseByte(s);
}
/**
* Parses the string argument as a signed decimal <code>short</code>. The characters in the string
* must all be decimal digits, except that the first character may be an ASCII minus sign <code>
* '-'</code> (<code>'\u002D'</code>) to indicate a negative value. The resulting <code>short
* </code> value is returned.
*
* @param s a <code>String</code> containing the <code>short</code> representation to be parsed
* @return the <code>short</code> value represented by the argument in decimal.
*/
public static short parseShort(String s) {
return Numbers.parseShort(s);
}
/**
* Parses the string argument as a signed decimal integer. The characters in the string must all
* be decimal digits, except that the first character may be an ASCII minus sign <code>'-'</code>
* (<code>'\u002D'</code>) to indicate a negative value. The resulting integer value is
* returned.
*
* @param s a <code>String</code> containing the <code>int</code> representation to be parsed
* @return the integer value represented by the argument in decimal.
*/
public static int parseInt(String s) {
return Numbers.parseInt(s);
}
/**
* Parses the string argument as a signed decimal <code>long</code>. The characters in the string
* must all be decimal digits, except that the first character may be an ASCII minus sign <code>
* '-'</code> (<code>\u002D'</code>) to indicate a negative value. The resulting <code>long
* </code> value is returned.
*
* <p>Note that neither the character <code>L</code> (<code>'\u004C'</code>) nor <code>l
* </code> (<code>'\u006C'</code>) is permitted to appear at the end of the string as a type
* indicator, as would be permitted in Java programming language source code.
*
* @param s a <code>String</code> containing the <code>long</code> representation to be parsed
* @return the <code>long</code> represented by the argument in decimal.
*/
public static long parseLong(String s) {
return Numbers.parseLong(s);
}
/**
* Returns a new <code>float</code> initialized to the value represented by the specified <code>
* String</code>, as performed by the <code>valueOf</code> method of class <code>Float</code>.
*
* @param s the string to be parsed.
* @return the <code>float</code> value represented by the string argument.
*/
public static float parseFloat(String s) {
return Numbers.parseFloat(s);
}
/**
* Returns a new <code>double</code> initialized to the value represented by the specified <code>
* String</code>, as performed by the <code>valueOf</code> methcod of class <code>Double</code>.
*
* @param s the string to be parsed.
* @return the <code>double</code> value represented by the string argument.
*/
public static double parseDouble(String s) {
return Numbers.parseDouble(s);
}
// boxing methods
/**
* Returns a <tt>Boolean</tt> instance representing the specified <tt>boolean</tt> value. If the
* specified <tt>boolean</tt> value is <tt>true</tt>, this method returns <tt>Boolean.TRUE</tt>;
* if it is <tt>false</tt>, this method returns <tt>Boolean.FALSE</tt>.
*
* @param b a boolean value.
* @return a <tt>Boolean</tt> instance representing <tt>b</tt>.
*/
public static Boolean box(boolean b) {
return Numbers.box(b);
}
/**
* Returns a <tt>Character</tt> instance representing the specified <tt>char</tt> value.
*
* @param c a char value.
* @return a <tt>Character</tt> instance representing <tt>c</tt>.
*/
public static Character box(char c) {
return Numbers.box(c);
}
/**
* Returns a <tt>Byte</tt> instance representing the specified <tt>byte</tt> value.
*
* @param b a byte value.
* @return a <tt>Byte</tt> instance representing <tt>b</tt>.
*/
public static Byte box(byte b) {
return Numbers.box(b);
}
/**
* Returns a <tt>Short</tt> instance representing the specified <tt>short</tt> value.
*
* @param s a short value.
* @return a <tt>Short</tt> instance representing <tt>s</tt>.
*/
public static Short box(short s) {
return Numbers.box(s);
}
/**
* Returns a <tt>Integer</tt> instance representing the specified <tt>int</tt> value.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
*/
public static Integer box(int i) {
return Numbers.box(i);
}
/**
* Returns a <tt>Long</tt> instance representing the specified <tt>long</tt> value.
*
* @param l a long value.
* @return a <tt>Long</tt> instance representing <tt>l</tt>.
*/
public static Long box(long l) {
return Numbers.box(l);
}
/**
* Returns a <tt>Float</tt> instance representing the specified <tt>float</tt> value.
*
* @param f a float value.
* @return a <tt>Float</tt> instance representing <tt>f</tt>.
*/
public static Float box(float f) {
return Numbers.box(f);
}
/**
* Returns a <tt>Double</tt> instance representing the specified <tt>double</tt> value.
*
* @param d a double value.
* @return a <tt>Double</tt> instance representing <tt>d</tt>.
*/
public static Double box(double d) {
return Numbers.box(d);
}
// unboxing methods
/**
* Returns the value of the given <tt>Boolean</tt> object as a boolean primitive.
*
* @param b the Boolean object whose value is returned.
* @return the primitive <code>boolean</code> value of the object.
*/
public static boolean unbox(Boolean b) {
return Numbers.unbox(b);
}
/**
* Returns the value of the given <tt>Character</tt> object as a char primitive.
*
* @param ch the Character object whose value is returned.
* @return the primitive <code>char</code> value of the object.
*/
public static char unbox(Character ch) {
return Numbers.unbox(ch);
}
/**
* Returns the value of the specified Byte as a <code>byte</code>.
*
* @param b Byte that is unboxed
* @return the byte value represented by the <code>Byte</code>.
*/
public static byte unbox(Byte b) {
return Numbers.unbox(b);
}
/**
* Returns the short value represented by <code>Short</code>.
*
* @param s Short that is unboxed.
* @return the short value represented by the <code>Short</code>.
*/
public static short unbox(Short s) {
return Numbers.unbox(s);
}
/**
* Returns the value of represented by <code>Integer</code>.
*
* @param i Integer that is unboxed.
* @return the int value represented by the <code>Integer</code>.
*/
public static int unbox(Integer i) {
return Numbers.unbox(i);
}
/**
* Returns the long value represented by the specified <code>Long</code>.
*
* @param l Long to be unboxed.
* @return the long value represented by the <code>Long</code>.
*/
public static long unbox(Long l) {
return Numbers.unbox(l);
}
/**
* Returns the float value represented by the specified <code>Float</code>.
*
* @param f Float to be unboxed.
* @return the float value represented by the <code>Float</code>.
*/
public static float unbox(Float f) {
return Numbers.unbox(f);
}
/**
* Returns the double value represented by the specified <code>Double</code>.
*
* @param d Double to be unboxed.
*/
public static double unbox(Double d) {
return Numbers.unbox(d);
}
// primitive types to String conversion
/**
* Returns a <tt>String</tt> object representing the specified boolean. If the specified boolean
* is <code>true</code>, then the string {@code "true"} will be returned, otherwise the string
* {@code "false"} will be returned.
*
* @param b the boolean to be converted
* @return the string representation of the specified <code>boolean</code>
*/
public static String str(boolean b) {
return Strings.str(b);
}
/**
* Returns a <code>String</code> object representing the specified <code>char</code>. The result
* is a string of length 1 consisting solely of the specified <code>char</code>.
*
* @param c the <code>char</code> to be converted
* @return the string representation of the specified <code>char</code>
*/
public static String str(char c) {
return Strings.str(c);
}
/**
* Returns a <code>String</code> object representing the specified integer. The argument is
* converted to signed decimal representation and returned as a string.
*
* @param i an integer to be converted.
* @return a string representation of the argument in base 10.
*/
public static String str(int i) {
return Strings.str(i);
}
/**
* Returns a string representation of the integer argument as an unsigned integer in base 16.
*
* <p>The unsigned integer value is the argument plus 2<sup>32</sup> if the argument is negative;
* otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in
* hexadecimal (base 16) with no extra leading <code>0</code>s. If the unsigned magnitude is
* zero, it is represented by a single zero character <code>'0'</code> (<code>'\u0030'</code>
* ); otherwise, the first character of the representation of the unsigned magnitude will not be
* the zero character. The following characters are used as hexadecimal digits:
*
* <blockquote>
*
* <pre>
* 0123456789abcdef
* </pre>
*
* </blockquote>
*
* These are the characters <code>'\u0030'</code> through <code>'\u0039'</code> and <code>
* '\u0061'</code> through <code>'\u0066'</code>.
*
* @param i an integer to be converted to a string.
* @return the string representation of the unsigned integer value represented by the argument in
* hexadecimal (base 16).
*/
public static String toHexString(int i) {
return Strings.toHexString(i);
}
/**
* Returns a <code>String</code> object representing the specified <code>long</code>. The argument
* is converted to signed decimal representation and returned as a string.
*
* @param l a <code>long</code> to be converted.
* @return a string representation of the argument in base 10.
*/
public static String str(long l) {
return Strings.str(l);
}
/**
* Returns a string representation of the <code>long</code> argument as an unsigned integer in
* base 16.
*
* <p>The unsigned <code>long</code> value is the argument plus 2<sup>64</sup> if the argument is
* negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII
* digits in hexadecimal (base 16) with no extra leading <code>0</code>s. If the unsigned
* magnitude is zero, it is represented by a single zero character <code>'0'</code> (<code>
* '\u0030'</code>); otherwise, the first character of the representation of the unsigned
* magnitude will not be the zero character. The following characters are used as hexadecimal
* digits:
*
* <blockquote>
*
* <pre>
* 0123456789abcdef
* </pre>
*
* </blockquote>
*
* These are the characters <code>'\u0030'</code> through <code>'\u0039'</code> and <code>
* '\u0061'</code> through <code>'\u0066'</code>.
*
* @param l a <code>long</code> to be converted to a string.
* @return the string representation of the unsigned <code>long</code> value represented by the
* argument in hexadecimal (base 16).
*/
public static String toHexString(long l) {
return Strings.toHexString(l);
}
/**
* Returns a string representation of the <code>float</code> argument. All characters mentioned
* below are ASCII characters.
*
* <ul>
* <li>If the argument is NaN, the result is the string "<code>NaN</code>".
* <li>Otherwise, the result is a string that represents the sign and magnitude (absolute value)
* of the argument. If the sign is negative, the first character of the result is '<code>-
* </code>' (<code>'\u002D'</code>); if the sign is positive, no sign character appears
* in the result. As for the magnitude <i>m</i>:
* <ul>
* <li>If <i>m</i> is infinity, it is represented by the characters <code>"Infinity"
* </code>; thus, positive infinity produces the result <code>"Infinity"</code> and
* negative infinity produces the result <code>"-Infinity"</code>.
* <li>If <i>m</i> is zero, it is represented by the characters <code>"0.0"</code>; thus,
* negative zero produces the result <code>"-0.0"</code> and positive zero produces
* the result <code>"0.0"</code>.
* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less than
* 10<sup>7</sup>, then it is represented as the integer part of <i>m</i>, in decimal
* form with no leading zeroes, followed by '<code>.</code>' (<code>'\u002E'
* </code>), followed by one or more decimal digits representing the fractional part
* of <i>m</i>.
* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or equal to
* 10<sup>7</sup>, then it is represented in so-called "computerized scientific
* notation." Let <i>n</i> be the unique integer such that 10<sup><i>n</i> </sup><=
* <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the mathematically
* exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so that 1 <= <i>a</i> <
* 10. The magnitude is then represented as the integer part of <i>a</i>, as a single
* decimal digit, followed by '<code>.</code>' (<code>'\u002E'</code>), followed
* by decimal digits representing the fractional part of <i>a</i>, followed by the
* letter '<code>E</code>' (<code>'\u0045'</code>), followed by a representation
* of <i>n</i> as a decimal integer, as produced by the method <code>{@link
* java.lang.Integer#toString(int)}</code>.
* </ul>
* </ul>
*
* How many digits must be printed for the fractional part of <i>m</i> or <i>a</i>? There must be
* at least one digit to represent the fractional part, and beyond that as many, but only as many,
* more digits as are needed to uniquely distinguish the argument value from adjacent values of
* type <code>float</code>. That is, suppose that <i>x</i> is the exact mathematical value
* represented by the decimal representation produced by this method for a finite nonzero argument
* <i>f</i>. Then <i>f</i> must be the <code>float</code> value nearest to <i>x</i>; or, if two
* <code>float</code> values are equally close to <i>x</i>, then <i>f</i> must be one of them and
* the least significant bit of the significand of <i>f</i> must be <code>0</code>.
*
* <p>
*
* @param f the float to be converted.
* @return a string representation of the argument.
*/
public static String str(float f) {
return Strings.str(f);
}
/**
* Returns a string representation of the <code>double</code> argument. All characters mentioned
* below are ASCII characters.
*
* <ul>
* <li>If the argument is NaN, the result is the string "<code>NaN</code>".
* <li>Otherwise, the result is a string that represents the sign and magnitude (absolute value)
* of the argument. If the sign is negative, the first character of the result is '<code>-
* </code>' (<code>'\u002D'</code>); if the sign is positive, no sign character appears
* in the result. As for the magnitude <i>m</i>:
* <ul>
* <li>If <i>m</i> is infinity, it is represented by the characters <code>"Infinity"
* </code>; thus, positive infinity produces the result <code>"Infinity"</code> and
* negative infinity produces the result <code>"-Infinity"</code>.
* <li>If <i>m</i> is zero, it is represented by the characters <code>"0.0"</code>; thus,
* negative zero produces the result <code>"-0.0"</code> and positive zero produces
* the result <code>"0.0"</code>.
* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less than
* 10<sup>7</sup>, then it is represented as the integer part of <i>m</i>, in decimal
* form with no leading zeroes, followed by '<code>.</code>' (<code>'\u002E'
* </code>), followed by one or more decimal digits representing the fractional part
* of <i>m</i>.
* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or equal to
* 10<sup>7</sup>, then it is represented in so-called "computerized scientific
* notation." Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup> <=
* <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the mathematically
* exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so that 1 <= <i>a</i> <
* 10. The magnitude is then represented as the integer part of <i>a</i>, as a single
* decimal digit, followed by '<code>.</code>' (<code>'\u002E'</code>), followed
* by decimal digits representing the fractional part of <i>a</i>, followed by the
* letter '<code>E</code>' (<code>'\u0045'</code>), followed by a representation
* of <i>n</i> as a decimal integer, as produced by the method {@link
* Integer#toString(int)}.
* </ul>
* </ul>
*
* How many digits must be printed for the fractional part of <i>m</i> or <i>a</i>? There must be
* at least one digit to represent the fractional part, and beyond that as many, but only as many,
* more digits as are needed to uniquely distinguish the argument value from adjacent values of
* type <code>double</code>. That is, suppose that <i>x</i> is the exact mathematical value
* represented by the decimal representation produced by this method for a finite nonzero argument
* <i>d</i>. Then <i>d</i> must be the <code>double</code> value nearest to <i>x</i>; or if two
* <code>double</code> values are equally close to <i>x</i>, then <i>d</i> must be one of them and
* the least significant bit of the significand of <i>d</i> must be <code>0</code>.
*
* <p>
*
* @param d the <code>double</code> to be converted.
* @return a string representation of the argument.
*/
public static String str(double d) {
return Strings.str(d);
}
/**
* Exits the BTrace session -- note that the particular client's tracing session exits and not the
* observed/traced program! After exit call, the trace action method terminates immediately and no
* other probe action method (of that client) will be called after that.
*
* @param exitCode exit value sent to the client
*/
public static void exit(int exitCode) {
Sys.exit(exitCode);
}
/**
* This is same as exit(int) except that the exit code is zero.
*
* @see #exit(int)
*/
public static void exit() {
Sys.exit();
}
/** accessing jvmstat (perf) int counter */
public static long perfInt(String name) {
return Counters.perfInt(name);
}
/** accessing jvmstat (perf) long counter */
public static long perfLong(String name) {
return Counters.perfLong(name);
}
/** accessing jvmstat (perf) String counter */
public static String perfString(String name) {
return Counters.perfString(name);
}
/** Operating on maps */
// Create a new map
public static <K, V> Map<K, V> newHashMap() {
return Collections.newHashMap();
}
public static <K, V> Map<K, V> newWeakMap() {
return Collections.newWeakMap();
}
public static <V> Deque<V> newDeque() {
return Collections.newDeque();
}
// get a particular item from a Map
public static <K, V> V get(Map<K, V> map, K key) {
return Collections.get(map, key);
}
// check whether an item exists
public static <K, V> boolean containsKey(Map<K, V> map, K key) {
return Collections.containsKey(map, key);
}
public static <K, V> boolean containsValue(Map<K, V> map, V value) {
return Collections.containsValue(map, value);
}
// put a particular item into a Map
public static <K, V> V put(Map<K, V> map, K key, V value) {
return Collections.put(map, key, value);
}
// remove a particular item from a Map
public static <K, V> V remove(Map<K, V> map, K key) {
return Collections.remove(map, key);
}
// clear all items from a Map
public static <K, V> void clear(Map<K, V> map) {
Collections.clear(map);
}
// return the size of a Map
public static <K, V> int size(Map<K, V> map) {
return Collections.size(map);
}
public static <K, V> boolean isEmpty(Map<K, V> map) {
return Collections.isEmpty(map);
}
// operations on collections
public static <E> int size(Collection<E> coll) {
return Collections.size(coll);
}
public static <E> boolean isEmpty(Collection<E> coll) {
return Collections.isEmpty(coll);
}
public static <E> boolean contains(Collection<E> coll, Object obj) {
return Collections.contains(coll, obj);
}
public static boolean contains(Object[] array, Object value) {
return Collections.contains(array, value);
}
// operations on Deque
public static <V> void push(Deque<V> queue, V value) {
Collections.push(queue, value);
}
public static <V> V poll(Deque<V> queue) {
return Collections.poll(queue);
}
public static <V> V peek(Deque<V> queue) {
return Collections.peek(queue);
}
public static <V> void addLast(Deque<V> queue, V value) {
Collections.addLast(queue, value);
}
public static <V> V peekFirst(Deque<V> queue) {
return Collections.peekFirst(queue);
}
public static <V> V peekLast(Deque<V> queue) {
return Collections.peekLast(queue);
}
public static <V> V removeLast(Deque<V> queue) {
return Collections.removeLast(queue);
}
public static <V> V removeFirst(Deque<V> queue) {
return Collections.removeFirst(queue);
}
/**
* Returns the current instrumentation level.
*
* <p>Instrumentation level is used in evaluating {@linkplain OnMethod#enableAt()} expressions to
* enable/disable the probe handler.
*
* @return the instrumentation level (non negative integer)
* @since 1.3.4
*/
public static int getInstrumentationLevel() {
return BTraceRuntime.getInstrumentationLevel();
}
/**
* Sets the current instrumentation level.
*
* <p>Instrumentation level is used in evaluating {@linkplain OnMethod#enableAt()} expressions to
* enable/disable the probe handler.
*
* @param level an arbitrary non negative integer number
* @since 1.3.4
*/
public static void setInstrumentationLevel(int level) {
if (level >= 0) {
BTraceRuntime.setInstrumentationLevel(level);
}
}
/**
* Returns n'th command line argument. <code>null</code> if not available.
*
* @param n command line argument index
* @return n'th command line argument
*/
public static String $(int n) {
return Sys.$(n);
}
/** Returns the process id of the currently BTrace'd process. */
public static int getpid() {
return Sys.getpid();
}
/** Returns the number of command line arguments. */
public static int $length() {
return Sys.$length();
}
// atomic stuff
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public static AtomicInteger newAtomicInteger(int initialValue) {
return Atomic.newAtomicInteger(initialValue);
}
/**
* Gets the current value of the given AtomicInteger.
*
* @param ai AtomicInteger whose value is returned.
* @return the current value
*/
public static int get(AtomicInteger ai) {
return Atomic.get(ai);
}
/**
* Sets to the given value to the given AtomicInteger.
*
* @param ai AtomicInteger whose value is set.
* @param newValue the new value
*/
public static void set(AtomicInteger ai, int newValue) {
Atomic.set(ai, newValue);
}
/**
* Eventually sets to the given value to the given AtomicInteger.
*
* @param ai AtomicInteger whose value is lazily set.
* @param newValue the new value
*/
public static void lazySet(AtomicInteger ai, int newValue) {
Atomic.lazySet(ai, newValue);
}
/**
* Atomically sets the value of given AtomitInteger to the given updated value if the current
* value {@code ==} the expected value.
*
* @param ai AtomicInteger whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that the actual value was not equal to the
* expected value.
*/
public static boolean compareAndSet(AtomicInteger ai, int expect, int update) {
return Atomic.compareAndSet(ai, expect, update);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a> and does not provide
* ordering guarantees, so is only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param ai AtomicInteger whose value is weakly compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public static boolean weakCompareAndSet(AtomicInteger ai, int expect, int update) {
return Atomic.weakCompareAndSet(ai, expect, update);
}
/**
* Atomically increments by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is incremented.
* @return the previous value
*/
public static int getAndIncrement(AtomicInteger ai) {
return Atomic.getAndIncrement(ai);
}
/**
* Atomically decrements by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is decremented.
* @return the previous value
*/
public static int getAndDecrement(AtomicInteger ai) {
return Atomic.getAndDecrement(ai);
}
/**
* Atomically increments by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is incremented.
* @return the updated value
*/
public static int incrementAndGet(AtomicInteger ai) {
return Atomic.incrementAndGet(ai);
}
/**
* Atomically decrements by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger whose value is decremented.
* @return the updated value
*/
public static int decrementAndGet(AtomicInteger ai) {
return Atomic.decrementAndGet(ai);
}
/**
* Atomically adds the given value to the current value.
*
* @param ai AtomicInteger whose value is added to.
* @param delta the value to add
* @return the previous value
*/
public static int getAndAdd(AtomicInteger ai, int delta) {
return Atomic.getAndAdd(ai, delta);
}
/**
* Atomically adds the given value to the current value.
*
* @param ai AtomicInteger whose value is added to.
* @param delta the value to add
* @return the updated value
*/
public static int addAndGet(AtomicInteger ai, int delta) {
return Atomic.addAndGet(ai, delta);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param ai AtomicInteger whose value is set.
* @param newValue the new value
* @return the previous value
*/
public static int getAndSet(AtomicInteger ai, int newValue) {
return Atomic.getAndSet(ai, newValue);
}
/**
* Creates a new AtomicLong with the given initial value.
*
* @param initialValue the initial value
*/
public static AtomicLong newAtomicLong(long initialValue) {
return Atomic.newAtomicLong(initialValue);
}
/**
* Gets the current value the given AtomicLong.
*
* @param al AtomicLong whose value is returned.
* @return the current value
*/
public static long get(AtomicLong al) {
return Atomic.get(al);
}
/**
* Sets to the given value.
*
* @param al AtomicLong whose value is set.
* @param newValue the new value
*/
public static void set(AtomicLong al, long newValue) {
Atomic.set(al, newValue);
}
/**
* Eventually sets to the given value to the given AtomicLong.
*
* @param al AtomicLong whose value is set.
* @param newValue the new value
*/
public static void lazySet(AtomicLong al, long newValue) {
Atomic.lazySet(al, newValue);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* @param al AtomicLong whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that the actual value was not equal to the
* expected value.
*/
public static boolean compareAndSet(AtomicLong al, long expect, long update) {
return Atomic.compareAndSet(al, expect, update);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* <p>May fail spuriously and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param al AtomicLong whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public static boolean weakCompareAndSet(AtomicLong al, long expect, long update) {
return Atomic.weakCompareAndSet(al, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @param al AtomicLong whose value is incremented.
* @return the previous value
*/
public static long getAndIncrement(AtomicLong al) {
return Atomic.getAndIncrement(al);
}
/**
* Atomically decrements by one the current value.
*
* @param al AtomicLong whose value is decremented.
* @return the previous value
*/
public static long getAndDecrement(AtomicLong al) {
return Atomic.getAndDecrement(al);
}
/**
* Atomically increments by one the current value.
*
* @param al AtomicLong whose value is incremented.
* @return the updated value
*/
public static long incrementAndGet(AtomicLong al) {
return Atomic.incrementAndGet(al);
}
/**
* Atomically decrements by one the current value.
*
* @param al AtomicLong whose value is decremented.
* @return the updated value
*/
public static long decrementAndGet(AtomicLong al) {
return Atomic.decrementAndGet(al);
}
/**
* Atomically adds the given value to the current value.
*
* @param al AtomicLong whose value is added to.
* @param delta the value to add
* @return the previous value
*/
public static long getAndAdd(AtomicLong al, long delta) {
return Atomic.getAndAdd(al, delta);
}
/**
* Atomically adds the given value to the current value.
*
* @param al AtomicLong whose value is added to
* @param delta the value to add
* @return the updated value
*/
public static long addAndGet(AtomicLong al, long delta) {
return Atomic.addAndGet(al, delta);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param al AtomicLong that is set.
* @param newValue the new value
* @return the previous value
*/
public static long getAndSet(AtomicLong al, long newValue) {
return Atomic.getAndSet(al, newValue);
}
/**
* BTrace to DTrace communication chennal. Raise DTrace USDT probe from BTrace.
*
* @see #dtraceProbe(String, String, int, int)
*/
public static int dtraceProbe(String str1, String str2) {
return D.probe(str1, str2);
}
/**
* BTrace to DTrace communication chennal. Raise DTrace USDT probe from BTrace.
*
* @see #dtraceProbe(String, String, int, int)
*/
public static int dtraceProbe(String str1, String str2, int i1) {
return D.probe(str1, str2, i1);
}
/**
* BTrace to DTrace communication channel. Raise DTrace USDT probe from BTrace.
*
* @param str1 first String param to DTrace probe
* @param str2 second String param to DTrace probe
* @param i1 first int param to DTrace probe
* @param i2 second int param to DTrace probe
*/
public static int dtraceProbe(String str1, String str2, int i1, int i2) {
return D.probe(str1, str2, i1, i2);
}
/**
* Gets the system property indicated by the specified key.
*
* @param key the name of the system property.
* @return the string value of the system property, or <code>null</code> if there is no property
* with that key.
* @throws NullPointerException if <code>key</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>key</code> is empty.
*/
public static String property(String key) {
return Sys.Env.property(key);
}
/**
* Returns all Sys properties.
*
* @return the system properties
*/
public static Properties properties() {
return Sys.Env.properties();
}
/** Prints all Sys properties. */
public static void printProperties() {
Sys.Env.printProperties();
}
/**
* Gets the value of the specified environment variable. An environment variable is a
* system-dependent external named value.
*
* @param name the name of the environment variable
* @return the string value of the variable, or <code>null</code> if the variable is not defined
* in the system environment
* @throws NullPointerException if <code>name</code> is <code>null</code>
*/
public static String getenv(String name) {
return Sys.Env.getenv(name);
}
/**
* Returns an unmodifiable string map view of the current system environment. The environment is a
* system-dependent mapping from names to values which is passed from parent to child processes.
*
* @return the environment as a map of variable names to values
*/
public static Map<String, String> getenv() {
return Sys.Env.getenv();
}
/** Prints all system environment values. */
public static void printEnv() {
Sys.Env.printEnv();
}
/**
* Returns the number of processors available to the Java virtual machine.
*
* <p>This value may change during a particular invocation of the virtual machine. Applications
* that are sensitive to the number of available processors should therefore occasionally poll
* this property and adjust their resource usage appropriately.
*
* @return the maximum number of processors available to the virtual machine; never smaller than
* one
*/
public static long availableProcessors() {
return Sys.Env.availableProcessors();
}
// memory usage
/**
* Returns the amount of free memory in the Java Virtual Machine. Calling the <code>gc</code>
* method may result in increasing the value returned by <code>freeMemory.</code>
*
* @return an approximation to the total amount of memory currently available for future allocated
* objects, measured in bytes.
*/
public static long freeMemory() {
return Sys.Memory.freeMemory();
}
/**
* Returns the total amount of memory in the Java virtual machine. The value returned by this
* method may vary over time, depending on the host environment.
*
* <p>Note that the amount of memory required to hold an object of any given type may be
* implementation-dependent.
*
* @return the total amount of memory currently available for current and future objects, measured
* in bytes.
*/
public static long totalMemory() {
return Sys.Memory.totalMemory();
}
/**
* Returns the maximum amount of memory that the Java virtual machine will attempt to use. If
* there is no inherent limit then the value {@link java.lang.Long#MAX_VALUE} will be returned.
*
* @return the maximum amount of memory that the virtual machine will attempt to use, measured in
* bytes
*/
public static long maxMemory() {
return Sys.Memory.maxMemory();
}
/** Returns heap memory usage */
public static MemoryUsage heapUsage() {
return Sys.Memory.heapUsage();
}
/** Returns non-heap memory usage */
public static MemoryUsage nonHeapUsage() {
return Sys.Memory.nonHeapUsage();
}
/**
* Returns the amount of memory in bytes that the Java virtual machine initially requests from the
* operating system for memory management.
*/
public static long init(MemoryUsage mu) {
return Sys.Memory.init(mu);
}
/**
* Returns the amount of memory in bytes that is committed for the Java virtual machine to use.
* This amount of memory is guaranteed for the Java virtual machine to use.
*/
public static long committed(MemoryUsage mu) {
return Sys.Memory.committed(mu);
}
/**
* Returns the maximum amount of memory in bytes that can be used for memory management. This
* method returns -1 if the maximum memory size is undefined.
*/
public static long max(MemoryUsage mu) {
return Sys.Memory.max(mu);
}
/** Returns the amount of used memory in bytes. */
public static long used(MemoryUsage mu) {
return Sys.Memory.used(mu);
}
/** Returns the approximate number of objects for which finalization is pending. */
public static long finalizationCount() {
return Sys.Memory.finalizationCount();
}
/**
* Returns the input arguments passed to the Java virtual machine which does not include the
* arguments to the <tt>main</tt> method. This method returns an empty list if there is no input
* argument to the Java virtual machine.
*
* <p>Some Java virtual machine implementations may take input arguments from multiple different
* sources: for examples, arguments passed from the application that launches the Java virtual
* machine such as the 'java' command, environment variables, configuration files, etc.
*
* <p>Typically, not all command-line options to the 'java' command are passed to the Java virtual
* machine. Thus, the returned input arguments may not include all command-line options.
*
* @return a list of <tt>String</tt> objects; each element is an argument passed to the Java
* virtual machine.
*/
public static List<String> vmArguments() {
return Sys.VM.vmArguments();
}
/**
* Prints VM input arguments list.
*
* @see #vmArguments
*/
public static void printVmArguments() {
Sys.VM.printVmArguments();
}
/**
* Returns the Java virtual machine implementation version. This method is equivalent to
* <b>Sys.getProperty("java.vm.version")</b>.
*
* @return the Java virtual machine implementation version.
*/
public static String vmVersion() {
return Sys.VM.vmVersion();
}
/**
* Tests if the Java virtual machine supports the boot class path mechanism used by the bootstrap
* class loader to search for class files.
*
* @return <tt>true</tt> if the Java virtual machine supports the class path mechanism;
* <tt>false</tt> otherwise.
*/
public static boolean isBootClassPathSupported() {
return Sys.VM.isBootClassPathSupported();
}
/**
* Returns the boot class path that is used by the bootstrap class loader to search for class
* files.
*
* <p>Multiple paths in the boot class path are separated by the path separator character of the
* platform on which the Java virtual machine is running.
*
* <p>A Java virtual machine implementation may not support the boot class path mechanism for the
* bootstrap class loader to search for class files. The {@link #isBootClassPathSupported} method
* can be used to determine if the Java virtual machine supports this method.
*
* @return the boot class path.
* @throws java.lang.UnsupportedOperationException if the Java virtual machine does not support
* this operation.
*/
public static String bootClassPath() {
return Sys.VM.bootClassPath();
}
/**
* Returns the Java class path that is used by the system class loader to search for class files.
* This method is equivalent to <b>Sys.getProperty("java.class.path")</b>.
*
* @return the Java class path.
*/
public static String classPath() {
return Sys.VM.classPath();
}
/**
* Returns the Java library path. This method is equivalent to
* <b>Sys.getProperty("java.library.path")</b>.
*
* <p>Multiple paths in the Java library path are separated by the path separator character of the
* platform of the Java virtual machine being monitored.
*
* @return the Java library path.
*/
public static String libraryPath() {
return Sys.VM.libraryPath();
}
/**
* Returns the current number of live threads including both daemon and non-daemon threads.
*
* @return the current number of live threads.
*/
public static long threadCount() {
return Sys.VM.threadCount();
}
/**
* Returns the peak live thread count since the Java virtual machine started or peak was reset.
*
* @return the peak live thread count.
*/
public static long peakThreadCount() {
return Sys.VM.peakThreadCount();
}
/**
* Returns the total number of threads created and also started since the Java virtual machine
* started.
*
* @return the total number of threads started.
*/
public static long totalStartedThreadCount() {
return Sys.VM.totalStartedThreadCount();
}
/**
* Returns the current number of live daemon threads.
*
* @return the current number of live daemon threads.
*/
public static long daemonThreadCount() {
return Sys.VM.daemonThreadCount();
}
/**
* Returns the total CPU time for the current thread in nanoseconds. The returned value is of
* nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation
* distinguishes between user mode time and system mode time, the returned CPU time is the amount
* of time that the current thread has executed in user mode or system mode.
*/
public static long currentThreadCpuTime() {
return Sys.VM.currentThreadCpuTime();
}
/**
* Returns the CPU time that the current thread has executed in user mode in nanoseconds. The
* returned value is of nanoseconds precision but not necessarily nanoseconds accuracy.
*/
public static long currentThreadUserTime() {
return Sys.VM.currentThreadUserTime();
}
/**
* Returns the total amount of time spent in GarbageCollection up to this point since the
* application was started.
*
* @return Returns the amount of overall time spent in GC
*/
public static long getTotalGcTime() {
return Sys.Memory.getTotalGcTime();
}
/**
* Returns an implementation-specific approximation of the amount of storage consumed by the
* specified object. The result may include some or all of the object's overhead, and thus is
* useful for comparison within an implementation but not between implementations.
*
* <p>The estimate may change during a single invocation of the JVM.
*
* @param objectToSize the object to size
* @return an implementation-specific approximation of the amount of storage consumed by the
* specified object
* @throws java.lang.NullPointerException if the supplied Object is <code>null</code>.
*/
public static long sizeof(Object objectToSize) {
return BTraceRuntime.sizeof(objectToSize);
}
/**
* Dump the snapshot of the Java heap to a file in hprof binary format. Only the live objects are
* dumped. Under the current dir of traced app, ./btrace<pid>/btrace-class/ directory is
* created. Under that directory, a file of given fileName is created.
*
* @param fileName name of the file to which heap is dumped
*/
public static void dumpHeap(String fileName) {
Sys.Memory.dumpHeap(fileName);
}
/**
* Dump the snapshot of the Java heap to a file in hprof binary format. Under the current dir of
* traced app, ./btrace<pid>/btrace-class/ directory is created. Under that directory, a
* file of given fileName is created.
*
* @param fileName name of the file to which heap is dumped
* @param live flag that tells whether only live objects are to be dumped or all objects are to be
* dumped.
*/
public static void dumpHeap(String fileName, boolean live) {
Sys.Memory.dumpHeap(fileName, live);
}
/**
* Runs the garbage collector.
*
* <p>Calling the <code>gc</code> method suggests that the Java Virtual Machine expend effort
* toward recycling unused objects in order to make the memory they currently occupy available for
* quick reuse. When control returns from the method call, the Java Virtual Machine has made a
* best effort to reclaim space from all discarded objects. This method calls Sys.gc() to perform
* GC.
*/
public static void gc() {
Sys.Memory.gc();
}
/**
* Runs the finalization methods of any objects pending finalization.
*
* <p>Calling this method suggests that the Java Virtual Machine expend effort toward running the
* <code>finalize</code> methods of objects that have been found to be discarded but whose <code>
* finalize</code> methods have not yet been run. When control returns from the method call, the
* Java Virtual Machine has made a best effort to complete all outstanding finalizations. This
* method calls Sys.runFinalization() to run finalization.
*/
public static void runFinalization() {
Sys.Memory.runFinalization();
}
/**
* Serialize a given object into the given file. Under the current dir of traced app,
* ./btrace<pid>/btrace-class/ directory is created. Under that directory, a file of given
* fileName is created.
*
* @param obj object that has to be serialized.
* @param fileName name of the file to which the object is serialized.
*/
public static void serialize(Serializable obj, String fileName) {
Export.serialize(obj, fileName);
}
/**
* Creates an XML document to persist the tree of the all transitively reachable objects from
* given "root" object.
*/
public static String toXML(Object obj) {
return Export.toXML(obj);
}
/**
* Writes an XML document to persist the tree of the all the transitively reachable objects from
* the given "root" object. Under the current dir of traced app, ./btrace<pid>/btrace-class/
* directory is created. Under that directory, a file of the given fileName is created.
*/
public static void writeXML(Object obj, String fileName) {
Export.writeXML(obj, fileName);
}
/**
* Writes a .dot document to persist the tree of the all the transitively reachable objects from
* the given "root" object. .dot documents can be viewed by Graphviz application
* (www.graphviz.org) Under the current dir of traced app, ./btrace<pid>/btrace-class/
* directory is created. Under that directory, a file of the given fileName is created.
*
* @since 1.1
*/
public static void writeDOT(Object obj, String fileName) {
Export.writeDOT(obj, fileName);
}
// speculative buffer management
/**
* Returns an identifier for a new speculative buffer.
*
* @return new speculative buffer id
*/
public static int speculation() {
return Speculation.speculation();
}
/**
* Sets current speculative buffer id.
*
* @param id the speculative buffer id
*/
public static void speculate(int id) {
Speculation.speculate(id);
}
/**
* Commits the speculative buffer associated with id.
*
* @param id the speculative buffer id
*/
public static void commit(int id) {
Speculation.commit(id);
}
/**
* Discards the speculative buffer associated with id.
*
* @param id the speculative buffer id
*/
public static void discard(int id) {
Speculation.discard(id);
}
// aggregation support
/**
* Creates a new aggregation based on the given aggregation function type.
*
* @param type the aggregating function to be performed on the data being added to the
* aggregation.
*/
public static Aggregation newAggregation(AggregationFunction type) {
return Aggregations.newAggregation(type);
}
/**
* Creates a grouping aggregation key with the provided value. The value must be a String or
* Number type.
*
* @param element1 the value of the aggregation key
*/
public static AggregationKey newAggregationKey(Object element1) {
return Aggregations.newAggregationKey(element1);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(Object element1, Object element2) {
return Aggregations.newAggregationKey(element1, element2);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
* @param element3 the third element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(
Object element1, Object element2, Object element3) {
return Aggregations.newAggregationKey(element1, element2, element3);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
* @param element3 the third element of the composite aggregation key
* @param element4 the fourth element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(
Object element1, Object element2, Object element3, Object element4) {
return Aggregations.newAggregationKey(element1, element2, element3, element4);
}
/**
* Adds a value to the aggregation with no grouping key. This method should be used when the
* aggregation is to calculate only a single aggregated value.
*
* @param aggregation the aggregation to which the value should be added
*/
public static void addToAggregation(Aggregation aggregation, long value) {
Aggregations.addToAggregation(aggregation, value);
}
/**
* Adds a value to the aggregation with a grouping key. This method should be used when the
* aggregation should effectively perform a "group by" on the key value. The aggregation will
* calculate a separate aggregated value for each unique aggregation key.
*
* @param aggregation the aggregation to which the value should be added
* @param key the grouping aggregation key
*/
public static void addToAggregation(Aggregation aggregation, AggregationKey key, long value) {
Aggregations.addToAggregation(aggregation, key, value);
}
/**
* Resets values within the aggregation to the default. This will affect all values within the
* aggregation when multiple aggregation keys have been used.
*
* @param aggregation the aggregation to be cleared
*/
public static void clearAggregation(Aggregation aggregation) {
Aggregations.clearAggregation(aggregation);
}
/**
* Removes all aggregated values from the aggregation except for the largest or smallest <code>
* abs(count)</code> elements.
*
* <p>If <code>count</code> is positive, the largest aggregated values in the aggregation will be
* preserved. If <code>count</code> is negative the smallest values will be preserved. If <code>
* count</code> is zero then all elements will be removed.
*
* <p>Behavior is intended to be similar to the dtrace <code>trunc()</code> function.
*
* @param aggregation the aggregation to be truncated
* @param count the number of elements to preserve. If negative, the smallest <code>abs(count)
* </code> elements are preserved.
*/
public static void truncateAggregation(Aggregation aggregation, int count) {
Aggregations.truncateAggregation(aggregation, count);
}
/** Prints the aggregation. */
public static void printAggregation(String name, Aggregation aggregation) {
Aggregations.printAggregation(name, aggregation);
}
/**
* Prints aggregation using the provided format
*
* @param name The name of the aggregation to be used in the textual output
* @param aggregation The aggregation to print
* @param format The format to use. It mimics {@linkplain String#format(java.lang.String,
* java.lang.Object[]) } behaviour with the addition of the ability to address the key title
* as a 0-indexed item
* @see String#format(java.lang.String, java.lang.Object[])
* @since 1.1
*/
public static void printAggregation(String name, Aggregation aggregation, String format) {
Aggregations.printAggregation(name, aggregation, format);
}
// Internals only below this point
private static void checkStatic(Field field) {
if (!Modifier.isStatic(field.getModifiers())) {
throw new IllegalArgumentException(field.getName() + " is not a static field");
}
}
private static Field getField(Class<?> clazz, String name, boolean throwError) {
return AccessController.doPrivileged(
(PrivilegedAction<Field>)
() -> {
Field field = null;
Class<?> cClass = clazz;
try {
while (Objects.isNull(field) && Objects.nonNull(cClass)) {
try {
field = cClass.getDeclaredField(name);
} catch (NoSuchFieldException exp) {
// Ignore the exception and continue looking for the parent class
cClass = cClass.getSuperclass();
}
}
if (Objects.isNull(cClass)) {
throw new NoSuchFieldException(name);
}
field.setAccessible(true);
return field;
} catch (Exception exp) {
if (throwError) {
throw translate(exp);
} else {
return null;
}
}
});
}
private static Field[] getAllFields(Class<?> clazz) {
return AccessController.doPrivileged(
(PrivilegedAction<Field[]>)
() -> {
try {
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
}
return fields;
} catch (Exception exp) {
throw translate(exp);
}
});
}
private static void addFieldValues(
StringBuilder buf, Object obj, Class<?> clazz, boolean classNamePrefix) {
Field[] fields = getAllFields(clazz);
for (Field f : fields) {
int modifiers = f.getModifiers();
if (!Modifier.isStatic(modifiers)) {
if (classNamePrefix) {
buf.append(f.getDeclaringClass().getName());
buf.append('.');
}
buf.append(f.getName());
buf.append('=');
try {
buf.append(Strings.str(f.get(obj)));
} catch (Exception exp) {
throw translate(exp);
}
buf.append(", ");
}
}
Class<?> sc = clazz.getSuperclass();
if (sc != null) {
addFieldValues(buf, obj, sc, classNamePrefix);
}
}
private static void addStaticFieldValues(
StringBuilder buf, Class<?> clazz, boolean classNamePrefix) {
Field[] fields = getAllFields(clazz);
for (Field f : fields) {
int modifiers = f.getModifiers();
if (Modifier.isStatic(modifiers)) {
if (classNamePrefix) {
buf.append(f.getDeclaringClass().getName());
buf.append('.');
}
buf.append(f.getName());
buf.append('=');
try {
buf.append(Strings.str(f.get(null)));
} catch (Exception exp) {
throw translate(exp);
}
buf.append(", ");
}
}
Class<?> sc = clazz.getSuperclass();
if (sc != null) {
addStaticFieldValues(buf, sc, classNamePrefix);
}
}
private static RuntimeException translate(Exception exp) {
if (exp instanceof RuntimeException) {
return (RuntimeException) exp;
} else {
return new RuntimeException(exp);
}
}
/** ******** Namespaced methods ***************** */
/*
* Wraps the threads related BTrace utility methods
* @since 1.2
*/
public static class Threads {
// Thread and stack access
/**
* Tests whether this thread has been interrupted. The <i>interrupted status</i> of the thread
* is unaffected by this method.
*
* <p>A thread interruption ignored because a thread was not alive at the time of the interrupt
* will be reflected by this method returning false.
*
* @return <code>true</code> if this thread has been interrupted; <code>false</code> otherwise.
*/
public static boolean isInteruppted() {
return Thread.currentThread().isInterrupted();
}
/** Prints the java stack trace of the current thread. */
public static void jstack() {
jstack(1, -1);
}
/**
* Prints the java stack trace of the current thread. But, atmost given number of frames.
*
* @param numFrames number of frames to be printed. When this is negative all frames are
* printed.
*/
public static void jstack(int numFrames) {
// passing '5' to skip our own frames to generate stack trace
jstack(1, numFrames);
}
private static void jstack(int strip, int numFrames) {
if (numFrames == 0) return;
StackTraceElement[] st = Thread.currentThread().getStackTrace();
BTraceRuntime.stackTrace(st, strip + 2, numFrames);
}
/** Prints Java stack traces of all the Java threads. */
public static void jstackAll() {
jstackAll(1, -1);
}
/**
* Prints Java stack traces of all the Java threads. But, at most given number of frames.
*
* @param numFrames number of frames to be printed. When this is negative all frames are
* printed.
*/
public static void jstackAll(int numFrames) {
jstackAll(1, numFrames);
}
private static void jstackAll(int strip, int numFrames) {
BTraceRuntime.stackTraceAll(numFrames);
}
/**
* Returns the stack trace of current thread as a String.
*
* @return the stack trace as a String.
*/
public static String jstackStr() {
return jstackStr(1, -1);
}
/**
* Returns the stack trace of the current thread as a String but includes atmost the given
* number of frames.
*
* @param numFrames number of frames to be included. When this is negative all frames are
* included.
* @return the stack trace as a String.
*/
public static String jstackStr(int numFrames) {
if (numFrames == 0) {
return "";
}
return jstackStr(1, numFrames);
}
private static String jstackStr(int strip, int numFrames) {
if (numFrames == 0) {
return "";
}
StackTraceElement[] st = Thread.currentThread().getStackTrace();
return BTraceRuntime.stackTraceStr(st, strip + 2, numFrames);
}
/**
* Returns the stack traces of all Java threads as a String.
*
* @return the stack traces as a String.
*/
public static String jstackAllStr() {
return jstackAllStr(-1);
}
/**
* Returns atmost given number of frames in stack traces of all threads as a String.
*
* @param numFrames number of frames to be included. When this is negative all frames are
* included.
* @return the stack traces as a String.
*/
public static String jstackAllStr(int numFrames) {
if (numFrames == 0) {
return "";
}
return BTraceRuntime.stackTraceAllStr(numFrames);
}
/**
* Prints the stack trace of the given exception object.
*
* @param exception throwable for which stack trace is printed.
*/
public static void jstack(Throwable exception) {
jstack(exception, -1);
}
/**
* Prints the stack trace of the given exception object. But, prints atmost given number of
* frames.
*
* @param exception throwable for which stack trace is printed.
* @param numFrames maximum number of frames to be printed.
*/
public static void jstack(Throwable exception, int numFrames) {
if (numFrames == 0) {
return;
}
StackTraceElement[] st = exception.getStackTrace();
println(exception.toString());
BTraceRuntime.stackTrace("\t", st, 0, numFrames);
Throwable cause = exception.getCause();
while (cause != null) {
print("Caused by: ");
println(cause.toString());
st = cause.getStackTrace();
BTraceRuntime.stackTrace("\t", st, 0, numFrames);
cause = cause.getCause();
}
}
/**
* Returns the stack trace of given exception object as a String.
*
* @param exception the throwable for which stack trace is returned.
*/
public static String jstackStr(Throwable exception) {
return jstackStr(exception, -1);
}
/**
* Returns stack trace of given exception object as a String.
*
* @param exception throwable for which stack trace is returned.
* @param numFrames maximum number of frames to be returned.
*/
public static String jstackStr(Throwable exception, int numFrames) {
if (numFrames == 0) {
return "";
}
StackTraceElement[] st = exception.getStackTrace();
StringBuilder buf = new StringBuilder();
buf.append(Strings.str(exception));
buf.append(BTraceRuntime.stackTraceStr("\t", st, 0, numFrames));
Throwable cause = exception.getCause();
while (cause != null) {
buf.append("Caused by:");
st = cause.getStackTrace();
buf.append(BTraceRuntime.stackTraceStr("\t", st, 0, numFrames));
cause = cause.getCause();
}
return buf.toString();
}
/**
* Returns a reference to the currently executing thread object.
*
* @return the currently executing thread.
*/
public static Thread currentThread() {
return Thread.currentThread();
}
/**
* Returns the identifier of the given Thread. The thread ID is a positive <tt>long</tt> number
* generated when the given thread was created. The thread ID is unique and remains unchanged
* during its lifetime. When a thread is terminated, the thread ID may be reused.
*/
public static long threadId(Thread thread) {
return thread.getId();
}
/**
* Returns the state of the given thread. This method is designed for use in monitoring of the
* system state, not for synchronization control.
*/
public static Thread.State threadState(Thread thread) {
return thread.getState();
}
/**
* Returns <tt>true</tt> if and only if the current thread holds the monitor lock on the
* specified object.
*
* <p>This method is designed to allow a program to assert that the current thread already holds
* a specified lock:
*
* <pre>
* assert Thread.holdsLock(obj);
* </pre>
*
* @param obj the object on which to test lock ownership
* @return <tt>true</tt> if the current thread holds the monitor lock on the specified object.
* @throws NullPointerException if obj is <tt>null</tt>
*/
public static boolean holdsLock(Object obj) {
return Thread.holdsLock(obj);
}
/** Prints the Java level deadlocks detected (if any). */
public static void deadlocks() {
deadlocks(true);
}
/**
* Prints deadlocks detected (if any). Optionally prints stack trace of the deadlocked threads.
*
* @param stackTrace boolean flag to specify whether to print stack traces of deadlocked threads
* or not.
*/
public static void deadlocks(boolean stackTrace) {
BTraceRuntime.deadlocks(stackTrace);
}
/**
* Returns the name of the given thread.
*
* @param thread thread whose name is returned
*/
public static String name(Thread thread) {
return thread.getName();
}
}
/*
* Wraps the strings related BTrace utility methods
* @since 1.2
*/
public static class Strings {
public static boolean startsWith(String s, String start) {
return s.startsWith(start);
}
public static boolean endsWith(String s, String end) {
return s.endsWith(end);
}
/**
* This is synonym to "concat".
*
* @see #concat(String, String)
*/
public static String strcat(String str1, String str2) {
return concat(str1, str2);
}
/** Concatenates the specified strings together. */
public static String concat(String str1, String str2) {
return str1.concat(str2);
}
/**
* Compares two strings lexicographically. The comparison is based on the Unicode value of each
* character in the strings. The character sequence represented by the first <code>String</code>
* object is compared lexicographically to the character sequence represented by the second
* string. The result is a negative integer if the first <code>String</code> object
* lexicographically precedes the second string. The result is a positive integer if the first
* <code>String</code> object lexicographically follows the second string. The result is zero if
* the strings are equal; <code>compareTo</code> returns <code>0</code> exactly when the {@link
* String#equals(Object)} method would return <code>true</code>.
*/
public static int compareTo(String str1, String str2) {
return str1.compareTo(str2);
}
/**
* This is synonym to "compareTo" method.
*
* @see #compareTo
*/
public static int strcmp(String str1, String str2) {
return str1.compareTo(str2);
}
/**
* Compares two strings lexicographically, ignoring case differences. This method returns an
* integer whose sign is that of calling <code>compareTo</code> with normalized versions of the
* strings where case differences have been eliminated by calling <code>
* Character.toLowerCase(Character.toUpperCase(character))</code> on each character.
*/
public static int compareToIgnoreCase(String str1, String str2) {
return str1.compareToIgnoreCase(str2);
}
/**
* This is synonym to "compareToIgnoreCase".
*
* @see #compareToIgnoreCase
*/
public static int stricmp(String str1, String str2) {
return str1.compareToIgnoreCase(str2);
}
/** Find String within String */
public static int strstr(String str1, String str2) {
return str1.indexOf(str2);
}
public static int indexOf(String str1, String str2) {
return str1.indexOf(str2);
}
public static int lastIndexOf(String str1, String str2) {
return str1.lastIndexOf(str2);
}
/** Substring */
public static String substr(String str, int start, int length) {
return str.substring(start, length);
}
public static String substr(String str, int start) {
return str.substring(start);
}
/**
* Returns the length of the given string. The length is equal to the number of <a
* href="Character.html#unicode">Unicode code units</a> in the string.
*
* @param str String whose length is calculated.
* @return the length of the sequence of characters represented by this object.
*/
public static int length(String str) {
return str.length();
}
/**
* This is synonym for "length".
*
* @see #length(String)
*/
public static int strlen(String str) {
return str.length();
}
// regular expression matching
/**
* Compiles the given regular expression into a pattern.
*
* @param regex The expression to be compiled
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static Pattern regexp(String regex) {
return Pattern.compile(regex);
}
/**
* This is synonym for "regexp".
*
* @see #regexp(String)
*/
public static Pattern pattern(String regex) {
return regexp(regex);
}
/**
* Compiles the given regular expression into a pattern with the given flags.
*
* @param regex The expression to be compiled
* @param flags Match flags, a bit mask that may include {@link Pattern#CASE_INSENSITIVE},
* {@link Pattern#MULTILINE}, {@link Pattern#DOTALL}, {@link Pattern#UNICODE_CASE}, {@link
* Pattern#CANON_EQ}, {@link Pattern#UNIX_LINES}, {@link Pattern#LITERAL} and {@link
* Pattern#COMMENTS}
* @throws IllegalArgumentException If bit values other than those corresponding to the defined
* match flags are set in <tt>flags</tt>
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static Pattern regexp(String regex, int flags) {
return Pattern.compile(regex, flags);
}
/**
* This is synonym for "regexp".
*
* @see #regexp(String, int)
*/
public static Pattern pattern(String regex, int flags) {
return regexp(regex, flags);
}
/**
* Matches the given (precompiled) regular expression and attempts to match the given input
* against it.
*/
public static boolean matches(Pattern regex, String input) {
return regex.matcher(input).matches();
}
/**
* Compiles the given regular expression and attempts to match the given input against it.
*
* <p>An invocation of this convenience method of the form
*
* <blockquote>
*
* <pre>
* Pattern.matches(regex, input);</pre>
*
* </blockquote>
*
* <p>behaves in exactly the same way as the expression
*
* <blockquote>
*
* <pre>
* Pattern.compile(regex).matcher(input).matches()</pre>
*
* </blockquote>
*
* <p>If a pattern is to be used multiple times, compiling it once and reusing it will be more
* efficient than invoking this method each time.
*
* @param regex The expression to be compiled
* @param input The character sequence to be matched
* @throws PatternSyntaxException If the expression's syntax is invalid
*/
public static boolean matches(String regex, String input) {
return Pattern.matches(regex, input);
}
/**
* Returns a <tt>String</tt> object representing the specified boolean. If the specified boolean
* is <code>true</code>, then the string {@code "true"} will be returned, otherwise the string
* {@code "false"} will be returned.
*
* @param b the boolean to be converted
* @return the string representation of the specified <code>boolean</code>
*/
public static String str(boolean b) {
return Boolean.toString(b);
}
/**
* Returns a <code>String</code> object representing the specified <code>char</code>. The result
* is a string of length 1 consisting solely of the specified <code>char</code>.
*
* @param c the <code>char</code> to be converted
* @return the string representation of the specified <code>char</code>
*/
public static String str(char c) {
return Character.toString(c);
}
/**
* Returns a <code>String</code> object representing the specified integer. The argument is
* converted to signed decimal representation and returned as a string.
*
* @param i an integer to be converted.
* @return a string representation of the argument in base 10.
*/
public static String str(int i) {
return Integer.toString(i);
}
/**
* Returns a string representation of the integer argument as an unsigned integer in
* base 16.
*
* <p>The unsigned integer value is the argument plus 2<sup>32</sup> if the argument is
* negative; otherwise, it is equal to the argument. This value is converted to a string of
* ASCII digits in hexadecimal (base 16) with no extra leading <code>0</code>s. If the
* unsigned magnitude is zero, it is represented by a single zero character <code>'0'</code> (
* <code>'\u0030'</code>); otherwise, the first character of the representation of the
* unsigned magnitude will not be the zero character. The following characters are used as
* hexadecimal digits:
*
* <blockquote>
*
* <pre>
* 0123456789abcdef
* </pre>
*
* </blockquote>
*
* These are the characters <code>'\u0030'</code> through <code>'\u0039'</code> and
* <code>'\u0061'</code> through <code>'\u0066'</code>.
*
* @param i an integer to be converted to a string.
* @return the string representation of the unsigned integer value represented by the argument
* in hexadecimal (base 16).
*/
public static String toHexString(int i) {
return Integer.toHexString(i);
}
/**
* Returns a <code>String</code> object representing the specified <code>long</code>. The
* argument is converted to signed decimal representation and returned as a string.
*
* @param l a <code>long</code> to be converted.
* @return a string representation of the argument in base 10.
*/
public static String str(long l) {
return Long.toString(l);
}
/**
* Returns a string representation of the object. In general, the <code>toString</code> method
* returns a string that "textually represents" this object. The result should be a concise but
* informative representation that is easy for a person to read. For bootstrap classes, returns
* the result of calling Object.toString() override. For non-bootstrap classes, default
* toString() value [className@hashCode] is returned.
*
* @param obj the object whose string representation is returned
* @return a string representation of the given object.
*/
public static String str(Object obj) {
if (obj == null) {
return "null";
} else if (obj instanceof String) {
return (String) obj;
} else if (obj.getClass().getClassLoader() == null) {
try {
return obj.toString();
} catch (NullPointerException e) {
// NPE can be thrown from inside the toString() method we have no control over
return "null";
}
} else {
return identityStr(obj);
}
}
/**
* Returns a string representation of the <code>long</code> argument as an unsigned integer in
* base 16.
*
* <p>The unsigned <code>long</code> value is the argument plus 2<sup>64</sup> if the argument
* is negative; otherwise, it is equal to the argument. This value is converted to a string of
* ASCII digits in hexadecimal (base 16) with no extra leading <code>0</code>s. If the
* unsigned magnitude is zero, it is represented by a single zero character <code>'0'</code> (
* <code>'\u0030'</code>); otherwise, the first character of the representation of the
* unsigned magnitude will not be the zero character. The following characters are used as
* hexadecimal digits:
*
* <blockquote>
*
* <pre>
* 0123456789abcdef
* </pre>
*
* </blockquote>
*
* These are the characters <code>'\u0030'</code> through <code>'\u0039'</code> and
* <code>'\u0061'</code> through <code>'\u0066'</code>.
*
* @param l a <code>long</code> to be converted to a string.
* @return the string representation of the unsigned <code>long</code> value represented by the
* argument in hexadecimal (base 16).
*/
public static String toHexString(long l) {
return Long.toHexString(l);
}
/**
* Returns a string representation of the <code>float</code> argument. All characters mentioned
* below are ASCII characters.
*
* <ul>
* <li>If the argument is NaN, the result is the string "<code>NaN</code>".
* <li>Otherwise, the result is a string that represents the sign and magnitude (absolute
* value) of the argument. If the sign is negative, the first character of the result is '
* <code>-</code>' (<code>'\u002D'</code>); if the sign is positive, no sign character
* appears in the result. As for the magnitude <i>m</i>:
* <ul>
* <li>If <i>m</i> is infinity, it is represented by the characters <code>"Infinity"
* </code>; thus, positive infinity produces the result <code>"Infinity"</code> and
* negative infinity produces the result <code>"-Infinity"</code>.
* <li>If <i>m</i> is zero, it is represented by the characters <code>"0.0"</code>;
* thus, negative zero produces the result <code>"-0.0"</code> and positive zero
* produces the result <code>"0.0"</code>.
* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less than
* 10<sup>7</sup>, then it is represented as the integer part of <i>m</i>, in
* decimal form with no leading zeroes, followed by '<code>.</code>' (<code>
* '\u002E'</code>), followed by one or more decimal digits representing the
* fractional part of <i>m</i>.
* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or equal to
* 10<sup>7</sup>, then it is represented in so-called "computerized scientific
* notation." Let <i>n</i> be the unique integer such that 10<sup><i>n</i>
* </sup><= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
* mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so that 1
* <= <i>a</i> < 10. The magnitude is then represented as the integer part of
* <i>a</i>, as a single decimal digit, followed by '<code>.</code>' (<code>
* '\u002E'</code>), followed by decimal digits representing the fractional part
* of <i>a</i>, followed by the letter '<code>E</code>' (<code>'\u0045'</code>),
* followed by a representation of <i>n</i> as a decimal integer, as produced by the
* method <code>{@link
* java.lang.Integer#toString(int)}</code>.
* </ul>
* </ul>
*
* How many digits must be printed for the fractional part of <i>m</i> or <i>a</i>? There must
* be at least one digit to represent the fractional part, and beyond that as many, but only as
* many, more digits as are needed to uniquely distinguish the argument value from adjacent
* values of type <code>float</code>. That is, suppose that <i>x</i> is the exact mathematical
* value represented by the decimal representation produced by this method for a finite nonzero
* argument <i>f</i>. Then <i>f</i> must be the <code>float</code> value nearest to <i>x</i>;
* or, if two <code>float</code> values are equally close to <i>x</i>, then <i>f</i> must be one
* of them and the least significant bit of the significand of <i>f</i> must be <code>0</code>.
*
* <p>
*
* @param f the float to be converted.
* @return a string representation of the argument.
*/
public static String str(float f) {
return Float.toString(f);
}
/**
* Returns a string representation of the <code>double</code> argument. All characters mentioned
* below are ASCII characters.
*
* <ul>
* <li>If the argument is NaN, the result is the string "<code>NaN</code>".
* <li>Otherwise, the result is a string that represents the sign and magnitude (absolute
* value) of the argument. If the sign is negative, the first character of the result is '
* <code>-</code>' (<code>'\u002D'</code>); if the sign is positive, no sign character
* appears in the result. As for the magnitude <i>m</i>:
* <ul>
* <li>If <i>m</i> is infinity, it is represented by the characters <code>"Infinity"
* </code>; thus, positive infinity produces the result <code>"Infinity"</code> and
* negative infinity produces the result <code>"-Infinity"</code>.
* <li>If <i>m</i> is zero, it is represented by the characters <code>"0.0"</code>;
* thus, negative zero produces the result <code>"-0.0"</code> and positive zero
* produces the result <code>"0.0"</code>.
* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less than
* 10<sup>7</sup>, then it is represented as the integer part of <i>m</i>, in
* decimal form with no leading zeroes, followed by '<code>.</code>' (<code>
* '\u002E'</code>), followed by one or more decimal digits representing the
* fractional part of <i>m</i>.
* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or equal to
* 10<sup>7</sup>, then it is represented in so-called "computerized scientific
* notation." Let <i>n</i> be the unique integer such that 10<sup><i>n</i></sup>
* <= <i>m</i> < 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
* mathematically exact quotient of <i>m</i> and 10<sup><i>n</i></sup> so that 1
* <= <i>a</i> < 10. The magnitude is then represented as the integer part of
* <i>a</i>, as a single decimal digit, followed by '<code>.</code>' (<code>
* '\u002E'</code>), followed by decimal digits representing the fractional part
* of <i>a</i>, followed by the letter '<code>E</code>' (<code>'\u0045'</code>),
* followed by a representation of <i>n</i> as a decimal integer, as produced by the
* method {@link Integer#toString(int)}.
* </ul>
* </ul>
*
* How many digits must be printed for the fractional part of <i>m</i> or <i>a</i>? There must
* be at least one digit to represent the fractional part, and beyond that as many, but only as
* many, more digits as are needed to uniquely distinguish the argument value from adjacent
* values of type <code>double</code>. That is, suppose that <i>x</i> is the exact mathematical
* value represented by the decimal representation produced by this method for a finite nonzero
* argument <i>d</i>. Then <i>d</i> must be the <code>double</code> value nearest to <i>x</i>;
* or if two <code>double</code> values are equally close to <i>x</i>, then <i>d</i> must be one
* of them and the least significant bit of the significand of <i>d</i> must be <code>0</code>.
*
* <p>
*
* @param d the <code>double</code> to be converted.
* @return a string representation of the argument.
*/
public static String str(double d) {
return Double.toString(d);
}
/**
* Safely creates a new instance of an appendable string buffer <br>
*
* @param threadSafe Specifies whether the buffer should be thread safe
* @return Returns either {@linkplain StringBuilder} or {@linkplain StringBuffer} instance
* depending on whether the instance is required to be thread safe or not, respectively.
* @since 1.2
*/
public static Appendable newStringBuilder(boolean threadSafe) {
return BTraceRuntime.newStringBuilder(threadSafe);
}
/**
* Safely creates a new instance of an appendable string buffer <br>
* The buffer will not be thread safe.
*
* @return Returns a new instance of {@linkplain StringBuilder} class
* @since 1.2
*/
public static Appendable newStringBuilder() {
return BTraceRuntime.newStringBuilder();
}
/**
* Appends a string to an appendable buffer created by {@linkplain
* BTraceUtils.Strings#newStringBuilder()}
*
* @param buffer The appendable buffer to append to
* @param strToAppend The string to append
* @return Returns the same appendable buffer instance
* @since 1.2
*/
public static Appendable append(Appendable buffer, String strToAppend) {
return BTraceRuntime.append(buffer, strToAppend);
}
/**
* Checks the length of an appendable buffer created by {@linkplain
* BTraceUtils.Strings#newStringBuilder()}
*
* @param buffer The appendable buffer instance
* @return Returns the length of the text contained by the buffer
* @since 1.2
*/
public static int length(Appendable buffer) {
return BTraceRuntime.length(buffer);
}
}
/*
* Wraps the numbers related BTrace utility methods
* @since 1.2
*/
public static class Numbers {
/**
* Returns a <code>double</code> value with a positive sign, greater than or equal to <code>0.0
* </code> and less than <code>1.0</code>. Returned values are chosen pseudorandomly with
* (approximately) uniform distribution from that range.
*/
public static double random() {
return Math.random();
}
/**
* Returns the natural logarithm (base <i>e</i>) of a <code>double</code> value. Special cases:
*
* <ul>
* <li>If the argument is NaN or less than zero, then the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is positive zero or negative zero, then the result is negative
* infinity.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a a value
* @return the value ln <code>a</code>, the natural logarithm of <code>a</code>.
*/
public static strictfp double log(double a) {
return Math.log(a);
}
/**
* Returns the base 10 logarithm of a <code>double</code> value. Special cases:
*
* <ul>
* <li>If the argument is NaN or less than zero, then the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is positive zero or negative zero, then the result is negative
* infinity.
* <li>If the argument is equal to 10<sup><i>n</i></sup> for integer <i>n</i>, then the result
* is <i>n</i>.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a a value
* @return the base 10 logarithm of <code>a</code>.
*/
public static strictfp double log10(double a) {
return Math.log10(a);
}
/**
* Returns Euler's number <i>e</i> raised to the power of a <code>double</code> value. Special
* cases:
*
* <ul>
* <li>If the argument is NaN, the result is NaN.
* <li>If the argument is positive infinity, then the result is positive infinity.
* <li>If the argument is negative infinity, then the result is positive zero.
* </ul>
*
* <p>The computed result must be within 1 ulp of the exact result. Results must be
* semi-monotonic.
*
* @param a the exponent to raise <i>e</i> to.
* @return the value <i>e</i><sup><code>a</code></sup>, where <i>e</i> is the base of the
* natural logarithms.
*/
public static strictfp double exp(double a) {
return Math.exp(a);
}
/**
* Returns <code>true</code> if the specified number is a Not-a-Number (NaN) value, <code>false
* </code> otherwise.
*
* @param d the value to be tested.
* @return <code>true</code> if the value of the argument is NaN; <code>false</code> otherwise.
*/
public static boolean isNaN(double d) {
return Double.isNaN(d);
}
/**
* Returns <code>true</code> if the specified number is a Not-a-Number (NaN) value, <code>false
* </code> otherwise.
*
* @param f the value to be tested.
* @return <code>true</code> if the value of the argument is NaN; <code>false</code> otherwise.
*/
public static boolean isNaN(float f) {
return Float.isNaN(f);
}
/**
* Returns <code>true</code> if the specified number is infinitely large in magnitude, <code>
* false</code> otherwise.
*
* @param d the value to be tested.
* @return <code>true</code> if the value of the argument is positive infinity or negative
* infinity; <code>false</code> otherwise.
*/
public static boolean isInfinite(double d) {
return Double.isInfinite(d);
}
/**
* Returns <code>true</code> if the specified number is infinitely large in magnitude, <code>
* false</code> otherwise.
*
* @param f the value to be tested.
* @return <code>true</code> if the value of the argument is positive infinity or negative
* infinity; <code>false</code> otherwise.
*/
public static boolean isInfinite(float f) {
return Float.isInfinite(f);
}
// string parsing methods
/**
* Parses the string argument as a boolean. The <code>boolean</code> returned represents the
* value <code>true</code> if the string argument is not <code>null</code> and is equal,
* ignoring case, to the string {@code "true"}.
*
* <p>Example: {@code Boolean.parseBoolean("True")} returns <tt>true</tt>.<br>
* Example: {@code Boolean.parseBoolean("yes")} returns <tt>false</tt>.
*
* @param s the <code>String</code> containing the boolean representation to be parsed
* @return the boolean represented by the string argument
*/
public static boolean parseBoolean(String s) {
return Boolean.parseBoolean(s);
}
/**
* Parses the string argument as a signed decimal <code>byte</code>. The characters in the
* string must all be decimal digits, except that the first character may be an ASCII minus sign
* <code>'-'</code> (<code>'\u002D'</code>) to indicate a negative value. The resulting
* <code>byte</code> value is returned.
*
* @param s a <code>String</code> containing the <code>byte</code> representation to be parsed
* @return the <code>byte</code> value represented by the argument in decimal
*/
public static byte parseByte(String s) {
return Byte.parseByte(s);
}
/**
* Parses the string argument as a signed decimal <code>short</code>. The characters in the
* string must all be decimal digits, except that the first character may be an ASCII minus sign
* <code>'-'</code> (<code>'\u002D'</code>) to indicate a negative value. The resulting
* <code>short</code> value is returned.
*
* @param s a <code>String</code> containing the <code>short</code> representation to be parsed
* @return the <code>short</code> value represented by the argument in decimal.
*/
public static short parseShort(String s) {
return Short.parseShort(s);
}
/**
* Parses the string argument as a signed decimal integer. The characters in the string must all
* be decimal digits, except that the first character may be an ASCII minus sign <code>'-'
* </code> (<code>'\u002D'</code>) to indicate a negative value. The resulting integer value
* is returned.
*
* @param s a <code>String</code> containing the <code>int</code> representation to be parsed
* @return the integer value represented by the argument in decimal.
*/
public static int parseInt(String s) {
return Integer.parseInt(s);
}
/**
* Parses the string argument as a signed decimal <code>long</code>. The characters in the
* string must all be decimal digits, except that the first character may be an ASCII minus sign
* <code>'-'</code> (<code>\u002D'</code>) to indicate a negative value. The resulting
* <code>long</code> value is returned.
*
* <p>Note that neither the character <code>L</code> (<code>'\u004C'</code>) nor <code>l
* </code> (<code>'\u006C'</code>) is permitted to appear at the end of the string as a type
* indicator, as would be permitted in Java programming language source code.
*
* @param s a <code>String</code> containing the <code>long</code> representation to be parsed
* @return the <code>long</code> represented by the argument in decimal.
*/
public static long parseLong(String s) {
return Long.parseLong(s);
}
/**
* Returns a new <code>float</code> initialized to the value represented by the specified <code>
* String</code>, as performed by the <code>valueOf</code> method of class <code>Float</code>.
*
* @param s the string to be parsed.
* @return the <code>float</code> value represented by the string argument.
*/
public static float parseFloat(String s) {
return Float.parseFloat(s);
}
/**
* Returns a new <code>double</code> initialized to the value represented by the specified
* <code>String</code>, as performed by the <code>valueOf</code> methcod of class <code>Double
* </code>.
*
* @param s the string to be parsed.
* @return the <code>double</code> value represented by the string argument.
*/
public static double parseDouble(String s) {
return Double.parseDouble(s);
}
// boxing methods
/**
* Returns a <tt>Boolean</tt> instance representing the specified <tt>boolean</tt> value. If the
* specified <tt>boolean</tt> value is <tt>true</tt>, this method returns <tt>Boolean.TRUE</tt>;
* if it is <tt>false</tt>, this method returns <tt>Boolean.FALSE</tt>.
*
* @param b a boolean value.
* @return a <tt>Boolean</tt> instance representing <tt>b</tt>.
*/
public static Boolean box(boolean b) {
return b;
}
/**
* Returns a <tt>Character</tt> instance representing the specified <tt>char</tt> value.
*
* @param c a char value.
* @return a <tt>Character</tt> instance representing <tt>c</tt>.
*/
public static Character box(char c) {
return c;
}
/**
* Returns a <tt>Byte</tt> instance representing the specified <tt>byte</tt> value.
*
* @param b a byte value.
* @return a <tt>Byte</tt> instance representing <tt>b</tt>.
*/
public static Byte box(byte b) {
return b;
}
/**
* Returns a <tt>Short</tt> instance representing the specified <tt>short</tt> value.
*
* @param s a short value.
* @return a <tt>Short</tt> instance representing <tt>s</tt>.
*/
public static Short box(short s) {
return s;
}
/**
* Returns a <tt>Integer</tt> instance representing the specified <tt>int</tt> value.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
*/
public static Integer box(int i) {
return i;
}
/**
* Returns a <tt>Long</tt> instance representing the specified <tt>long</tt> value.
*
* @param l a long value.
* @return a <tt>Long</tt> instance representing <tt>l</tt>.
*/
public static Long box(long l) {
return l;
}
/**
* Returns a <tt>Float</tt> instance representing the specified <tt>float</tt> value.
*
* @param f a float value.
* @return a <tt>Float</tt> instance representing <tt>f</tt>.
*/
public static Float box(float f) {
return f;
}
/**
* Returns a <tt>Double</tt> instance representing the specified <tt>double</tt> value.
*
* @param d a double value.
* @return a <tt>Double</tt> instance representing <tt>d</tt>.
*/
public static Double box(double d) {
return d;
}
// unboxing methods
/**
* Returns the value of the given <tt>Boolean</tt> object as a boolean primitive.
*
* @param b the Boolean object whose value is returned.
* @return the primitive <code>boolean</code> value of the object.
*/
public static boolean unbox(Boolean b) {
return b;
}
/**
* Returns the value of the given <tt>Character</tt> object as a char primitive.
*
* @param ch the Character object whose value is returned.
* @return the primitive <code>char</code> value of the object.
*/
public static char unbox(Character ch) {
return ch;
}
/**
* Returns the value of the specified Byte as a <code>byte</code>.
*
* @param b Byte that is unboxed
* @return the byte value represented by the <code>Byte</code>.
*/
public static byte unbox(Byte b) {
return b;
}
/**
* Returns the short value represented by <code>Short</code>.
*
* @param s Short that is unboxed.
* @return the short value represented by the <code>Short</code>.
*/
public static short unbox(Short s) {
return s;
}
/**
* Returns the value of represented by <code>Integer</code>.
*
* @param i Integer that is unboxed.
* @return the int value represented by the <code>Integer</code>.
*/
public static int unbox(Integer i) {
return i;
}
/**
* Returns the long value represented by the specified <code>Long</code>.
*
* @param l Long to be unboxed.
* @return the long value represented by the <code>Long</code>.
*/
public static long unbox(Long l) {
return l;
}
/**
* Returns the float value represented by the specified <code>Float</code>.
*
* @param f Float to be unboxed.
* @return the float value represented by the <code>Float</code>.
*/
public static float unbox(Float f) {
return f;
}
/**
* Returns the double value represented by the specified <code>Double</code>.
*
* @param d Double to be unboxed.
*/
public static double unbox(Double d) {
return d;
}
}
/*
* Wraps the time related BTrace utility methods
* @since 1.2
*/
public static class Time {
/**
* Returns the current time in milliseconds. Note that while the unit of time of the return
* value is a millisecond, the granularity of the value depends on the underlying operating
* system and may be larger. For example, many operating systems measure time in units of tens
* of milliseconds.
*
* @return the difference, measured in milliseconds, between the current time and midnight,
* January 1, 1970 UTC.
*/
public static long millis() {
return java.lang.System.currentTimeMillis();
}
/**
* Returns the current value of the most precise available system timer, in nanoseconds.
*
* <p>This method can only be used to measure elapsed time and is not related to any other
* notion of system or wall-clock time. The value returned represents nanoseconds since some
* fixed but arbitrary time (perhaps in the future, so values may be negative). This method
* provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are
* made about how frequently values change. Differences in successive calls that span greater
* than approximately 292 years (2<sup>63</sup> nanoseconds) will not accurately compute elapsed
* time due to numerical overflow.
*
* @return The current value of the system timer, in nanoseconds.
*/
public static long nanos() {
return java.lang.System.nanoTime();
}
/**
* Generates a string timestamp (current date&time)
*
* @param format The format to be used - see {@linkplain SimpleDateFormat}
* @return Returns a string representing current date&time
* @since 1.1
*/
public static String timestamp(String format) {
return new SimpleDateFormat(format).format(Calendar.getInstance().getTime());
}
/**
* Generates a string timestamp (current date&time) in the default system format
*
* @return Returns a string representing current date&time
* @since 1.1
*/
public static String timestamp() {
return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}
}
/*
* Wraps the collections related BTrace utility methods
* @since 1.2
*/
@SuppressWarnings("EmptyMethod")
public static class Collections {
// Create a new map
public static <K, V> Map<K, V> newHashMap() {
return BTraceRuntime.newHashMap();
}
public static <K, V> Map<K, V> newWeakMap() {
return BTraceRuntime.newWeakMap();
}
public static <V> Deque<V> newDeque() {
return BTraceRuntime.newDeque();
}
public static <K, V> void putAll(Map<K, V> src, Map<K, V> dst) {
BTraceRuntime.putAll(src, dst);
}
public static <K, V> void copy(Map<K, V> src, Map<K, V> dst) {
BTraceRuntime.copy(src, dst);
}
public static <V> void copy(Collection<V> src, Collection<V> dst) {}
// get a particular item from a Map
public static <K, V> V get(Map<K, V> map, K key) {
return BTraceRuntime.get(map, key);
}
// check whether an item exists
public static <K, V> boolean containsKey(Map<K, V> map, K key) {
return BTraceRuntime.containsKey(map, key);
}
public static <K, V> boolean containsValue(Map<K, V> map, V value) {
return BTraceRuntime.containsValue(map, value);
}
// put a particular item into a Map
public static <K, V> V put(Map<K, V> map, K key, V value) {
return BTraceRuntime.put(map, key, value);
}
// remove a particular item from a Map
public static <K, V> V remove(Map<K, V> map, K key) {
return BTraceRuntime.remove(map, key);
}
// clear all items from a Map
public static <K, V> void clear(Map<K, V> map) {
BTraceRuntime.clear(map);
}
// return the size of a Map
public static <K, V> int size(Map<K, V> map) {
return BTraceRuntime.size(map);
}
public static <K, V> boolean isEmpty(Map<K, V> map) {
return BTraceRuntime.isEmpty(map);
}
// operations on collections
public static <E> int size(Collection<E> coll) {
return BTraceRuntime.size(coll);
}
public static <E> boolean isEmpty(Collection<E> coll) {
return BTraceRuntime.isEmpty(coll);
}
public static <E> boolean contains(Collection<E> coll, Object obj) {
return BTraceRuntime.contains(coll, obj);
}
public static boolean contains(Object[] array, Object value) {
for (Object each : array) {
if (compare(each, value)) {
return true;
}
}
return false;
}
public static <E> Object[] toArray(Collection<E> collection) {
return BTraceRuntime.toArray(collection);
}
// operations on Deque
public static <V> void push(Deque<V> queue, V value) {
BTraceRuntime.push(queue, value);
}
public static <V> V poll(Deque<V> queue) {
return BTraceRuntime.poll(queue);
}
public static <V> V peek(Deque<V> queue) {
return BTraceRuntime.peek(queue);
}
public static <V> void addLast(Deque<V> queue, V value) {
BTraceRuntime.addLast(queue, value);
}
public static <V> V peekFirst(Deque<V> queue) {
return BTraceRuntime.peekFirst(queue);
}
public static <V> V peekLast(Deque<V> queue) {
return BTraceRuntime.peekLast(queue);
}
public static <V> V removeLast(Deque<V> queue) {
return BTraceRuntime.removeLast(queue);
}
public static <V> V removeFirst(Deque<V> queue) {
return BTraceRuntime.removeFirst(queue);
}
}
/*
* Wraps the atomicity related BTrace utility methods
* @since 1.2
*/
public static class Atomic {
/**
* Creates a new AtomicInteger with the given initial value.
*
* @param initialValue the initial value
*/
public static AtomicInteger newAtomicInteger(int initialValue) {
return BTraceRuntime.newAtomicInteger(initialValue);
}
/**
* Gets the current value of the given AtomicInteger.
*
* @param ai AtomicInteger whose value is returned.
* @return the current value
*/
public static int get(AtomicInteger ai) {
return BTraceRuntime.get(ai);
}
/**
* Sets to the given value to the given AtomicInteger.
*
* @param ai AtomicInteger whose value is set.
* @param newValue the new value
*/
public static void set(AtomicInteger ai, int newValue) {
BTraceRuntime.set(ai, newValue);
}
/**
* Eventually sets to the given value to the given AtomicInteger.
*
* @param ai AtomicInteger whose value is lazily set.
* @param newValue the new value
*/
public static void lazySet(AtomicInteger ai, int newValue) {
BTraceRuntime.lazySet(ai, newValue);
}
/**
* Atomically sets the value of given AtomitInteger to the given updated value if the current
* value {@code ==} the expected value.
*
* @param ai AtomicInteger whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that the actual value was not equal to the
* expected value.
*/
public static boolean compareAndSet(AtomicInteger ai, int expect, int update) {
return BTraceRuntime.compareAndSet(ai, expect, update);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a> and does not provide
* ordering guarantees, so is only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param ai AtomicInteger whose value is weakly compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public static boolean weakCompareAndSet(AtomicInteger ai, int expect, int update) {
return BTraceRuntime.weakCompareAndSet(ai, expect, update);
}
/**
* Atomically increments by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is incremented.
* @return the previous value
*/
public static int getAndIncrement(AtomicInteger ai) {
return BTraceRuntime.getAndIncrement(ai);
}
/**
* Atomically decrements by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is decremented.
* @return the previous value
*/
public static int getAndDecrement(AtomicInteger ai) {
return BTraceRuntime.getAndDecrement(ai);
}
/**
* Atomically increments by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger that is incremented.
* @return the updated value
*/
public static int incrementAndGet(AtomicInteger ai) {
return BTraceRuntime.incrementAndGet(ai);
}
/**
* Atomically decrements by one the current value of given AtomicInteger.
*
* @param ai AtomicInteger whose value is decremented.
* @return the updated value
*/
public static int decrementAndGet(AtomicInteger ai) {
return BTraceRuntime.decrementAndGet(ai);
}
/**
* Atomically adds the given value to the current value.
*
* @param ai AtomicInteger whose value is added to.
* @param delta the value to add
* @return the previous value
*/
public static int getAndAdd(AtomicInteger ai, int delta) {
return BTraceRuntime.getAndAdd(ai, delta);
}
/**
* Atomically adds the given value to the current value.
*
* @param ai AtomicInteger whose value is added to.
* @param delta the value to add
* @return the updated value
*/
public static int addAndGet(AtomicInteger ai, int delta) {
return BTraceRuntime.addAndGet(ai, delta);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param ai AtomicInteger whose value is set.
* @param newValue the new value
* @return the previous value
*/
public static int getAndSet(AtomicInteger ai, int newValue) {
return BTraceRuntime.getAndSet(ai, newValue);
}
/**
* Creates a new AtomicLong with the given initial value.
*
* @param initialValue the initial value
*/
public static AtomicLong newAtomicLong(long initialValue) {
return BTraceRuntime.newAtomicLong(initialValue);
}
/**
* Gets the current value the given AtomicLong.
*
* @param al AtomicLong whose value is returned.
* @return the current value
*/
public static long get(AtomicLong al) {
return BTraceRuntime.get(al);
}
/**
* Sets to the given value.
*
* @param al AtomicLong whose value is set.
* @param newValue the new value
*/
public static void set(AtomicLong al, long newValue) {
BTraceRuntime.set(al, newValue);
}
/**
* Eventually sets to the given value to the given AtomicLong.
*
* @param al AtomicLong whose value is set.
* @param newValue the new value
*/
public static void lazySet(AtomicLong al, long newValue) {
BTraceRuntime.lazySet(al, newValue);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* @param al AtomicLong whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that the actual value was not equal to the
* expected value.
*/
public static boolean compareAndSet(AtomicLong al, long expect, long update) {
return BTraceRuntime.compareAndSet(al, expect, update);
}
/**
* Atomically sets the value to the given updated value if the current value {@code ==} the
* expected value.
*
* <p>May fail spuriously and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param al AtomicLong whose value is compared and set.
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public static boolean weakCompareAndSet(AtomicLong al, long expect, long update) {
return BTraceRuntime.weakCompareAndSet(al, expect, update);
}
/**
* Atomically increments by one the current value.
*
* @param al AtomicLong whose value is incremented.
* @return the previous value
*/
public static long getAndIncrement(AtomicLong al) {
return BTraceRuntime.getAndIncrement(al);
}
/**
* Atomically decrements by one the current value.
*
* @param al AtomicLong whose value is decremented.
* @return the previous value
*/
public static long getAndDecrement(AtomicLong al) {
return BTraceRuntime.getAndDecrement(al);
}
/**
* Atomically increments by one the current value.
*
* @param al AtomicLong whose value is incremented.
* @return the updated value
*/
public static long incrementAndGet(AtomicLong al) {
return BTraceRuntime.incrementAndGet(al);
}
/**
* Atomically decrements by one the current value.
*
* @param al AtomicLong whose value is decremented.
* @return the updated value
*/
public static long decrementAndGet(AtomicLong al) {
return BTraceRuntime.decrementAndGet(al);
}
/**
* Atomically adds the given value to the current value.
*
* @param al AtomicLong whose value is added to.
* @param delta the value to add
* @return the previous value
*/
public static long getAndAdd(AtomicLong al, long delta) {
return BTraceRuntime.getAndAdd(al, delta);
}
/**
* Atomically adds the given value to the current value.
*
* @param al AtomicLong whose value is added to
* @param delta the value to add
* @return the updated value
*/
public static long addAndGet(AtomicLong al, long delta) {
return BTraceRuntime.addAndGet(al, delta);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param al AtomicLong that is set.
* @param newValue the new value
* @return the previous value
*/
public static long getAndSet(AtomicLong al, long newValue) {
return BTraceRuntime.getAndSet(al, newValue);
}
}
/*
* Wraps the aggregations related BTrace utility methods
* @since 1.2
*/
public static class Aggregations {
/**
* Creates a new aggregation based on the given aggregation function type.
*
* @param type the aggregating function to be performed on the data being added to the
* aggregation.
*/
public static Aggregation newAggregation(AggregationFunction type) {
return BTraceRuntime.newAggregation(type);
}
/**
* Creates a grouping aggregation key with the provided value. The value must be a String or
* Number type.
*
* @param element1 the value of the aggregation key
*/
public static AggregationKey newAggregationKey(Object element1) {
return BTraceRuntime.newAggregationKey(element1);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(Object element1, Object element2) {
return BTraceRuntime.newAggregationKey(element1, element2);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
* @param element3 the third element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(
Object element1, Object element2, Object element3) {
return BTraceRuntime.newAggregationKey(element1, element2, element3);
}
/**
* Creates a composite grouping aggregation key with the provided values. The values must be
* String or Number types.
*
* @param element1 the first element of the composite aggregation key
* @param element2 the second element of the composite aggregation key
* @param element3 the third element of the composite aggregation key
* @param element4 the fourth element of the composite aggregation key
*/
public static AggregationKey newAggregationKey(
Object element1, Object element2, Object element3, Object element4) {
return BTraceRuntime.newAggregationKey(element1, element2, element3, element4);
}
/**
* Adds a value to the aggregation with no grouping key. This method should be used when the
* aggregation is to calculate only a single aggregated value.
*
* @param aggregation the aggregation to which the value should be added
*/
public static void addToAggregation(Aggregation aggregation, long value) {
BTraceRuntime.addToAggregation(aggregation, value);
}
/**
* Adds a value to the aggregation with a grouping key. This method should be used when the
* aggregation should effectively perform a "group by" on the key value. The aggregation will
* calculate a separate aggregated value for each unique aggregation key.
*
* @param aggregation the aggregation to which the value should be added
* @param key the grouping aggregation key
*/
public static void addToAggregation(Aggregation aggregation, AggregationKey key, long value) {
BTraceRuntime.addToAggregation(aggregation, key, value);
}
/**
* Resets values within the aggregation to the default. This will affect all values within the
* aggregation when multiple aggregation keys have been used.
*
* @param aggregation the aggregation to be cleared
*/
public static void clearAggregation(Aggregation aggregation) {
BTraceRuntime.clearAggregation(aggregation);
}
/**
* Removes all aggregated values from the aggregation except for the largest or smallest <code>
* abs(count)</code> elements.
*
* <p>If <code>count</code> is positive, the largest aggregated values in the aggregation will
* be preserved. If <code>count</code> is negative the smallest values will be preserved. If
* <code>count</code> is zero then all elements will be removed.
*
* <p>Behavior is intended to be similar to the dtrace <code>trunc()</code> function.
*
* @param aggregation the aggregation to be truncated
* @param count the number of elements to preserve. If negative, the smallest <code>abs(count)
* </code> elements are preserved.
*/
public static void truncateAggregation(Aggregation aggregation, int count) {
BTraceRuntime.truncateAggregation(aggregation, count);
}
public static void printAggregation(String name, Aggregation aggregation) {
BTraceRuntime.printAggregation(name, aggregation);
}
public static void printAggregation(String name, Aggregation aggregation, String format) {
BTraceRuntime.printAggregation(name, aggregation, format);
}
public static void printAggregation(
String name, String format, Collection<Aggregation> aggregationList) {
Aggregation[] aggregationArray = new Aggregation[aggregationList.size()];
int index = 0;
for (Aggregation a : aggregationList) {
aggregationArray[index] = a;
index++;
}
BTraceRuntime.printAggregation(name, format, aggregationArray);
}
}
/**
* Profiling support. It is a highly specialized aggregation (therefore not included in the
* generic aggregations support) which is able to calculate clean self time spent in
* hierarchically called methods (or bigger parts of code)
*/
public static class Profiling {
/**
* Creates a new {@linkplain Profiler} instance
*
* @return A new {@linkplain Profiler} instance
*/
public static Profiler newProfiler() {
return BTraceRuntime.newProfiler();
}
/**
* Creates a new {@linkplain Profiler} instance with the specified expected count of the
* distinct methods to be recorded.
*
* @param expectedBlockCnt The expected count of the distinct blocks to be recorded.
* @return Returns a new {@linkplain Profiler} instance
*/
public static Profiler newProfiler(int expectedBlockCnt) {
return BTraceRuntime.newProfiler(expectedBlockCnt);
}
/**
* Records the entry to a particular code block
*
* @param profiler The {@linkplain Profiler} instance to use
* @param blockName The block identifier
*/
public static void recordEntry(Profiler profiler, String blockName) {
BTraceRuntime.recordEntry(profiler, blockName);
}
/**
* Records the exit out of a particular code block
*
* @param profiler The {@linkplain Profiler} instance to use
* @param blockName The block identifier
* @param duration The time spent in the mentioned block
*/
public static void recordExit(Profiler profiler, String blockName, long duration) {
BTraceRuntime.recordExit(profiler, blockName, duration);
}
/**
* Creates a new snapshot of the profiling metrics collected sofar
*
* @param profiler The {@linkplain Profiler} instance to use
* @return Returns an immutable snapshot of the profiling metrics in the form of a map where the
* key is the block name and the value is a map of metrics names and the appropriate values
* <br>
* The supported metrics names are: "selfTime", "wallTime" and "invocations"
*/
public static Profiler.Snapshot snapshot(Profiler profiler) {
return BTraceRuntime.snapshot(profiler);
}
public static Profiler.Snapshot snapshotAndReset(Profiler profiler) {
return BTraceRuntime.snapshotAndReset(profiler);
}
public static void reset(Profiler profiler) {
BTraceRuntime.resetProfiler(profiler);
}
public static void printSnapshot(String name, Profiler profiler) {
BTraceRuntime.printSnapshot(name, profiler.snapshot());
}
public static void printSnapshot(String name, Profiler profiler, String format) {
BTraceRuntime.printSnapshot(name, profiler.snapshot(), format);
}
}
/*
* Wraps the speculation related BTrace utility methods
* @since 1.2
*/
public static class Speculation {
/**
* Returns an identifier for a new speculative buffer.
*
* @return new speculative buffer id
*/
public static int speculation() {
return BTraceRuntime.speculation();
}
/**
* Sets current speculative buffer id.
*
* @param id the speculative buffer id
*/
public static void speculate(int id) {
BTraceRuntime.speculate(id);
}
/**
* Commits the speculative buffer associated with id.
*
* @param id the speculative buffer id
*/
public static void commit(int id) {
BTraceRuntime.commit(id);
}
/**
* Discards the speculative buffer associated with id.
*
* @param id the speculative buffer id
*/
public static void discard(int id) {
BTraceRuntime.discard(id);
}
}
/*
* Wraps the references related BTrace utility methods
* @since 1.2
*/
public static class References {
/**
* Creates and returns a weak reference to the given object.
*
* @param obj object for which a weak reference is created.
* @return a weak reference to the given object.
*/
public static WeakReference weakRef(Object obj) {
return new WeakReference<>(obj);
}
/**
* Creates and returns a soft reference to the given object.
*
* @param obj object for which a soft reference is created.
* @return a soft reference to the given object.
*/
public static SoftReference softRef(Object obj) {
return new SoftReference<>(obj);
}
/**
* Returns the given reference object's referent. If the reference object has been cleared,
* either by the program or by the garbage collector, then this method returns <code>null</code>
* .
*
* @param ref reference object whose referent is returned.
* @return The object to which the reference refers, or <code>null</code> if the reference
* object has been cleared.
*/
public static Object deref(Reference ref) {
if (ref.getClass().getClassLoader() == null) {
return ref.get();
} else {
throw new IllegalArgumentException();
}
}
}
/*
* Wraps the reflection related BTrace utility methods
* @since 1.2
*/
public static class Reflective {
/**
* Returns the runtime class of the given Object.
*
* @param obj the Object whose Class is returned
* @return the Class object of given object
*/
public static Class<?> classOf(Object obj) {
return obj.getClass();
}
/**
* Returns the Class object representing the class or interface that declares the field
* represented by the given Field object.
*
* @param field whose declaring Class is returned
*/
public static Class<?> declaringClass(Field field) {
return field.getDeclaringClass();
}
/** Returns the name of the given Class object. */
public static String name(Class<?> clazz) {
return clazz.getName();
}
/**
* Returns the name of the Field object.
*
* @param field Field for which name is returned
* @return name of the given field
*/
public static String name(Field field) {
return field.getName();
}
/**
* Returns the type of the Field object.
*
* @param field Field for which type is returned
* @return type of the given field
*/
public static Class<?> type(Field field) {
return field.getType();
}
/** Returns the access flags of the given Class. */
public static int accessFlags(Class<?> clazz) {
return clazz.getModifiers();
}
/** Returns the access flags of the given Field. */
public static int accessFlags(Field field) {
return field.getModifiers();
}
/** Returns the current context class loader */
public static ClassLoader contextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
// get Class of the given name
/** Returns Class object for given class name. */
public static Class<?> classForName(String name) {
ClassLoader callerLoader = BTraceRuntime.getCallerClassloader(STACK_DEC);
return classForName(name, callerLoader);
}
/** Returns the Class for the given class name using the given class loader. */
public static Class<?> classForName(String name, ClassLoader cl) {
try {
return Class.forName(name, false, cl);
} catch (ClassNotFoundException exp) {
throw translate(exp);
}
}
/**
* Determines if the class or interface represented by the first <code>Class</code> object is
* either the same as, or is a superclass or superinterface of, the class or interface
* represented by the second <code>Class</code> parameter. It returns <code>true</code> if so;
* otherwise it returns <code>false</code>.
*/
public static boolean isAssignableFrom(Class<?> a, Class<?> b) {
return a.isAssignableFrom(b);
}
/**
* Determines if the specified <code>Object</code> is assignment-compatible with the object
* represented by the specified <code>Class</code>. This method is the dynamic equivalent of the
* Java language <code>instanceof</code> operator. The method returns <code>true</code> if the
* specified <code>Object</code> argument is non-null and can be cast to the reference type
* represented by this <code>Class</code> object without raising a <code>ClassCastException.
* </code> It returns <code>false</code> otherwise.
*
* @param clazz the class that is checked.
* @param obj the object to check.
* @return true if <code>obj</code> is an instance of the given class.
*/
public static boolean isInstance(Class<?> clazz, Object obj) {
return clazz.isInstance(obj);
}
/**
* Returns the <code>Class</code> representing the superclass of the entity (class, interface,
* primitive type or void) represented by the given <code>Class</code>. If the given <code>Class
* </code> represents either the <code>Object</code> class, an interface, a primitive type, or
* void, then null is returned. If the given object represents an array class then the <code>
* Class</code> object representing the <code>Object</code> class is returned.
*
* @param clazz the Class whose super class is returned.
* @return the superclass of the class represented by the given object.
*/
public static Class<?> getSuperclass(Class<?> clazz) {
return clazz.getSuperclass();
}
/**
* Determines if the specified <code>Class</code> object represents an interface type.
*
* @param clazz the Class object to check.
* @return <code>true</code> if the Class represents an interface; <code>false</code> otherwise.
*/
public static boolean isInterface(Class<?> clazz) {
return clazz.isInterface();
}
/**
* Determines if the given <code>Class</code> object represents an array class.
*
* @param clazz Class object to check.
* @return <code>true</code> if the given object represents an array class; <code>false</code>
* otherwise.
*/
public static boolean isArray(Class<?> clazz) {
return clazz.isArray();
}
/** Returns whether the given Class represent primitive type or not. */
public static boolean isPrimitive(Class<?> clazz) {
return clazz.isPrimitive();
}
/** returns component type of an array Class. */
public static Class<?> getComponentType(Class<?> clazz) {
return clazz.getComponentType();
}
// Accessing fields by reflection
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class
* or interface represented by the given <code>Class</code> object. The <code>name</code>
* parameter is a <code>String</code> that specifies the simple name of the desired field.
* Returns <code>null</code> on not finding field if throwException parameter is <code>false
* </code>. Else throws a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @param throwException whether to throw exception on failing to find field or not
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(Class clazz, String name, boolean throwException) {
return getField(clazz, name, throwException);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class
* or interface represented by the given <code>Class</code> object. The <code>name</code>
* parameter is a <code>String</code> that specifies the simple name of the desired field.
* Throws a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(Class clazz, String name) {
return field(clazz, name, true);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class
* or interface represented by the given <code>Class</code> object. The <code>name</code>
* parameter is a <code>String</code> that specifies the simple name of the desired field.
* Returns <code>null</code> on not finding field if throwException parameter is <code>false
* </code>. Else throws a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @param throwException whether to throw exception on failing to find field or not
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(String clazz, String name, boolean throwException) {
ClassLoader callerLoader = BTraceRuntime.getCallerClassloader(STACK_DEC);
return field(classForName(clazz, callerLoader), name, throwException);
}
/**
* Returns a <code>Field</code> object that reflects the specified declared field of the class
* or interface represented by the given <code>Class</code> object. The <code>name</code>
* parameter is a <code>String</code> that specifies the simple name of the desired field.
* Throws a <code>RuntimeException</code> when field is not found.
*
* @param clazz Class whose field is returned
* @param name the name of the field
* @return the <code>Field</code> object for the specified field in this class
*/
public static Field field(String clazz, String name) {
ClassLoader callerLoader = BTraceRuntime.getCallerClassloader(STACK_DEC);
return field(classForName(clazz, callerLoader), name);
}
// field value get methods
/**
* Gets the value of a static <code>byte</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>byte</code> field
*/
public static byte getByte(Field field) {
checkStatic(field);
try {
return field.getByte(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>byte</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>byte</code> value from
* @return the value of the <code>byte</code> field
*/
public static byte getByte(Field field, Object obj) {
try {
return field.getByte(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>byte</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>byte</code> value from
* @return the value of the <code>byte</code> field
* @since 1.3.5
*/
public static byte getByte(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getByte(f, instance);
}
/**
* Gets the value of a static <code>byte</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>byte</code> value from
* @return the value of the <code>byte</code> field
* @since 1.3.5
*/
public static byte getByteStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getByte(f, null);
}
/**
* Gets the value of a static <code>short</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>short</code> field
*/
public static short getShort(Field field) {
checkStatic(field);
try {
return field.getShort(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>short</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>short</code> value from
* @return the value of the <code>short</code> field
*/
public static short getShort(Field field, Object obj) {
try {
return field.getShort(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>short</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>short</code> value from
* @return the value of the <code>short</code> field
* @since 1.3.5
*/
public static short getShort(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getShort(f, instance);
}
/**
* Gets the value of a static <code>short</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>short</code> value from
* @return the value of the <code>short</code> field
* @since 1.3.5
*/
public static short getShortStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getShort(f, null);
}
/**
* Gets the value of a static <code>int</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>int</code> field
*/
public static int getInt(Field field) {
checkStatic(field);
try {
return field.getInt(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>int</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>int</code> value from
* @return the value of the <code>int</code> field
*/
public static int getInt(Field field, Object obj) {
try {
return field.getInt(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>int</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>int</code> value from
* @return the value of the <code>int</code> field
* @since 1.3.5
*/
public static int getInt(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getInt(f, instance);
}
/**
* Gets the value of a sttaic <code>int</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>int</code> value from
* @return the value of the <code>int</code> field
* @since 1.3.5
*/
public static int getIntStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getInt(f, null);
}
/**
* Gets the value of a static <code>long</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>long</code> field
*/
public static long getLong(Field field) {
checkStatic(field);
try {
return field.getLong(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>long</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>long</code> value from
* @return the value of the <code>long</code> field
*/
public static long getLong(Field field, Object obj) {
try {
return field.getLong(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>long</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>long</code> value from
* @return the value of the <code>long</code> field
* @since 1.3.5
*/
public static long getLong(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getLong(f, instance);
}
/**
* Gets the value of a static <code>long</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>long</code> value from
* @return the value of the <code>long</code> field
* @since 1.3.5
*/
public static long getLongStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getLong(f, null);
}
/**
* Gets the value of a static <code>float</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>float</code> field
*/
public static float getFloat(Field field) {
checkStatic(field);
try {
return field.getFloat(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>float</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>float</code> value from
* @return the value of the <code>float</code> field
*/
public static float getFloat(Field field, Object obj) {
try {
return field.getFloat(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>float</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>float</code> value from
* @return the value of the <code>float</code> field
* @since 1.3.5
*/
public static float getFloat(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getFloat(f, instance);
}
/**
* Gets the value of a static <code>float</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>float</code> value from
* @return the value of the <code>float</code> field
* @since 1.3.5
*/
public static float getFloatStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getFloat(f, null);
}
/**
* Gets the value of a static <code>double</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>double</code> field
*/
public static double getDouble(Field field) {
checkStatic(field);
try {
return field.getDouble(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>double</code> field.
*
* @param field Field object whose value is returned.
* @param instance the object to extract the <code>double</code> value from
* @return the value of the <code>double</code> field
*/
public static double getDouble(Field field, Object instance) {
try {
return field.getDouble(instance);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>double</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>double</code> value from
* @return the value of the <code>double</code> field
* @since 1.3.5
*/
public static double getDouble(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getDouble(f, instance);
}
/**
* Gets the value of a static <code>double</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>double</code> value from
* @return the value of the <code>double</code> field
* @since 1.3.5
*/
public static double getDouble(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getDouble(f, null);
}
/**
* Gets the value of a static <code>boolean</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>boolean</code> field
*/
public static boolean getBoolean(Field field) {
checkStatic(field);
try {
return field.getBoolean(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>boolean</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>boolean</code> value from
* @return the value of the <code>boolean</code> field
*/
public static boolean getBoolean(Field field, Object obj) {
try {
return field.getBoolean(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>boolean</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>boolean</code> value from
* @return the value of the <code>boolean</code> field
* @since 1.3.5
*/
public static boolean getBoolean(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getBoolean(f, instance);
}
/**
* Gets the value of a static <code>boolean</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>boolean</code> value from
* @return the value of the <code>boolean</code> field
* @since 1.3.5
*/
public static boolean getBooleanStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getBoolean(f, null);
}
/**
* Gets the value of a static <code>char</code> field.
*
* @param field Field object whose value is returned.
* @return the value of the <code>char</code> field
*/
public static char getChar(Field field) {
checkStatic(field);
try {
return field.getChar(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>char</code> field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the <code>char</code> value from
* @return the value of the <code>char</code> field
*/
public static char getChar(Field field, Object obj) {
try {
return field.getChar(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance <code>char</code> field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the <code>char</code> value from
* @return the value of the <code>char</code> field
* @since 1.3.5
*/
public static char getChar(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return getChar(f, instance);
}
/**
* Gets the value of a static <code>char</code> field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the <code>char</code> value from
* @return the value of the <code>char</code> field
* @since 1.3.5
*/
public static char getCharStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return getChar(f, null);
}
/**
* Gets the value of a static reference field.
*
* @param field Field object whose value is returned.
* @return the value of the reference field
*/
public static Object get(Field field) {
checkStatic(field);
try {
return field.get(null);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance reference field.
*
* @param field Field object whose value is returned.
* @param obj the object to extract the reference value from
* @return the value of the reference field
*/
public static Object get(Field field, Object obj) {
try {
return field.get(obj);
} catch (Exception exp) {
throw translate(exp);
}
}
/**
* Gets the value of an instance reference field.
*
* @param name name of the field whose value is returned.
* @param instance the object to extract the reference value from
* @return the value of the reference field
* @since 1.3.5
*/
public static Object get(String name, Object instance) {
Field f = getField(instance.getClass(), name, true);
return get(f, instance);
}
/**
* Gets the value of a static reference field.
*
* @param name name of the field whose value is returned.
* @param clazz the class to extract the reference value from
* @return the value of the reference field
* @since 1.3.5
*/
public static Object getStatic(String name, Class clazz) {
Field f = getField(clazz, name, true);
return get(f, null);
}
/**
* Print all instance fields of an object as name-value pairs. Includes the inherited fields as
* well.
*
* @param obj Object whose fields are printed.
*/
public static void printFields(Object obj) {
printFields(obj, false);
}
/**
* Print all instance fields of an object as name-value pairs. Includes the inherited fields as
* well. Optionally, prints name of the declaring class before each field - so that if same
* named field in super class chain may be disambiguated.
*
* @param obj Object whose fields are printed.
* @param classNamePrefix flag to tell whether to prefix field names names by class name or not.
*/
public static void printFields(Object obj, boolean classNamePrefix) {
StringBuilder buf = new StringBuilder();
buf.append('{');
addFieldValues(buf, obj, obj.getClass(), classNamePrefix);
buf.append('}');
println(buf.toString());
}
/**
* Print all static fields of the class as name-value pairs. Includes the inherited fields as
* well.
*
* @param clazz Class whose static fields are printed.
*/
public static void printStaticFields(Class clazz) {
printStaticFields(clazz, false);
}
/**
* Print all static fields of the class as name-value pairs. Includes the inherited fields as
* well. Optionally, prints name of the declaring class before each field - so that if same
* named field in super class chain may be disambigated.
*
* @param clazz Class whose static fields are printed.
* @param classNamePrefix flag to tell whether to prefix field names names by class name or not.
*/
public static void printStaticFields(Class clazz, boolean classNamePrefix) {
StringBuilder buf = new StringBuilder();
buf.append('{');
addStaticFieldValues(buf, clazz, classNamePrefix);
buf.append('}');
println(buf.toString());
}
}
/*
* Wraps the data export related BTrace utility methods
* @since 1.2
*/
public static class Export {
/**
* Serialize a given object into the given file. Under the current dir of traced app,
* ./btrace<pid>/btrace-class/ directory is created. Under that directory, a file of given
* fileName is created.
*
* @param obj object that has to be serialized.
* @param fileName name of the file to which the object is serialized.
*/
public static void serialize(Serializable obj, String fileName) {
BTraceRuntime.serialize(obj, fileName);
}
/**
* Creates an XML document to persist the tree of the all transitively reachable objects from
* given "root" object.
*/
public static String toXML(Object obj) {
return BTraceRuntime.toXML(obj);
}
/**
* Writes an XML document to persist the tree of the all the transitively reachable objects from
* the given "root" object. Under the current dir of traced app,
* ./btrace<pid>/btrace-class/ directory is created. Under that directory, a file of the
* given fileName is created.
*/
public static void writeXML(Object obj, String fileName) {
BTraceRuntime.writeXML(obj, fileName);
}
/**
* Writes a .dot document to persist the tree of the all the transitively reachable objects from
* the given "root" object. .dot documents can be viewed by Graphviz application
* (www.graphviz.org) Under the current dir of traced app, ./btrace<pid>/btrace-class/
* directory is created. Under that directory, a file of the given fileName is created.
*
* @since 1.1
*/
public static void writeDOT(Object obj, String fileName) {
BTraceRuntime.writeDOT(obj, fileName);
}
}
/*
* Wraps the OS related BTrace utility methods
* @since 1.2
*/
public static class Sys {
/**
* Returns n'th command line argument. <code>null</code> if not available.
*
* @param n command line argument index
* @return n'th command line argument
*/
public static String $(int n) {
return BTraceRuntime.$(n);
}
/**
* Returns a command line argument value for the given key. {@code null} if not available.<br>
* In order to provide a key-value pair on the command line it must have the following syntax -
* <key>=<value>
*
* @param key the argument key
* @return the corresponding value or {@code null}
*/
public static String $(String key) {
return BTraceRuntime.$(key);
}
/** Returns the process id of the currently BTrace'd process. */
public static int getpid() {
int pid = -1;
try {
pid = Integer.parseInt($(0));
} catch (Exception ignored) {
}
return pid;
}
/** Returns the number of command line arguments. */
public static int $length() {
return BTraceRuntime.$length();
}
/**
* Exits the BTrace session -- note that the particular client's tracing session exits and not
* the observed/traced program! After exit call, the trace action method terminates immediately
* and no other probe action method (of that client) will be called after that.
*
* @param exitCode exit value sent to the client
*/
public static void exit(int exitCode) {
BTraceRuntime.exit(exitCode);
}
/**
* This is same as exit(int) except that the exit code is zero.
*
* @see #exit(int)
*/
public static void exit() {
exit(0);
}
/*
* Wraps the environment related BTrace utility methods
* @since 1.2
*/
public static class Env {
/**
* Gets the system property indicated by the specified key.
*
* @param key the name of the system property.
* @return the string value of the system property, or <code>null</code> if there is no
* property with that key.
* @throws NullPointerException if <code>key</code> is <code>null</code>.
* @throws IllegalArgumentException if <code>key</code> is empty.
*/
public static String property(String key) {
return BTraceRuntime.property(key);
}
/**
* Returns all Sys properties.
*
* @return the system properties
*/
public static Properties properties() {
return BTraceRuntime.properties();
}
/** Prints all Sys properties. */
public static void printProperties() {
BTraceRuntime.printMap(properties());
}
/**
* Gets the value of the specified environment variable. An environment variable is a
* system-dependent external named value.
*
* @param name the name of the environment variable
* @return the string value of the variable, or <code>null</code> if the variable is not
* defined in the system environment
* @throws NullPointerException if <code>name</code> is <code>null</code>
*/
public static String getenv(String name) {
return BTraceRuntime.getenv(name);
}
/**
* Returns an unmodifiable string map view of the current system environment. The environment
* is a system-dependent mapping from names to values which is passed from parent to child
* processes.
*
* @return the environment as a map of variable names to values
*/
public static Map<String, String> getenv() {
return BTraceRuntime.getenv();
}
/** Prints all system environment values. */
public static void printEnv() {
BTraceRuntime.printMap(getenv());
}
/**
* Returns the number of processors available to the Java virtual machine.
*
* <p>This value may change during a particular invocation of the virtual machine.
* Applications that are sensitive to the number of available processors should therefore
* occasionally poll this property and adjust their resource usage appropriately.
*
* @return the maximum number of processors available to the virtual machine; never smaller
* than one
*/
public static long availableProcessors() {
return Runtime.getRuntime().availableProcessors();
}
}
/*
* Wraps the memory related BTrace utility methods
* @since 1.2
*/
public static class Memory {
// memory usage
/**
* Returns the amount of free memory in the Java Virtual Machine. Calling the <code>gc</code>
* method may result in increasing the value returned by <code>freeMemory.</code>
*
* @return an approximation to the total amount of memory currently available for future
* allocated objects, measured in bytes.
*/
public static long freeMemory() {
return Runtime.getRuntime().freeMemory();
}
/**
* Returns the total amount of memory in the Java virtual machine. The value returned by this
* method may vary over time, depending on the host environment.
*
* <p>Note that the amount of memory required to hold an object of any given type may be
* implementation-dependent.
*
* @return the total amount of memory currently available for current and future objects,
* measured in bytes.
*/
public static long totalMemory() {
return Runtime.getRuntime().totalMemory();
}
/**
* Returns the maximum amount of memory that the Java virtual machine will attempt to use. If
* there is no inherent limit then the value {@link java.lang.Long#MAX_VALUE} will be
* returned.
*
* @return the maximum amount of memory that the virtual machine will attempt to use, measured
* in bytes
*/
public static long maxMemory() {
return Runtime.getRuntime().maxMemory();
}
/** Returns heap memory usage */
public static MemoryUsage heapUsage() {
return BTraceRuntime.heapUsage();
}
/** Returns non-heap memory usage */
public static MemoryUsage nonHeapUsage() {
return BTraceRuntime.nonHeapUsage();
}
/**
* Returns the amount of memory in bytes that the Java virtual machine initially requests from
* the operating system for memory management.
*/
public static long init(MemoryUsage mu) {
return mu.getInit();
}
/**
* Returns the amount of memory in bytes that is committed for the Java virtual machine to
* use. This amount of memory is guaranteed for the Java virtual machine to use.
*/
public static long committed(MemoryUsage mu) {
return mu.getCommitted();
}
/**
* Returns the maximum amount of memory in bytes that can be used for memory management. This
* method returns -1 if the maximum memory size is undefined.
*/
public static long max(MemoryUsage mu) {
return mu.getMax();
}
/** Returns the amount of used memory in bytes. */
public static long used(MemoryUsage mu) {
return mu.getUsed();
}
/** Returns the approximate number of objects for which finalization is pending. */
public static long finalizationCount() {
return BTraceRuntime.finalizationCount();
}
/**
* Dump the snapshot of the Java heap to a file in hprof binary format. Only the live objects
* are dumped. Under the current dir of traced app, ./btrace<pid>/btrace-class/
* directory is created. Under that directory, a file of given fileName is created.
*
* @param fileName name of the file to which heap is dumped
*/
public static void dumpHeap(String fileName) {
dumpHeap(fileName, true);
}
/**
* Dump the snapshot of the Java heap to a file in hprof binary format. Under the current dir
* of traced app, ./btrace<pid>/btrace-class/ directory is created. Under that
* directory, a file of given fileName is created.
*
* @param fileName name of the file to which heap is dumped
* @param live flag that tells whether only live objects are to be dumped or all objects are
* to be dumped.
*/
public static void dumpHeap(String fileName, boolean live) {
BTraceRuntime.dumpHeap(fileName, live);
}
/**
* Runs the garbage collector.
*
* <p>Calling the <code>gc</code> method suggests that the Java Virtual Machine expend effort
* toward recycling unused objects in order to make the memory they currently occupy available
* for quick reuse. When control returns from the method call, the Java Virtual Machine has
* made a best effort to reclaim space from all discarded objects. This method calls Sys.gc()
* to perform GC.
*/
public static void gc() {
java.lang.System.gc();
}
/**
* Returns the total amount of time spent in GarbageCollection up to this point since the
* application was started.
*
* @return Returns the amount of overall time spent in GC
*/
public static long getTotalGcTime() {
return BTraceRuntime.getTotalGcTime();
}
/**
* Returns an overview of available memory pools <br>
* It is possible to provide a text format the overview will use
*
* @param poolFormat The text format string to format the overview. <br>
* Exactly 5 arguments are passed to the format function. <br>
* The format defaults to ";%1$s;%2$d;%3$d;%4$d;%5$d;Memory]"
* @return Returns the formatted value of memory pools overview
* @since 1.2
*/
public static String getMemoryPoolUsage(String poolFormat) {
return BTraceRuntime.getMemoryPoolUsage(poolFormat);
}
/**
* Runs the finalization methods of any objects pending finalization.
*
* <p>Calling this method suggests that the Java Virtual Machine expend effort toward running
* the <code>finalize</code> methods of objects that have been found to be discarded but whose
* <code>finalize</code> methods have not yet been run. When control returns from the method
* call, the Java Virtual Machine has made a best effort to complete all outstanding
* finalizations. This method calls Sys.runFinalization() to run finalization.
*/
public static void runFinalization() {
java.lang.System.runFinalization();
}
}
/*
* Wraps the VM related BTrace utility methods
* @since 1.2
*/
public static class VM {
/**
* Returns the input arguments passed to the Java virtual machine which does not include the
* arguments to the <tt>main</tt> method. This method returns an empty list if there is no
* input argument to the Java virtual machine.
*
* <p>Some Java virtual machine implementations may take input arguments from multiple
* different sources: for examples, arguments passed from the application that launches the
* Java virtual machine such as the 'java' command, environment variables, configuration
* files, etc.
*
* <p>Typically, not all command-line options to the 'java' command are passed to the Java
* virtual machine. Thus, the returned input arguments may not include all command-line
* options.
*
* @return a list of <tt>String</tt> objects; each element is an argument passed to the Java
* virtual machine.
*/
public static List<String> vmArguments() {
return BTraceRuntime.getInputArguments();
}
/**
* Prints VM input arguments list.
*
* @see #vmArguments
*/
public static void printVmArguments() {
println(vmArguments());
}
/**
* Returns the Java virtual machine implementation version. This method is equivalent to
* <b>Sys.getProperty("java.vm.version")}</b>.
*
* @return the Java virtual machine implementation version.
*/
public static String vmVersion() {
return BTraceRuntime.getVmVersion();
}
/**
* Tests if the Java virtual machine supports the boot class path mechanism used by the
* bootstrap class loader to search for class files.
*
* @return <tt>true</tt> if the Java virtual machine supports the class path mechanism;
* <tt>false</tt> otherwise.
*/
public static boolean isBootClassPathSupported() {
return BTraceRuntime.isBootClassPathSupported();
}
/**
* Returns the boot class path that is used by the bootstrap class loader to search for class
* files.
*
* <p>Multiple paths in the boot class path are separated by the path separator character of
* the platform on which the Java virtual machine is running.
*
* <p>A Java virtual machine implementation may not support the boot class path mechanism for
* the bootstrap class loader to search for class files. The {@link #isBootClassPathSupported}
* method can be used to determine if the Java virtual machine supports this method.
*
* @return the boot class path.
* @throws java.lang.UnsupportedOperationException if the Java virtual machine does not
* support this operation.
*/
public static String bootClassPath() {
return BTraceRuntime.getBootClassPath();
}
/**
* Returns the Java class path that is used by the system class loader to search for class
* files. This method is equivalent to <b>Sys.getProperty("java.class.path")</b>.
*
* @return the Java class path.
*/
public static String classPath() {
return Sys.Env.property("java.class.path");
}
/**
* Returns the Java library path. This method is equivalent to
* <b>Sys.getProperty("java.library.path")</b>.
*
* <p>Multiple paths in the Java library path are separated by the path separator character of
* the platform of the Java virtual machine being monitored.
*
* @return the Java library path.
*/
public static String libraryPath() {
return Sys.Env.property("java.library.path");
}
/**
* Returns the current number of live threads including both daemon and non-daemon threads.
*
* @return the current number of live threads.
*/
public static long threadCount() {
return BTraceRuntime.getThreadCount();
}
/**
* Returns the peak live thread count since the Java virtual machine started or peak was
* reset.
*
* @return the peak live thread count.
*/
public static long peakThreadCount() {
return BTraceRuntime.getPeakThreadCount();
}
/**
* Returns the total number of threads created and also started since the Java virtual machine
* started.
*
* @return the total number of threads started.
*/
public static long totalStartedThreadCount() {
return BTraceRuntime.getTotalStartedThreadCount();
}
/**
* Returns the current number of live daemon threads.
*
* @return the current number of live daemon threads.
*/
public static long daemonThreadCount() {
return BTraceRuntime.getDaemonThreadCount();
}
/**
* Returns the system load average for the last minute
*
* @return the system load average for the last minute
*/
public static double systemLoadAverage() {
return BTraceRuntime.getSystemLoadAverage();
}
/**
* Returns the CPU time used by the process on which the Java virtual machine is running in
* nanoseconds.
*
* @return the CPU time used by the process on which the JVM is running in nanoseconds.
* Returns -1 if this operation is not supported on this platform
*/
public static long processCPUTime() {
return BTraceRuntime.getProcessCPUTime();
}
/**
* Returns the start time of the Java virtual machine in milliseconds. This method returns the
* approximate time when the Java virtual machine started.
*
* @return start time of the Java virtual machine in milliseconds.
*/
public static long vmStartTime() {
return BTraceRuntime.vmStartTime();
}
/**
* Returns the uptime of the Java virtual machine in milliseconds.
*
* @return uptime of the Java virtual machine in milliseconds.
*/
public static long vmUptime() {
return BTraceRuntime.vmUptime();
}
/**
* Returns the total CPU time for the current thread in nanoseconds. The returned value is of
* nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation
* distinguishes between user mode time and system mode time, the returned CPU time is the
* amount of time that the current thread has executed in user mode or system mode.
*/
public static long currentThreadCpuTime() {
return BTraceRuntime.getCurrentThreadCpuTime();
}
/**
* Returns the CPU time that the current thread has executed in user mode in nanoseconds. The
* returned value is of nanoseconds precision but not necessarily nanoseconds accuracy.
*/
public static long currentThreadUserTime() {
return BTraceRuntime.getCurrentThreadUserTime();
}
}
}
/*
* Wraps the jvmstat counters related BTrace utility methods
* @since 1.2
*/
public static class Counters {
/** accessing jvmstat (perf) int counter */
public static long perfInt(String name) {
return BTraceRuntime.perfInt(name);
}
/** accessing jvmstat (perf) long counter */
public static long perfLong(String name) {
return BTraceRuntime.perfLong(name);
}
/** accessing jvmstat (perf) String counter */
public static String perfString(String name) {
return BTraceRuntime.perfString(name);
}
}
/*
* Wraps the dtrace related BTrace utility methods
* @since 1.2
*/
public static class D {
/**
* BTrace to DTrace communication chennal. Raise DTrace USDT probe from BTrace.
*
* @see #dtraceProbe(String, String, int, int)
*/
public static int probe(String str1, String str2) {
return probe(str1, str2, -1, -1);
}
/**
* BTrace to DTrace communication chennal. Raise DTrace USDT probe from BTrace.
*
* @see #dtraceProbe(String, String, int, int)
*/
public static int probe(String str1, String str2, int i1) {
return probe(str1, str2, i1, -1);
}
/**
* BTrace to DTrace communication channel. Raise DTrace USDT probe from BTrace.
*
* @param str1 first String param to DTrace probe
* @param str2 second String param to DTrace probe
* @param i1 first int param to DTrace probe
* @param i2 second int param to DTrace probe
*/
public static int probe(String str1, String str2, int i1, int i2) {
return BTraceRuntime.dtraceProbe(str1, str2, i1, i2);
}
}
/**
* Support for JFR integration.
*
* @since 2.1.0
*/
public static final class Jfr {
/**
* Create a new event instance using the factory field annotated by {@linkplain
* org.openjdk.btrace.core.annotations.Event}
*
* @param eventFactory the event factory
* @return new event instance
*/
public static JfrEvent prepareEvent(JfrEvent.Factory eventFactory) {
return eventFactory.newEvent();
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, byte fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, char fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, short fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, int fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, long fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, float fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, double fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, boolean fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Set an event field value
*
* @param event event instance
* @param fieldName field name
* @param fieldValue field value
*/
public static void setEventField(JfrEvent event, String fieldName, String fieldValue) {
event.withValue(fieldName, fieldValue);
}
/**
* Check whether the event should be committed.
*
* @see Event#shouldCommit()
* @param event event to check
* @return {@literal true} if the event should be committed
*/
public static boolean shouldCommit(JfrEvent event) {
return event.shouldCommit();
}
/**
* Commit the event
*
* @see Event#commit()
* @param event the event to commit
*/
public static void commit(JfrEvent event) {
event.commit();
}
public static void begin(JfrEvent event) {
event.begin();
}
public static void end(JfrEvent event) {
event.end();
}
}
}
| btraceio/btrace | btrace-core/src/main/java/org/openjdk/btrace/core/BTraceUtils.java |
180,213 | /*
* 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.hadoop.hive.ql.parse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.fs.ContentSummary;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Context;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.exec.ConditionalTask;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.UnionOperator;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.exec.mr.ExecDriver;
import org.apache.hadoop.hive.ql.exec.mr.MapRedTask;
import org.apache.hadoop.hive.ql.hooks.ReadEntity;
import org.apache.hadoop.hive.ql.hooks.WriteEntity;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.SemanticDispatcher;
import org.apache.hadoop.hive.ql.lib.SemanticGraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.SemanticNodeProcessor;
import org.apache.hadoop.hive.ql.lib.SemanticRule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.optimizer.GenMRFileSink1;
import org.apache.hadoop.hive.ql.optimizer.GenMROperator;
import org.apache.hadoop.hive.ql.optimizer.GenMRProcContext;
import org.apache.hadoop.hive.ql.optimizer.GenMRProcContext.GenMapRedCtx;
import org.apache.hadoop.hive.ql.optimizer.GenMRRedSink1;
import org.apache.hadoop.hive.ql.optimizer.GenMRRedSink2;
import org.apache.hadoop.hive.ql.optimizer.GenMRRedSink3;
import org.apache.hadoop.hive.ql.optimizer.GenMRTableScan1;
import org.apache.hadoop.hive.ql.optimizer.GenMRUnion1;
import org.apache.hadoop.hive.ql.optimizer.MapJoinFactory;
import org.apache.hadoop.hive.ql.optimizer.physical.PhysicalContext;
import org.apache.hadoop.hive.ql.optimizer.physical.PhysicalOptimizer;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.MapredWork;
import org.apache.hadoop.hive.ql.plan.MoveWork;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.session.SessionState.LogHelper;
import org.apache.hadoop.hive.shims.ShimLoader;
public class MapReduceCompiler extends TaskCompiler {
protected final Logger LOG = LoggerFactory.getLogger(MapReduceCompiler.class);
public MapReduceCompiler() {
}
@Override
public void init(QueryState queryState, LogHelper console, Hive db) {
super.init(queryState, console, db);
//It is required the use of recursive input dirs when hive.optimize.union.remove = true
if(conf.getBoolVar(HiveConf.ConfVars.HIVE_OPTIMIZE_UNION_REMOVE)) {
conf.setBoolean("mapred.input.dir.recursive", true);
}
}
// loop over all the tasks recursively
@Override
protected void setInputFormat(Task<?> task) {
if (task instanceof ExecDriver) {
MapWork work = ((MapredWork) task.getWork()).getMapWork();
Map<String, Operator<? extends OperatorDesc>> opMap = work.getAliasToWork();
if (!opMap.isEmpty()) {
for (Operator<? extends OperatorDesc> op : opMap.values()) {
setInputFormat(work, op);
}
}
} else if (task instanceof ConditionalTask) {
List<Task<?>> listTasks
= ((ConditionalTask) task).getListTasks();
for (Task<?> tsk : listTasks) {
setInputFormat(tsk);
}
}
if (task.getChildTasks() != null) {
for (Task<?> childTask : task.getChildTasks()) {
setInputFormat(childTask);
}
}
}
@Override
protected void optimizeOperatorPlan(ParseContext pCtx) throws SemanticException {
this.runDynPartitionSortOptimizations(pCtx, conf);
}
private void setInputFormat(MapWork work, Operator<? extends OperatorDesc> op) {
if (op.isUseBucketizedHiveInputFormat()) {
work.setUseBucketizedHiveInputFormat(true);
return;
}
if (op.getChildOperators() != null) {
for (Operator<? extends OperatorDesc> childOp : op.getChildOperators()) {
setInputFormat(work, childOp);
}
}
}
// loop over all the tasks recursively
private void breakTaskTree(Task<?> task) {
if (task instanceof ExecDriver) {
Map<String, Operator<? extends OperatorDesc>> opMap =
((MapredWork) task.getWork()).getMapWork().getAliasToWork();
if (!opMap.isEmpty()) {
for (Operator<? extends OperatorDesc> op : opMap.values()) {
breakOperatorTree(op);
}
}
} else if (task instanceof ConditionalTask) {
List<Task<?>> listTasks = ((ConditionalTask) task)
.getListTasks();
for (Task<?> tsk : listTasks) {
breakTaskTree(tsk);
}
}
if (task.getChildTasks() == null) {
return;
}
for (Task<?> childTask : task.getChildTasks()) {
breakTaskTree(childTask);
}
}
// loop over all the operators recursively
private void breakOperatorTree(Operator<? extends OperatorDesc> topOp) {
if (topOp instanceof ReduceSinkOperator) {
topOp.setChildOperators(null);
}
for (Operator<? extends OperatorDesc> op : topOp.getChildOperators()) {
breakOperatorTree(op);
}
}
/**
* Make a best guess at trying to find the number of reducers
*/
private static int getNumberOfReducers(MapredWork mrwork, HiveConf conf) {
if (mrwork.getReduceWork() == null) {
return 0;
}
if (mrwork.getReduceWork().getNumReduceTasks() >= 0) {
return mrwork.getReduceWork().getNumReduceTasks();
}
return conf.getIntVar(HiveConf.ConfVars.HADOOP_NUM_REDUCERS);
}
@Override
protected void decideExecMode(List<Task<?>> rootTasks, Context ctx,
GlobalLimitCtx globalLimitCtx)
throws SemanticException {
// bypass for explain queries for now
if (ctx.isExplainSkipExecution()) {
return;
}
// user has told us to run in local mode or doesn't want auto-local mode
if (ctx.isLocalOnlyExecutionMode() ||
!conf.getBoolVar(HiveConf.ConfVars.LOCAL_MODE_AUTO)) {
return;
}
final Context lCtx = ctx;
PathFilter p = new PathFilter() {
@Override
public boolean accept(Path file) {
return !lCtx.isMRTmpFileURI(file.toUri().getPath());
}
};
List<ExecDriver> mrtasks = Utilities.getMRTasks(rootTasks);
// map-reduce jobs will be run locally based on data size
// first find out if any of the jobs needs to run non-locally
boolean hasNonLocalJob = false;
for (ExecDriver mrtask : mrtasks) {
try {
ContentSummary inputSummary = Utilities.getInputSummary
(ctx, mrtask.getWork().getMapWork(), p);
int numReducers = getNumberOfReducers(mrtask.getWork(), conf);
long estimatedInput;
if (globalLimitCtx != null && globalLimitCtx.isEnable()) {
// If the global limit optimization is triggered, we will
// estimate input data actually needed based on limit rows.
// estimated Input = (num_limit * max_size_per_row) * (estimated_map + 2)
//
long sizePerRow = HiveConf.getLongVar(conf,
HiveConf.ConfVars.HIVE_LIMIT_MAX_ROW_SIZE);
estimatedInput = (globalLimitCtx.getGlobalOffset() +
globalLimitCtx.getGlobalLimit()) * sizePerRow;
long minSplitSize = HiveConf.getLongVar(conf,
HiveConf.ConfVars.MAPRED_MIN_SPLIT_SIZE);
long estimatedNumMap = inputSummary.getLength() / minSplitSize + 1;
estimatedInput = estimatedInput * (estimatedNumMap + 1);
} else {
estimatedInput = inputSummary.getLength();
}
if (LOG.isDebugEnabled()) {
LOG.debug("Task: " + mrtask.getId() + ", Summary: " +
inputSummary.getLength() + "," + inputSummary.getFileCount() + ","
+ numReducers + ", estimated Input: " + estimatedInput);
}
if (MapRedTask.isEligibleForLocalMode(conf, numReducers,
estimatedInput, inputSummary.getFileCount()) != null) {
hasNonLocalJob = true;
break;
} else {
mrtask.setLocalMode(true);
}
} catch (IOException e) {
throw new SemanticException(e);
}
}
if (!hasNonLocalJob) {
// Entire query can be run locally.
// Save the current tracker value and restore it when done.
ctx.setOriginalTracker(ShimLoader.getHadoopShims().getJobLauncherRpcAddress(conf));
ShimLoader.getHadoopShims().setJobLauncherRpcAddress(conf, "local");
console.printInfo("Automatically selecting local only mode for query");
}
}
@Override
protected void optimizeTaskPlan(List<Task<?>> rootTasks,
ParseContext pCtx, Context ctx) throws SemanticException {
// reduce sink does not have any kids - since the plan by now has been
// broken up into multiple
// tasks, iterate over all tasks.
// For each task, go over all operators recursively
for (Task<?> rootTask : rootTasks) {
breakTaskTree(rootTask);
}
PhysicalContext physicalContext = new PhysicalContext(conf,
getParseContext(pCtx, rootTasks), ctx, rootTasks, pCtx.getFetchTask());
PhysicalOptimizer physicalOptimizer = new PhysicalOptimizer(
physicalContext, conf);
physicalOptimizer.optimize();
}
@Override
protected void generateTaskTree(List<Task<?>> rootTasks, ParseContext pCtx,
List<Task<MoveWork>> mvTask, Set<ReadEntity> inputs, Set<WriteEntity> outputs) throws SemanticException {
// generate map reduce plans
ParseContext tempParseContext = getParseContext(pCtx, rootTasks);
GenMRProcContext procCtx = new GenMRProcContext(
conf,
// Must be deterministic order map for consistent q-test output across Java versions
new LinkedHashMap<Operator<? extends OperatorDesc>, Task<?>>(),
tempParseContext, mvTask, rootTasks,
new LinkedHashMap<Operator<? extends OperatorDesc>, GenMapRedCtx>(),
inputs, outputs);
// create a walker which walks the tree in a DFS manner while maintaining
// the operator stack.
// The dispatcher generates the plan from the operator tree
Map<SemanticRule, SemanticNodeProcessor> opRules = new LinkedHashMap<SemanticRule, SemanticNodeProcessor>();
opRules.put(new RuleRegExp(new String("R1"),
TableScanOperator.getOperatorName() + "%"),
new GenMRTableScan1());
opRules.put(new RuleRegExp(new String("R2"),
TableScanOperator.getOperatorName() + "%.*" + ReduceSinkOperator.getOperatorName() + "%"),
new GenMRRedSink1());
opRules.put(new RuleRegExp(new String("R3"),
ReduceSinkOperator.getOperatorName() + "%.*" + ReduceSinkOperator.getOperatorName() + "%"),
new GenMRRedSink2());
opRules.put(new RuleRegExp(new String("R4"),
FileSinkOperator.getOperatorName() + "%"),
new GenMRFileSink1());
opRules.put(new RuleRegExp(new String("R5"),
UnionOperator.getOperatorName() + "%"),
new GenMRUnion1());
opRules.put(new RuleRegExp(new String("R6"),
UnionOperator.getOperatorName() + "%.*" + ReduceSinkOperator.getOperatorName() + "%"),
new GenMRRedSink3());
opRules.put(new RuleRegExp(new String("R7"),
MapJoinOperator.getOperatorName() + "%"),
MapJoinFactory.getTableScanMapJoin());
// The dispatcher fires the processor corresponding to the closest matching
// rule and passes the context along
SemanticDispatcher disp = new DefaultRuleDispatcher(new GenMROperator(), opRules,
procCtx);
SemanticGraphWalker ogw = new GenMapRedWalker(disp);
ArrayList<Node> topNodes = new ArrayList<Node>();
topNodes.addAll(pCtx.getTopOps().values());
ogw.startWalking(topNodes, null);
}
}
| apache/hive | ql/src/java/org/apache/hadoop/hive/ql/parse/MapReduceCompiler.java |
180,215 | /*
* opsu! - an open-source osu! client
* Copyright (C) 2014-2017 Jeffrey Han
*
* opsu! 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.
*
* opsu! 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 opsu!. If not, see <http://www.gnu.org/licenses/>.
*/
package itdelatrisu.opsu.states;
import itdelatrisu.opsu.ErrorHandler;
import itdelatrisu.opsu.GameData;
import itdelatrisu.opsu.GameImage;
import itdelatrisu.opsu.GameMod;
import itdelatrisu.opsu.Opsu;
import itdelatrisu.opsu.ScoreData;
import itdelatrisu.opsu.Utils;
import itdelatrisu.opsu.audio.HitSound;
import itdelatrisu.opsu.audio.MusicController;
import itdelatrisu.opsu.audio.SoundController;
import itdelatrisu.opsu.audio.SoundEffect;
import itdelatrisu.opsu.beatmap.Beatmap;
import itdelatrisu.opsu.beatmap.BeatmapHPDropRateCalculator;
import itdelatrisu.opsu.beatmap.BeatmapParser;
import itdelatrisu.opsu.beatmap.HitObject;
import itdelatrisu.opsu.beatmap.TimingPoint;
import itdelatrisu.opsu.db.BeatmapDB;
import itdelatrisu.opsu.db.ScoreDB;
import itdelatrisu.opsu.objects.Circle;
import itdelatrisu.opsu.objects.DummyObject;
import itdelatrisu.opsu.objects.GameObject;
import itdelatrisu.opsu.objects.Slider;
import itdelatrisu.opsu.objects.Spinner;
import itdelatrisu.opsu.objects.curves.Curve;
import itdelatrisu.opsu.objects.curves.FakeCombinedCurve;
import itdelatrisu.opsu.objects.curves.Vec2f;
import itdelatrisu.opsu.options.Options;
import itdelatrisu.opsu.render.FrameBufferCache;
import itdelatrisu.opsu.replay.LifeFrame;
import itdelatrisu.opsu.replay.PlaybackSpeed;
import itdelatrisu.opsu.replay.Replay;
import itdelatrisu.opsu.replay.ReplayFrame;
import itdelatrisu.opsu.ui.Colors;
import itdelatrisu.opsu.ui.Fonts;
import itdelatrisu.opsu.ui.InputOverlayKey;
import itdelatrisu.opsu.ui.MenuButton;
import itdelatrisu.opsu.ui.StarStream;
import itdelatrisu.opsu.ui.UI;
import itdelatrisu.opsu.ui.animations.AnimatedValue;
import itdelatrisu.opsu.ui.animations.AnimationEquation;
import itdelatrisu.opsu.user.User;
import itdelatrisu.opsu.user.UserList;
import itdelatrisu.opsu.video.FFmpeg;
import itdelatrisu.opsu.video.Video;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.newdawn.slick.Animation;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.DelayedFadeOutTransition;
import org.newdawn.slick.state.transition.EasedFadeOutTransition;
import org.newdawn.slick.state.transition.EmptyTransition;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.util.Log;
/**
* "Game" state.
*/
public class Game extends BasicGameState {
/** Game play states. */
public enum PlayState {
/** Normal play. */
NORMAL,
/** First time loading the song. */
FIRST_LOAD,
/** Manual retry. */
RETRY,
/** Replay. */
REPLAY,
/** Health is zero: no-continue/force restart. */
LOSE
}
/** Music fade-out time, in milliseconds. */
private static final int MUSIC_FADEOUT_TIME = 2000;
/** Screen fade-out time, in milliseconds, when health hits zero. */
private static final int LOSE_FADEOUT_TIME = 500;
/** Game element fade-out time, in milliseconds, when the game ends. */
private static final int FINISHED_FADEOUT_TIME = 400;
/** Maximum rotation, in degrees, over fade out upon death. */
private static final float MAX_ROTATION = 90f;
/** The duration of the score changing animation. */
private static final float SCOREBOARD_ANIMATION_TIME = 500f;
/** The time the scoreboard takes to fade in. */
private static final float SCOREBOARD_FADE_IN_TIME = 300f;
/** Minimum time before start of song, in milliseconds, to process skip-related actions. */
private static final int SKIP_OFFSET = 2000;
/** Tolerance in case if hit object is not snapped to the grid. */
private static final float STACK_LENIENCE = 3f;
/** Stack position offset modifier. */
private static final float STACK_OFFSET_MODIFIER = 0.05f;
/** The associated beatmap. */
private Beatmap beatmap;
/** The associated GameData object. */
private GameData data;
/** Current hit object index (in both hit object arrays). */
private int objectIndex = 0;
/** The map's game objects, indexed by objectIndex. */
private GameObject[] gameObjects;
/** Any passed, unfinished hit object indices before objectIndex. */
private List<Integer> passedObjects;
/** Delay time, in milliseconds, before song starts. */
private int leadInTime;
/** Hit object approach time, in milliseconds. */
private int approachTime;
/** The amount of time for hit objects to fade in, in milliseconds. */
private int fadeInTime;
/** Decay time for hit objects in the "Hidden" mod, in milliseconds. */
private int hiddenDecayTime;
/** Time before the hit object time by which the objects have completely faded in the "Hidden" mod, in milliseconds. */
private int hiddenTimeDiff;
/** Time offsets for obtaining each hit result (indexed by HIT_* constants). */
private int[] hitResultOffset;
/** Current play state. */
private PlayState playState;
/** Current break index in breaks ArrayList. */
private int breakIndex;
/** Break start time (0 if not in break). */
private int breakTime = 0;
/** Whether the break sound has been played. */
private boolean breakSound;
/** Skip button (displayed at song start, when necessary). */
private MenuButton skipButton;
/** Current timing point index in timingPoints ArrayList. */
private int timingPointIndex;
/** Current beat lengths (base value and inherited value). */
private float beatLengthBase, beatLength;
/** Whether the countdown sound has been played. */
private boolean
countdownReadySound, countdown3Sound, countdown1Sound,
countdown2Sound, countdownGoSound;
/** Mouse coordinates before game paused. */
private Vec2f pausedMousePosition;
/** Track position when game paused. */
private int pauseTime = -1;
/** Value for handling hitCircleSelect pulse effect (expanding, alpha level). */
private float pausePulse;
/** Whether a checkpoint has been loaded during this game. */
private boolean checkpointLoaded = false;
/** Number of deaths, used if "Easy" mod is enabled. */
private byte deaths = 0;
/** Track position at death, used if "Easy" mod is enabled. */
private int deathTime = -1;
/** System time position at death. */
private long failTime;
/** Track time position at death. */
private int failTrackTime;
/** Rotations for game objects at death. */
private IdentityHashMap<GameObject, Float> rotations;
/** Number of retries. */
private int retries = 0;
/** Whether or not this game is a replay. */
private boolean isReplay = false;
/** The replay, if any. */
private Replay replay;
/** The current replay frame index. */
private int replayIndex = 0;
/** The replay cursor coordinates. */
private int replayX, replayY;
/** Whether a replay key is currently pressed. */
private boolean replayKeyPressed;
/** The replay skip time, or -1 if none. */
private int replaySkipTime = -1;
/** The last replay frame time. */
private int lastReplayTime = 0;
/** The keys from the previous replay frame. */
private int lastReplayKeys = 0;
/** The last game keys pressed. */
private int lastKeysPressed = ReplayFrame.KEY_NONE;
/** The previous game mod state (before the replay). */
private int previousMods = 0;
/** The list of current replay frames (for recording replays). */
private LinkedList<ReplayFrame> replayFrames;
/** The list of current life frames (for recording replays). */
private LinkedList<LifeFrame> lifeFrames;
/** The offscreen image rendered to. */
private Image offscreen;
/** The offscreen graphics. */
private Graphics gOffscreen;
/** The current flashlight area radius. */
private int flashlightRadius;
/** The cursor coordinates using the "auto" or "relax" mods. */
private Vec2f autoMousePosition;
/** Whether or not the cursor should be pressed using the "auto" mod. */
private boolean autoMousePressed;
/** Playback speed (used in replays and "auto" mod). */
private PlaybackSpeed playbackSpeed;
/** Whether the game is currently seeking to a replay position. */
private boolean isSeeking;
/** Music position bar coordinates and dimensions (for replay seeking). */
private float musicBarX, musicBarY, musicBarWidth, musicBarHeight;
/** The previous scores. */
private ScoreData[] previousScores;
/** The current rank in the scores. */
private int currentRank;
/** The time the rank was last updated. */
private int lastRankUpdateTime;
/** Whether the scoreboard is visible. */
private boolean scoreboardVisible;
/** The current alpha of the scoreboard. */
private float currentScoreboardAlpha;
/** The star stream shown when passing another score. */
private StarStream scoreboardStarStream;
/** Whether the game is finished (last hit object passed). */
private boolean gameFinished = false;
/** Timer after game has finished, before changing states. */
private AnimatedValue gameFinishedTimer = new AnimatedValue(2500, 0, 1, AnimationEquation.LINEAR);
/** The HP drop rate. */
private float hpDropRate = 0.05f;
/** The last track position. */
private int lastTrackPosition = 0;
/** The beatmap video (if any). */
private Video video;
/** The video start time (if any), otherwise -1. */
private int videoStartTime;
/** The video seek time (if any). */
private int videoSeekTime;
/** The single merged slider (if enabled). */
private FakeCombinedCurve mergedSlider;
/** The objects holding data for the input overlay. */
private InputOverlayKey[] inputOverlayKeys;
/** Music position bar background colors. */
private static final Color
MUSICBAR_NORMAL = new Color(12, 9, 10, 0.25f),
MUSICBAR_HOVER = new Color(12, 9, 10, 0.35f),
MUSICBAR_FILL = new Color(255, 255, 255, 0.75f);
// game-related variables
private GameContainer container;
private StateBasedGame game;
private Input input;
private final int state;
public Game(int state) {
this.state = state;
inputOverlayKeys = new InputOverlayKey[] {
new InputOverlayKey("K1", ReplayFrame.KEY_K1, 0, new Color(248, 216, 0)),
new InputOverlayKey("K2", ReplayFrame.KEY_K2, 0, new Color(248, 216, 0)),
new InputOverlayKey("M1", ReplayFrame.KEY_M1, 4, new Color(248, 0, 158)),
new InputOverlayKey("M2", ReplayFrame.KEY_M2, 8, new Color(248, 0, 158)),
};
}
@Override
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
this.container = container;
this.game = game;
input = container.getInput();
int width = container.getWidth();
int height = container.getHeight();
// create offscreen graphics
offscreen = new Image(width, height);
gOffscreen = offscreen.getGraphics();
gOffscreen.setBackground(Color.black);
// initialize music position bar location
musicBarX = width * 0.01f;
musicBarY = height * 0.05f;
musicBarWidth = Math.max(width * 0.005f, 7);
musicBarHeight = height * 0.9f;
// initialize scoreboard star stream
scoreboardStarStream = new StarStream(0, height * 2f / 3f, width / 4, 0, 0);
scoreboardStarStream.setPositionSpread(height / 20f);
scoreboardStarStream.setDirectionSpread(10f);
scoreboardStarStream.setDurationSpread(700, 100);
// create the associated GameData object
data = new GameData(width, height);
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
int width = container.getWidth();
int height = container.getHeight();
int trackPosition = MusicController.getPosition(true);
if (pauseTime > -1) // returning from pause screen
trackPosition = pauseTime;
else if (deathTime > -1) // "Easy" mod: health bar increasing
trackPosition = deathTime;
int firstObjectTime = beatmap.objects[0].getTime();
int timeDiff = firstObjectTime - trackPosition;
g.setBackground(Color.black);
// "flashlight" mod: initialize offscreen graphics
if (GameMod.FLASHLIGHT.isActive()) {
gOffscreen.clear();
Graphics.setCurrent(gOffscreen);
}
// background
float dimLevel = Options.getBackgroundDim();
if (video != null && video.isStarted() && !video.isFinished()) {
// video
video.render(0, 0, width, height, dimLevel);
} else {
// image
if (trackPosition < firstObjectTime) {
if (timeDiff < approachTime)
dimLevel += (1f - dimLevel) * ((float) timeDiff / approachTime);
else
dimLevel = 1f;
}
if (Options.isDefaultPlayfieldForced() || !beatmap.drawBackground(width, height, 0, 0, dimLevel, false)) {
Image bg = GameImage.MENU_BG.getImage();
bg.setAlpha(dimLevel);
bg.drawCentered(width / 2, height / 2);
bg.setAlpha(1f);
}
}
if (GameMod.FLASHLIGHT.isActive())
Graphics.setCurrent(g);
// "auto" and "autopilot" mods: move cursor automatically
// TODO: this should really be in update(), not render()
autoMousePosition.set(width / 2, height / 2);
autoMousePressed = false;
if (GameMod.AUTO.isActive() || GameMod.AUTOPILOT.isActive()) {
Vec2f autoPoint = null;
if (gameFinished) {
// game finished, do nothing
} else if (isLeadIn()) {
// lead-in
float progress = Math.max((float) (leadInTime - beatmap.audioLeadIn) / approachTime, 0f);
autoMousePosition.y = height / (2f - progress);
} else if (objectIndex == 0 && trackPosition < firstObjectTime) {
// before first object
timeDiff = firstObjectTime - trackPosition;
if (timeDiff < approachTime) {
Vec2f point = gameObjects[0].getPointAt(trackPosition);
autoPoint = getPointAt(autoMousePosition.x, autoMousePosition.y, point.x, point.y, 1f - ((float) timeDiff / approachTime));
}
} else if (objectIndex < beatmap.objects.length) {
// normal object
int objectTime = beatmap.objects[objectIndex].getTime();
if (trackPosition < objectTime) {
Vec2f startPoint = gameObjects[objectIndex - 1].getPointAt(trackPosition);
int startTime = gameObjects[objectIndex - 1].getEndTime();
if (beatmap.breaks != null && breakIndex < beatmap.breaks.size()) {
// starting a break: keep cursor at previous hit object position
if (breakTime > 0 || objectTime > beatmap.breaks.get(breakIndex))
autoPoint = startPoint;
// after a break ends: move startTime to break end time
else if (breakIndex > 1) {
int lastBreakEndTime = beatmap.breaks.get(breakIndex - 1);
if (objectTime > lastBreakEndTime && startTime < lastBreakEndTime)
startTime = lastBreakEndTime;
}
}
if (autoPoint == null) {
Vec2f endPoint = gameObjects[objectIndex].getPointAt(trackPosition);
int totalTime = objectTime - startTime;
if (totalTime == 0)
// this can happen on 2B maps, see issue 401
autoPoint = endPoint;
else
autoPoint = getPointAt(startPoint.x, startPoint.y, endPoint.x, endPoint.y, (float) (trackPosition - startTime) / totalTime);
// hit circles: show a mouse press
int offset300 = hitResultOffset[GameData.HIT_300];
if ((beatmap.objects[objectIndex].isCircle() && objectTime - trackPosition < offset300) ||
(beatmap.objects[objectIndex - 1].isCircle() && trackPosition - beatmap.objects[objectIndex - 1].getTime() < offset300))
autoMousePressed = true;
}
} else {
autoPoint = gameObjects[objectIndex].getPointAt(trackPosition);
autoMousePressed = true;
}
} else {
// last object
autoPoint = gameObjects[objectIndex - 1].getPointAt(trackPosition);
}
// set mouse coordinates
if (autoPoint != null)
autoMousePosition.set(autoPoint.x, autoPoint.y);
}
// "flashlight" mod: restricted view of hit objects around cursor
if (GameMod.FLASHLIGHT.isActive()) {
// render hit objects offscreen
Graphics.setCurrent(gOffscreen);
int trackPos = (isLeadIn()) ? (leadInTime - Options.getMusicOffset() - beatmap.localMusicOffset) * -1 : trackPosition;
drawHitObjects(gOffscreen, trackPos);
// restore original graphics context
gOffscreen.flush();
Graphics.setCurrent(g);
// draw alpha map around cursor
g.setDrawMode(Graphics.MODE_ALPHA_MAP);
g.clearAlphaMap();
int mouseX, mouseY;
if (pauseTime > -1 && pausedMousePosition != null) {
mouseX = (int) pausedMousePosition.x;
mouseY = (int) pausedMousePosition.y;
} else if (GameMod.AUTO.isActive() || GameMod.AUTOPILOT.isActive()) {
mouseX = (int) autoMousePosition.x;
mouseY = (int) autoMousePosition.y;
} else if (isReplay) {
mouseX = replayX;
mouseY = replayY;
} else {
mouseX = input.getMouseX();
mouseY = input.getMouseY();
}
int alphaRadius = flashlightRadius * 256 / 215;
int alphaX = mouseX - alphaRadius / 2;
int alphaY = mouseY - alphaRadius / 2;
GameImage.ALPHA_MAP.getImage().draw(alphaX, alphaY, alphaRadius, alphaRadius);
// blend offscreen image
g.setDrawMode(Graphics.MODE_ALPHA_BLEND);
g.setClip(alphaX, alphaY, alphaRadius, alphaRadius);
g.drawImage(offscreen, 0, 0);
g.clearClip();
g.setDrawMode(Graphics.MODE_NORMAL);
}
// break periods
if (beatmap.breaks != null && breakIndex < beatmap.breaks.size() && breakTime > 0) {
int endTime = beatmap.breaks.get(breakIndex);
int breakLength = endTime - breakTime;
// letterbox effect (black bars on top/bottom)
if (beatmap.letterboxInBreaks && breakLength >= 4000) {
// let it fade in/out
float a = Colors.BLACK_ALPHA.a;
if (trackPosition - breakTime > breakLength / 2) {
Colors.BLACK_ALPHA.a = (Math.min(500f, breakTime + breakLength - trackPosition)) / 500f;
} else {
Colors.BLACK_ALPHA.a = Math.min(500, trackPosition - breakTime) / 500f;
}
g.setColor(Colors.BLACK_ALPHA);
g.fillRect(0, 0, width, height * 0.125f);
g.fillRect(0, height * 0.875f, width, height * 0.125f);
Colors.BLACK_ALPHA.a = a;
}
data.drawGameElements(g, true, objectIndex == 0, 1f);
if (breakLength >= 8000 &&
trackPosition - breakTime > 2000 &&
trackPosition - breakTime < 5000) {
// show break start
if (data.getHealthPercent() >= 50) {
GameImage.SECTION_PASS.getImage().drawCentered(width / 2f, height / 2f);
if (!breakSound) {
playSoundEffect(SoundEffect.SECTIONPASS);
breakSound = true;
}
} else {
GameImage.SECTION_FAIL.getImage().drawCentered(width / 2f, height / 2f);
if (!breakSound) {
playSoundEffect(SoundEffect.SECTIONFAIL);
breakSound = true;
}
}
} else if (breakLength >= 4000) {
// show break end (flash twice for 500ms)
int endTimeDiff = endTime - trackPosition;
if ((endTimeDiff > 1500 && endTimeDiff < 2000) ||
(endTimeDiff > 500 && endTimeDiff < 1000)) {
Image arrow = GameImage.WARNINGARROW.getImage();
Color color = (Options.getSkin().getVersion() == 1) ? Color.white : Color.red;
arrow.setRotation(0);
arrow.draw(width * 0.15f, height * 0.15f, color);
arrow.draw(width * 0.15f, height * 0.75f, color);
arrow.setRotation(180);
arrow.draw(width * 0.75f, height * 0.15f, color);
arrow.draw(width * 0.75f, height * 0.75f, color);
}
}
}
// non-break
else {
// game elements
float gameElementAlpha = 1f;
if (gameFinished) {
// game finished: fade everything out
float t = 1f - Math.min(gameFinishedTimer.getTime() / (float) FINISHED_FADEOUT_TIME, 1f);
gameElementAlpha = AnimationEquation.OUT_CUBIC.calc(t);
}
data.drawGameElements(g, false, objectIndex == 0, gameElementAlpha);
// skip beginning
if (objectIndex == 0 &&
trackPosition < beatmap.objects[0].getTime() - SKIP_OFFSET)
skipButton.draw();
// show retries
if (objectIndex == 0 && retries >= 2 && timeDiff >= -1000) {
int retryHeight = Math.max(
GameImage.SCOREBAR_BG.getImage().getHeight(),
GameImage.SCOREBAR_KI.getImage().getHeight()
);
float oldAlpha = Colors.WHITE_FADE.a;
if (timeDiff < -500)
Colors.WHITE_FADE.a = (1000 + timeDiff) / 500f;
Fonts.MEDIUM.drawString(
2 + (width / 100), retryHeight,
String.format("%d retries and counting...", retries),
Colors.WHITE_FADE
);
Colors.WHITE_FADE.a = oldAlpha;
}
if (isLeadIn()) // render approach circles during song lead-in
trackPosition = (leadInTime - Options.getMusicOffset() - beatmap.localMusicOffset) * -1;
// countdown
if (beatmap.countdown > 0) {
float speedModifier = GameMod.getSpeedMultiplier() * playbackSpeed.getModifier();
timeDiff = firstObjectTime - trackPosition;
if (timeDiff >= 500 * speedModifier && timeDiff < 3000 * speedModifier) {
if (timeDiff >= 1500 * speedModifier) {
GameImage.COUNTDOWN_READY.getImage().drawCentered(width / 2, height / 2);
if (!countdownReadySound) {
playSoundEffect(SoundEffect.READY);
countdownReadySound = true;
}
}
if (timeDiff < 2000 * speedModifier) {
GameImage.COUNTDOWN_3.getImage().draw(0, 0);
if (!countdown3Sound) {
playSoundEffect(SoundEffect.COUNT3);
countdown3Sound = true;
}
}
if (timeDiff < 1500 * speedModifier) {
GameImage.COUNTDOWN_2.getImage().draw(width - GameImage.COUNTDOWN_2.getImage().getWidth(), 0);
if (!countdown2Sound) {
playSoundEffect(SoundEffect.COUNT2);
countdown2Sound = true;
}
}
if (timeDiff < 1000 * speedModifier) {
GameImage.COUNTDOWN_1.getImage().drawCentered(width / 2, height / 2);
if (!countdown1Sound) {
playSoundEffect(SoundEffect.COUNT1);
countdown1Sound = true;
}
}
} else if (timeDiff >= -500 * speedModifier && timeDiff < 500 * speedModifier) {
Image go = GameImage.COUNTDOWN_GO.getImage();
go.setAlpha((timeDiff < 0) ? 1 - (timeDiff / speedModifier / -500f) : 1);
go.drawCentered(width / 2, height / 2);
if (!countdownGoSound) {
playSoundEffect(SoundEffect.GO);
countdownGoSound = true;
}
}
}
// draw hit objects
if (!GameMod.FLASHLIGHT.isActive())
drawHitObjects(g, trackPosition);
}
// in-game scoreboard
if (previousScores != null && trackPosition >= firstObjectTime && !GameMod.RELAX.isActive() && !GameMod.AUTOPILOT.isActive()) {
// NOTE: osu! uses the actual score, but we use sliding score instead
ScoreData currentScore = data.getCurrentScoreData(beatmap, true);
while (currentRank > 0 && previousScores[currentRank - 1].score < currentScore.score) {
currentRank--;
scoreboardStarStream.burst(20);
lastRankUpdateTime = trackPosition;
}
float animation = AnimationEquation.IN_OUT_QUAD.calc(
Utils.clamp((trackPosition - lastRankUpdateTime) / SCOREBOARD_ANIMATION_TIME, 0f, 1f)
);
int scoreboardPosition = 2 * container.getHeight() / 3;
// draw star stream behind the scores
scoreboardStarStream.draw();
if (currentRank < 4) {
// draw the (new) top 5 ranks
for (int i = 0; i < 4; i++) {
int index = i + (i >= currentRank ? 1 : 0);
if (i < previousScores.length) {
float position = index + (i == currentRank ? animation - 3f : -2f);
previousScores[i].drawSmall(g, scoreboardPosition, index + 1, position, data, currentScoreboardAlpha, false);
}
}
currentScore.drawSmall(g, scoreboardPosition, currentRank + 1, currentRank - 1f - animation, data, currentScoreboardAlpha, true);
} else {
// draw the top 2 and next 2 ranks
previousScores[0].drawSmall(g, scoreboardPosition, 1, -2f, data, currentScoreboardAlpha, false);
previousScores[1].drawSmall(g, scoreboardPosition, 2, -1f, data, currentScoreboardAlpha, false);
previousScores[currentRank - 2].drawSmall(
g, scoreboardPosition, currentRank - 1, animation - 1f, data, currentScoreboardAlpha * animation, false
);
previousScores[currentRank - 1].drawSmall(g, scoreboardPosition, currentRank, animation, data, currentScoreboardAlpha, false);
currentScore.drawSmall(g, scoreboardPosition, currentRank + 1, 2f, data, currentScoreboardAlpha, true);
if (animation < 1.0f && currentRank < previousScores.length) {
previousScores[currentRank].drawSmall(
g, scoreboardPosition, currentRank + 2, 1f + 5 * animation, data, currentScoreboardAlpha * (1f - animation), false
);
}
}
}
if (GameMod.AUTO.isActive())
GameImage.UNRANKED.getImage().drawCentered(width / 2, height * 0.077f);
// draw replay speed button
if (isReplay || GameMod.AUTO.isActive())
playbackSpeed.getButton().draw();
// draw music position bar (for replay seeking)
if (isReplay && Options.isReplaySeekingEnabled()) {
int mouseX = input.getMouseX(), mouseY = input.getMouseY();
g.setColor((musicPositionBarContains(mouseX, mouseY)) ? MUSICBAR_HOVER : MUSICBAR_NORMAL);
g.fillRoundRect(musicBarX, musicBarY, musicBarWidth, musicBarHeight, 4);
if (!isLeadIn()) {
g.setColor(MUSICBAR_FILL);
float musicBarPosition = Math.min((float) trackPosition / beatmap.endTime, 1f);
g.fillRoundRect(musicBarX, musicBarY, musicBarWidth, musicBarHeight * musicBarPosition, 4);
}
}
// key overlay
if (isReplay || Options.alwaysShowKeyOverlay()) {
final float BTNSIZE = container.getHeight() * 0.0615f;
int x = (int) (container.getWidth() - BTNSIZE / 2f);
int y = (int) (container.getHeight() / 2f - BTNSIZE - BTNSIZE / 2f);
Image bg = GameImage.INPUTOVERLAY_BACKGROUND.getImage();
bg = bg.getScaledCopy(BTNSIZE * 4.3f / bg.getWidth());
bg.rotate(90f);
bg.drawCentered(container.getWidth() - bg.getHeight() / 2, container.getHeight() / 2);
Image keyimg =
GameImage.INPUTOVERLAY_KEY.getImage().getScaledCopy((int) BTNSIZE, (int) BTNSIZE);
for (int i = 0; i < 4; i++) {
inputOverlayKeys[i].render(g, x, y, keyimg);
y += BTNSIZE;
}
}
// returning from pause screen
if (pauseTime > -1 && pausedMousePosition != null) {
// darken the screen
g.setColor(Colors.BLACK_ALPHA);
g.fillRect(0, 0, width, height);
// draw overlay text
String overlayText = "Click on the pulsing cursor to continue play!";
int textWidth = Fonts.LARGE.getWidth(overlayText), textHeight = Fonts.LARGE.getLineHeight();
int textX = (width - textWidth) / 2, textY = (height - textHeight) / 2;
int paddingX = 8, paddingY = 4;
g.setLineWidth(1f);
g.setColor(Color.black);
g.fillRect(textX - paddingX, textY - paddingY, textWidth + paddingX * 2, textHeight + paddingY * 2);
g.setColor(Colors.LIGHT_BLUE);
g.drawRect(textX - paddingX, textY - paddingY, textWidth + paddingX * 2, textHeight + paddingY * 2);
g.setColor(Color.white);
Fonts.LARGE.drawString(textX, textY, overlayText);
// draw glowing hit select circle and pulse effect
int circleDiameter = GameImage.HITCIRCLE.getImage().getWidth();
Image cursorCircle = GameImage.HITCIRCLE_SELECT.getImage().getScaledCopy(circleDiameter, circleDiameter);
cursorCircle.setAlpha(1.0f);
cursorCircle.drawCentered(pausedMousePosition.x, pausedMousePosition.y);
Image cursorCirclePulse = cursorCircle.getScaledCopy(1f + pausePulse);
cursorCirclePulse.setAlpha(1f - pausePulse);
cursorCirclePulse.drawCentered(pausedMousePosition.x, pausedMousePosition.y);
}
if (isReplay)
UI.draw(g, replayX, replayY, replayKeyPressed);
else if (GameMod.AUTO.isActive())
UI.draw(g, (int) autoMousePosition.x, (int) autoMousePosition.y, autoMousePressed);
else if (GameMod.AUTOPILOT.isActive())
UI.draw(g, (int) autoMousePosition.x, (int) autoMousePosition.y, Utils.isGameKeyPressed());
else
UI.draw(g);
}
@Override
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
UI.update(delta);
int mouseX = input.getMouseX(), mouseY = input.getMouseY();
skipButton.hoverUpdate(delta, mouseX, mouseY);
if (isReplay || GameMod.AUTO.isActive())
playbackSpeed.getButton().hoverUpdate(delta, mouseX, mouseY);
int trackPosition = MusicController.getPosition(true);
int firstObjectTime = beatmap.objects[0].getTime();
scoreboardStarStream.update(delta);
// returning from pause screen: must click previous mouse position
if (pauseTime > -1) {
// paused during lead-in or break, or "relax" or "autopilot": continue immediately
if (pausedMousePosition == null || (GameMod.RELAX.isActive() || GameMod.AUTOPILOT.isActive())) {
pauseTime = -1;
if (!isLeadIn())
MusicController.resume();
if (video != null)
video.resume();
}
// focus lost: go back to pause screen
else if (!container.hasFocus()) {
game.enterState(Opsu.STATE_GAMEPAUSEMENU);
pausePulse = 0f;
}
// advance pulse animation
else {
pausePulse += delta / 750f;
if (pausePulse > 1f)
pausePulse = 0f;
// is mouse within the circle?
double distance = Math.hypot(pausedMousePosition.x - mouseX, pausedMousePosition.y - mouseY);
int circleRadius = GameImage.HITCIRCLE.getImage().getWidth() / 2;
if (distance < circleRadius)
UI.updateTooltip(delta, "Click to resume gameplay.", false);
}
return;
}
// replays: skip intro
if (isReplay && replaySkipTime > -1 && trackPosition >= replaySkipTime) {
if (skipIntro())
trackPosition = MusicController.getPosition(true);
}
// "flashlight" mod: calculate visible area radius
updateFlashlightRadius(delta, trackPosition);
// stop updating during song lead-in
if (isLeadIn()) {
leadInTime -= delta;
if (!isLeadIn())
MusicController.resume();
return;
}
// "Easy" mod: multiple "lives"
if (GameMod.EASY.isActive() && deathTime > -1) {
if (data.getHealthPercent() < 99f) {
data.changeHealth(delta / 5f);
data.updateDisplays(delta);
return;
}
MusicController.resume();
if (video != null)
video.resume();
deathTime = -1;
}
// update video
if (video != null && !video.isFinished()) {
if (trackPosition >= videoStartTime)
video.update(trackPosition - videoStartTime - videoSeekTime);
}
// normal game update
if (!isReplay && !gameFinished) {
addReplayFrameAndRun(mouseX, mouseY, lastKeysPressed, trackPosition);
addLifeFrame(trackPosition);
}
// watching replay
else if (!gameFinished) {
// out of frames, use previous data
if (replayIndex >= replay.frames.length)
updateGame(replayX, replayY, delta, MusicController.getPosition(true), lastKeysPressed);
boolean hasVideo = (video != null);
// seeking to a position earlier than original track position
if (isSeeking && replayIndex - 1 >= 1 && replayIndex < replay.frames.length &&
trackPosition < replay.frames[replayIndex - 1].getTime()) {
replayIndex = 0;
while (objectIndex >= 0) {
gameObjects[objectIndex].reset();
objectIndex--;
}
// reset game data
FakeCombinedCurve oldMergedSlider = mergedSlider;
resetGameData();
mergedSlider = oldMergedSlider;
// load the first timingPoint
if (!beatmap.timingPoints.isEmpty()) {
TimingPoint timingPoint = beatmap.timingPoints.get(0);
if (!timingPoint.isInherited()) {
setBeatLength(timingPoint, true);
timingPointIndex++;
}
}
}
// update and run replay frames
while (replayIndex < replay.frames.length && trackPosition >= replay.frames[replayIndex].getTime()) {
ReplayFrame frame = replay.frames[replayIndex];
replayX = frame.getScaledX();
replayY = frame.getScaledY();
replayKeyPressed = frame.isKeyPressed();
lastKeysPressed = frame.getKeys();
runReplayFrame(frame);
replayIndex++;
}
mouseX = replayX;
mouseY = replayY;
// unmute sounds
if (isSeeking) {
isSeeking = false;
SoundController.mute(false);
if (hasVideo)
loadVideo(trackPosition);
}
}
// update key overlay
if (isReplay || Options.alwaysShowKeyOverlay()) {
for (int i = 0; i < 4; i++) {
int keys = autoMousePressed ? 1 : lastKeysPressed;
boolean countpresses = breakTime == 0 && !isLeadIn() &&
trackPosition > firstObjectTime;
inputOverlayKeys[i].update(keys, countpresses, delta);
}
}
lastTrackPosition = trackPosition;
// update in-game scoreboard
if (previousScores != null && trackPosition > firstObjectTime) {
// show scoreboard if selected, and always in break
// hide when game ends
if ((scoreboardVisible || breakTime > 0) && !gameFinished) {
currentScoreboardAlpha += 1f / SCOREBOARD_FADE_IN_TIME * delta;
if (currentScoreboardAlpha > 1f)
currentScoreboardAlpha = 1f;
} else {
currentScoreboardAlpha -= 1f / SCOREBOARD_FADE_IN_TIME * delta;
if (currentScoreboardAlpha < 0f)
currentScoreboardAlpha = 0f;
}
}
data.updateDisplays(delta);
// game finished: change state after timer expires
if (gameFinished && !gameFinishedTimer.update(delta)) {
if (checkpointLoaded) // if checkpoint used, skip ranking screen
game.closeRequested();
else { // go to ranking screen
MusicController.setPitch(1f);
game.enterState(Opsu.STATE_GAMERANKING, new EasedFadeOutTransition(), new FadeInTransition());
}
}
}
/**
* Updates the game.
* @param mouseX the mouse x coordinate
* @param mouseY the mouse y coordinate
* @param delta the delta interval
* @param trackPosition the track position
* @param keys the keys that are pressed
*/
private void updateGame(int mouseX, int mouseY, int delta, int trackPosition, int keys) {
// map complete!
if (!hasMoreObjects() || (MusicController.trackEnded() && objectIndex > 0)) {
// track ended before last object(s) was processed: force a hit result
if (MusicController.trackEnded() && hasMoreObjects()) {
for (int index : passedObjects)
gameObjects[index].update(delta, mouseX, mouseY, false, trackPosition);
passedObjects.clear();
for (int i = objectIndex; i < gameObjects.length; i++)
gameObjects[i].update(delta, mouseX, mouseY, false, trackPosition);
objectIndex = gameObjects.length;
}
// save score and replay
if (!checkpointLoaded) {
boolean unranked = (GameMod.AUTO.isActive() || GameMod.RELAX.isActive() || GameMod.AUTOPILOT.isActive());
((GameRanking) game.getState(Opsu.STATE_GAMERANKING)).setGameData(data);
if (isReplay)
data.setReplay(replay);
else if (replayFrames != null) {
// finalize replay frames with start/skip frames
if (!replayFrames.isEmpty())
replayFrames.getFirst().setTimeDiff(replaySkipTime * -1);
replayFrames.addFirst(ReplayFrame.getStartFrame(replaySkipTime));
replayFrames.addFirst(ReplayFrame.getStartFrame(0));
Replay r = data.getReplay(
replayFrames.toArray(new ReplayFrame[replayFrames.size()]),
lifeFrames.toArray(new LifeFrame[lifeFrames.size()]),
beatmap
);
if (r != null && !unranked)
r.save();
}
ScoreData score = data.getScoreData(beatmap);
data.setGameplay(!isReplay);
// add score to database and user stats
if (!unranked && !isReplay) {
ScoreDB.addScore(score);
User user = UserList.get().getCurrentUser();
user.add(data.getScore(), data.getScorePercent());
ScoreDB.updateUser(user);
}
}
// start timer
gameFinished = true;
gameFinishedTimer.setTime(0);
return;
}
// timing points
if (timingPointIndex < beatmap.timingPoints.size()) {
TimingPoint timingPoint = beatmap.timingPoints.get(timingPointIndex);
if (trackPosition >= timingPoint.getTime()) {
setBeatLength(timingPoint, true);
timingPointIndex++;
}
}
// song beginning
if (objectIndex == 0 && trackPosition < beatmap.objects[0].getTime())
return; // nothing to do here
// break periods
if (beatmap.breaks != null && breakIndex < beatmap.breaks.size()) {
int breakValue = beatmap.breaks.get(breakIndex);
if (breakTime > 0) { // in a break period
if (trackPosition < breakValue &&
trackPosition < beatmap.objects[objectIndex].getTime() - approachTime)
return;
else {
// break is over
breakTime = 0;
breakIndex++;
}
} else if (trackPosition >= breakValue) {
// start a break
breakTime = breakValue;
breakSound = false;
breakIndex++;
return;
}
}
// pause game if focus lost
if (!container.hasFocus() && !GameMod.AUTO.isActive() && !isReplay) {
if (pauseTime < 0) {
pausedMousePosition = new Vec2f(mouseX, mouseY);
pausePulse = 0f;
}
if (MusicController.isPlaying() || isLeadIn())
pauseTime = trackPosition;
if (video != null)
video.pause();
game.enterState(Opsu.STATE_GAMEPAUSEMENU, new EmptyTransition(), new FadeInTransition());
}
// drain health
if (lastTrackPosition > 0)
data.changeHealth((trackPosition - lastTrackPosition) * -1 * hpDropRate);
// health ran out?
if (!data.isAlive()) {
// "Easy" mod
if (GameMod.EASY.isActive() && !GameMod.SUDDEN_DEATH.isActive()) {
deaths++;
if (deaths < 3) {
deathTime = trackPosition;
MusicController.pause();
if (video != null)
video.pause();
return;
}
}
// game over, force a restart
if (!isReplay) {
if (playState != PlayState.LOSE) {
playState = PlayState.LOSE;
failTime = System.currentTimeMillis();
failTrackTime = MusicController.getPosition(true);
MusicController.fadeOut(MUSIC_FADEOUT_TIME);
MusicController.pitchFadeOut(MUSIC_FADEOUT_TIME);
rotations = new IdentityHashMap<GameObject, Float>();
SoundController.playSound(SoundEffect.FAIL);
// record to stats
User user = UserList.get().getCurrentUser();
user.add(data.getScore());
ScoreDB.updateUser(user);
// fade to pause menu
game.enterState(Opsu.STATE_GAMEPAUSEMENU,
new DelayedFadeOutTransition(Color.black, MUSIC_FADEOUT_TIME, MUSIC_FADEOUT_TIME - LOSE_FADEOUT_TIME),
new FadeInTransition());
return;
}
}
}
// don't process hit results when already lost
if (playState != PlayState.LOSE) {
boolean keyPressed = keys != ReplayFrame.KEY_NONE;
// update passed objects
Iterator<Integer> iter = passedObjects.iterator();
while (iter.hasNext()) {
int index = iter.next();
if (gameObjects[index].update(delta, mouseX, mouseY, keyPressed, trackPosition))
iter.remove();
}
// update objects (loop over any skipped indexes)
while (objectIndex < gameObjects.length && trackPosition > beatmap.objects[objectIndex].getTime()) {
// check if we've already passed the next object's start time
boolean overlap =
(objectIndex + 1 < gameObjects.length &&
trackPosition > beatmap.objects[objectIndex + 1].getTime() - hitResultOffset[GameData.HIT_50]);
// update hit object and check completion status
if (gameObjects[objectIndex].update(delta, mouseX, mouseY, keyPressed, trackPosition)) {
// done, so increment object index
objectIndex++;
} else if (overlap) {
// overlap, so save the current object and increment object index
passedObjects.add(objectIndex);
objectIndex++;
} else
break;
}
}
}
@Override
public int getID() { return state; }
@Override
public void keyPressed(int key, char c) {
int trackPosition = MusicController.getPosition(true);
int mouseX = input.getMouseX();
int mouseY = input.getMouseY();
// game keys
if (!Keyboard.isRepeatEvent() && !gameFinished) {
int keys = ReplayFrame.KEY_NONE;
if (key == Options.getGameKeyLeft())
keys = ReplayFrame.KEY_K1;
else if (key == Options.getGameKeyRight())
keys = ReplayFrame.KEY_K2;
if (keys != ReplayFrame.KEY_NONE)
gameKeyPressed(keys, mouseX, mouseY, trackPosition);
}
if (UI.globalKeyPressed(key))
return;
switch (key) {
case Input.KEY_ESCAPE:
// game finished: only advance the timer
if (gameFinished) {
gameFinishedTimer.setTime(gameFinishedTimer.getDuration());
break;
}
// "auto" mod or watching replay: go back to song menu
if (GameMod.AUTO.isActive() || isReplay) {
game.closeRequested();
break;
}
// pause game
if (pauseTime < 0 && breakTime <= 0 && trackPosition >= beatmap.objects[0].getTime()) {
pausedMousePosition = new Vec2f(mouseX, mouseY);
pausePulse = 0f;
}
if (MusicController.isPlaying() || isLeadIn())
pauseTime = trackPosition;
if (video != null)
video.pause();
game.enterState(Opsu.STATE_GAMEPAUSEMENU, new EmptyTransition(), new FadeInTransition());
break;
case Input.KEY_SPACE:
// skip intro
if (!gameFinished)
skipIntro();
break;
case Input.KEY_R:
// restart
if (!input.isKeyDown(Input.KEY_RCONTROL) && !input.isKeyDown(Input.KEY_LCONTROL))
break;
// fall through
case Input.KEY_GRAVE:
// restart
if (gameFinished)
break;
try {
if (trackPosition < beatmap.objects[0].getTime())
retries--; // don't count this retry (cancel out later increment)
playState = PlayState.RETRY;
enter(container, game);
skipIntro();
} catch (SlickException e) {
ErrorHandler.error("Failed to restart game.", e, false);
}
break;
case Input.KEY_S:
// save checkpoint
if (gameFinished)
break;
if (input.isKeyDown(Input.KEY_RCONTROL) || input.isKeyDown(Input.KEY_LCONTROL)) {
if (isLeadIn())
break;
int position = (pauseTime > -1) ? pauseTime : trackPosition;
if (Options.setCheckpoint(position / 1000)) {
playSoundEffect(SoundEffect.MENUCLICK);
UI.getNotificationManager().sendBarNotification("Checkpoint saved.");
}
}
break;
case Input.KEY_L:
// load checkpoint
if (gameFinished)
break;
if (input.isKeyDown(Input.KEY_RCONTROL) || input.isKeyDown(Input.KEY_LCONTROL)) {
int checkpoint = Options.getCheckpoint();
if (checkpoint == 0 || checkpoint > beatmap.endTime)
break; // invalid checkpoint
try {
playState = PlayState.RETRY;
enter(container, game);
checkpointLoaded = true;
if (isLeadIn()) {
leadInTime = 0;
MusicController.resume();
}
playSoundEffect(SoundEffect.MENUHIT);
UI.getNotificationManager().sendBarNotification("Checkpoint loaded.");
// skip to checkpoint
MusicController.setPosition(checkpoint);
MusicController.setPitch(getCurrentPitch());
if (video != null)
loadVideo(checkpoint);
while (objectIndex < gameObjects.length &&
beatmap.objects[objectIndex++].getTime() <= checkpoint)
;
objectIndex--;
lastReplayTime = beatmap.objects[objectIndex].getTime();
lastTrackPosition = checkpoint;
} catch (SlickException e) {
ErrorHandler.error("Failed to load checkpoint.", e, false);
}
}
break;
case Input.KEY_F:
// change playback speed
if (gameFinished)
break;
if (isReplay || GameMod.AUTO.isActive()) {
playbackSpeed = playbackSpeed.next();
MusicController.setPitch(getCurrentPitch());
}
break;
case Input.KEY_UP:
UI.changeVolume(1);
break;
case Input.KEY_DOWN:
UI.changeVolume(-1);
break;
case Input.KEY_TAB:
if (!gameFinished)
scoreboardVisible = !scoreboardVisible;
break;
case Input.KEY_EQUALS:
case Input.KEY_ADD:
if (!Keyboard.isRepeatEvent() && !gameFinished)
adjustLocalMusicOffset(1);
break;
case Input.KEY_MINUS:
case Input.KEY_SUBTRACT:
if (!Keyboard.isRepeatEvent() && !gameFinished)
adjustLocalMusicOffset(-1);
break;
}
}
@Override
public void mousePressed(int button, int x, int y) {
if (gameFinished)
return;
// watching replay
if (isReplay || GameMod.AUTO.isActive()) {
if (button == Input.MOUSE_MIDDLE_BUTTON)
return;
// skip button
if (skipButton.contains(x, y))
skipIntro();
// playback speed button
else if (playbackSpeed.getButton().contains(x, y)) {
playbackSpeed = playbackSpeed.next();
MusicController.setPitch(getCurrentPitch());
}
// replay seeking
else if (Options.isReplaySeekingEnabled() && !GameMod.AUTO.isActive() && musicPositionBarContains(x, y)) {
SoundController.mute(true); // mute sounds while seeking
float pos = (y - musicBarY) / musicBarHeight * beatmap.endTime;
MusicController.setPosition((int) pos);
lastTrackPosition = (int) pos;
isSeeking = true;
}
return;
}
if (Options.isMouseDisabled())
return;
// mouse wheel: pause the game
if (button == Input.MOUSE_MIDDLE_BUTTON && !Options.isMouseWheelDisabled()) {
int trackPosition = MusicController.getPosition(true);
if (pauseTime < 0 && breakTime <= 0 && trackPosition >= beatmap.objects[0].getTime()) {
pausedMousePosition = new Vec2f(x, y);
pausePulse = 0f;
}
if (MusicController.isPlaying() || isLeadIn())
pauseTime = trackPosition;
if (video != null)
video.pause();
game.enterState(Opsu.STATE_GAMEPAUSEMENU, new EmptyTransition(), new FadeInTransition());
return;
}
// game keys
int keys = ReplayFrame.KEY_NONE;
if (button == Input.MOUSE_LEFT_BUTTON)
keys = ReplayFrame.KEY_M1;
else if (button == Input.MOUSE_RIGHT_BUTTON)
keys = ReplayFrame.KEY_M2;
if (keys != ReplayFrame.KEY_NONE)
gameKeyPressed(keys, x, y, MusicController.getPosition(true));
}
/**
* Handles a game key pressed event.
* @param keys the game keys pressed
* @param x the mouse x coordinate
* @param y the mouse y coordinate
* @param trackPosition the track position
*/
private void gameKeyPressed(int keys, int x, int y, int trackPosition) {
// returning from pause screen
if (pauseTime > -1) {
double distance = Math.hypot(pausedMousePosition.x - x, pausedMousePosition.y - y);
int circleRadius = GameImage.HITCIRCLE.getImage().getWidth() / 2;
if (distance < circleRadius) {
// unpause the game
pauseTime = -1;
pausedMousePosition = null;
if (!isLeadIn())
MusicController.resume();
if (video != null)
video.resume();
}
return;
}
// skip beginning
if (skipButton.contains(x, y)) {
if (skipIntro())
return; // successfully skipped
}
// "auto" and "relax" mods: ignore user actions
if (GameMod.AUTO.isActive() || GameMod.RELAX.isActive())
return;
// send a game key press
if (!isReplay && !gameFinished && keys != ReplayFrame.KEY_NONE) {
lastKeysPressed |= keys; // set keys bits
addReplayFrameAndRun(x, y, lastKeysPressed, trackPosition);
}
}
@Override
public void mouseReleased(int button, int x, int y) {
if (gameFinished)
return;
if (Options.isMouseDisabled())
return;
if (button == Input.MOUSE_MIDDLE_BUTTON)
return;
int keys = ReplayFrame.KEY_NONE;
if (button == Input.MOUSE_LEFT_BUTTON)
keys = ReplayFrame.KEY_M1;
else if (button == Input.MOUSE_RIGHT_BUTTON)
keys = ReplayFrame.KEY_M2;
if (keys != ReplayFrame.KEY_NONE)
gameKeyReleased(keys, x, y, MusicController.getPosition(true));
}
@Override
public void keyReleased(int key, char c) {
if (gameFinished)
return;
int keys = ReplayFrame.KEY_NONE;
if (key == Options.getGameKeyLeft())
keys = ReplayFrame.KEY_K1;
else if (key == Options.getGameKeyRight())
keys = ReplayFrame.KEY_K2;
if (keys != ReplayFrame.KEY_NONE)
gameKeyReleased(keys, input.getMouseX(), input.getMouseY(), MusicController.getPosition(true));
}
/**
* Handles a game key released event.
* @param keys the game keys released
* @param x the mouse x coordinate
* @param y the mouse y coordinate
* @param trackPosition the track position
*/
private void gameKeyReleased(int keys, int x, int y, int trackPosition) {
if (!isReplay && keys != ReplayFrame.KEY_NONE && !isLeadIn() && pauseTime == -1) {
lastKeysPressed &= ~keys; // clear keys bits
addReplayFrameAndRun(x, y, lastKeysPressed, trackPosition);
}
}
@Override
public void mouseWheelMoved(int newValue) {
if (Options.isMouseWheelDisabled())
return;
UI.globalMouseWheelMoved(newValue, false);
}
@Override
public void enter(GameContainer container, StateBasedGame game)
throws SlickException {
UI.enter();
if (beatmap == null || beatmap.objects == null)
throw new RuntimeException("Running game with no beatmap loaded.");
// free all previously cached hitobject to framebuffer mappings if some still exist
FrameBufferCache.getInstance().freeMap();
// grab the mouse (not working for touchscreen)
// container.setMouseGrabbed(true);
// restart the game
if (playState != PlayState.NORMAL) {
// reset key states
lastKeysPressed = 0;
for (int i = 0; i < 4; i++)
inputOverlayKeys[i].reset();
// update play stats
if (playState == PlayState.FIRST_LOAD) {
beatmap.incrementPlayCounter();
BeatmapDB.updatePlayStatistics(beatmap);
}
// load mods
if (isReplay) {
previousMods = GameMod.getModState();
GameMod.loadModState(replay.mods);
}
data.setGameplay(true);
// check play state
if (playState == PlayState.FIRST_LOAD) {
loadImages();
setMapModifiers();
retries = 0;
} else if (playState == PlayState.RETRY && !GameMod.AUTO.isActive()) {
retries++;
} else if (playState == PlayState.REPLAY || GameMod.AUTO.isActive()) {
retries = 0;
}
gameObjects = new GameObject[beatmap.objects.length];
playbackSpeed = PlaybackSpeed.NORMAL;
// reset game data
resetGameData();
// load the first timingPoint for stacking
if (!beatmap.timingPoints.isEmpty()) {
TimingPoint timingPoint = beatmap.timingPoints.get(0);
if (!timingPoint.isInherited()) {
setBeatLength(timingPoint, true);
timingPointIndex++;
}
}
// initialize object maps
boolean ignoreSkins = Options.isBeatmapSkinIgnored();
Color[] combo = ignoreSkins ? Options.getSkin().getComboColors() : beatmap.getComboColors();
int comboIndex = 0;
for (int i = 0; i < beatmap.objects.length; i++) {
HitObject hitObject = beatmap.objects[i];
// is this the last note in the combo?
boolean comboEnd = false;
if (i + 1 >= beatmap.objects.length || beatmap.objects[i + 1].isNewCombo())
comboEnd = true;
// calculate color index if ignoring beatmap skin
Color color;
if (ignoreSkins) {
if (hitObject.isNewCombo() || i == 0) {
int skip = (hitObject.isSpinner() ? 0 : 1) + hitObject.getComboSkip();
for (int j = 0; j < skip; j++)
comboIndex = (comboIndex + 1) % combo.length;
}
color = combo[comboIndex];
} else
color = combo[hitObject.getComboIndex()];
// pass beatLength to hit objects
int hitObjectTime = hitObject.getTime();
while (timingPointIndex < beatmap.timingPoints.size()) {
TimingPoint timingPoint = beatmap.timingPoints.get(timingPointIndex);
if (timingPoint.getTime() > hitObjectTime)
break;
setBeatLength(timingPoint, false);
timingPointIndex++;
}
try {
if (hitObject.isCircle())
gameObjects[i] = new Circle(hitObject, this, data, color, comboEnd);
else if (hitObject.isSlider())
gameObjects[i] = new Slider(hitObject, this, data, color, comboEnd);
else if (hitObject.isSpinner())
gameObjects[i] = new Spinner(hitObject, this, data);
else // invalid hit object, use a dummy GameObject
gameObjects[i] = new DummyObject(hitObject);
} catch (Exception e) {
// try to handle the error gracefully: substitute in a dummy GameObject
ErrorHandler.error(String.format("Failed to create %s at index %d:\n%s",
hitObject.getTypeName(), i, hitObject.toString()), e, true);
gameObjects[i] = new DummyObject(hitObject);
continue;
}
}
// stack calculations
calculateStacks();
// load the first timingPoint
timingPointIndex = 0;
beatLengthBase = beatLength = 1;
if (!beatmap.timingPoints.isEmpty()) {
TimingPoint timingPoint = beatmap.timingPoints.get(0);
if (!timingPoint.isInherited()) {
setBeatLength(timingPoint, true);
timingPointIndex++;
}
}
// experimental merged slider
if (Options.isExperimentalSliderMerging())
createMergedSlider();
// unhide cursor for "auto" mod and replays
if (GameMod.AUTO.isActive() || isReplay)
UI.getCursor().show();
// load replay frames
if (isReplay) {
// load initial data
replayX = container.getWidth() / 2;
replayY = container.getHeight() / 2;
replayKeyPressed = false;
replaySkipTime = -1;
for (replayIndex = 0; replayIndex < replay.frames.length; replayIndex++) {
ReplayFrame frame = replay.frames[replayIndex];
if (frame.getY() < 0) { // skip time (?)
if (frame.getTime() >= 0 && replayIndex > 0)
replaySkipTime = frame.getTime();
} else if (frame.getTime() == 0) {
replayX = frame.getScaledX();
replayY = frame.getScaledY();
replayKeyPressed = frame.isKeyPressed();
} else
break;
}
}
// initialize replay-recording structures
else {
lastKeysPressed = ReplayFrame.KEY_NONE;
replaySkipTime = -1;
replayFrames = new LinkedList<ReplayFrame>();
replayFrames.add(new ReplayFrame(0, 0, input.getMouseX(), input.getMouseY(), 0));
lifeFrames = new LinkedList<LifeFrame>();
}
leadInTime = beatmap.audioLeadIn + approachTime;
playState = PlayState.NORMAL;
// fetch previous scores
previousScores = ScoreDB.getMapScoresExcluding(beatmap, replay == null ? null : replay.getReplayFilename());
lastRankUpdateTime = -1000;
if (previousScores != null)
currentRank = previousScores.length;
scoreboardVisible = previousScores.length > 0;
currentScoreboardAlpha = 0f;
// using local offset?
if (beatmap.localMusicOffset != 0)
UI.getNotificationManager().sendBarNotification(String.format("Using local beatmap offset (%dms)", beatmap.localMusicOffset));
// using custom difficulty settings?
if (Options.getFixedCS() > 0f || Options.getFixedAR() > 0f || Options.getFixedOD() > 0f ||
Options.getFixedHP() > 0f || Options.getFixedSpeed() > 0f)
UI.getNotificationManager().sendNotification("Playing with custom difficulty settings.");
// load video
if (beatmap.video != null) {
loadVideo((beatmap.videoOffset < 0) ? -beatmap.videoOffset : 0);
videoStartTime = Math.max(0, beatmap.videoOffset);
}
// needs to play before setting position to resume without lag later
MusicController.playAt(0, false);
MusicController.pause();
SoundController.mute(false);
}
skipButton.resetHover();
if (isReplay || GameMod.AUTO.isActive())
playbackSpeed.getButton().resetHover();
MusicController.setPitch(getCurrentPitch());
}
@Override
public void leave(GameContainer container, StateBasedGame game)
throws SlickException {
// container.setMouseGrabbed(false);
// re-hide cursor
if (GameMod.AUTO.isActive() || isReplay)
UI.getCursor().hide();
// replays
if (isReplay)
GameMod.loadModState(previousMods);
}
/**
* Draws hit objects, hit results, and follow points.
* @param g the graphics context
* @param trackPosition the track position
*/
private void drawHitObjects(Graphics g, int trackPosition) {
// draw result objects (under)
data.drawHitResults(trackPosition, false);
// include previous object in follow points
int lastObjectIndex = -1;
if (objectIndex > 0 && objectIndex < beatmap.objects.length &&
trackPosition < beatmap.objects[objectIndex].getTime() && !beatmap.objects[objectIndex - 1].isSpinner())
lastObjectIndex = objectIndex - 1;
boolean loseState = (playState == PlayState.LOSE);
if (loseState)
trackPosition = failTrackTime + (int) (System.currentTimeMillis() - failTime);
// draw merged slider
if (!loseState && mergedSlider != null && Options.isExperimentalSliderMerging()) {
mergedSlider.draw(Color.white);
mergedSlider.clearPoints();
}
// get hit objects in reverse order, or else overlapping objects are unreadable
Stack<Integer> stack = new Stack<Integer>();
int spinnerIndex = -1; // draw spinner first (assume there can only be 1...)
for (int index : passedObjects) {
if (beatmap.objects[index].isSpinner()) {
if (spinnerIndex == -1)
spinnerIndex = index;
} else
stack.add(index);
}
for (int index = objectIndex; index < gameObjects.length && beatmap.objects[index].getTime() < trackPosition + approachTime; index++) {
if (beatmap.objects[index].isSpinner()) {
if (spinnerIndex == -1)
spinnerIndex = index;
} else
stack.add(index);
// draw follow points
if (Options.isFollowPointEnabled() && !loseState)
lastObjectIndex = drawFollowPointsBetween(objectIndex, lastObjectIndex, trackPosition);
}
if (spinnerIndex != -1)
stack.add(spinnerIndex);
// draw hit objects
while (!stack.isEmpty()){
int idx = stack.pop();
GameObject gameObj = gameObjects[idx];
// normal case
if (!loseState)
gameObj.draw(g, trackPosition);
// death: make objects "fall" off the screen
else {
// time the object began falling
int objTime = Math.max(beatmap.objects[idx].getTime() - approachTime, failTrackTime);
float dt = (trackPosition - objTime) / (float) (MUSIC_FADEOUT_TIME);
// would the object already be visible?
if (dt <= 0)
continue;
// generate rotation speeds for each objects
final float rotSpeed;
if (rotations.containsKey(gameObj)) {
rotSpeed = rotations.get(gameObj);
} else {
rotSpeed = (float) (2.0f * (Math.random() - 0.5f) * MAX_ROTATION);
rotations.put(gameObj, rotSpeed);
}
g.pushTransform();
// translate and rotate the object
g.translate(0, dt * dt * container.getHeight());
Vec2f rotationCenter = gameObj.getPointAt((beatmap.objects[idx].getTime() + beatmap.objects[idx].getEndTime()) / 2);
g.rotate(rotationCenter.x, rotationCenter.y, rotSpeed * dt);
gameObj.draw(g, trackPosition);
g.popTransform();
}
}
// draw result objects (over)
data.drawHitResults(trackPosition, true);
}
/**
* Draws follow points between two objects.
* @param index the current object index
* @param lastObjectIndex the last object index
* @param trackPosition the current track position
* @return the new lastObjectIndex value
*/
private int drawFollowPointsBetween(int index, int lastObjectIndex, int trackPosition) {
if (lastObjectIndex == -1)
return -1;
if (beatmap.objects[index].isSpinner() || beatmap.objects[index].isNewCombo())
return lastObjectIndex;
// calculate points
final int followPointInterval = container.getHeight() / 14;
int lastObjectEndTime = gameObjects[lastObjectIndex].getEndTime() + 1;
int objectStartTime = beatmap.objects[index].getTime();
Vec2f startPoint = gameObjects[lastObjectIndex].getPointAt(lastObjectEndTime);
Vec2f endPoint = gameObjects[index].getPointAt(objectStartTime);
float xDiff = endPoint.x - startPoint.x;
float yDiff = endPoint.y - startPoint.y;
float dist = (float) Math.hypot(xDiff, yDiff);
int numPoints = (int) ((dist - GameImage.HITCIRCLE.getImage().getWidth()) / followPointInterval);
if (numPoints > 0) {
// set the image angle
Image followPoint = GameImage.FOLLOWPOINT.getImage();
float angle = (float) Math.toDegrees(Math.atan2(yDiff, xDiff));
followPoint.setRotation(angle);
// draw points
float progress = 0f, alpha = 1f;
if (lastObjectIndex < objectIndex)
progress = (float) (trackPosition - lastObjectEndTime) / (objectStartTime - lastObjectEndTime);
else {
alpha = Utils.clamp((1f - ((objectStartTime - trackPosition) / (float) approachTime)) * 2f, 0, 1);
followPoint.setAlpha(alpha);
}
float step = 1f / (numPoints + 1);
float t = step;
for (int i = 0; i < numPoints; i++) {
float x = startPoint.x + xDiff * t;
float y = startPoint.y + yDiff * t;
float nextT = t + step;
if (lastObjectIndex < objectIndex) { // fade the previous trail
if (progress < nextT) {
if (progress > t)
followPoint.setAlpha(1f - ((progress - t + step) / (step * 2f)));
else if (progress > t - step)
followPoint.setAlpha(1f - ((progress - (t - step)) / (step * 2f)));
else
followPoint.setAlpha(1f);
followPoint.drawCentered(x, y);
}
} else
followPoint.drawCentered(x, y);
t = nextT;
}
followPoint.setAlpha(1f);
}
return index;
}
/**
* Loads all required data from a beatmap.
* @param beatmap the beatmap to load
*/
public void loadBeatmap(Beatmap beatmap) {
this.beatmap = beatmap;
Display.setTitle(String.format("%s - %s", game.getTitle(), beatmap.toString()));
if (beatmap.timingPoints == null)
BeatmapDB.load(beatmap, BeatmapDB.LOAD_ARRAY);
BeatmapParser.parseHitObjects(beatmap);
HitSound.setDefaultSampleSet(beatmap.sampleSet);
Utils.gc(true);
}
/**
* Resets all game data and structures.
*/
public void resetGameData() {
data.clear();
objectIndex = 0;
passedObjects = new LinkedList<Integer>();
breakIndex = 0;
breakTime = 0;
breakSound = false;
timingPointIndex = 0;
beatLengthBase = beatLength = 1;
pauseTime = -1;
pausedMousePosition = null;
countdownReadySound = false;
countdown3Sound = false;
countdown1Sound = false;
countdown2Sound = false;
countdownGoSound = false;
checkpointLoaded = false;
deaths = 0;
deathTime = -1;
replayFrames = null;
lifeFrames = null;
lastReplayTime = 0;
autoMousePosition = new Vec2f();
autoMousePressed = false;
flashlightRadius = container.getHeight() * 2 / 3;
scoreboardStarStream.clear();
gameFinished = false;
gameFinishedTimer.setTime(0);
lastTrackPosition = 0;
if (video != null) {
try {
video.close();
} catch (IOException e) {}
video = null;
}
videoSeekTime = 0;
mergedSlider = null;
}
/**
* Skips the beginning of a track.
* @return {@code true} if skipped, {@code false} otherwise
*/
private synchronized boolean skipIntro() {
int firstObjectTime = beatmap.objects[0].getTime();
int trackPosition = MusicController.getPosition(true);
if (objectIndex == 0 && trackPosition < firstObjectTime - SKIP_OFFSET) {
if (isLeadIn()) {
leadInTime = 0;
MusicController.resume();
}
MusicController.setPosition(firstObjectTime - SKIP_OFFSET);
MusicController.setPitch(getCurrentPitch());
replaySkipTime = (isReplay) ? -1 : trackPosition;
if (isReplay) {
replayX = (int) skipButton.getX();
replayY = (int) skipButton.getY();
}
playSoundEffect(SoundEffect.MENUHIT);
return true;
}
return false;
}
/**
* Loads all game images.
*/
private void loadImages() {
int width = container.getWidth();
int height = container.getHeight();
// set images
File parent = beatmap.getFile().getParentFile();
for (GameImage img : GameImage.values()) {
if (img.isBeatmapSkinnable()) {
img.setDefaultImage();
img.setBeatmapSkinImage(parent);
}
}
// skip button
if (GameImage.SKIP.getImages() != null) {
Animation skip = GameImage.SKIP.getAnimation();
skipButton = new MenuButton(skip, width - skip.getWidth() / 2f, height - (skip.getHeight() / 2f));
} else {
Image skip = GameImage.SKIP.getImage();
skipButton = new MenuButton(skip, width - skip.getWidth() / 2f, height - (skip.getHeight() / 2f));
}
skipButton.setHoverAnimationDuration(350);
skipButton.setHoverAnimationEquation(AnimationEquation.IN_OUT_BACK);
skipButton.setHoverExpand(1.1f, MenuButton.Expand.UP_LEFT);
// load other images...
((GamePauseMenu) game.getState(Opsu.STATE_GAMEPAUSEMENU)).loadImages();
data.loadImages();
}
/**
* Loads the beatmap video (if any).
* @param offset the time to seek to (in milliseconds)
*/
private void loadVideo(int offset) {
// close previous video
if (video != null) {
try {
video.close();
} catch (IOException e) {}
video = null;
}
if (!Options.isBeatmapVideoEnabled() || beatmap.video == null || !beatmap.video.isFile() || !FFmpeg.exists())
return;
// load video
int time = Math.max(0, offset);
try {
video = new Video(beatmap.video);
video.seek(time);
video.resume();
videoSeekTime = time;
} catch (Exception e) {
video = null;
videoSeekTime = 0;
Log.error(e);
UI.getNotificationManager().sendNotification("Failed to load beatmap video.\nSee log for details.", Color.red);
}
}
/**
* Set map modifiers.
*/
private void setMapModifiers() {
// map-based properties, re-initialized each game
float multiplier = GameMod.getDifficultyMultiplier();
float circleSize = Math.min(beatmap.circleSize * multiplier, 10f);
float approachRate = Math.min(beatmap.approachRate * multiplier, 10f);
float overallDifficulty = Math.min(beatmap.overallDifficulty * multiplier, 10f);
float HPDrainRate = Math.min(beatmap.HPDrainRate * multiplier, 10f);
// fixed difficulty overrides
if (Options.getFixedCS() > 0f)
circleSize = Options.getFixedCS();
if (Options.getFixedAR() > 0f)
approachRate = Options.getFixedAR();
if (Options.getFixedOD() > 0f)
overallDifficulty = Options.getFixedOD();
if (Options.getFixedHP() > 0f)
HPDrainRate = Options.getFixedHP();
// Stack modifier scales with hit object size
// StackOffset = HitObjectRadius / 10
//int diameter = (int) (104 - (circleSize * 8));
float diameter = 108.848f - (circleSize * 8.9646f);
HitObject.setStackOffset(diameter * STACK_OFFSET_MODIFIER);
// initialize objects
Circle.init(container, diameter);
Slider.init(container, diameter, beatmap);
Spinner.init(container, overallDifficulty);
Curve.init(container.getWidth(), container.getHeight(), diameter, (Options.isBeatmapSkinIgnored()) ?
Options.getSkin().getSliderBorderColor() : beatmap.getSliderBorderColor());
// approachRate (hit object approach time)
approachTime = (int) Utils.mapDifficultyRange(approachRate, 1800, 1200, 450);
// overallDifficulty (hit result time offsets)
hitResultOffset = new int[GameData.HIT_MAX];
hitResultOffset[GameData.HIT_300] = (int) Utils.mapDifficultyRange(overallDifficulty, 80, 50, 20);
hitResultOffset[GameData.HIT_100] = (int) Utils.mapDifficultyRange(overallDifficulty, 140, 100, 60);
hitResultOffset[GameData.HIT_50] = (int) Utils.mapDifficultyRange(overallDifficulty, 200, 150, 100);
hitResultOffset[GameData.HIT_MISS] = (int) (500 - (overallDifficulty * 10));
data.setHitResultOffset(hitResultOffset);
// HPDrainRate (health change)
BeatmapHPDropRateCalculator hpCalc = new BeatmapHPDropRateCalculator(beatmap, HPDrainRate, overallDifficulty);
hpCalc.calculate();
hpDropRate = hpCalc.getHpDropRate();
data.setHealthModifiers(HPDrainRate, hpCalc.getHpMultiplierNormal(), hpCalc.getHpMultiplierComboEnd());
// difficulty multiplier (scoring)
data.calculateDifficultyMultiplier(beatmap.HPDrainRate, beatmap.circleSize, beatmap.overallDifficulty);
// hit object fade-in time (TODO: formula)
fadeInTime = Math.min(375, (int) (approachTime / 2.5f));
// fade times ("Hidden" mod)
// TODO: find the actual formulas for this
hiddenDecayTime = (int) (approachTime / 3.6f);
hiddenTimeDiff = (int) (approachTime / 3.3f);
}
/**
* Sets the play state.
* @param state the new play state
*/
public void setPlayState(PlayState state) { this.playState = state; }
/**
* Returns the current play state.
*/
public PlayState getPlayState() { return playState; }
/**
* Returns whether or not the track is in the lead-in time state.
*/
public boolean isLeadIn() { return leadInTime > 0; }
/**
* Returns the object approach time, in milliseconds.
*/
public int getApproachTime() { return approachTime; }
/**
* Returns the amount of time for hit objects to fade in, in milliseconds.
*/
public int getFadeInTime() { return fadeInTime; }
/**
* Returns the object decay time in the "Hidden" mod, in milliseconds.
*/
public int getHiddenDecayTime() { return hiddenDecayTime; }
/**
* Returns the time before the hit object time by which the objects have
* completely faded in the "Hidden" mod, in milliseconds.
*/
public int getHiddenTimeDiff() { return hiddenTimeDiff; }
/**
* Returns an array of hit result offset times, in milliseconds (indexed by GameData.HIT_* constants).
*/
public int[] getHitResultOffsets() { return hitResultOffset; }
/**
* Returns the beat length.
*/
public float getBeatLength() { return beatLength; }
/**
* Sets the beat length fields based on a given timing point.
* @param timingPoint the timing point
* @param setSampleSet whether to set the hit sample set based on the timing point
*/
private void setBeatLength(TimingPoint timingPoint, boolean setSampleSet) {
if (!timingPoint.isInherited())
beatLengthBase = beatLength = timingPoint.getBeatLength();
else
beatLength = beatLengthBase * timingPoint.getSliderMultiplier();
if (setSampleSet) {
HitSound.setDefaultSampleSet(timingPoint.getSampleType());
SoundController.setSampleVolume(timingPoint.getSampleVolume());
}
}
/**
* Returns the slider multiplier given by the current timing point.
*/
public float getTimingPointMultiplier() { return beatLength / beatLengthBase; }
/**
* Sets a replay to view, or resets the replay if null.
* @param replay the replay
*/
public void setReplay(Replay replay) {
if (replay == null) {
this.isReplay = false;
this.replay = null;
} else {
if (replay.frames == null) {
ErrorHandler.error("Attempting to set a replay with no frames.", null, false);
return;
}
this.isReplay = true;
this.replay = replay;
}
}
/**
* Adds a replay frame to the list, if possible, and runs it.
* @param x the cursor x coordinate
* @param y the cursor y coordinate
* @param keys the keys pressed
* @param time the time of the replay Frame
*/
private synchronized void addReplayFrameAndRun(int x, int y, int keys, int time){
// "auto" and "autopilot" mods: use automatic cursor coordinates
if (GameMod.AUTO.isActive() || GameMod.AUTOPILOT.isActive()) {
x = (int) autoMousePosition.x;
y = (int) autoMousePosition.y;
}
ReplayFrame frame = addReplayFrame(x, y, keys, time);
if (frame != null)
runReplayFrame(frame);
}
/**
* Runs a replay frame.
* @param frame the frame to run
*/
private void runReplayFrame(ReplayFrame frame){
int keys = frame.getKeys();
int replayX = frame.getScaledX();
int replayY = frame.getScaledY();
int deltaKeys = (keys & ~lastReplayKeys); // keys that turned on
if (deltaKeys != ReplayFrame.KEY_NONE) // send a key press
sendGameKeyPress(deltaKeys, replayX, replayY, frame.getTime());
else if (keys != lastReplayKeys)
; // do nothing
else
updateGame(replayX, replayY, frame.getTimeDiff(), frame.getTime(), keys);
lastReplayKeys = keys;
}
/**
* Sends a game key press and updates the hit objects.
* @param trackPosition the track position
* @param x the cursor x coordinate
* @param y the cursor y coordinate
* @param keys the keys that are pressed
*/
private void sendGameKeyPress(int keys, int x, int y, int trackPosition) {
if (!hasMoreObjects() || gameFinished) // nothing to do here
return;
// check missed objects first
Iterator<Integer> iter = passedObjects.iterator();
while (iter.hasNext()) {
int index = iter.next();
HitObject hitObject = beatmap.objects[index];
if (hitObject.isCircle() && gameObjects[index].mousePressed(x, y, trackPosition)) {
iter.remove(); // circle hit, remove it
return;
} else if (hitObject.isSlider() && gameObjects[index].mousePressed(x, y, trackPosition))
return; // slider initial circle hit
}
// check current object
if (objectIndex >= gameObjects.length)
return;
HitObject hitObject = beatmap.objects[objectIndex];
if (hitObject.isCircle() && gameObjects[objectIndex].mousePressed(x, y, trackPosition))
objectIndex++; // circle hit
else if (hitObject.isSlider())
gameObjects[objectIndex].mousePressed(x, y, trackPosition);
}
/**
* Adds a replay frame to the list, if possible.
* @param x the cursor x coordinate
* @param y the cursor y coordinate
* @param keys the keys pressed
* @param time the time of the replay frame
* @return a ReplayFrame representing the data
*/
private ReplayFrame addReplayFrame(int x, int y, int keys, int time) {
int timeDiff = time - lastReplayTime;
lastReplayTime = time;
int cx = (int) ((x - HitObject.getXOffset()) / HitObject.getXMultiplier());
int cy = (int) ((y - HitObject.getYOffset()) / HitObject.getYMultiplier());
ReplayFrame frame = new ReplayFrame(timeDiff, time, cx, cy, keys);
if (replayFrames != null)
replayFrames.add(frame);
return frame;
}
/**
* Adds a life frame to the list, if possible.
* @param time the time of the life frame
*/
private void addLifeFrame(int time) {
if (lifeFrames == null)
return;
// don't record life frames before first object
if (time < beatmap.objects[0].getTime() - approachTime)
return;
lifeFrames.add(new LifeFrame(time, data.getHealthPercent() / 100f));
}
/**
* Returns the point at the t value between a start and end point.
* @param startX the starting x coordinate
* @param startY the starting y coordinate
* @param endX the ending x coordinate
* @param endY the ending y coordinate
* @param t the t value [0, 1]
* @return the position vector
*/
private Vec2f getPointAt(float startX, float startY, float endX, float endY, float t) {
// "autopilot" mod: move quicker between objects
if (GameMod.AUTOPILOT.isActive())
t = Utils.clamp(t * 2f, 0f, 1f);
return new Vec2f(startX + (endX - startX) * t, startY + (endY - startY) * t);
}
/**
* Updates the current visible area radius (if the "flashlight" mod is enabled).
* @param delta the delta interval
* @param trackPosition the track position
*/
private void updateFlashlightRadius(int delta, int trackPosition) {
if (!GameMod.FLASHLIGHT.isActive())
return;
int width = container.getWidth(), height = container.getHeight();
boolean firstObject = (objectIndex == 0 && trackPosition < beatmap.objects[0].getTime());
if (isLeadIn()) {
// lead-in: expand area
float progress = Math.max((float) (leadInTime - beatmap.audioLeadIn) / approachTime, 0f);
flashlightRadius = width - (int) ((width - (height * 2 / 3)) * progress);
} else if (firstObject) {
// before first object: shrink area
int timeDiff = beatmap.objects[0].getTime() - trackPosition;
flashlightRadius = width;
if (timeDiff < approachTime) {
float progress = (float) timeDiff / approachTime;
flashlightRadius -= (width - (height * 2 / 3)) * (1 - progress);
}
} else {
// gameplay: size based on combo
int targetRadius;
int combo = data.getComboStreak();
if (combo < 100)
targetRadius = height * 2 / 3;
else if (combo < 200)
targetRadius = height / 2;
else
targetRadius = height / 3;
if (beatmap.breaks != null && breakIndex < beatmap.breaks.size() && breakTime > 0) {
// breaks: expand at beginning, shrink at end
flashlightRadius = targetRadius;
int endTime = beatmap.breaks.get(breakIndex);
int breakLength = endTime - breakTime;
if (breakLength > approachTime * 3) {
float progress = 1f;
if (trackPosition - breakTime < approachTime)
progress = (float) (trackPosition - breakTime) / approachTime;
else if (endTime - trackPosition < approachTime)
progress = (float) (endTime - trackPosition) / approachTime;
flashlightRadius += (width - flashlightRadius) * progress;
}
} else if (flashlightRadius != targetRadius) {
// radius size change
float radiusDiff = height * delta / 2000f;
if (flashlightRadius > targetRadius) {
flashlightRadius -= radiusDiff;
if (flashlightRadius < targetRadius)
flashlightRadius = targetRadius;
} else {
flashlightRadius += radiusDiff;
if (flashlightRadius > targetRadius)
flashlightRadius = targetRadius;
}
}
}
}
/**
* Performs stacking calculations on all hit objects, and updates their
* positions if necessary.
* @author peppy (https://gist.github.com/peppy/1167470)
*/
private void calculateStacks() {
// reverse pass for stack calculation
for (int i = gameObjects.length - 1; i > 0; i--) {
HitObject hitObjectI = beatmap.objects[i];
// already calculated
if (hitObjectI.getStack() != 0 || hitObjectI.isSpinner())
continue;
// search for hit objects in stack
for (int n = i - 1; n >= 0; n--) {
HitObject hitObjectN = beatmap.objects[n];
if (hitObjectN.isSpinner())
continue;
// check if in range stack calculation
float timeI = hitObjectI.getTime() - (approachTime * beatmap.stackLeniency);
float timeN = hitObjectN.isSlider() ? gameObjects[n].getEndTime() : hitObjectN.getTime();
if (timeI > timeN)
break;
// possible special case: if slider end in the stack,
// all next hit objects in stack move right down
if (hitObjectN.isSlider()) {
Vec2f p1 = gameObjects[i].getPointAt(hitObjectI.getTime());
Vec2f p2 = gameObjects[n].getPointAt(gameObjects[n].getEndTime());
float distance = Utils.distance(p1.x, p1.y, p2.x, p2.y);
// check if hit object part of this stack
if (distance < STACK_LENIENCE * HitObject.getXMultiplier()) {
int offset = hitObjectI.getStack() - hitObjectN.getStack() + 1;
for (int j = n + 1; j <= i; j++) {
HitObject hitObjectJ = beatmap.objects[j];
p1 = gameObjects[j].getPointAt(hitObjectJ.getTime());
distance = Utils.distance(p1.x, p1.y, p2.x, p2.y);
// hit object below slider end
if (distance < STACK_LENIENCE * HitObject.getXMultiplier())
hitObjectJ.setStack(hitObjectJ.getStack() - offset);
}
break; // slider end always start of the stack: reset calculation
}
}
// not a special case: stack moves up left
float distance = Utils.distance(
hitObjectI.getX(), hitObjectI.getY(),
hitObjectN.getX(), hitObjectN.getY()
);
if (distance < STACK_LENIENCE) {
hitObjectN.setStack(hitObjectI.getStack() + 1);
hitObjectI = hitObjectN;
}
}
}
// update hit object positions
for (int i = 0; i < gameObjects.length; i++) {
if (beatmap.objects[i].getStack() != 0)
gameObjects[i].updatePosition();
}
}
/** Creates the single merged slider. */
private void createMergedSlider() {
// workaround for sliders not appearing after loading a checkpoint
// https://github.com/yugecin/opsu-dance/issues/130
if (!Options.isExperimentalSliderShrinking())
mergedSlider = null;
// initialize merged slider structures
if (mergedSlider == null) {
List<Vec2f> curvePoints = new ArrayList<Vec2f>();
for (GameObject gameObject : gameObjects) {
if (gameObject instanceof Slider) {
Slider slider = (Slider) gameObject;
slider.baseSliderFrom = curvePoints.size();
curvePoints.addAll(Arrays.asList(slider.getCurve().getCurvePoints()));
}
}
if (!curvePoints.isEmpty())
this.mergedSlider = new FakeCombinedCurve(curvePoints.toArray(new Vec2f[curvePoints.size()]));
} else {
int base = 0;
for (GameObject gameObject : gameObjects) {
if (gameObject instanceof Slider) {
Slider slider = (Slider) gameObject;
slider.baseSliderFrom = base;
base += slider.getCurve().getCurvePoints().length;
}
}
}
}
/**
* Adds points in the merged slider to render.
* @param from the start index to render
* @param to the end index to render
*/
public void addMergedSliderPointsToRender(int from, int to) {
mergedSlider.addRange(from, to);
}
/** Returns whether there are any more objects remaining in the map. */
private boolean hasMoreObjects() {
return objectIndex < gameObjects.length || !passedObjects.isEmpty();
}
/** Returns the current pitch. */
private float getCurrentPitch() {
float base = (Options.getFixedSpeed() > 0f) ? Options.getFixedSpeed() : 1f;
return base * GameMod.getSpeedMultiplier() * playbackSpeed.getModifier();
}
/**
* Returns true if the coordinates are within the music position bar bounds.
* @param cx the x coordinate
* @param cy the y coordinate
*/
private boolean musicPositionBarContains(float cx, float cy) {
return ((cx > musicBarX && cx < musicBarX + musicBarWidth) &&
(cy > musicBarY && cy < musicBarY + musicBarHeight));
}
/**
* Adjusts the beatmap's local music offset.
* @param sign the sign (multiplier)
*/
private void adjustLocalMusicOffset(int sign) {
if (pauseTime > -1) {
UI.getNotificationManager().sendBarNotification("Offset can only be changed while game is not paused.");
return;
}
boolean alt = input.isKeyDown(Input.KEY_LALT) || input.isKeyDown(Input.KEY_RALT);
int diff = sign * (alt ? 1 : 5);
int newOffset = Utils.clamp(beatmap.localMusicOffset + diff, -1000, 1000);
UI.getNotificationManager().sendBarNotification(String.format("Local beatmap offset set to %dms", newOffset));
if (beatmap.localMusicOffset != newOffset) {
beatmap.localMusicOffset = newOffset;
BeatmapDB.updateLocalOffset(beatmap);
}
}
/**
* Plays a sound, unless gameplay sounds are disabled.
* @param s the sound effect
*/
private void playSoundEffect(SoundEffect s) {
if (!Options.isGameplaySoundDisabled())
SoundController.playSound(s);
}
}
| itdelatrisu/opsu | src/itdelatrisu/opsu/states/Game.java |
180,218 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.googlejavaformat;
import static java.lang.Math.max;
import static java.lang.Math.min;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.googlejavaformat.Indent.Const;
import com.google.googlejavaformat.Input.Tok;
import com.google.googlejavaformat.Input.Token;
import com.google.googlejavaformat.Output.BreakTag;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* An {@code OpsBuilder} creates a list of {@link Op}s, which is turned into a {@link Doc} by {@link
* DocBuilder}.
*/
public final class OpsBuilder {
/** @return the actual size of the AST node at position, including comments. */
public int actualSize(int position, int length) {
Token startToken = input.getPositionTokenMap().get(position);
int start = startToken.getTok().getPosition();
for (Tok tok : startToken.getToksBefore()) {
if (tok.isComment()) {
start = min(start, tok.getPosition());
}
}
Token endToken = input.getPositionTokenMap().get(position + length - 1);
int end = endToken.getTok().getPosition() + endToken.getTok().length();
for (Tok tok : endToken.getToksAfter()) {
if (tok.isComment()) {
end = max(end, tok.getPosition() + tok.length());
}
}
return end - start;
}
/** @return the start column of the token at {@code position}, including leading comments. */
public Integer actualStartColumn(int position) {
Token startToken = input.getPositionTokenMap().get(position);
int start = startToken.getTok().getPosition();
int line0 = input.getLineNumber(start);
for (Tok tok : startToken.getToksBefore()) {
if (line0 != input.getLineNumber(tok.getPosition())) {
return start;
}
if (tok.isComment()) {
start = min(start, tok.getPosition());
}
}
return start;
}
/** A request to add or remove a blank line in the output. */
public abstract static class BlankLineWanted {
/** Always emit a blank line. */
public static final BlankLineWanted YES = new SimpleBlankLine(Optional.of(true));
/** Never emit a blank line. */
public static final BlankLineWanted NO = new SimpleBlankLine(Optional.of(false));
/**
* Explicitly preserve blank lines from the input (e.g. before the first member in a class
* declaration). Overrides conditional blank lines.
*/
public static final BlankLineWanted PRESERVE =
new SimpleBlankLine(/* wanted= */ Optional.empty());
/** Is the blank line wanted? */
public abstract Optional<Boolean> wanted();
/** Merge this blank line request with another. */
public abstract BlankLineWanted merge(BlankLineWanted wanted);
/** Emit a blank line if the given break is taken. */
public static BlankLineWanted conditional(BreakTag breakTag) {
return new ConditionalBlankLine(ImmutableList.of(breakTag));
}
private static final class SimpleBlankLine extends BlankLineWanted {
private final Optional<Boolean> wanted;
SimpleBlankLine(Optional<Boolean> wanted) {
this.wanted = wanted;
}
@Override
public Optional<Boolean> wanted() {
return wanted;
}
@Override
public BlankLineWanted merge(BlankLineWanted other) {
return this;
}
}
private static final class ConditionalBlankLine extends BlankLineWanted {
private final ImmutableList<BreakTag> tags;
ConditionalBlankLine(Iterable<BreakTag> tags) {
this.tags = ImmutableList.copyOf(tags);
}
@Override
public Optional<Boolean> wanted() {
for (BreakTag tag : tags) {
if (tag.wasBreakTaken()) {
return Optional.of(true);
}
}
return Optional.empty();
}
@Override
public BlankLineWanted merge(BlankLineWanted other) {
if (!(other instanceof ConditionalBlankLine)) {
return other;
}
return new ConditionalBlankLine(
Iterables.concat(this.tags, ((ConditionalBlankLine) other).tags));
}
}
}
private final Input input;
private final List<Op> ops = new ArrayList<>();
private final Output output;
private static final Indent.Const ZERO = Indent.Const.ZERO;
private int tokenI = 0;
private int inputPosition = Integer.MIN_VALUE;
/** The number of unclosed open ops in the input stream. */
int depth = 0;
/** Add an {@link Op}, and record open/close ops for later validation of unclosed levels. */
public final void add(Op op) {
if (op instanceof OpenOp) {
depth++;
} else if (op instanceof CloseOp) {
depth--;
if (depth < 0) {
throw new AssertionError();
}
}
ops.add(op);
}
/** Add a list of {@link Op}s. */
public final void addAll(List<Op> ops) {
for (Op op : ops) {
add(op);
}
}
/**
* The {@code OpsBuilder} constructor.
*
* @param input the {@link Input}, used for retrieve information from the AST
* @param output the {@link Output}, used here only to record blank-line information
*/
public OpsBuilder(Input input, Output output) {
this.input = input;
this.output = output;
}
/** Get the {@code OpsBuilder}'s {@link Input}. */
public final Input getInput() {
return input;
}
/** Returns the number of unclosed open ops in the input stream. */
public int depth() {
return depth;
}
/**
* Checks that all open ops in the op stream have matching close ops.
*
* @throws FormattingError if any ops were unclosed
*/
public void checkClosed(int previous) {
if (depth != previous) {
throw new FormattingError(diagnostic(String.format("saw %d unclosed ops", depth)));
}
}
/** Create a {@link FormatterDiagnostic} at the current position. */
public FormatterDiagnostic diagnostic(String message) {
return input.createDiagnostic(inputPosition, message);
}
/**
* Sync to position in the input. If we've skipped outputting any tokens that were present in the
* input tokens, output them here and optionally complain.
*
* @param inputPosition the {@code 0}-based input position
*/
public final void sync(int inputPosition) {
if (inputPosition > this.inputPosition) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
int tokensN = tokens.size();
this.inputPosition = inputPosition;
if (tokenI < tokensN && inputPosition > tokens.get(tokenI).getTok().getPosition()) {
// Found a missing input token. Insert it and mark it missing (usually not good).
Input.Token token = tokens.get(tokenI++);
throw new FormattingError(
diagnostic(String.format("did not generate token \"%s\"", token.getTok().getText())));
}
}
}
/** Output any remaining tokens from the input stream (e.g. terminal whitespace). */
public final void drain() {
int inputPosition = input.getText().length() + 1;
if (inputPosition > this.inputPosition) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
int tokensN = tokens.size();
while (tokenI < tokensN && inputPosition > tokens.get(tokenI).getTok().getPosition()) {
Input.Token token = tokens.get(tokenI++);
add(
Doc.Token.make(
token,
Doc.Token.RealOrImaginary.IMAGINARY,
ZERO,
/* breakAndIndentTrailingComment= */ Optional.empty()));
}
}
this.inputPosition = inputPosition;
checkClosed(0);
}
/**
* Open a new level by emitting an {@link OpenOp}.
*
* @param plusIndent the extra indent for the new level
*/
public final void open(Indent plusIndent) {
add(OpenOp.make(plusIndent));
}
/** Close the current level, by emitting a {@link CloseOp}. */
public final void close() {
add(CloseOp.make());
}
/** Return the text of the next {@link Input.Token}, or absent if there is none. */
public final Optional<String> peekToken() {
return peekToken(0);
}
/** Return the text of an upcoming {@link Input.Token}, or absent if there is none. */
public final Optional<String> peekToken(int skip) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
int idx = tokenI + skip;
return idx < tokens.size()
? Optional.of(tokens.get(idx).getTok().getOriginalText())
: Optional.empty();
}
/**
* Returns the {@link Input.Tok}s starting at the current source position, which are satisfied by
* the given predicate.
*/
public ImmutableList<Tok> peekTokens(int startPosition, Predicate<Input.Tok> predicate) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
Preconditions.checkState(
tokens.get(tokenI).getTok().getPosition() == startPosition,
"Expected the current token to be at position %s, found: %s",
startPosition,
tokens.get(tokenI));
ImmutableList.Builder<Tok> result = ImmutableList.builder();
for (int idx = tokenI; idx < tokens.size(); idx++) {
Tok tok = tokens.get(idx).getTok();
if (!predicate.apply(tok)) {
break;
}
result.add(tok);
}
return result.build();
}
/**
* Emit an optional token iff it exists on the input. This is used to emit tokens whose existence
* has been lost in the AST.
*
* @param token the optional token
*/
public final void guessToken(String token) {
token(
token,
Doc.Token.RealOrImaginary.IMAGINARY,
ZERO,
/* breakAndIndentTrailingComment= */ Optional.empty());
}
public final void token(
String token,
Doc.Token.RealOrImaginary realOrImaginary,
Indent plusIndentCommentsBefore,
Optional<Indent> breakAndIndentTrailingComment) {
ImmutableList<? extends Input.Token> tokens = input.getTokens();
if (token.equals(peekToken().orElse(null))) { // Found the input token. Output it.
add(
Doc.Token.make(
tokens.get(tokenI++),
Doc.Token.RealOrImaginary.REAL,
plusIndentCommentsBefore,
breakAndIndentTrailingComment));
} else {
/*
* Generated a "bad" token, which doesn't exist on the input. Drop it, and complain unless
* (for example) we're guessing at an optional token.
*/
if (realOrImaginary.isReal()) {
throw new FormattingError(
diagnostic(
String.format(
"expected token: '%s'; generated %s instead",
peekToken().orElse(null), token)));
}
}
}
/**
* Emit a single- or multi-character op by breaking it into single-character {@link Doc.Token}s.
*
* @param op the operator to emit
*/
public final void op(String op) {
int opN = op.length();
for (int i = 0; i < opN; i++) {
token(
op.substring(i, i + 1),
Doc.Token.RealOrImaginary.REAL,
ZERO,
/* breakAndIndentTrailingComment= */ Optional.empty());
}
}
/** Emit a {@link Doc.Space}. */
public final void space() {
add(Doc.Space.make());
}
/** Emit a {@link Doc.Break}. */
public final void breakOp() {
breakOp(Doc.FillMode.UNIFIED, "", ZERO);
}
/**
* Emit a {@link Doc.Break}.
*
* @param plusIndent extra indent if taken
*/
public final void breakOp(Indent plusIndent) {
breakOp(Doc.FillMode.UNIFIED, "", plusIndent);
}
/** Emit a filled {@link Doc.Break}. */
public final void breakToFill() {
breakOp(Doc.FillMode.INDEPENDENT, "", ZERO);
}
/** Emit a forced {@link Doc.Break}. */
public final void forcedBreak() {
breakOp(Doc.FillMode.FORCED, "", ZERO);
}
/**
* Emit a forced {@link Doc.Break}.
*
* @param plusIndent extra indent if taken
*/
public final void forcedBreak(Indent plusIndent) {
breakOp(Doc.FillMode.FORCED, "", plusIndent);
}
/**
* Emit a {@link Doc.Break}, with a specified {@code flat} value (e.g., {@code " "}).
*
* @param flat the {@link Doc.Break} when not broken
*/
public final void breakOp(String flat) {
breakOp(Doc.FillMode.UNIFIED, flat, ZERO);
}
/**
* Emit a {@link Doc.Break}, with a specified {@code flat} value (e.g., {@code " "}).
*
* @param flat the {@link Doc.Break} when not broken
*/
public final void breakToFill(String flat) {
breakOp(Doc.FillMode.INDEPENDENT, flat, ZERO);
}
/**
* Emit a generic {@link Doc.Break}.
*
* @param fillMode the {@link Doc.FillMode}
* @param flat the {@link Doc.Break} when not broken
* @param plusIndent extra indent if taken
*/
public final void breakOp(Doc.FillMode fillMode, String flat, Indent plusIndent) {
breakOp(fillMode, flat, plusIndent, /* optionalTag= */ Optional.empty());
}
/**
* Emit a generic {@link Doc.Break}.
*
* @param fillMode the {@link Doc.FillMode}
* @param flat the {@link Doc.Break} when not broken
* @param plusIndent extra indent if taken
* @param optionalTag an optional tag for remembering whether the break was taken
*/
public final void breakOp(
Doc.FillMode fillMode, String flat, Indent plusIndent, Optional<BreakTag> optionalTag) {
add(Doc.Break.make(fillMode, flat, plusIndent, optionalTag));
}
private int lastPartialFormatBoundary = -1;
/**
* Make the boundary of a region that can be partially formatted. The boundary will be included in
* the following region, e.g.: [[boundary0, boundary1), [boundary1, boundary2), ...].
*/
public void markForPartialFormat() {
if (lastPartialFormatBoundary == -1) {
lastPartialFormatBoundary = tokenI;
return;
}
if (tokenI == lastPartialFormatBoundary) {
return;
}
Token start = input.getTokens().get(lastPartialFormatBoundary);
Token end = input.getTokens().get(tokenI - 1);
output.markForPartialFormat(start, end);
lastPartialFormatBoundary = tokenI;
}
/**
* Force or suppress a blank line here in the output.
*
* @param wanted whether to force ({@code true}) or suppress {@code false}) the blank line
*/
public final void blankLineWanted(BlankLineWanted wanted) {
output.blankLine(getI(input.getTokens().get(tokenI)), wanted);
}
private static int getI(Input.Token token) {
for (Input.Tok tok : token.getToksBefore()) {
if (tok.getIndex() >= 0) {
return tok.getIndex();
}
}
return token.getTok().getIndex();
}
private static final Doc.Space SPACE = Doc.Space.make();
/**
* Build a list of {@link Op}s from the {@code OpsBuilder}.
*
* @return the list of {@link Op}s
*/
public final ImmutableList<Op> build() {
markForPartialFormat();
// Rewrite the ops to insert comments.
Multimap<Integer, Op> tokOps = ArrayListMultimap.create();
int opsN = ops.size();
for (int i = 0; i < opsN; i++) {
Op op = ops.get(i);
if (op instanceof Doc.Token) {
/*
* Token ops can have associated non-tokens, including comments, which we need to insert.
* They can also cause line breaks, so we insert them before or after the current level,
* when possible.
*/
Doc.Token tokenOp = (Doc.Token) op;
Input.Token token = tokenOp.getToken();
int j = i; // Where to insert toksBefore before.
while (0 < j && ops.get(j - 1) instanceof OpenOp) {
--j;
}
int k = i; // Where to insert toksAfter after.
while (k + 1 < opsN && ops.get(k + 1) instanceof CloseOp) {
++k;
}
if (tokenOp.realOrImaginary().isReal()) {
/*
* Regular input token. Copy out toksBefore before token, and toksAfter after it. Insert
* this token's toksBefore at position j.
*/
int newlines = 0; // Count of newlines in a row.
boolean space = false; // Do we need an extra space after a previous "/*" comment?
boolean lastWasComment = false; // Was the last thing we output a comment?
boolean allowBlankAfterLastComment = false;
for (Input.Tok tokBefore : token.getToksBefore()) {
if (tokBefore.isNewline()) {
newlines++;
} else if (tokBefore.isComment()) {
tokOps.put(
j,
Doc.Break.make(
tokBefore.isSlashSlashComment() ? Doc.FillMode.FORCED : Doc.FillMode.UNIFIED,
"",
tokenOp.getPlusIndentCommentsBefore()));
tokOps.putAll(j, makeComment(tokBefore));
space = tokBefore.isSlashStarComment();
newlines = 0;
lastWasComment = true;
if (tokBefore.isJavadocComment()) {
tokOps.put(j, Doc.Break.makeForced());
}
allowBlankAfterLastComment =
tokBefore.isSlashSlashComment()
|| (tokBefore.isSlashStarComment() && !tokBefore.isJavadocComment());
}
}
if (allowBlankAfterLastComment && newlines > 1) {
// Force a line break after two newlines in a row following a line or block comment
output.blankLine(token.getTok().getIndex(), BlankLineWanted.YES);
}
if (lastWasComment && newlines > 0) {
tokOps.put(j, Doc.Break.makeForced());
} else if (space) {
tokOps.put(j, SPACE);
}
// Now we've seen the Token; output the toksAfter.
for (Input.Tok tokAfter : token.getToksAfter()) {
if (tokAfter.isComment()) {
boolean breakAfter =
tokAfter.isJavadocComment()
|| (tokAfter.isSlashStarComment()
&& tokenOp.breakAndIndentTrailingComment().isPresent());
if (breakAfter) {
tokOps.put(
k + 1,
Doc.Break.make(
Doc.FillMode.FORCED,
"",
tokenOp.breakAndIndentTrailingComment().orElse(Const.ZERO)));
} else {
tokOps.put(k + 1, SPACE);
}
tokOps.putAll(k + 1, makeComment(tokAfter));
if (breakAfter) {
tokOps.put(k + 1, Doc.Break.make(Doc.FillMode.FORCED, "", ZERO));
}
}
}
} else {
/*
* This input token was mistakenly not generated for output. As no whitespace or comments
* were generated (presumably), copy all input non-tokens literally, even spaces and
* newlines.
*/
int newlines = 0;
boolean lastWasComment = false;
for (Input.Tok tokBefore : token.getToksBefore()) {
if (tokBefore.isNewline()) {
newlines++;
} else if (tokBefore.isComment()) {
newlines = 0;
lastWasComment = tokBefore.isComment();
}
if (lastWasComment && newlines > 0) {
tokOps.put(j, Doc.Break.makeForced());
}
tokOps.put(j, Doc.Tok.make(tokBefore));
}
for (Input.Tok tokAfter : token.getToksAfter()) {
tokOps.put(k + 1, Doc.Tok.make(tokAfter));
}
}
}
}
/*
* Construct new list of ops, splicing in the comments. If a comment is inserted immediately
* before a space, suppress the space.
*/
ImmutableList.Builder<Op> newOps = ImmutableList.builder();
boolean afterForcedBreak = false; // Was the last Op a forced break? If so, suppress spaces.
for (int i = 0; i < opsN; i++) {
for (Op op : tokOps.get(i)) {
if (!(afterForcedBreak && op instanceof Doc.Space)) {
newOps.add(op);
afterForcedBreak = isForcedBreak(op);
}
}
Op op = ops.get(i);
if (afterForcedBreak
&& (op instanceof Doc.Space
|| (op instanceof Doc.Break
&& ((Doc.Break) op).getPlusIndent() == 0
&& " ".equals(((Doc) op).getFlat())))) {
continue;
}
newOps.add(op);
if (!(op instanceof OpenOp)) {
afterForcedBreak = isForcedBreak(op);
}
}
for (Op op : tokOps.get(opsN)) {
if (!(afterForcedBreak && op instanceof Doc.Space)) {
newOps.add(op);
afterForcedBreak = isForcedBreak(op);
}
}
return newOps.build();
}
private static boolean isForcedBreak(Op op) {
return op instanceof Doc.Break && ((Doc.Break) op).isForced();
}
private static List<Op> makeComment(Input.Tok comment) {
return comment.isSlashStarComment()
? ImmutableList.of(Doc.Tok.make(comment))
: ImmutableList.of(Doc.Tok.make(comment), Doc.Break.makeForced());
}
@Override
public final String toString() {
return MoreObjects.toStringHelper(this)
.add("input", input)
.add("ops", ops)
.add("output", output)
.add("tokenI", tokenI)
.add("inputPosition", inputPosition)
.toString();
}
}
| google/google-java-format | core/src/main/java/com/google/googlejavaformat/OpsBuilder.java |
180,219 | /* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb_voltpatches.util;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Panel;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
/**
* Class declaration
*
*
* @author ulrivo@users
* @version 1.0.0
*/
// an entry panel to input/edit a record of a sql table
// ZaurusTableForm is constructed with a tableName and a connection
public class ZaurusTableForm extends ScrollPane
implements TextListener, ItemListener, ActionListener {
// connection to database - brought via the constructor
Connection cConn;
DatabaseMetaData dbmeta;
// the name of table for the form
String tableName;
// array holding the components (TextField or Choice) in the GUI
ZaurusComponent[] komponente;
// the columns of the table
String[] columns;
// and their types
short[] columnTypes;
// the names of the primary keys of the table
String[] primaryKeys;
// the position of the primary keys in the table i. e. the column index starting from 0
int[] pkColIndex;
// the names of the imported/foreign keys of the table
// first dimension is running through the constraints, second dim through the keys of one constraint
String[][] importedKeys;
// the position of the imported keys in the table i. e. the column index starting from 0
int[][] imColIndex;
// the names of the tables and columns which are the reference for the imported keys
String[] refTables;
String[][] refColumns;
// the position of the reference keys in the reference table i. e. the column index starting from 0
int[][] refColIndex;
// an array holding array of primary keys values matching the search condition
// first dimension through the results, second dimension running through the primary keys
Object[][] resultRowPKs;
// there is an explicit count because a delete may shrink the result rows
int numberOfResult;
// prepared statement to fetch the required rows
PreparedStatement pStmt;
// pointer into the resultRowPKs
int aktRowNr;
public ZaurusTableForm(String name, Connection con) {
super();
tableName = name;
cConn = con;
this.fetchColumns();
this.fetchPrimaryKeys();
// System.out.print("primaryKeys: ");
// for (int i=0; i<primaryKeys.length;i++) {
// System.out.print(primaryKeys[i]+", ");
// } // end of for (int i=0; i<primaryKeys.length;i++)
// System.out.println();
this.fetchImportedKeys();
this.initGUI();
}
// cancel the change/update of a row - show the row again
public void cancelChanges() {
this.showAktRow();
}
// delete current row, answer special action codes, see comment below
public int deleteRow() {
// build the delete string
String deleteString = "DELETE FROM " + tableName
+ this.generatePKWhere();
PreparedStatement ps = null;
// System.out.println("delete string "+deleteString);
try {
// fill the question marks
ps = cConn.prepareStatement(deleteString);
ps.clearParameters();
int i;
for (int j = 0; j < primaryKeys.length; j++) {
ps.setObject(j + 1, resultRowPKs[aktRowNr][j]);
} // end of for (int i=0; i<primaryKeys.length; i++)
ps.executeUpdate();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
return 0;
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {}
}
// delete the corresponding primary key values from resultRowPKs
numberOfResult--;
for (int i = aktRowNr; i < numberOfResult; i++) {
for (int j = 0; j < primaryKeys.length; j++) {
resultRowPKs[i][j] = resultRowPKs[i + 1][j];
}
}
// there are the following outcomes after deleting aktRowNr:
/*
A B C D E F
no rows left J N N N N N
one row left - J N J N N
deleted row was the last row - J J N N N
deleted row was the pre-last - - - - J N
first D X + D + *
. D X X D D
. D X +
last X
new numberOfResult 0 1 2 1 2 2
old aktRowNr 0 1 2 0 1 0
D - deleted row
X - any one row
+ - one or more rows
* - zero or more rows
*/
// A. return to the search panel and tell 'last row deleted' on the status line
// B. show the previous row and disable previous button
// C. show the previous row as akt row
// D. show akt row and disable next button
// E. show akt row and disable next button
// F. show akt row
// these actions reduce to the following actions for ZaurusEditor:
// 1. show search panel
// 2. disable previous button
// 3. disable next button
// 4. do nothing
// and 1,2,3,4 are the possible return codes
int actionCode;
if (numberOfResult == 0) {
// case A
actionCode = 1;
ZaurusEditor.printStatus("Last row was deleted.");
return actionCode;
} else if (numberOfResult == aktRowNr) {
// B or C
// new aktRow is previous row
aktRowNr--;
if (aktRowNr == 0) {
// B
actionCode = 2;
} else {
// C
actionCode = 4;
} // end of if (aktRowNr == 0)
} else {
// D, E, F
if (numberOfResult >= 2 && aktRowNr < numberOfResult - 1) {
// F
actionCode = 4;
} else {
actionCode = 3;
} // end of else
}
this.showAktRow();
ZaurusEditor.printStatus("Row was deleted.");
return actionCode;
}
// answer a String containing a String list of primary keys i. e. "pk1, pk2, pk3"
public String getPrimaryKeysString() {
String result = "";
for (int i = 0; i < primaryKeys.length; i++) {
if (result != "") {
result += ", ";
}
result += primaryKeys[i];
} // end of for (int i=0; i<primaryKeys.length; i++)
return result;
}
// open the panel to insert a new row into the table
public void insertNewRow() {
// reset all fields
for (int i = 0; i < komponente.length; i++) {
komponente[i].clearContent();
} // end of for (int i=0; i<komponente.length; i++)
// reset the field for the primary keys
for (int i = 0; i < primaryKeys.length; i++) {
komponente[pkColIndex[i]].setEditable(true);
}
ZaurusEditor.printStatus("enter a new row for table " + tableName);
}
// show next row
// answer true, if there is after the next row another row
public boolean nextRow() {
if (aktRowNr + 1 == numberOfResult) {
return false;
}
aktRowNr++;
this.showAktRow();
return (aktRowNr + 1 < numberOfResult);
}
// show prev row
// answer true, if there is previous the previous row another row
public boolean prevRow() {
if (aktRowNr == 0) {
return false;
}
aktRowNr--;
this.showAktRow();
return (aktRowNr > 0);
}
// save all changes which are be made in the textfelder to the database
// answer true, if the update succeeds
public boolean saveChanges() {
// the initial settings of the textfields counts with one
// so a real change by the user needs as many changes as there are columns
// System.out.print("Anderungen in den Feldern: ");
// there are changes to the database
// memorize all columns which have been changed
int[] changedColumns = new int[columns.length];
int countChanged = 0;
// build the update string
String updateString = "";
for (int i = 0; i < columns.length; i++) {
if (komponente[i].hasChanged()) {
if (updateString != "") {
updateString += ", ";
}
updateString += columns[i] + "=?";
changedColumns[countChanged++] = i;
}
} // end of for (int i=0; i<columns.length; i++)
if (countChanged > 0) {
updateString = "UPDATE " + tableName + " SET " + updateString
+ this.generatePKWhere();
PreparedStatement ps = null;
// System.out.println("update "+updateString);
try {
// fill the question marks
ps = cConn.prepareStatement(updateString);
ps.clearParameters();
int i;
for (i = 0; i < countChanged; i++) {
ps.setObject(i + 1,
komponente[changedColumns[i]].getContent());
// System.out.print(" changed feld "+komponente[changedColumns[i]].getContent());
} // end of for (int i=0; i<countChanged; i++)
// System.out.println();
for (int j = 0; j < primaryKeys.length; j++) {
ps.setObject(i + j + 1, resultRowPKs[aktRowNr][j]);
} // end of for (int i=0; i<primaryKeys.length; i++)
ps.executeUpdate();
ZaurusEditor.printStatus("changed row was saved to table "
+ tableName);
return true;
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
return false;
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {}
}
} else {
// System.out.println("no changes");
return true;
} // end of if (changed)
}
// save a new row
// answer true, if saving succeeds
public boolean saveNewRow() {
// check the fields of the primary keys whether one is empty
boolean onePKempty = false;
int tmp;
PreparedStatement ps = null;
for (tmp = 0; tmp < primaryKeys.length; tmp++) {
if (komponente[pkColIndex[tmp]].getContent().equals("")) {
onePKempty = true;
break;
}
}
if (onePKempty) {
komponente[pkColIndex[tmp]].requestFocus();
ZaurusEditor.printStatus("no value for primary key "
+ primaryKeys[tmp]);
return false;
} // end of if (onePKempty)
// build the insert string
String insertString = "INSERT INTO " + tableName + " VALUES(";
for (int j = 0; j < columns.length; j++) {
if (j > 0) {
insertString += ", ";
}
insertString += "?";
} // end of for (int i=0; i<columns.length; i++)
insertString += ")";
// System.out.println("insert string "+insertString);
try {
// fill the question marks
ps = cConn.prepareStatement(insertString);
ps.clearParameters();
int i;
for (i = 0; i < columns.length; i++) {
ps.setObject(i + 1, komponente[i].getContent());
}
ps.executeUpdate();
ZaurusEditor.printStatus("new row was saved to table "
+ tableName);
return true;
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
return false;
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {}
}
}
// read all primary key values into resultRowPKs for the rows which meet the search condition i. e.
// which contains the search words
// answer the number of found rows, -1 if there is an SQL exception
public int searchRows(String[] words, boolean allWords,
boolean ignoreCase, boolean noMatchWhole) {
// System.out.print("search in " + tableName + " for: ");
// for (int i=0; i < words.length; i++) {
// System.out.print(words[i]+", ");
// }
// System.out.println("allWords = "+allWords+", ignoreCase = "+ignoreCase+", noMatchWhole= "+noMatchWhole);
String where = this.generateWhere(words, allWords, ignoreCase,
noMatchWhole);
Vector temp = new Vector(20);
Statement stmt = null;
try {
stmt = cConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT "
+ this.getPrimaryKeysString()
+ " FROM " + tableName + where);
while (rs.next()) {
Object[] pkValues = new Object[primaryKeys.length];
for (int i = 0; i < primaryKeys.length; i++) {
pkValues[i] = rs.getObject(pkColIndex[i] + 1);
} // end of for (int i=0; i<primaryKeys.length; i++)
temp.addElement(pkValues);
}
rs.close();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
return -1;
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {}
}
resultRowPKs = new Object[temp.size()][primaryKeys.length];
numberOfResult = temp.size();
for (int i = 0; i < primaryKeys.length; i++) {
for (int j = 0; j < temp.size(); j++) {
resultRowPKs[j][i] = ((Object[]) temp.elementAt(j))[i];
} // end of for (int j=0; j<temp.size(); j++)
} // end of for (int i=0; i<primaryKeys.length; i++)
// prepare statement for fetching the result rows for later use
String stmtString = "SELECT * FROM " + tableName;
try {
pStmt = cConn.prepareStatement(stmtString
+ this.generatePKWhere());
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
} // end of try-catch
// System.out.println("prepared statement: "+stmtString);
if (numberOfResult > 0) {
this.disablePKFields();
aktRowNr = 0;
this.showAktRow();
} // end of if (numberOfResult > 0)
// System.out.println("number of rows: "+numberOfResult);
return numberOfResult;
}
public void actionPerformed(ActionEvent e) {}
public void textValueChanged(TextEvent e) {
for (int i = 0; i < columns.length; i++) {
if (komponente[i] == e.getSource()) {
komponente[i].setChanged();
break;
}
}
}
public void itemStateChanged(ItemEvent e) {
for (int i = 0; i < columns.length; i++) {
if (komponente[i] == e.getSource()) {
komponente[i].setChanged();
break;
}
}
}
// ******************************************************
// private methods
// ******************************************************
// set all fields for primary keys to not editable
private void disablePKFields() {
for (int i = 0; i < primaryKeys.length; i++) {
komponente[pkColIndex[i]].setEditable(false);
} // end of for (int i=0; i<columns.length; i++)
}
// fetch all values from a table and a column
// fill the ZaurusChoice zc with the row values for the Choice
// and the column values as values
private void fillZChoice(ZaurusChoice zc, String tab, String col) {
Statement stmt = null;
try {
if (cConn == null) {
return;
}
stmt = cConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM " + tab
+ " ORDER BY " + col);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int colIndex = rs.findColumn(col);
while (rs.next()) {
String tmp = "";
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) {
tmp += "; ";
}
tmp += rs.getString(i);
} // end of for (int i=1; i<=numberOfColumns; i++)
zc.add(tmp, rs.getString(colIndex));
}
rs.close();
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {}
}
}
// fetch all column names
private void fetchColumns() {
Vector temp = new Vector(20);
Vector tempType = new Vector(20);
try {
if (cConn == null) {
return;
}
if (dbmeta == null) {
dbmeta = cConn.getMetaData();
}
ResultSet colList = dbmeta.getColumns(null, null, tableName, "%");
while (colList.next()) {
temp.addElement(colList.getString("COLUMN_NAME"));
tempType.addElement(new Short(colList.getShort("DATA_TYPE")));
}
colList.close();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
}
columns = new String[temp.size()];
temp.copyInto(columns);
columnTypes = new short[temp.size()];
for (int i = 0; i < columnTypes.length; i++) {
columnTypes[i] = ((Short) tempType.elementAt(i)).shortValue();
}
}
// fetch the imported keys i.e. columns which reference to foreign keys in other tables
private void fetchImportedKeys() {
Vector imKeys = new Vector(20);
Vector imKeyNames = null;
Vector refTabs = new Vector(20);
Vector refCols = new Vector(20);
Vector refColNames = null;
try {
if (cConn == null) {
return;
}
if (dbmeta == null) {
dbmeta = cConn.getMetaData();
}
ResultSet colList = dbmeta.getImportedKeys(null, null, tableName);
String pkTable, pkColumn, fkColumn;
int keySeq;
while (colList.next()) {
pkTable = colList.getString("PKTABLE_NAME");
pkColumn = colList.getString("PKCOLUMN_NAME");
fkColumn = colList.getString("FKCOLUMN_NAME");
keySeq = colList.getInt("KEY_SEQ");
if (keySeq == 1) {
if (imKeyNames != null) {
imKeys.addElement(imKeyNames);
refCols.addElement(refColNames);
} // end of if (exKeyNames != null)
imKeyNames = new Vector(20);
refColNames = new Vector(20);
refTabs.addElement(pkTable);
} // end of if (keySeq == 1)
imKeyNames.addElement(fkColumn);
refColNames.addElement(pkColumn);
}
if (imKeyNames != null) {
imKeys.addElement(imKeyNames);
refCols.addElement(refColNames);
} // end of if (exKeyNames != null)
colList.close();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
}
// System.out.println("Imported Keys of "+tableName);
int numberOfConstraints = imKeys.size();
importedKeys = new String[numberOfConstraints][];
imColIndex = new int[numberOfConstraints][];
refTables = new String[numberOfConstraints];
refColumns = new String[numberOfConstraints][];
refColIndex = new int[numberOfConstraints][];
for (int i = 0; i < numberOfConstraints; i++) {
Vector keys = (Vector) imKeys.elementAt(i);
Vector cols = (Vector) refCols.elementAt(i);
int numberOfKeys = keys.size();
importedKeys[i] = new String[numberOfKeys];
imColIndex[i] = new int[numberOfKeys];
refColumns[i] = new String[numberOfKeys];
refColIndex[i] = new int[numberOfKeys];
refTables[i] = (String) refTabs.elementAt(i);
// System.out.println("reference table "+refTables[i]);
for (int j = 0; j < numberOfKeys; j++) {
importedKeys[i][j] = (String) keys.elementAt(j);
imColIndex[i][j] = this.getColIndex(importedKeys[i][j]);
refColumns[i][j] = (String) cols.elementAt(j);
refColIndex[i][j] = this.getColIndex(refColumns[i][j],
refTables[i]);
// System.out.println(" importedKeys "+importedKeys[i][j]+"(Index: "+imColIndex[i][j]+") refColumns "+refColumns[i][j]+"(Index: "+refColIndex[i][j]+")");
} // end of for (int j=0; j<numberOfKeys; j++)
}
}
private void fetchPrimaryKeys() {
Vector temp = new Vector(20);
try {
if (cConn == null) {
return;
}
if (dbmeta == null) {
dbmeta = cConn.getMetaData();
}
ResultSet colList = dbmeta.getPrimaryKeys(null, null, tableName);
while (colList.next()) {
temp.addElement(colList.getString("COLUMN_NAME"));
}
colList.close();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
}
primaryKeys = new String[temp.size()];
temp.copyInto(primaryKeys);
pkColIndex = new int[primaryKeys.length];
for (int i = 0; i < primaryKeys.length; i++) {
pkColIndex[i] = this.getColIndex(primaryKeys[i]);
} // end of for (int i=0; i<primaryKeys.length; i++)
}
private String generatePKWhere() {
String stmtString = " WHERE ";
for (int i = 0; i < primaryKeys.length; i++) {
if (i > 0) {
stmtString += " AND ";
}
stmtString += primaryKeys[i] + "=?";
} // end of for (int i=0; i<primaryKeys.length; i++)
return stmtString;
}
// generate the Where-condition for the words
private String generateWhere(String[] words, boolean allWords,
boolean ignoreCase, boolean noMatchWhole) {
String result = "";
// if all words must match use AND between the different conditions
String join;
if (allWords) {
join = " AND ";
} else {
join = " OR ";
} // end of else
for (int wordInd = 0; wordInd < words.length; wordInd++) {
String oneCondition = "";
for (int col = 0; col < columns.length; col++) {
if (oneCondition != "") {
oneCondition += " OR ";
}
if (ignoreCase) {
if (noMatchWhole) {
oneCondition += "LOWER(" + columns[col] + ") LIKE '%"
+ words[wordInd].toLowerCase() + "%'";
} else {
oneCondition += "LOWER(" + columns[col] + ") LIKE '"
+ words[wordInd].toLowerCase() + "'";
}
} else {
if (noMatchWhole) {
oneCondition += columns[col] + " LIKE '%"
+ words[wordInd] + "%'";
} else {
oneCondition += columns[col] + " LIKE '"
+ words[wordInd] + "'";
}
}
}
if (result != "") {
result += join;
}
result += "(" + oneCondition + ")";
}
if (result != "") {
result = " WHERE " + result;
} // end of if (result != "")
// System.out.println("result: "+result);
return result;
}
// answer the index of the column named name in the actual table
private int getColIndex(String name) {
for (int i = 0; i < columns.length; i++) {
if (name.equals(columns[i])) {
return i;
} // end of if (name.equals(columns[i]))
} // end of for (int i=0; i<columns.length; i++)
return -1;
}
// answer the index of the column named colName in the table tabName
private int getColIndex(String colName, String tabName) {
int ordPos = 0;
try {
if (cConn == null) {
return -1;
}
if (dbmeta == null) {
dbmeta = cConn.getMetaData();
}
ResultSet colList = dbmeta.getColumns(null, null, tabName,
colName);
colList.next();
ordPos = colList.getInt("ORDINAL_POSITION");
colList.close();
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
}
return ordPos - 1;
}
// answer the index of the constraint for the column index
// answer -1, if the column is not part of any constraint
private int getConstraintIndex(int colIndex) {
for (int i = 0; i < imColIndex.length; i++) {
for (int j = 0; j < imColIndex[i].length; j++) {
if (colIndex == imColIndex[i][j]) {
return i;
} // end of if (col == imColIndex[i][j])
} // end of for (int j=0; j<imColIndex[i].length; j++)
} // end of for (int i=0; i<imColIndex.length; i++)
return -1;
}
private void initGUI() {
Panel pEntry = new Panel();
pEntry.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(3, 3, 3, 3);
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = c.weighty = 1;
c.anchor = GridBagConstraints.WEST;
komponente = new ZaurusComponent[columns.length];
for (int i = 0; i < columns.length; i++) {
c.gridy = i;
c.gridx = 0;
pEntry.add(new Label((String) columns[i]), c);
c.gridx = 1;
int constraint = this.getConstraintIndex(i);
if (constraint >= 0 && imColIndex[constraint].length == 1) {
// we use ony foreign keys with one index
ZaurusChoice tmp = new ZaurusChoice();
this.fillZChoice(tmp, refTables[constraint],
refColumns[constraint][0]);
tmp.addItemListener(this);
komponente[i] = tmp;
pEntry.add(tmp, c);
} else if (columnTypes[i] == java.sql.Types.DATE) {
// System.out.println("hier gibt es eine Date-Spalte namens "+columns[i]);
ZaurusTextField tmp = new ZaurusTextField(8);
tmp.addTextListener(this);
pEntry.add(tmp, c);
komponente[i] = tmp;
} else {
ZaurusTextField tmp = new ZaurusTextField(5);
tmp.addTextListener(this);
pEntry.add(tmp, c);
komponente[i] = tmp;
}
komponente[i].setEditable(true);
}
this.add(pEntry);
}
// get and show the values of the actual row in the GUI
private void showAktRow() {
try {
pStmt.clearParameters();
for (int i = 0; i < primaryKeys.length; i++) {
pStmt.setObject(i + 1, resultRowPKs[aktRowNr][i]);
} // end of for (int i=0; i<primaryKeys.length; i++)
ResultSet rs = pStmt.executeQuery();
rs.next();
for (int i = 0; i < columns.length; i++) {
komponente[i].setContent(rs.getString(i + 1));
} // end of for (int i=0; i<primaryKeys.length; i++)
rs.close();
} catch (SQLException e) {
ZaurusEditor.printStatus("SQL Exception: " + e.getMessage());
} // end of try-catch
for (int i = 0; i < columns.length; i++) {
komponente[i].clearChanges();
}
}
}
| doytsujin/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/util/ZaurusTableForm.java |
180,220 | /*
* Copyright 2017 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.client;
import static java.util.Objects.requireNonNull;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Streams;
import com.linecorp.armeria.client.endpoint.EndpointGroup;
import com.linecorp.armeria.common.Scheme;
import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.util.AsyncCloseableSupport;
import com.linecorp.armeria.common.util.ReleasableHolder;
import com.linecorp.armeria.common.util.ShutdownHooks;
import io.micrometer.core.instrument.MeterRegistry;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.resolver.AddressResolverGroup;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import io.netty.util.ResourceLeakTracker;
/**
* A {@link ClientFactory} which combines all discovered {@link ClientFactory} implementations.
*
* <h2>How are the {@link ClientFactory}s discovered?</h2>
*
* <p>{@link DefaultClientFactory} looks up the {@link ClientFactoryProvider}s available in the current JVM
* using Java SPI (Service Provider Interface). The {@link ClientFactoryProvider} implementations will create
* the {@link ClientFactory} implementations.
*/
final class DefaultClientFactory implements ClientFactory {
private static final Logger logger = LoggerFactory.getLogger(DefaultClientFactory.class);
private static final ResourceLeakDetector<ClientFactory> leakDetector =
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ClientFactory.class);
private static volatile boolean shutdownHookDisabled;
static final DefaultClientFactory DEFAULT =
(DefaultClientFactory) ClientFactory.builder().build();
static final DefaultClientFactory INSECURE =
(DefaultClientFactory) ClientFactory.builder().tlsNoVerify().build();
static {
if (DefaultClientFactory.class.getClassLoader() == ClassLoader.getSystemClassLoader()) {
try {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
if (!shutdownHookDisabled) {
ClientFactory.closeDefault();
}
}));
} catch (IllegalStateException e) {
logger.debug("Skipped adding a shutdown hook to the DefaultClientFactory.", e);
}
}
}
static void disableShutdownHook0() {
shutdownHookDisabled = true;
}
private final HttpClientFactory httpClientFactory;
private final Multimap<Scheme, ClientFactory> clientFactories;
private final List<ClientFactory> clientFactoriesToClose;
private final AsyncCloseableSupport closeable = AsyncCloseableSupport.of(this::closeAsync);
@Nullable
private final ResourceLeakTracker<ClientFactory> leakTracker = leakDetector.track(this);
DefaultClientFactory(HttpClientFactory httpClientFactory) {
this.httpClientFactory = httpClientFactory;
final List<ClientFactory> availableClientFactories = new ArrayList<>();
// Give priority to custom client factories.
Streams.stream(ServiceLoader.load(ClientFactoryProvider.class,
DefaultClientFactory.class.getClassLoader()))
.map(provider -> provider.newFactory(httpClientFactory))
.forEach(availableClientFactories::add);
availableClientFactories.add(httpClientFactory);
final ImmutableListMultimap.Builder<Scheme, ClientFactory> builder = ImmutableListMultimap.builder();
for (ClientFactory f : availableClientFactories) {
f.supportedSchemes().forEach(s -> builder.put(s, f));
}
clientFactories = builder.build();
clientFactoriesToClose = ImmutableList.copyOf(availableClientFactories).reverse();
}
@Override
public Set<Scheme> supportedSchemes() {
return clientFactories.keySet();
}
@Override
public EventLoopGroup eventLoopGroup() {
return httpClientFactory.eventLoopGroup();
}
@Override
public Supplier<EventLoop> eventLoopSupplier() {
return httpClientFactory.eventLoopSupplier();
}
@Override
public ReleasableHolder<EventLoop> acquireEventLoop(SessionProtocol sessionProtocol,
EndpointGroup endpointGroup,
@Nullable Endpoint endpoint) {
return httpClientFactory.acquireEventLoop(sessionProtocol, endpointGroup, endpoint);
}
@Override
public MeterRegistry meterRegistry() {
return httpClientFactory.meterRegistry();
}
@Override
@Deprecated
public void setMeterRegistry(MeterRegistry meterRegistry) {
httpClientFactory.setMeterRegistry(meterRegistry);
}
@Override
public int numConnections() {
return httpClientFactory.numConnections();
}
@Override
public ClientFactoryOptions options() {
return httpClientFactory.options();
}
@Override
public Object newClient(ClientBuilderParams params) {
validateParams(params);
final Scheme scheme = params.scheme();
final Class<?> clientType = params.clientType();
for (ClientFactory factory : clientFactories.get(scheme)) {
if (factory.isClientTypeSupported(clientType)) {
return factory.newClient(params);
}
}
// Since we passed validation, there should have been at least 1 factory for this scheme,
// but for some reason none of these passed the filter.
throw new IllegalStateException(
"No ClientFactory for scheme: " + scheme + " matched clientType: " + clientType);
}
@Override
public <T> T unwrap(Object client, Class<T> type) {
final T params = ClientFactory.super.unwrap(client, type);
if (params != null) {
return params;
}
for (ClientFactory factory : clientFactories.values()) {
final T p = factory.unwrap(client, type);
if (p != null) {
return p;
}
}
return null;
}
@Override
public ClientFactory unwrap() {
return httpClientFactory;
}
@Nullable
@Override
public <T> T as(Class<T> type) {
requireNonNull(type, "type");
T result = ClientFactory.super.as(type);
if (result != null) {
return result;
}
for (ClientFactory f : clientFactories.values()) {
result = f.as(type);
if (result != null) {
return result;
}
}
return null;
}
@Override
public boolean isClosing() {
return closeable.isClosing();
}
@Override
public boolean isClosed() {
return closeable.isClosed();
}
@Override
public CompletableFuture<?> whenClosed() {
return closeable.whenClosed();
}
@Override
public CompletableFuture<?> closeAsync() {
return closeAsync(true);
}
CompletableFuture<?> closeAsync(boolean checkDefault) {
if (checkDefault && checkDefault()) {
return whenClosed();
}
return closeable.closeAsync();
}
private void closeAsync(CompletableFuture<?> future) {
if (leakTracker != null) {
leakTracker.close(this);
}
final CompletableFuture<?>[] delegateCloseFutures =
clientFactoriesToClose.stream()
.map(ClientFactory::closeAsync)
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(delegateCloseFutures).handle((unused, cause) -> {
if (cause != null) {
future.completeExceptionally(cause);
} else {
future.complete(null);
}
return null;
});
}
@Override
public void close() {
if (checkDefault()) {
return;
}
closeable.close();
}
@Override
public CompletableFuture<Void> closeOnJvmShutdown(Runnable whenClosing) {
requireNonNull(whenClosing, "whenClosing");
return ShutdownHooks.addClosingTask(this, whenClosing);
}
private boolean checkDefault() {
// The global default should never be closed.
if (this == DEFAULT || this == INSECURE) {
logger.debug("Refusing to close the default {}; must be closed via closeDefault()",
ClientFactory.class.getSimpleName());
return true;
}
return false;
}
@VisibleForTesting
AddressResolverGroup<InetSocketAddress> addressResolverGroup() {
return httpClientFactory.addressResolverGroup();
}
}
| line/armeria | core/src/main/java/com/linecorp/armeria/client/DefaultClientFactory.java |
180,223 | /*
* Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.api.entities;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.channel.concrete.StageChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel;
import net.dv8tion.jda.api.entities.channel.unions.AudioChannelUnion;
import net.dv8tion.jda.api.requests.RestAction;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.OffsetDateTime;
/**
* Represents the voice state of a {@link net.dv8tion.jda.api.entities.Member Member} in a
* {@link net.dv8tion.jda.api.entities.Guild Guild}.
*
* @see Member#getVoiceState()
*/
public interface GuildVoiceState extends ISnowflake
{
/**
* Returns the {@link net.dv8tion.jda.api.JDA JDA} instance of this VoiceState
*
* @return The corresponding JDA instance
*/
@Nonnull
JDA getJDA();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} muted themselves.
*
* @return The User's self-mute status
*/
boolean isSelfMuted();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} deafened themselves.
*
* @return The User's self-deaf status
*/
boolean isSelfDeafened();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} is muted, either
* by choice {@link #isSelfMuted()} or muted by an admin {@link #isGuildMuted()}
*
* @return the Member's mute status
*/
boolean isMuted();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} is deafened, either
* by choice {@link #isSelfDeafened()} or deafened by an admin {@link #isGuildDeafened()}
*
* @return the Member's deaf status
*/
boolean isDeafened();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} got muted by an Admin
*
* @return the Member's guild-mute status
*/
boolean isGuildMuted();
/**
* Returns whether the {@link net.dv8tion.jda.api.entities.Member Member} got deafened by an Admin
*
* @return the Member's guild-deaf status
*/
boolean isGuildDeafened();
/**
* Returns true if this {@link net.dv8tion.jda.api.entities.Member Member} is unable to speak because the
* channel is actively suppressing audio communication. This occurs in
* {@link VoiceChannel VoiceChannels} where the Member either doesn't have
* {@link net.dv8tion.jda.api.Permission#VOICE_SPEAK Permission#VOICE_SPEAK} or if the channel is the
* designated AFK channel.
* <br>This is also used by {@link StageChannel StageChannels} for listeners without speaker approval.
*
* @return True, if this {@link net.dv8tion.jda.api.entities.Member Member's} audio is being suppressed.
*
* @see #getRequestToSpeakTimestamp()
*/
boolean isSuppressed();
/**
* Returns true if this {@link net.dv8tion.jda.api.entities.Member Member} is currently streaming with Go Live.
*
* @return True, if this member is streaming
*/
boolean isStream();
/**
* Returns true if this {@link net.dv8tion.jda.api.entities.Member Member} has their camera turned on.
* <br>This does not include streams! See {@link #isStream()}
*
* @return True, if this member has their camera turned on.
*/
boolean isSendingVideo();
/**
* Returns the current {@link AudioChannelUnion} that the {@link Member} is in.
* If the {@link Member} is currently not connected to a {@link AudioChannel}, this returns null.
*
* @return The AudioChannelUnion that the Member is connected to, or null.
*/
@Nullable
AudioChannelUnion getChannel();
/**
* Returns the {@link Guild} for the {@link Member} that this GuildVoiceState belongs to.
*
* @return the Member's Guild
*/
@Nonnull
Guild getGuild();
/**
* Returns the {@link net.dv8tion.jda.api.entities.Member Member} corresponding to this GuildVoiceState instance
* (BackReference)
*
* @return the Member that holds this GuildVoiceState
*/
@Nonnull
Member getMember();
/**
* Used to determine if the {@link Member} is currently connected to an {@link AudioChannel}
* in the {@link Guild} returned from {@link #getGuild()}.
* <br>If this is {@code false}, {@link #getChannel()} will return {@code null}.
*
* @return True, if the {@link Member} is currently connected to an {@link AudioChannel} in this {@link Guild}
*/
boolean inAudioChannel();
/**
* The Session-Id for this VoiceState
*
* @return The Session-Id
*/
@Nullable
String getSessionId();
/**
* The time at which the user requested to speak.
* <br>This is used for {@link StageChannel StageChannels} and can only be approved by members with {@link net.dv8tion.jda.api.Permission#VOICE_MUTE_OTHERS Permission.VOICE_MUTE_OTHERS} on the channel.
*
* @return The request to speak timestamp, or null if this user didn't request to speak
*/
@Nullable
OffsetDateTime getRequestToSpeakTimestamp();
/**
* Promote the member to speaker.
* <p>This requires a non-null {@link #getRequestToSpeakTimestamp()}.
* You can use {@link #inviteSpeaker()} to invite the member to become a speaker if they haven't requested to speak.
*
* <p>This does nothing if the member is not connected to a {@link StageChannel}.
*
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have {@link net.dv8tion.jda.api.Permission#VOICE_MUTE_OTHERS Permission.VOICE_MUTE_OTHERS}
* in the associated {@link StageChannel}
*
* @return {@link RestAction}
*/
@Nonnull
@CheckReturnValue
RestAction<Void> approveSpeaker();
/**
* Reject this members {@link #getRequestToSpeakTimestamp() request to speak}
* or moves a {@link StageInstance#getSpeakers() speaker} back to the {@link StageInstance#getAudience() audience}.
* <p>This requires a non-null {@link #getRequestToSpeakTimestamp()}.
* The member will have to request to speak again.
*
* <p>This does nothing if the member is not connected to a {@link StageChannel}.
*
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have {@link net.dv8tion.jda.api.Permission#VOICE_MUTE_OTHERS Permission.VOICE_MUTE_OTHERS}
* in the associated {@link StageChannel}
*
* @return {@link RestAction}
*/
@Nonnull
@CheckReturnValue
RestAction<Void> declineSpeaker();
/**
* Invite this member to become a speaker.
*
* <p>This does nothing if the member is not connected to a {@link StageChannel}.
*
* @throws net.dv8tion.jda.api.exceptions.InsufficientPermissionException
* If the currently logged in account does not have {@link net.dv8tion.jda.api.Permission#VOICE_MUTE_OTHERS Permission.VOICE_MUTE_OTHERS}
* in the associated {@link StageChannel}
*
* @return {@link RestAction}
*/
@Nonnull
@CheckReturnValue
RestAction<Void> inviteSpeaker();
}
| discord-jda/JDA | src/main/java/net/dv8tion/jda/api/entities/GuildVoiceState.java |
180,224 | /*
* 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.netbeans.lib.nbjavac.services;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCStringTemplate;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.List;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/**
*
* @author lahvac
*/
public class NBAttr extends Attr {
public static boolean TEST_DO_SINGLE_FAIL;
public static void preRegister(Context context) {
context.put(attrKey, new Context.Factory<Attr>() {
public Attr make(Context c) {
return new NBAttr(c);
}
});
}
private final CancelService cancelService;
private final NBResolve rs;
private final TreeMaker tm;
public NBAttr(Context context) {
super(context);
cancelService = CancelService.instance(context);
rs = NBResolve.instance(context);
tm = TreeMaker.instance(context);
}
@Override
public void attribClass(DiagnosticPosition pos, ClassSymbol c) {
cancelService.abortIfCanceled();
if (TEST_DO_SINGLE_FAIL) {
TEST_DO_SINGLE_FAIL = false;
throw new AssertionError("Test requested failure");
}
super.attribClass(pos, c);
}
@Override
public void visitClassDef(JCClassDecl tree) {
cancelService.abortIfCanceled();
super.visitClassDef(tree);
}
@Override
public void visitMethodDef(JCMethodDecl tree) {
cancelService.abortIfCanceled();
super.visitMethodDef(tree);
}
@Override
public void visitBlock(JCBlock tree) {
cancelService.abortIfCanceled();
super.visitBlock(tree);
}
@Override
public void visitVarDef(JCVariableDecl tree) {
//for erroneous "var", make sure the synthetic make.Error() has an invalid/synthetic position:
tm.at(-1);
super.visitVarDef(tree);
}
@Override
public Type attribType(JCTree tree, Env<AttrContext> env) {
cancelService.abortIfCanceled();
return super.attribType(tree, env);
}
@Override
public void visitCatch(JCCatch that) {
super.visitBlock(tm.Block(0, List.of(that.param, that.body)));
}
@Override
public void visitStringTemplate(JCStringTemplate tree) {
//workaround for:
//a) crash when tree.processor is null
//b) crash when the StringTemplate.process method does not exist
//should be removed when javac is improved to be more resilient w.r.t. these errors:
boolean prevInStringTemplate = rs.inStringTemplate;
try {
if (tree.processor == null) {
tree.processor = tm.Erroneous();
}
rs.inStringTemplate = true;
super.visitStringTemplate(tree);
} finally {
rs.inStringTemplate = prevInStringTemplate;
}
}
private boolean fullyAttribute;
private Env<AttrContext> fullyAttributeResult;
protected void breakTreeFound(Env<AttrContext> env) {
if (fullyAttribute) {
fullyAttributeResult = env;
} else {
try {
MethodHandles.lookup()
.findSpecial(Attr.class, "breakTreeFound", MethodType.methodType(void.class, Env.class), NBAttr.class)
.invokeExact(this, env);
} catch (Throwable ex) {
sneakyThrows(ex);
}
}
}
protected void breakTreeFound(Env<AttrContext> env, Type result) {
if (fullyAttribute) {
fullyAttributeResult = env;
} else {
try {
MethodHandles.lookup()
.findSpecial(Attr.class, "breakTreeFound", MethodType.methodType(void.class, Env.class, Type.class), NBAttr.class)
.invokeExact(this, env, result);
} catch (Throwable ex) {
sneakyThrows(ex);
}
}
}
private <T extends Throwable> void sneakyThrows(Throwable t) throws T {
throw (T) t;
}
public Env<AttrContext> attributeAndCapture(JCTree tree, Env<AttrContext> env, JCTree to) {
try {
fullyAttribute = true;
Env<AttrContext> result = tree instanceof JCExpression ?
attribExprToTree((JCExpression) tree, env, to) :
attribStatToTree(tree, env, to);
return fullyAttributeResult != null ? fullyAttributeResult : result;
} finally {
fullyAttribute = false;
}
}
}
| apache/netbeans | java/lib.nbjavac/src/org/netbeans/lib/nbjavac/services/NBAttr.java |
180,227 | package com.linkedin.metadata.restli;
import static com.linkedin.gms.factory.common.LocalEbeanConfigFactory.getListenerToTrackCounts;
import io.ebean.datasource.DataSourceConfig;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class EbeanServerConfig {
@Value("${ebean.username}")
private String ebeanDatasourceUsername;
@Value("${ebean.password}")
private String ebeanDatasourcePassword;
@Value("${ebean.driver}")
private String ebeanDatasourceDriver;
@Value("${ebean.minConnections:1}")
private Integer ebeanMinConnections;
@Value("${ebean.maxInactiveTimeSeconds:120}")
private Integer ebeanMaxInactiveTimeSecs;
@Value("${ebean.maxAgeMinutes:120}")
private Integer ebeanMaxAgeMinutes;
@Value("${ebean.leakTimeMinutes:15}")
private Integer ebeanLeakTimeMinutes;
@Value("${ebean.waitTimeoutMillis:1000}")
private Integer ebeanWaitTimeoutMillis;
@Value("${ebean.autoCreateDdl:false}")
private Boolean ebeanAutoCreate;
@Value("${ebean.postgresUseIamAuth:false}")
private Boolean postgresUseIamAuth;
@Bean("ebeanDataSourceConfig")
@Primary
public DataSourceConfig buildDataSourceConfig(
@Value("${ebean.url}") String dataSourceUrl,
@Qualifier("parseqEngineThreads") int ebeanMaxConnections) {
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUsername(ebeanDatasourceUsername);
dataSourceConfig.setPassword(ebeanDatasourcePassword);
dataSourceConfig.setUrl(dataSourceUrl);
dataSourceConfig.setDriver(ebeanDatasourceDriver);
dataSourceConfig.setMinConnections(ebeanMinConnections);
dataSourceConfig.setMaxConnections(ebeanMaxConnections);
dataSourceConfig.setMaxInactiveTimeSecs(ebeanMaxInactiveTimeSecs);
dataSourceConfig.setMaxAgeMinutes(ebeanMaxAgeMinutes);
dataSourceConfig.setLeakTimeMinutes(ebeanLeakTimeMinutes);
dataSourceConfig.setWaitTimeoutMillis(ebeanWaitTimeoutMillis);
dataSourceConfig.setListener(getListenerToTrackCounts("mce-consumer"));
// Adding IAM auth access for AWS Postgres
if (postgresUseIamAuth) {
Map<String, String> custom = new HashMap<>();
custom.put("wrapperPlugins", "iam");
dataSourceConfig.setCustomProperties(custom);
}
return dataSourceConfig;
}
}
| datahub-project/datahub | metadata-jobs/mce-consumer-job/src/main/java/com/linkedin/metadata/restli/EbeanServerConfig.java |
180,231 | /*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.swing.text.html;
import java.io.*;
import java.util.Hashtable;
import javax.swing.text.AttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
/**
* Constants used in the <code>HTMLDocument</code>. These
* are basically tag and attribute definitions.
*
* @author Timothy Prinzing
* @author Sunita Mani
*
*/
public class HTML {
/**
* Typesafe enumeration for an HTML tag. Although the
* set of HTML tags is a closed set, we have left the
* set open so that people can add their own tag types
* to their custom parser and still communicate to the
* reader.
*/
public static class Tag {
/** @since 1.3 */
public Tag() {}
/**
* Creates a new <code>Tag</code> with the specified <code>id</code>,
* and with <code>causesBreak</code> and <code>isBlock</code>
* set to <code>false</code>.
*
* @param id the id of the new tag
*/
protected Tag(String id) {
this(id, false, false);
}
/**
* Creates a new <code>Tag</code> with the specified <code>id</code>;
* <code>causesBreak</code> and <code>isBlock</code> are defined
* by the user.
*
* @param id the id of the new tag
* @param causesBreak <code>true</code> if this tag
* causes a break to the flow of data
* @param isBlock <code>true</code> if the tag is used
* to add structure to a document
*/
protected Tag(String id, boolean causesBreak, boolean isBlock) {
name = id;
this.breakTag = causesBreak;
this.blockTag = isBlock;
}
/**
* Returns <code>true</code> if this tag is a block
* tag, which is a tag used to add structure to a
* document.
*
* @return <code>true</code> if this tag is a block
* tag, otherwise returns <code>false</code>
*/
public boolean isBlock() {
return blockTag;
}
/**
* Returns <code>true</code> if this tag causes a
* line break to the flow of data, otherwise returns
* <code>false</code>.
*
* @return <code>true</code> if this tag causes a
* line break to the flow of data, otherwise returns
* <code>false</code>
*/
public boolean breaksFlow() {
return breakTag;
}
/**
* Returns <code>true</code> if this tag is pre-formatted,
* which is true if the tag is either <code>PRE</code> or
* <code>TEXTAREA</code>.
*
* @return <code>true</code> if this tag is pre-formatted,
* otherwise returns <code>false</code>
*/
public boolean isPreformatted() {
return (this == PRE || this == TEXTAREA);
}
/**
* Returns the string representation of the
* tag.
*
* @return the <code>String</code> representation of the tag
*/
public String toString() {
return name;
}
/**
* Returns <code>true</code> if this tag is considered to be a paragraph
* in the internal HTML model. <code>false</code> - otherwise.
*
* @return <code>true</code> if this tag is considered to be a paragraph
* in the internal HTML model. <code>false</code> - otherwise.
* @see HTMLDocument.HTMLReader.ParagraphAction
*/
boolean isParagraph() {
return (
this == P
|| this == IMPLIED
|| this == DT
|| this == H1
|| this == H2
|| this == H3
|| this == H4
|| this == H5
|| this == H6
);
}
boolean blockTag;
boolean breakTag;
String name;
boolean unknown;
// --- Tag Names -----------------------------------
public static final Tag A = new Tag("a");
public static final Tag ADDRESS = new Tag("address");
public static final Tag APPLET = new Tag("applet");
public static final Tag AREA = new Tag("area");
public static final Tag B = new Tag("b");
public static final Tag BASE = new Tag("base");
public static final Tag BASEFONT = new Tag("basefont");
public static final Tag BIG = new Tag("big");
public static final Tag BLOCKQUOTE = new Tag("blockquote", true, true);
public static final Tag BODY = new Tag("body", true, true);
public static final Tag BR = new Tag("br", true, false);
public static final Tag CAPTION = new Tag("caption");
public static final Tag CENTER = new Tag("center", true, false);
public static final Tag CITE = new Tag("cite");
public static final Tag CODE = new Tag("code");
public static final Tag DD = new Tag("dd", true, true);
public static final Tag DFN = new Tag("dfn");
public static final Tag DIR = new Tag("dir", true, true);
public static final Tag DIV = new Tag("div", true, true);
public static final Tag DL = new Tag("dl", true, true);
public static final Tag DT = new Tag("dt", true, true);
public static final Tag EM = new Tag("em");
public static final Tag FONT = new Tag("font");
public static final Tag FORM = new Tag("form", true, false);
public static final Tag FRAME = new Tag("frame");
public static final Tag FRAMESET = new Tag("frameset");
public static final Tag H1 = new Tag("h1", true, true);
public static final Tag H2 = new Tag("h2", true, true);
public static final Tag H3 = new Tag("h3", true, true);
public static final Tag H4 = new Tag("h4", true, true);
public static final Tag H5 = new Tag("h5", true, true);
public static final Tag H6 = new Tag("h6", true, true);
public static final Tag HEAD = new Tag("head", true, true);
public static final Tag HR = new Tag("hr", true, false);
public static final Tag HTML = new Tag("html", true, false);
public static final Tag I = new Tag("i");
public static final Tag IMG = new Tag("img");
public static final Tag INPUT = new Tag("input");
public static final Tag ISINDEX = new Tag("isindex", true, false);
public static final Tag KBD = new Tag("kbd");
public static final Tag LI = new Tag("li", true, true);
public static final Tag LINK = new Tag("link");
public static final Tag MAP = new Tag("map");
public static final Tag MENU = new Tag("menu", true, true);
public static final Tag META = new Tag("meta");
/*public*/ static final Tag NOBR = new Tag("nobr");
public static final Tag NOFRAMES = new Tag("noframes", true, true);
public static final Tag OBJECT = new Tag("object");
public static final Tag OL = new Tag("ol", true, true);
public static final Tag OPTION = new Tag("option");
public static final Tag P = new Tag("p", true, true);
public static final Tag PARAM = new Tag("param");
public static final Tag PRE = new Tag("pre", true, true);
public static final Tag SAMP = new Tag("samp");
public static final Tag SCRIPT = new Tag("script");
public static final Tag SELECT = new Tag("select");
public static final Tag SMALL = new Tag("small");
public static final Tag SPAN = new Tag("span");
public static final Tag STRIKE = new Tag("strike");
public static final Tag S = new Tag("s");
public static final Tag STRONG = new Tag("strong");
public static final Tag STYLE = new Tag("style");
public static final Tag SUB = new Tag("sub");
public static final Tag SUP = new Tag("sup");
public static final Tag TABLE = new Tag("table", false, true);
public static final Tag TD = new Tag("td", true, true);
public static final Tag TEXTAREA = new Tag("textarea");
public static final Tag TH = new Tag("th", true, true);
public static final Tag TITLE = new Tag("title", true, true);
public static final Tag TR = new Tag("tr", false, true);
public static final Tag TT = new Tag("tt");
public static final Tag U = new Tag("u");
public static final Tag UL = new Tag("ul", true, true);
public static final Tag VAR = new Tag("var");
/**
* All text content must be in a paragraph element.
* If a paragraph didn't exist when content was
* encountered, a paragraph is manufactured.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag IMPLIED = new Tag("p-implied");
/**
* All text content is labeled with this tag.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag CONTENT = new Tag("content");
/**
* All comments are labeled with this tag.
* <p>
* This is a tag synthesized by the HTML reader.
* Since elements are identified by their tag type,
* we create a some fake tag types to mark the elements
* that were manufactured.
*/
public static final Tag COMMENT = new Tag("comment");
static final Tag allTags[] = {
A, ADDRESS, APPLET, AREA, B, BASE, BASEFONT, BIG,
BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE,
DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME,
FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML,
I, IMG, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU,
META, NOBR, NOFRAMES, OBJECT, OL, OPTION, P, PARAM,
PRE, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, S,
STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA,
TH, TITLE, TR, TT, U, UL, VAR
};
static {
// Force HTMLs static initialize to be loaded.
getTag("html");
}
}
// There is no unique instance of UnknownTag, so we allow it to be
// Serializable.
public static class UnknownTag extends Tag implements Serializable {
/**
* Creates a new <code>UnknownTag</code> with the specified
* <code>id</code>.
* @param id the id of the new tag
*/
public UnknownTag(String id) {
super(id);
}
/**
* Returns the hash code which corresponds to the string
* for this tag.
*/
public int hashCode() {
return toString().hashCode();
}
/**
* Compares this object to the specified object.
* The result is <code>true</code> if and only if the argument is not
* <code>null</code> and is an <code>UnknownTag</code> object
* with the same name.
*
* @param obj the object to compare this tag with
* @return <code>true</code> if the objects are equal;
* <code>false</code> otherwise
*/
public boolean equals(Object obj) {
if (obj instanceof UnknownTag) {
return toString().equals(obj.toString());
}
return false;
}
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
s.defaultWriteObject();
s.writeBoolean(blockTag);
s.writeBoolean(breakTag);
s.writeBoolean(unknown);
s.writeObject(name);
}
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
blockTag = s.readBoolean();
breakTag = s.readBoolean();
unknown = s.readBoolean();
name = (String)s.readObject();
}
}
/**
* Typesafe enumeration representing an HTML
* attribute.
*/
public static final class Attribute {
/**
* Creates a new <code>Attribute</code> with the specified
* <code>id</code>.
*
* @param id the id of the new <code>Attribute</code>
*/
Attribute(String id) {
name = id;
}
/**
* Returns the string representation of this attribute.
* @return the string representation of this attribute
*/
public String toString() {
return name;
}
private String name;
public static final Attribute SIZE = new Attribute("size");
public static final Attribute COLOR = new Attribute("color");
public static final Attribute CLEAR = new Attribute("clear");
public static final Attribute BACKGROUND = new Attribute("background");
public static final Attribute BGCOLOR = new Attribute("bgcolor");
public static final Attribute TEXT = new Attribute("text");
public static final Attribute LINK = new Attribute("link");
public static final Attribute VLINK = new Attribute("vlink");
public static final Attribute ALINK = new Attribute("alink");
public static final Attribute WIDTH = new Attribute("width");
public static final Attribute HEIGHT = new Attribute("height");
public static final Attribute ALIGN = new Attribute("align");
public static final Attribute NAME = new Attribute("name");
public static final Attribute HREF = new Attribute("href");
public static final Attribute REL = new Attribute("rel");
public static final Attribute REV = new Attribute("rev");
public static final Attribute TITLE = new Attribute("title");
public static final Attribute TARGET = new Attribute("target");
public static final Attribute SHAPE = new Attribute("shape");
public static final Attribute COORDS = new Attribute("coords");
public static final Attribute ISMAP = new Attribute("ismap");
public static final Attribute NOHREF = new Attribute("nohref");
public static final Attribute ALT = new Attribute("alt");
public static final Attribute ID = new Attribute("id");
public static final Attribute SRC = new Attribute("src");
public static final Attribute HSPACE = new Attribute("hspace");
public static final Attribute VSPACE = new Attribute("vspace");
public static final Attribute USEMAP = new Attribute("usemap");
public static final Attribute LOWSRC = new Attribute("lowsrc");
public static final Attribute CODEBASE = new Attribute("codebase");
public static final Attribute CODE = new Attribute("code");
public static final Attribute ARCHIVE = new Attribute("archive");
public static final Attribute VALUE = new Attribute("value");
public static final Attribute VALUETYPE = new Attribute("valuetype");
public static final Attribute TYPE = new Attribute("type");
public static final Attribute CLASS = new Attribute("class");
public static final Attribute STYLE = new Attribute("style");
public static final Attribute LANG = new Attribute("lang");
public static final Attribute FACE = new Attribute("face");
public static final Attribute DIR = new Attribute("dir");
public static final Attribute DECLARE = new Attribute("declare");
public static final Attribute CLASSID = new Attribute("classid");
public static final Attribute DATA = new Attribute("data");
public static final Attribute CODETYPE = new Attribute("codetype");
public static final Attribute STANDBY = new Attribute("standby");
public static final Attribute BORDER = new Attribute("border");
public static final Attribute SHAPES = new Attribute("shapes");
public static final Attribute NOSHADE = new Attribute("noshade");
public static final Attribute COMPACT = new Attribute("compact");
public static final Attribute START = new Attribute("start");
public static final Attribute ACTION = new Attribute("action");
public static final Attribute METHOD = new Attribute("method");
public static final Attribute ENCTYPE = new Attribute("enctype");
public static final Attribute CHECKED = new Attribute("checked");
public static final Attribute MAXLENGTH = new Attribute("maxlength");
public static final Attribute MULTIPLE = new Attribute("multiple");
public static final Attribute SELECTED = new Attribute("selected");
public static final Attribute ROWS = new Attribute("rows");
public static final Attribute COLS = new Attribute("cols");
public static final Attribute DUMMY = new Attribute("dummy");
public static final Attribute CELLSPACING = new Attribute("cellspacing");
public static final Attribute CELLPADDING = new Attribute("cellpadding");
public static final Attribute VALIGN = new Attribute("valign");
public static final Attribute HALIGN = new Attribute("halign");
public static final Attribute NOWRAP = new Attribute("nowrap");
public static final Attribute ROWSPAN = new Attribute("rowspan");
public static final Attribute COLSPAN = new Attribute("colspan");
public static final Attribute PROMPT = new Attribute("prompt");
public static final Attribute HTTPEQUIV = new Attribute("http-equiv");
public static final Attribute CONTENT = new Attribute("content");
public static final Attribute LANGUAGE = new Attribute("language");
public static final Attribute VERSION = new Attribute("version");
public static final Attribute N = new Attribute("n");
public static final Attribute FRAMEBORDER = new Attribute("frameborder");
public static final Attribute MARGINWIDTH = new Attribute("marginwidth");
public static final Attribute MARGINHEIGHT = new Attribute("marginheight");
public static final Attribute SCROLLING = new Attribute("scrolling");
public static final Attribute NORESIZE = new Attribute("noresize");
public static final Attribute ENDTAG = new Attribute("endtag");
public static final Attribute COMMENT = new Attribute("comment");
static final Attribute MEDIA = new Attribute("media");
static final Attribute allAttributes[] = {
FACE,
COMMENT,
SIZE,
COLOR,
CLEAR,
BACKGROUND,
BGCOLOR,
TEXT,
LINK,
VLINK,
ALINK,
WIDTH,
HEIGHT,
ALIGN,
NAME,
HREF,
REL,
REV,
TITLE,
TARGET,
SHAPE,
COORDS,
ISMAP,
NOHREF,
ALT,
ID,
SRC,
HSPACE,
VSPACE,
USEMAP,
LOWSRC,
CODEBASE,
CODE,
ARCHIVE,
VALUE,
VALUETYPE,
TYPE,
CLASS,
STYLE,
LANG,
DIR,
DECLARE,
CLASSID,
DATA,
CODETYPE,
STANDBY,
BORDER,
SHAPES,
NOSHADE,
COMPACT,
START,
ACTION,
METHOD,
ENCTYPE,
CHECKED,
MAXLENGTH,
MULTIPLE,
SELECTED,
ROWS,
COLS,
DUMMY,
CELLSPACING,
CELLPADDING,
VALIGN,
HALIGN,
NOWRAP,
ROWSPAN,
COLSPAN,
PROMPT,
HTTPEQUIV,
CONTENT,
LANGUAGE,
VERSION,
N,
FRAMEBORDER,
MARGINWIDTH,
MARGINHEIGHT,
SCROLLING,
NORESIZE,
MEDIA,
ENDTAG
};
}
// The secret to 73, is that, given that the Hashtable contents
// never change once the static initialization happens, the initial size
// that the hashtable grew to was determined, and then that very size
// is used.
//
private static final Hashtable<String, Tag> tagHashtable = new Hashtable<String, Tag>(73);
/** Maps from StyleConstant key to HTML.Tag. */
private static final Hashtable<Object, Tag> scMapping = new Hashtable<Object, Tag>(8);
static {
for (int i = 0; i < Tag.allTags.length; i++ ) {
tagHashtable.put(Tag.allTags[i].toString(), Tag.allTags[i]);
StyleContext.registerStaticAttributeKey(Tag.allTags[i]);
}
StyleContext.registerStaticAttributeKey(Tag.IMPLIED);
StyleContext.registerStaticAttributeKey(Tag.CONTENT);
StyleContext.registerStaticAttributeKey(Tag.COMMENT);
for (int i = 0; i < Attribute.allAttributes.length; i++) {
StyleContext.registerStaticAttributeKey(Attribute.
allAttributes[i]);
}
StyleContext.registerStaticAttributeKey(HTML.NULL_ATTRIBUTE_VALUE);
scMapping.put(StyleConstants.Bold, Tag.B);
scMapping.put(StyleConstants.Italic, Tag.I);
scMapping.put(StyleConstants.Underline, Tag.U);
scMapping.put(StyleConstants.StrikeThrough, Tag.STRIKE);
scMapping.put(StyleConstants.Superscript, Tag.SUP);
scMapping.put(StyleConstants.Subscript, Tag.SUB);
scMapping.put(StyleConstants.FontFamily, Tag.FONT);
scMapping.put(StyleConstants.FontSize, Tag.FONT);
}
/**
* Returns the set of actual HTML tags that
* are recognized by the default HTML reader.
* This set does not include tags that are
* manufactured by the reader.
*/
public static Tag[] getAllTags() {
Tag[] tags = new Tag[Tag.allTags.length];
System.arraycopy(Tag.allTags, 0, tags, 0, Tag.allTags.length);
return tags;
}
/**
* Fetches a tag constant for a well-known tag name (i.e. one of
* the tags in the set {A, ADDRESS, APPLET, AREA, B,
* BASE, BASEFONT, BIG,
* BLOCKQUOTE, BODY, BR, CAPTION, CENTER, CITE, CODE,
* DD, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, FRAME,
* FRAMESET, H1, H2, H3, H4, H5, H6, HEAD, HR, HTML,
* I, IMG, INPUT, ISINDEX, KBD, LI, LINK, MAP, MENU,
* META, NOBR, NOFRAMES, OBJECT, OL, OPTION, P, PARAM,
* PRE, SAMP, SCRIPT, SELECT, SMALL, SPAN, STRIKE, S,
* STRONG, STYLE, SUB, SUP, TABLE, TD, TEXTAREA,
* TH, TITLE, TR, TT, U, UL, VAR}. If the given
* name does not represent one of the well-known tags, then
* <code>null</code> will be returned.
*
* @param tagName the <code>String</code> name requested
* @return a tag constant corresponding to the <code>tagName</code>,
* or <code>null</code> if not found
*/
public static Tag getTag(String tagName) {
Tag t = tagHashtable.get(tagName);
return (t == null ? null : t);
}
/**
* Returns the HTML <code>Tag</code> associated with the
* <code>StyleConstants</code> key <code>sc</code>.
* If no matching <code>Tag</code> is found, returns
* <code>null</code>.
*
* @param sc the <code>StyleConstants</code> key
* @return tag which corresponds to <code>sc</code>, or
* <code>null</code> if not found
*/
static Tag getTagForStyleConstantsKey(StyleConstants sc) {
return scMapping.get(sc);
}
/**
* Fetches an integer attribute value. Attribute values
* are stored as a string, and this is a convenience method
* to convert to an actual integer.
*
* @param attr the set of attributes to use to try to fetch a value
* @param key the key to use to fetch the value
* @param def the default value to use if the attribute isn't
* defined or there is an error converting to an integer
*/
public static int getIntegerAttributeValue(AttributeSet attr,
Attribute key, int def) {
int value = def;
String istr = (String) attr.getAttribute(key);
if (istr != null) {
try {
value = Integer.valueOf(istr).intValue();
} catch (NumberFormatException e) {
value = def;
}
}
return value;
}
// This is used in cases where the value for the attribute has not
// been specified.
//
public static final String NULL_ATTRIBUTE_VALUE = "#DEFAULT";
// size determined similar to size of tagHashtable
private static final Hashtable<String, Attribute> attHashtable = new Hashtable<String, Attribute>(77);
static {
for (int i = 0; i < Attribute.allAttributes.length; i++ ) {
attHashtable.put(Attribute.allAttributes[i].toString(), Attribute.allAttributes[i]);
}
}
/**
* Returns the set of HTML attributes recognized.
* @return the set of HTML attributes recognized
*/
public static Attribute[] getAllAttributeKeys() {
Attribute[] attributes = new Attribute[Attribute.allAttributes.length];
System.arraycopy(Attribute.allAttributes, 0,
attributes, 0, Attribute.allAttributes.length);
return attributes;
}
/**
* Fetches an attribute constant for a well-known attribute name
* (i.e. one of the attributes in the set {FACE, COMMENT, SIZE,
* COLOR, CLEAR, BACKGROUND, BGCOLOR, TEXT, LINK, VLINK, ALINK,
* WIDTH, HEIGHT, ALIGN, NAME, HREF, REL, REV, TITLE, TARGET,
* SHAPE, COORDS, ISMAP, NOHREF, ALT, ID, SRC, HSPACE, VSPACE,
* USEMAP, LOWSRC, CODEBASE, CODE, ARCHIVE, VALUE, VALUETYPE,
* TYPE, CLASS, STYLE, LANG, DIR, DECLARE, CLASSID, DATA, CODETYPE,
* STANDBY, BORDER, SHAPES, NOSHADE, COMPACT, START, ACTION, METHOD,
* ENCTYPE, CHECKED, MAXLENGTH, MULTIPLE, SELECTED, ROWS, COLS,
* DUMMY, CELLSPACING, CELLPADDING, VALIGN, HALIGN, NOWRAP, ROWSPAN,
* COLSPAN, PROMPT, HTTPEQUIV, CONTENT, LANGUAGE, VERSION, N,
* FRAMEBORDER, MARGINWIDTH, MARGINHEIGHT, SCROLLING, NORESIZE,
* MEDIA, ENDTAG}).
* If the given name does not represent one of the well-known attributes,
* then <code>null</code> will be returned.
*
* @param attName the <code>String</code> requested
* @return the <code>Attribute</code> corresponding to <code>attName</code>
*/
public static Attribute getAttributeKey(String attName) {
Attribute a = attHashtable.get(attName);
if (a == null) {
return null;
}
return a;
}
}
| dragonwell-project/dragonwell8 | jdk/src/share/classes/javax/swing/text/html/HTML.java |
180,232 | /*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.internal.jvm;
import org.gradle.api.NonNullApi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* These JVM arguments should be passed to any Gradle process that will be running on Java 9+
* Gradle accesses those packages reflectively. On Java versions 9 to 15, the users will get
* a warning they can do nothing about. On Java 16+, strong encapsulation of JDK internals is
* enforced and not having the explicit permissions for reflective accesses will result in runtime exceptions.
*/
@NonNullApi
public class JpmsConfiguration {
public static final List<String> GROOVY_JPMS_ARGS = Collections.unmodifiableList(Arrays.asList(
"--add-opens=java.base/java.lang=ALL-UNNAMED",
"--add-opens=java.base/java.lang.invoke=ALL-UNNAMED",
"--add-opens=java.base/java.util=ALL-UNNAMED",
"--add-opens=java.prefs/java.util.prefs=ALL-UNNAMED", // required by PreferenceCleaningGroovySystemLoader
"--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", // Required by JdkTools and JdkJavaCompiler
"--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED" // Required by JdkTools and JdkJavaCompiler
));
public static final List<String> GRADLE_DAEMON_JPMS_ARGS;
static {
List<String> gradleDaemonJvmArgs = new ArrayList<String>();
gradleDaemonJvmArgs.addAll(GROOVY_JPMS_ARGS);
List<String> configurationCacheJpmsArgs = Collections.unmodifiableList(Arrays.asList(
"--add-opens=java.prefs/java.util.prefs=ALL-UNNAMED", // required by JavaObjectSerializationCodec.kt
"--add-opens=java.base/java.nio.charset=ALL-UNNAMED", // required by BeanSchemaKt
"--add-opens=java.base/java.net=ALL-UNNAMED", // required by JavaObjectSerializationCodec
"--add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED" // serialized from org.gradle.internal.file.StatStatistics$Collector
));
gradleDaemonJvmArgs.addAll(configurationCacheJpmsArgs);
GRADLE_DAEMON_JPMS_ARGS = Collections.unmodifiableList(gradleDaemonJvmArgs);
}
}
| gradle/gradle | platforms/core-runtime/base-services/src/main/java/org/gradle/internal/jvm/JpmsConfiguration.java |
180,233 | /*
* 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.jmeter.threads;
import java.io.Serializable;
import java.time.Duration;
import java.util.IdentityHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.jmeter.control.Controller;
import org.apache.jmeter.control.IteratingController;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.engine.TreeCloner;
import org.apache.jmeter.engine.event.LoopIterationListener;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.schema.PropertiesAccessor;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.ListedHashTree;
import org.apiguardian.api.API;
import org.jetbrains.annotations.NotNull;
/**
* ThreadGroup holds the settings for a JMeter thread group.
*
* This class is intended to be ThreadSafe.
*/
public abstract class AbstractThreadGroup extends AbstractTestElement
implements Serializable, Controller, JMeterThreadMonitor, TestCompilerHelper {
private static final long serialVersionUID = 240L;
// Only create the map if it is required
private final transient IdentityHashMap<TestElement, Object> children = new IdentityHashMap<>();
private static final Object DUMMY = new Object();
public static final Duration DEFAULT_THREAD_STOP_TIMEOUT =
Duration.ofMillis(
JMeterUtils.getPropDefault("jmeterengine.threadstop.wait", 5 * 1000L));
/** Action to be taken when a Sampler error occurs */
public static final String ON_SAMPLE_ERROR = "ThreadGroup.on_sample_error"; // int
/** Continue, i.e. ignore sampler errors */
public static final String ON_SAMPLE_ERROR_CONTINUE = "continue";
/** Start next loop for current thread if sampler error occurs */
public static final String ON_SAMPLE_ERROR_START_NEXT_LOOP = "startnextloop";
/** Stop current thread if sampler error occurs */
public static final String ON_SAMPLE_ERROR_STOPTHREAD = "stopthread";
/** Stop test (all threads) if sampler error occurs, the entire test is stopped at the end of any current samples */
public static final String ON_SAMPLE_ERROR_STOPTEST = "stoptest";
/** Stop test NOW (all threads) if sampler error occurs, the entire test is stopped abruptly. Any current samplers are interrupted if possible. */
public static final String ON_SAMPLE_ERROR_STOPTEST_NOW = "stoptestnow";
/** Number of threads in the thread group */
public static final String NUM_THREADS = "ThreadGroup.num_threads";
public static final String MAIN_CONTROLLER = "ThreadGroup.main_controller";
/** The same user or different users */
public static final String IS_SAME_USER_ON_NEXT_ITERATION = "ThreadGroup.same_user_on_next_iteration";
private final AtomicInteger numberOfThreads = new AtomicInteger(0); // Number of active threads in this group
@Override
public AbstractThreadGroupSchema getSchema() {
return AbstractThreadGroupSchema.INSTANCE;
}
@NotNull
@Override
public PropertiesAccessor<? extends AbstractThreadGroup, ? extends AbstractThreadGroupSchema> getProps() {
return new PropertiesAccessor<>(this, getSchema());
}
/** {@inheritDoc} */
@Override
public boolean isDone() {
return getSamplerController().isDone();
}
/** {@inheritDoc} */
@Override
public Sampler next() {
return getSamplerController().next();
}
/**
* Get the sampler controller.
*
* @return the sampler controller.
*/
public Controller getSamplerController() {
return get(getSchema().getMainController());
}
/**
* Set the sampler controller.
*
* @param c
* the sampler controller.
*/
public void setSamplerController(LoopController c) {
c.setContinueForever(false);
set(getSchema().getMainController(), c);
}
/**
* Add a test element.
*
* @param child
* the test element to add.
*/
@Override
public void addTestElement(TestElement child) {
getSamplerController().addTestElement(child);
}
/**
* {@inheritDoc}
*/
@Override
public final boolean addTestElementOnce(TestElement child){
synchronized (children) {
if (children.putIfAbsent(child, DUMMY) == null) {
addTestElement(child);
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
public void addIterationListener(LoopIterationListener lis) {
getSamplerController().addIterationListener(lis);
}
/** {@inheritDoc} */
@Override
public void removeIterationListener(LoopIterationListener iterationListener) {
getSamplerController().removeIterationListener(iterationListener);
}
/** {@inheritDoc} */
@Override
public void initialize() {
Controller c = getSamplerController();
JMeterProperty property = c.getProperty(TestElement.NAME);
property.setObjectValue(getName()); // Copy our name into that of the controller
property.setRunningVersion(property.isRunningVersion());// otherwise name reverts
c.initialize();
}
/**
* Start next iteration after an error
*/
public void startNextLoop() {
((IteratingController) getSamplerController()).startNextLoop();
}
/**
* NOOP
*/
@Override
public void triggerEndOfLoop() {
// NOOP
}
/**
* Set the total number of threads to start
*
* @param numThreads
* the number of threads.
*/
public void setNumThreads(int numThreads) {
set(getSchema().getNumThreads(), numThreads);
}
/**
* Increment the number of active threads
*/
void incrNumberOfThreads() {
numberOfThreads.incrementAndGet();
}
/**
* Decrement the number of active threads
*/
void decrNumberOfThreads() {
numberOfThreads.decrementAndGet();
}
/**
* Get the number of active threads
*
* @return the number of active threads
*/
public int getNumberOfThreads() {
return numberOfThreads.get();
}
/**
* Get the number of threads.
*
* @return the number of threads.
*/
public int getNumThreads() {
return get(getSchema().getNumThreads());
}
private String getOnSampleError() {
return get(getSchema().getOnSampleError());
}
/**
* Check if a sampler error should cause thread to start next loop.
*
* @return true if thread should start next loop
*/
public boolean getOnErrorStartNextLoop() {
return getOnSampleError().equalsIgnoreCase(ON_SAMPLE_ERROR_START_NEXT_LOOP);
}
/**
* Check if a sampler error should cause thread to stop.
*
* @return true if thread should stop
*/
public boolean getOnErrorStopThread() {
return getOnSampleError().equalsIgnoreCase(ON_SAMPLE_ERROR_STOPTHREAD);
}
/**
* Check if a sampler error should cause test to stop.
*
* @return true if test (all threads) should stop
*/
public boolean getOnErrorStopTest() {
return getOnSampleError().equalsIgnoreCase(ON_SAMPLE_ERROR_STOPTEST);
}
/**
* Check if a sampler error should cause test to stop now.
*
* @return true if test (all threads) should stop immediately
*/
public boolean getOnErrorStopTestNow() {
return getOnSampleError().equalsIgnoreCase(ON_SAMPLE_ERROR_STOPTEST_NOW);
}
/**
* Hard or graceful stop depending on now flag
* @param threadName String thread name
* @param now if true interrupt {@link Thread}
* @return boolean true if stop succeeded
*/
public abstract boolean stopThread(String threadName, boolean now);
/**
* @return int number of active threads
*/
public abstract int numberOfActiveThreads();
/**
* Start the {@link ThreadGroup}
* @param groupCount group number
* @param notifier {@link ListenerNotifier}
* @param threadGroupTree {@link ListedHashTree}
* @param engine {@link StandardJMeterEngine}
*/
public abstract void start(int groupCount, ListenerNotifier notifier, ListedHashTree threadGroupTree, StandardJMeterEngine engine);
/**
* Add a new {@link JMeterThread} to this {@link ThreadGroup} for engine
* @param delay Delay in milliseconds
* @param engine {@link StandardJMeterEngine}
* @return {@link JMeterThread}
*/
public abstract JMeterThread addNewThread(int delay, StandardJMeterEngine engine);
/**
* @return true if threads were correctly stopped
*/
public abstract boolean verifyThreadsStopped();
/**
* Wait for all Group Threads to stop after a graceful stop
*/
public abstract void waitThreadsStopped();
/**
* This immediately stop threads of Group by interrupting them.
* It differs from {@link AbstractThreadGroup#stop()} by being a hard stop
*/
public abstract void tellThreadsToStop();
/**
* This gracefully stops threads of Group
*/
public abstract void stop();
public void breakThreadLoop() {
((IteratingController) getSamplerController()).breakLoop();
}
/**
* Set the kind of user
*
* @param isSameUserOnNextIteration
* true is the same user on next iteration of loop
* false is a different user on next iteration of loop
*/
public void setIsSameUserOnNextIteration(boolean isSameUserOnNextIteration) {
set(getSchema().getSameUserOnNextIteration(), isSameUserOnNextIteration);
}
/**
* Get kind of user:
* <ul>
* <li>true means same user running multiple iterations</li>
* <li>false means a different user for each iteration</li>
* </ul>
* @return the kind of user.
*/
public boolean isSameUserOnNextIteration() {
return get(getSchema().getSameUserOnNextIteration());
}
/**
* Create {@link JMeterThread}. Note: the input tree is not cloned.
* @param engine {@link StandardJMeterEngine}
* @param monitor {@link JMeterThreadMonitor}
* @param notifier {@link ListenerNotifier}
* @param groupNumber thread group number
* @param threadNumber int thread number
* @param threadGroupTree {@link ListedHashTree}
* @param variables initial variables
* @return {@link JMeterThread}
*/
@API(status = API.Status.EXPERIMENTAL, since = "5.5")
protected JMeterThread makeThread(
StandardJMeterEngine engine,
JMeterThreadMonitor monitor, ListenerNotifier notifier,
int groupNumber, int threadNumber,
ListedHashTree threadGroupTree,
JMeterVariables variables) {
boolean onErrorStopTest = getOnErrorStopTest();
boolean onErrorStopTestNow = getOnErrorStopTestNow();
boolean onErrorStopThread = getOnErrorStopThread();
boolean onErrorStartNextLoop = getOnErrorStartNextLoop();
String groupName = getName();
final JMeterThread jmeterThread = new JMeterThread(threadGroupTree, monitor, notifier, isSameUserOnNextIteration());
jmeterThread.setThreadNum(threadNumber);
jmeterThread.setThreadGroup(this);
jmeterThread.putVariables(variables);
String distributedPrefix =
JMeterUtils.getPropDefault(JMeterUtils.THREAD_GROUP_DISTRIBUTED_PREFIX_PROPERTY_NAME, "");
final String threadName = distributedPrefix + (distributedPrefix.isEmpty() ? "":"-") +groupName + " " + groupNumber + "-" + (threadNumber + 1);
jmeterThread.setThreadName(threadName);
jmeterThread.setEngine(engine);
jmeterThread.setOnErrorStopTest(onErrorStopTest);
jmeterThread.setOnErrorStopTestNow(onErrorStopTestNow);
jmeterThread.setOnErrorStopThread(onErrorStopThread);
jmeterThread.setOnErrorStartNextLoop(onErrorStartNextLoop);
return jmeterThread;
}
/**
* @param tree {@link ListedHashTree}
* @return a clone of tree
*/
@API(status = API.Status.EXPERIMENTAL, since = "5.5")
public static ListedHashTree cloneTree(ListedHashTree tree) {
TreeCloner cloner = new TreeCloner(true);
tree.traverse(cloner);
return cloner.getClonedTree();
}
}
| apache/jmeter | src/core/src/main/java/org/apache/jmeter/threads/AbstractThreadGroup.java |
180,234 | /*
* Copyright 2014 Chris Banes
*
* 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 app.philm.in.util;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import java.net.URLEncoder;
import app.philm.in.model.PhilmMovie;
import app.philm.in.model.PhilmMovieVideo;
import app.philm.in.model.PhilmPerson;
import app.philm.in.model.PhilmPersonCredit;
public class ImageHelper {
private static final boolean RESIZE_ALL = false;
private static final int[] TRAKT_POSTER_SIZES = { 138, 300 };
private static final int[] TRAKT_BACKDROP_SIZES = { 218, 940 };
private static final String YOUTUBE_URL_BASE = "http://img.youtube.com/vi/";
private static final String YOUTUBE_MEDIUM_Q_FILENAME = "mqdefault.jpg";
private static final int YOUTUBE_MEDIUM_Q_WIDTH = 180;
private static final String YOUTUBE_HIGH_Q_FILENAME = "hqdefault.jpg";
private static final int YOUTUBE_HIGH_Q_WIDTH = 480;
private String mTmdbBaseUrl;
private int[] mTmdbPosterSizes;
private int[] mTmdbBackdropSizes;
private int[] mTmdbProfileSizes;
public void setTmdbBackdropSizes(int[] tmdbBackdropSizes) {
mTmdbBackdropSizes = tmdbBackdropSizes;
}
public void setTmdbPosterSizes(int[] tmdbPosterSizes) {
mTmdbPosterSizes = tmdbPosterSizes;
}
public void setTmdbBaseUrl(String baseUrl) {
mTmdbBaseUrl = baseUrl;
}
public void setTmdbProfileSizes(int[] tmdbProfileSizes) {
mTmdbProfileSizes = tmdbProfileSizes;
}
public String getPosterUrl(final PhilmPersonCredit credit, final int width, final int height) {
final String imageUrl = credit.getPosterPath();
Preconditions.checkNotNull(imageUrl, "movie must have poster url");
String url = buildTmdbPosterUrl(imageUrl, width, RESIZE_ALL);
return RESIZE_ALL ? getResizedUrl(url, width, height) : url;
}
public String getPosterUrl(final PhilmMovie movie, final int width, final int height) {
String url = null;
if (!TextUtils.isEmpty(movie.getTmdbPosterUrl())) {
url = buildTmdbPosterUrl(movie.getTmdbPosterUrl(),
width, RESIZE_ALL);
} else if (!TextUtils.isEmpty(movie.getTraktPosterUrl())) {
url = buildTraktUrl(movie.getTraktPosterUrl(),
selectSize(width, TRAKT_POSTER_SIZES, RESIZE_ALL));
}
Verify.verifyNotNull(url);
return RESIZE_ALL ? getResizedUrl(url, width, height) : url;
}
public String getFanartUrl(final PhilmMovie movie, final int width, final int height) {
String url = null;
if (!TextUtils.isEmpty(movie.getTmdbBackdropUrl())) {
url = buildTmdbBackdropUrl(movie.getTmdbBackdropUrl(), width, RESIZE_ALL);
} else if (!TextUtils.isEmpty(movie.getTraktBackdropUrl())) {
url = buildTraktUrl(movie.getTraktBackdropUrl(),
selectSize(width, TRAKT_BACKDROP_SIZES, RESIZE_ALL));
}
Verify.verifyNotNull(url);
return RESIZE_ALL ? getResizedUrl(url, width, height) : url;
}
public String getFanartUrl(final PhilmMovie.BackdropImage image,
final int width, final int height) {
final String imageUrl = image.url;
Preconditions.checkNotNull(imageUrl, "image must have backdrop url");
String url = null;
switch (image.sourceType) {
case PhilmMovie.TYPE_TMDB:
url = buildTmdbBackdropUrl(imageUrl, width, RESIZE_ALL);
break;
case PhilmMovie.TYPE_TRAKT:
url = buildTraktUrl(imageUrl, selectSize(width, TRAKT_BACKDROP_SIZES, RESIZE_ALL));
break;
}
return RESIZE_ALL ? getResizedUrl(url, width, height) : url;
}
public String getProfileUrl(final PhilmPerson person, final int width, final int height) {
final String imageUrl = person.getPictureUrl();
Preconditions.checkNotNull(imageUrl, "movie must have picture url");
String url = null;
switch (person.getPictureType()) {
case PhilmMovie.TYPE_TMDB:
url = buildTmdbBackdropUrl(imageUrl, width, RESIZE_ALL);
break;
case PhilmMovie.TYPE_TRAKT:
url = buildTraktUrl(imageUrl, selectSize(width, TRAKT_BACKDROP_SIZES, RESIZE_ALL));
break;
}
return RESIZE_ALL ? getResizedUrl(url, width, height) : url;
}
public static String getResizedUrl(String url, int width, int height) {
StringBuffer sb = new StringBuffer("https://images1-focus-opensocial.googleusercontent.com/gadgets/proxy");
sb.append("?container=focus");
sb.append("&resize_w=").append(width);
sb.append("&resize_h=").append(height);
sb.append("&url=").append(URLEncoder.encode(url));
sb.append("&refresh=31536000");
return sb.toString();
}
private String buildTmdbPosterUrl(String imageUrl, int width, boolean forceLarger) {
if (mTmdbBaseUrl != null && mTmdbPosterSizes != null) {
return buildTmdbUrl(mTmdbBaseUrl, imageUrl,
selectSize(width, mTmdbPosterSizes, forceLarger));
} else {
return null;
}
}
private String buildTmdbBackdropUrl(String imageUrl, int width, boolean forceLarger) {
if (mTmdbBaseUrl != null && mTmdbBackdropSizes != null) {
return buildTmdbUrl(mTmdbBaseUrl, imageUrl,
selectSize(width, mTmdbBackdropSizes, forceLarger));
} else {
return null;
}
}
private String buildTmdbProfileUrl(String imageUrl, int width, boolean forceLarger) {
if (mTmdbBaseUrl != null && mTmdbProfileSizes != null) {
return buildTmdbUrl(mTmdbBaseUrl, imageUrl,
selectSize(width, mTmdbProfileSizes, forceLarger));
} else {
return null;
}
}
private static int selectSize(final int width, final int[] widths, final boolean forceLarger) {
int previousBucketWidth = 0;
for (int i = 0; i < widths.length; i++) {
final int currentBucketWidth = widths[i];
if (width < currentBucketWidth) {
if (forceLarger || previousBucketWidth != 0) {
// We're in between this and the previous bucket
final int bucketDiff = currentBucketWidth - previousBucketWidth;
if (width < previousBucketWidth + (bucketDiff / 2)) {
return previousBucketWidth;
} else {
return currentBucketWidth;
}
} else {
return currentBucketWidth;
}
} else if (i == widths.length - 1) {
// If we get here then we're larger than a bucket
if (width < currentBucketWidth * 2) {
return currentBucketWidth;
}
}
previousBucketWidth = currentBucketWidth;
}
return Integer.MAX_VALUE;
}
private static String buildTraktUrl(final String originalUrl, final int width) {
if (!TextUtils.isEmpty(originalUrl) && width != Integer.MAX_VALUE) {
final int lastDot = originalUrl.lastIndexOf('.');
if (lastDot != 0) {
StringBuilder url = new StringBuilder(originalUrl.substring(0, lastDot));
url.append('-').append(width);
url.append(originalUrl.substring(lastDot));
return url.toString();
}
}
return originalUrl;
}
private static String buildTmdbUrl(String baseUrl, String imagePath, int width) {
StringBuilder url = new StringBuilder(baseUrl);
if (width == Integer.MAX_VALUE) {
url.append("original");
} else {
url.append('w').append(width);
}
url.append(imagePath);
return url.toString();
}
public String getVideoSnapshotUrl(PhilmMovieVideo video, final int width, final int height) {
switch (video.getSource()) {
case YOUTUBE:
StringBuilder url = new StringBuilder(YOUTUBE_URL_BASE);
url.append(video.getId()).append("/");
final int size = selectSize(width,
new int[] { YOUTUBE_MEDIUM_Q_WIDTH, YOUTUBE_HIGH_Q_WIDTH }, false);
switch (size) {
case YOUTUBE_MEDIUM_Q_WIDTH:
url.append(YOUTUBE_MEDIUM_Q_FILENAME);
break;
case YOUTUBE_HIGH_Q_WIDTH:
case Integer.MAX_VALUE:
url.append(YOUTUBE_HIGH_Q_FILENAME);
break;
}
return url.toString();
}
return null;
}
}
| yelinaung/philm | lib/src/main/java/app/philm/in/util/ImageHelper.java |
180,236 | /*
* Copyright (c) 2017 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.truth;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Thread.currentThread;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
/** Utility that cleans stack traces to remove noise from common frameworks. */
@GwtIncompatible
@J2ktIncompatible
final class StackTraceCleaner {
static final String CLEANER_LINK = "https://goo.gl/aH3UyP";
/**
* <b>Call {@link Platform#cleanStackTrace} rather than calling this directly.</b>
*
* <p>Cleans the stack trace on the given {@link Throwable}, replacing the original stack trace
* stored on the instance (see {@link Throwable#setStackTrace(StackTraceElement[])}).
*
* <p>Removes Truth stack frames from the top and JUnit framework and reflective call frames from
* the bottom. Collapses the frames for various frameworks in the middle of the trace as well.
*/
static void cleanStackTrace(Throwable throwable) {
new StackTraceCleaner(throwable).clean(Sets.<Throwable>newIdentityHashSet());
}
private final Throwable throwable;
private final List<StackTraceElementWrapper> cleanedStackTrace = new ArrayList<>();
private @Nullable StackTraceElementWrapper lastStackFrameElementWrapper = null;
private @Nullable StackFrameType currentStreakType = null;
private int currentStreakLength = 0;
/**
* A new instance is instantiated for each throwable to be cleaned. This is so that helper methods
* can make use of instance variables describing the state of the cleaning process.
*/
private StackTraceCleaner(Throwable throwable) {
this.throwable = throwable;
}
// TODO(b/135924708): Add this to the test runners so that we clean all stack traces, not just
// those of exceptions originating in Truth.
/** Cleans the stack trace on {@code throwable}, replacing the trace that was originally on it. */
@SuppressWarnings("SetAll") // not available under old versions of Android
private void clean(Set<Throwable> seenThrowables) {
// Stack trace cleaning can be disabled using a system property.
if (isStackTraceCleaningDisabled()) {
return;
}
/*
* TODO(cpovirk): Consider wrapping this whole method in a try-catch in case there are any bugs.
* It would be a shame for us to fail to report the "real" assertion failure because we're
* instead reporting a bug in Truth's cosmetic stack cleaning.
*/
// Prevent infinite recursion if there is a reference cycle between Throwables.
if (seenThrowables.contains(throwable)) {
return;
}
seenThrowables.add(throwable);
StackTraceElement[] stackFrames = throwable.getStackTrace();
int stackIndex = stackFrames.length - 1;
for (; stackIndex >= 0 && !isTruthEntrance(stackFrames[stackIndex]); stackIndex--) {
// Find first frame that enters Truth's world, and remove all above.
}
stackIndex += 1;
int endIndex = 0;
for (;
endIndex < stackFrames.length && !isJUnitIntrastructure(stackFrames[endIndex]);
endIndex++) {
// Find last frame of setup frames, and remove from there down.
}
/*
* If the stack trace would be empty, the error was probably thrown from "JUnit infrastructure"
* frames. Keep those frames around (though much of JUnit itself and related startup frames will
* still be removed by the remainder of this method) so that the user sees a useful stack.
*/
if (stackIndex >= endIndex) {
endIndex = stackFrames.length;
}
for (; stackIndex < endIndex; stackIndex++) {
StackTraceElementWrapper stackTraceElementWrapper =
new StackTraceElementWrapper(stackFrames[stackIndex]);
// Always keep frames that might be useful.
if (stackTraceElementWrapper.getStackFrameType() == StackFrameType.NEVER_REMOVE) {
endStreak();
cleanedStackTrace.add(stackTraceElementWrapper);
continue;
}
// Otherwise, process the current frame for collapsing
addToStreak(stackTraceElementWrapper);
lastStackFrameElementWrapper = stackTraceElementWrapper;
}
// Close out the streak on the bottom of the stack.
endStreak();
// Filter out testing framework and reflective calls from the bottom of the stack
ListIterator<StackTraceElementWrapper> iterator =
cleanedStackTrace.listIterator(cleanedStackTrace.size());
while (iterator.hasPrevious()) {
StackTraceElementWrapper stackTraceElementWrapper = iterator.previous();
if (stackTraceElementWrapper.getStackFrameType() == StackFrameType.TEST_FRAMEWORK
|| stackTraceElementWrapper.getStackFrameType() == StackFrameType.REFLECTION) {
iterator.remove();
} else {
break;
}
}
// Replace the stack trace on the Throwable with the cleaned one.
StackTraceElement[] result = new StackTraceElement[cleanedStackTrace.size()];
for (int i = 0; i < result.length; i++) {
result[i] = cleanedStackTrace.get(i).getStackTraceElement();
}
throwable.setStackTrace(result);
// Recurse on any related Throwables that are attached to this one
if (throwable.getCause() != null) {
new StackTraceCleaner(throwable.getCause()).clean(seenThrowables);
}
for (Throwable suppressed : Platform.getSuppressed(throwable)) {
new StackTraceCleaner(suppressed).clean(seenThrowables);
}
}
/**
* Either adds the given frame to the running streak or closes out the running streak and starts a
* new one.
*/
private void addToStreak(StackTraceElementWrapper stackTraceElementWrapper) {
if (stackTraceElementWrapper.getStackFrameType() != currentStreakType) {
endStreak();
currentStreakType = stackTraceElementWrapper.getStackFrameType();
currentStreakLength = 1;
} else {
currentStreakLength++;
}
}
/** Ends the current streak, adding a summary frame to the result. Resets the streak counter. */
private void endStreak() {
if (currentStreakLength == 0) {
return;
}
if (currentStreakLength == 1) {
// A single frame isn't a streak. Just include the frame as-is in the result.
cleanedStackTrace.add(checkNotNull(lastStackFrameElementWrapper));
} else {
// Add a single frame to the result summarizing the streak of framework frames
cleanedStackTrace.add(
createStreakReplacementFrame(checkNotNull(currentStreakType), currentStreakLength));
}
clearStreak();
}
/** Resets the streak counter. */
private void clearStreak() {
currentStreakType = null;
currentStreakLength = 0;
}
private static final ImmutableSet<String> SUBJECT_CLASS =
ImmutableSet.of(
Subject.class.getCanonicalName());
private static final ImmutableSet<String> STANDARD_SUBJECT_BUILDER_CLASS =
ImmutableSet.of(StandardSubjectBuilder.class.getCanonicalName());
private static boolean isTruthEntrance(StackTraceElement stackTraceElement) {
return isFromClassOrClassNestedInside(stackTraceElement, SUBJECT_CLASS)
/*
* Don't match classes _nested inside_ StandardSubjectBuilder because that would match
* Expect's Statement implementation. While we want to strip everything from there _down_, we
* don't want to strip everything from there _up_ (which would strip the test class itself!).
*
* (StandardSubjectBuilder is listed here only for its fail() methods, anyway, so we don't
* have to worry about nested classes like we do with Subject.)
*/
|| isFromClassDirectly(stackTraceElement, STANDARD_SUBJECT_BUILDER_CLASS);
}
private static final ImmutableSet<String> JUNIT_INFRASTRUCTURE_CLASSES =
ImmutableSet.of("org.junit.runner.Runner", "org.junit.runners.model.Statement");
private static boolean isJUnitIntrastructure(StackTraceElement stackTraceElement) {
// It's not clear whether looking at nested classes here is useful, harmful, or neutral.
return isFromClassOrClassNestedInside(stackTraceElement, JUNIT_INFRASTRUCTURE_CLASSES);
}
private static boolean isFromClassOrClassNestedInside(
StackTraceElement stackTraceElement, ImmutableSet<String> recognizedClasses) {
Class<?> stackClass;
try {
stackClass = loadClass(stackTraceElement.getClassName());
} catch (ClassNotFoundException e) {
return false;
}
try {
for (; stackClass != null; stackClass = stackClass.getEnclosingClass()) {
for (String recognizedClass : recognizedClasses) {
if (isSubtypeOf(stackClass, recognizedClass)) {
return true;
}
}
}
} catch (Error e) {
if (e.getClass().getName().equals("com.google.j2objc.ReflectionStrippedError")) {
/*
* We're running under j2objc without reflection. Skip testing the enclosing classes. At
* least we tested the class itself against all the recognized classes.
*
* TODO(cpovirk): The smarter thing might be to guess the name of the enclosing classes by
* removing "$Foo" from the end of the name. But this should be good enough for now.
*/
return false;
}
if (e instanceof IncompatibleClassChangeError) {
// OEM class-loading bug? https://issuetracker.google.com/issues/37045084
return false;
}
throw e;
}
return false;
}
private static boolean isSubtypeOf(@Nullable Class<?> subclass, String superclass) {
for (; subclass != null; subclass = checkNotNull(subclass).getSuperclass()) {
if (subclass.getCanonicalName() != null && subclass.getCanonicalName().equals(superclass)) {
return true;
}
}
return false;
}
private static boolean isFromClassDirectly(
StackTraceElement stackTraceElement, ImmutableSet<String> recognizedClasses) {
Class<?> stackClass;
try {
stackClass = loadClass(stackTraceElement.getClassName());
} catch (ClassNotFoundException e) {
return false;
}
for (String recognizedClass : recognizedClasses) {
if (isSubtypeOf(stackClass, recognizedClass)) {
return true;
}
}
return false;
}
// Using plain Class.forName can cause problems.
/*
* TODO(cpovirk): Consider avoiding classloading entirely by reading classes with ASM. But that
* won't work on Android, so we might ultimately need classloading as a fallback. Another
* possibility is to load classes in a fresh, isolated classloader. However, that requires
* creating a list of jars to load from, which is fragile and would also require special handling
* under Android. If we're lucky, this new solution will just work: The classes should already be
* loaded, anyway, since they appear on the stack, so we just have to hope that we have the right
* classloader.
*/
private static Class<?> loadClass(String name) throws ClassNotFoundException {
ClassLoader loader =
firstNonNull(
currentThread().getContextClassLoader(), StackTraceCleaner.class.getClassLoader());
return loader.loadClass(name);
}
/**
* Wrapper around a {@link StackTraceElement} for calculating and holding the metadata used to
* clean the stack trace.
*/
private static class StackTraceElementWrapper {
private final StackTraceElement stackTraceElement;
private final StackFrameType stackFrameType;
/** Creates a wrapper with the given frame with frame type inferred from frame's class name. */
StackTraceElementWrapper(StackTraceElement stackTraceElement) {
this(stackTraceElement, StackFrameType.forClassName(stackTraceElement.getClassName()));
}
/** Creates a wrapper with the given frame and the given frame type. */
StackTraceElementWrapper(StackTraceElement stackTraceElement, StackFrameType stackFrameType) {
this.stackTraceElement = stackTraceElement;
this.stackFrameType = stackFrameType;
}
/** Returns the type of this frame. */
StackFrameType getStackFrameType() {
return stackFrameType;
}
/** Returns the wrapped {@link StackTraceElement}. */
StackTraceElement getStackTraceElement() {
return stackTraceElement;
}
}
private static StackTraceElementWrapper createStreakReplacementFrame(
StackFrameType stackFrameType, int length) {
return new StackTraceElementWrapper(
new StackTraceElement(
"[["
+ stackFrameType.getName()
+ ": "
+ length
+ " frames collapsed ("
+ CLEANER_LINK
+ ")]]",
"",
"",
0),
stackFrameType);
}
/**
* Enum of the package or class-name based categories of stack frames that might be removed or
* collapsed by the cleaner.
*/
private enum StackFrameType {
NEVER_REMOVE("N/A"),
TEST_FRAMEWORK(
"Testing framework",
"junit",
"org.junit",
"androidx.test.internal.runner",
"com.github.bazel_contrib.contrib_rules_jvm.junit5",
"com.google.testing.junit",
"com.google.testing.testsize",
"com.google.testing.util"),
REFLECTION("Reflective call", "java.lang.reflect", "jdk.internal.reflect", "sun.reflect"),
CONCURRENT_FRAMEWORK(
"Concurrent framework",
"com.google.tracing.CurrentContext",
"com.google.common.util.concurrent",
"java.util.concurrent.ForkJoin");
/** Helper method to determine the frame type from the fully qualified class name. */
private static StackFrameType forClassName(String fullyQualifiedClassName) {
// Never remove the frames from a test class. These will probably be the frame of a failing
// assertion.
// TODO(cpovirk): This is really only for tests in Truth itself, so this doesn't matter yet,
// but.... If the Truth tests someday start calling into nested classes, we may want to add:
// || fullyQualifiedClassName.contains("Test$")
if (fullyQualifiedClassName.endsWith("Test")
&& !fullyQualifiedClassName.equals(
"androidx.test.internal.runner.junit3.NonLeakyTestSuite$NonLeakyTest")) {
return StackFrameType.NEVER_REMOVE;
}
for (StackFrameType stackFrameType : StackFrameType.values()) {
if (stackFrameType.belongsToType(fullyQualifiedClassName)) {
return stackFrameType;
}
}
return StackFrameType.NEVER_REMOVE;
}
private final String name;
private final ImmutableList<String> prefixes;
/**
* Each type of stack frame has a name of the summary displayed in the cleaned trace.
*
* <p>Most also have a set of fully qualified class name prefixes that identify when a frame
* belongs to this type.
*/
StackFrameType(String name, String... prefixes) {
this.name = name;
this.prefixes = ImmutableList.copyOf(prefixes);
}
/** Returns the name of this frame type to display in the cleaned trace */
String getName() {
return name;
}
/**
* Returns true if the given frame belongs to this frame type based on the package and/or class
* name of the frame.
*/
boolean belongsToType(String fullyQualifiedClassName) {
for (String prefix : prefixes) {
// TODO(cpovirk): Should we also check prefix + "$"?
if (fullyQualifiedClassName.equals(prefix)
|| fullyQualifiedClassName.startsWith(prefix + ".")) {
return true;
}
}
return false;
}
}
/**
* Returns true if stack trace cleaning is explicitly disabled in a system property. This switch
* is intended to be used when attempting to debug the frameworks which are collapsed or filtered
* out of stack traces by the cleaner.
*/
private static boolean isStackTraceCleaningDisabled() {
// Reading system properties might be forbidden.
try {
return Boolean.parseBoolean(
System.getProperty("com.google.common.truth.disable_stack_trace_cleaning"));
} catch (SecurityException e) {
// Hope for the best.
return false;
// TODO(cpovirk): Log a warning? Or is that likely to trigger other violations?
}
}
}
| google/truth | core/src/main/java/com/google/common/truth/StackTraceCleaner.java |
180,246 | package pl.pw.edu.mini.zpoif.task1.mafia.worker;
import pl.pw.edu.mini.zpoif.task1.mafia.MafiaOrganization;
import pl.pw.edu.mini.zpoif.task1.mafia.SalesDepartment;
import pl.pw.edu.mini.zpoif.task1.mafia.SpecialOperationsDepartment;
import java.util.Objects;
public abstract class MafiaWorker {
public static class LegalTrader extends MafiaWorker {
private static int transactionSummary = 0;
public void makeDeal(){
System.out.println("nielegalna transakcja dokonana");
transactionSummary += MafiaOrganization.VALUE_OF_SINGLE_LEGAL_TRANSACTION * 2;
}
}
public static class Controller extends MafiaWorker {
public void check(){
System.out.println("Kontroluje!");
if(Objects.equals(SalesDepartment.color, "green")){
System.out.println("Nie trzeba kontrolować!");
}
}
}
public static class Recruiter extends MafiaWorker {
public void recruit(){
if( Math.random() >= 0.5 ) {
System.out.println("Zrekrutowałem!");
} else {
System.out.println("Porażka! :(");
}
}
}
public static class DirtyJobGuy extends MafiaWorker {
public void doJob(){
System.out.println("Wykonuje mokra robote!");
}
}
public static class TheGodfather extends MafiaWorker {
public void bless(){
System.out.println("Popieram!");
}
}
public static class IllegalTrader extends MafiaWorker {
private static int transactionSummary = 0;
public void makeDeal(){
System.out.println("nielegalna transakcja dokonana");
transactionSummary += SpecialOperationsDepartment.illegalTransactionValue;
}
}
}
| janskwr/ZPOIF | zadanie1/src/pl/pw/edu/mini/zpoif/task1/mafia/worker/MafiaWorker.java |
180,260 | package sprzęt;
import pracownicy.Pracownik;
import pracownicy.Robotnik;
public class Linia {
public void dodaj_pracownika_na_stanowisko(Robotnik robotnik) {
return;
}
public void dodaj_losowego_pracownika() {
return;
}
}
| barteksad/OOP | Egzamin 2017/src/sprzęt/Linia.java |
180,264 | package com.example.trzewa.bandrider;
public class Constans {
public static final String NICKNAME_PARSE_KEY = "nickname";
public static final String USER_PARSE_KEY = "user";
public static final String ADDRESS_PARSE_KEY = "address";
public static final String CATEGORY_SELECTED = "category";
//sprzęt
public static final String STUFF_NAME = "name";
public static final String STUFF_OWNER = "owner";
public static final String STUFF_CATEGORY = "category";
public static final String STUFF_SWITCH_STATUS = "Switchstatus";
//instrument
public static final String INST_NAME = "name";
public static final String INST_OWNER = "owner";
public static final String INST_CATEGORY = "category";
public static final String INS_SWITCH_STATUS = "Switchstatus";
public static final String[] ELEMENTY_INSTRUMENTS = {"strunowe", "dęte", "perkusyjne"};
public static final String[] ELEMENTY_STUFF = {"wzmacniacz", "mikrofon", "głośnik"};
public static final String[] ELEMENTY_ACCESSORIES = {"Instrumenty", "Sprzęt" , "Akcesoria" };
}
| trzewa/BandRider | app/src/main/java/com/example/trzewa/bandrider/Constans.java |
180,265 | package org.polsl.backend.service;
import org.polsl.backend.dto.PaginatedResult;
import org.polsl.backend.dto.hardware.HardwareDTO;
import org.polsl.backend.dto.hardware.HardwareListOutputDTO;
import org.polsl.backend.dto.history.HistoryDTO;
import org.polsl.backend.entity.Affiliation;
import org.polsl.backend.entity.AffiliationHardware;
import org.polsl.backend.entity.ComputerSet;
import org.polsl.backend.entity.ComputerSetHardware;
import org.polsl.backend.entity.Hardware;
import org.polsl.backend.entity.HardwareDictionary;
import org.polsl.backend.exception.BadRequestException;
import org.polsl.backend.exception.NotFoundException;
import org.polsl.backend.repository.AffiliationHardwareRepository;
import org.polsl.backend.repository.AffiliationRepository;
import org.polsl.backend.repository.ComputerSetHardwareRepository;
import org.polsl.backend.repository.ComputerSetRepository;
import org.polsl.backend.repository.HardwareDictionaryRepository;
import org.polsl.backend.repository.HardwareRepository;
import org.polsl.backend.type.InventoryNumberEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Logika biznesowa hardware'u.
*/
@Service
public class HardwareService {
private final HardwareRepository hardwareRepository;
private final HardwareDictionaryRepository hardwareDictionaryRepository;
private final ComputerSetRepository computerSetRepository;
private final ComputerSetHardwareRepository computerSetHardwareRepository;
private final AffiliationRepository affiliationRepository;
private final AffiliationHardwareRepository affiliationHardwareRepository;
@Autowired
public HardwareService(HardwareRepository hardwareRepository,
HardwareDictionaryRepository hardwareDictionaryRepository,
ComputerSetRepository computerSetRepository,
ComputerSetHardwareRepository computerSetHardwareRepository1,
AffiliationRepository affiliationRepository,
AffiliationHardwareRepository affiliationHardwareRepository) {
this.hardwareRepository = hardwareRepository;
this.hardwareDictionaryRepository = hardwareDictionaryRepository;
this.computerSetRepository = computerSetRepository;
this.computerSetHardwareRepository = computerSetHardwareRepository1;
this.affiliationRepository = affiliationRepository;
this.affiliationHardwareRepository = affiliationHardwareRepository;
}
//region HTTP METHODS
public PaginatedResult<HardwareListOutputDTO> getHardwareList(Specification<Hardware> spec, boolean withDeleted) {
final Specification<Hardware> resultSpecification = withDeleted
? spec
: ((Specification<Hardware>) (root, query, criteriaBuilder) -> criteriaBuilder.isNull(root.get("validTo")))
.and(spec);
Iterable<Hardware> hardwareList = hardwareRepository.findAll(resultSpecification);
List<HardwareListOutputDTO> dtos = new ArrayList<>();
for (Hardware hardware : hardwareList) {
HardwareListOutputDTO dto = new HardwareListOutputDTO();
dto.setId(hardware.getId());
dto.setDeleted(hardware.getValidTo() != null);
dto.setName(hardware.getName());
dto.setType(hardware.getHardwareDictionary().getValue());
dto.setInventoryNumber(hardware.getInventoryNumber());
dto.setAffiliationName(getValidAffiliationName(hardware));
dto.setComputerSetInventoryNumber(getComputerSetInventoryNumber(hardware));
dtos.add(dto);
}
PaginatedResult<HardwareListOutputDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
public HardwareDTO getOneHardware(long id) {
Hardware hardware = hardwareRepository.findByIdAndValidToIsNull(id)
.orElseThrow(() -> new NotFoundException("sprzęt", "id", id));
HardwareDTO dto = new HardwareDTO();
dto.setName(hardware.getName());
dto.setInventoryNumber(hardware.getInventoryNumber());
dto.setDictionaryId(hardware.getHardwareDictionary().getId());
//WCZYTAJ NAJNOWSZĄ PRZYNALEŻNOSC DO KTÓREJ NALEZY SPRZET
AffiliationHardware lastEntryAffiliation = affiliationHardwareRepository.findTheLatestRowForHardware(id)
.orElseThrow(() -> new RuntimeException("Brak połączenia przynależności ze sprzętem o id: " + id));
dto.setAffiliationId(lastEntryAffiliation.getAffiliation().getId());
Optional<ComputerSetHardware> lastEntry = computerSetHardwareRepository.findTheLatestRowForHardware(id);
lastEntry.ifPresent(computerSetHardware -> dto.setComputerSetId(computerSetHardware.getComputerSet().getId()));
return dto;
}
public PaginatedResult<HistoryDTO> getHardwareAffiliationsHistory(long id) {
Iterable<AffiliationHardware> affiliationHardwareList;
affiliationHardwareList = affiliationHardwareRepository.findAllByHardwareId(id);
List<HistoryDTO> dtos = new ArrayList<>();
for (AffiliationHardware affiliationHardware : affiliationHardwareList) {
HistoryDTO dto = new HistoryDTO();
dto.setName(AffiliationService.generateName(affiliationHardware.getAffiliation()));
dto.setValidFrom(affiliationHardware.getValidFrom());
if (affiliationHardware.getValidTo() != null) {
dto.setValidTo(affiliationHardware.getValidTo());
}
dtos.add(dto);
}
PaginatedResult<HistoryDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
public PaginatedResult<HistoryDTO> getHardwareComputerSetsHistory(long id) {
Iterable<ComputerSetHardware> computerSetHardwareList;
computerSetHardwareList = computerSetHardwareRepository.findAllByHardwareId(id);
List<HistoryDTO> dtos = new ArrayList<>();
for (ComputerSetHardware computerSetHardware : computerSetHardwareList) {
HistoryDTO dto = new HistoryDTO();
dto.setInventoryNumber(computerSetHardware.getComputerSet().getInventoryNumber());
dto.setName(computerSetHardware.getComputerSet().getName());
dto.setValidFrom(computerSetHardware.getValidFrom());
if (computerSetHardware.getValidTo() != null) {
dto.setValidTo(computerSetHardware.getValidTo());
}
dtos.add(dto);
}
PaginatedResult<HistoryDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
@Transactional
public void createHardware(HardwareDTO request) {
if (request.getInventoryNumber() != null)
throw new BadRequestException("Zakaz ręcznego wprowadzania numeru inwentarzowego.");
Hardware hardware = new Hardware();
//WYGENERUJ NUMER INWENTARZOWY
String newInvNumb = InventoryNumberGenerator
.generateInventoryNumber(InventoryNumberEnum.HARDWARE, hardwareRepository.count());
hardware.setInventoryNumber(newInvNumb);
hardware.setName(request.getName());
HardwareDictionary hardwareDictionary = hardwareDictionaryRepository.findById(request.getDictionaryId())
.orElseThrow(() -> new NotFoundException("słownik urządzeń", "id", request.getDictionaryId()));
hardware.setHardwareDictionary(hardwareDictionary);
hardwareRepository.save(hardware);
//STWORZ POLACZENIE Z ZESTAWEM KOMPUTEROWYM
if (request.getComputerSetId() != null) {
ComputerSet computerSet = computerSetRepository.findByIdAndValidToIsNull(request.getComputerSetId())
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", request.getComputerSetId()));
ComputerSetHardware computerSetHardware = new ComputerSetHardware(computerSet, hardware);
computerSetHardwareRepository.save(computerSetHardware);
}
//STWORZ POLACZENIE Z PRZYNALEZNOSCIA
Affiliation affiliation = affiliationRepository.findByIdAndIsDeletedIsFalse(request.getAffiliationId())
.orElseThrow(() -> new NotFoundException("przynależność", "id", request.getAffiliationId()));
AffiliationHardware affiliationHardware = new AffiliationHardware(affiliation, hardware);
affiliationHardwareRepository.save(affiliationHardware);
}
@Transactional
public void editHardware(Long id, HardwareDTO request) throws NotFoundException {
if (request.getInventoryNumber() != null) throw new BadRequestException("Zakaz edycji numeru inwentarzowego.");
//WCZYTAJ Z BAZY SPRZET, KTORY BEDZIE EDYTOWANY
Hardware hardware = hardwareRepository.findById(id)
.orElseThrow(() -> new NotFoundException("sprzęt", "id", id));
hardware.setName(request.getName());
HardwareDictionary hardwareDictionary = hardwareDictionaryRepository.findById(request.getDictionaryId())
.orElseThrow(() -> new NotFoundException("słownik urządzeń", "id", request.getDictionaryId()));
hardware.setHardwareDictionary(hardwareDictionary);
hardwareRepository.save(hardware);
//SPRAWDZ CZY AKTUALNY STAN SPRZETU POWIAZANEGO Z DANYM ZESTAWEM KOMPUETROWYM MA BYC ZMIENIONY
Optional<ComputerSetHardware> lastEntry = computerSetHardwareRepository.findTheLatestRowForHardware(id);
if (lastEntry.isPresent() && !lastEntry.get().getComputerSet().getId().equals(request.getComputerSetId())) {
ComputerSetHardware computerSetHardware = lastEntry.get();
computerSetHardware.setValidTo(LocalDateTime.now());
computerSetHardwareRepository.save(computerSetHardware);
}
if (request.getComputerSetId() != null && !(
lastEntry.isPresent() && lastEntry.get().getComputerSet().getId().equals(request.getComputerSetId())
)) {
ComputerSet computerSet = computerSetRepository.findByIdAndValidToIsNull(request.getComputerSetId())
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", request.getComputerSetId()));
ComputerSetHardware computerSetHardware = new ComputerSetHardware(computerSet, hardware);
computerSetHardwareRepository.save(computerSetHardware);
}
//SPRAWCZY CZY AKTUALNY STAN PRZYNALEZNOSCI SPRZETU MA BYC ZMIENIONY
AffiliationHardware lastEntryAffiliation = affiliationHardwareRepository.findTheLatestRowForHardware(id)
.orElseThrow(() -> new RuntimeException("Brak połączenia przynależności ze sprzętem o id: " + id));
if (!lastEntryAffiliation.getAffiliation().getId().equals(request.getAffiliationId())) {
lastEntryAffiliation.setValidTo(LocalDateTime.now());
affiliationHardwareRepository.save(lastEntryAffiliation);
Affiliation affiliation = affiliationRepository.findByIdAndIsDeletedIsFalse(request.getAffiliationId())
.orElseThrow(() -> new NotFoundException("przynależność", "id", request.getAffiliationId()));
AffiliationHardware affiliationHardware = new AffiliationHardware(affiliation, hardware);
affiliationHardwareRepository.save(affiliationHardware);
}
}
@Transactional
public void deleteHardware(Long id) throws NotFoundException {
Hardware hardware = hardwareRepository.findById(id)
.orElseThrow(() -> new NotFoundException("sprzęt", "id", id));
hardware.setValidTo(LocalDateTime.now());
hardwareRepository.save(hardware);
//ZAKONCZ POWIAZANIE Z ZESTAWEM KOMPUTEROWYM
Optional<ComputerSetHardware> lastEntryComputerSet = computerSetHardwareRepository.findTheLatestRowForHardware(id);
if (lastEntryComputerSet.isPresent()) {
ComputerSetHardware computerSetHardware = lastEntryComputerSet.get();
computerSetHardware.setValidTo(LocalDateTime.now());
computerSetHardwareRepository.save(computerSetHardware);
}
//ZAKONCZ POWIAZANIE Z PRZYNALEZNOSCIA
AffiliationHardware lastEntryAffiliation = affiliationHardwareRepository.findTheLatestRowForHardware(id)
.orElseThrow(() -> new RuntimeException("Brak połączenia przynależności ze sprzętem o id: " + id));
lastEntryAffiliation.setValidTo(LocalDateTime.now());
affiliationHardwareRepository.save(lastEntryAffiliation);
}
//endregion
//region METODY POMOCNICZE
private String getValidAffiliationName(Hardware hardware) {
for (AffiliationHardware affiliationHardware : hardware.getAffiliationHardwareSet()) {
if (affiliationHardware.getValidTo() == null) {
return AffiliationService.generateName(affiliationHardware.getAffiliation());
}
}
return null;
}
private String getComputerSetInventoryNumber(Hardware hardware) {
for (ComputerSetHardware computerSetHardware : hardware.getComputerSetHardwareSet()) {
if (computerSetHardware.getValidTo() == null) {
return computerSetHardware.getComputerSet().getInventoryNumber();
}
}
return null;
}
//endregion
}
| Samograje/co-gdzie-kiedy | backend/src/main/java/org/polsl/backend/service/HardwareService.java |
180,272 | package com.myprojects.gza.myGymApp.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.myprojects.gza.myGymApp.entity.Equipment;
import com.myprojects.gza.myGymApp.errors.ThereIsNoSuchAnEquipmentException;
import com.myprojects.gza.myGymApp.service.EquipmentService;
@Controller
@RequestMapping("/user/equipments")
public class EquipmentController {
@Autowired
private EquipmentService equipmentService;
@GetMapping("/")
public String showEquipment(Model model) {
List<Equipment> equipments=equipmentService.getAll();
if(equipments.size()==0) {
model.addAttribute("info", "Brak dodanego sprzętu.");
}
model.addAttribute("equipments", equipments);
return "equipment/list";
}
@GetMapping("/add")
public String showFormToAddEquipment(Model model) {
model.addAttribute("equipment", new Equipment());
return "equipment/add";
}
@PostMapping("/add")
public String saveFormToAddEquipment(@Valid @ModelAttribute("equipment") Equipment equipment, BindingResult bindingResult, Model model) {
try {
equipmentService.save(equipment);
model.addAttribute("info", "Pomyślnie dodano nowy sprzęt.");
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("warning", "Wystąpił problem z dodaniem nowego sprzętu.");
}
return showEquipment(model);
}
@GetMapping("/edit")
public String showFormToEditEquipment(@RequestParam("equipmentId") int id, Model model) {
Equipment equipment=equipmentService.getById(id);
model.addAttribute("equipment", equipment);
return "equipment/edit";
}
@PostMapping("/edit")
public String saveFormToEditEquipment(@Valid @ModelAttribute("equipment") Equipment equipment, BindingResult bindingResult, Model model) {
try {
equipmentService.update(equipment);
model.addAttribute("info", "Pomyślnie zaktualizowano sprzęt.");
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("warning", "Wystąpił problem z aktualizacją sprzętu.");
}
return "equipment/edit";
}
@GetMapping("/search")
public String searchEquipment(@RequestParam("searchedPhrase") String searchedPhrase, Model model) {
List<Equipment> searchedEquipments=equipmentService.search(searchedPhrase);
model.addAttribute("equipments", searchedEquipments);
if(searchedEquipments.size()==0) {
model.addAttribute("warning", "Nie znaleziono podanej frazy :(");
}else {
model.addAttribute("info", "Znaleziono " +searchedEquipments.size() + " pasujących rezultatów");
}
return "equipment/list";
}
@GetMapping("/delete")
public String deleteEditEquipment(@RequestParam("equipmentId") int id, Model model) {
try {
equipmentService.delete(id);
model.addAttribute("info", "Sprzęt został usunięty.");
} catch (ThereIsNoSuchAnEquipmentException e) {
e.printStackTrace();
model.addAttribute("warning", "Wystąpił problem z usunięciem sprzętu.");
}
return showEquipment(model);
}
}
| gzacharski/System-Obslugi-Silowni | src/main/java/com/myprojects/gza/myGymApp/controller/EquipmentController.java |
180,274 | package ui.client.view;
import model.Equimpent;
import ui.client.model.ListaTowarowModel;
import javax.swing.*;
public class WypozyczeniaTopPanel extends JPanel {
JComboBox<Equimpent> equimpentCB;
public WypozyczeniaTopPanel() {
initializeComponents();
}
private void initializeComponents() {
JLabel wybierzSprzetLB = new JLabel("Wybierz sprzęt do wypożyczenia");
ListaTowarowModel model = new ListaTowarowModel();
equimpentCB = new JComboBox<Equimpent>(model);
add(wybierzSprzetLB);
add(equimpentCB);
}
public JComboBox<Equimpent> getEquimpentCB() {
return equimpentCB;
}
}
| rahul765/tensorflow-language-classification | FileTypeData/Prog_Data_train/java/WypozyczeniaTopPanel.java |
180,275 | package pl.edu.agh.integracja.firefighterspost.gui.model;
import java.util.ArrayList;
import java.util.List;
public class AlertGuiModel {
private Long externalId;
private String type;
private String address;
private String city;
private String actionName;
private String description;
private String latitude;
private String longitude;
private String notifiactionDate;
private String creator;
private String requestedUnits;
private List<String> orderedResources = new ArrayList<>();
private Integer requestedFirefightersUnitNumber;
public Long getExternalId() {
return externalId;
}
public void setExternalId(Long externalId) {
this.externalId = externalId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getActionName() {
return actionName;
}
public void setActionName(String actionName) {
this.actionName = actionName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getNotifiactionDate() {
return notifiactionDate;
}
public void setNotifiactionDate(String notifiactionDate) {
this.notifiactionDate = notifiactionDate;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getRequestedUnits() {
return requestedUnits;
}
public void setRequestedUnits(String requestedUnits) {
this.requestedUnits = requestedUnits;
}
public List<String> getOrderedResources() {
return orderedResources;
}
public void setOrderedResources(List<String> orderedResources) {
this.orderedResources = orderedResources;
}
public Integer getRequestedFirefightersUnitNumber() {
return requestedFirefightersUnitNumber;
}
public void setRequestedFirefightersUnitNumber(Integer requestedFirefightersUnitNumber) {
this.requestedFirefightersUnitNumber = requestedFirefightersUnitNumber;
}
@Override
public String toString() {
return
"Typ: " + type +
"\nAdres: " + address +
"\nMiasto: " + city +
"\nOpis: " + description +
"\nLokalizacja-szerokość: " + latitude +
"\nLokalizacja-długość: " + longitude +
"\nData powiadomienia: " + notifiactionDate +
"\nZgłaszający: " + creator +
"\nLiczba zastępów: " + requestedUnits +
"\nZamówiony sprzęt: " + orderedResources +
"\nLiczba zamówionych zastępów: " + requestedFirefightersUnitNumber;
}
}
| tloszabno/FirefightersCenter | FirefightersPostApp/src/main/java/pl/edu/agh/integracja/firefighterspost/gui/model/AlertGuiModel.java |
180,276 | package pl.pwr.edu.parser.feed.it;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import pl.pwr.edu.parser.feed.ParserTemplateStep;
/**
* Created by Jakub Pomykała on 19/04/2017.
*/
@Component
@Order(30)
public class DobreProgramyStep extends ParserTemplateStep {
private Logger log = LoggerFactory.getLogger(DobreProgramyStep.class);
@Override
public void parse() {
long page = 2;
while (page < 300) {
log.info("Fetch page: " + page);
Set<String> articleUrlsFromPage = getArticleUrlsFromPage(page++);
articleUrlsFromPage.forEach(this::parseTemplate);
}
}
@Override
public String getArticlesUrl(long page) {
return "https://www.dobreprogramy.pl/Lab," + page + ".html";
}
@Override
public Set<String> extractArticleUrls(Document document) {
Element container = document.getElementsByClass("list block-content").first();
Elements headerContainer = container.getElementsByClass("text-h25 title-comments-padding font-serif");
return headerContainer
.stream()
.map(this::elementToLink)
.collect(Collectors.toSet());
}
private String elementToLink(Element articleElement) {
Element anchor = articleElement.getElementsByTag("a").first();
return anchor.attr("href");
}
@Override
protected String parseBody(Document document) {
String body = Optional.of(document)
.map(this::tryGetBody)
.orElseGet(() -> tryGetAlternateBody(document));
String removed = body.replaceAll("Udostępnij: Facebook Twitter Polub: O autorze", "");
String removedAuthor = removed.replaceAll("Mateusz Budzeń @Scorpions.B", "");
return removedAuthor.trim();
}
private String tryGetBody(Document document) {
Elements elementsByClass = document.getElementsByClass("entry-content");
Element firstContainer = elementsByClass.first();
if (firstContainer == null) {
return null;
}
return firstContainer.text();
}
private String tryGetAlternateBody(Document document) {
Element entry = document.getElementById("phContent_divMetaBody");
return entry.text();
}
@Override
protected String parseCategory(Document document) {
return "sprzęt";
}
}
| jpomykala/masters-thesis | FetchArticlesApp/src/main/java/pl/pwr/edu/parser/feed/it/DobreProgramyStep.java |