file_id
int64
1
180k
content
stringlengths
13
357k
repo
stringlengths
6
109
path
stringlengths
6
1.15k
179,430
/*************************************************************************** * Copyright © 2020-2023 - Arianne * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.actions.admin; import static games.stendhal.common.constants.Actions.ALTER; import static games.stendhal.common.constants.Actions.ALTERKILL; import static games.stendhal.common.constants.Actions.CREATURE; import static games.stendhal.common.constants.Actions.TARGET; import java.util.Arrays; import games.stendhal.common.NotificationType; import games.stendhal.common.grammar.Grammar; import games.stendhal.server.actions.CommandCenter; import games.stendhal.server.core.engine.GameEvent; import games.stendhal.server.core.engine.SingletonRepository; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.player.Player; import marauroa.common.game.RPAction; /** * Changes solo or shared kill count of specified creature for player. */ public class AlterKillAction extends AdministrationAction { public static void register() { CommandCenter.register(ALTERKILL, new AlterKillAction(), 19); } @Override protected void perform(final Player admin, final RPAction action) { for (final String param: Arrays.asList("target", "killtype", "count", "creature")) { if (!action.has(param)) { admin.sendPrivateText("\"" + param + "\" wymagany parametr: " + action); return; } } final Entity target = getTargetAnyZone(admin, action); if (target == null) { admin.sendPrivateText("Gracz \"" + action.get(TARGET) + "\" nie został odnaleziony: " + action); return; } if (!(target instanceof Player)) { admin.sendPrivateText("Nie można zmieniać zabójstw jednostek niebędących graczami \"" + target.getName() + "\": " + action); return; } final String killtype = action.get("killtype").toLowerCase(); if (!Arrays.asList("solo", "shared").contains(killtype)) { admin.sendPrivateText("Typ zabójstwa musi być \"solo\" albo \"shared\": " + action); return; } final boolean solo = killtype.equals("solo"); final int count; try { count = Integer.parseInt(action.get("count")); } catch (final NumberFormatException e) { admin.sendPrivateText("Ilość zabójstw musi być liczbą: " + action); return; } final String creatureOrig = action.get(CREATURE); final String creature = Grammar.singular(creatureOrig); if (!SingletonRepository.getEntityManager().isCreature(creature)) { admin.sendPrivateText("\"" + creatureOrig + "\" nie jest prawidłową nazwą stworzenia: " + action); return; } final Player player = (Player) target; if (solo) { player.setSoloKillCount(creature, count); } else { player.setSharedKillCount(creature, count); } // Notify player of changes player.sendPrivateText(NotificationType.SUPPORT, "Twoja ilość zabójstw (typ: " + killtype + ") dla potwora " + creature + " została zmieniona na " + count + " przez " + admin.getTitle()); // log event new GameEvent(player.getName(), ALTER, "kill", action.get(TARGET), killtype, String.valueOf(count), creature).raise(); } }
PolanieOnLine/PolanieOnLine
src/games/stendhal/server/actions/admin/AlterKillAction.java
179,435
/*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.maps.zakopane.playroom; import games.stendhal.server.core.engine.SingletonRepository; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.entity.item.Item; /** * @author edi18028 */ public class PlaySet { private StendhalRPZone zone; public PlaySet(final StendhalRPZone zone) { this.zone = zone; } public void createFiguraFioletowa(final int x, final int y) { final Item figurafioletowa = SingletonRepository.getEntityManager() .getItem("figura fioletowa"); figurafioletowa.setPosition(x, y); zone.add(figurafioletowa, false); } public void createFiguraZielona(final int x, final int y) { final Item figurazielona = SingletonRepository.getEntityManager() .getItem("figura zielona"); figurazielona.setPosition(x, y); zone.add(figurazielona, false); } public void createDamkaFioletowa(final int x, final int y) { final Item damkafioletowa = SingletonRepository.getEntityManager() .getItem("damka fioletowa"); damkafioletowa.setPosition(x, y); zone.add(damkafioletowa, false); } public void createDamkaZielona(final int x, final int y) { final Item damkazielona = SingletonRepository.getEntityManager() .getItem("damka zielona"); damkazielona.setPosition(x, y); zone.add(damkazielona, false); } public void createPionekCzerwony(final int x, final int y) { final Item pionekczerwony = SingletonRepository.getEntityManager() .getItem("pionek czerwony"); pionekczerwony.setPosition(x, y); zone.add(pionekczerwony, false); } public void createPionekNiebieski(final int x, final int y) { final Item pionekniebieski = SingletonRepository.getEntityManager() .getItem("pionek niebieski"); pionekniebieski.setPosition(x, y); zone.add(pionekniebieski, false); } public void createPionekZielony(final int x, final int y) { final Item pionekzielony = SingletonRepository.getEntityManager() .getItem("pionek zielony"); pionekzielony.setPosition(x, y); zone.add(pionekzielony, false); } public void createPionekZolty(final int x, final int y) { final Item pionekzolty = SingletonRepository.getEntityManager() .getItem("pionek żółty"); pionekzolty.setPosition(x, y); zone.add(pionekzolty, false); } public void createKostka(final int x, final int y) { final Item kostka = SingletonRepository.getEntityManager() .getItem("kostka"); kostka.setPosition(x, y); zone.add(kostka, false); } public void createKolko(final int x, final int y) { final Item kolko = SingletonRepository.getEntityManager() .getItem("kółko"); kolko.setPosition(x, y); zone.add(kolko, false); } public void createKrzyzyk(final int x, final int y) { final Item krzyzyk = SingletonRepository.getEntityManager() .getItem("krzyżyk"); krzyzyk.setPosition(x, y); zone.add(krzyzyk, false); } public void createCzarnyPionek(final int x, final int y) { final Item czarnypionek = SingletonRepository.getEntityManager() .getItem("czarny pionek"); czarnypionek.setPosition(x, y); zone.add(czarnypionek, false); } public void createCzarnaWieza(final int x, final int y) { final Item czarnawieza = SingletonRepository.getEntityManager() .getItem("czarna wieża"); czarnawieza.setPosition(x, y); zone.add(czarnawieza, false); } public void createCzarnySkoczek(final int x, final int y) { final Item czarnyskoczek = SingletonRepository.getEntityManager() .getItem("czarny skoczek"); czarnyskoczek.setPosition(x, y); zone.add(czarnyskoczek, false); } public void createCzarnyGoniec(final int x, final int y) { final Item czarnygoniec = SingletonRepository.getEntityManager() .getItem("czarny goniec"); czarnygoniec.setPosition(x, y); zone.add(czarnygoniec, false); } public void createCzarnyHetman(final int x, final int y) { final Item czarnyhetman = SingletonRepository.getEntityManager() .getItem("czarny hetman"); czarnyhetman.setPosition(x, y); zone.add(czarnyhetman, false); } public void createCzarnyKrol(final int x, final int y) { final Item czarnykrol = SingletonRepository.getEntityManager() .getItem("czarny król"); czarnykrol.setPosition(x, y); zone.add(czarnykrol, false); } public void createBialyPionek(final int x, final int y) { final Item bialypionek = SingletonRepository.getEntityManager() .getItem("biały pionek"); bialypionek.setPosition(x, y); zone.add(bialypionek, false); } public void createBialaWieza(final int x, final int y) { final Item bialawieza = SingletonRepository.getEntityManager() .getItem("biała wieża"); bialawieza.setPosition(x, y); zone.add(bialawieza, false); } public void createBialySkoczek(final int x, final int y) { final Item bialyskoczek = SingletonRepository.getEntityManager() .getItem("biały skoczek"); bialyskoczek.setPosition(x, y); zone.add(bialyskoczek, false); } public void createBialyGoniec(final int x, final int y) { final Item bialygoniec = SingletonRepository.getEntityManager() .getItem("biały goniec"); bialygoniec.setPosition(x, y); zone.add(bialygoniec, false); } public void createBialyHetman(final int x, final int y) { final Item bialyhetman = SingletonRepository.getEntityManager() .getItem("biały hetman"); bialyhetman.setPosition(x, y); zone.add(bialyhetman, false); } public void createBialyKrol(final int x, final int y) { final Item bialykrol = SingletonRepository.getEntityManager() .getItem("biały król"); bialykrol.setPosition(x, y); zone.add(bialykrol, false); } }
PolanieOnLine/PolanieOnLine
src/games/stendhal/server/maps/zakopane/playroom/PlaySet.java
179,436
package zad1_l13; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Okno extends JFrame{ private final JPanel panel; private final JLabel label_text; private final JLabel label_kolor; private JRadioButton radio_czerwony; private JRadioButton radio_zielony; private JRadioButton radio_niebieski; private final JLabel label_dlugosc; private JSlider slider_dlugosc; private final JButton button_czysc; private final JButton button_rysuj; public Okno(){ getContentPane().setBackground(new Color(141, 167, 142)); setSize(500, 540); setLayout(new FlowLayout()); label_text = new JLabel("Program rysujący figury."); add(label_text); panel = new JPanel(); panel.setPreferredSize(new Dimension(450, 450)); add(panel); //Powinno sie jeszcze dodac do grupy radiobuttonow label_kolor = new JLabel("Wybierz kolor:"); panel.add(label_kolor); radio_czerwony=new JRadioButton("Czerwony"); panel.add(radio_czerwony); radio_zielony=new JRadioButton("Zielony"); panel.add(radio_zielony); radio_niebieski=new JRadioButton("Niebieski"); panel.add(radio_niebieski); label_dlugosc = new JLabel("Wybierz dlugosc boku/promienia:"); panel.add(label_dlugosc); slider_dlugosc=new JSlider(JSlider.HORIZONTAL,10,100,10); slider_dlugosc.setMajorTickSpacing(10); slider_dlugosc.setPaintTicks(true); slider_dlugosc.setPaintLabels(true); panel.add(slider_dlugosc); button_czysc = new JButton("Czyść"); panel.add(button_czysc); button_rysuj = new JButton("Rysuj"); panel.add(button_rysuj); button_czysc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { panel.repaint(); } }); button_rysuj.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Figura figura = null; Graphics g = panel.getGraphics(); int dlugosc=slider_dlugosc.getValue(); if(radio_czerwony.isSelected()){ figura=new Trojkat(); figura.setDlugosc(dlugosc); g.setColor(Color.red); g.drawString(figura.informacja(),40,380); int tabX[]={150,150+figura.getDlugosc(),150+figura.getDlugosc()/2}; int tabY[]={200+figura.getDlugosc(),200+figura.getDlugosc(),200}; int n = tabX.length; g.fillPolygon( tabX, tabY, n ); }else if(radio_zielony.isSelected()){ figura=new Kwadrat(); figura.setDlugosc(dlugosc); g.setColor(Color.green); g.fillRect(170,200,figura.getDlugosc(),figura.getDlugosc()); g.drawString(figura.informacja(),60,380); }else if(radio_niebieski.isSelected()){ figura=new Kolo(); figura.setDlugosc(dlugosc); g.setColor(Color.blue); g.fillOval(170, 200, figura.getDlugosc(), figura.getDlugosc()); g.drawString(figura.informacja(),60,380); } } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } }
PaullWo/STUDIA-Programowanie_Obiektowe
Lab13/zad1_l13/src/zad1_l13/Okno.java
179,437
package com.oxygenum.splendor; import java.util.ArrayList; public class Card { private int color; private int points; private int number_of_niebieski; private int number_of_bialy; private int number_of_brazowy; private int number_of_zielony; private int number_of_czerwony; private String wym1; public int getNumber_of_niebieski() { return number_of_niebieski; } public int getNumber_of_bialy() { return number_of_bialy; } public int getNumber_of_brazowy() { return number_of_brazowy; } public int getNumber_of_zielony() { return number_of_zielony; } public int getNumber_of_czerwony() { return number_of_czerwony; } private int wym1_tlo; private String wym2; private int wym2_tlo; private String wym3; private int wym3_tlo; private String wym4; private int wym4_tlo; private int color_nr; public int getColorDrawable() { return color; } public int getColor() { return color_nr; } public String getPointsStr() { return Integer.toString(points); } public int getPoints(){ return points; } public String getWym1() { return wym1; } public int getWym1_tlo() { return wym1_tlo; } public String getWym2() { return wym2; } public int getWym2_tlo() { return wym2_tlo; } public String getWym3() { return wym3; } public int getWym3_tlo() { return wym3_tlo; } public String getWym4() { return wym4; } public int getWym4_tlo() { return wym4_tlo; } public Card(int color, int points, int number_of_brazowy, int number_of_bialy, int number_of_czerwony, int number_of_niebieski, int number_of_zielony) { this.color_nr = color -1; switch (color){ case 1: this.color = R.drawable.karta; break; case 2: this.color = R.drawable.karta2; break; case 3: this.color = R.drawable.karta3; break; case 4: this.color = R.drawable.karta4; break; case 5: this.color = R.drawable.karta5; break; } this.points = points; this.number_of_niebieski = number_of_niebieski; this.number_of_bialy = number_of_bialy; this.number_of_brazowy = number_of_brazowy; this.number_of_zielony = number_of_zielony; this.number_of_czerwony = number_of_czerwony; ArrayList<String> wym = new ArrayList<>(); ArrayList<Integer> wym_tlo = new ArrayList<>(); if (number_of_brazowy != 0){ wym.add(Integer.toString(number_of_brazowy)); wym_tlo.add(R.drawable.zeton3); } if (number_of_bialy != 0){ wym.add(Integer.toString(number_of_bialy)); wym_tlo.add(R.drawable.zeton2); } if (number_of_czerwony != 0){ wym.add(Integer.toString(number_of_czerwony)); wym_tlo.add(R.drawable.zeton5); } if (number_of_niebieski != 0){ wym.add(Integer.toString(number_of_niebieski)); wym_tlo.add(R.drawable.zeton); } if (number_of_zielony != 0){ wym.add(Integer.toString(number_of_zielony)); wym_tlo.add(R.drawable.zeton4); } while (wym.size() < 4){ wym.add(""); wym_tlo.add(R.drawable.zeton6); } wym1 = wym.get(0); wym2 = wym.get(1); wym3 = wym.get(2); wym4 = wym.get(3); wym1_tlo = wym_tlo.get(0); wym2_tlo = wym_tlo.get(1); wym3_tlo = wym_tlo.get(2); wym4_tlo = wym_tlo.get(3); } }
oxygenum44/Splendor
app/src/main/java/com/oxygenum/splendor/Card.java
179,439
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package algorytmy; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import static java.lang.System.in; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.imageio.ImageIO; import mainPackage.RGB; /** * * @author Robert Gaca */ public class segmentacjaLiter { private static final int czarny = Color.BLACK.getRGB(); private static final int bialy = Color.WHITE.getRGB(); private static final int czerwony = Color.RED.getRGB(); private static final int zielony = Color.GREEN.getRGB(); private static final int niebieski = Color.BLUE.getRGB(); private static final int zolty = Color.YELLOW.getRGB(); private int licznikLiter; private int licznikWierszy; public static BufferedImage szkieletyzacja1(BufferedImage in) { List<BufferedImage> listaWierszy = new ArrayList<>(); List<BufferedImage> listaLiter = new ArrayList<>(); HashMap<String, ArrayList<Integer>> czarneWiersze = new HashMap<>(); BufferedImage out; listaWierszy = wydobycieWierszy(in); for (BufferedImage l : listaWierszy) { listaLiter.add(wydobycieLiter(l)); } out = joiner(listaLiter); return out; } public static BufferedImage joiner(List<BufferedImage> in) { BufferedImage out; int width = 0; int height = 0; int startHeight = 0; int endHeight = 0; for (BufferedImage im : in) { width = im.getWidth(); height += im.getHeight(); } out = new BufferedImage(width, height, in.get(0).getType()); startHeight = 0; endHeight = 0; for (BufferedImage im : in) { endHeight += im.getHeight(); for (int i = 0; i < width; i++) { for (int j = startHeight, k = 0; j < endHeight; j++, k++) { out.setRGB(i, j, im.getRGB(i, k)); } } startHeight += im.getHeight(); } return out; } public static List<BufferedImage> wydobycieWierszy(BufferedImage in) { BufferedImage outtmp = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); outtmp = RGB.powiekszKopiujac(in, 0); out = RGB.powiekszKopiujac(in, 0); int width; int heigth; width = in.getWidth(); heigth = in.getHeight(); int waga = 0; int r, g, b; int straznik = 0; //Szukanie po wierszach i kopiowanie do nowego obrazka /** * Jesli posiada czarny piksel tzn ze jest litera i do listy dodajemy * wartosc tego wiersza pozostale wiersze wypelniamy na zolto */ HashMap<Integer, ArrayList<Integer>> czarneWiersze = new HashMap<>(); List<Integer> czarne = new ArrayList<>(); List<BufferedImage> wierszeObrazy = new ArrayList<>(); //wiersze ktore posiadaja czarne piksele for (int i = 0; i < width; i++) { for (int j = 0; j < heigth; j++) { if (RGB.getR(outtmp.getRGB(i, j)) == 0) { if (!czarne.contains(j)) { czarne.add(j); } } } } //wypelnianie pozostalych wierszy for (int i = 0; i < width; i++) { for (int j = 0; j < heigth; j++) { if (!czarne.contains(j)) { out.setRGB(i, j, zolty); } } } Collections.sort(czarne); int first, current, previous; int licznikwierszy = 1; first = czarne.get(0); previous = czarne.get(0); for (int i = 0; i < czarne.size(); i++) { //System.out.println(czarne.get(i)); current = czarne.get(i); if (current - previous > 1 || i == czarne.size() - 1) { //Jesli koniec petli ostatni wiersz obrazka if (i == czarne.size() - 1) { previous = current; } BufferedImage temp = new BufferedImage(out.getWidth(), (previous - first + 1), out.getType()); for (int k = 0; k < width; k++) { for (int l = first, m = 0; l <= previous; l++) { temp.setRGB(k, m++, out.getRGB(k, l)); } } wierszeObrazy.add(temp); first = current; } previous = current; } try { for (int i = 0; i < wierszeObrazy.size(); i++) { ImageIO.write(wierszeObrazy.get(i), "jpg", new File("out/wiersz" + (i + 1) + ".jpg")); } } catch (Exception e) { e.getMessage(); } return wierszeObrazy; } public static BufferedImage wydobycieLiter(BufferedImage in) { BufferedImage outtmp = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); outtmp = RGB.powiekszKopiujac(in, 0); out = RGB.powiekszKopiujac(in, 0); int width; int heigth; width = in.getWidth(); heigth = in.getHeight(); int waga = 0; int r, g, b; int straznik = 0; //Szukanie po wierszach i kopiowanie do nowego obrazka /** * Jesli posiada czarny piksel tzn ze jest litera i do listy dodajemy * wartosc tego wiersza pozostale wiersze wypelniamy na zolto */ HashMap<Integer, ArrayList<Integer>> czarneWiersze = new HashMap<>(); List<Integer> czarne = new ArrayList<>(); List<List<Integer>> odcinki = new ArrayList<>(); //wiersze ktore posiadaja czarne piksele for (int i = 0; i < width; i++) { for (int j = 0; j < heigth; j++) { if (RGB.getR(outtmp.getRGB(i, j)) == 0) { if (!czarne.contains(i)) { czarne.add(i); } } } } //wypelnianie pozostalych wierszy for (int i = 0; i < width; i++) { for (int j = 0; j < heigth; j++) { if (!czarne.contains(i)) { out.setRGB(i, j, zolty); } } } Collections.sort(czarne); //znacznik konca listy dodana wartosc wieksza o 2 od ostatniego wyrazu //zeby poprawnie przeszla petla i zauwazyla roznice w celu zazanczenia kolumny czarne.add(czarne.get(czarne.size() - 1) + 2); int first, previous, current, count, max, roznica; first = czarne.get(0); previous = czarne.get(0); max = heigth; count = 0; for (int k : czarne) { current = k; roznica = current - previous; if (roznica > 1) { List<Integer> tempList = new ArrayList<>(); for (int i = first; i <= previous; i++) { tempList.add(i); } odcinki.add(tempList); first = current; } previous = current; } //sprawdzanie kazdego odcinka boolean zawieraCzarne = false; for (List l : odcinki) { for (int j = 0; j < heigth; j++) { zawieraCzarne = false; for (int i = 0; i < l.size(); i++) { int w = (int) l.get(i); if (RGB.getB(out.getRGB(w, j)) == 0) { zawieraCzarne = true; } } if (zawieraCzarne == false) { for (int i = 0; i < l.size(); i++) { int w = (int) l.get(i); out.setRGB(w, j, czerwony); } } } } return out; } public static BufferedImage wycinanieLitery(BufferedImage in){ BufferedImage out ; int up=0,down=0,left=0,right=0; //UP outloop:for (int i = 0; i < in.getWidth(); i++) { for (int j = 0; j < in.getHeight(); j++) { if(RGB.getR(in.getRGB(i, j))==0 && RGB.getG(in.getRGB(i, j))==0 && RGB.getB(in.getRGB(i, j))==0){ up = i; break outloop; } } } //Down outloop:for (int i = 0; i < in.getWidth(); i++) { for (int j = in.getHeight()-1; j >=0 ; j--) { if(RGB.getR(in.getRGB(i, j))==0 && RGB.getG(in.getRGB(i, j))==0 && RGB.getB(in.getRGB(i, j))==0){ down = i; break outloop; } } } //Left outloop:for (int j = 0; j < in.getHeight(); j++) { for (int i = 0; i < in.getWidth(); i++) { if(RGB.getR(in.getRGB(i, j))==0 && RGB.getG(in.getRGB(i, j))==0 && RGB.getB(in.getRGB(i, j))==0){ left = j; break outloop; } } } //Right outloop:for (int j = 0; j < in.getHeight(); j++) { for (int i = in.getWidth()-1; i >0; i--) { if(RGB.getR(in.getRGB(i, j))==0 && RGB.getG(in.getRGB(i, j))==0 && RGB.getB(in.getRGB(i, j))==0){ right = j; break outloop; } } } System.out.println("Left "+left+" right "+right+" up "+up+" down "+down); int newwidth,newheight; newwidth = in.getWidth()-left-(in.getWidth()-right-1); newheight = in.getHeight()-up-(in.getHeight()-down-1); out = new BufferedImage(newwidth,newheight,in.getType()); for (int i = left,k=0; i <=right; i++,k++) { for (int j = up,l=0; j <=down; j++,l++) { out.setRGB(k, l, in.getRGB(i, j)); } } return out; } }
gqc3k/AIPO
src/main/java/algorytmy/segmentacjaLiter.java
179,442
import java.awt.Color; import java.awt.event.*; import javax.swing.*; public class ZdarzeniaAkcja extends JPanel { public ZdarzeniaAkcja() { JButton przyciskCzerwony = new JButton("Czerwony"); przyciskCzerwony.addActionListener(new ObslugaCzerwony()); add(przyciskCzerwony); JButton przyciskNiebieski = new JButton("Niebiski"); przyciskNiebieski.addActionListener(new ObslugaNiebieski()); add(przyciskNiebieski); } class ObslugaCzerwony implements ActionListener { public void actionPerformed(ActionEvent e) { setBackground(Color.RED); } } class ObslugaNiebieski implements ActionListener { public void actionPerformed(ActionEvent evt) { setBackground(Color.BLUE); } } }
kubaxd864/ZSEiT
Java/Java/ZdarzeniaAkcja.java
179,443
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Listing45 extends JPanel implements ActionListener { JButton przyciskCzerwony, przyciskNiebieski; public Listing45() { przyciskCzerwony = new JButton( "Czerwony" ); przyciskCzerwony.addActionListener( this ); add( przyciskCzerwony ); przyciskNiebieski = new JButton( "Niebieski" ); przyciskNiebieski.addActionListener( this ); add( przyciskNiebieski ); } public void actionPerformed( ActionEvent evt ) { if ( evt.getSource() == przyciskCzerwony ) setBackground( Color.RED ); else if ( evt.getSource() == przyciskNiebieski ) setBackground( Color.BLUE ); } }
spec-reki/ZSEiT
2022.2023/p.Byszewski/Java - console apps/Listing 4/Listing45.java
179,445
//zadanie 2 public class Main2 { public static void main(String[] args){ Zakupy pomidor = new Zakupy("pomidor",2.4,"świeży, czerwony, z Polski"); pomidor.buy(); pomidor.showInfo(); } }
Prawy126/Java
Laby/lab 8/src/Main2.java
179,446
package zad1; public class Rose extends Flower{ public Rose(String nazwa, double cena) { super(nazwa,cena); } public Rose(int ilosc) { super(ilosc); } public Integer getIlosc() { return super.ilosc; }; public String getKolor() { return "czerwony"; } public double getCena() { return super.cena; } public String getNazwa() { return "róża"; } }
axelGITT/UTP
UTP2/src/zad1/Rose.java
179,448
// [Programowanie Java GUI - lekcja 28: Nimbus LookAndFeel] - https://www.youtube.com/watch?v=1W5BWdvg52I&list=PL3298E3EB8CFDE9BA&index=28 package Lesson28; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; public class AdvancedNotepad extends JFrame implements ActionListener { private JTextArea textArea; private JMenuBar menuBar; private JMenu fileMenu, toolsMenu, lookAndFeelMenu, helpMenu; private JMenuItem closeItem, saveItem, openItem, aboutItem; private JComboBox<String> colorCombo; private JTextField searchField; private JButton searchButton; private JColorChooser colorChooser; private JPanel sidePanel; public AdvancedNotepad() { setTitle("Zaawansowany Notatnik"); setSize(700, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(textArea); add(scrollPane, BorderLayout.CENTER); // Menu menuBar = new JMenuBar(); // File menu fileMenu = new JMenu("Plik"); saveItem = new JMenuItem("Zapisz"); openItem = new JMenuItem("Otwórz"); closeItem = new JMenuItem("Zamknij"); saveItem.addActionListener(this); openItem.addActionListener(this); closeItem.addActionListener(this); fileMenu.add(saveItem); fileMenu.add(openItem); fileMenu.addSeparator(); fileMenu.add(closeItem); // Look and Feel menu lookAndFeelMenu = new JMenu("Look and Feel"); for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { JMenuItem item = new JMenuItem(info.getName()); item.addActionListener(e -> { try { UIManager.setLookAndFeel(info.getClassName()); SwingUtilities.updateComponentTreeUI(this); } catch (Exception ex) { ex.printStackTrace(); } }); lookAndFeelMenu.add(item); } // Help menu helpMenu = new JMenu("Pomoc"); aboutItem = new JMenuItem("O programie"); aboutItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "Zaawansowany Notatnik v1.0")); helpMenu.add(aboutItem); // Add menus to menubar menuBar.add(fileMenu); menuBar.add(lookAndFeelMenu); menuBar.add(helpMenu); setJMenuBar(menuBar); // Side Panel sidePanel = new JPanel(); sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS)); colorCombo = new JComboBox<>(new String[] {"Czarny", "Czerwony", "Niebieski"}); colorCombo.addActionListener(e -> { switch (colorCombo.getSelectedItem().toString()) { case "Czarny": textArea.setForeground(Color.BLACK); break; case "Czerwony": textArea.setForeground(Color.RED); break; case "Niebieski": textArea.setForeground(Color.BLUE); break; } }); searchField = new JTextField(10); searchButton = new JButton("Szukaj"); searchButton.addActionListener(e -> { String searchTerm = searchField.getText(); if (!searchTerm.isEmpty()) { int start = textArea.getText().indexOf(searchTerm); if (start >= 0) textArea.select(start, start + searchTerm.length()); } }); JButton chooseColorButton = new JButton("Wybierz kolor"); chooseColorButton.addActionListener(e -> { Color newColor = JColorChooser.showDialog(this, "Wybierz kolor tekstu", textArea.getForeground()); if (newColor != null) textArea.setForeground(newColor); }); sidePanel.add(colorCombo); sidePanel.add(searchField); sidePanel.add(searchButton); sidePanel.add(chooseColorButton); add(sidePanel, BorderLayout.EAST); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == saveItem) { JFileChooser fileChooser = new JFileChooser(); int choice = fileChooser.showSaveDialog(this); if (choice == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try (FileWriter writer = new FileWriter(file)) { writer.write(textArea.getText()); } catch (IOException ioException) { ioException.printStackTrace(); } } } else if (e.getSource() == openItem) { JFileChooser fileChooser = new JFileChooser(); int choice = fileChooser.showOpenDialog(this); if (choice == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try (FileReader reader = new FileReader(file)) { textArea.read(reader, null); } catch (IOException ioException) { ioException.printStackTrace(); } } } else if (e.getSource() == closeItem) { System.exit(0); } } public static void main(String[] args) { AdvancedNotepad notepad = new AdvancedNotepad(); notepad.setVisible(true); } }
dawidolko/Programming-Java
JavaGUI/.Courses/Courses1/Lesson28/AdvancedNotepad.java
179,449
import java.awt.image.BufferedImage; /** * * @author Michal Wasniowski, Lukasz Wiktor */ public class ColorSpaceConverter { public static int getLuminanceFromBufferedImage(BufferedImage image, int x, int y) { if(x < 0 || y < 0 || x >= image.getWidth() || y >= image.getHeight() ) { return 0; } return getLuminanceFromRGB(image.getRGB(x, y)); } public static int getLuminanceFromRGB(int rgb) { int red = getRedFromRGB(rgb); // czerwony int green = getGreenFromRGB(rgb); // zielony int blue = getBlueFromRGB(rgb); // niebieski return getLuminanceFromRGB(red, green, blue); } public static int getRGBFromLuminance(int lum) { int rgb = 0; //set red if (lum < 0) { rgb += (-lum << 16); } //set green //rgb += (0 << 8); //set blue if (lum > 0) { rgb += lum; } return rgb; } public static int getLuminanceFromRGB(int red, int green, int blue) { // acording to formula from lecture // Y = 0,299R + 0,587G + 0,114B double result = 0.299* red + 0.587*green + 0.114*blue; return (int)result; } public static int getRedFromRGB(int rgb) { return (rgb & 0x00ff0000) >> 16; } public static int getGreenFromRGB(int rgb) { return (rgb & 0x0000ff00) >> 8; } public static int getBlueFromRGB(int rgb) { return (rgb & 0x000000ff); } public static int getRGBFromRedGreenBlue(int red, int green, int blue) { int rgb = 0xff000000; rgb += red << 16; rgb += green << 8; rgb += blue; return rgb; } public static int getMeanRed(int point00, int point01, int point10, int point11) { int red = getRedFromRGB(point00); red += getRedFromRGB(point01); red += getRedFromRGB(point10); red += getRedFromRGB(point11); return red /= 4; } public static int getMeanGreen(int point00, int point01, int point10, int point11) { int green = getGreenFromRGB(point00); green += getGreenFromRGB(point01); green += getGreenFromRGB(point10); green += getGreenFromRGB(point11); return green /= 4; } public static int getMeanBlue(int point00, int point01, int point10, int point11) { int blue = getBlueFromRGB(point00); blue += getBlueFromRGB(point01); blue += getBlueFromRGB(point10); blue += getBlueFromRGB(point11); return blue /= 4; } public static int getMeanRGB(int rgb1, int rgb2, int rgb3, int rgb4) { int green = getMeanGreen(rgb1, rgb2, rgb3, rgb4); int red = getMeanRed(rgb1, rgb2, rgb3, rgb4); int blue = getMeanBlue(rgb1, rgb2, rgb3, rgb4); int rgb = ColorSpaceConverter.getRGBFromRedGreenBlue(red, green, blue); return rgb; } }
cauchych/VideoIndexer
src/ColorSpaceConverter.java
179,451
package zad2; class Peony extends Flower { Peony(int i) { super(i); this.setColour("czerwony"); } @Override public String toString() { return "piwonia"; } }
AgelkazzWrenchsprocket/PJATK_JAVA_GUI
lab2/src/zad2/Peony.java
179,452
import java.awt.Color; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; public abstract class ColorFactory { private static final HashMap<String,Color> map=new HashMap<String,Color>() { { put("Czerwony",Color.RED); put("Zielony",Color.GREEN); put("Niebieski",Color.BLUE); put("Żółty",Color.YELLOW); } }; private static final List<String> keys=map.keySet().stream().sorted().collect(Collectors.toList()); public static List<String> getKeys() { return keys; } public static Color make(String name) { return map.get(name); } }
Ch3shireDev/WIT-Zajecia
semestr-8/Programowanie obiektowe w Java/alexander/POJ/Archiwum/2022w/ID07IO1/Factory/src/ColorFactory.java
179,459
public class Lab6Zad8 { public static void main(String[] args) { String str = "zielony,niebieski,czerwony"; String str1 = str.substring(0, 6); String str2 = str.substring(7, 15); System.out.println(str); System.out.println(str1); System.out.println(str2); } }
dominikkugler/java2023
Lab6Zad8.java
179,460
public class Lab6Zad7 { public static void main(String[] args) { String str = "zielony,niebieski,czerwony"; String[] results = str.split(","); for (String result : results) { System.out.println(result); } } }
dominikkugler/java2023
Lab6Zad7.java
179,466
public enum Colour { RED("Czerwony"), GREEN("Zielony"), BLUE("Niebieski"); private String description; Colour(String description) { this.description = description; } public String getDescription() { return description; } }
GrzegorzAcademy/JSE-task
src/Colour.java
179,467
package pl.edu.pjwstk.s8267.GUI.Lab11; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; public class Z4 extends JFrame { private Drawer painter; private JCheckBoxMenuItem laczaca; public Z4() { super("Skromny edytor graficzny"); setDefaultCloseOperation(EXIT_ON_CLOSE); painter = new Drawer(); setContentPane(painter); initMenuBar(); pack(); setVisible(true); } private void initMenuBar() { JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu plik = new JMenu("Plik"); plik.setMnemonic(KeyEvent.VK_P); menuBar.add(plik); JMenuItem nowy = new JMenuItem("Nowy"); nowy.setMnemonic(KeyEvent.VK_N); nowy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); plik.add(nowy); JMenuItem otworz = new JMenuItem("Otworz"); otworz.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { loadFile(chooser.getSelectedFile().getAbsolutePath()); } } }); otworz.setMnemonic(KeyEvent.VK_O); otworz.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)); plik.add(otworz); JMenuItem zapisz = new JMenuItem("Zapisz"); zapisz.setMnemonic(KeyEvent.VK_Z); zapisz.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); plik.add(zapisz); plik.addSeparator(); JMenuItem koniec = new JMenuItem("Koniec"); koniec.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); koniec.setMnemonic(KeyEvent.VK_K); koniec.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); plik.add(koniec); JMenu punkty = new JMenu("Punkty"); punkty.setMnemonic(KeyEvent.VK_K); menuBar.add(punkty); JMenu kolory = new JMenu("Kolory"); punkty.add(kolory); ButtonGroup colorGroup = new ButtonGroup(); JRadioButtonMenuItem czerwony = new JRadioButtonMenuItem("czerwony"); czerwony.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShapeColor(Color.RED); painter.repaint(); } }); colorGroup.add(czerwony); czerwony.setMnemonic(KeyEvent.VK_C); kolory.add(czerwony); JRadioButtonMenuItem zielony = new JRadioButtonMenuItem("zielony"); zielony.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShapeColor(Color.GREEN); painter.repaint(); } }); colorGroup.add(zielony); zielony.setMnemonic(KeyEvent.VK_Z); kolory.add(zielony); JRadioButtonMenuItem niebieski = new JRadioButtonMenuItem("niebieski"); niebieski.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShapeColor(Color.BLUE); painter.repaint(); } }); colorGroup.add(niebieski); niebieski.setMnemonic(KeyEvent.VK_N); kolory.add(niebieski); kolory.addSeparator(); JRadioButtonMenuItem uzytkownika = new JRadioButtonMenuItem("użytkownika"); uzytkownika.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] clr = JOptionPane.showInputDialog(null, "Podaj kolor (rrr,ggg,bbb)", "Kolor punktu", JOptionPane.QUESTION_MESSAGE).replace("(", "").replace(")", "").split(","); painter.setShapeColor(new Color(Integer.parseInt(clr[0]), Integer.parseInt(clr[1]), Integer.parseInt(clr[2]))); painter.repaint(); } }); colorGroup.add(uzytkownika); uzytkownika.setMnemonic(KeyEvent.VK_U); kolory.add(uzytkownika); JMenu ksztalty = new JMenu("Kształty"); punkty.add(ksztalty); ButtonGroup shapeGroup = new ButtonGroup(); JRadioButtonMenuItem kolko = new JRadioButtonMenuItem("kółko"); kolko.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShape(Drawer.CIRCLE); painter.repaint(); } }); shapeGroup.add(kolko); kolko.setMnemonic(KeyEvent.VK_K); ksztalty.add(kolko); JRadioButtonMenuItem kwadrat = new JRadioButtonMenuItem("kwadrat"); kwadrat.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShape(Drawer.SQUARE); painter.repaint(); } }); shapeGroup.add(kwadrat); kwadrat.setMnemonic(KeyEvent.VK_W); ksztalty.add(kwadrat); JRadioButtonMenuItem krzyzyk = new JRadioButtonMenuItem("krzyżyk"); krzyzyk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setShape(Drawer.CROSS); painter.repaint(); } }); shapeGroup.add(krzyzyk); krzyzyk.setMnemonic(KeyEvent.VK_R); ksztalty.add(krzyzyk); JMenu linia = new JMenu("Linia"); linia.setMnemonic(KeyEvent.VK_L); menuBar.add(linia); laczaca = new JCheckBoxMenuItem("łącząca"); laczaca.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { painter.setDrawLine(laczaca.isSelected()); painter.repaint(); } }); laczaca.setMnemonic(KeyEvent.VK_C); linia.add(laczaca); linia.addSeparator(); JMenuItem kolorLinii = new JMenuItem("Kolor linii"); kolorLinii.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String[] clr = JOptionPane.showInputDialog(null, "Podaj kolor (rrr,ggg,bbb)", "Kolor linii", JOptionPane.QUESTION_MESSAGE).replace("(", "").replace(")", "").split(","); painter.setLineColor(new Color(Integer.parseInt(clr[0]), Integer.parseInt(clr[1]), Integer.parseInt(clr[2]))); painter.repaint(); } }); kolorLinii.setMnemonic(KeyEvent.VK_K); linia.add(kolorLinii); menuBar.add(Box.createHorizontalGlue()); JMenu about = new JMenu("O autorze"); about.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { JOptionPane.showMessageDialog(Z4.this, "Aplikacja stworzona przez:\nKrzysiek Bielicki\nhttp://skyman.pl", "O Autorze", JOptionPane.INFORMATION_MESSAGE); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); menuBar.add(about); } protected void loadFile(String absolutePath) { try { BufferedReader reader = new BufferedReader( new FileReader(absolutePath) ); String line; ArrayList<Point> points = new ArrayList<Point>(); while((line = reader.readLine()) != null) { String[] ptsString = line.split(" "); for(int i = 0; i < ptsString.length; i++) { String[] pString = ptsString[i].replace("(", "").replace(")", "").split(","); points.add(new Point(Integer.parseInt(pString[0].trim()), Integer.parseInt(pString[1].trim()))); } } painter.setPoints(points); pack(); painter.repaint(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { new Z4(); } }
krzysiekbielicki/GUI
Lab11/src/pl/edu/pjwstk/s8267/GUI/Lab11/Z4.java
179,468
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GUI extends Main { private JFrame frame; private JPanel panel; private JTextField colorInput; public void createAndShowGUI() { //Tworzenie Frame frame = new JFrame("Color Change App"); //Zakonczenie dzialania aplikacji po zamknieciu wyskakujacego okna frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //ustawienie wielkosci a nastepnie lokalizacji okna frame.setSize(400, 200); frame.setLocationRelativeTo(null); //Tworzenie Panelu panel = new JPanel(); frame.add(panel); JPanel inputPanel = new JPanel(); panel.add(inputPanel, BorderLayout.CENTER); inputPanel.setLayout(new BorderLayout()); JLabel label = new JLabel("Zmień kolor na:"); inputPanel.add(label, BorderLayout.NORTH); colorInput = new JTextField(20); inputPanel.add(colorInput, BorderLayout.CENTER); JButton confirmChange = new JButton("Potwierdź"); panel.add(confirmChange, BorderLayout.EAST); //metoda zmieniajaca kolor tla confirmChange.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String colorName = colorInput.getText().toLowerCase(); Color color = getColorFromName(colorName); if (color != null) { panel.setBackground(color); } else { JOptionPane.showMessageDialog(frame, "Nieprawidłowa nazwa koloru!", "Błąd", JOptionPane.ERROR_MESSAGE); } } }); frame.setVisible(true); } //Metoda zwracajaca kod koloru private Color getColorFromName(String colorName) { switch (colorName) { case "czerwony": return Color.RED; case "zielony": return Color.GREEN; case "niebieski": return Color.BLUE; default: return null; } } }
Jemdrek03/Laboratorium_3_Jezyki_Programowania
src/GUI.java
179,470
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class JPEGLS { private ArrayList<Scheme> schemes; private Pixel[][] bitmap; public JPEGLS(byte[] input) { initSchemes(); int width = input[13] * 256 + input[12] & 0xFF; int height = input[15] * 256 + input[14] & 0xFF; parseBitmap(Arrays.copyOfRange(input, 18, input.length - 26), width, height); } private static double log2(double x) { return Math.log(x) / Math.log(2); } public void printEncodingStats() { ArrayList<Color> colors = new ArrayList<>(); colors.add(Color.ALL); colors.add(Color.RED); colors.add(Color.GREEN); colors.add(Color.BLUE); for (Color color : colors) { int bestScheme = findBestSchemeID(color) + 1; System.out.println("\nNajlepszy schemat (kolor: " + color.name() + "):\t" + bestScheme + "\n\n"); } } public int findBestSchemeID(Color color) { System.out.println("=================== ENTROPIA WG SCHEMATU (kolor: " + color.name() + ") ==================="); double bestEntropy = Double.MAX_VALUE; int bestSchemeID = -1; for (Scheme scheme : schemes) { int id = schemes.indexOf(scheme); Pixel[][] encoded = encode(id); double entropy = getEntropy(encoded, color); if (entropy < bestEntropy) { bestEntropy = entropy; bestSchemeID = id; } System.out.println((id + 1) + ":\t" + entropy); } return bestSchemeID; } public Pixel[][] encode(int schemeID) { Scheme scheme = schemes.get(schemeID); Pixel[][] result = new Pixel[bitmap.length][bitmap[0].length]; for (int i = 0; i < bitmap.length; i++) { for (int j = 0; j < bitmap[0].length; j++) { Pixel n = i == 0 ? new Pixel() : bitmap[i - 1][j]; Pixel w = j == 0 ? new Pixel() : bitmap[i][j - 1]; Pixel nw = i == 0 || j == 0 ? new Pixel() : bitmap[i - 1][j - 1]; result[i][j] = bitmap[i][j].sub(scheme.count(n, w, nw)).mod(256); } } return result; } private void initSchemes() { schemes = new ArrayList<>(); schemes.add((n, w, nw) -> w); schemes.add((n, w, nw) -> n); schemes.add((n, w, nw) -> nw); schemes.add((n, w, nw) -> n.add(w).sub(nw)); schemes.add((n, w, nw) -> n.add(w.sub(nw)).div(2)); schemes.add((n, w, nw) -> w.add(n.sub(nw)).div(2)); schemes.add((n, w, nw) -> n.add(w).div(2)); schemes.add((n, w, nw) -> { int[] _n = new int[]{n.red, n.green, n.blue}; int[] _w = new int[]{w.red, w.green, w.blue}; int[] _nw = new int[]{nw.red, nw.green, nw.blue}; int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { int max = Math.max(_w[i], _n[i]); if (_nw[i] >= max) { rgb[i] = max; } else { int min = Math.min(_w[i], _n[i]); if (_nw[i] <= min) { rgb[i] = min; } else { rgb[i] = _w[i] + _n[i] - _nw[i]; } } } return new Pixel(rgb[0], rgb[1], rgb[2]); }); } private void parseBitmap(byte[] bitmapBytes, int width, int height) { bitmap = new Pixel[height][width]; for (int i = 0, k = 0; i < height; i++) { for (int j = 0; j < width; j++) { bitmap[i][j] = new Pixel(bitmapBytes[k * 3 + 2], bitmapBytes[k * 3 + 1], bitmapBytes[k * 3]); k++; } } } public void printBitmapEntropyInfo() { System.out.println("=================== ENTROPIA (wg koloru) ==================="); System.out.println("wszystkie:\t" + getEntropy(bitmap, Color.ALL)); System.out.println("czerwony:\t" + getEntropy(bitmap, Color.RED)); System.out.println("zielony:\t" + getEntropy(bitmap, Color.GREEN)); System.out.println("niebieski:\t" + getEntropy(bitmap, Color.BLUE)); System.out.println("\n"); } private double getEntropy(Pixel[][] bitmap, Color color) { HashMap<Integer, Integer> freq = new HashMap<>(); int size = 0; for (Pixel[] row : bitmap) { for (Pixel pixel : row) { if (color == Color.ALL || color == Color.RED) { freq.put(pixel.red, freq.getOrDefault(pixel.red, 0) + 1); size++; } if (color == Color.ALL || color == Color.GREEN) { freq.put(pixel.green, freq.getOrDefault(pixel.green, 0) + 1); size++; } if (color == Color.ALL || color == Color.BLUE) { freq.put(pixel.blue, freq.getOrDefault(pixel.blue, 0) + 1); size++; } } } return countEntropy(freq, size); } private double countEntropy(HashMap<Integer, Integer> freq, int size) { double sizeLog = log2(size); final double[] entropy = {0}; freq.forEach((color, occur) -> entropy[0] += (sizeLog - log2(occur)) * occur); return entropy[0] / size; } private enum Color { RED, GREEN, BLUE, ALL } private interface Scheme { Pixel count(Pixel n, Pixel w, Pixel nw); } }
malinowska423/kkd-2020
lista4/JPEGLS.java
179,471
package model.player; import java.io.Serializable; public class Player implements Serializable { private String nickname; private int color; //1 - blue, 2 - yellow, 3 - green, 4 - red private int score; private int id; private boolean isDrawing = false; private boolean isReady = false; private String lastAction; public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public boolean isDrawing() { return isDrawing; } public void setDrawing(boolean drawing) { isDrawing = drawing; } public boolean isReady() { return isReady; } public void setReady(boolean ready) { isReady = ready; } public String getLastAction() { return lastAction; } public void setLastAction(String lastAction) { this.lastAction = lastAction; } public String getColor() { switch (color){ case 1: return "Niebieski"; case 2: return "Żółty"; case 3: return "Zielony"; case 4: return "Czerwony"; } return "brak"; } public void setColor(int color) { this.color = color; } }
toczak/LudoGameFX
src/main/java/model/player/Player.java
179,478
package books.api.service; import books.api.model.User; import books.api.model.user.Reputation; import org.springframework.stereotype.Service; @Service public class UserServiceImpl { public Reputation getUserReputation(int userId) { return new Reputation(100.0); } public User getUser(int id) { User user = new User(id); user.setReputation(getUserReputation(id)); user.setUserName("czerwony"); return user; } }
chemicL/books
books-api/src/main/java/books/api/service/UserServiceImpl.java
179,486
package pl.tlasica.goalskeeper; import android.graphics.Color; import java.text.SimpleDateFormat; import java.util.Calendar; public class Handy { private static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm"); public static int calToNum(Calendar cal) { int acc = 0; acc += cal.get(Calendar.YEAR) * 10000; acc += (cal.get(Calendar.MONTH)+1) * 100; acc += cal.get(Calendar.DAY_OF_MONTH); return acc; } private static void resetTime(Calendar cal) { cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); } public static Calendar numToCal(int num) { Calendar c = Calendar.getInstance(); resetTime(c); int year = num / 10000; int month = ((num % 10000) / 100)-1; int day = num % 100; c.set(year, month, day); return c; } public static int diffDays(Calendar a, Calendar b) { long diff = Math.abs( a.getTimeInMillis() - b.getTimeInMillis()); return (int)(diff / (1000 * 60 * 60 * 24)); //daysBetween(LocalDate.fromCalendarFields(tstamp), LocalDate.fromCalendarFields(now)).getDays() } public static String toString(Calendar tstamp) { return FORMAT.format(tstamp.getTime()); } public static int doneColor(Boolean done) { if (done!=null && done) { return Color.parseColor("#99CC00"); } else return Color.WHITE; //else return Color.parseColor("#FF4444"); (taki czerwony) } }
tlasica/Habitoo
src/pl/tlasica/goalskeeper/Handy.java
179,489
package kosmos; /** * Enum type to store some basic information about a planet * * @author Antoni Pokusiński * @version 1.0 date: 27-01-2022 */ public enum Planeta { ZIEMIA(5.976e+24, 12742L, 150000000L, 365.256, "Niebieski", TypPlanety.SKALISTA), MERKURY(3.303e+23, 4879L, 57910000L, 87.969, "Szary", TypPlanety.SKALISTA), WENUS(4.869e+24, 12103L, 108200000L, 224.701, "Żółty", TypPlanety.SKALISTA), MARS(6.421e+23, 6779L, 227900000L, 686.980,"Czerwony", TypPlanety.SKALISTA), JOWISZ(1.9e+27, 139822L, 778500000L, 4332.589, "Pomarańczowy", TypPlanety.GAZOWA), SATURN(5.688e+26, 116464L, 1434000000L, 10759.22, "Żółty", TypPlanety.GAZOWA), URAN(8.686e+25, 50724L, 2872460000L, 30685.4, "Cyjan", TypPlanety.LODOWO_GAZOWA), NEPTUN(1.024e+26, 49244L, 4495000000L, 60189, "Niebieski", TypPlanety.LODOWO_GAZOWA); public enum TypPlanety { SKALISTA, GAZOWA, LODOWO_GAZOWA; } double masa; //kg long srednica; //km long odleglosc; //km double czas_obiegu; //dni String kolor; TypPlanety typ; /** * Constructs and initializes a planet, given some basic characteristics * @param masa planet's weight * @param srednica planet's diameter * @param odleglosc average distance to the Sun * @param czas_obiegu orbital period * @param kolor planet's color * @param typ planet's type (based on its chemical composition) */ private Planeta(double masa, long srednica, long odleglosc, double czas_obiegu, String kolor, TypPlanety typ) { this.masa = masa; this.srednica = srednica; this.odleglosc = odleglosc; this.czas_obiegu = czas_obiegu; this.kolor = kolor; this.typ = typ; } /** * Simple getter function * @return planet's average distance to the Sun */ public double getOdleglosc() { return this.odleglosc; } }
panantoni01/University
Sem5_2021-2022/Java/Lista_13/kosmos/Planeta.java
179,493
import java.util.ArrayList; public class QuantumCoder { public Pixel[][] filteredLow; public Pixel[][] filteredHigh; public byte[] bytes; public Pixel[][] quantified; private TGAAnalyzer tga; private int k; public QuantumCoder(TGAAnalyzer tga, int k) { this.tga = tga; this.k = k; this.filteredLow = null; this.filteredHigh = null; this.bytes = null; this.quantified = null; } public static byte[] differentialCoding(byte[] bytes) { byte[] result = new byte[bytes.length]; result[0] = bytes[0]; for (int i = 1; i < bytes.length; i++) { result[i] = (byte) (bytes[i] - bytes[i - 1]); } return result; } public static ArrayList<Integer> differentialDecoding(ArrayList<Integer> diffs) { ArrayList<Integer> result = new ArrayList<>(); int a = diffs.get(0); result.add(a); for (int i = 1; i < diffs.size(); i++) { a += diffs.get(i); result.add(a); } return result; } public void encode() { filteredLow = new Pixel[tga.height][tga.width]; filteredHigh = new Pixel[tga.height][tga.width]; for (int i = 0; i < tga.height; i++) { for (int j = 0; j < tga.width; j++) { filteredLow[i][j] = filters(i, j, false); filteredHigh[i][j] = filters(i, j, true); } } byte[] byteArray = differentialCoding(TGAAnalyzer.pixelsToBytes(filteredLow)); for (int i = 0; i < byteArray.length; i++) { byte x = byteArray[i]; byteArray[i] = (byte) (x > 0 ? 2 * x : Math.abs(x) * 2 + 1); } StringBuilder bitStringBuilder = new StringBuilder(); for (byte x : byteArray) { bitStringBuilder.append(EliasGamma.encode(x)); } String bitString = bitStringBuilder.toString(); if (bitString.length() % 8 != 0) { bitString += "0".repeat(8 - (bitString.length() % 8)); } bytes = getBytesFromBinaryString(bitString); quantified = quantify(filteredHigh); } public byte[] decode() { String content = getBinaryStringFromBytes(tga.bitmapBytes); ArrayList<Integer> codes = EliasGamma.decode(content); codes.forEach(x -> x = x % 2 == 0 ? x / 2 : -(x / 2)); ArrayList<Integer> decoded = differentialDecoding(codes); byte[] bytes = new byte[decoded.size()]; for (int i = 0; i < decoded.size(); i++) { bytes[i] = decoded.get(i).byteValue(); } return tga.getTGABytes(bytes); } private Pixel filters(int x, int y, boolean high) { int[][] weightsLow = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}; int[][] weightsHigh = {{0, -1, 0}, {-1, 5, -1}, {0, -1, 0}}; int[][] weights = high ? weightsHigh : weightsLow; Pixel pixel = new Pixel(); for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { pixel = pixel.add(tga.getBitmapItem(x + i, y + j).mul(weights[i + 1][j + 1])); } } int weightsSum = 0; for (int[] row : weights) { for (int weight : row) { weightsSum += weight; } } weightsSum = weightsSum < 0 ? 1 : weightsSum; pixel = pixel.div(weightsSum); pixel = pixel.max(0); pixel = pixel.min(255); return pixel; } private Pixel[][] quantify(Pixel[][] pixels) { Pixel[][] quantifiedPixels = new Pixel[pixels.length][pixels[0].length]; int step = (int) (256 / Math.pow(2, k)); for (int i = 0; i < pixels.length; i++) { for (int j = 0; j < pixels[0].length; j++) { quantifiedPixels[i][j] = pixels[i][j].quantization(step); } } return quantifiedPixels; } byte[] getBytesFromBinaryString(String s) { int size = (s.length() / 8) + (s.length() % 8 > 0 ? 1 : 0); byte[] bytes = new byte[size]; for (int i = 0, k = 0; i < size; i++, k += 8) { try { bytes[i] = (byte) Short.parseShort(s.substring(k, k + 8), 2); } catch (StringIndexOutOfBoundsException e) { bytes[i] = (byte) Short.parseShort(s.substring(k), 2); } } return bytes; } public void stats(String statsTitle, Pixel[][] changed) { System.out.println(statsTitle); System.out.println("Blad sredniokwadaratowy "); double mse = mse(changed); System.out.println("\t(ogolny)\t" + mse); System.out.println("\t(czerwony)\t" + mse(changed, 0)); System.out.println("\t(zielony)\t" + mse(changed, 1)); System.out.println("\t(niebieski)\t" + mse(changed, 2)); System.out.println("Stosunek sygnalu do szumu: " + snr(mse)); System.out.println("\n"); } public double mse(Pixel[][] changed) { double sum = 0; for (int i = 0; i < tga.height; i++) { for (int j = 0; j < tga.width; j++) { sum += euclidSquared(getPixelAsDoubleArray(tga.getBitmap()[i][j]), getPixelAsDoubleArray(changed[i][j])); } } return sum / (tga.width * tga.height); } public double mse(Pixel[][] changed, int color) { double sum = 0; for (int i = 0; i < tga.height; i++) { for (int j = 0; j < tga.width; j++) { int a, b; switch (color) { case 0 -> { a = tga.getBitmap()[i][j].red; b = changed[i][j].red; } case 1 -> { a = tga.getBitmap()[i][j].green; b = changed[i][j].green; } case 2 -> { a = tga.getBitmap()[i][j].blue; b = changed[i][j].blue; } default -> { a = 0; b = 0; } } sum += Math.pow(a - b, 2); } } return sum / (tga.width * tga.height); } public double snr(double MSE) { double sum = 0; for (Pixel[] row : tga.getBitmap()) { for (Pixel pixel : row) { sum += Math.pow(pixel.red, 2) + Math.pow(pixel.green, 2) + Math.pow(pixel.blue, 2); } } return (sum / (tga.width * tga.height)) / MSE; } private double euclidSquared(Double[] a, Double[] b) { double sum = 0; for (int i = 0; i < a.length; i++) { sum += Math.pow((a[i] - b[i]), 2); } return sum; } private Double[] getPixelAsDoubleArray(Pixel a) { Double[] x = new Double[3]; x[0] = (double) a.red; x[1] = ((double) a.green); x[2] = ((double) a.blue); return x; } private String getBinaryStringFromBytes(byte[] bytes) { StringBuilder s = new StringBuilder(); for (byte aByte : bytes) { s.append(String.format("%8s", Integer.toBinaryString(aByte & 0xFF)).replace(' ', '0')); } return s.toString(); } }
malinowska423/kkd-2020
lista6/QuantumCoder.java
179,502
package Z4ElementsGUI; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // zastosowanie rozdzielnych listnerów public class Sample003AListner { JButton czerwonyButton, niebieskiButton,resetButton; JTextField poletekstowe; private JButton przycisk(int x, int y, String textJButton){ JButton sampleJButton = new JButton(); sampleJButton.setBounds(x,y,200,50); sampleJButton.setText(textJButton); return sampleJButton; } private JPanel myContentPane() { JPanel myPanel = new JPanel(null); int liczba = 0; myPanel.setBackground(Color.white); czerwonyButton = przycisk(100,200, "Czerwony"); niebieskiButton = przycisk(200,400,"Niebieski"); resetButton = przycisk(400, 600,"Reset"); poletekstowe = new JTextField(20); poletekstowe.setBounds(10,50,180,50); czerwonyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myPanel.setBackground(Color.black); String cos = poletekstowe.getText(); int liczba = Integer.valueOf(cos); poletekstowe.setText("Podaj nową liczbę"); System.out.println(liczba); } }); ; /* czerwonyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myPanel.setBackground(Color.red); } }); */ niebieskiButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myPanel.setBackground(Color.blue); String napis = poletekstowe.getText(); System.out.println(napis); poletekstowe.setText(""); } }); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myPanel.setBackground(Color.white); } }); myPanel.add(poletekstowe); myPanel.add(czerwonyButton); myPanel.add(niebieskiButton); myPanel.add(resetButton); return myPanel; } public Sample003AListner () { JFrame myWindow = new JFrame("JButton Sample"); myWindow.setContentPane(myContentPane()); myWindow.setSize(900, 800); myWindow.setLayout(null); myWindow.setResizable(false); myWindow.setLocationRelativeTo(null); myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myWindow.setVisible(true); } public static void main (String[] args) { new Sample003AListner(); } }
zbigolo/Klasa3pp_2324
src/Z4ElementsGUI/Sample003AListner.java
179,503
package Z4ElementsGUI; // zastosowanie listnera dla wszystkich import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.*; import java.awt.event.ActionEvent; public class Sample003BListner { JButton czerwonyButton, niebieskiButton,resetButton; JLabel etykieta; private JButton przycisk(int x, int y, String textJButton, String command){ JButton sampleJButton = new JButton(); sampleJButton.setBounds(x,y,200,50); sampleJButton.setText(textJButton); sampleJButton.setBackground(Color.white); sampleJButton.setSelected(false); sampleJButton.setActionCommand(command); return sampleJButton; } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == czerwonyButton) { czerwonyButton.setBackground(Color.red); niebieskiButton.setBackground(Color.red); etykieta.setText(czerwonyButton.getText()); } if(source == niebieskiButton){ czerwonyButton.setBackground(Color.blue); niebieskiButton.setBackground(Color.blue); resetButton.setBackground(Color.yellow); etykieta.setText(niebieskiButton.getText().toString()); } } public void actionPerformed2(ActionEvent e) { Object source = e.getActionCommand(); if(source.equals("reset")){ czerwonyButton.setBackground(Color.white); niebieskiButton.setBackground(Color.white); resetButton.setBackground(Color.white); etykieta.setText(""); } } private JPanel myContentPane() { JPanel myPanel = new JPanel(null); etykieta = new JLabel(); etykieta.setBounds(400,250,200,50); etykieta.setVisible(true); etykieta.setOpaque(true); etykieta.setBackground(Color.white); czerwonyButton = przycisk(100,200, "Czerwony","czerwony"); niebieskiButton = przycisk(200,400,"Niebieski","niebieski"); resetButton = przycisk(400, 600,"Reset","reset"); czerwonyButton.addActionListener(this::actionPerformed); niebieskiButton.addActionListener(this::actionPerformed); resetButton.addActionListener(this::actionPerformed2); myPanel.add(etykieta); myPanel.add(czerwonyButton); myPanel.add(niebieskiButton); myPanel.add(resetButton); return myPanel; } public Sample003BListner () { JFrame myWindow = new JFrame("JButton Sample"); myWindow.setContentPane(myContentPane()); myWindow.setSize(900, 800); myWindow.setLayout(null); myWindow.setResizable(false); myWindow.setLocationRelativeTo(null); myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myWindow.setVisible(true); } public static void main (String[] args) { new Sample003BListner(); } }
zbigolo/Klasa3pp_2324
src/Z4ElementsGUI/Sample003BListner.java
179,505
package application.langtonsant.entity; import javafx.scene.paint.Color; import java.io.Serializable; /** * Wrapper dla klasy javafx.scene.paint.Color, umożliwiający jego serializację. */ public class SavableColor implements Serializable { private long serialVersionUID = 1L; /** * Czerwony. */ private double r; /** * Zielony. */ private double g; /** * Niebieski. */ private double b; /** * Przeźroczystość. */ private double opacity; /** * Ustala wartości pól z instancji javafx.scene.paint.Color. * @param color Instancja klasy javafx.scene.paint.Color. */ public SavableColor(Color color) { r = color.getRed(); g = color.getGreen(); b = color.getBlue(); opacity = color.getOpacity(); } /** * Ustala wartości pól z instancji javafx.scene.paint.Color. * @param color Instancja klasy javafx.scene.paint.Color. */ public void setFromColorClass(Color color) { r = color.getRed(); g = color.getGreen(); b = color.getBlue(); opacity = color.getOpacity(); } /** * Zwraca instancję javafx.scene.paint.Color. * @return Instancja klasy Obiekt klasy javafx.scene.paint.Color. */ public Color toColorClass() { return new Color(r, g, b, opacity); } }
wukash-r/langant
src/application/langtonsant/entity/SavableColor.java
179,507
package Lab4; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Zadanie2 extends JFrame { private JPanel panel1; private JComboBox comboBox1; private JTextArea textArea1; private JButton smallerButton; private JButton fatButton; private JButton italicsButton; private JButton biggerButton; private JLabel kolorLabel; private JLabel edytorLabel; public static void main(String[] args) { Zadanie2 zadanie2 = new Zadanie2(); zadanie2.setVisible(true); } public Zadanie2() { super("Zadanie 2"); this.setContentPane(this.panel1); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setSize(600, 400); comboBox1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String color = String.valueOf(comboBox1.getSelectedItem()); switch (color) { case "czerwony" -> textArea1.setForeground(Color.RED); case "czarny" -> textArea1.setForeground(Color.BLACK); case "zielony" -> textArea1.setForeground(Color.GREEN); case "niebieski" -> textArea1.setForeground(Color.BLUE); case "zolty" -> textArea1.setForeground(Color.YELLOW); case "szary" -> textArea1.setForeground(Color.GRAY); } } }); fatButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textArea1.setFont(new Font("Bold", Font.BOLD, textArea1.getFont().getSize())); } }); italicsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textArea1.setFont(new Font("Italic", Font.ITALIC, textArea1.getFont().getSize())); } }); smallerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textArea1.setFont(new Font("Smaller", textArea1.getFont().getStyle(), textArea1.getFont().getSize() - 1)); } }); biggerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textArea1.setFont(new Font("Smaller", textArea1.getFont().getStyle(), textArea1.getFont().getSize() + 1)); } }); } }
Tomasz3976/Swing
src/Lab4/Zadanie2.java
179,508
package com.example.lenovo.string_color; public class generatorList { String nazwaKoloruMnemoniczna = null; String kolorFałszywyHex = null; String nazwaFalszywegoKoloru = null; String falszywyHexButton = null; String falszywyHexButtonMnemoniczna = null; generatorList(String nazwaKoloruMnemoniczna, String kolorFałszywyHex, String nazwaFalszywegoKoloru, String falszywyHexButton, String falszywyHexButtonMnemoniczna) { this.nazwaKoloruMnemoniczna = nazwaKoloruMnemoniczna; this.kolorFałszywyHex = kolorFałszywyHex; this.nazwaFalszywegoKoloru = nazwaFalszywegoKoloru; this.falszywyHexButton = falszywyHexButton; this.falszywyHexButtonMnemoniczna = falszywyHexButtonMnemoniczna; } public String getStringColor() { return nazwaKoloruMnemoniczna; } public String getFalszywyHex() { return kolorFałszywyHex; } public String getNazwaFalszywegoKoloru() { return nazwaFalszywegoKoloru; } public String getFalszywyHexButton() { return falszywyHexButton; } public String getFalszywyHexButtonMnemoniczna() { return falszywyHexButtonMnemoniczna; } /*generatorList kolor_1 = new generatorList("niebieski", "#ff0000", "czerwony");*/ }
michalszmyt95/itmProj
string_color/app/src/main/java/com/example/lenovo/string_color/generatorList.java
179,510
package pl.gornik.shape; public enum ColorType { RED("czerwony"), BLUE("niebieski"), YELLOW("żółty"), GREEN("zielony"), BLACK("czarny"), WHITE("biały"); private String color; ColorType(String color) { this.color = color; } public String getColor() { return color; } }
lkoin/Enum
src/pl/gornik/shape/ColorType.java
179,511
package Adapter; /** * Created by K.Karkucinski on 2016-12-29. */ public class DodgeChallenger implements SportowySamochod { private int szybkosc = 290; private String kolor= "Czerwony"; public void spalanie() { System.out.println("Spalanie 13l na 100 km"); } public int getSzybkosc() { return szybkosc; } public String getKolor() { return kolor; } }
adrych/DesignPatterns
06Adapter/Students/2016/kkarkucinski/Adapter/DodgeChallenger.java
179,513
package składniki; public class CzerwonyŚledź extends Składnik { }
barteksad/OOP
Egzamin 2017/src/składniki/CzerwonyŚledź.java
179,516
package day2.owoce; public class Jablko extends BaseOwoc { public Jablko(int waga) { kolor = "czerwony"; this.waga = waga; cena = 1; } @Override public String pobierzKolor() { return kolor; } }
juzerBasia/SII_fimoteka
src/main/java/day2/owoce/Jablko.java
179,518
import javax.swing.*; public class PanelLista extends JPanel { public PanelLista() { String[] kolory = {"Czerwony", "Niebieski", "Żółty"}; String[] pory = {"Wiosna", "Lato", "Jesień", "Zima"}; JComboBox<String> kolor = new JComboBox<String>(kolory); kolor.addItem("Biały"); kolor.addItem("Czarny"); kolor.setEditable(true); kolor.setBounds(20, 20, 160, 30); JComboBox<String> pora = new JComboBox<String>(pory); pora.setSelectedItem(2); pora.setBounds(20, 70, 160, 30); add(kolor); add(pora); setLayout(null); } }
juanmeister420/zseit
programowanie_obiektowe/byszewski/rys2.10/PanelLista.java
179,519
import javax.swing.*; import java.awt.*; public class PanelOpcja extends JPanel { public PanelOpcja() { String[] kolory = {"Czerwony", "Niebieski", "Żółty"}; String[] pory = {"Wiosna", "Lato", "Jesień", "Zima"}; JRadioButton [] opcjeKolor = new JRadioButton[kolory.length]; for(int k = 0; k < kolory.length; k++) opcjeKolor[k] = new JRadioButton(kolory[k]); JRadioButton [] opcjePora = new JRadioButton[pory.length]; for(int i = 0; i < pory.length; i++) opcjePora[i] = new JRadioButton(pory[i]); ButtonGroup KolorGrupa = new ButtonGroup(); for( JRadioButton opcja : opcjeKolor) KolorGrupa.add(opcja); ButtonGroup PoraGrupa = new ButtonGroup(); for( JRadioButton opcja : opcjePora) PoraGrupa.add(opcja); JPanel panelKolor = new JPanel(new GridLayout(3, 1)); panelKolor.setBounds(10, 10, 110, 80); panelKolor.setBorder(BorderFactory.createRaisedBevelBorder()); for( JRadioButton opcja : opcjeKolor) panelKolor.add(opcja); JPanel panelPora = new JPanel(new GridLayout(4, 1)); panelPora.setBounds(150, 10, 110, 100); panelPora.setBorder(BorderFactory.createRaisedBevelBorder()); for( JRadioButton opcja : opcjePora) panelPora.add(opcja); opcjeKolor[1].setSelected(true); opcjePora[2].setSelected(true); add(panelKolor); add(panelPora); setLayout( null ); } }
juanmeister420/zseit
programowanie_obiektowe/byszewski/rys2.12/PanelOpcja.java
179,521
package mapDiscovery; import lejos.nxt.*; import lejos.robotics.localization.OdometryPoseProvider; import lejos.robotics.navigation.*; import lejos.robotics.objectdetection.*; public class Discovery { static int BLUE_L; static int BLUE_H; static int RED_L; static int RED_H; static int BLACK_L; static int BLACK_H; static int WHITE_L; static int WHITE_H; static int pos_x = 3; static int pos_y = -1; static int orient = 0; // 0-N, 1-E, 2-S, 3-W static Pose nice_pose; private static void setColorValues(LightSensor light) { String kolory[] = {"bialy", "czarny", "niebieski", "czerwony"}; int wartosci[] = new int[4]; for (int i=0; i<4; i++) { LCD.clear(); LCD.drawString("Pokaz 1 " + kolory[i], 0, 0); LCD.drawString("I nacisnij prawy", 0, 1); while(!Button.RIGHT.isDown()) { int value = light.getNormalizedLightValue(); LCD.drawInt(value, 0,2); } while(!Button.RIGHT.isUp()) {} int v_min = light.getNormalizedLightValue(); /*int v_max = v_min;*/ /*int tab[] = new int[3]; for (int j=1; j<4; j++) { LCD.clear(); LCD.drawString("Pokaz " + (j + 1) + " " + kolory[i], 0, 0); while(!Button.RIGHT.isDown()) { int next_v = light.getNormalizedLightValue(); LCD.drawInt(next_v, 0,2); } while(!Button.RIGHT.isUp()) {} int temp = light.getNormalizedLightValue(); tab[j-1] = temp; /*if (temp > v_max) v_max = temp; else if (temp < v_min) v_min = temp;*/ //}*/ //wartosci[i] = Math.round((v_min + tab[0] + tab[1] + tab[2]) / 4); wartosci[i] = v_min; /*switch (i){ case 0: WHITE_L = v_min - 10; WHITE_H = v_max + 100; break; case 1: BLACK_L = v_min; BLACK_H = v_max; break; case 2: BLUE_L = v_min - 100; BLUE_H = v_max; break; case 3: RED_L = v_min; RED_H = v_max; break; }*/ } WHITE_L = wartosci[0]; BLACK_L = wartosci[1]; //BLUE_L = wartosci[2]; RED_L = wartosci[3]; /*if (RED_H < WHITE_L) { WHITE_L = RED_H; } if (BLACK_H < RED_L) { int diff = Math.abs(BLACK_H - RED_L); BLACK_H = BLACK_H + Math.round(2 * diff / 3.0f) + 1; RED_L = BLACK_H; }*/ } private static String color(int value) { int b_d, k_d, r_d, w_d; //b_d = Math.abs(value - BLUE_L); int min;// = b_d; String ret_val = "blue"; k_d = Math.abs(value - BLACK_L); //if (k_d < min) { min = k_d; ret_val = "black"; //} r_d = Math.abs(value - RED_L); if (r_d < min) { min = r_d; ret_val = "red"; } w_d = Math.abs(value - WHITE_L); if (w_d < min) { min = w_d; ret_val = "white"; } return ret_val; /*if ((value > BLACK_L)&&(value <= BLACK_H)) return "black"; if ((value > BLUE_L)&&(value <= BLUE_H)) return "blue"; if ((value > WHITE_L)&&(value <= WHITE_H)) return "white"; if ((value > RED_L)&&(value <= RED_H)) return "red"; return "unknown";*/ } private static String f_color(int value) { String color = color(value); if (color.contentEquals("black")) return "blue"; return color; } private static DMap moveOneFront(DifferentialPilot pilot, LightSensor light, DMap mapa) { int new_val = light.getNormalizedLightValue(); String start_color = color(new_val); String new_color = start_color; pilot.forward(); int new_col_val; do { new_col_val = light.getNormalizedLightValue(); new_color = color(new_col_val); } while (!new_color.contentEquals("black")); /*LCD.drawString(new_color, 0, 4); do { new_col_val = light.getNormalizedLightValue(); new_color = color(new_col_val); } while (new_color.contentEquals("black"));*/ pilot.stop(); if (start_color.contentEquals("black")){ pilot.travel(5); } else pilot.travel(30); correctPosition(pilot, light); //pilot.travel(100); // skorygowac aby nie wjezdzac na obiekty!! switch (orient) { case 0: pos_y++; break; case 1: pos_x++; break; case 2: pos_y--; break; case 3: pos_x--; break; }; new_color = f_color(light.getNormalizedLightValue()); LCD.drawString(new_color, 0, 4); if (new_color.contentEquals("blue")) { mapa.setField(pos_x, pos_y, 'N'); } else if (new_color.contentEquals("red")) { mapa.setField(pos_x, pos_y, 'C'); } else { mapa.setField(pos_x, pos_y, 'B'); } return mapa; } private static void correctPosition(DifferentialPilot pilot, LightSensor light) { //pilot.travel(7); int start_val = light.getNormalizedLightValue(); int now_val = start_val; String now_c = color(now_val); pilot.rotateLeft(); do { now_val = light.getNormalizedLightValue(); now_c = color(now_val); } while (!now_c.contentEquals("black")); pilot.stop(); //pilot.rotate(5.0f); String out = color(light.getNormalizedLightValue()); //pilot.rotate(-5.0f); OdometryPoseProvider pp = new OdometryPoseProvider(pilot); Pose pose; pilot.rotateRight(); try { Thread.sleep(250); } catch (InterruptedException e1) { e1.printStackTrace(); } do { now_val = light.getNormalizedLightValue(); now_c = color(now_val); } while (!now_c.contentEquals(out)); pose = pp.getPose(); double rotation = pose.getHeading() * -1.0f; if (!color(start_val).contentEquals("black")){ rotation = rotation / 2.0f; } pilot.rotate(rotation); pp = new OdometryPoseProvider(pilot); now_val = light.getNormalizedLightValue(); now_c = color(now_val); start_val = now_val; pilot.forward(); try { Thread.sleep(2500); } catch (InterruptedException e) { e.printStackTrace(); } now_val = light.getNormalizedLightValue(); now_c = color(now_val); while (!now_c.contentEquals("black")) { now_val = light.getNormalizedLightValue(); now_c = color(now_val); } pilot.stop(); pilot.travel((pp.getPose().getX() / -2.0f) + 30.0f); return; } private static DMap goAWay(String way, DifferentialPilot pilot, LightSensor light, DMap mapa) { for (int i=0; i<way.length(); i++) { char next_l = way.charAt(i); if (next_l == 'r') { pilot.rotate(-90.0f); orient = (orient + 1) % 4; } else if (next_l == 'l') { pilot.rotate(90.0f); orient = (orient - 1); if (orient == -1) { orient = 3; } } else if (next_l == 'f') { mapa = moveOneFront(pilot, light, mapa); } }; return mapa; } public static void main(String[] args) throws Exception { LightSensor light = new LightSensor(SensorPort.S4); DifferentialPilot pilot = new DifferentialPilot(56, 128, Motor.C, Motor.B); pilot.setTravelSpeed(75.0f); pilot.setRotateSpeed(25.0f); setColorValues(light); LCD.clear(); //int iterator = 0; /*LCD.clear(); LCD.drawString("w " + WHITE_L + " " + WHITE_H, 0, 0); LCD.drawString("r " + RED_L + " " + RED_H, 0, 1); LCD.drawString("b " + BLUE_L + " " + BLUE_H, 0, 2); LCD.drawString("k " + BLACK_L + " " + BLACK_H, 0, 3);*/ while(!Button.ENTER.isDown()) { } DMap mapa = new DMap(); /*iterator = 0; while(!Button.ESCAPE.isDown()) { int value = light.getNormalizedLightValue(); if (iterator % 10 == 0) LCD.clear(); String color = color(value); LCD.drawString(color, 0, 1); LCD.drawInt(value, 0,0); iterator++; }*/ mapa = moveOneFront(pilot, light, mapa); mapa.setField(pos_x, pos_y, 'S'); while (mapa.unknownCount() > 0){ LCD.drawInt(mapa.unknownCount(), 0, 7); String way = mapa.findAWay(pos_x, pos_y, orient); // W odległości manhatańskiej/taksówkowej //LCD.drawString("" + pos_x + "x" + pos_y, 0, 3); //LCD.drawString(way, 0, 4); mapa = goAWay(way, pilot, light, mapa); } mapa.printOnDisplay(); Sound.beep(); while(!Button.RIGHT.isDown()) { } } }
Hazardius/miniature-map-creator
mapDiscovery/src/mapDiscovery/Discovery.java
179,522
package kwiat; import ogrod.*; public class Kwiat { int ilosclisci; void kwitnie(){ System.out.println("kwiat kwitnie"); } public Platek metoda() { return new Platek(); } protected class Platek implements Ogrod { public void Platek(){} public void kolor(){ System.out.println("Kolor Kawiatka jest czerwony"); } } }
ntmagda/inneCwiczeniaJAVA
Iterfejsy i inne/src/kwiat/Kwiat.java
179,523
import javax.swing.*; import java.awt.*; public class PanelOpcja2 extends JPanel { public PanelOpcja2() { String[] kolory = {"Czerwony", "Niebieski", "Żółty"}; String[] pory = {"Wiosna", "Lato", "Jesień", "Zima"}; JCheckBox [] opcjeKolor = new JCheckBox[kolory.length]; for(int k = 0; k < kolory.length; k++) opcjeKolor[k] = new JCheckBox(kolory[k]); JCheckBox [] opcjePora = new JCheckBox[pory.length]; for(int i = 0; i < pory.length; i++) opcjePora[i] = new JCheckBox(pory[i]); ButtonGroup KolorGrupa = new ButtonGroup(); for( JCheckBox opcja : opcjeKolor) KolorGrupa.add(opcja); ButtonGroup PoraGrupa = new ButtonGroup(); for( JCheckBox opcja : opcjePora) PoraGrupa.add(opcja); JPanel panelKolor = new JPanel(new GridLayout(3, 1)); panelKolor.setBounds(10, 10, 110, 80); panelKolor.setBorder(BorderFactory.createRaisedBevelBorder()); for( JCheckBox opcja : opcjeKolor) panelKolor.add(opcja); JPanel panelPora = new JPanel(new GridLayout(4, 1)); panelPora.setBounds(150, 10, 110, 100); panelPora.setBorder(BorderFactory.createRaisedBevelBorder()); for( JCheckBox opcja : opcjePora) panelPora.add(opcja); opcjeKolor[1].setSelected(true); opcjePora[2].setSelected(true); add(panelKolor); add(panelPora); setLayout( null ); } }
juanmeister420/zseit
programowanie_obiektowe/byszewski/rys2.13/PanelOpcja2.java
179,526
package _0A_Zdarzenia; /** @version 1.30 2000-06-03 @author Cay Horstmann zastosowanie anonimowej klasy wewnetrznej */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestPrzyciskow2 { public static void main(String[] args) { RamkaPrzyciskow2 ramka = new RamkaPrzyciskow2(); ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ramka.setVisible(true); } } /** Ramka, zawierajaca panel przycisk�w */ class RamkaPrzyciskow2 extends JFrame { public RamkaPrzyciskow2() { setTitle("TestPrzyciskow"); setSize(SZEROKOSC, WYSOKOSC); // dolacz panel do ramki PanelPrzyciskow2 panel = new PanelPrzyciskow2(); Container powZawartosci = getContentPane(); powZawartosci.add(panel); } public static final int SZEROKOSC = 300; public static final int WYSOKOSC = 200; } /** Panel, zawierajacy trzy przyciski */ class PanelPrzyciskow2 extends JPanel { public PanelPrzyciskow2() { // skonstruuj przyciski zbudujPrzycisk("Zolty", Color.yellow); zbudujPrzycisk("Niebieski", Color.blue); zbudujPrzycisk("Czerwony", Color.red); } void zbudujPrzycisk(String nazwa, final Color kolorTla) { JButton przycisk = new JButton(nazwa); add(przycisk); // Sluchacz, zmieniajacy kolor tla panelu // anonimowa klasa wewnetrzna implementujaca ActionListener przycisk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent zdarzenie) { setBackground(kolorTla); repaint(); } }); } }
pdobrzynski/Java_Wyklad
src/_0A_Zdarzenia/TestPrzyciskow2.java
179,528
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package debugging; import client.Main; import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.debug.Arrow; import com.jme3.scene.shape.Box; /** * * @author 48793 */ public class DebugUtils { public static void addArrow(Node node,AssetManager a){ Arrow arrow = new Arrow(Vector3f.UNIT_Z.mult(7f)); putShape(node, arrow, ColorRGBA.Red,a).setLocalTranslation(new Vector3f(0, 0.01f, 0)); //x - czerwony } private static Geometry putShape(Node node, Mesh shape, ColorRGBA color,AssetManager a) { Geometry g = new Geometry("coordinate axis", shape); Material mat = new Material(a, "Common/MatDefs/Misc/Unshaded.j3md"); mat.getAdditionalRenderState().setWireframe(true); mat.getAdditionalRenderState().setLineWidth(4); mat.setColor("Color", color); g.setMaterial(mat); node.attachChild(g); return g; } public static Node createUnshadedBoxNode(){ Box box2 = new Box(0.2f,0.2f,0.2f); Geometry red = new Geometry("Box", box2); Material mat2 = new Material(Main.getInstance().getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat2.setColor("Color", ColorRGBA.Red); red.setMaterial(mat2); Node n = new Node(); n.attachChild(red); return n; } }
MakaryBardowski/BHMultiplayer
src/main/java/debugging/DebugUtils.java
179,530
import zad1.*; import zad2.*; import zad3.Book; import zad3.Bookstore; import zad3.Client; import zad3.Novel; public class App { public static void main(String[] args) { // Exercise 1.1-1.7 Point[] points = new Point[]{ new Point(), new Point(5, 12), new Point(2, 121), }; for (Point point : points) { System.out.println(point); point.description(); point.move(4, 3); point.description(); // point.clear(); point.description(); System.out.println("\n"); } // Exercise 1.8 - 1.10 Figura figura = new Figura(points[1]); System.out.println(figura.opis()); Okrag[] okregi = new Okrag[]{ new Okrag(), new Okrag(new Point(5, 12), 5), new Okrag(points[1], 6), }; for (Okrag okrag : okregi) { System.out.println(okrag); System.out.println(okrag.getPowierzchnia()); System.out.println(okrag.getSrednica() + "\n"); } // Exercise 1.11 - 1.12 Prostokat prostokat = new Prostokat(15, 10, "Czerwony"); System.out.println(prostokat.getKolor()); System.out.println(prostokat.getX() + " " + prostokat.getY()); // Exercise 1.13 Trojkat trojkat = new Trojkat(3, 5, "Zielony"); System.out.println(trojkat); System.out.println(trojkat.getKolor()); // Exercise 1.14 - 1.15 prostokat.przesun(3, 5); System.out.println("\nProstokat przesuniety: " + prostokat.getX() + " " + prostokat.getY()); // Exercise 1.16 - 1.17 Kwadrat kwadrat = new Kwadrat(5, 5, "Fioletowy"); System.out.println(kwadrat.getX() + " " + kwadrat.getY() + " "); // Exercise 1.18 - 1.19 System.out.println(kwadrat.opis()); // Exercise 1.20 Okrag okrag1 = new Okrag(points[2], 5, "Niebieski"); System.out.println(okrag1.opis()); // Exercise 2 Car car = new Car("BMW", "Seria 5", "Sedan", "Czarny", 2020, 21980); System.out.println(car); PassengerCar passengerCar = new PassengerCar("Mercedes", "E klasa", "Sedan", "Srebrny", 2021, 43122, 1800, 2400, 5); System.out.println(passengerCar); // Exercise 3 Bookstore bookStore = new Bookstore("HelloBoook"); bookStore.printName(); Book book = new Book("Stary czlowiek i morze", 1830, "Novel", "Tom Ford"); book.printBook(); System.out.println("\nCreating novel:"); Novel novelBook = new Novel("Nowy czlowiek i stare morze", 2020, "Zycie zycie jest nowela", "Ronaldinho", "MESSI ANKARA MESSI ANKARA MESSI UENA MESSI ANKARA MESSI ANKARA MESSI ANKARA MESSI ANKARA MESSI\r\n"); novelBook.printBook(); Client client = new Client("John", "booooooookstor"); client.printName(); } }
Tnovyloo/Java-OOP
Lab06/lab06/src/App.java
179,531
package com.project.app.domain.enumeration; /** * The Fields enumeration. */ public enum Fields { ZIELONY, CZERWONY, CZARNY, }
w3raza/AGH-Science-Clubs
src/main/java/com/project/app/domain/enumeration/Fields.java
179,532
package pl.lodz.p.it.ssbd2020.ssbd04.entities; /** * Reprezentuje kolor klasy miejsc. */ public enum SeatClassColor { /** * RED - Kolor czerwony */ RED, /** * ORANGE - Kolor pomarańczowy */ ORANGE, /** * YELLLOW - Kolor żółty */ YELLOW, /** * OLIVE - Kolor oliwkowy */ OLIVE, /** * GREEN - Kolor zielony */ GREEN, /** * TEAL - Kolor turkusowy */ TEAL, /** * BLUE - Kolor niebieski */ BLUE, /** * VIOLET - Kolor fioletowy */ VIOLET, /** * PURPLE - Kolor purpurowy */ PURPLE, /** * PINK - Kolor różowy */ PINK, /** * BROWN - Kolor brązowy */ BROWN, /** * GREY - Kolor szary */ GREY, /** * BLACK - Kolor czarny */ BLACK }
ssbd-bilelotpol/ssbd202004
src/main/java/pl/lodz/p/it/ssbd2020/ssbd04/entities/SeatClassColor.java
179,569
package com.blstream.myhoard.controller; import com.blstream.myhoard.biz.exception.ErrorCode; import com.blstream.myhoard.biz.exception.MyHoardException; import com.blstream.myhoard.biz.model.MediaDTO; import com.blstream.myhoard.biz.model.UserDTO; import com.blstream.myhoard.biz.service.MediaService; import com.blstream.myhoard.biz.service.MediaServiceImpl; import com.blstream.myhoard.validator.MediaValidator; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.*; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartHttpServletRequest; /** * * @author gohilukk */ @Controller @RequestMapping(value = "/media") public class MediaController { // @Autowired private MediaService<MediaDTO> mediaService; private MediaValidator mediaValidator; public void setMediaValidator(MediaValidator mediaValidator) { this.mediaValidator = mediaValidator; } public void setMediaService(MediaService<MediaDTO> mediaService) { this.mediaService = mediaService; } @RequestMapping(method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody public List<MediaDTO> getMedia(HttpServletRequest request) { UserDTO user = (UserDTO) request.getAttribute("user"); Map<String, Object> params = new HashMap<>(); params.put("owner", Integer.parseInt(user.getId())); return mediaService.getList(params); } @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = {"image/jpeg", "image/png", "image/gif"}) @ResponseStatus(HttpStatus.OK) @ResponseBody public byte[] get(@PathVariable String id, @RequestParam(value = "size", defaultValue = "0") String size, HttpServletRequest request) { mediaValidator.validateGet(request, id); return mediaService.getThumbnail(Integer.parseInt(id), Integer.parseInt(size)); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public MediaDTO addMedia(MultipartHttpServletRequest request) { mediaValidator.validatePost(request); try { MediaDTO media = new MediaDTO(); UserDTO user = (UserDTO) request.getAttribute("user"); MultiValueMap<String, MultipartFile> map = request.getMultiFileMap(); MultipartFile file = map.values().iterator().next().iterator().next(); media.setFile(file.getBytes()); media.setOwner(user.getId()); mediaService.create(media); return media; } catch (IOException ex) { throw new MyHoardException(ErrorCode.BAD_REQUEST).add("file", "Niepoprawny plik"); } } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void removeMedia(@PathVariable String id, HttpServletRequest request) { mediaValidator.validateDelete(request, id); mediaService.remove(Integer.parseInt(id)); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public MediaDTO updateMedia(@PathVariable String id, HttpServletRequest request) { byte[] file = mediaValidator.validatePut(request, id); MediaDTO media = mediaService.get(Integer.parseInt(id)); media.setFile(file); mediaService.update(media); return media; } @RequestMapping(value = "/{id}/thumbnailShow", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody public void getThumbnailShowSize(@PathVariable String id, @RequestParam(value = "size", defaultValue = "0") String size, HttpServletRequest request, HttpServletResponse response) { try { UserDTO user = (UserDTO) request.getAttribute("user"); MediaDTO media = mediaService.get(Integer.parseInt(id)); if (!user.getId().equals(media.getOwner())) { throw new MyHoardException(ErrorCode.FORBIDDEN).add("id", "Brak uprawnień do zasobu."); } byte[] imageBytes = mediaService.getThumbnail(Integer.parseInt(id), Integer.parseInt(size)); response.setContentType("image/jpeg"); response.setContentLength(imageBytes.length); response.getOutputStream().write(imageBytes); } catch (IOException ex) { throw new MyHoardException(ErrorCode.BAD_REQUEST).add("file", "Niepoprawny plik"); } catch (NumberFormatException ex) { throw new MyHoardException(ErrorCode.BAD_REQUEST).add("id", "Niepoprawny identyfikator."); } } @ExceptionHandler(MyHoardException.class) public void returnCode(MyHoardException exception, HttpServletResponse response) throws IOException { // @ResponseBody odmawiało posłuszeństwa z niewyjaśnionych powodów response.setStatus(exception.getResponseStatus()); response.setContentType("application/json;charset=UTF-8"); response.getOutputStream().write(exception.toError().toString().getBytes("UTF-8")); } }
intive/myHoard_Java2
src/main/java/com/blstream/myhoard/controller/MediaController.java
179,570
package com.blstream.myhoard.controller; import com.blstream.myhoard.biz.exception.ErrorCode; import com.blstream.myhoard.biz.exception.MyHoardError; import com.blstream.myhoard.biz.exception.MyHoardException; import com.blstream.myhoard.biz.model.UserDTO; import com.blstream.myhoard.biz.service.ResourceService; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping(value = "/users") public class UserController { private ResourceService<UserDTO> userService; public void setUserService(ResourceService<UserDTO> userService) { this.userService = userService; } @RequestMapping(method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody public List<UserDTO> getUsers(HttpServletRequest request) { UserDTO user =(UserDTO) request.getAttribute("user"); Map<String, Object> params = new HashMap<>(); params.put("currentUsername", user.getUsername()); return userService.getList(params); } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public UserDTO addUser(@RequestBody @Valid UserDTO user, BindingResult result) { if (user.getUsername() != null && result.hasFieldErrors("username") || result.hasFieldErrors("email") || result.hasFieldErrors("password")) { MyHoardException exception = new MyHoardException(ErrorCode.BAD_REQUEST); if (user.getUsername() != null && result.hasFieldErrors("username")) exception.add("username", result.getFieldError("username").getDefaultMessage()); if (result.hasFieldErrors("email")) exception.add("email", "Niepoprawny adres e-mail: " + user.getEmail()); if (result.hasFieldErrors("password")) exception.add("password", result.getFieldError("password").getDefaultMessage()); throw exception; } userService.create(user); return user; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @ResponseBody public UserDTO getUser(@PathVariable String id, HttpServletRequest request) { try { UserDTO user = (UserDTO)request.getAttribute("user"); if (!user.getId().equals(id)) throw new MyHoardException(ErrorCode.FORBIDDEN); return userService.get(Integer.parseInt(id)); } catch (NumberFormatException ex) { throw new MyHoardException(ErrorCode.BAD_REQUEST).add("id", "Niepoprawne id"); } } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public UserDTO updateUser(@PathVariable String id, @RequestBody @Valid UserDTO user, BindingResult result, HttpServletRequest request) { UserDTO currentUser = (UserDTO)request.getAttribute("user"); if (!currentUser.getId().equals(id)) throw new MyHoardException(ErrorCode.FORBIDDEN); if (user.getUsername() != null && result.hasFieldErrors("username") || user.getEmail() != null && result.hasFieldErrors("email") || user.getPassword()!= null && result.hasFieldErrors("password")) { MyHoardException exception = new MyHoardException(ErrorCode.BAD_REQUEST); if (user.getUsername() != null && result.hasFieldErrors("username")) exception.add("username", result.getFieldError("username").getDefaultMessage()); if (result.hasFieldErrors("email")) exception.add("email", "Niepoprawny adres e-mail: " + user.getEmail()); if (result.hasFieldErrors("password")) exception.add("password", result.getFieldError("password").getDefaultMessage()); throw exception; } user.setId(id); currentUser.updateObject(user); userService.update(user); return user; } @RequestMapping(value = "/current", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public UserDTO updateCurrentUser(@RequestBody @Valid UserDTO user, BindingResult result, HttpServletRequest request) { UserDTO currentUser = (UserDTO)request.getAttribute("user"); if (user.getUsername() != null && result.hasFieldErrors("username") || user.getEmail() != null && result.hasFieldErrors("email") || user.getPassword()!= null && result.hasFieldErrors("password")) { MyHoardException exception = new MyHoardException(ErrorCode.BAD_REQUEST); if (user.getUsername() != null && result.hasFieldErrors("username")) exception.add("username", result.getFieldError("username").getDefaultMessage()); if (result.hasFieldErrors("email")) exception.add("email", "Niepoprawny adres e-mail: " + user.getEmail()); if (result.hasFieldErrors("password")) exception.add("password", result.getFieldError("password").getDefaultMessage()); throw exception; } user.setId(currentUser.getId()); currentUser.updateObject(user); userService.update(user); return user; } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) public void removeUser(@PathVariable String id, HttpServletRequest request) { try { UserDTO user = (UserDTO)request.getAttribute("user"); if (!user.getId().equals(id)) throw new MyHoardException(ErrorCode.FORBIDDEN); userService.remove(Integer.parseInt(id)); } catch (NumberFormatException ex) { throw new MyHoardException(ErrorCode.BAD_REQUEST).add("id", "Niepoprawne id"); } } @ExceptionHandler(MyHoardException.class) public void returnCode(MyHoardException exception, HttpServletResponse response) throws IOException { // @ResponseBody odmawiało posłuszeństwa z niewyjaśnionych powodów response.setStatus(exception.getResponseStatus()); response.setContentType("application/json;charset=UTF-8"); response.getOutputStream().write(exception.toError().toString().getBytes("UTF-8")); } }
intive/myHoard_Java2
src/main/java/com/blstream/myhoard/controller/UserController.java
179,574
package com.blstream.myhoard.controller; import com.blstream.myhoard.biz.exception.ErrorCode; import com.blstream.myhoard.biz.exception.MyHoardError; import com.blstream.myhoard.biz.exception.MyHoardException; import com.blstream.myhoard.biz.model.SessionDTO; import com.blstream.myhoard.biz.model.UserDTO; import com.blstream.myhoard.biz.service.ResourceService; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @Controller @RequestMapping(value = "/oauth/token") public class TokenController { private ResourceService<SessionDTO> sessionService; private ResourceService<UserDTO> userService; public void setSessionService(ResourceService<SessionDTO> sessionService) { this.sessionService = sessionService; } public void setUserService(ResourceService<UserDTO> userService) { this.userService = userService; } @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public SessionDTO login(@RequestBody @Valid UserDTO user, BindingResult result) { Map<String, Object> params = new HashMap<>(); if (user.getEmail() != null) params.put("email", user.getEmail()); else if (user.getUsername() != null) params.put("username", user.getUsername()); List<UserDTO> list = userService.getList(params); if (list.isEmpty() || list.size() > 1) throw new MyHoardException(ErrorCode.NOT_FOUND); UserDTO saved = list.get(0); user.setPassword(encode(user.getPassword())); if (user.getGrantType() != null) { if ((saved.getEmail().equals(user.getEmail()) || saved.getUsername().equals(user.getUsername())) && saved.getPassword().equals(user.getPassword())) { SessionDTO created; switch (user.getGrantType()) { case "password": //TODO Generowanie tokenu, temporary broken access_token Random random = new Random(); created = new SessionDTO("0", encode((java.util.Calendar.getInstance().getTime().toString()+user.getUsername()+random.nextInt())), java.util.Calendar.getInstance().getTime(), encode("refresh_token" + java.util.Calendar.getInstance().getTime()+user.getUsername()), saved.getId()); sessionService.create(created); return created; case "refresh_token": if(user.getRefreshToken() != null) { params.clear(); params.put("refreshToken", user.getRefreshToken()); if (sessionService.getList(params).isEmpty()) throw new MyHoardException(ErrorCode.NOT_FOUND).add("refresh_token", "Not found in database"); created = new SessionDTO("0", encode((java.util.Calendar.getInstance().getTime().toString()+user.getUsername())), java.util.Calendar.getInstance().getTime(), encode("refresh_token" + java.util.Calendar.getInstance().getTime()+user.getUsername()), saved.getId()); sessionService.create(created); return created; } else throw new MyHoardException(ErrorCode.AUTH_TOKEN_NOT_PROVIDED).add("refresh_token", "Missing field"); default: throw new MyHoardException(ErrorCode.BAD_REQUEST).add("grant_type", "Wrong value: " + user.getGrantType()); } } else throw new MyHoardException(ErrorCode.AUTH_BAD_CREDENTIALS); } else throw new MyHoardException(ErrorCode.BAD_REQUEST).add("grant_type", "Missing field"); } public static String encode(String tmp) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(tmp.getBytes()); String pass = new BigInteger(1, md.digest()).toString(16); return pass; } catch (NoSuchAlgorithmException e) { throw new MyHoardException(ErrorCode.INTERNAL_SERVER_ERROR).add("reason", "No such algorithm exception"); } } @ExceptionHandler(MyHoardException.class) // @ResponseBody public void returnCode(MyHoardException exception, HttpServletResponse response) throws IOException { // @ResponseBody odmawiało posłuszeństwa z niewyjaśnionych powodów response.setStatus(exception.getResponseStatus()); response.setContentType("application/json;charset=UTF-8"); response.getOutputStream().write(exception.toError().toString().getBytes("UTF-8")); // response.setStatus(exception.getResponseStatus()); // return exception.toError(); } }
intive/myHoard_Java2
src/main/java/com/blstream/myhoard/controller/TokenController.java
179,575
import sun.audio.AudioPlayer; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main_menu{ public JPanel mainPanel; private JLabel titleImg; private JButton mainCurrentWeatherButton; private JButton mainDailyWeatherButton; private JButton mainHourlyWeatherButton; public JButton mainLanguageButton; private JPanel upperMainPanel; private JPanel lowerMainPanel; private JButton mainMusicButton; public static String language = "en"; public static boolean isMusic = true; public Main_menu(){ //Main current weather button action listener mainCurrentWeatherButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Frame frameCurrentWeather = new Frame(); frameCurrentWeather.splitPanel.setRightComponent(GUI.currentWeather.mainPanel); GUI.frame.setContentPane(frameCurrentWeather.mainPanel); GUI.frame.setVisible(true); } }); //Main hourly weather button action listener mainHourlyWeatherButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Frame frameCurrentWeather = new Frame(); frameCurrentWeather.splitPanel.setRightComponent(GUI.hourlyWeather.contentPanel); GUI.frame.setContentPane(frameCurrentWeather.mainPanel); GUI.frame.setVisible(true); } }); //Main daily weather button action listener mainDailyWeatherButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Frame frameCurrentWeather = new Frame(); frameCurrentWeather.splitPanel.setRightComponent(GUI.dailyWeather.contentPanel); GUI.frame.setContentPane(frameCurrentWeather.mainPanel); GUI.frame.setVisible(true); } }); mainMusicButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (isMusic){ AudioPlayer.player.stop(GUI.BGM); isMusic = false; if(Main_menu.language.equals("en")) { mainMusicButton.setText("Music on"); } else if (Main_menu.language.equals("pl")){ mainMusicButton.setText("Włącz muzykę"); } } else{ AudioPlayer.player.start(GUI.BGM); isMusic = true; if(Main_menu.language.equals("en")) { mainMusicButton.setText("Music off"); } else if (Main_menu.language.equals("pl")){ mainMusicButton.setText("Wyłącz muzykę"); } } } }); mainLanguageButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GUI.currentWeather = new CurrentWeather(); GUI.dailyWeather = new DailyWeather(); GUI.hourlyWeather = new HourlyWeather(); if(language.equals("en")){ language = "pl"; mainLanguageButton.setText("English"); mainDailyWeatherButton.setText("Pogoda dzienna"); mainCurrentWeatherButton.setText("Pogoda na teraz"); mainHourlyWeatherButton.setText("Pogoda godzinowa"); if(isMusic) { mainMusicButton.setText("Wyłącz muzykę"); } else{ mainMusicButton.setText("Włącz muzykę"); } } else if (language.equals("pl")){ language = "en"; mainLanguageButton.setText("Polski"); mainDailyWeatherButton.setText("Daily weather"); mainCurrentWeatherButton.setText("Current weather"); mainHourlyWeatherButton.setText("Hourly weather"); if(isMusic) { mainMusicButton.setText("Music off"); } else{ mainMusicButton.setText("Music on"); } } } }); } //Customize action listeners of buttons private void createUIComponents() { } // public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException { // // //Declaring window // // System.setProperty( // "Quaqua.design","lion" // ); // // UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel"); // //setting size of window // frame.setPreferredSize(new Dimension(500, 500)); // frame.setMinimumSize(new Dimension(500, 500)); // // //setting spawn point of window // frame.setLocationRelativeTo(null); // // // Adding main panel to window // frame.setContentPane(new Main_menu().mainPanel); // frame.setVisible(true); // } }
maciekchylak/WeatherApp
src/main/java/Main_menu.java
179,576
package PGame; import javax.sound.sampled.*; import java.io.File; import java.util.ArrayList; /** * Klasa MusicPlayer */ public class MusicPlayer implements Runnable { /** * lista przechowująca muzykę */ private ArrayList<String> musicFiles; /** * index aktualnej muzyki */ private int currentSongIndex; /** * deklaracja obiektu Clip */ private Clip clip; /** * konstruktor MusicPlayer */ public MusicPlayer(String... files) { musicFiles = new ArrayList<String>(); for (String file : files) { musicFiles.add("Client/data/music/" + file + ".wav"); } } /** * metoda odpoweidzialna za dodanie muzyki * * @param fileName */ private void playSound(String fileName) { try { File soundFile = new File(fileName); AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); AudioFormat format = ais.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); clip = (Clip) AudioSystem.getLine(info); clip.open(ais); FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN); gainControl.setValue(-30); clip.start(); clip.loop(100); } catch (Exception e) { e.printStackTrace(); } } /** * metoda odpoweidzialna za włączenie muzyki */ @Override public void run() { playSound(musicFiles.get(currentSongIndex)); } /** * metoda odpoweidzialna za wyłączenie muzyki */ public void stopMusic() { clip.stop(); clip.close(); } }
Mikboch/LunarLanderGame
Client/src/PGame/MusicPlayer.java
179,582
/* * 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 AdapterPluggablePrzyklad; /** * * @author KrzysieK */ public class OdtwarzaczMP3 { public void Play(String nazwaPliku, String format){ if (format.equalsIgnoreCase("mp3")) System.out.println("Plik o nazwie " + nazwaPliku + "." + format + " jest odtwarzany"); else System.out.println("Odtwarzacz MP3 odtwarza tylko muzykę w formacie \".mp3\""); }; }
adrych/DesignPatterns
06Adapter/Students/2016/Szarafinski/PluggableAdapterPrzyklad/OdtwarzaczMP3.java
179,594
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.job.results; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.xcontent.ConstructingObjectParser; import org.elasticsearch.xcontent.ObjectParser.ValueType; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xpack.core.common.time.TimeUtils; import org.elasticsearch.xpack.core.ml.MachineLearningField; import org.elasticsearch.xpack.core.ml.job.config.Job; import java.io.IOException; import java.util.Date; import java.util.Objects; /** * Model Plot POJO. */ public class ModelPlot implements ToXContentObject, Writeable { /** * Result type */ public static final String RESULT_TYPE_VALUE = "model_plot"; public static final ParseField RESULTS_FIELD = new ParseField(RESULT_TYPE_VALUE); public static final ParseField PARTITION_FIELD_NAME = new ParseField("partition_field_name"); public static final ParseField PARTITION_FIELD_VALUE = new ParseField("partition_field_value"); public static final ParseField OVER_FIELD_NAME = new ParseField("over_field_name"); public static final ParseField OVER_FIELD_VALUE = new ParseField("over_field_value"); public static final ParseField BY_FIELD_NAME = new ParseField("by_field_name"); public static final ParseField BY_FIELD_VALUE = new ParseField("by_field_value"); public static final ParseField MODEL_FEATURE = new ParseField("model_feature"); public static final ParseField MODEL_LOWER = new ParseField("model_lower"); public static final ParseField MODEL_UPPER = new ParseField("model_upper"); public static final ParseField MODEL_MEDIAN = new ParseField("model_median"); public static final ParseField ACTUAL = new ParseField("actual"); public static final ParseField BUCKET_SPAN = new ParseField("bucket_span"); public static final ParseField DETECTOR_INDEX = new ParseField("detector_index"); public static final ConstructingObjectParser<ModelPlot, Void> STRICT_PARSER = createParser(false); public static final ConstructingObjectParser<ModelPlot, Void> LENIENT_PARSER = createParser(true); private static ConstructingObjectParser<ModelPlot, Void> createParser(boolean ignoreUnknownFields) { ConstructingObjectParser<ModelPlot, Void> parser = new ConstructingObjectParser<>( RESULT_TYPE_VALUE, ignoreUnknownFields, a -> new ModelPlot((String) a[0], (Date) a[1], (long) a[2], (int) a[3]) ); parser.declareString(ConstructingObjectParser.constructorArg(), Job.ID); parser.declareField( ConstructingObjectParser.constructorArg(), p -> TimeUtils.parseTimeField(p, Result.TIMESTAMP.getPreferredName()), Result.TIMESTAMP, ValueType.VALUE ); parser.declareLong(ConstructingObjectParser.constructorArg(), BUCKET_SPAN); parser.declareInt(ConstructingObjectParser.constructorArg(), DETECTOR_INDEX); parser.declareString((modelPlot, s) -> {}, Result.RESULT_TYPE); parser.declareString(ModelPlot::setPartitionFieldName, PARTITION_FIELD_NAME); parser.declareString(ModelPlot::setPartitionFieldValue, PARTITION_FIELD_VALUE); parser.declareString(ModelPlot::setOverFieldName, OVER_FIELD_NAME); parser.declareString(ModelPlot::setOverFieldValue, OVER_FIELD_VALUE); parser.declareString(ModelPlot::setByFieldName, BY_FIELD_NAME); parser.declareString(ModelPlot::setByFieldValue, BY_FIELD_VALUE); parser.declareString(ModelPlot::setModelFeature, MODEL_FEATURE); parser.declareDouble(ModelPlot::setModelLower, MODEL_LOWER); parser.declareDouble(ModelPlot::setModelUpper, MODEL_UPPER); parser.declareDouble(ModelPlot::setModelMedian, MODEL_MEDIAN); parser.declareDouble(ModelPlot::setActual, ACTUAL); return parser; } private final String jobId; private final Date timestamp; private final long bucketSpan; private int detectorIndex; private String partitionFieldName; private String partitionFieldValue; private String overFieldName; private String overFieldValue; private String byFieldName; private String byFieldValue; private String modelFeature; private double modelLower; private double modelUpper; private double modelMedian; /** * This can be <code>null</code> because buckets where no values were observed will still have a model, but no actual */ private Double actual; public ModelPlot(String jobId, Date timestamp, long bucketSpan, int detectorIndex) { this.jobId = jobId; this.timestamp = timestamp; this.bucketSpan = bucketSpan; this.detectorIndex = detectorIndex; } public ModelPlot(StreamInput in) throws IOException { jobId = in.readString(); timestamp = new Date(in.readLong()); partitionFieldName = in.readOptionalString(); partitionFieldValue = in.readOptionalString(); overFieldName = in.readOptionalString(); overFieldValue = in.readOptionalString(); byFieldName = in.readOptionalString(); byFieldValue = in.readOptionalString(); modelFeature = in.readOptionalString(); modelLower = in.readDouble(); modelUpper = in.readDouble(); modelMedian = in.readDouble(); actual = in.readOptionalDouble(); bucketSpan = in.readLong(); detectorIndex = in.readInt(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(jobId); out.writeLong(timestamp.getTime()); out.writeOptionalString(partitionFieldName); out.writeOptionalString(partitionFieldValue); out.writeOptionalString(overFieldName); out.writeOptionalString(overFieldValue); out.writeOptionalString(byFieldName); out.writeOptionalString(byFieldValue); out.writeOptionalString(modelFeature); out.writeDouble(modelLower); out.writeDouble(modelUpper); out.writeDouble(modelMedian); out.writeOptionalDouble(actual); out.writeLong(bucketSpan); out.writeInt(detectorIndex); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Job.ID.getPreferredName(), jobId); builder.field(Result.RESULT_TYPE.getPreferredName(), RESULT_TYPE_VALUE); builder.field(BUCKET_SPAN.getPreferredName(), bucketSpan); builder.field(DETECTOR_INDEX.getPreferredName(), detectorIndex); if (timestamp != null) { builder.timeField(Result.TIMESTAMP.getPreferredName(), Result.TIMESTAMP.getPreferredName() + "_string", timestamp.getTime()); } if (partitionFieldName != null) { builder.field(PARTITION_FIELD_NAME.getPreferredName(), partitionFieldName); } if (partitionFieldValue != null) { builder.field(PARTITION_FIELD_VALUE.getPreferredName(), partitionFieldValue); } if (overFieldName != null) { builder.field(OVER_FIELD_NAME.getPreferredName(), overFieldName); } if (overFieldValue != null) { builder.field(OVER_FIELD_VALUE.getPreferredName(), overFieldValue); } if (byFieldName != null) { builder.field(BY_FIELD_NAME.getPreferredName(), byFieldName); } if (byFieldValue != null) { builder.field(BY_FIELD_VALUE.getPreferredName(), byFieldValue); } if (modelFeature != null) { builder.field(MODEL_FEATURE.getPreferredName(), modelFeature); } builder.field(MODEL_LOWER.getPreferredName(), modelLower); builder.field(MODEL_UPPER.getPreferredName(), modelUpper); builder.field(MODEL_MEDIAN.getPreferredName(), modelMedian); if (actual != null) { builder.field(ACTUAL.getPreferredName(), actual); } builder.endObject(); return builder; } public String getJobId() { return jobId; } public String getId() { return jobId + "_model_plot_" + timestamp.getTime() + "_" + bucketSpan + "_" + detectorIndex + "_" + MachineLearningField.valuesToId(byFieldValue, overFieldValue, partitionFieldValue); } public Date getTimestamp() { return timestamp; } public long getBucketSpan() { return bucketSpan; } public int getDetectorIndex() { return detectorIndex; } public String getPartitionFieldName() { return partitionFieldName; } public void setPartitionFieldName(String partitionFieldName) { this.partitionFieldName = partitionFieldName; } public String getPartitionFieldValue() { return partitionFieldValue; } public void setPartitionFieldValue(String partitionFieldValue) { this.partitionFieldValue = partitionFieldValue; } public String getOverFieldName() { return overFieldName; } public void setOverFieldName(String overFieldName) { this.overFieldName = overFieldName; } public String getOverFieldValue() { return overFieldValue; } public void setOverFieldValue(String overFieldValue) { this.overFieldValue = overFieldValue; } public String getByFieldName() { return byFieldName; } public void setByFieldName(String byFieldName) { this.byFieldName = byFieldName; } public String getByFieldValue() { return byFieldValue; } public void setByFieldValue(String byFieldValue) { this.byFieldValue = byFieldValue; } public String getModelFeature() { return modelFeature; } public void setModelFeature(String modelFeature) { this.modelFeature = modelFeature; } public double getModelLower() { return modelLower; } public void setModelLower(double modelLower) { this.modelLower = modelLower; } public double getModelUpper() { return modelUpper; } public void setModelUpper(double modelUpper) { this.modelUpper = modelUpper; } public double getModelMedian() { return modelMedian; } public void setModelMedian(double modelMedian) { this.modelMedian = modelMedian; } public Double getActual() { return actual; } public void setActual(Double actual) { this.actual = actual; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof ModelPlot == false) { return false; } ModelPlot that = (ModelPlot) other; return Objects.equals(this.jobId, that.jobId) && Objects.equals(this.timestamp, that.timestamp) && Objects.equals(this.partitionFieldValue, that.partitionFieldValue) && Objects.equals(this.partitionFieldName, that.partitionFieldName) && Objects.equals(this.overFieldValue, that.overFieldValue) && Objects.equals(this.overFieldName, that.overFieldName) && Objects.equals(this.byFieldValue, that.byFieldValue) && Objects.equals(this.byFieldName, that.byFieldName) && Objects.equals(this.modelFeature, that.modelFeature) && this.modelLower == that.modelLower && this.modelUpper == that.modelUpper && this.modelMedian == that.modelMedian && Objects.equals(this.actual, that.actual) && this.bucketSpan == that.bucketSpan && this.detectorIndex == that.detectorIndex; } @Override public int hashCode() { return Objects.hash( jobId, timestamp, partitionFieldName, partitionFieldValue, overFieldName, overFieldValue, byFieldName, byFieldValue, modelFeature, modelLower, modelUpper, modelMedian, actual, bucketSpan, detectorIndex ); } }
elastic/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/results/ModelPlot.java
179,598
/* * Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.jdk8; import java.util.Objects; import java.util.concurrent.atomic.*; import java.util.function.*; import java.util.stream.Collector; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.exceptions.Exceptions; import io.reactivex.rxjava3.internal.subscriptions.*; import io.reactivex.rxjava3.internal.util.AtomicThrowable; import io.reactivex.rxjava3.parallel.ParallelFlowable; import io.reactivex.rxjava3.plugins.RxJavaPlugins; /** * Reduces all 'rails' into a single via a Java 8 {@link Collector} callback set. * * @param <T> the value type * @param <A> the accumulator type * @param <R> the result type * @since 3.0.0 */ public final class ParallelCollector<T, A, R> extends Flowable<R> { final ParallelFlowable<? extends T> source; final Collector<T, A, R> collector; public ParallelCollector(ParallelFlowable<? extends T> source, Collector<T, A, R> collector) { this.source = source; this.collector = collector; } @Override protected void subscribeActual(Subscriber<? super R> s) { ParallelCollectorSubscriber<T, A, R> parent; try { parent = new ParallelCollectorSubscriber<>(s, source.parallelism(), collector); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptySubscription.error(ex, s); return; } s.onSubscribe(parent); source.subscribe(parent.subscribers); } static final class ParallelCollectorSubscriber<T, A, R> extends DeferredScalarSubscription<R> { private static final long serialVersionUID = -5370107872170712765L; final ParallelCollectorInnerSubscriber<T, A, R>[] subscribers; final AtomicReference<SlotPair<A>> current = new AtomicReference<>(); final AtomicInteger remaining = new AtomicInteger(); final AtomicThrowable error = new AtomicThrowable(); final Function<A, R> finisher; ParallelCollectorSubscriber(Subscriber<? super R> subscriber, int n, Collector<T, A, R> collector) { super(subscriber); this.finisher = collector.finisher(); @SuppressWarnings("unchecked") ParallelCollectorInnerSubscriber<T, A, R>[] a = new ParallelCollectorInnerSubscriber[n]; for (int i = 0; i < n; i++) { a[i] = new ParallelCollectorInnerSubscriber<>(this, collector.supplier().get(), collector.accumulator(), collector.combiner()); } this.subscribers = a; remaining.lazySet(n); } SlotPair<A> addValue(A value) { for (;;) { SlotPair<A> curr = current.get(); if (curr == null) { curr = new SlotPair<>(); if (!current.compareAndSet(null, curr)) { continue; } } int c = curr.tryAcquireSlot(); if (c < 0) { current.compareAndSet(curr, null); continue; } if (c == 0) { curr.first = value; } else { curr.second = value; } if (curr.releaseSlot()) { current.compareAndSet(curr, null); return curr; } return null; } } @Override public void cancel() { for (ParallelCollectorInnerSubscriber<T, A, R> inner : subscribers) { inner.cancel(); } } void innerError(Throwable ex) { if (error.compareAndSet(null, ex)) { cancel(); downstream.onError(ex); } else { if (ex != error.get()) { RxJavaPlugins.onError(ex); } } } void innerComplete(A value, BinaryOperator<A> combiner) { for (;;) { SlotPair<A> sp = addValue(value); if (sp != null) { try { value = combiner.apply(sp.first, sp.second); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); innerError(ex); return; } } else { break; } } if (remaining.decrementAndGet() == 0) { SlotPair<A> sp = current.get(); current.lazySet(null); R result; try { result = Objects.requireNonNull(finisher.apply(sp.first), "The finisher returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); innerError(ex); return; } complete(result); } } } static final class ParallelCollectorInnerSubscriber<T, A, R> extends AtomicReference<Subscription> implements FlowableSubscriber<T> { private static final long serialVersionUID = -7954444275102466525L; final ParallelCollectorSubscriber<T, A, R> parent; final BiConsumer<A, T> accumulator; final BinaryOperator<A> combiner; A container; boolean done; ParallelCollectorInnerSubscriber(ParallelCollectorSubscriber<T, A, R> parent, A container, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner) { this.parent = parent; this.accumulator = accumulator; this.combiner = combiner; this.container = container; } @Override public void onSubscribe(Subscription s) { SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); } @Override public void onNext(T t) { if (!done) { try { accumulator.accept(container, t); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); get().cancel(); onError(ex); } } } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } container = null; done = true; parent.innerError(t); } @Override public void onComplete() { if (!done) { A v = container; container = null; done = true; parent.innerComplete(v, combiner); } } void cancel() { SubscriptionHelper.cancel(this); } } static final class SlotPair<T> extends AtomicInteger { private static final long serialVersionUID = 473971317683868662L; T first; T second; final AtomicInteger releaseIndex = new AtomicInteger(); int tryAcquireSlot() { for (;;) { int acquired = get(); if (acquired >= 2) { return -1; } if (compareAndSet(acquired, acquired + 1)) { return acquired; } } } boolean releaseSlot() { return releaseIndex.incrementAndGet() == 2; } } }
ReactiveX/RxJava
src/main/java/io/reactivex/rxjava3/internal/jdk8/ParallelCollector.java
179,601
package jadx.gui.device.debugger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.atomic.AtomicInteger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.skylot.jdwp.JDWP; import io.github.skylot.jdwp.JDWP.ArrayReference.Length.LengthReplyData; import io.github.skylot.jdwp.JDWP.ByteBuffer; import io.github.skylot.jdwp.JDWP.Event.Composite.BreakpointEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassPrepareEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ClassUnloadEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.EventData; import io.github.skylot.jdwp.JDWP.Event.Composite.ExceptionEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldAccessEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.FieldModificationEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodEntryEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MethodExitWithReturnValueEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnterEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorContendedEnteredEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.MonitorWaitedEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.SingleStepEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.ThreadStartEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMDeathEvent; import io.github.skylot.jdwp.JDWP.Event.Composite.VMStartEvent; import io.github.skylot.jdwp.JDWP.EventRequest.Set.ClassMatchRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.CountRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.LocationOnlyRequest; import io.github.skylot.jdwp.JDWP.EventRequest.Set.StepRequest; import io.github.skylot.jdwp.JDWP.Method.VariableTableWithGeneric.VarTableWithGenericData; import io.github.skylot.jdwp.JDWP.Method.VariableTableWithGeneric.VarWithGenericSlot; import io.github.skylot.jdwp.JDWP.ObjectReference; import io.github.skylot.jdwp.JDWP.ObjectReference.ReferenceType.ReferenceTypeReplyData; import io.github.skylot.jdwp.JDWP.ObjectReference.SetValues.FieldValueSetter; import io.github.skylot.jdwp.JDWP.Packet; import io.github.skylot.jdwp.JDWP.ReferenceType.FieldsWithGeneric.FieldsWithGenericData; import io.github.skylot.jdwp.JDWP.ReferenceType.FieldsWithGeneric.FieldsWithGenericReplyData; import io.github.skylot.jdwp.JDWP.ReferenceType.MethodsWithGeneric.MethodsWithGenericData; import io.github.skylot.jdwp.JDWP.ReferenceType.MethodsWithGeneric.MethodsWithGenericReplyData; import io.github.skylot.jdwp.JDWP.ReferenceType.Signature.SignatureReplyData; import io.github.skylot.jdwp.JDWP.StackFrame.GetValues.GetValuesReplyData; import io.github.skylot.jdwp.JDWP.StackFrame.GetValues.GetValuesSlots; import io.github.skylot.jdwp.JDWP.StackFrame.SetValues.SlotValueSetter; import io.github.skylot.jdwp.JDWP.StackFrame.ThisObject.ThisObjectReplyData; import io.github.skylot.jdwp.JDWP.StringReference.Value.ValueReplyData; import io.github.skylot.jdwp.JDWP.ThreadReference.Frames.FramesReplyData; import io.github.skylot.jdwp.JDWP.ThreadReference.Frames.FramesReplyDataFrames; import io.github.skylot.jdwp.JDWP.ThreadReference.Name.NameReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllClassesWithGeneric.AllClassesWithGenericData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllClassesWithGeneric.AllClassesWithGenericReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllThreads.AllThreadsReplyData; import io.github.skylot.jdwp.JDWP.VirtualMachine.AllThreads.AllThreadsReplyDataThreads; import io.github.skylot.jdwp.JDWP.VirtualMachine.CreateString.CreateStringReplyData; import jadx.api.plugins.input.data.AccessFlags; import jadx.gui.device.debugger.smali.RegisterInfo; import jadx.gui.utils.IOUtils; import jadx.gui.utils.ObjectPool; // TODO: Finish error notification, inner errors should be logged let user notice. public class SmaliDebugger { private static final Logger LOG = LoggerFactory.getLogger(SmaliDebugger.class); private final JDWP jdwp; private final int localTcpPort; private final InputStream inputStream; private final OutputStream outputStream; // All event callbacks will be called in this queue, e.g. class prepare/unload private static final Executor EVENT_LISTENER_QUEUE = Executors.newSingleThreadExecutor(); // Handle callbacks of single step, breakpoint and watchpoint private static final Executor SUSPEND_LISTENER_QUEUE = Executors.newSingleThreadExecutor(); private final Map<Integer, ICommandResult> callbackMap = new ConcurrentHashMap<>(); private final Map<Integer, EventListenerAdapter> eventListenerMap = new ConcurrentHashMap<>(); private final Map<String, AllClassesWithGenericData> classMap = new ConcurrentHashMap<>(); private final Map<Long, AllClassesWithGenericData> classIDMap = new ConcurrentHashMap<>(); private final Map<Long, List<MethodsWithGenericData>> clsMethodMap = new ConcurrentHashMap<>(); private final Map<Long, List<FieldsWithGenericData>> clsFieldMap = new ConcurrentHashMap<>(); private Map<Long, Map<Long, RuntimeDebugInfo>> varMap = Collections.emptyMap(); // cls id: <mth id: var table> private final CountRequest oneOffEventReq; private final AtomicInteger idGenerator = new AtomicInteger(1); private final SuspendInfo suspendInfo = new SuspendInfo(); private final SuspendListener suspendListener; private ObjectPool<List<GetValuesSlots>> slotsPool; private ObjectPool<List<JDWP.EventRequestEncoder>> stepReqPool; private ObjectPool<SynchronousQueue<Packet>> syncQueuePool; private ObjectPool<List<Long>> fieldIdPool; private final Map<Integer, Thread> syncQueueMap = new ConcurrentHashMap<>(); private final AtomicInteger syncQueueID = new AtomicInteger(0); private static final ICommandResult SKIP_RESULT = res -> { }; private SmaliDebugger(SuspendListener suspendListener, int localTcpPort, JDWP jdwp, InputStream inputStream, OutputStream outputStream) { this.jdwp = jdwp; this.localTcpPort = localTcpPort; this.suspendListener = suspendListener; this.inputStream = inputStream; this.outputStream = outputStream; oneOffEventReq = jdwp.eventRequest().cmdSet().newCountRequest(); oneOffEventReq.count = 1; } /** * After a successful attach the remote app will be suspended, so we have times to * set breakpoints or do any other things, after that call resume() to activate the app. */ public static SmaliDebugger attach(String host, int port, SuspendListener suspendListener) throws SmaliDebuggerException { try { byte[] bytes = JDWP.IDSizes.encode().getBytes(); JDWP.setPacketID(bytes, 1); LOG.debug("Connecting to ADB {}:{}", host, port); Socket socket = new Socket(host, port); InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); socket.setSoTimeout(5000); JDWP jdwp = initJDWP(outputStream, inputStream); socket.setSoTimeout(0); // set back to 0 so the decodingLoop won't break for timeout. SmaliDebugger debugger = new SmaliDebugger(suspendListener, port, jdwp, inputStream, outputStream); debugger.decodingLoop(); debugger.listenClassUnloadEvent(); debugger.initPools(); return debugger; } catch (IOException e) { throw new SmaliDebuggerException("Attach failed", e); } } private void onSuspended(long thread, long clazz, long mth, long offset) { suspendInfo.update() .updateThread(thread) .updateClass(clazz) .updateMethod(mth) .updateOffset(offset); if (suspendInfo.isAnythingChanged()) { SUSPEND_LISTENER_QUEUE.execute(() -> suspendListener.onSuspendEvent(suspendInfo)); } } public void stepInto() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.INTO); } public void stepOver() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.OVER); } public void stepOut() throws SmaliDebuggerException { sendStepRequest(suspendInfo.getThreadID(), JDWP.StepDepth.OUT); } public void exit() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdExit().encode(-1)); tryThrowError(res); } public void detach() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdDispose().encode()); tryThrowError(res); } private void initPools() { slotsPool = new ObjectPool<>(() -> { List<GetValuesSlots> slots = new ArrayList<>(1); GetValuesSlots slot = jdwp.stackFrame().cmdGetValues().newValuesSlots(); slot.slot = 0; slot.sigbyte = JDWP.Tag.OBJECT; slots.add(slot); return slots; }); stepReqPool = new ObjectPool<>(() -> { List<JDWP.EventRequestEncoder> eventEncoders = new ArrayList<>(2); eventEncoders.add(jdwp.eventRequest().cmdSet().newStepRequest()); eventEncoders.add(oneOffEventReq); return eventEncoders; }); syncQueuePool = new ObjectPool<>(SynchronousQueue::new); fieldIdPool = new ObjectPool<>(() -> { List<Long> ids = new ArrayList<>(1); ids.add((long) -1); return ids; }); } /** * @param regNum If it's an argument, just pass its index, non-static method should be index + 1. * e.g. void a(int b, int c), you want the value of b, then should pass 1 (0 + 1), * this is a virtual method, so 0 is for the this object and 1 is the real index of b. * <p> * If it's a variable then should be the reg number + number of arguments and + 1 * if it's in a non-static method. * e.g. to get the value of v3 in a virtual method with 2 arguments, should pass * 6 (3 + 2 + 1 = 6). */ public RuntimeRegister getRegisterSync(long threadID, long frameID, int regNum, RuntimeType type) throws SmaliDebuggerException { List<GetValuesSlots> slots = slotsPool.get(); GetValuesSlots slot = slots.get(0); slot.slot = regNum; slot.sigbyte = (byte) type.getTag(); Packet res = sendCommandSync(jdwp.stackFrame().cmdGetValues().encode(threadID, frameID, slots)); tryThrowError(res); slotsPool.put(slots); GetValuesReplyData val = jdwp.stackFrame().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return buildRegister(regNum, val.values.get(0).slotValue.tag, val.values.get(0).slotValue.idOrValue); } public long getThisID(long threadID, long frameID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.stackFrame().cmdThisObject().encode(threadID, frameID)); tryThrowError(res); ThisObjectReplyData data = jdwp.stackFrame().cmdThisObject().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return data.objectThis.objectID; } public List<RuntimeField> getAllFieldsSync(long clsID) throws SmaliDebuggerException { return getAllFields(clsID); } public void getFieldValueSync(long clsID, RuntimeField fld) throws SmaliDebuggerException { List<RuntimeField> list = new ArrayList<>(1); list.add(fld); getAllFieldValuesSync(clsID, list); } public void getAllFieldValuesSync(long thisID, List<RuntimeField> flds) throws SmaliDebuggerException { List<Long> ids = new ArrayList<>(flds.size()); flds.forEach(f -> ids.add(f.getFieldID())); Packet res = sendCommandSync(jdwp.objectReference().cmdGetValues().encode(thisID, ids)); tryThrowError(res); ObjectReference.GetValues.GetValuesReplyData data = jdwp.objectReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); List<ObjectReference.GetValues.GetValuesReplyDataValues> values = data.values; for (int i = 0; i < values.size(); i++) { ObjectReference.GetValues.GetValuesReplyDataValues value = values.get(i); flds.get(i).setValue(value.value.idOrValue) .setType(RuntimeType.fromJdwpTag(value.value.tag)); } } public Frame getCurrentFrame(long threadID) throws SmaliDebuggerException { return getCurrentFrameInternal(threadID); } public List<Frame> getFramesSync(long threadID) throws SmaliDebuggerException { return getAllFrames(threadID); } public List<Long> getAllThreadsSync() throws SmaliDebuggerException { return getAllThreads(); } @Nullable public String getThreadNameSync(long threadID) throws SmaliDebuggerException { return sendThreadNameReq(threadID); } @Nullable public String getClassSignatureSync(long classID) throws SmaliDebuggerException { return getClassSignatureInternal(classID); } @Nullable public String getMethodSignatureSync(long classID, long methodID) throws SmaliDebuggerException { return getMethodSignatureInternal(classID, methodID); } public boolean errIsTypeMismatched(int errCode) { return errCode == JDWP.Error.TYPE_MISMATCH; } public boolean errIsInvalidSlot(int errCode) { return errCode == JDWP.Error.INVALID_SLOT; } public boolean errIsInvalidObject(int errCode) { return errCode == JDWP.Error.INVALID_OBJECT; } private static class ClassListenerInfo { int prepareReqID; int unloadReqID; ClassListener listener; void reset(ClassListener l) { this.listener = l; this.prepareReqID = -1; this.unloadReqID = -1; } } private ClassListenerInfo clsListener; /** * Listens for class preparation and unload events. */ public void setClassListener(ClassListener listener) throws SmaliDebuggerException { if (clsListener != null) { if (listener != clsListener.listener) { unregisterEventSync(JDWP.EventKind.CLASS_PREPARE, clsListener.prepareReqID); unregisterEventSync(JDWP.EventKind.CLASS_UNLOAD, clsListener.unloadReqID); } } else { clsListener = new ClassListenerInfo(); } clsListener.reset(listener); regClassPrepareEvent(clsListener); regClassUnloadEvent(clsListener); } private void regClassUnloadEvent(ClassListenerInfo info) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassExcludeRequest((byte) JDWP.EventKind.CLASS_UNLOAD, (byte) JDWP.SuspendPolicy.NONE, "java.*")); tryThrowError(res); info.unloadReqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(info.unloadReqID, new EventListenerAdapter() { @Override void onClassUnload(ClassUnloadEvent event) { info.listener.onUnloaded(DbgUtils.classSigToRawFullName(event.signature)); } }); } private void regClassPrepareEvent(ClassListenerInfo info) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassExcludeRequest((byte) JDWP.EventKind.CLASS_PREPARE, (byte) JDWP.SuspendPolicy.NONE, "java.*")); tryThrowError(res); info.prepareReqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(info.prepareReqID, new EventListenerAdapter() { @Override void onClassPrepare(ClassPrepareEvent event) { info.listener.onPrepared(DbgUtils.classSigToRawFullName(event.signature), event.typeID); } }); } public void regClassPrepareEventForBreakpoint(String clsSig, ClassPrepareListener l) throws SmaliDebuggerException { Packet res = sendCommandSync(buildClassMatchReqForBreakpoint(clsSig, JDWP.EventKind.CLASS_PREPARE)); tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, new EventListenerAdapter() { @Override void onClassPrepare(ClassPrepareEvent event) { EVENT_LISTENER_QUEUE.execute(() -> { try { l.onPrepared(event.typeID); } finally { eventListenerMap.remove(reqID); try { resume(); } catch (SmaliDebuggerException e) { LOG.error("Resume failed", e); } } }); } }); } public interface MethodEntryListener { /** * return true to remove */ boolean entry(String mthSig); } public void regMethodEntryEventSync(String clsSig, MethodEntryListener l) throws SmaliDebuggerException { Packet res = sendCommandSync( jdwp.eventRequest().cmdSet().newClassMatchRequest((byte) JDWP.EventKind.METHOD_ENTRY, (byte) JDWP.SuspendPolicy.ALL, clsSig)); tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, new EventListenerAdapter() { @Override void onMethodEntry(MethodEntryEvent event) { EVENT_LISTENER_QUEUE.execute(() -> { boolean removeListener = false; try { String sig = getMethodSignatureInternal(event.location.classID, event.location.methodID); removeListener = l.entry(sig); if (removeListener) { sendCommand(jdwp.eventRequest().cmdClear().encode((byte) JDWP.EventKind.METHOD_ENTRY, reqID), SKIP_RESULT); onSuspended(event.thread, event.location.classID, event.location.methodID, -1); eventListenerMap.remove(reqID); } } catch (SmaliDebuggerException e) { LOG.error("Method entry failed", e); } finally { if (!removeListener) { try { resume(); } catch (SmaliDebuggerException e) { LOG.error("Resume failed", e); } } } }); } }); } private void unregisterEventSync(int eventKind, int reqID) throws SmaliDebuggerException { eventListenerMap.remove(reqID); Packet rst = sendCommandSync(jdwp.eventRequest().cmdClear().encode((byte) eventKind, reqID)); tryThrowError(rst); } public String readObjectSignatureSync(RuntimeValue val) throws SmaliDebuggerException { long objID = readID(val); // get type reference by object id. Packet res = sendCommandSync(jdwp.objectReference().cmdReferenceType().encode(objID)); tryThrowError(res); ReferenceTypeReplyData data = jdwp.objectReference().cmdReferenceType().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); // get signature by type reference id. res = sendCommandSync(jdwp.referenceType().cmdSignature().encode(data.typeID)); tryThrowError(res); SignatureReplyData sigData = jdwp.referenceType().cmdSignature().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return sigData.signature; } public String readStringSync(RuntimeValue val) throws SmaliDebuggerException { return readStringSync(readID(val)); } public String readStringSync(long id) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.stringReference().cmdValue().encode(id)); tryThrowError(res); ValueReplyData strData = jdwp.stringReference().cmdValue().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return strData.stringValue; } public boolean setValueSync(int runtimeRegNum, RuntimeType type, Object val, long threadID, long frameID) throws SmaliDebuggerException { if (type == RuntimeType.STRING) { long newID = createString((String) val); if (newID == -1) { return false; } val = newID; type = RuntimeType.OBJECT; } List<SlotValueSetter> setters = buildRegValueSetter(type.getTag(), runtimeRegNum); JDWP.encodeAny(setters.get(0).slotValue.idOrValue, val); Packet res = sendCommandSync(jdwp.stackFrame().cmdSetValues().encode(threadID, frameID, setters)); tryThrowError(res); return jdwp.stackFrame().cmdSetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); } public boolean setValueSync(long objID, long fldID, RuntimeType type, Object val) throws SmaliDebuggerException { if (type == RuntimeType.STRING) { long newID = createString((String) val); if (newID == -1) { return false; } val = newID; } List<FieldValueSetter> setters = buildFieldValueSetter(); FieldValueSetter setter = setters.get(0); setter.fieldID = fldID; JDWP.encodeAny(setter.value.idOrValue, val); Packet res = sendCommandSync(jdwp.objectReference().cmdSetValues().encode(objID, setters)); tryThrowError(res); return jdwp.objectReference().cmdSetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); } public void getValueSync(long objID, RuntimeField fld) throws SmaliDebuggerException { List<Long> ids = fieldIdPool.get(); ids.set(0, fld.getFieldID()); Packet res = sendCommandSync(jdwp.objectReference().cmdGetValues().encode(objID, ids)); tryThrowError(res); ObjectReference.GetValues.GetValuesReplyData data = jdwp.objectReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); fld.setValue(data.values.get(0).value.idOrValue) .setType(RuntimeType.fromJdwpTag(data.values.get(0).value.tag)); } private long createString(String localStr) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdCreateString().encode(localStr)); tryThrowError(res); CreateStringReplyData id = jdwp.virtualMachine().cmdCreateString().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return id.stringObject; } public long readID(RuntimeValue val) { return JDWP.decodeBySize(val.getRawVal().getBytes(), 0, val.getRawVal().size()); } public String readArraySignature(RuntimeValue val) throws SmaliDebuggerException { return readObjectSignatureSync(val); } public int readArrayLength(RuntimeValue val) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.arrayReference().cmdLength().encode(readID(val))); tryThrowError(res); LengthReplyData data = jdwp.arrayReference().cmdLength().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return data.arrayLength; } /** * @param startIndex less than 0 means 0 * @param len less than or equals 0 means the maximum value 99 or the rest of the elements. * @return An entry, The key is the total length of this array when len is <= 0, otherwise 0, * the value, if this array is an object array then it's object ids. */ public Entry<Integer, List<Long>> readArray(RuntimeValue reg, int startIndex, int len) throws SmaliDebuggerException { long id = readID(reg); Entry<Integer, List<Long>> ret; if (len <= 0) { Packet res = sendCommandSync(jdwp.arrayReference().cmdLength().encode(id)); tryThrowError(res); LengthReplyData data = jdwp.arrayReference().cmdLength().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); len = Math.min(99, data.arrayLength); ret = new SimpleEntry<>(data.arrayLength, null); } else { ret = new SimpleEntry<>(0, null); } startIndex = Math.max(0, startIndex); Packet res = sendCommandSync(jdwp.arrayReference().cmdGetValues().encode(id, startIndex, len)); tryThrowError(res); JDWP.ArrayReference.GetValues.GetValuesReplyData valData = jdwp.arrayReference().cmdGetValues().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); ret.setValue(valData.values.idOrValues); return ret; } public byte readByte(RuntimeValue val) { return JDWP.decodeByte(val.getRawVal().getBytes(), 0); } public char readChar(RuntimeValue val) { return JDWP.decodeChar(val.getRawVal().getBytes(), 0); } public short readShort(RuntimeValue val) { return JDWP.decodeShort(val.getRawVal().getBytes(), 0); } public int readInt(RuntimeValue val) { return JDWP.decodeInt(val.getRawVal().getBytes(), 0); } public float readFloat(RuntimeValue val) { return JDWP.decodeFloat(val.getRawVal().getBytes(), 0); } /** * @param val has 8 bytes mostly */ public long readAll(RuntimeValue val) { return JDWP.decodeBySize(val.getRawVal().getBytes(), 0, Math.min(val.getRawVal().size(), 8)); } public double readDouble(RuntimeValue val) { return JDWP.decodeDouble(val.getRawVal().getBytes(), 0); } @Nullable public RuntimeDebugInfo getRuntimeDebugInfo(long clsID, long mthID) throws SmaliDebuggerException { Map<Long, RuntimeDebugInfo> secMap = varMap.get(clsID); RuntimeDebugInfo info = null; if (secMap != null) { info = secMap.get(mthID); } if (info == null) { info = initDebugInfo(clsID, mthID); } return info; } private RuntimeDebugInfo initDebugInfo(long clsID, long mthID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.method().cmdVariableTableWithGeneric.encode(clsID, mthID)); tryThrowError(res); VarTableWithGenericData data = jdwp.method().cmdVariableTableWithGeneric.decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); if (varMap == Collections.EMPTY_MAP) { varMap = new ConcurrentHashMap<>(); } RuntimeDebugInfo info = new RuntimeDebugInfo(data); varMap.computeIfAbsent(clsID, k -> new HashMap<>()).put(mthID, info); return info; } private static JDWP initJDWP(OutputStream outputStream, InputStream inputStream) throws SmaliDebuggerException { try { handShake(outputStream, inputStream); outputStream.write(JDWP.Suspend.encode().setPacketID(1).getBytes()); // suspend all threads Packet res = readPacket(inputStream); tryThrowError(res); if (res.isReplyPacket() && res.getID() == 1) { // get id sizes for decoding & encoding of jdwp packets. outputStream.write(JDWP.IDSizes.encode().setPacketID(1).getBytes()); res = readPacket(inputStream); tryThrowError(res); if (res.isReplyPacket() && res.getID() == 1) { JDWP.IDSizes.IDSizesReplyData sizes = JDWP.IDSizes.decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return new JDWP(sizes); } } } catch (IOException e) { throw new SmaliDebuggerException(e); } throw new SmaliDebuggerException("Failed to init JDWP."); } private static void handShake(OutputStream outputStream, InputStream inputStream) throws SmaliDebuggerException { byte[] buf; try { outputStream.write(JDWP.encodeHandShakePacket()); buf = IOUtils.readNBytes(inputStream, 14); } catch (Exception e) { throw new SmaliDebuggerException("jdwp handshake failed", e); } if (buf == null || !JDWP.decodeHandShakePacket(buf)) { throw new SmaliDebuggerException("jdwp handshake bad reply"); } } private MethodsWithGenericData getMethodBySig(long classID, String sig) { List<MethodsWithGenericData> methods = clsMethodMap.get(classID); if (methods != null) { for (MethodsWithGenericData method : methods) { if (sig.startsWith(method.name + "(") && sig.endsWith(method.signature)) { return method; } } } return null; } private int genID() { return idGenerator.getAndAdd(1); } /** * Read & decode packets from Socket connection */ private void decodingLoop() { Executors.newSingleThreadExecutor().execute(() -> { boolean errFromCallback; while (true) { errFromCallback = false; try { Packet res = readPacket(inputStream); if (res == null) { break; } suspendInfo.nextRound(); ICommandResult callback = callbackMap.remove(res.getID()); if (callback != null) { if (callback != SKIP_RESULT) { errFromCallback = true; callback.onCommandReply(res); } continue; } if (res.getCommandSetID() == 64 && res.getCommandID() == 100) { // command from JVM errFromCallback = true; decodeCompositeEvents(res); } else { printUnexpectedID(res.getID()); } } catch (SmaliDebuggerException e) { LOG.error("Error in debugger decoding loop", e); if (!errFromCallback) { // fatal error break; } } } suspendInfo.setTerminated(); clearWaitingSyncQueue(); suspendListener.onSuspendEvent(suspendInfo); }); } private void sendCommand(ByteBuffer buf, ICommandResult callback) throws SmaliDebuggerException { int id = genID(); callbackMap.put(id, callback); try { outputStream.write(buf.setPacketID(id).getBytes()); } catch (IOException e) { throw new SmaliDebuggerException(e); } } /** * Do not use this method inside a ICommandResult callback, it will cause deadlock. * It should be used in a thread. */ private Packet sendCommandSync(ByteBuffer buf) throws SmaliDebuggerException { SynchronousQueue<Packet> store = syncQueuePool.get(); sendCommand(buf, res -> { try { store.put(res); } catch (Exception e) { LOG.error("Command send failed", e); } }); Integer id = syncQueueID.getAndAdd(1); try { syncQueueMap.put(id, Thread.currentThread()); return store.take(); } catch (InterruptedException e) { throw new SmaliDebuggerException(e); } finally { syncQueueMap.remove(id); syncQueuePool.put(store); } } // called by decodingLoop() when fatal error occurred, // if don't do so the store.take() may block forever. private void clearWaitingSyncQueue() { syncQueueMap.keySet().forEach(k -> { Thread t = syncQueueMap.remove(k); if (t != null) { t.interrupt(); } }); } private void printUnexpectedID(int id) throws SmaliDebuggerException { throw new SmaliDebuggerException("Missing handler for this id: " + id); } private void decodeCompositeEvents(Packet res) throws SmaliDebuggerException { EventData data = jdwp.event().cmdComposite().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); for (JDWP.EventRequestDecoder event : data.events) { EventListenerAdapter listener = eventListenerMap.get(event.getRequestID()); if (listener == null) { LOG.error("Missing handler for id: {}", event.getRequestID()); continue; } if (event instanceof VMStartEvent) { listener.onVMStart((VMStartEvent) event); return; } if (event instanceof VMDeathEvent) { listener.onVMDeath((VMDeathEvent) event); return; } if (event instanceof SingleStepEvent) { listener.onSingleStep((SingleStepEvent) event); return; } if (event instanceof BreakpointEvent) { listener.onBreakpoint((BreakpointEvent) event); return; } if (event instanceof MethodEntryEvent) { listener.onMethodEntry((MethodEntryEvent) event); return; } if (event instanceof MethodExitEvent) { listener.onMethodExit((MethodExitEvent) event); return; } if (event instanceof MethodExitWithReturnValueEvent) { listener.onMethodExitWithReturnValue((MethodExitWithReturnValueEvent) event); return; } if (event instanceof MonitorContendedEnterEvent) { listener.onMonitorContendedEnter((MonitorContendedEnterEvent) event); return; } if (event instanceof MonitorContendedEnteredEvent) { listener.onMonitorContendedEntered((MonitorContendedEnteredEvent) event); return; } if (event instanceof MonitorWaitEvent) { listener.onMonitorWait((MonitorWaitEvent) event); return; } if (event instanceof MonitorWaitedEvent) { listener.onMonitorWaited((MonitorWaitedEvent) event); return; } if (event instanceof ExceptionEvent) { listener.onException((ExceptionEvent) event); return; } if (event instanceof ThreadStartEvent) { listener.onThreadStart((ThreadStartEvent) event); return; } if (event instanceof ThreadDeathEvent) { listener.onThreadDeath((ThreadDeathEvent) event); return; } if (event instanceof ClassPrepareEvent) { listener.onClassPrepare((ClassPrepareEvent) event); return; } if (event instanceof ClassUnloadEvent) { listener.onClassUnload((ClassUnloadEvent) event); return; } if (event instanceof FieldAccessEvent) { listener.onFieldAccess((FieldAccessEvent) event); return; } if (event instanceof FieldModificationEvent) { listener.onFieldModification((FieldModificationEvent) event); return; } throw new SmaliDebuggerException("Unexpected event: " + event); } } private final EventListenerAdapter stepListener = new EventListenerAdapter() { @Override void onSingleStep(SingleStepEvent event) { onSuspended(event.thread, event.location.classID, event.location.methodID, event.location.index); } }; private void sendStepRequest(long threadID, int depth) throws SmaliDebuggerException { List<JDWP.EventRequestEncoder> stepReq = buildStepRequest(threadID, JDWP.StepSize.MIN, depth); ByteBuffer stepEncodedBuf = jdwp.eventRequest().cmdSet().encode( (byte) JDWP.EventKind.SINGLE_STEP, (byte) JDWP.SuspendPolicy.ALL, stepReq); stepReqPool.put(stepReq); sendCommand(stepEncodedBuf, res -> { tryThrowError(res); int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, stepListener); }); resume(); } public void resume() throws SmaliDebuggerException { sendCommand(JDWP.Resume.encode(), SKIP_RESULT); } public void suspend() throws SmaliDebuggerException { sendCommand(JDWP.Suspend.encode(), SKIP_RESULT); } public void setBreakpoint(RuntimeBreakpoint bp) throws SmaliDebuggerException { sendCommand(buildBreakpointRequest(bp), res -> { tryThrowError(res); bp.reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(bp.reqID, new EventListenerAdapter() { @Override void onBreakpoint(BreakpointEvent event) { onSuspended(event.thread, event.location.classID, event.location.methodID, event.location.index); } }); }); } public long getClassID(String clsSig, boolean fetch) throws SmaliDebuggerException { do { AllClassesWithGenericData data = classMap.get(clsSig); if (data == null) { if (fetch) { getAllClasses(); fetch = false; continue; } break; } else { return data.typeID; } } while (true); return -1; } public long getMethodID(long cid, String mthSig) throws SmaliDebuggerException { initClassCache(cid); MethodsWithGenericData data = getMethodBySig(cid, mthSig); if (data != null) { return data.methodID; } return -1; } public void initClassCache(long clsID) throws SmaliDebuggerException { initFields(clsID); initMethods(clsID); } public void removeBreakpoint(RuntimeBreakpoint bp) throws SmaliDebuggerException { sendCommand(jdwp.eventRequest().cmdClear().encode((byte) JDWP.EventKind.BREAKPOINT, bp.reqID), SKIP_RESULT); } private ByteBuffer buildBreakpointRequest(RuntimeBreakpoint bp) { LocationOnlyRequest req = jdwp.eventRequest().cmdSet().newLocationOnlyRequest(); req.loc.classID = bp.clsID; req.loc.methodID = bp.mthID; req.loc.index = bp.offset; req.loc.tag = JDWP.TypeTag.CLASS; List<JDWP.EventRequestEncoder> list = new ArrayList<>(1); list.add(req); return jdwp.eventRequest().cmdSet().encode((byte) JDWP.EventKind.BREAKPOINT, (byte) JDWP.SuspendPolicy.ALL, list); } /** * Builds a one-off class prepare event for setting up breakpoints. */ private ByteBuffer buildClassMatchReqForBreakpoint(String cls, int eventKind) { List<JDWP.EventRequestEncoder> encoders = new ArrayList<>(2); ClassMatchRequest match = jdwp.eventRequest().cmdSet().newClassMatchRequest(); encoders.add(match); encoders.add(oneOffEventReq); match.classPattern = cls; return jdwp.eventRequest().cmdSet().encode((byte) eventKind, (byte) JDWP.SuspendPolicy.ALL, encoders); } private List<JDWP.EventRequestEncoder> buildStepRequest(long threadID, int stepSize, int stepDepth) { List<JDWP.EventRequestEncoder> eventEncoders = stepReqPool.get(); StepRequest req = (StepRequest) eventEncoders.get(0); req.size = stepSize; req.depth = stepDepth; req.thread = threadID; return eventEncoders; } private List<FieldValueSetter> buildFieldValueSetter() { FieldValueSetter setter = jdwp.objectReference().cmdSetValues().new FieldValueSetter(); setter.value = jdwp.new UntaggedValuePacket(); setter.value.idOrValue = new ByteBuffer(); List<FieldValueSetter> setters = new ArrayList<>(1); setters.add(setter); return setters; } private List<SlotValueSetter> buildRegValueSetter(int tag, int regNum) { List<SlotValueSetter> setters = new ArrayList<>(1); SlotValueSetter setter = jdwp.stackFrame().cmdSetValues().new SlotValueSetter(); setters.add(setter); setter.slot = regNum; setter.slotValue = jdwp.new ValuePacket(); setter.slotValue.tag = tag; setter.slotValue.idOrValue = new ByteBuffer(); return setters; } private String getClassSignatureInternal(long id) throws SmaliDebuggerException { AllClassesWithGenericData data = classIDMap.get(id); if (data == null) { getAllClasses(); } data = classIDMap.get(id); if (data != null) { return data.signature; } return null; } private String getMethodSignatureInternal(long clsID, long mthID) throws SmaliDebuggerException { List<MethodsWithGenericData> mthData = clsMethodMap.get(clsID); if (mthData == null) { Packet res = sendCommandSync(jdwp.referenceType().cmdMethodsWithGeneric().encode(clsID)); tryThrowError(res); MethodsWithGenericReplyData data = jdwp.referenceType().cmdMethodsWithGeneric().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); mthData = data.declared; clsMethodMap.put(clsID, mthData); } if (mthData != null) { for (MethodsWithGenericData data : mthData) { if (data.methodID == mthID) { return data.name + data.signature; } } } return null; } private String sendThreadNameReq(long id) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.threadReference().cmdName().encode(id)); tryThrowError(res); NameReplyData nameData = jdwp.threadReference().cmdName().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); return nameData.threadName; } private List<RuntimeField> getAllFields(long clsID) throws SmaliDebuggerException { initFields(clsID); List<FieldsWithGenericData> flds = clsFieldMap.get(clsID); if (flds != null && flds.size() > 0) { List<RuntimeField> rfs = new ArrayList<>(flds.size()); for (FieldsWithGenericData fld : flds) { String type = fld.signature; if (fld.genericSignature != null && !fld.genericSignature.trim().isEmpty()) { type += "<" + fld.genericSignature + ">"; } rfs.add(new RuntimeField(fld.name, type, fld.fieldID, fld.modBits)); } return rfs; } return Collections.emptyList(); } public Frame getCurrentFrameInternal(long threadID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.threadReference().cmdFrames().encode(threadID, 0, 1)); tryThrowError(res); FramesReplyData frameData = jdwp.threadReference().cmdFrames().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); FramesReplyDataFrames frame = frameData.frames.get(0); return new Frame(frame.frameID, frame.location.classID, frame.location.methodID, frame.location.index); } private List<Frame> getAllFrames(long threadID) throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.threadReference().cmdFrames().encode(threadID, 0, -1)); tryThrowError(res); FramesReplyData frameData = jdwp.threadReference().cmdFrames().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); List<Frame> frames = new ArrayList<>(); for (FramesReplyDataFrames frame : frameData.frames) { frames.add(new Frame(frame.frameID, frame.location.classID, frame.location.methodID, frame.location.index)); } return frames; } private List<Long> getAllThreads() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdAllThreads().encode()); tryThrowError(res); AllThreadsReplyData data; data = jdwp.virtualMachine().cmdAllThreads().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); List<Long> threads = new ArrayList<>(data.threads.size()); for (AllThreadsReplyDataThreads thread : data.threads) { threads.add(thread.thread); } return threads; } private void getAllClasses() throws SmaliDebuggerException { Packet res = sendCommandSync(jdwp.virtualMachine().cmdAllClassesWithGeneric().encode()); tryThrowError(res); AllClassesWithGenericReplyData classData = jdwp.virtualMachine().cmdAllClassesWithGeneric().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); for (AllClassesWithGenericData aClass : classData.classes) { classMap.put(DbgUtils.classSigToRawFullName(aClass.signature), aClass); classIDMap.put(aClass.typeID, aClass); } } private void initFields(long clsID) throws SmaliDebuggerException { if (clsFieldMap.get(clsID) == null) { Packet res = sendCommandSync(jdwp.referenceType().cmdFieldsWithGeneric().encode(clsID)); tryThrowError(res); FieldsWithGenericReplyData data = jdwp.referenceType().cmdFieldsWithGeneric().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); clsFieldMap.put(clsID, data.declared); } } private void initMethods(long clsID) throws SmaliDebuggerException { if (clsMethodMap.get(clsID) == null) { Packet res = sendCommandSync(jdwp.referenceType().cmdMethodsWithGeneric().encode(clsID)); tryThrowError(res); MethodsWithGenericReplyData data = jdwp.referenceType().cmdMethodsWithGeneric().decode(res.getBuf(), JDWP.PACKET_HEADER_SIZE); clsMethodMap.put(clsID, data.declared); } } /** * Removes class cache when it's unloaded from JVM. */ private void listenClassUnloadEvent() throws SmaliDebuggerException { sendCommand( jdwp.eventRequest().cmdSet().encode((byte) JDWP.EventKind.CLASS_UNLOAD, (byte) JDWP.SuspendPolicy.NONE, Collections.emptyList()), res -> { int reqID = jdwp.eventRequest().cmdSet().decodeRequestID(res.getBuf(), JDWP.PACKET_HEADER_SIZE); eventListenerMap.put(reqID, new EventListenerAdapter() { @Override void onClassUnload(ClassUnloadEvent event) { EVENT_LISTENER_QUEUE.execute(() -> { System.out.printf("ClassUnloaded: %s%n", event.signature); AllClassesWithGenericData clsData = classMap.remove(event.signature); if (clsData != null) { classIDMap.remove(clsData.typeID); clsFieldMap.remove(clsData.typeID); clsMethodMap.remove(clsData.typeID); varMap.remove(clsData.typeID); } }); } }); }); } /** * Reads a JDWP packet. */ @Nullable private static Packet readPacket(InputStream inputStream) throws SmaliDebuggerException { try { byte[] header = IOUtils.readNBytes(inputStream, JDWP.PACKET_HEADER_SIZE); if (header == null) { // stream ended return null; } int bodyLength = JDWP.getPacketLength(header, 0) - JDWP.PACKET_HEADER_SIZE; if (bodyLength <= 0) { return Packet.make(header); } byte[] body = IOUtils.readNBytes(inputStream, bodyLength); if (body == null) { throw new SmaliDebuggerException("Stream truncated"); } return Packet.make(concatBytes(header, body)); } catch (IOException e) { throw new SmaliDebuggerException("Read packer error", e); } } private static byte[] concatBytes(byte[] buf1, byte[] buf2) { byte[] tempBuf = new byte[buf1.length + buf2.length]; System.arraycopy(buf1, 0, tempBuf, 0, buf1.length); System.arraycopy(buf2, 0, tempBuf, buf1.length, buf2.length); return tempBuf; } private static void tryThrowError(@Nullable Packet res) throws SmaliDebuggerException { if (res == null) { throw new SmaliDebuggerException("Stream ended"); } if (res.isError()) { throw new SmaliDebuggerException("(JDWP Error Code:" + res.getErrorCode() + ") " + res.getErrorText(), res.getErrorCode()); } } private interface ICommandResult { void onCommandReply(Packet res) throws SmaliDebuggerException; } public static class RuntimeField extends RuntimeValue { private final String name; private final String fldType; private final long fieldID; private final int modBits; private RuntimeField(String name, String type, long fieldID, int modBits) { super(null, null); this.name = name; this.fldType = type; this.fieldID = fieldID; this.modBits = modBits; } public String getFieldType() { return fldType; } public String getName() { return name; } public long getFieldID() { return fieldID; } private RuntimeField setValue(ByteBuffer rawVal) { super.rawVal = rawVal; return this; } public boolean isBelongToThis() { return !AccessFlags.hasFlag(modBits, AccessFlags.STATIC) && !AccessFlags.hasFlag(modBits, AccessFlags.SYNTHETIC); } } public static class RuntimeBreakpoint { private long clsID; private long mthID; private long offset; private int reqID; public long getCodeOffset() { return offset; } } public RuntimeBreakpoint makeBreakpoint(long cid, long mid, long offset) { RuntimeBreakpoint bp = new RuntimeBreakpoint(); bp.clsID = cid; bp.mthID = mid; bp.offset = offset; return bp; } private RuntimeRegister buildRegister(int num, int tag, ByteBuffer buf) throws SmaliDebuggerException { return new RuntimeRegister(num, RuntimeType.fromJdwpTag(tag), buf); } public static class RuntimeValue { protected ByteBuffer rawVal; protected RuntimeType type; RuntimeValue(RuntimeType type, ByteBuffer rawVal) { this.rawVal = rawVal; this.type = type; } public RuntimeType getType() { return type; } public void setType(RuntimeType type) { this.type = type; } private ByteBuffer getRawVal() { return rawVal; } } public static class RuntimeRegister extends RuntimeValue { private final int num; private RuntimeRegister(int num, RuntimeType type, ByteBuffer rawVal) { super(type, rawVal); this.num = num; } public int getRegNum() { return num; } } public static class RuntimeVarInfo extends RegisterInfo { private final VarWithGenericSlot slot; private RuntimeVarInfo(VarWithGenericSlot slot) { this.slot = slot; } @Override public String getName() { return slot.name; } @Override public int getRegNum() { return slot.slot; } @Override public String getType() { String gen = getSignature(); if (gen == null || gen.isEmpty()) { return this.slot.signature; } return gen; } @NotNull @Override public String getSignature() { return this.slot.genericSignature.trim(); } @Override public int getStartOffset() { return (int) slot.codeIndex; } @Override public int getEndOffset() { return (int) (slot.codeIndex + slot.length); } @Override public boolean isMarkedAsParameter() { return false; } } public static class RuntimeDebugInfo { private final List<RuntimeVarInfo> infoList; private RuntimeDebugInfo(VarTableWithGenericData data) { infoList = new ArrayList<>(data.slots.size()); for (VarWithGenericSlot slot : data.slots) { infoList.add(new RuntimeVarInfo(slot)); } } public List<RuntimeVarInfo> getInfoList() { return infoList; } } public static class Frame { private final long id; private final long clsID; private final long mthID; private final long index; private Frame(long id, long clsID, long mthID, long index) { this.id = id; this.clsID = clsID; this.mthID = mthID; this.index = index; } public long getID() { return id; } public long getClassID() { return clsID; } public long getMethodID() { return mthID; } public long getCodeIndex() { return index; } } public interface ClassPrepareListener { void onPrepared(long id); } public interface ClassListener { void onPrepared(String cls, long id); void onUnloaded(String cls); } /** * Listener for breakpoint, watch, step, etc. */ public interface SuspendListener { /** * For step, breakpoint, watchpoint, and any other events that suspend the JVM. * This method will be called in stateListenQueue. */ void onSuspendEvent(SuspendInfo current); } }
skylot/jadx
jadx-gui/src/main/java/jadx/gui/device/debugger/SmaliDebugger.java
179,602
/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cglib.util; abstract class SorterTemplate { private static final int MERGESORT_THRESHOLD = 12; private static final int QUICKSORT_THRESHOLD = 7; abstract protected void swap(int i, int j); abstract protected int compare(int i, int j); protected void quickSort(int lo, int hi) { quickSortHelper(lo, hi); insertionSort(lo, hi); } private void quickSortHelper(int lo, int hi) { for (;;) { int diff = hi - lo; if (diff <= QUICKSORT_THRESHOLD) { break; } int i = (hi + lo) / 2; if (compare(lo, i) > 0) { swap(lo, i); } if (compare(lo, hi) > 0) { swap(lo, hi); } if (compare(i, hi) > 0) { swap(i, hi); } int j = hi - 1; swap(i, j); i = lo; int v = j; for (;;) { while (compare(++i, v) < 0) { /* nothing */ } while (compare(--j, v) > 0) { /* nothing */ } if (j < i) { break; } swap(i, j); } swap(i, hi - 1); if (j - lo <= hi - i + 1) { quickSortHelper(lo, j); lo = i + 1; } else { quickSortHelper(i + 1, hi); hi = j; } } } private void insertionSort(int lo, int hi) { for (int i = lo + 1 ; i <= hi; i++) { for (int j = i; j > lo; j--) { if (compare(j - 1, j) > 0) { swap(j - 1, j); } else { break; } } } } protected void mergeSort(int lo, int hi) { int diff = hi - lo; if (diff <= MERGESORT_THRESHOLD) { insertionSort(lo, hi); return; } int mid = lo + diff / 2; mergeSort(lo, mid); mergeSort(mid, hi); merge(lo, mid, hi, mid - lo, hi - mid); } private void merge(int lo, int pivot, int hi, int len1, int len2) { if (len1 == 0 || len2 == 0) { return; } if (len1 + len2 == 2) { if (compare(pivot, lo) < 0) { swap(pivot, lo); } return; } int first_cut, second_cut; int len11, len22; if (len1 > len2) { len11 = len1 / 2; first_cut = lo + len11; second_cut = lower(pivot, hi, first_cut); len22 = second_cut - pivot; } else { len22 = len2 / 2; second_cut = pivot + len22; first_cut = upper(lo, pivot, second_cut); len11 = first_cut - lo; } rotate(first_cut, pivot, second_cut); int new_mid = first_cut + len22; merge(lo, first_cut, new_mid, len11, len22); merge(new_mid, second_cut, hi, len1 - len11, len2 - len22); } private void rotate(int lo, int mid, int hi) { int lot = lo; int hit = mid - 1; while (lot < hit) { swap(lot++, hit--); } lot = mid; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } lot = lo; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } } private int lower(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid= lo + half; if (compare(mid, val) < 0) { lo = mid + 1; len = len - half -1; } else { len = half; } } return lo; } private int upper(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid = lo + half; if (compare(val, mid) < 0) { len = half; } else { lo = mid + 1; len = len - half -1; } } return lo; } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/cglib/util/SorterTemplate.java
179,603
/* * Copyright 2012 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. */ /** * Writes very large data stream asynchronously neither spending a lot of * memory nor getting {@link java.lang.OutOfMemoryError}. For a detailed * example, please refer to {@code io.netty.example.http.file}. */ package io.netty.handler.stream;
netty/netty
handler/src/main/java/io/netty/handler/stream/package-info.java
179,608
/* * Copyright (C) 2012-2017 The Project Lombok Authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Generates a lot of code which fits with a class that is a representation of an immutable entity. * <p> * Equivalent to {@code @Getter @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) @AllArgsConstructor @ToString @EqualsAndHashCode}. * <p> * Complete documentation is found at <a href="https://projectlombok.org/features/Value">the project lombok features page for &#64;Value</a>. * * @see lombok.Getter * @see lombok.experimental.FieldDefaults * @see lombok.AllArgsConstructor * @see lombok.ToString * @see lombok.EqualsAndHashCode * @see lombok.Data */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Value { /** * If you specify a static constructor name, then the generated constructor will be private, and * instead a static factory method is created that other classes can use to create instances. * We suggest the name: "of", like so: * * <pre> * public @Value(staticConstructor = "of") class Point { final int x, y; } * </pre> * * Default: No static constructor, instead the normal constructor is public. * * @return Name of static 'constructor' method to generate (blank = generate a normal constructor). */ String staticConstructor() default ""; }
projectlombok/lombok
src/core/lombok/Value.java
179,611
/* * 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.spark.api.plugin; import java.util.Collections; import java.util.Map; import org.apache.spark.SparkContext; import org.apache.spark.annotation.DeveloperApi; /** * :: DeveloperApi :: * Driver component of a {@link SparkPlugin}. * * @since 3.0.0 */ @DeveloperApi public interface DriverPlugin { /** * Initialize the plugin. * <p> * This method is called early in the initialization of the Spark driver. Explicitly, it is * called before the Spark driver's task scheduler is initialized. This means that a lot * of other Spark subsystems may yet not have been initialized. This call also blocks driver * initialization. * <p> * It's recommended that plugins be careful about what operations are performed in this call, * preferably performing expensive operations in a separate thread, or postponing them until * the application has fully started. * * @param sc The SparkContext loading the plugin. * @param pluginContext Additional plugin-specific about the Spark application where the plugin * is running. * @return A map that will be provided to the {@link ExecutorPlugin#init(PluginContext,Map)} * method. */ default Map<String, String> init(SparkContext sc, PluginContext pluginContext) { return Collections.emptyMap(); } /** * Register metrics published by the plugin with Spark's metrics system. * <p> * This method is called later in the initialization of the Spark application, after most * subsystems are up and the application ID is known. If there are metrics registered in * the registry ({@link PluginContext#metricRegistry()}), then a metrics source with the * plugin name will be created. * <p> * Note that even though the metric registry is still accessible after this method is called, * registering new metrics after this method is called may result in the metrics not being * available. * * @param appId The application ID from the cluster manager. * @param pluginContext Additional plugin-specific about the Spark application where the plugin * is running. */ default void registerMetrics(String appId, PluginContext pluginContext) {} /** * RPC message handler. * <p> * Plugins can use Spark's RPC system to send messages from executors to the driver (but not * the other way around, currently). Messages sent by the executor component of the plugin will * be delivered to this method, and the returned value will be sent back to the executor as * the reply, if the executor has requested one. * <p> * Any exception thrown will be sent back to the executor as an error, in case it is expecting * a reply. In case a reply is not expected, a log message will be written to the driver log. * <p> * The implementation of this handler should be thread-safe. * <p> * Note all plugins share RPC dispatch threads, and this method is called synchronously. So * performing expensive operations in this handler may affect the operation of other active * plugins. Internal Spark endpoints are not directly affected, though, since they use different * threads. * <p> * Spark guarantees that the driver component will be ready to receive messages through this * handler when executors are started. * * @param message The incoming message. * @return Value to be returned to the caller. Ignored if the caller does not expect a reply. */ default Object receive(Object message) throws Exception { throw new UnsupportedOperationException(); } /** * Informs the plugin that the Spark application is shutting down. * <p> * This method is called during the driver shutdown phase. It is recommended that plugins * not use any Spark functions (e.g. send RPC messages) during this call. */ default void shutdown() {} }
apache/spark
core/src/main/java/org/apache/spark/api/plugin/DriverPlugin.java
179,613
package edu.stanford.nlp.util; import java.io.DataOutputStream; import java.io.Serializable; import java.util.Comparator; import java.util.List; import edu.stanford.nlp.util.logging.PrettyLoggable; import edu.stanford.nlp.util.logging.PrettyLogger; import edu.stanford.nlp.util.logging.Redwood.RedwoodChannels; /** * Pair is a Class for holding mutable pairs of objects. * <p> * <i>Implementation note:</i> * On a 32-bit JVM uses ~ 8 (this) + 4 (first) + 4 (second) = 16 bytes. * On a 64-bit JVM uses ~ 16 (this) + 8 (first) + 8 (second) = 32 bytes. * <p> * Many applications use a lot of Pairs so it's good to keep this * number small. * * @author Dan Klein * @author Christopher Manning (added stuff from Kristina's, rounded out) * @version 2002/08/25 */ public class Pair <T1,T2> implements Comparable<Pair<T1,T2>>, Serializable, PrettyLoggable { /** * Direct access is deprecated. Use first(). * * @serial */ public T1 first; /** * Direct access is deprecated. Use second(). * * @serial */ public T2 second; public Pair() { // first = null; second = null; -- default initialization } public Pair(T1 first, T2 second) { this.first = first; this.second = second; } public T1 first() { return first; } public T2 second() { return second; } public void setFirst(T1 o) { first = o; } public void setSecond(T2 o) { second = o; } @Override public String toString() { return "(" + first + "," + second + ")"; } @Override public boolean equals(Object o) { if (o instanceof Pair) { @SuppressWarnings("rawtypes") Pair p = (Pair) o; return (first == null ? p.first() == null : first.equals(p.first())) && (second == null ? p.second() == null : second.equals(p.second())); } else { return false; } } @Override public int hashCode() { int firstHash = (first == null ? 0 : first.hashCode()); int secondHash = (second == null ? 0 : second.hashCode()); return firstHash*31 + secondHash; } public List<Object> asList() { return CollectionUtils.makeList(first, second); } /** * Returns a Pair constructed from X and Y. Convenience method; the * compiler will disambiguate the classes used for you so that you * don't have to write out potentially long class names. */ public static <X, Y> Pair<X, Y> makePair(X x, Y y) { return new Pair<>(x, y); } /** * Write a string representation of a Pair to a DataStream. * The {@code toString()} method is called on each of the pair * of objects and a {@code String} representation is written. * This might not allow one to recover the pair of objects unless they * are of type {@code String}. */ public void save(DataOutputStream out) { try { out.writeUTF(first.toString()); out.writeUTF(second.toString()); } catch (Exception e) { e.printStackTrace(); } } /** * Compares this {@code Pair} to another object. * If the object is a {@code Pair}, this function will work providing * the elements of the {@code Pair} are themselves comparable. * It will then return a value based on the pair of objects, where * <code>p &gt; q iff p.first() &gt; q.first() || * (p.first().equals(q.first()) && p.second() &gt; q.second())</code>. * If the other object is not a {@code Pair}, it throws a * {@code ClassCastException}. * * @param another the {@code Object} to be compared. * @return the value {@code 0} if the argument is a * {@code Pair} equal to this {@code Pair}; a value less than * {@code 0} if the argument is a {@code Pair} * greater than this {@code Pair}; and a value * greater than {@code 0} if the argument is a * {@code Pair} less than this {@code Pair}. * @throws ClassCastException if the argument is not a * {@code Pair}. * @see java.lang.Comparable */ @SuppressWarnings("unchecked") public int compareTo(Pair<T1,T2> another) { if (first() instanceof Comparable) { int comp = ((Comparable<T1>) first()).compareTo(another.first()); if (comp != 0) { return comp; } } if (second() instanceof Comparable) { return ((Comparable<T2>) second()).compareTo(another.second()); } if ((!(first() instanceof Comparable)) && (!(second() instanceof Comparable))) { throw new AssertionError("Neither element of pair comparable"); } return 0; } /** * If first and second are Strings, then this returns an MutableInternedPair * where the Strings have been interned, and if this Pair is serialized * and then deserialized, first and second are interned upon * deserialization. * * @param p A pair of Strings * @return MutableInternedPair, with same first and second as this. */ public static Pair<String, String> stringIntern(Pair<String, String> p) { return new MutableInternedPair(p); } /** * Returns an MutableInternedPair where the Strings have been interned. * This is a factory method for creating an * MutableInternedPair. It requires the arguments to be Strings. * If this Pair is serialized * and then deserialized, first and second are interned upon * deserialization. * <p><i>Note:</i> I put this in thinking that its use might be * faster than calling <code>x = new Pair(a, b).stringIntern()</code> * but it's not really clear whether this is true. * * @param first The first object * @param second The second object * @return An MutableInternedPair, with given first and second */ public static Pair<String, String> internedStringPair(String first, String second) { return new MutableInternedPair(first, second); } /** * use serialVersionUID for cross version serialization compatibility */ private static final long serialVersionUID = 1360822168806852921L; static class MutableInternedPair extends Pair<String, String> { private MutableInternedPair(Pair<String, String> p) { super(p.first, p.second); internStrings(); } private MutableInternedPair(String first, String second) { super(first, second); internStrings(); } protected Object readResolve() { internStrings(); return this; } private void internStrings() { if (first != null) { first = first.intern(); } if (second != null) { second = second.intern(); } } // use serialVersionUID for cross version serialization compatibility private static final long serialVersionUID = 1360822168806852922L; } /** * {@inheritDoc} */ public void prettyLog(RedwoodChannels channels, String description) { PrettyLogger.log(channels, description, this.asList()); } /** * Compares a {@code Pair} to another {@code Pair} according to the first object of the pair only * This function will work providing the first element of the {@code Pair} is comparable, * otherwise will throw a {@code ClassCastException}. * * @author jonathanberant */ public static class ByFirstPairComparator<T1,T2> implements Comparator<Pair<T1,T2>> { @SuppressWarnings("unchecked") @Override public int compare(Pair<T1, T2> pair1, Pair<T1, T2> pair2) { return ((Comparable<T1>) pair1.first()).compareTo(pair2.first()); } } /** * Compares a {@code Pair} to another {@code Pair} according to the first object of the pair only in decreasing order * This function will work providing * the first element of the {@code Pair} is comparable, otherwise will throw a {@code ClassCastException} * @author jonathanberant */ public static class ByFirstReversePairComparator<T1,T2> implements Comparator<Pair<T1,T2>> { @SuppressWarnings("unchecked") @Override public int compare(Pair<T1, T2> pair1, Pair<T1, T2> pair2) { return -((Comparable<T1>) pair1.first()).compareTo(pair2.first()); } } /** * Compares a {@code Pair} to another {@code Pair} according to the second object of the pair only * This function will work providing * the first element of the {@code Pair} is comparable, otherwise will throw a {@code ClassCastException} * @author jonathanberant */ public static class BySecondPairComparator<T1,T2> implements Comparator<Pair<T1,T2>> { @SuppressWarnings("unchecked") @Override public int compare(Pair<T1, T2> pair1, Pair<T1, T2> pair2) { return ((Comparable<T2>) pair1.second()).compareTo(pair2.second()); } } /** * Compares a {@code Pair} to another {@code Pair} according to the second object of the pair only in decreasing order * This function will work providing * the first element of the {@code Pair} is comparable, otherwise will throw a {@code ClassCastException} * * @author jonathanberant */ public static class BySecondReversePairComparator<T1,T2> implements Comparator<Pair<T1,T2>> { @SuppressWarnings("unchecked") @Override public int compare(Pair<T1, T2> pair1, Pair<T1, T2> pair2) { return -((Comparable<T2>) pair1.second()).compareTo(pair2.second()); } } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/util/Pair.java
179,614
package org.telegram.tgnet.tl; import org.telegram.messenger.DialogObject; import org.telegram.tgnet.AbstractSerializedData; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.tl.TL_stats.TL_statsPercentValue; import org.telegram.ui.Stories.recorder.StoryPrivacyBottomSheet; import java.util.ArrayList; public class TL_stories { public static class TL_stories_storyViews extends TLObject { public static final int constructor = 0xde9eed1d; public ArrayList<StoryViews> views = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_storyViews TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_storyViews.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_storyViews", constructor)); } else { return null; } } TL_stories_storyViews result = new TL_stories_storyViews(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryViews object = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class StoryView extends TLObject { public int flags; public boolean blocked; public boolean blocked_my_stories_from; public long user_id; public int date; public TLRPC.Reaction reaction; public TLRPC.Message message; public TLRPC.Peer peer_id; public StoryItem story; public static StoryView TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryView result = null; switch (constructor) { case TL_storyView.constructor: result = new TL_storyView(); break; case TL_storyViewPublicForward.constructor: result = new TL_storyViewPublicForward(); break; case TL_storyViewPublicRepost.constructor: result = new TL_storyViewPublicRepost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryView", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyView extends StoryView { public static final int constructor = 0xb0bdeac5; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; user_id = stream.readInt64(exception); date = stream.readInt32(exception); if ((flags & 4) != 0) { reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); stream.writeInt64(user_id); stream.writeInt32(date); if ((flags & 4) != 0) { reaction.serializeToStream(stream); } } } public static class TL_storyViewPublicForward extends StoryView { public static final int constructor = 0x9083670b; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; message = TLRPC.Message.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); message.serializeToStream(stream); } } public static class TL_storyViewPublicRepost extends StoryView { public static final int constructor = 0xbd74cf49; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); blocked = (flags & 1) != 0; blocked_my_stories_from = (flags & 2) != 0; peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = blocked ? (flags | 1) : (flags &~ 1); flags = blocked_my_stories_from ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); peer_id.serializeToStream(stream); story.serializeToStream(stream); } } public static abstract class PeerStories extends TLObject { public int flags; public TLRPC.Peer peer; public int max_read_id; public ArrayList<StoryItem> stories = new ArrayList<>(); public static PeerStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { PeerStories result = null; switch (constructor) { case 0x9a35e999: result = new TL_peerStories(); break; case 0x8611a200: result = new TL_peerStories_layer162(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in PeerStories", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_peerStories extends PeerStories { public static final int constructor = 0x9a35e999; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 1) != 0) { max_read_id = stream.readInt32(exception); } int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); peer.serializeToStream(stream); if ((flags & 1) != 0) { stream.writeInt32(max_read_id); } stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } } } public static class TL_peerStories_layer162 extends TL_peerStories { public static final int constructor = 0x8611a200; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); long user_id = stream.readInt64(exception); peer = new TLRPC.TL_peerUser(); peer.user_id = user_id; if ((flags & 1) != 0) { max_read_id = stream.readInt32(exception); } int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt64(peer.user_id); if ((flags & 1) != 0) { stream.writeInt32(max_read_id); } stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } } } public static class TL_stories_peerStories extends TLObject { public static final int constructor = 0xcae68768; public PeerStories stories; public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_peerStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_peerStories.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_peerStories", constructor)); } else { return null; } } TL_stories_peerStories result = new TL_stories_peerStories(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { stories = PeerStories.TLdeserialize(stream, stream.readInt32(exception), exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stories.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static abstract class stories_AllStories extends TLObject { public static stories_AllStories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { stories_AllStories result = null; switch (constructor) { case 0x1158fe3e: result = new TL_stories_allStoriesNotModified(); break; case 0x6efc5e81: result = new TL_stories_allStories(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in stories_AllStories", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_stories_allStoriesNotModified extends stories_AllStories { public static final int constructor = 0x1158fe3e; public int flags; public String state; public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); state = stream.readString(exception); stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeString(state); stealth_mode.serializeToStream(stream); } } public static class TL_stories_allStories extends stories_AllStories { public static final int constructor = 0x6efc5e81; public int flags; public boolean has_more; public int count; public String state; public ArrayList<PeerStories> peer_stories = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); has_more = (flags & 1) != 0; count = stream.readInt32(exception); state = stream.readString(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { PeerStories object = PeerStories.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } peer_stories.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = has_more ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); stream.writeInt32(count); stream.writeString(state); stream.writeInt32(0x1cb5c415); int count = peer_stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { peer_stories.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } stealth_mode.serializeToStream(stream); } } public static class TL_stories_canSendStory extends TLObject { public static final int constructor = 0xc7dfdfdd; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_stories_sendStory extends TLObject { public static final int constructor = 0xe4e6694b; public int flags; public boolean pinned; public boolean noforwards; public boolean fwd_modified; public TLRPC.InputPeer peer; public TLRPC.InputMedia media; public ArrayList<MediaArea> media_areas = new ArrayList<>(); public String caption; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public ArrayList<TLRPC.InputPrivacyRule> privacy_rules = new ArrayList<>(); public long random_id; public int period; public TLRPC.InputPeer fwd_from_id; public int fwd_from_story; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 4) : (flags &~ 4); flags = noforwards ? (flags | 16) : (flags &~ 16); flags = fwd_modified ? (flags | 128) : (flags &~ 128); stream.writeInt32(flags); peer.serializeToStream(stream); media.serializeToStream(stream); if ((flags & 32) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } stream.writeInt32(0x1cb5c415); int count = privacy_rules.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy_rules.get(a).serializeToStream(stream); } stream.writeInt64(random_id); if ((flags & 8) != 0) { stream.writeInt32(period); } if ((flags & 64) != 0) { fwd_from_id.serializeToStream(stream); } if ((flags & 64) != 0) { stream.writeInt32(fwd_from_story); } } } public static class TL_stories_deleteStories extends TLObject { public static final int constructor = 0xae59db5f; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_togglePinned extends TLObject { public static final int constructor = 0x9a75a1ef; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public boolean pinned; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } stream.writeBool(pinned); } } public static class TL_stories_editStory extends TLObject { public static final int constructor = 0xb583ba46; public int flags; public TLRPC.InputPeer peer; public int id; public TLRPC.InputMedia media; public ArrayList<MediaArea> media_areas = new ArrayList<>(); public String caption; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public ArrayList<TLRPC.InputPrivacyRule> privacy_rules = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); if ((flags & 1) != 0) { media.serializeToStream(stream); } if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 2) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy_rules.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy_rules.get(a).serializeToStream(stream); } } } } public static class TL_stories_getAllStories extends TLObject { public static final int constructor = 0xeeb0d625; public int flags; public boolean include_hidden; public boolean next; public String state; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return stories_AllStories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = next ? (flags | 2) : (flags &~ 2); flags = include_hidden ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeString(state); } } } public static class TL_stories_togglePeerStoriesHidden extends TLObject { public static final int constructor = 0xbd0415c4; public TLRPC.InputPeer peer; public boolean hidden; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeBool(hidden); } } public static class TL_stories_stories extends TLObject { public static final int constructor = 0x63c3dd0a; public int flags; public int count; public ArrayList<StoryItem> stories = new ArrayList<>(); public ArrayList<Integer> pinned_to_top = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_stories_stories TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stories_stories.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stories_stories", constructor)); } else { return null; } } TL_stories_stories result = new TL_stories_stories(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryItem object = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } stories.add(object); } if ((flags & 1) != 0) { magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { pinned_to_top.add(stream.readInt32(exception)); } } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = stories.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stories.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); count = pinned_to_top.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(pinned_to_top.get(a)); } } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_stories_getPeerStories extends TLObject { public static final int constructor = 0x2c4ada50; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_peerStories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_updateStory extends TLRPC.Update { public static final int constructor = 0x75b3b798; public TLRPC.Peer peer; public StoryItem story; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); story.serializeToStream(stream); } } public static class TL_stories_getPinnedStories extends TLObject { public static final int constructor = 0x5821a5dc; public TLRPC.InputPeer peer; public int offset_id; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(offset_id); stream.writeInt32(limit); } } public static class TL_stories_getStoriesArchive extends TLObject { public static final int constructor = 0xb4352016; public TLRPC.InputPeer peer; public int offset_id; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(offset_id); stream.writeInt32(limit); } } public static class TL_updateReadStories extends TLRPC.Update { public static final int constructor = 0xf74e932b; public TLRPC.Peer peer; public int max_id; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); max_id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(max_id); } } public static class StoryViewsList extends TLObject { public int flags; public int count; public int views_count; public int forwards_count; public int reactions_count; public ArrayList<StoryView> views = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public String next_offset = ""; public static StoryViewsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryViewsList result = null; switch (constructor) { case TL_storyViewsList.constructor: result = new TL_storyViewsList(); break; case TL_storyViewsList_layer167.constructor: result = new TL_storyViewsList_layer167(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryViewsList", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyViewsList extends StoryViewsList { public static final int constructor = 0x59d78fc5; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); views_count = stream.readInt32(exception); forwards_count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryView object = StoryView.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(views_count); stream.writeInt32(forwards_count); stream.writeInt32(reactions_count); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } } public static class TL_storyViewsList_layer167 extends StoryViewsList { public static final int constructor = 0x46e9b9ec; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryView object = StoryView.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } views.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(reactions_count); stream.writeInt32(0x1cb5c415); int count = views.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { views.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } } public static class TL_stories_readStories extends TLObject { public static final int constructor = 0xa556dac8; public TLRPC.InputPeer peer; public int max_id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(max_id); } } public static class TL_stories_incrementStoryViews extends TLObject { public static final int constructor = 0xb2028afb; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_getStoryViewsList extends TLObject { public static final int constructor = 0x7ed23c57; public int flags; public boolean just_contacts; public boolean reactions_first; public boolean forwards_first; public TLRPC.InputPeer peer; public String q; public int id; public String offset; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return StoryViewsList.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = just_contacts ? (flags | 1) : (flags &~ 1); flags = reactions_first ? (flags | 4) : (flags &~ 4); flags = forwards_first ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); peer.serializeToStream(stream); if ((flags & 2) != 0) { stream.writeString(q); } stream.writeInt32(id); stream.writeString(offset); stream.writeInt32(limit); } } public static class TL_stories_getStoriesByID extends TLObject { public static final int constructor = 0x5774ca74; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_stories.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_stories_getStoriesViews extends TLObject { public static final int constructor = 0x28e16cc8; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stories_storyViews.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } public static class TL_exportedStoryLink extends TLObject { public static final int constructor = 0x3fc9053b; public String link; public static TL_exportedStoryLink TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_exportedStoryLink.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_exportedStoryLink", constructor)); } else { return null; } } TL_exportedStoryLink result = new TL_exportedStoryLink(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { link = stream.readString(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeString(link); } } public static class TL_stories_exportStoryLink extends TLObject { public static final int constructor = 0x7b8def20; public TLRPC.InputPeer peer; public int id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_exportedStoryLink.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(id); } } public static class TL_stories_report extends TLObject { public static final int constructor = 0x1923fa8c; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLRPC.ReportReason reason; public String message; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } reason.serializeToStream(stream); stream.writeString(message); } } public static class TL_stories_getAllReadPeerStories extends TLObject { public static final int constructor = 0x9b5ae7f9; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_stories_getPeerMaxIDs extends TLObject { public static final int constructor = 0x535983c3; public ArrayList<TLRPC.InputPeer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { TLRPC.Vector vector = new TLRPC.Vector(); int size = stream.readInt32(exception); for (int a = 0; a < size; a++) { vector.objects.add(stream.readInt32(exception)); } return vector; } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { id.get(a).serializeToStream(stream); } } } public static class TL_updateStoriesStealthMode extends TLRPC.Update { public static final int constructor = 0x2c084dc1; public TL_storiesStealthMode stealth_mode; public void readParams(AbstractSerializedData stream, boolean exception) { stealth_mode = TL_storiesStealthMode.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stealth_mode.serializeToStream(stream); } } public static class TL_storiesStealthMode extends TLObject { public static final int constructor = 0x712e27fd; public int flags; public int active_until_date; public int cooldown_until_date; public static TL_storiesStealthMode TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_storiesStealthMode.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_storiesStealthMode", constructor)); } else { return null; } } TL_storiesStealthMode result = new TL_storiesStealthMode(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); if ((flags & 1) != 0) { active_until_date = stream.readInt32(exception); } if ((flags & 2) != 0) { cooldown_until_date = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeInt32(active_until_date); } if ((flags & 2) != 0) { stream.writeInt32(cooldown_until_date); } } } public static class TL_stories_activateStealthMode extends TLObject { public static final int constructor = 0x57bbd166; public int flags; public boolean past; public boolean future; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = past ? (flags | 1) : (flags &~ 1); flags = future ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); } } public static class TL_stories_sendReaction extends TLObject { public static final int constructor = 0x7fd736b2; public int flags; public boolean add_to_recent; public TLRPC.InputPeer peer; public int story_id; public TLRPC.Reaction reaction; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Updates.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = add_to_recent ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(story_id); reaction.serializeToStream(stream); } } public static class TL_stories_getChatsToSend extends TLObject { public static final int constructor = 0xa56a8b60; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.TL_messages_chats.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_myBoost extends TLObject { public static int constructor = 0xc448415c; public int flags; public int slot; public TLRPC.Peer peer; public int date; public int expires; public int cooldown_until_date; public static TL_myBoost TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_myBoost.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_myBoost", constructor)); } else { return null; } } TL_myBoost result = new TL_myBoost(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); slot = stream.readInt32(exception); if ((flags & 1) != 0) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } date = stream.readInt32(exception); expires = stream.readInt32(exception); if ((flags & 2) != 0) { cooldown_until_date = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(slot); if ((flags & 1) != 0) { peer.serializeToStream(stream); } stream.writeInt32(date); stream.writeInt32(expires); if ((flags & 2) != 0) { stream.writeInt32(cooldown_until_date); } } } public static class TL_premium_myBoosts extends TLObject { public static int constructor = 0x9ae228e2; public ArrayList<TL_myBoost> my_boosts = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_premium_myBoosts TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_myBoosts.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_myBoosts", constructor)); } else { return null; } } TL_premium_myBoosts result = new TL_premium_myBoosts(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_myBoost object = TL_myBoost.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } my_boosts.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(0x1cb5c415); int count = my_boosts.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { my_boosts.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { chats.get(a).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_premium_getMyBoosts extends TLObject { public static int constructor = 0xbe77b4a; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_myBoosts.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); } } public static class TL_premium_boostsStatus extends TLObject { public static int constructor = 0x4959427a; public int flags; public boolean my_boost; public int level; public int current_level_boosts; public int boosts; public int gift_boosts; public int next_level_boosts; public TL_statsPercentValue premium_audience; public String boost_url; public ArrayList<TL_prepaidGiveaway> prepaid_giveaways = new ArrayList<>(); public ArrayList<Integer> my_boost_slots = new ArrayList<>(); public static TL_premium_boostsStatus TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_boostsStatus.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_boostsStatus", constructor)); } else { return null; } } TL_premium_boostsStatus result = new TL_premium_boostsStatus(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); my_boost = (flags & 4) != 0; level = stream.readInt32(exception); current_level_boosts = stream.readInt32(exception); boosts = stream.readInt32(exception); if ((flags & 16) != 0) { gift_boosts = stream.readInt32(exception); } if ((flags & 1) != 0) { next_level_boosts = stream.readInt32(exception); } if ((flags & 2) != 0) { premium_audience = TL_stats.TL_statsPercentValue.TLdeserialize(stream, stream.readInt32(exception), exception); } boost_url = stream.readString(exception); if ((flags & 8) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_prepaidGiveaway object = TL_prepaidGiveaway.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } prepaid_giveaways.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { my_boost_slots.add(stream.readInt32(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = my_boost ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); stream.writeInt32(level); stream.writeInt32(current_level_boosts); stream.writeInt32(boosts); if ((flags & 16) != 0) { stream.writeInt32(gift_boosts); } if ((flags & 1) != 0) { stream.writeInt32(next_level_boosts); } if ((flags & 2) != 0) { premium_audience.serializeToStream(stream); } stream.writeString(boost_url); if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = prepaid_giveaways.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { prepaid_giveaways.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = my_boost_slots.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(my_boost_slots.get(a)); } } } } public static class TL_premium_getBoostsStatus extends TLObject { public static int constructor = 0x42f1f61; public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_boostsStatus.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); } } public static class TL_premium_applyBoost extends TLObject { public static int constructor = 0x6b7da746; public int flags; public ArrayList<Integer> slots = new ArrayList<>(); public TLRPC.InputPeer peer; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_myBoosts.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = slots.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(slots.get(a)); } } peer.serializeToStream(stream); } } public static class TL_boost extends TLObject { public static int constructor = 0x2a1c8c71; public static final long NO_USER_ID = -1L; //custom public int flags; public boolean gift; public boolean giveaway; public boolean unclaimed; public String id; public long user_id = NO_USER_ID; public int giveaway_msg_id; public int date; public int expires; public String used_gift_slug; public int multiplier; public static TL_boost TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_boost.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_boost", constructor)); } else { return null; } } TL_boost result = new TL_boost(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); gift = (flags & 2) != 0; giveaway = (flags & 4) != 0; unclaimed = (flags & 8) != 0; id = stream.readString(exception); if ((flags & 1) != 0) { user_id = stream.readInt64(exception); } if ((flags & 4) != 0) { giveaway_msg_id = stream.readInt32(exception); } date = stream.readInt32(exception); expires = stream.readInt32(exception); if ((flags & 16) != 0) { used_gift_slug = stream.readString(exception); } if ((flags & 32) != 0) { multiplier = stream.readInt32(exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = gift ? (flags | 2) : (flags &~ 2); flags = giveaway ? (flags | 4) : (flags &~ 4); flags = unclaimed ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); stream.writeString(id); if ((flags & 1) != 0) { stream.writeInt64(user_id); } if ((flags & 4) != 0) { stream.writeInt32(giveaway_msg_id); } stream.writeInt32(date); stream.writeInt32(expires); if ((flags & 16) != 0) { stream.writeString(used_gift_slug); } if ((flags & 32) != 0) { stream.writeInt32(multiplier); } } } public static class TL_premium_boostsList extends TLObject { public static int constructor = 0x86f8613c; public int flags; public int count; public ArrayList<TL_boost> boosts = new ArrayList<>(); public String next_offset; public ArrayList<TLRPC.User> users = new ArrayList<>(); public static TL_premium_boostsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_premium_boostsList.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_premium_boostsList", constructor)); } else { return null; } } TL_premium_boostsList result = new TL_premium_boostsList(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TL_boost object = TL_boost.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } boosts.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = boosts.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { boosts.get(a).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { users.get(a).serializeToStream(stream); } } } public static class TL_premium_getBoostsList extends TLObject { public static int constructor = 0x60f67660; public int flags; public boolean gifts; public TLRPC.InputPeer peer; public String offset; public int limit; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_premium_boostsList.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = gifts ? (flags | 1) : (flags &~ 1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeString(offset); stream.writeInt32(limit); } } public static abstract class StoryItem extends TLObject { public int flags; public boolean pinned; public boolean isPublic; public boolean close_friends; public boolean contacts; public boolean selected_contacts; public boolean noforwards; public boolean min; public boolean out; public int id; public int date; public TLRPC.Peer from_id; public StoryFwdHeader fwd_from; public int expire_date; public String caption; public boolean edited; public ArrayList<TLRPC.MessageEntity> entities = new ArrayList<>(); public TLRPC.MessageMedia media; public ArrayList<MediaArea> media_areas = new ArrayList(); public ArrayList<TLRPC.PrivacyRule> privacy = new ArrayList<>(); public StoryViews views; public TLRPC.Reaction sent_reaction; public long lastUpdateTime; //custom public String attachPath; //custom public String firstFramePath; //custom public long dialogId;// custom public boolean justUploaded;// custom public int messageId;//custom public int messageType;//custom public int fileReference; public String detectedLng; //custom public String translatedLng; //custom public boolean translated; //custom public TLRPC.TL_textWithEntities translatedText; //custom public StoryPrivacyBottomSheet.StoryPrivacy parsedPrivacy; //custom public static StoryItem TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryItem result = null; switch (constructor) { case TL_storyItem.constructor: result = new TL_storyItem(); break; case TL_storyItem_layer174.constructor: result = new TL_storyItem_layer174(); break; case TL_storyItem_layer166.constructor: result = new TL_storyItem_layer166(); break; case TL_storyItem_layer160.constructor: result = new TL_storyItem_layer160(); break; case TL_storyItemDeleted.constructor: result = new TL_storyItemDeleted(); break; case TL_storyItemSkipped.constructor: result = new TL_storyItemSkipped(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryItem", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static abstract class StoryViews extends TLObject { public int flags; public int views_count; public int reactions_count; public ArrayList<Long> recent_viewers = new ArrayList<>(); public boolean has_viewers; public int forwards_count; public ArrayList<TLRPC.ReactionCount> reactions = new ArrayList<>(); public static StoryViews TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryViews result = null; switch (constructor) { case 0xd36760cf: result = new TL_storyViews_layer160(); break; case 0xc64c0b97: result = new TL_storyViews_layer161(); break; case 0x8d595cd6: result = new TL_storyViews(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryViews", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyViews_layer160 extends StoryViews { public static final int constructor = 0xd36760cf; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); views_count = stream.readInt32(exception); if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(views_count); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_storyViews_layer161 extends StoryViews { public static final int constructor = 0xc64c0b97; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); views_count = stream.readInt32(exception); reactions_count = stream.readInt32(exception); if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(views_count); stream.writeInt32(reactions_count); if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_storyViews extends StoryViews { public static final int constructor = 0x8d595cd6; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); has_viewers = (flags & 2) != 0; views_count = stream.readInt32(exception); if ((flags & 4) != 0) { forwards_count = stream.readInt32(exception); } if ((flags & 8) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.ReactionCount object = TLRPC.ReactionCount.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } reactions.add(object); } } if ((flags & 16) != 0) { reactions_count = stream.readInt32(exception); } if ((flags & 1) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { recent_viewers.add(stream.readInt64(exception)); } } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = has_viewers ? (flags | 2) : (flags & ~2); stream.writeInt32(flags); stream.writeInt32(views_count); if ((flags & 4) != 0) { stream.writeInt32(forwards_count); } if ((flags & 8) != 0) { stream.writeInt32(0x1cb5c415); int count = reactions.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { reactions.get(a).serializeToStream(stream); } } if ((flags & 16) != 0) { stream.writeInt32(reactions_count); } if ((flags & 1) != 0) { stream.writeInt32(0x1cb5c415); int count = recent_viewers.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt64(recent_viewers.get(a)); } } } } public static class TL_publicForwardStory extends TL_stats.PublicForward { public static final int constructor = 0xedf3add0; public TLRPC.Peer peer; public StoryItem story; public void readParams(AbstractSerializedData stream, boolean exception) { peer = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); story.serializeToStream(stream); } } public static class StoryFwdHeader extends TLObject { public int flags; public boolean modified; public TLRPC.Peer from; public String from_name; public int story_id; public static StoryFwdHeader TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryFwdHeader result = null; switch (constructor) { case TL_storyFwdHeader.constructor: result = new TL_storyFwdHeader(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryFwdHeader", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyFwdHeader extends StoryFwdHeader { public static final int constructor = 0xb826e150; @Override public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); modified = (flags & 8) != 0; if ((flags & 1) != 0) { from = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 2) != 0) { from_name = stream.readString(exception); } if ((flags & 4) != 0) { story_id = stream.readInt32(exception); } } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = modified ? (flags | 8) : (flags &~ 8); stream.writeInt32(flags); if ((flags & 1) != 0) { from.serializeToStream(stream); } if ((flags & 2) != 0) { stream.writeString(from_name); } if ((flags & 4) != 0) { stream.writeInt32(story_id); } } } public static class TL_storyItem extends StoryItem { public static final int constructor = 0x79b26a24; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); if ((flags & 262144) != 0) { from_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 131072) != 0) { fwd_from = TL_storyFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); if ((flags & 262144) != 0) { from_id.serializeToStream(stream); } if ((flags & 131072) != 0) { fwd_from.serializeToStream(stream); } stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer174 extends TL_storyItem { public static final int constructor = 0xaf6365a1; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); if ((flags & 131072) != 0) { fwd_from = TL_storyFwdHeader.TLdeserialize(stream, stream.readInt32(exception), exception); } expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); if ((flags & 131072) != 0) { fwd_from.serializeToStream(stream); } stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer166 extends TL_storyItem { public static final int constructor = 0x44c457ce; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; out = (flags & 65536) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 16384) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { MediaArea object = MediaArea.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } media_areas.add(object); } } if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } if ((flags & 32768) != 0) { sent_reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); flags = out ? (flags | 65536) : (flags &~ 65536); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 16384) != 0) { stream.writeInt32(0x1cb5c415); int count = media_areas.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { media_areas.get(a).serializeToStream(stream); } } if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } if ((flags & 32768) != 0) { sent_reaction.serializeToStream(stream); } } } public static class TL_storyItem_layer160 extends TL_storyItem { public static final int constructor = 0x562aa637; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); pinned = (flags & 32) != 0; isPublic = (flags & 128) != 0; close_friends = (flags & 256) != 0; min = (flags & 512) != 0; noforwards = (flags & 1024) != 0; edited = (flags & 2048) != 0; contacts = (flags & 4096) != 0; selected_contacts = (flags & 8192) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); if ((flags & 1) != 0) { caption = stream.readString(exception); } if ((flags & 2) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.MessageEntity object = TLRPC.MessageEntity.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } entities.add(object); } } media = TLRPC.MessageMedia.TLdeserialize(stream, stream.readInt32(exception), exception); if ((flags & 4) != 0) { int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.PrivacyRule object = TLRPC.PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } privacy.add(object); } } if ((flags & 8) != 0) { views = StoryViews.TLdeserialize(stream, stream.readInt32(exception), exception); } } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = pinned ? (flags | 32) : (flags &~ 32); flags = isPublic ? (flags | 128) : (flags &~ 128); flags = close_friends ? (flags | 256) : (flags &~ 256); flags = min ? (flags | 512) : (flags &~ 512); flags = noforwards ? (flags | 1024) : (flags &~ 1024); flags = edited ? (flags | 2048) : (flags &~ 2048); flags = contacts ? (flags | 4096) : (flags &~ 4096); flags = selected_contacts ? (flags | 8192) : (flags &~ 8192); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); if ((flags & 1) != 0) { stream.writeString(caption); } if ((flags & 2) != 0) { stream.writeInt32(0x1cb5c415); int count = entities.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { entities.get(a).serializeToStream(stream); } } media.serializeToStream(stream); if ((flags & 4) != 0) { stream.writeInt32(0x1cb5c415); int count = privacy.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { privacy.get(a).serializeToStream(stream); } } if ((flags & 8) != 0) { views.serializeToStream(stream); } } } public static class TL_storyItemDeleted extends StoryItem { public static final int constructor = 0x51e6ee4f; public void readParams(AbstractSerializedData stream, boolean exception) { id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(id); } } public static class TL_storyItemSkipped extends StoryItem { public static final int constructor = 0xffadc913; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); close_friends = (flags & 256) != 0; id = stream.readInt32(exception); date = stream.readInt32(exception); expire_date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = close_friends ? (flags | 256) : (flags &~ 256); stream.writeInt32(flags); stream.writeInt32(id); stream.writeInt32(date); stream.writeInt32(expire_date); } } public static class TL_mediaAreaCoordinates extends TLObject { public static final int constructor = 0x3d1ea4e; public double x; public double y; public double w; public double h; public double rotation; public static TL_mediaAreaCoordinates TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_mediaAreaCoordinates.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_mediaAreaCoordinates", constructor)); } else { return null; } } TL_mediaAreaCoordinates result = new TL_mediaAreaCoordinates(); result.readParams(stream, exception); return result; } @Override public void readParams(AbstractSerializedData stream, boolean exception) { x = stream.readDouble(exception); y = stream.readDouble(exception); w = stream.readDouble(exception); h = stream.readDouble(exception); rotation = stream.readDouble(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeDouble(x); stream.writeDouble(y); stream.writeDouble(w); stream.writeDouble(h); stream.writeDouble(rotation); } } public static class MediaArea extends TLObject { public TL_mediaAreaCoordinates coordinates; public TLRPC.Reaction reaction; public int flags; public boolean dark; public boolean flipped; public static MediaArea TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { MediaArea result = null; switch (constructor) { case TL_mediaAreaVenue.constructor: result = new TL_mediaAreaVenue(); break; case TL_mediaAreaGeoPoint.constructor: result = new TL_mediaAreaGeoPoint(); break; case TL_inputMediaAreaVenue.constructor: result = new TL_inputMediaAreaVenue(); break; case TL_inputMediaAreaChannelPost.constructor: result = new TL_inputMediaAreaChannelPost(); break; case TL_mediaAreaSuggestedReaction.constructor: result = new TL_mediaAreaSuggestedReaction(); break; case TL_mediaAreaChannelPost.constructor: result = new TL_mediaAreaChannelPost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in MediaArea", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_mediaAreaSuggestedReaction extends MediaArea { public static final int constructor = 0x14455871; public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); dark = (flags & 1) != 0; flipped = (flags & 2) != 0; coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = dark ? (flags | 1) : (flags &~ 1); flags = flipped ? (flags | 2) : (flags &~ 2); stream.writeInt32(flags); coordinates.serializeToStream(stream); reaction.serializeToStream(stream); } } public static class TL_mediaAreaChannelPost extends MediaArea { public static final int constructor = 0x770416af; public long channel_id; public int msg_id; public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); channel_id = stream.readInt64(exception); msg_id = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); stream.writeInt64(channel_id); stream.writeInt32(msg_id); } } public static class TL_mediaAreaVenue extends MediaArea { public static final int constructor = 0xbe82db9c; public TLRPC.GeoPoint geo; public String title; public String address; public String provider; public String venue_id; public String venue_type; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); geo = TLRPC.GeoPoint.TLdeserialize(stream, stream.readInt32(exception), exception); title = stream.readString(exception); address = stream.readString(exception); provider = stream.readString(exception); venue_id = stream.readString(exception); venue_type = stream.readString(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); geo.serializeToStream(stream); stream.writeString(title); stream.writeString(address); stream.writeString(provider); stream.writeString(venue_id); stream.writeString(venue_type); } } public static class TL_inputMediaAreaVenue extends MediaArea { public static final int constructor = 0xb282217f; public long query_id; public String result_id; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); query_id = stream.readInt64(exception); result_id = stream.readString(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); stream.writeInt64(query_id); stream.writeString(result_id); } } public static class TL_inputMediaAreaChannelPost extends MediaArea { public static final int constructor = 0x2271f2bf; public TLRPC.InputChannel channel; public int msg_id; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); channel = TLRPC.InputChannel.TLdeserialize(stream, stream.readInt32(exception), exception); msg_id = stream.readInt32(exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); channel.serializeToStream(stream); stream.writeInt32(msg_id); } } public static class TL_mediaAreaGeoPoint extends MediaArea { public static final int constructor = 0xdf8b3b22; public TLRPC.GeoPoint geo; @Override public void readParams(AbstractSerializedData stream, boolean exception) { coordinates = TL_mediaAreaCoordinates.TLdeserialize(stream, stream.readInt32(exception), exception); geo = TLRPC.GeoPoint.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); coordinates.serializeToStream(stream); geo.serializeToStream(stream); } } public static class TL_prepaidGiveaway extends TLObject { public static int constructor = 0xb2539d54; public long id; public int months; public int quantity; public int date; public static TL_prepaidGiveaway TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_prepaidGiveaway.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_prepaidGiveaway", constructor)); } else { return null; } } TL_prepaidGiveaway result = new TL_prepaidGiveaway(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { id = stream.readInt64(exception); months = stream.readInt32(exception); quantity = stream.readInt32(exception); date = stream.readInt32(exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt64(id); stream.writeInt32(months); stream.writeInt32(quantity); stream.writeInt32(date); } } public static class TL_stats_storyStats extends TLObject { public final static int constructor = 0x50cd067c; public TL_stats.StatsGraph views_graph; public TL_stats.StatsGraph reactions_by_emotion_graph; public static TL_stats_storyStats TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_stats_storyStats.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_stats_storyStats", constructor)); } else { return null; } } TL_stats_storyStats result = new TL_stats_storyStats(); result.readParams(stream, exception); return result; } public void readParams(AbstractSerializedData stream, boolean exception) { views_graph = TL_stats.StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); reactions_by_emotion_graph = TL_stats.StatsGraph.TLdeserialize(stream, stream.readInt32(exception), exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); views_graph.serializeToStream(stream); reactions_by_emotion_graph.serializeToStream(stream); } } public static class TL_stats_getStoryStats extends TLObject { public final static int constructor = 0x374fef40; public int flags; public boolean dark; public TLRPC.InputPeer peer; public int id; public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_stats_storyStats.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = dark ? (flags | 1) : (flags & ~1); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); } } public static class StoryReaction extends TLObject { public TLRPC.Peer peer_id; public StoryItem story; public TLRPC.Message message; public static StoryReaction TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { StoryReaction result = null; switch (constructor) { case TL_storyReaction.constructor: result = new TL_storyReaction(); break; case TL_storyReactionPublicForward.constructor: result = new TL_storyReactionPublicForward(); break; case TL_storyReactionPublicRepost.constructor: result = new TL_storyReactionPublicRepost(); break; } if (result == null && exception) { throw new RuntimeException(String.format("can't parse magic %x in StoryReaction", constructor)); } if (result != null) { result.readParams(stream, exception); } return result; } } public static class TL_storyReactionPublicForward extends StoryReaction { public final static int constructor = 0xbbab2643; @Override public void readParams(AbstractSerializedData stream, boolean exception) { message = TLRPC.Message.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); message.serializeToStream(stream); } } public static class TL_storyReactionPublicRepost extends StoryReaction { public final static int constructor = 0xcfcd0f13; @Override public void readParams(AbstractSerializedData stream, boolean exception) { peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); story = StoryItem.TLdeserialize(stream, stream.readInt32(exception), exception); if (story != null) { story.dialogId = DialogObject.getPeerDialogId(peer_id); } } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer_id.serializeToStream(stream); story.serializeToStream(stream); } } public static class TL_storyReaction extends StoryReaction { public final static int constructor = 0x6090d6d5; public int date; public TLRPC.Reaction reaction; @Override public void readParams(AbstractSerializedData stream, boolean exception) { peer_id = TLRPC.Peer.TLdeserialize(stream, stream.readInt32(exception), exception); date = stream.readInt32(exception); reaction = TLRPC.Reaction.TLdeserialize(stream, stream.readInt32(exception), exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer_id.serializeToStream(stream); stream.writeInt32(date); reaction.serializeToStream(stream); } } public static class TL_storyReactionsList extends TLObject { public final static int constructor = 0xaa5f789c; public int flags; public int count; public ArrayList<StoryReaction> reactions = new ArrayList<>(); public ArrayList<TLRPC.Chat> chats = new ArrayList<>(); public ArrayList<TLRPC.User> users = new ArrayList<>(); public String next_offset; public static TL_storyReactionsList TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { if (TL_storyReactionsList.constructor != constructor) { if (exception) { throw new RuntimeException(String.format("can't parse magic %x in TL_storyReactionsList", constructor)); } else { return null; } } TL_storyReactionsList result = new TL_storyReactionsList(); result.readParams(stream, exception); return result; } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); stream.writeInt32(flags); stream.writeInt32(count); stream.writeInt32(0x1cb5c415); int count = reactions.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { reactions.get(i).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = chats.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { chats.get(i).serializeToStream(stream); } stream.writeInt32(0x1cb5c415); count = users.size(); stream.writeInt32(count); for (int i = 0; i < count; ++i) { users.get(i).serializeToStream(stream); } if ((flags & 1) != 0) { stream.writeString(next_offset); } } @Override public void readParams(AbstractSerializedData stream, boolean exception) { flags = stream.readInt32(exception); count = stream.readInt32(exception); int magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } int count = stream.readInt32(exception); for (int a = 0; a < count; a++) { StoryReaction object = StoryReaction.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } reactions.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.Chat object = TLRPC.Chat.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } chats.add(object); } magic = stream.readInt32(exception); if (magic != 0x1cb5c415) { if (exception) { throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); } return; } count = stream.readInt32(exception); for (int a = 0; a < count; a++) { TLRPC.User object = TLRPC.User.TLdeserialize(stream, stream.readInt32(exception), exception); if (object == null) { return; } users.add(object); } if ((flags & 1) != 0) { next_offset = stream.readString(exception); } } } public static class TL_getStoryReactionsList extends TLObject { public final static int constructor = 0xb9b2881f; public int flags; public boolean forwards_first; public TLRPC.InputPeer peer; public int id; public TLRPC.Reaction reaction; public String offset; public int limit; @Override public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TL_storyReactionsList.TLdeserialize(stream, constructor, exception); } @Override public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); flags = forwards_first ? (flags | 4) : (flags &~ 4); stream.writeInt32(flags); peer.serializeToStream(stream); stream.writeInt32(id); if ((flags & 1) != 0) { reaction.serializeToStream(stream); } if ((flags & 2) != 0) { stream.writeString(offset); } stream.writeInt32(limit); } } public static class TL_togglePinnedToTop extends TLObject { public static final int constructor = 0xb297e9b; public TLRPC.InputPeer peer; public ArrayList<Integer> id = new ArrayList<>(); public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { return TLRPC.Bool.TLdeserialize(stream, constructor, exception); } public void serializeToStream(AbstractSerializedData stream) { stream.writeInt32(constructor); peer.serializeToStream(stream); stream.writeInt32(0x1cb5c415); int count = id.size(); stream.writeInt32(count); for (int a = 0; a < count; a++) { stream.writeInt32(id.get(a)); } } } }
DrKLO/Telegram
TMessagesProj/src/main/java/org/telegram/tgnet/tl/TL_stories.java
179,615
package com.airbnb.lottie.value; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.airbnb.lottie.LottieAnimationView; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; /** * Allows you to set a callback on a resolved {@link com.airbnb.lottie.model.KeyPath} to modify * its animation values at runtime. * * If your dynamic property does the following, you must call {@link LottieAnimationView#invalidate()} or * {@link LottieDrawable#invalidateSelf()} each time you want to update this value. * 1. Use {@link com.airbnb.lottie.RenderMode#SOFTWARE} * 2. Rendering a static image (the animation is either paused or there are no values * changing within the animation itself) * When using software rendering, Lottie caches the internal rendering bitmap. Whenever the animation changes * internally, Lottie knows to invalidate the bitmap and re-render it on the next frame. If the animation * never changes but your dynamic property does outside of Lottie, Lottie must be notified that it changed * in order to set the bitmap as dirty and re-render it on the next frame. */ public class LottieValueCallback<T> { private final LottieFrameInfo<T> frameInfo = new LottieFrameInfo<>(); @Nullable private BaseKeyframeAnimation<?, ?> animation; /** * This can be set with {@link #setValue(Object)} to use a value instead of deferring * to the callback. **/ @Nullable protected T value = null; public LottieValueCallback() { } public LottieValueCallback(@Nullable T staticValue) { value = staticValue; } /** * Override this if you haven't set a static value in the constructor or with setValue. * <p> * Return null to resort to the default value. * * Refer to the javadoc for this class for a special case that requires manual invalidation * each time you want to return something different from this method. */ @Nullable public T getValue(LottieFrameInfo<T> frameInfo) { return value; } public final void setValue(@Nullable T value) { this.value = value; if (animation != null) { animation.notifyListeners(); } } @RestrictTo(RestrictTo.Scope.LIBRARY) @Nullable public final T getValueInternal( float startFrame, float endFrame, T startValue, T endValue, float linearKeyframeProgress, float interpolatedKeyframeProgress, float overallProgress ) { return getValue( frameInfo.set( startFrame, endFrame, startValue, endValue, linearKeyframeProgress, interpolatedKeyframeProgress, overallProgress ) ); } @RestrictTo(RestrictTo.Scope.LIBRARY) public final void setAnimation(@Nullable BaseKeyframeAnimation<?, ?> animation) { this.animation = animation; } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/value/LottieValueCallback.java
179,617
/* * 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.rocketmq.store.timer; /** * Represents a slot of timing wheel. Format: * ┌────────────┬───────────┬───────────┬───────────┬───────────┐ * │delayed time│ first pos │ last pos │ num │ magic │ * ├────────────┼───────────┼───────────┼───────────┼───────────┤ * │ 8bytes │ 8bytes │ 8bytes │ 4bytes │ 4bytes │ * └────────────┴───────────┴───────────┴───────────┴───────────┘ */ public class Slot { public static final short SIZE = 32; public final long timeMs; //delayed time public final long firstPos; public final long lastPos; public final int num; public final int magic; //no use now, just keep it public Slot(long timeMs, long firstPos, long lastPos) { this.timeMs = timeMs; this.firstPos = firstPos; this.lastPos = lastPos; this.num = 0; this.magic = 0; } public Slot(long timeMs, long firstPos, long lastPos, int num, int magic) { this.timeMs = timeMs; this.firstPos = firstPos; this.lastPos = lastPos; this.num = num; this.magic = magic; } }
apache/rocketmq
store/src/main/java/org/apache/rocketmq/store/timer/Slot.java
179,620
package edu.stanford.nlp.pipeline; import edu.stanford.nlp.ling.CoreAnnotation; import java.util.*; /** * This is an interface for adding annotations to a partially annotated * Annotation. In some ways, it is just a glorified function, except * that it explicitly operates in-place on Annotation objects. Annotators * should be given to an AnnotationPipeline in order to make * annotation pipelines (the whole motivation of this package), and * therefore implementers of this interface should be designed to play * well with other Annotators and in their javadocs they should * explicitly state what annotations they are assuming already exist * in the annotation (like parse, POS tag, etc), what keys they are * expecting them under (see, for instance, the ones in CoreAnnotations), * and what annotations they will add (or modify) and the keys * for them as well. If you would like to look at the code for a * relatively simple Annotator, I recommend NERAnnotator. For a lot * of code you could just add the implements directly, but I recommend * wrapping instead because I believe that it will help to keep the * pipeline code more manageable. * * An Annotator should also provide a description of what it produces and * a description of what it requires to have been produced by using Sets * of requirements. * The StanfordCoreNLP version of the AnnotationPipeline can * enforce requirements, throwing an exception if an annotator does * not have all of its prerequisites met. An Annotator which does not * participate in this system can simply return Collections.emptySet() * for both requires() and requirementsSatisfied(). * * <h2>Properties</h2> * * We extensively use Properties objects to configure each Annotator. * In particular, CoreNLP has most of its properties in an informal * namespace with properties names like "parse.maxlen" to specify that * a property only applies to a parser annotator. There can also be * global properties; they should not have any periods in their names. * Each Annotator knows its own name; we assume these don't collide badly, * though possibly two parsers could share the "parse.*" namespace. * An Annotator should have a constructor that simply takes a Properties * object. At this point, the Annotator should expect to be getting * properties in namespaces. The classes that annotators call (like * a concrete parser, tagger, or whatever) mainly expect properties * not in namespaces. In general the annotator should subset the * passed in properties to keep only global properties and ones in * its own namespace, and then strip the namespace prefix from the * latter properties. * * @author Jenny Finkel */ public interface Annotator { /** * Given an Annotation, perform a task on this Annotation. */ void annotate(Annotation annotation); /** * A block of code called when this annotator unmounts from the * {@link AnnotatorPool}. * By default, nothing is done. */ default void unmount() { } /** * Returns a set of requirements for which tasks this annotator can * provide. For example, the POS annotator will return "pos". */ Set<Class<? extends CoreAnnotation>> requirementsSatisfied(); /** * Returns the set of tasks which this annotator requires in order * to perform. For example, the POS annotator will return * "tokenize", "ssplit". */ Set<Class<? extends CoreAnnotation>> requires(); default Collection<String> exactRequirements() { return null; } /** * These are annotators which StanfordCoreNLP knows how to create. * Add new annotators and/or annotators from other groups here! */ String STANFORD_TOKENIZE = "tokenize"; String STANFORD_CDC_TOKENIZE = "cdc_tokenize"; String STANFORD_CLEAN_XML = "cleanxml"; String STANFORD_SSPLIT = "ssplit"; String STANFORD_MWT = "mwt"; String STANFORD_DOCDATE = "docdate"; String STANFORD_POS = "pos"; String STANFORD_LEMMA = "lemma"; String STANFORD_NER = "ner"; String STANFORD_REGEXNER = "regexner"; String STANFORD_TOKENSREGEX = "tokensregex"; String STANFORD_ENTITY_MENTIONS = "entitymentions"; String STANFORD_GENDER = "gender"; String STANFORD_TRUECASE = "truecase"; String STANFORD_PARSE = "parse"; String STANFORD_DETERMINISTIC_COREF = "dcoref"; String STANFORD_COREF = "coref"; String STANFORD_COREF_MENTION = "coref.mention"; // TODO(jebolton) Merge with entitymention String STANFORD_RELATION = "relation"; String STANFORD_SENTIMENT = "sentiment"; String STANFORD_COLUMN_DATA_CLASSIFIER = "cdc"; String STANFORD_DEPENDENCIES = "depparse"; String STANFORD_NATLOG = "natlog"; String STANFORD_OPENIE = "openie"; String STANFORD_QUOTE = "quote"; String STANFORD_QUOTE_ATTRIBUTION = "quote.attribution"; String STANFORD_UD_FEATURES = "udfeats"; String STANFORD_LINK = "entitylink"; String STANFORD_KBP = "kbp"; /** * A mapping from an annotator to a its default transitive dependencies. * Note that this is not guaranteed to be accurate, as properties set in the annotator * can change the annotator's dependencies; but, it's a reasonable guess if you're using * things out-of-the-box. */ @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") Map<String, Set<String>> DEFAULT_REQUIREMENTS = new HashMap<String, Set<String>>(){{ put(STANFORD_TOKENIZE, new LinkedHashSet<>(Arrays.asList())); put(STANFORD_CDC_TOKENIZE, new LinkedHashSet<>(Arrays.asList())); put(STANFORD_CLEAN_XML, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_SSPLIT, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_MWT, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_DOCDATE, new LinkedHashSet<>(Arrays.asList())); put(STANFORD_POS, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_LEMMA, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS))); put(STANFORD_NER, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA))); put(STANFORD_TOKENSREGEX, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_REGEXNER, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_ENTITY_MENTIONS, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER))); put(STANFORD_GENDER, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER))); put(STANFORD_TRUECASE, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE))); put(STANFORD_PARSE, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS))); put(STANFORD_DETERMINISTIC_COREF, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_PARSE))); put(STANFORD_COREF, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_DEPENDENCIES))); put(STANFORD_COREF_MENTION, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_DEPENDENCIES))); put(STANFORD_RELATION, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_PARSE, STANFORD_DEPENDENCIES))); put(STANFORD_SENTIMENT, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_PARSE))); put(STANFORD_COLUMN_DATA_CLASSIFIER, new LinkedHashSet<>(Arrays.asList())); put(STANFORD_DEPENDENCIES, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS))); put(STANFORD_NATLOG, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_DEPENDENCIES))); put(STANFORD_OPENIE, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_DEPENDENCIES, STANFORD_NATLOG))); put(STANFORD_QUOTE, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_COREF))); put(STANFORD_QUOTE_ATTRIBUTION, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_LEMMA, STANFORD_NER, STANFORD_COREF_MENTION, STANFORD_DEPENDENCIES, STANFORD_QUOTE))); put(STANFORD_UD_FEATURES, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_DEPENDENCIES))); put(STANFORD_LINK, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_DEPENDENCIES, STANFORD_LEMMA, STANFORD_NER, STANFORD_ENTITY_MENTIONS))); // TODO: there are language specific dependencies which we may // want to encode somehow. For example, English KBP needs coref // to function. Spanish KBP doesn't need coref, and in fact, // Spanish coref doesn't even exist. put(STANFORD_KBP, new LinkedHashSet<>(Arrays.asList(STANFORD_TOKENIZE, STANFORD_POS, STANFORD_DEPENDENCIES, STANFORD_LEMMA, STANFORD_NER))); }}; }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/pipeline/Annotator.java
179,623
package com.airbnb.lottie; import androidx.annotation.Nullable; import java.util.Arrays; /** * Contains class to hold the resulting value of an async task or an exception if it failed. * <p> * Either value or exception will be non-null. */ public final class LottieResult<V> { @Nullable private final V value; @Nullable private final Throwable exception; public LottieResult(V value) { this.value = value; exception = null; } public LottieResult(Throwable exception) { this.exception = exception; value = null; } @Nullable public V getValue() { return value; } @Nullable public Throwable getException() { return exception; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof LottieResult)) { return false; } LottieResult<?> that = (LottieResult<?>) o; if (getValue() != null && getValue().equals(that.getValue())) { return true; } if (getException() != null && that.getException() != null) { return getException().toString().equals(getException().toString()); } return false; } @Override public int hashCode() { return Arrays.hashCode(new Object[]{getValue(), getException()}); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieResult.java
179,626
/* * 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.kafka.server.config; import org.apache.kafka.clients.CommonClientConfigs; public class Defaults { /** ********* General Configuration *********/ public static final boolean BROKER_ID_GENERATION_ENABLE = true; public static final int MAX_RESERVED_BROKER_ID = 1000; public static final int BROKER_ID = -1; public static final int NUM_NETWORK_THREADS = 3; public static final int NUM_IO_THREADS = 8; public static final int BACKGROUND_THREADS = 10; public static final int QUEUED_MAX_REQUESTS = 500; public static final int QUEUED_MAX_REQUEST_BYTES = -1; public static final boolean DELETE_TOPIC_ENABLE = true; public static final int REQUEST_TIMEOUT_MS = 30000; public static final long CONNECTION_SETUP_TIMEOUT_MS = CommonClientConfigs.DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MS; public static final long CONNECTION_SETUP_TIMEOUT_MAX_MS = CommonClientConfigs.DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS; /** ********* KRaft mode configs *********/ public static final int EMPTY_NODE_ID = -1; public static final long SERVER_MAX_STARTUP_TIME_MS = Long.MAX_VALUE; public static final int MIGRATION_METADATA_MIN_BATCH_SIZE = 200; /** ********* Authorizer Configuration *********/ public static final String AUTHORIZER_CLASS_NAME = ""; /** ********* Controlled shutdown configuration *********/ public static final int CONTROLLED_SHUTDOWN_MAX_RETRIES = 3; public static final int CONTROLLED_SHUTDOWN_RETRY_BACKOFF_MS = 5000; public static final boolean CONTROLLED_SHUTDOWN_ENABLE = true; /** ********* Fetch Configuration *********/ public static final int MAX_INCREMENTAL_FETCH_SESSION_CACHE_SLOTS = 1000; public static final int FETCH_MAX_BYTES = 55 * 1024 * 1024; /** ********* Request Limit Configuration ***********/ public static final int MAX_REQUEST_PARTITION_SIZE_LIMIT = 2000; /** ********* Delegation Token Configuration *********/ public static final long DELEGATION_TOKEN_MAX_LIFE_TIME_MS = 7 * 24 * 60 * 60 * 1000L; public static final long DELEGATION_TOKEN_EXPIRY_TIME_MS = 24 * 60 * 60 * 1000L; public static final long DELEGATION_TOKEN_EXPIRY_CHECK_INTERVAL_MS = 1 * 60 * 60 * 1000L; }
apache/kafka
server/src/main/java/org/apache/kafka/server/config/Defaults.java
179,627
import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; /** * Slalom * <p> * Converted from BASIC to Java by Aldrin Misquitta (@aldrinm) * * There is a bug in the original version where the data pointer doesn't reset after a race is completed. This causes subsequent races to error at * some future point on line "540 READ Q" */ public class Slalom { private static final int MAX_NUM_GATES = 25; private static final int[] MAX_SPEED = { 14, 18, 26, 29, 18, 25, 28, 32, 29, 20, 29, 29, 25, 21, 26, 29, 20, 21, 20, 18, 26, 25, 33, 31, 22 }; public static void main(String[] args) { var random = new Random(); printIntro(); Scanner scanner = new Scanner(System.in); int numGates = readNumberOfGatesChoice(scanner); printMenu(); MenuChoice menuChoice; do { menuChoice = readMenuOption(scanner); switch (menuChoice) { case INS: printInstructions(); break; case MAX: printApproxMaxSpeeds(numGates); break; case RUN: run(numGates, scanner, random); break; } } while (menuChoice != MenuChoice.RUN); } private static void run(int numGates, Scanner scan, Random random) { int rating = readSkierRating(scan); boolean gameInProgress = true; var medals = new Medals(0, 0, 0); while (gameInProgress) { System.out.println("THE STARTER COUNTS DOWN...5...4...3...2...1...GO!"); System.out.println("YOU'RE OFF!"); int speed = random.nextInt(18 - 9) + 9; float totalTimeTaken = 0; try { totalTimeTaken = runThroughGates(numGates, scan, random, speed); System.out.printf("%nYOU TOOK %.2f SECONDS.%n", totalTimeTaken + random.nextFloat()); medals = evaluateAndUpdateMedals(totalTimeTaken, numGates, rating, medals); } catch (WipedOutOrSnaggedAFlag | DisqualifiedException e) { //end of this race! Print time taken and stop System.out.printf("%nYOU TOOK %.2f SECONDS.%n", totalTimeTaken + random.nextFloat()); } gameInProgress = readRaceAgainChoice(scan); } System.out.println("THANKS FOR THE RACE"); if (medals.getGold() >= 1) System.out.printf("GOLD MEDALS: %d%n", medals.getGold()); if (medals.getSilver() >= 1) System.out.printf("SILVER MEDALS: %d%n", medals.getSilver()); if (medals.getBronze() >= 1) System.out.printf("BRONZE MEDALS: %d%n", medals.getBronze()); } private static Medals evaluateAndUpdateMedals(float totalTimeTaken, int numGates, int rating, Medals medals) { var m = totalTimeTaken; m = m / numGates; int goldMedals = medals.getGold(); int silverMedals = medals.getSilver(); int bronzeMedals = medals.getBronze(); if (m < 1.5 - (rating * 0.1)) { System.out.println("YOU WON A GOLD MEDAL!"); goldMedals++; } else if (m < 2.9 - rating * 0.1) { System.out.println("YOU WON A SILVER MEDAL"); silverMedals++; } else if (m < 4.4 - rating * 0.01) { System.out.println("YOU WON A BRONZE MEDAL"); bronzeMedals++; } return new Medals(goldMedals, silverMedals, bronzeMedals); } /** * @return the total time taken through all the gates. */ private static float runThroughGates(int numGates, Scanner scan, Random random, int speed) throws DisqualifiedException, WipedOutOrSnaggedAFlag { float totalTimeTaken = 0.0f; for (int i = 0; i < numGates; i++) { var gateNum = i + 1; boolean stillInRace = true; boolean gateCompleted = false; while (!gateCompleted) { System.out.printf("%nHERE COMES GATE # %d:%n", gateNum); printSpeed(speed); var tmpSpeed = speed; int chosenOption = readOption(scan); switch (chosenOption) { case 0: //how long printHowLong(totalTimeTaken, random); break; case 1: //speed up a lot speed = speed + random.nextInt(10 - 5) + 5; break; case 2: //speed up a little speed = speed + random.nextInt(5 - 3) + 3; break; case 3: //speed up a teensy speed = speed + random.nextInt(4 - 1) + 1; break; case 4: //keep going at the same speed break; case 5: //check a teensy speed = speed - random.nextInt(4 - 1) + 1; break; case 6: //check a little speed = speed - random.nextInt(5 - 3) + 3; break; case 7: //check a lot speed = speed - random.nextInt(10 - 5) + 5; break; case 8: //cheat System.out.println("***CHEAT"); if (random.nextFloat() < 0.7) { System.out.println("AN OFFICIAL CAUGHT YOU!"); stillInRace = false; } else { System.out.println("YOU MADE IT!"); totalTimeTaken = totalTimeTaken + 1.5f; } break; } if (stillInRace) { printSpeed(speed); stillInRace = checkAndProcessIfOverMaxSpeed(random, speed, MAX_SPEED[i]); if (!stillInRace) throw new WipedOutOrSnaggedAFlag(); } else { throw new DisqualifiedException();//we've been dis-qualified } if (speed < 7) { System.out.println("LET'S BE REALISTIC, OK? LET'S GO BACK AND TRY AGAIN..."); speed = tmpSpeed; gateCompleted = false; } else { totalTimeTaken = totalTimeTaken + (MAX_SPEED[i] - speed + 1); if (speed > MAX_SPEED[i]) { totalTimeTaken = totalTimeTaken + 0.5f; } gateCompleted = true; } } } return totalTimeTaken; } private static boolean checkAndProcessIfOverMaxSpeed(Random random, int speed, int maxSpeed) { boolean stillInRace = true; if (speed > maxSpeed) { if (random.nextFloat() >= (speed - maxSpeed) * 0.1 + 0.2) { System.out.println("YOU WENT OVER THE MAXIMUM SPEED AND MADE IT!"); } else { System.out.print("YOU WENT OVER THE MAXIMUM SPEED AND "); if (random.nextBoolean()) { System.out.println("WIPED OUT!"); } else { System.out.println("SNAGGED A FLAG!"); } stillInRace = false; } } else if (speed > maxSpeed - 1) { System.out.println("CLOSE ONE!"); } return stillInRace; } private static boolean readRaceAgainChoice(Scanner scan) { System.out.print("\nDO YOU WANT TO RACE AGAIN? "); String raceAgain = ""; final String YES = "YES"; final String NO = "NO"; while (!YES.equals(raceAgain) && !NO.equals(raceAgain)) { raceAgain = scan.nextLine(); if (!(YES.equals(raceAgain) || NO.equals(raceAgain))) { System.out.println("PLEASE TYPE 'YES' OR 'NO'"); } } return raceAgain.equals(YES); } private static void printSpeed(int speed) { System.out.printf("%3d M.P.H.%n", speed); } private static void printHowLong(float t, Random random) { System.out.printf("YOU'VE TAKEN %.2f SECONDS.%n", t + random.nextFloat()); } private static int readOption(Scanner scan) { Integer option = null; while (option == null) { System.out.print("OPTION? "); try { option = scan.nextInt(); } catch (InputMismatchException ex) { System.out.println("!NUMBER EXPECTED - RETRY INPUT LINE\n"); } scan.nextLine(); if (option != null && (option > 8 || option < 0)) { System.out.println("WHAT?"); option = null; } } return option; } private static int readSkierRating(Scanner scan) { int rating = 0; while (rating < 1 || rating > 3) { System.out.print("RATE YOURSELF AS A SKIER, (1=WORST, 3=BEST)? "); try { rating = scan.nextInt(); if (rating < 1 || rating > 3) { System.out.println("THE BOUNDS ARE 1-3"); } } catch (InputMismatchException ex) { System.out.println("!NUMBER EXPECTED - RETRY INPUT LINE\n"); } scan.nextLine(); } return rating; } private static void printApproxMaxSpeeds(int numGates) { System.out.println("GATE MAX"); System.out.println(" # M.P.H."); System.out.println("---------"); for (int i = 0; i < numGates; i++) { System.out.println((i+1) + " " + MAX_SPEED[i]); } } private static void printInstructions() { System.out.println("\n*** SLALOM: THIS IS THE 1976 WINTER OLYMPIC GIANT SLALOM. YOU ARE"); System.out.println(" THE AMERICAN TEAM'S ONLY HOPE OF A GOLD MEDAL."); System.out.println(); System.out.println(" 0 -- TYPE THIS IS YOU WANT TO SEE HOW LONG YOU'VE TAKEN."); System.out.println(" 1 -- TYPE THIS IF YOU WANT TO SPEED UP A LOT."); System.out.println(" 2 -- TYPE THIS IF YOU WANT TO SPEED UP A LITTLE."); System.out.println(" 3 -- TYPE THIS IF YOU WANT TO SPEED UP A TEENSY."); System.out.println(" 4 -- TYPE THIS IF YOU WANT TO KEEP GOING THE SAME SPEED."); System.out.println(" 5 -- TYPE THIS IF YOU WANT TO CHECK A TEENSY."); System.out.println(" 6 -- TYPE THIS IF YOU WANT TO CHECK A LITTLE."); System.out.println(" 7 -- TYPE THIS IF YOU WANT TO CHECK A LOT."); System.out.println(" 8 -- TYPE THIS IF YOU WANT TO CHEAT AND TRY TO SKIP A GATE."); System.out.println(); System.out.println(" THE PLACE TO USE THESE OPTIONS IS WHEN THE COMPUTER ASKS:"); System.out.println(); System.out.println("OPTION?"); System.out.println(); System.out.println(" GOOD LUCK!"); } private static MenuChoice readMenuOption(Scanner scan) { System.out.print("COMMAND--? "); MenuChoice menuChoice = null; while (menuChoice == null) { String choice = scan.next(); if (Arrays.stream(MenuChoice.values()).anyMatch(a -> a.name().equals(choice))) { menuChoice = MenuChoice.valueOf(choice); } else { System.out.print("\""+ choice + "\" IS AN ILLEGAL COMMAND--RETRY? "); } scan.nextLine(); } return menuChoice; } private static void printMenu() { System.out.println("TYPE INS FOR INSTRUCTIONS"); System.out.println("TYPE MAX FOR APPROXIMATE MAXIMUM SPEEDS"); System.out.println("TYPE RUN FOR THE BEGINNING OF THE RACE"); } private static int readNumberOfGatesChoice(Scanner scan) { int numGates = 0; while (numGates < 1) { System.out.print("HOW MANY GATES DOES THIS COURSE HAVE (1 TO 25)? "); numGates = scan.nextInt(); if (numGates > MAX_NUM_GATES) { System.out.println(MAX_NUM_GATES + " IS THE LIMIT."); numGates = MAX_NUM_GATES; } } return numGates; } private static void printIntro() { System.out.println(" SLALOM"); System.out.println(" CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n"); } private enum MenuChoice { INS, MAX, RUN } private static class DisqualifiedException extends Exception { } private static class WipedOutOrSnaggedAFlag extends Exception { } private static class Medals { private int gold = 0; private int silver = 0; private int bronze = 0; public Medals(int gold, int silver, int bronze) { this.gold = gold; this.silver = silver; this.bronze = bronze; } public int getGold() { return gold; } public int getSilver() { return silver; } public int getBronze() { return bronze; } } }
coding-horror/basic-computer-games
79_Slalom/java/Slalom.java
179,630
package com.airbnb.lottie; import androidx.annotation.NonNull; /** * Class for initializing the library with custom config */ public class Lottie { private Lottie() { } /** * Initialize Lottie with global configuration. * * @see LottieConfig.Builder */ public static void initialize(@NonNull final LottieConfig lottieConfig) { L.setFetcher(lottieConfig.networkFetcher); L.setCacheProvider(lottieConfig.cacheProvider); L.setTraceEnabled(lottieConfig.enableSystraceMarkers); L.setNetworkCacheEnabled(lottieConfig.enableNetworkCache); L.setDisablePathInterpolatorCache(lottieConfig.disablePathInterpolatorCache); L.setDefaultAsyncUpdates(lottieConfig.defaultAsyncUpdates); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/Lottie.java
179,632
package edu.stanford.nlp.trees; import edu.stanford.nlp.ling.*; import edu.stanford.nlp.process.PTBTokenizer; import edu.stanford.nlp.trees.international.pennchinese.ChineseEnglishWordMap; import edu.stanford.nlp.util.*; import edu.stanford.nlp.util.XMLUtils; import edu.stanford.nlp.util.logging.Redwood; import java.io.*; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; /** * A class for customizing the print method(s) for a * {@code edu.stanford.nlp.trees.Tree} as the output of the * parser. This class supports printing in multiple ways and altering * behavior via properties specified at construction. * * @author Roger Levy * @author Christopher Manning * @author Galen Andrew */ public class TreePrint { /** A logger for this class */ private static final Redwood.RedwoodChannels log = Redwood.channels(TreePrint.class); // TODO: Add support for makeCopulaHead as an outputFormatOption here. public static final String rootLabelOnlyFormat = "rootSymbolOnly"; public static final String headMark = "=H"; /** The legal output tree formats. */ public static final String[] outputTreeFormats = { "penn", "oneline", rootLabelOnlyFormat, "words", "wordsAndTags", "dependencies", "typedDependencies", "typedDependenciesCollapsed", "latexTree", "xmlTree", "collocations", "semanticGraph", "conllStyleDependencies", "conll2007" }; private final LinkedHashMap<String, String> formats; private final LinkedHashMap<String, String> options; private final boolean markHeadNodes; // = false; private final boolean lexicalize; // = false; private final boolean removeEmpty; private final boolean ptb2text; private final boolean transChinese; // = false; private final boolean basicDependencies; private final boolean collapsedDependencies; private final boolean nonCollapsedDependencies; private final boolean nonCollapsedDependenciesSeparated; private final boolean CCPropagatedDependencies; private final boolean treeDependencies; private final boolean includeTags; private final HeadFinder hf; private final TreebankLanguagePack tlp; private final WordStemmer stemmer; private final Predicate<Dependency<Label, Label, Object>> dependencyFilter; private final Predicate<Dependency<Label, Label, Object>> dependencyWordFilter; private final GrammaticalStructureFactory gsf; /** Pool use of one WordNetConnection. I don't really know if * Dan Bikel's WordNet code is thread safe, but it definitely doesn't * close its files, and too much of our code makes TreePrint objects and * then drops them on the floor, and so we run out of file handles. * That is, if this variable isn't static, code crashes. * Maybe we should change this code to use jwnl(x)? * CDM July 2006. */ private static WordNetConnection wnc; /** This PrintWriter is used iff the user doesn't pass one in to a * call to printTree(). It prints to System.out. */ private final PrintWriter pw = new PrintWriter(System.out, true); /** Construct a new TreePrint that will print the given formats. * Warning! This is the anglocentric constructor. * It will work correctly only for English. * * @param formats The formats to print the tree in. */ public TreePrint(String formats) { this(formats, "", new PennTreebankLanguagePack()); } /** Make a TreePrint instance with no options specified. */ public TreePrint(String formats, TreebankLanguagePack tlp) { this(formats, "", tlp); } /** Make a TreePrint instance. This one uses the default tlp headFinder. */ public TreePrint(String formats, String options, TreebankLanguagePack tlp) { this(formats, options, tlp, tlp.headFinder(), tlp.typedDependencyHeadFinder()); } /** * Make a TreePrint instance. * * @param formatString A comma separated list of ways to print each Tree. * For instance, "penn" or "words,typedDependencies". * Known formats are: oneline, penn, latexTree, xmlTree, words, * wordsAndTags, rootSymbolOnly, dependencies, * typedDependencies, typedDependenciesCollapsed, * collocations, semanticGraph, conllStyleDependencies, * conll2007. The last two are both tab-separated values * formats. The latter has a lot more columns filled with * underscores. All of them print a blank line after * the output except for oneline. oneline is also not * meaningful in XML output (it is ignored: use penn instead). * (Use of typedDependenciesCollapsed is deprecated. It * works but we recommend instead selecting a type of * dependencies using the optionsString argument. Note in * particular that typedDependenciesCollapsed does not do * CC propagation, which we generally recommend.) * @param optionsString Options that additionally specify how trees are to * be printed (for instance, whether stemming should be done). * Known options are: {@code stem, lexicalize, markHeadNodes, * xml, removeTopBracket, transChinese, * includePunctuationDependencies, basicDependencies, treeDependencies, * CCPropagatedDependencies, collapsedDependencies, nonCollapsedDependencies, * nonCollapsedDependenciesSeparated, includeTags}. * @param tlp The TreebankLanguagePack used to do things like delete * or ignore punctuation in output * @param hf The HeadFinder used in printing output */ public TreePrint(String formatString, String optionsString, TreebankLanguagePack tlp, HeadFinder hf, HeadFinder typedDependencyHF) { formats = StringUtils.stringToPropertiesMap(formatString); options = StringUtils.stringToPropertiesMap(optionsString); List<String> okOutputs = Arrays.asList(outputTreeFormats); for (String format : formats.keySet()) { if ( ! okOutputs.contains(format)) { throw new RuntimeException("Error: output tree format " + format + " not supported. Known formats are: " + okOutputs); } } this.hf = hf; this.tlp = tlp; boolean includePunctuationDependencies; includePunctuationDependencies = propertyToBoolean(this.options, "includePunctuationDependencies"); boolean generateOriginalDependencies = tlp.generateOriginalDependencies(); Predicate<String> puncFilter; if (includePunctuationDependencies) { dependencyFilter = Filters.acceptFilter(); dependencyWordFilter = Filters.acceptFilter(); puncFilter = Filters.acceptFilter(); } else { dependencyFilter = new Dependencies.DependentPuncTagRejectFilter<>(tlp.punctuationTagRejectFilter()); dependencyWordFilter = new Dependencies.DependentPuncWordRejectFilter<>(tlp.punctuationWordRejectFilter()); //Universal dependencies filter punction by tags puncFilter = generateOriginalDependencies ? tlp.punctuationWordRejectFilter() : tlp.punctuationTagRejectFilter(); } if (propertyToBoolean(this.options, "stem")) { stemmer = new WordStemmer(); } else { stemmer = null; } if (formats.containsKey("typedDependenciesCollapsed") || formats.containsKey("typedDependencies") || (formats.containsKey("conll2007") && tlp.supportsGrammaticalStructures())) { gsf = tlp.grammaticalStructureFactory(puncFilter, typedDependencyHF); } else { gsf = null; } lexicalize = propertyToBoolean(this.options, "lexicalize"); markHeadNodes = propertyToBoolean(this.options, "markHeadNodes"); transChinese = propertyToBoolean(this.options, "transChinese"); ptb2text = propertyToBoolean(this.options, "ptb2text"); removeEmpty = propertyToBoolean(this.options, "noempty") || ptb2text; basicDependencies = propertyToBoolean(this.options, "basicDependencies"); collapsedDependencies = propertyToBoolean(this.options, "collapsedDependencies"); nonCollapsedDependencies = propertyToBoolean(this.options, "nonCollapsedDependencies"); nonCollapsedDependenciesSeparated = propertyToBoolean(this.options, "nonCollapsedDependenciesSeparated"); treeDependencies = propertyToBoolean(this.options, "treeDependencies"); includeTags = propertyToBoolean(this.options, "includeTags"); // if no option format for the dependencies is specified, CCPropagated is the default if ( ! basicDependencies && ! collapsedDependencies && ! nonCollapsedDependencies && ! nonCollapsedDependenciesSeparated && ! treeDependencies) { CCPropagatedDependencies = true; } else { CCPropagatedDependencies = propertyToBoolean(this.options, "CCPropagatedDependencies"); } } private static boolean propertyToBoolean(LinkedHashMap<String, String> prop, String key) { return Boolean.parseBoolean(prop.get(key)); } /** * Prints the tree to the default PrintWriter. * @param t The tree to display */ public void printTree(Tree t) { printTree(t, pw); } /** * Prints the tree, with an empty ID. * @param t The tree to display * @param pw The PrintWriter to print it to */ public void printTree(final Tree t, PrintWriter pw) { printTree(t, "", pw); } /** * Prints the tree according to the options specified for this instance. * If the tree {@code t} is {@code null}, then the code prints * a line indicating a skipped tree. Under the XML option this is * an {@code s} element with the {@code skipped} attribute having * value {@code true}, and, otherwise, it is the token * {@code SENTENCE_SKIPPED_OR_UNPARSABLE}. * * @param t The tree to display * @param id A name for this sentence * @param pw Where to display the tree */ public void printTree(final Tree t, final String id, final PrintWriter pw) { final boolean inXml = propertyToBoolean(options, "xml"); if (t == null) { // Parsing didn't succeed. if (inXml) { pw.print("<s"); if ( ! StringUtils.isNullOrEmpty(id)) { pw.print(" id=\"" + XMLUtils.escapeXML(id) + '\"'); } pw.println(" skipped=\"true\"/>"); pw.println(); } else { pw.println("SENTENCE_SKIPPED_OR_UNPARSABLE"); } } else { if (inXml) { pw.print("<s"); if ( ! StringUtils.isNullOrEmpty(id)) { pw.print(" id=\"" + XMLUtils.escapeXML(id) + '\"'); } pw.println(">"); } printTreeInternal(t, pw, inXml); if (inXml) { pw.println("</s>"); pw.println(); } } } /** * Prints the trees according to the options specified for this instance. * If the tree {@code t} is {@code null}, then the code prints * a line indicating a skipped tree. Under the XML option this is * an {@code s} element with the {@code skipped} attribute having * value {@code true}, and, otherwise, it is the token * {@code SENTENCE_SKIPPED_OR_UNPARSABLE}. * * @param trees The list of trees to display * @param id A name for this sentence * @param pw Where to dislay the tree */ public void printTrees(final List<ScoredObject<Tree>> trees, final String id, final PrintWriter pw) { final boolean inXml = propertyToBoolean(options, "xml"); int ii = 0; // incremented before used, so first tree is numbered 1 for (ScoredObject<Tree> tp : trees) { ii++; Tree t = tp.object(); double score = tp.score(); if (t == null) { // Parsing didn't succeed. if (inXml) { pw.print("<s"); if ( ! StringUtils.isNullOrEmpty(id)) { pw.print(" id=\"" + XMLUtils.escapeXML(id) + '\"'); } pw.print(" n=\""); pw.print(ii); pw.print('\"'); pw.print(" score=\"" + score + '\"'); pw.println(" skipped=\"true\"/>"); pw.println(); } else { pw.println("SENTENCE_SKIPPED_OR_UNPARSABLE Parse #" + ii + " with score " + score); } } else { if (inXml) { pw.print("<s"); if ( ! StringUtils.isNullOrEmpty(id)) { pw.print(" id=\""); pw.print(XMLUtils.escapeXML(id)); pw.print('\"'); } pw.print(" n=\""); pw.print(ii); pw.print('\"'); pw.print(" score=\""); pw.print(score); pw.print('\"'); pw.println(">"); } else { pw.print("# Parse "); pw.print(ii); pw.print(" with score "); pw.println(score); } printTreeInternal(t, pw, inXml); if (inXml) { pw.println("</s>"); pw.println(); } } } } /** Print the internal part of a tree having already identified it. * The ID and outer XML element is printed wrapping this method, but none * of the internal content. * * @param t The tree to print. Now known to be non-null * @param pw Where to print it to * @param inXml Whether to use XML style printing */ private void printTreeInternal(final Tree t, final PrintWriter pw, final boolean inXml) { Tree outputTree = t; if (formats.containsKey("conll2007") || removeEmpty) { outputTree = outputTree.prune(new BobChrisTreeNormalizer.EmptyFilter()); } if (formats.containsKey("words")) { if (inXml) { ArrayList<Label> sentUnstemmed = outputTree.yield(); pw.println(" <words>"); int i = 1; for (Label w : sentUnstemmed) { pw.println(" <word ind=\"" + i + "\">" + XMLUtils.escapeXML(w.value()) + "</word>"); i++; } pw.println(" </words>"); } else { String sent = SentenceUtils.listToString(outputTree.yield(), false); if(ptb2text) { pw.println(PTBTokenizer.ptb2Text(sent)); } else { pw.println(sent); pw.println(); } } } if (propertyToBoolean(options, "removeTopBracket")) { String s = outputTree.label().value(); if (tlp.isStartSymbol(s)) { if (outputTree.isUnaryRewrite()) { outputTree = outputTree.firstChild(); } else { // It's not quite clear what to do if the tree isn't unary at the top // but we then don't strip the ROOT symbol, since that seems closer // than losing part of the tree altogether.... log.info("TreePrint: can't remove top bracket: not unary"); } } // Note that TreePrint is also called on dependency trees that have // a word as the root node, and so we don't error if there isn't // the root symbol at the top; rather we silently assume that this // is a dependency tree!! } if (stemmer != null) { stemmer.visitTree(outputTree); } if (lexicalize) { outputTree = Trees.lexicalize(outputTree, hf); Function<Tree, Tree> a = TreeFunctions.getLabeledToDescriptiveCoreLabelTreeFunction(); outputTree = a.apply(outputTree); } if (formats.containsKey("collocations")) { outputTree = getCollocationProcessedTree(outputTree, hf); } if (!lexicalize) { // delexicalize the output tree Function<Tree, Tree> a = TreeFunctions.getLabeledTreeToStringLabeledTreeFunction(); outputTree = a.apply(outputTree); } Tree outputPSTree = outputTree; // variant with head-marking, translations if (markHeadNodes) { outputPSTree = markHeadNodes(outputPSTree); } if (transChinese) { TreeTransformer tt = t1 -> { t1 = t1.treeSkeletonCopy(); for (Tree subtree : t1) { if (subtree.isLeaf()) { Label oldLabel = subtree.label(); String translation = ChineseEnglishWordMap.getInstance().getFirstTranslation(oldLabel.value()); if (translation == null) translation = "[UNK]"; Label newLabel = new StringLabel(oldLabel.value() + ':' + translation); subtree.setLabel(newLabel); } } return t1; }; outputPSTree = tt.transformTree(outputPSTree); } if (propertyToBoolean(options, "xml")) { if (formats.containsKey("wordsAndTags")) { ArrayList<TaggedWord> sent = outputTree.taggedYield(); pw.println(" <words pos=\"true\">"); int i = 1; for (TaggedWord tw : sent) { pw.println(" <word ind=\"" + i + "\" pos=\"" + XMLUtils.escapeXML(tw.tag()) + "\">" + XMLUtils.escapeXML(tw.word()) + "</word>"); i++; } pw.println(" </words>"); } if (formats.containsKey("penn")) { pw.println(" <tree style=\"penn\">"); StringWriter sw = new StringWriter(); PrintWriter psw = new PrintWriter(sw); outputPSTree.pennPrint(psw); pw.print(XMLUtils.escapeXML(sw.toString())); pw.println(" </tree>"); } if (formats.containsKey("latexTree")) { pw.println(" <tree style=\"latexTrees\">"); pw.println(".["); StringWriter sw = new StringWriter(); PrintWriter psw = new PrintWriter(sw); outputTree.indentedListPrint(psw,false); pw.print(XMLUtils.escapeXML(sw.toString())); pw.println(".]"); pw.println(" </tree>"); } if (formats.containsKey("xmlTree")) { pw.println("<tree style=\"xml\">"); outputTree.indentedXMLPrint(pw,false); pw.println("</tree>"); } if (formats.containsKey("dependencies")) { Tree indexedTree = outputTree.deepCopy(outputTree.treeFactory(), CoreLabel.factory()); indexedTree.indexLeaves(); Set<Dependency<Label, Label, Object>> depsSet = indexedTree.mapDependencies(dependencyWordFilter, hf); List<Dependency<Label, Label, Object>> sortedDeps = new ArrayList<>(depsSet); sortedDeps.sort(Dependencies.dependencyIndexComparator()); pw.println("<dependencies style=\"untyped\">"); for (Dependency<Label, Label, Object> d : sortedDeps) { pw.println(d.toString("xml")); } pw.println("</dependencies>"); } if (formats.containsKey("conll2007") || formats.containsKey("conllStyleDependencies")) { log.info("The \"conll2007\" and \"conllStyleDependencies\" formats are ignored in xml."); } if (formats.containsKey("typedDependencies")) { GrammaticalStructure gs = gsf.newGrammaticalStructure(outputTree); if (basicDependencies) { print(gs.typedDependencies(), "xml", includeTags, pw); } if (nonCollapsedDependencies || nonCollapsedDependenciesSeparated) { print(gs.allTypedDependencies(), "xml", includeTags, pw); } if (collapsedDependencies) { print(gs.typedDependenciesCollapsed(GrammaticalStructure.Extras.MAXIMAL), "xml", includeTags, pw); } if (CCPropagatedDependencies) { print(gs.typedDependenciesCCprocessed(), "xml", includeTags, pw); } if(treeDependencies) { print(gs.typedDependenciesCollapsedTree(), "xml", includeTags, pw); } } if (formats.containsKey("typedDependenciesCollapsed")) { GrammaticalStructure gs = gsf.newGrammaticalStructure(outputTree); print(gs.typedDependenciesCCprocessed(), "xml", includeTags, pw); } // This makes parser require jgrapht. Bad. // if (formats.containsKey("semanticGraph")) { // SemanticGraph sg = SemanticGraph.makeFromTree(outputTree, true, false, false, null); // pw.println(sg.toFormattedString()); // } } else { // non-XML printing if (formats.containsKey("wordsAndTags")) { pw.println(SentenceUtils.listToString(outputTree.taggedYield(), false)); pw.println(); } if (formats.containsKey("oneline")) { pw.println(outputPSTree); } if (formats.containsKey("penn")) { outputPSTree.pennPrint(pw); pw.println(); } if (formats.containsKey(rootLabelOnlyFormat)) { pw.println(outputTree.label().value()); } if (formats.containsKey("latexTree")) { pw.println(".["); outputTree.indentedListPrint(pw,false); pw.println(".]"); } if (formats.containsKey("xmlTree")) { outputTree.indentedXMLPrint(pw,false); } if (formats.containsKey("dependencies")) { Tree indexedTree = outputTree.deepCopy(outputTree.treeFactory()); indexedTree.indexLeaves(); List<Dependency<Label, Label, Object>> sortedDeps = getSortedDeps(indexedTree, dependencyWordFilter); for (Dependency<Label, Label, Object> d : sortedDeps) { pw.println(d.toString("predicate")); } pw.println(); } if (formats.containsKey("conll2007")) { // CoNLL-X 2007 format: http://ilk.uvt.nl/conll/#dataformat // wsg: This code should be retained (and not subsumed into EnglishGrammaticalStructure) so // that dependencies for other languages can be printed. // wsg2011: This code currently ignores the dependency label since the present implementation // of mapDependencies() returns UnnamedDependency objects. // TODO: if there is a GrammaticalStructureFactory available, use that instead of mapDependencies Tree it = outputTree.deepCopy(outputTree.treeFactory(), CoreLabel.factory()); it.indexLeaves(); List<CoreLabel> tagged = it.taggedLabeledYield(); List<Dependency<Label, Label, Object>> sortedDeps = getSortedDeps(it, Filters.acceptFilter()); for (Dependency<Label, Label, Object> d : sortedDeps) { if (!dependencyFilter.test(d)) { continue; } if (!(d.dependent() instanceof HasIndex) || !(d.governor() instanceof HasIndex)) { throw new IllegalArgumentException("Expected labels to have indices"); } HasIndex dep = (HasIndex) d.dependent(); HasIndex gov = (HasIndex) d.governor(); int depi = dep.index(); int govi = gov.index(); CoreLabel w = tagged.get(depi - 1); // Used for both course and fine POS tag fields String tag = PTBTokenizer.ptbToken2Text(w.tag()); String word = PTBTokenizer.ptbToken2Text(w.word()); String lemma = "_"; String feats = "_"; String pHead = "_"; String pDepRel = "_"; String depRel; if (d.name() != null) { depRel = d.name().toString(); } else { depRel = (govi == 0) ? "ROOT" : "NULL"; } // The 2007 format has 10 fields pw.printf("%d\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s%n", depi, word, lemma, tag, tag, feats, govi, depRel, pHead, pDepRel); } pw.println(); } if (formats.containsKey("conllStyleDependencies")) { // TODO: Rewrite this to output StanfordDependencies using EnglishGrammaticalStructure code BobChrisTreeNormalizer tn = new BobChrisTreeNormalizer(); Tree indexedTree = outputTree.deepCopy(outputTree.treeFactory(), CoreLabel.factory()); // TODO: Can the below for-loop be deleted now? (Now that the HeadFinder knows about NML.) for (Tree node : indexedTree) { if (node.label().value().startsWith("NML")) { node.label().setValue("NP"); } } indexedTree = tn.normalizeWholeTree(indexedTree, outputTree.treeFactory()); indexedTree.indexLeaves(); Set<Dependency<Label, Label, Object>> depsSet = null; boolean failed = false; try { depsSet = indexedTree.mapDependencies(dependencyFilter, hf); } catch (Exception e) { failed = true; } if (failed) { log.info("failed: "); log.info(t); log.info(); } else { Map<Integer,Integer> deps = Generics.newHashMap(); for (Dependency<Label, Label, Object> dep : depsSet) { CoreLabel child = (CoreLabel)dep.dependent(); CoreLabel parent = (CoreLabel)dep.governor(); Integer childIndex = child.get(CoreAnnotations.IndexAnnotation.class); Integer parentIndex = parent.get(CoreAnnotations.IndexAnnotation.class); // log.info(childIndex+"\t"+parentIndex); deps.put(childIndex, parentIndex); } boolean foundRoot = false; int index = 1; for (Tree node : indexedTree.getLeaves()) { String word = node.label().value(); String tag = node.parent(indexedTree).label().value(); int parent = 0; if (deps.containsKey(index)) { parent = deps.get(index); } else { if (foundRoot) { throw new RuntimeException(); } foundRoot = true; } pw.println(index + '\t' + word + '\t' + tag + '\t' + parent); index++; } pw.println(); } } if (formats.containsKey("typedDependencies")) { GrammaticalStructure gs = gsf.newGrammaticalStructure(outputTree); if (basicDependencies) { print(gs.typedDependencies(), includeTags, pw); } if (nonCollapsedDependencies) { print(gs.allTypedDependencies(), includeTags, pw); } if (nonCollapsedDependenciesSeparated) { print(gs.allTypedDependencies(), "separator", includeTags, pw); } if (collapsedDependencies) { print(gs.typedDependenciesCollapsed(GrammaticalStructure.Extras.MAXIMAL), includeTags, pw); } if (CCPropagatedDependencies) { print(gs.typedDependenciesCCprocessed(), includeTags, pw); } if (treeDependencies) { print(gs.typedDependenciesCollapsedTree(), includeTags, pw); } } if (formats.containsKey("typedDependenciesCollapsed")) { GrammaticalStructure gs = gsf.newGrammaticalStructure(outputTree); print(gs.typedDependenciesCCprocessed(), includeTags, pw); } // This makes parser require jgrapht. Bad // if (formats.containsKey("semanticGraph")) { // SemanticGraph sg = SemanticGraph.makeFromTree(outputTree, true, false, false, null); // pw.println(sg.toFormattedString()); // } } // flush to make sure we see all output pw.flush(); } private List<Dependency<Label, Label, Object>> getSortedDeps(Tree tree, Predicate<Dependency<Label, Label, Object>> filter) { if (gsf != null) { GrammaticalStructure gs = gsf.newGrammaticalStructure(tree); Collection<TypedDependency> deps = gs.typedDependencies(GrammaticalStructure.Extras.NONE); List<Dependency<Label, Label, Object>> sortedDeps = new ArrayList<>(); for (TypedDependency dep : deps) { sortedDeps.add(new NamedDependency(dep.gov(), dep.dep(), dep.reln().toString())); } sortedDeps.sort(Dependencies.dependencyIndexComparator()); return sortedDeps; } else { Set<Dependency<Label, Label, Object>> depsSet = tree.mapDependencies(filter, hf, "root"); List<Dependency<Label, Label, Object>> sortedDeps = new ArrayList<>(depsSet); sortedDeps.sort(Dependencies.dependencyIndexComparator()); return sortedDeps; } } /** For the input tree, collapse any collocations in it that exist in * WordNet and are contiguous in the tree into a single node. * A single static Wordnet connection is used by all instances of this * class. Reflection to check that a Wordnet connection exists. Otherwise * we print an error and do nothing. * * @param tree The input tree. NOTE: This tree is mangled by this method * @param hf The head finder to use * @return The collocation collapsed tree */ private static synchronized Tree getCollocationProcessedTree(Tree tree, HeadFinder hf) { if (wnc == null) { try { Class<?> cl = Class.forName("edu.stanford.nlp.trees.WordNetInstance"); wnc = (WordNetConnection) cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { log.info("Couldn't open WordNet Connection. Aborting collocation detection."); log.info(e); wnc = null; } } if (wnc != null) { CollocationFinder cf = new CollocationFinder(tree, wnc, hf); tree = cf.getMangledTree(); } else { log.error("WordNetConnection unavailable for collocations."); } return tree; } public void printHeader(PrintWriter pw, String charset) { if (propertyToBoolean(options, "xml")) { pw.println("<?xml version=\"1.0\" encoding=\"" + charset + "\"?>"); pw.println("<corpus>"); } } public void printFooter(PrintWriter pw) { if (propertyToBoolean(options, "xml")) { pw.println("</corpus>"); } } public Tree markHeadNodes(Tree t) { return markHeadNodes(t, null); } private Tree markHeadNodes(Tree t, Tree head) { if (t.isLeaf()) { return t; // don't worry about head-marking leaves } Label newLabel; if (t == head) { newLabel = headMark(t.label()); } else { newLabel = t.label(); } Tree newHead = hf.determineHead(t); return t.treeFactory().newTreeNode(newLabel, Arrays.asList(headMarkChildren(t, newHead))); } private static Label headMark(Label l) { Label l1 = l.labelFactory().newLabel(l); l1.setValue(l1.value() + headMark); return l1; } private Tree[] headMarkChildren(Tree t, Tree head) { Tree[] kids = t.children(); Tree[] newKids = new Tree[kids.length]; for (int i = 0, n = kids.length; i < n; i++) { newKids[i] = markHeadNodes(kids[i], head); } return newKids; } /** This provides a simple main method for calling TreePrint. * Flags supported are: * <ol> * <li> -format format (like -outputFormat of parser, default "penn") * <li> -options options (like -outputFormatOptions of parser, default "") * <li> -tLP class (the TreebankLanguagePack, default "edu.stanford.nlp.tree.PennTreebankLanguagePack") * <li> -hf class (the HeadFinder, default, the one in the class specified by -tLP) * <li> -useTLPTreeReader (use the treeReaderFactory() inside * the -tLP class; otherwise a PennTreeReader with no normalization is used) * </ol> * The single argument should be a file containing Trees in the format that is either * Penn Treebank s-expressions or as specified by -useTLPTreeReader and the -tLP class, * or if there is no such argument, trees are read from stdin and the program runs as a * filter. * * @param args Command line arguments, as above. */ public static void main(String[] args) { String format = "penn"; String options = ""; String tlpName = "edu.stanford.nlp.trees.PennTreebankLanguagePack"; String hfName = null; Map<String,Integer> flagMap = Generics.newHashMap(); flagMap.put("-format", 1); flagMap.put("-options", 1); flagMap.put("-tLP", 1); flagMap.put("-hf", 1); Map<String,String[]> argsMap = StringUtils.argsToMap(args,flagMap); args = argsMap.get(null); if (argsMap.containsKey("-format")) { format = argsMap.get("-format")[0]; } if(argsMap.containsKey("-options")) { options = argsMap.get("-options")[0]; } if (argsMap.containsKey("-tLP")) { tlpName = argsMap.get("-tLP")[0]; } if (argsMap.containsKey("-hf")) { hfName = argsMap.get("-hf")[0]; } TreebankLanguagePack tlp; try { tlp = (TreebankLanguagePack) Class.forName(tlpName).getDeclaredConstructor().newInstance(); } catch (Exception e) { log.warning(e); return; } HeadFinder hf; if (hfName != null) { try { hf = (HeadFinder) Class.forName(hfName).getDeclaredConstructor().newInstance(); } catch (Exception e) { log.warning(e); return; } } else { hf = tlp.headFinder(); } TreePrint print = new TreePrint(format, options, tlp, (hf == null) ? tlp.headFinder(): hf, tlp.typedDependencyHeadFinder()); Iterator<Tree> i; // initialized below if (args.length > 0) { Treebank trees; // initialized below TreeReaderFactory trf; if (argsMap.containsKey("-useTLPTreeReader")) { trf = tlp.treeReaderFactory(); } else { trf = in -> new PennTreeReader(in, new LabeledScoredTreeFactory(new StringLabelFactory()), new TreeNormalizer()); } trees = new DiskTreebank(trf); trees.loadPath(args[0]); i = trees.iterator(); } else { i = tlp.treeTokenizerFactory().getTokenizer(new BufferedReader(new InputStreamReader(System.in))); } while(i.hasNext()) { print.printTree(i.next()); } } /** * NO OUTSIDE USE * Returns a String representation of the result of this set of * typed dependencies in a user-specified format. * Currently, three formats are supported: * <dl> * <dt>"plain"</dt> * <dd>(Default.) Formats the dependencies as logical relations, * as exemplified by the following: * <pre> * nsubj(died-1, Sam-0) * tmod(died-1, today-2) * </pre> * </dd> * <dt>"readable"</dt> * <dd>Formats the dependencies as a table with columns * {@code dependent}, {@code relation}, and * {@code governor}, as exemplified by the following: * <pre> * Sam-0 nsubj died-1 * today-2 tmod died-1 * </pre> * </dd> * <dt>"xml"</dt> * <dd>Formats the dependencies as XML, as exemplified by the following: * <pre> * &lt;dependencies&gt; * &lt;dep type="nsubj"&gt; * &lt;governor idx="1"&gt;died&lt;/governor&gt; * &lt;dependent idx="0"&gt;Sam&lt;/dependent&gt; * &lt;/dep&gt; * &lt;dep type="tmod"&gt; * &lt;governor idx="1"&gt;died&lt;/governor&gt; * &lt;dependent idx="2"&gt;today&lt;/dependent&gt; * &lt;/dep&gt; * &lt;/dependencies&gt; * </pre> * </dd> * </dl> * * @param dependencies The TypedDependencies to print * @param format a {@code String} specifying the desired format * @return a {@code String} representation of the typed * dependencies in this {@code GrammaticalStructure} */ private static String toString(Collection<TypedDependency> dependencies, String format, boolean includeTags) { if (format != null && format.equals("xml")) { return toXMLString(dependencies, includeTags); } else if (format != null && format.equals("readable")) { return toReadableString(dependencies); } else if (format != null && format.equals("separator")) { return toString(dependencies, true, includeTags); } else { return toString(dependencies, false, includeTags); } } /** * NO OUTSIDE USE * Returns a String representation of this set of typed dependencies * as exemplified by the following: * <pre> * tmod(died-6, today-9) * nsubj(died-6, Sam-3) * </pre> * * @param dependencies The TypedDependencies to print * @param extraSep boolean indicating whether the extra dependencies have to be printed separately, after the basic ones * @return a {@code String} representation of this set of * typed dependencies */ private static String toString(Collection<TypedDependency> dependencies, boolean extraSep, boolean includeTags) { CoreLabel.OutputFormat labelFormat = (includeTags) ? CoreLabel.OutputFormat.VALUE_TAG_INDEX : CoreLabel.OutputFormat.VALUE_INDEX; StringBuilder buf = new StringBuilder(); if (extraSep) { List<TypedDependency> extraDeps = new ArrayList<>(); for (TypedDependency td : dependencies) { if (td.extra()) { extraDeps.add(td); } else { buf.append(td.toString(labelFormat)).append('\n'); } } // now we print the separator for extra dependencies, and print these if there are some if (!extraDeps.isEmpty()) { buf.append("======\n"); for (TypedDependency td : extraDeps) { buf.append(td.toString(labelFormat)).append('\n'); } } } else { for (TypedDependency td : dependencies) { buf.append(td.toString(labelFormat)).append('\n'); } } return buf.toString(); } // NO OUTSIDE USE private static String toReadableString(Collection<TypedDependency> dependencies) { StringBuilder buf = new StringBuilder(); buf.append(String.format("%-20s%-20s%-20s%n", "dep", "reln", "gov")); buf.append(String.format("%-20s%-20s%-20s%n", "---", "----", "---")); for (TypedDependency td : dependencies) { buf.append(String.format("%-20s%-20s%-20s%n", td.dep(), td.reln(), td.gov())); } return buf.toString(); } // NO OUTSIDE USE private static String toXMLString(Collection<TypedDependency> dependencies, boolean includeTags) { StringBuilder buf = new StringBuilder("<dependencies style=\"typed\">\n"); for (TypedDependency td : dependencies) { String reln = td.reln().toString(); String gov = td.gov().value(); String govTag = td.gov().tag(); int govIdx = td.gov().index(); String dep = td.dep().value(); String depTag = td.dep().tag(); int depIdx = td.dep().index(); boolean extra = td.extra(); // add an attribute if the node is a copy // (this happens in collapsing when different prepositions are conjuncts) String govCopy = ""; int copyGov = td.gov().copyCount(); if (copyGov > 0) { govCopy = " copy=\"" + copyGov + '\"'; } String depCopy = ""; int copyDep = td.dep().copyCount(); if (copyDep > 0) { depCopy = " copy=\"" + copyDep + '\"'; } String govTagAttribute = (includeTags && govTag != null) ? " tag=\"" + govTag + "\"" : ""; String depTagAttribute = (includeTags && depTag != null) ? " tag=\"" + depTag + "\"" : ""; // add an attribute if the typed dependency is an extra relation (do not preserve the tree structure) String extraAttr = ""; if (extra) { extraAttr = " extra=\"yes\""; } buf.append(" <dep type=\"").append(XMLUtils.escapeXML(reln)).append('\"').append(extraAttr).append(">\n"); buf.append(" <governor idx=\"").append(govIdx).append('\"').append(govCopy).append(govTagAttribute).append('>').append(XMLUtils.escapeXML(gov)).append("</governor>\n"); buf.append(" <dependent idx=\"").append(depIdx).append('\"').append(depCopy).append(depTagAttribute).append('>').append(XMLUtils.escapeXML(dep)).append("</dependent>\n"); buf.append(" </dep>\n"); } buf.append("</dependencies>"); return buf.toString(); } /** * USED BY TREEPRINT AND WSD.SUPWSD.PREPROCESS * Prints this set of typed dependencies to the specified * {@code PrintWriter}. * @param dependencies The collection of TypedDependency to print * @param pw Where to print them */ public static void print(Collection<TypedDependency> dependencies, boolean includeTags, PrintWriter pw) { pw.println(toString(dependencies, false, includeTags)); } /** * USED BY TREEPRINT * Prints this set of typed dependencies to the specified * {@code PrintWriter} in the specified format. * @param dependencies The collection of TypedDependency to print * @param format "xml" or "readable" or other * @param pw Where to print them */ public static void print(Collection<TypedDependency> dependencies, String format, boolean includeTags, PrintWriter pw) { pw.println(toString(dependencies, format, includeTags)); } }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/trees/TreePrint.java
179,634
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.hexagonal.domain; import static com.iluwatar.hexagonal.domain.LotteryConstants.PRIZE_AMOUNT; import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import java.util.Map; /** * Lottery administration implementation. */ public class LotteryAdministration { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; /** * Constructor. */ @Inject public LotteryAdministration(LotteryTicketRepository repository, LotteryEventLog notifications, WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } /** * Get all the lottery tickets submitted for lottery. */ public Map<LotteryTicketId, LotteryTicket> getAllSubmittedTickets() { return repository.findAll(); } /** * Draw lottery numbers. */ public LotteryNumbers performLottery() { var numbers = LotteryNumbers.createRandom(); var tickets = getAllSubmittedTickets(); for (var id : tickets.keySet()) { var lotteryTicket = tickets.get(id); var playerDetails = lotteryTicket.playerDetails(); var playerAccount = playerDetails.bankAccount(); var result = LotteryUtils.checkTicketForPrize(repository, id, numbers).getResult(); if (result == LotteryTicketCheckResult.CheckResult.WIN_PRIZE) { if (wireTransfers.transferFunds(PRIZE_AMOUNT, SERVICE_BANK_ACCOUNT, playerAccount)) { notifications.ticketWon(playerDetails, PRIZE_AMOUNT); } else { notifications.prizeError(playerDetails, PRIZE_AMOUNT); } } else if (result == LotteryTicketCheckResult.CheckResult.NO_PRIZE) { notifications.ticketDidNotWin(playerDetails); } } return numbers; } /** * Begin new lottery round. */ public void resetLottery() { repository.deleteAll(); } }
iluwatar/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryAdministration.java
179,636
import java.lang.Math; /** * Game of 3-D Plot * <p> * Based on the BASIC game of 3-D Plot here * https://github.com/coding-horror/basic-computer-games/blob/main/87%203-D%20Plot/3dplot.bas * <p> * Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing * new features - no additional text, error checking, etc has been added. * * Converted from BASIC to Java by Darren Cardenas. */ // Java class names cannot begin with a letter, so class name 3dplot cannot be used public class Plot3D { public void play() { showIntro(); startGame(); } // End of method play private void showIntro() { System.out.println(" ".repeat(31) + "3D PLOT"); System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println("\n\n\n"); } // End of method showIntro private void startGame() { float row = 0; int column = 0; int limit = 0; int plotVal = 0; int root = 0; String lineContent = ""; // Begin loop through all rows for (row = -30; row <= 30; row += 1.5) { limit = 0; root = 5 * (int) Math.floor((Math.sqrt(900 - row * row) / 5)); // Begin loop through all columns for (column = root; column >= -root; column += -5) { plotVal = 25 + (int) Math.floor(func(Math.sqrt(row * row + column * column)) - 0.7 * column); if (plotVal > limit) { limit = plotVal; // Add whitespace while (lineContent.length() < (plotVal-1)) { lineContent += " "; } lineContent += "*"; } } // End loop through all columns System.out.println(lineContent); lineContent = ""; } // End loop through all rows } // End of method startGame // Function to be plotted public double func(double inputVal) { return (30 * Math.exp(-inputVal * inputVal / 100)); } public static void main(String[] args) { Plot3D plot = new Plot3D(); plot.play(); } // End of method main } // End of class Plot3D
coding-horror/basic-computer-games
87_3-D_Plot/java/Plot3D.java
179,638
package com.baeldung.bitset; import org.openjdk.jol.info.ClassLayout; import org.openjdk.jol.info.GraphLayout; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.BitSet; public class Plotter { public static void main(String[] args) throws IOException { Path path = Paths.get("footprint.csv"); try (BufferedWriter stream = Files.newBufferedWriter(path, StandardOpenOption.CREATE)) { stream.write("bits,bool,bitset\n"); for (int i = 0; i <= 10_000_000; i += 500) { System.out.println("Number of bits => " + i); boolean[] ba = new boolean[i]; BitSet bitSet = new BitSet(i); long baSize = ClassLayout.parseInstance(ba).instanceSize(); long bitSetSize = GraphLayout.parseInstance(bitSet).totalSize(); stream.write((i + "," + baSize + "," + bitSetSize + "\n")); if (i % 10_000 == 0) { stream.flush(); } } } } }
eugenp/tutorials
jmh/src/main/java/com/baeldung/bitset/Plotter.java
179,639
package com.airbnb.lottie; import android.graphics.Bitmap; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; /** * Data class describing an image asset embedded in a Lottie json file. */ public class LottieImageAsset { private final int width; private final int height; private final String id; private final String fileName; private final String dirName; /** * Pre-set a bitmap for this asset */ @Nullable private Bitmap bitmap; @RestrictTo(RestrictTo.Scope.LIBRARY) public LottieImageAsset(int width, int height, String id, String fileName, String dirName) { this.width = width; this.height = height; this.id = id; this.fileName = fileName; this.dirName = dirName; } public int getWidth() { return width; } public int getHeight() { return height; } /** * The reference id in the json file. */ public String getId() { return id; } public String getFileName() { return fileName; } @SuppressWarnings("unused") public String getDirName() { return dirName; } /** * Returns the bitmap that has been stored for this image asset if one was explicitly set. */ @Nullable public Bitmap getBitmap() { return bitmap; } /** * Permanently sets the bitmap on this LottieImageAsset. This will: * 1) Overwrite any existing Bitmaps. * 2) Apply to *all* animations that use this LottieComposition. * * If you only want to replace the bitmap for this animation, use dynamic properties * with {@link LottieProperty#IMAGE}. */ public void setBitmap(@Nullable Bitmap bitmap) { this.bitmap = bitmap; } /** * Returns a new {@link LottieImageAsset} with the same properties as this one but with the * dimensions and bitmap scaled. */ public LottieImageAsset copyWithScale(float scale) { LottieImageAsset newAsset = new LottieImageAsset((int) (width * scale), (int) (height * scale), id, fileName, dirName); if (bitmap != null) { Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newAsset.width, newAsset.height, true); newAsset.setBitmap(scaledBitmap); } return newAsset; } /** * Returns whether this asset has an embedded Bitmap or whether the fileName is a base64 encoded bitmap. */ public boolean hasBitmap() { return bitmap != null || (fileName.startsWith("data:") && fileName.indexOf("base64,") > 0); } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieImageAsset.java
179,640
package com.airbnb.lottie.utils; import androidx.core.os.TraceCompat; public class LottieTrace { private static final int MAX_DEPTH = 5; private final String[] sections = new String[MAX_DEPTH]; private final long[] startTimeNs = new long[MAX_DEPTH]; private int traceDepth = 0; private int depthPastMaxDepth = 0; public void beginSection(String section) { if (traceDepth == MAX_DEPTH) { depthPastMaxDepth++; return; } sections[traceDepth] = section; startTimeNs[traceDepth] = System.nanoTime(); //noinspection deprecation TraceCompat.beginSection(section); traceDepth++; } public float endSection(String section) { if (depthPastMaxDepth > 0) { depthPastMaxDepth--; return 0; } traceDepth--; if (traceDepth == -1) { throw new IllegalStateException("Can't end trace section. There are none."); } if (!section.equals(sections[traceDepth])) { throw new IllegalStateException("Unbalanced trace call " + section + ". Expected " + sections[traceDepth] + "."); } //noinspection deprecation TraceCompat.endSection(); return (System.nanoTime() - startTimeNs[traceDepth]) / 1000000f; } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/utils/LottieTrace.java
179,641
/* * 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.coyote.http2; import java.io.IOException; import java.io.StringReader; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import org.apache.coyote.ActionCode; import org.apache.coyote.CloseNowException; import org.apache.coyote.InputBuffer; import org.apache.coyote.Request; import org.apache.coyote.Response; import org.apache.coyote.http11.HttpOutputBuffer; import org.apache.coyote.http11.OutputFilter; import org.apache.coyote.http11.filters.SavedRequestInputFilter; import org.apache.coyote.http11.filters.VoidOutputFilter; import org.apache.coyote.http2.HpackDecoder.HeaderEmitter; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.Host; import org.apache.tomcat.util.http.parser.Priority; import org.apache.tomcat.util.net.ApplicationBufferHandler; import org.apache.tomcat.util.net.WriteBuffer; import org.apache.tomcat.util.res.StringManager; class Stream extends AbstractNonZeroStream implements HeaderEmitter { private static final Log log = LogFactory.getLog(Stream.class); private static final StringManager sm = StringManager.getManager(Stream.class); private static final int HEADER_STATE_START = 0; private static final int HEADER_STATE_PSEUDO = 1; private static final int HEADER_STATE_REGULAR = 2; private static final int HEADER_STATE_TRAILER = 3; private static final MimeHeaders ACK_HEADERS; private static final Integer HTTP_UPGRADE_STREAM = Integer.valueOf(1); private static final Set<String> HTTP_CONNECTION_SPECIFIC_HEADERS = new HashSet<>(); static { Response response = new Response(); response.setStatus(100); StreamProcessor.prepareHeaders(null, response, true, null, null); ACK_HEADERS = response.getMimeHeaders(); HTTP_CONNECTION_SPECIFIC_HEADERS.add("connection"); HTTP_CONNECTION_SPECIFIC_HEADERS.add("proxy-connection"); HTTP_CONNECTION_SPECIFIC_HEADERS.add("keep-alive"); HTTP_CONNECTION_SPECIFIC_HEADERS.add("transfer-encoding"); HTTP_CONNECTION_SPECIFIC_HEADERS.add("upgrade"); } private volatile long contentLengthReceived = 0; private final Http2UpgradeHandler handler; private final WindowAllocationManager allocationManager = new WindowAllocationManager(this); private final Request coyoteRequest; private final Response coyoteResponse = new Response(); private final StreamInputBuffer inputBuffer; private final StreamOutputBuffer streamOutputBuffer = new StreamOutputBuffer(); private final Http2OutputBuffer http2OutputBuffer = new Http2OutputBuffer(coyoteResponse, streamOutputBuffer); // State machine would be too much overhead private int headerState = HEADER_STATE_START; private StreamException headerException = null; private volatile StringBuilder cookieHeader = null; private volatile boolean hostHeaderSeen = false; private Object pendingWindowUpdateForStreamLock = new Object(); private int pendingWindowUpdateForStream = 0; private volatile int urgency = Priority.DEFAULT_URGENCY; private volatile boolean incremental = Priority.DEFAULT_INCREMENTAL; Stream(Integer identifier, Http2UpgradeHandler handler) { this(identifier, handler, null); } Stream(Integer identifier, Http2UpgradeHandler handler, Request coyoteRequest) { super(handler.getConnectionId(), identifier); this.handler = handler; setWindowSize(handler.getRemoteSettings().getInitialWindowSize()); if (coyoteRequest == null) { // HTTP/2 new request this.coyoteRequest = new Request(); this.inputBuffer = new StandardStreamInputBuffer(); this.coyoteRequest.setInputBuffer(inputBuffer); } else { // HTTP/1.1 upgrade this.coyoteRequest = coyoteRequest; this.inputBuffer = new SavedRequestStreamInputBuffer((SavedRequestInputFilter) coyoteRequest.getInputBuffer()); // Headers have been read by this point state.receivedStartOfHeaders(); if (HTTP_UPGRADE_STREAM.equals(identifier)) { // Populate coyoteRequest from headers (HTTP/1.1 only) try { prepareRequest(); } catch (IllegalArgumentException iae) { // Something in the headers is invalid // Set correct return status coyoteResponse.setStatus(400); // Set error flag. This triggers error processing rather than // the normal mapping coyoteResponse.setError(); } } // Request body, if any, has been read and buffered state.receivedEndOfStream(); } this.coyoteRequest.setSendfile(handler.hasAsyncIO() && handler.getProtocol().getUseSendfile()); this.coyoteResponse.setOutputBuffer(http2OutputBuffer); this.coyoteRequest.setResponse(coyoteResponse); this.coyoteRequest.protocol().setString("HTTP/2.0"); if (this.coyoteRequest.getStartTimeNanos() < 0) { this.coyoteRequest.setStartTimeNanos(System.nanoTime()); } } private void prepareRequest() { if (coyoteRequest.scheme().isNull()) { if (handler.getProtocol().getHttp11Protocol().isSSLEnabled()) { coyoteRequest.scheme().setString("https"); } else { coyoteRequest.scheme().setString("http"); } } MessageBytes hostValueMB = coyoteRequest.getMimeHeaders().getUniqueValue("host"); if (hostValueMB == null) { throw new IllegalArgumentException(); } // This processing expects bytes. Trigger a conversion if required. hostValueMB.toBytes(); ByteChunk valueBC = hostValueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); int colonPos = Host.parse(hostValueMB); if (colonPos != -1) { int port = 0; for (int i = colonPos + 1; i < valueL; i++) { char c = (char) valueB[i + valueS]; if (c < '0' || c > '9') { throw new IllegalArgumentException(); } port = port * 10 + c - '0'; } coyoteRequest.setServerPort(port); // Only need to copy the host name up to the : valueL = colonPos; } // Extract the host name char[] hostNameC = new char[valueL]; for (int i = 0; i < valueL; i++) { hostNameC[i] = (char) valueB[i + valueS]; } coyoteRequest.serverName().setChars(hostNameC, 0, valueL); } final void receiveReset(long errorCode) { if (log.isTraceEnabled()) { log.trace( sm.getString("stream.reset.receive", getConnectionId(), getIdAsString(), Long.toString(errorCode))); } // Set the new state first since read and write both check this state.receivedReset(); // Reads wait internally so need to call a method to break the wait() if (inputBuffer != null) { inputBuffer.receiveReset(); } cancelAllocationRequests(); } final void cancelAllocationRequests() { allocationManager.notifyAny(); } @Override final void incrementWindowSize(int windowSizeIncrement) throws Http2Exception { windowAllocationLock.lock(); try { // If this is zero then any thread that has been trying to write for // this stream will be waiting. Notify that thread it can continue. Use // notify all even though only one thread is waiting to be on the safe // side. boolean notify = getWindowSize() < 1; super.incrementWindowSize(windowSizeIncrement); if (notify && getWindowSize() > 0) { allocationManager.notifyStream(); } } finally { windowAllocationLock.unlock(); } } final int reserveWindowSize(int reservation, boolean block) throws IOException { windowAllocationLock.lock(); try { long windowSize = getWindowSize(); while (windowSize < 1) { if (!canWrite()) { throw new CloseNowException(sm.getString("stream.notWritable", getConnectionId(), getIdAsString())); } if (block) { try { long writeTimeout = handler.getProtocol().getStreamWriteTimeout(); allocationManager.waitForStream(writeTimeout); windowSize = getWindowSize(); if (windowSize == 0) { doStreamCancel(sm.getString("stream.writeTimeout"), Http2Error.ENHANCE_YOUR_CALM); } } catch (InterruptedException e) { // Possible shutdown / rst or similar. Use an IOException to // signal to the client that further I/O isn't possible for this // Stream. throw new IOException(e); } } else { allocationManager.waitForStreamNonBlocking(); return 0; } } int allocation; if (windowSize < reservation) { allocation = (int) windowSize; } else { allocation = reservation; } decrementWindowSize(allocation); return allocation; } finally { windowAllocationLock.unlock(); } } void doStreamCancel(String msg, Http2Error error) throws CloseNowException { StreamException se = new StreamException(msg, error, getIdAsInt()); // Prevent the application making further writes streamOutputBuffer.closed = true; // Prevent Tomcat's error handling trying to write coyoteResponse.setError(); coyoteResponse.setErrorReported(); // Trigger a reset once control returns to Tomcat streamOutputBuffer.reset = se; throw new CloseNowException(msg, se); } void waitForConnectionAllocation(long timeout) throws InterruptedException { allocationManager.waitForConnection(timeout); } void waitForConnectionAllocationNonBlocking() { allocationManager.waitForConnectionNonBlocking(); } void notifyConnection() { allocationManager.notifyConnection(); } @Override public final void emitHeader(String name, String value) throws HpackException { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.header.debug", getConnectionId(), getIdAsString(), name, value)); } // Header names must be lower case if (!name.toLowerCase(Locale.US).equals(name)) { throw new HpackException(sm.getString("stream.header.case", getConnectionId(), getIdAsString(), name)); } if (HTTP_CONNECTION_SPECIFIC_HEADERS.contains(name)) { throw new HpackException( sm.getString("stream.header.connection", getConnectionId(), getIdAsString(), name)); } if ("te".equals(name)) { if (!"trailers".equals(value)) { throw new HpackException(sm.getString("stream.header.te", getConnectionId(), getIdAsString(), value)); } } if (headerException != null) { // Don't bother processing the header since the stream is going to // be reset anyway return; } if (name.length() == 0) { throw new HpackException(sm.getString("stream.header.empty", getConnectionId(), getIdAsString())); } boolean pseudoHeader = name.charAt(0) == ':'; if (pseudoHeader && headerState != HEADER_STATE_PSEUDO) { headerException = new StreamException( sm.getString("stream.header.unexpectedPseudoHeader", getConnectionId(), getIdAsString(), name), Http2Error.PROTOCOL_ERROR, getIdAsInt()); // No need for further processing. The stream will be reset. return; } if (headerState == HEADER_STATE_PSEUDO && !pseudoHeader) { headerState = HEADER_STATE_REGULAR; } switch (name) { case ":method": { if (coyoteRequest.method().isNull()) { coyoteRequest.method().setString(value); if ("HEAD".equals(value)) { configureVoidOutputFilter(); } } else { throw new HpackException( sm.getString("stream.header.duplicate", getConnectionId(), getIdAsString(), ":method")); } break; } case ":scheme": { if (coyoteRequest.scheme().isNull()) { coyoteRequest.scheme().setString(value); } else { throw new HpackException( sm.getString("stream.header.duplicate", getConnectionId(), getIdAsString(), ":scheme")); } break; } case ":path": { if (!coyoteRequest.requestURI().isNull()) { throw new HpackException( sm.getString("stream.header.duplicate", getConnectionId(), getIdAsString(), ":path")); } if (value.length() == 0) { throw new HpackException(sm.getString("stream.header.noPath", getConnectionId(), getIdAsString())); } int queryStart = value.indexOf('?'); String uri; if (queryStart == -1) { uri = value; } else { uri = value.substring(0, queryStart); String query = value.substring(queryStart + 1); coyoteRequest.queryString().setString(query); } // Bug 61120. Set the URI as bytes rather than String so: // - any path parameters are correctly processed // - the normalization security checks are performed that prevent // directory traversal attacks byte[] uriBytes = uri.getBytes(StandardCharsets.ISO_8859_1); coyoteRequest.requestURI().setBytes(uriBytes, 0, uriBytes.length); break; } case ":authority": { if (coyoteRequest.serverName().isNull()) { parseAuthority(value, false); } else { throw new HpackException( sm.getString("stream.header.duplicate", getConnectionId(), getIdAsString(), ":authority")); } break; } case "cookie": { // Cookie headers need to be concatenated into a single header // See RFC 7540 8.1.2.5 if (cookieHeader == null) { cookieHeader = new StringBuilder(); } else { cookieHeader.append("; "); } cookieHeader.append(value); break; } case "host": { if (coyoteRequest.serverName().isNull()) { // No :authority header. This is first host header. Use it. hostHeaderSeen = true; parseAuthority(value, true); } else if (!hostHeaderSeen) { // First host header - must be consistent with :authority hostHeaderSeen = true; compareAuthority(value); } else { // Multiple hosts headers - illegal throw new HpackException( sm.getString("stream.header.duplicate", getConnectionId(), getIdAsString(), "host")); } break; } case "priority": { try { Priority p = Priority.parsePriority(new StringReader(value)); setUrgency(p.getUrgency()); setIncremental(p.getIncremental()); } catch (IOException ioe) { // Not possible with StringReader } break; } default: { if (headerState == HEADER_STATE_TRAILER && !handler.getProtocol().isTrailerHeaderAllowed(name)) { break; } if ("expect".equals(name) && "100-continue".equals(value)) { coyoteRequest.setExpectation(true); } if (pseudoHeader) { headerException = new StreamException( sm.getString("stream.header.unknownPseudoHeader", getConnectionId(), getIdAsString(), name), Http2Error.PROTOCOL_ERROR, getIdAsInt()); } if (headerState == HEADER_STATE_TRAILER) { // HTTP/2 headers are already always lower case coyoteRequest.getMimeTrailerFields().addValue(name).setString(value); } else { coyoteRequest.getMimeHeaders().addValue(name).setString(value); } } } } void configureVoidOutputFilter() { addOutputFilter(new VoidOutputFilter()); // Prevent further writes by the application streamOutputBuffer.closed = true; } private void parseAuthority(String value, boolean host) throws HpackException { int i; try { i = Host.parse(value); } catch (IllegalArgumentException iae) { // Host value invalid throw new HpackException(sm.getString("stream.header.invalid", getConnectionId(), getIdAsString(), host ? "host" : ":authority", value)); } if (i > -1) { coyoteRequest.serverName().setString(value.substring(0, i)); coyoteRequest.setServerPort(Integer.parseInt(value.substring(i + 1))); } else { coyoteRequest.serverName().setString(value); } } private void compareAuthority(String value) throws HpackException { int i; try { i = Host.parse(value); } catch (IllegalArgumentException iae) { // Host value invalid throw new HpackException( sm.getString("stream.header.invalid", getConnectionId(), getIdAsString(), "host", value)); } if (i == -1 && (!value.equals(coyoteRequest.serverName().getString()) || coyoteRequest.getServerPort() != -1) || i > -1 && ((!value.substring(0, i).equals(coyoteRequest.serverName().getString()) || Integer.parseInt(value.substring(i + 1)) != coyoteRequest.getServerPort()))) { // Host value inconsistent throw new HpackException(sm.getString("stream.host.inconsistent", getConnectionId(), getIdAsString(), value, coyoteRequest.serverName().getString(), Integer.toString(coyoteRequest.getServerPort()))); } } @Override public void setHeaderException(StreamException streamException) { if (headerException == null) { headerException = streamException; } } @Override public void validateHeaders() throws StreamException { if (headerException == null) { return; } handler.getHpackDecoder().setHeaderEmitter(Http2UpgradeHandler.HEADER_SINK); throw headerException; } final boolean receivedEndOfHeaders() throws ConnectionException { if (coyoteRequest.method().isNull() || coyoteRequest.scheme().isNull() || !coyoteRequest.method().equals("CONNECT") && coyoteRequest.requestURI().isNull()) { throw new ConnectionException(sm.getString("stream.header.required", getConnectionId(), getIdAsString()), Http2Error.PROTOCOL_ERROR); } // Cookie headers need to be concatenated into a single header // See RFC 7540 8.1.2.5 // Can only do this once the headers are fully received if (cookieHeader != null) { coyoteRequest.getMimeHeaders().addValue("cookie").setString(cookieHeader.toString()); } return headerState == HEADER_STATE_REGULAR || headerState == HEADER_STATE_PSEUDO; } final void writeHeaders() throws IOException { boolean endOfStream = streamOutputBuffer.hasNoBody() && coyoteResponse.getTrailerFields() == null; handler.writeHeaders(this, coyoteResponse.getMimeHeaders(), endOfStream, Constants.DEFAULT_HEADERS_FRAME_SIZE); } final void addOutputFilter(OutputFilter filter) { http2OutputBuffer.addFilter(filter); } final void writeTrailers() throws IOException { Supplier<Map<String,String>> supplier = coyoteResponse.getTrailerFields(); if (supplier == null) { // No supplier was set, end of stream will already have been sent return; } // We can re-use the MimeHeaders from the response since they have // already been processed by the encoder at this point MimeHeaders mimeHeaders = coyoteResponse.getMimeHeaders(); mimeHeaders.recycle(); Map<String,String> headerMap = supplier.get(); if (headerMap == null) { headerMap = Collections.emptyMap(); } // Copy the contents of the Map to the MimeHeaders // TODO: Is there benefit in refactoring this? Is MimeHeaders too // heavyweight? Can we reduce the copy/conversions? for (Map.Entry<String,String> headerEntry : headerMap.entrySet()) { MessageBytes mb = mimeHeaders.addValue(headerEntry.getKey()); mb.setString(headerEntry.getValue()); } handler.writeHeaders(this, mimeHeaders, true, Constants.DEFAULT_HEADERS_FRAME_SIZE); } final void writeAck() throws IOException { handler.writeHeaders(this, ACK_HEADERS, false, Constants.DEFAULT_HEADERS_ACK_FRAME_SIZE); } @Override final String getConnectionId() { return handler.getConnectionId(); } final Request getCoyoteRequest() { return coyoteRequest; } final Response getCoyoteResponse() { return coyoteResponse; } @Override final ByteBuffer getInputByteBuffer() { if (inputBuffer == null) { // This must either be an HTTP upgrade. There should not be a request body so return a zero length //ByteBuffer to trigger a flow control error. return ZERO_LENGTH_BYTEBUFFER; } return inputBuffer.getInBuffer(); } final void receivedStartOfHeaders(boolean headersEndStream) throws Http2Exception { if (headerState == HEADER_STATE_START) { headerState = HEADER_STATE_PSEUDO; handler.getHpackDecoder().setMaxHeaderCount(handler.getProtocol().getMaxHeaderCount()); handler.getHpackDecoder().setMaxHeaderSize(handler.getProtocol().getMaxHeaderSize()); } else if (headerState == HEADER_STATE_PSEUDO || headerState == HEADER_STATE_REGULAR) { // Trailer headers MUST include the end of stream flag if (headersEndStream) { headerState = HEADER_STATE_TRAILER; handler.getHpackDecoder().setMaxHeaderCount(handler.getProtocol().getMaxTrailerCount()); handler.getHpackDecoder().setMaxHeaderSize(handler.getProtocol().getMaxTrailerSize()); } else { throw new ConnectionException( sm.getString("stream.trailerHeader.noEndOfStream", getConnectionId(), getIdAsString()), Http2Error.PROTOCOL_ERROR); } } // Parser will catch attempt to send a headers frame after the stream // has closed. state.receivedStartOfHeaders(); } @Override final void receivedData(int payloadSize) throws Http2Exception { contentLengthReceived += payloadSize; long contentLengthHeader = coyoteRequest.getContentLengthLong(); if (contentLengthHeader > -1 && contentLengthReceived > contentLengthHeader) { throw new ConnectionException( sm.getString("stream.header.contentLength", getConnectionId(), getIdAsString(), Long.valueOf(contentLengthHeader), Long.valueOf(contentLengthReceived)), Http2Error.PROTOCOL_ERROR); } } final void receivedEndOfStream() throws ConnectionException { if (isContentLengthInconsistent()) { throw new ConnectionException( sm.getString("stream.header.contentLength", getConnectionId(), getIdAsString(), Long.valueOf(coyoteRequest.getContentLengthLong()), Long.valueOf(contentLengthReceived)), Http2Error.PROTOCOL_ERROR); } state.receivedEndOfStream(); if (inputBuffer != null) { inputBuffer.notifyEof(); } } final boolean isContentLengthInconsistent() { long contentLengthHeader = coyoteRequest.getContentLengthLong(); if (contentLengthHeader > -1 && contentLengthReceived != contentLengthHeader) { return true; } return false; } final void sentHeaders() { state.sentHeaders(); } final void sentEndOfStream() { streamOutputBuffer.endOfStreamSent = true; state.sentEndOfStream(); } final boolean isReadyForWrite() { return streamOutputBuffer.isReady(); } final boolean flush(boolean block) throws IOException { return streamOutputBuffer.flush(block); } final StreamInputBuffer getInputBuffer() { return inputBuffer; } final HttpOutputBuffer getOutputBuffer() { return http2OutputBuffer; } final boolean isActive() { return state.isActive(); } final boolean canWrite() { return state.canWrite(); } final void closeIfIdle() { state.closeIfIdle(); } final boolean isInputFinished() { return !state.isFrameTypePermitted(FrameType.DATA); } final void close(Http2Exception http2Exception) { if (http2Exception instanceof StreamException) { try { StreamException se = (StreamException) http2Exception; if (log.isTraceEnabled()) { log.trace(sm.getString("stream.reset.send", getConnectionId(), getIdAsString(), se.getError())); } // Need to update state atomically with the sending of the RST // frame else other threads currently working with this stream // may see the state change and send a RST frame before the RST // frame triggered by this thread. If that happens the client // may see out of order RST frames which may hard to follow if // the client is unaware the RST frames may be received out of // order. handler.sendStreamReset(state, se); cancelAllocationRequests(); if (inputBuffer != null) { inputBuffer.swallowUnread(); } } catch (IOException ioe) { ConnectionException ce = new ConnectionException(sm.getString("stream.reset.fail", getConnectionId(), getIdAsString()), Http2Error.PROTOCOL_ERROR, ioe); handler.closeConnection(ce); } } else { handler.closeConnection(http2Exception); } recycle(); } /* * This method is called recycle for consistency with the rest of the Tomcat code base. Currently, it calls the * handler to replace this stream with an implementation that uses less memory. It does not fully recycle the Stream * ready for re-use since Stream objects are not re-used. This is useful because Stream instances are retained for a * period after the Stream closes. */ final void recycle() { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.recycle", getConnectionId(), getIdAsString())); } int remaining; // May be null if stream was closed before any DATA frames were processed. ByteBuffer inputByteBuffer = getInputByteBuffer(); if (inputByteBuffer == null) { remaining = 0; } else { remaining = inputByteBuffer.remaining(); } handler.replaceStream(this, new RecycledStream(getConnectionId(), getIdentifier(), state, remaining)); } boolean isTrailerFieldsReady() { // Once EndOfStream has been received, canRead will be false return !state.canRead(); } boolean isTrailerFieldsSupported() { return !streamOutputBuffer.endOfStreamSent; } StreamException getResetException() { return streamOutputBuffer.reset; } int getWindowUpdateSizeToWrite(int increment) { int result; int threshold = handler.getProtocol().getOverheadWindowUpdateThreshold(); synchronized (pendingWindowUpdateForStreamLock) { if (increment > threshold) { result = increment + pendingWindowUpdateForStream; pendingWindowUpdateForStream = 0; } else { pendingWindowUpdateForStream += increment; if (pendingWindowUpdateForStream > threshold) { result = pendingWindowUpdateForStream; pendingWindowUpdateForStream = 0; } else { result = 0; } } } return result; } public int getUrgency() { return urgency; } public void setUrgency(int urgency) { this.urgency = urgency; } public boolean getIncremental() { return incremental; } public void setIncremental(boolean incremental) { this.incremental = incremental; } class StreamOutputBuffer implements HttpOutputBuffer, WriteBuffer.Sink { private final Lock writeLock = new ReentrantLock(); private final ByteBuffer buffer = ByteBuffer.allocate(8 * 1024); private final WriteBuffer writeBuffer = new WriteBuffer(32 * 1024); // Flag that indicates that data was left over on a previous // non-blocking write. Once set, this flag stays set until all the data // has been written. private boolean dataLeft; private volatile long written = 0; private int streamReservation = 0; private volatile boolean closed = false; private volatile StreamException reset = null; private volatile boolean endOfStreamSent = false; /* * The write methods share a common lock to ensure that only one thread at a time is able to access the buffer. * Without this protection, a client that performed concurrent writes could corrupt the buffer. */ @Override public final int doWrite(ByteBuffer chunk) throws IOException { writeLock.lock(); try { if (closed) { throw new IOException(sm.getString("stream.closed", getConnectionId(), getIdAsString())); } // chunk is always fully written int result = chunk.remaining(); if (writeBuffer.isEmpty()) { int chunkLimit = chunk.limit(); while (chunk.remaining() > 0) { int thisTime = Math.min(buffer.remaining(), chunk.remaining()); chunk.limit(chunk.position() + thisTime); buffer.put(chunk); chunk.limit(chunkLimit); if (chunk.remaining() > 0 && !buffer.hasRemaining()) { // Only flush if we have more data to write and the buffer // is full if (flush(true, coyoteResponse.getWriteListener() == null)) { writeBuffer.add(chunk); dataLeft = true; break; } } } } else { writeBuffer.add(chunk); } written += result; return result; } finally { writeLock.unlock(); } } final boolean flush(boolean block) throws IOException { writeLock.lock(); try { /* * Need to ensure that there is exactly one call to flush even when there is no data to write. Too few calls * (i.e. zero) and the end of stream message is not sent for a completed asynchronous write. Too many calls * and the end of stream message is sent too soon and trailer headers are not sent. */ boolean dataInBuffer = buffer.position() > 0; boolean flushed = false; if (dataInBuffer) { dataInBuffer = flush(false, block); flushed = true; } if (dataInBuffer) { dataLeft = true; } else { if (writeBuffer.isEmpty()) { // Both buffer and writeBuffer are empty. if (flushed) { dataLeft = false; } else { dataLeft = flush(false, block); } } else { dataLeft = writeBuffer.write(this, block); } } return dataLeft; } finally { writeLock.unlock(); } } private boolean flush(boolean writeInProgress, boolean block) throws IOException { writeLock.lock(); try { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.outputBuffer.flush.debug", getConnectionId(), getIdAsString(), Integer.toString(buffer.position()), Boolean.toString(writeInProgress), Boolean.toString(closed))); } if (buffer.position() == 0) { if (closed && !endOfStreamSent) { // Handling this special case here is simpler than trying // to modify the following code to handle it. handler.writeBody(Stream.this, buffer, 0, coyoteResponse.getTrailerFields() == null); } // Buffer is empty. Nothing to do. return false; } buffer.flip(); int left = buffer.remaining(); while (left > 0) { if (streamReservation == 0) { streamReservation = reserveWindowSize(left, block); if (streamReservation == 0) { // Must be non-blocking. // Note: Can't add to the writeBuffer here as the write // may originate from the writeBuffer. buffer.compact(); return true; } } while (streamReservation > 0) { int connectionReservation = handler.reserveWindowSize(Stream.this, streamReservation, block); if (connectionReservation == 0) { // Must be non-blocking. // Note: Can't add to the writeBuffer here as the write // may originate from the writeBuffer. buffer.compact(); return true; } // Do the write handler.writeBody(Stream.this, buffer, connectionReservation, !writeInProgress && closed && left == connectionReservation && coyoteResponse.getTrailerFields() == null); streamReservation -= connectionReservation; left -= connectionReservation; } } buffer.clear(); return false; } finally { writeLock.unlock(); } } final boolean isReady() { writeLock.lock(); try { // Bug 63682 // Only want to return false if the window size is zero AND we are // already waiting for an allocation. if (getWindowSize() > 0 && allocationManager.isWaitingForStream() || handler.getWindowSize() > 0 && allocationManager.isWaitingForConnection() || dataLeft) { return false; } else { return true; } } finally { writeLock.unlock(); } } @Override public final long getBytesWritten() { return written; } @Override public final void end() throws IOException { if (reset != null) { throw new CloseNowException(reset); } if (!closed) { closed = true; flush(true); writeTrailers(); } } /** * @return <code>true</code> if it is certain that the associated response has no body. */ final boolean hasNoBody() { return ((written == 0) && closed); } @Override public void flush() throws IOException { /* * This method should only be called during blocking I/O. All the Servlet API calls that end up here are * illegal during non-blocking I/O. Servlet 5.4. However, the wording Servlet specification states that the * behaviour is undefined so we do the best we can which is to perform a flush using blocking I/O or * non-blocking I/O based depending which is currently in use. */ flush(getCoyoteResponse().getWriteListener() == null); } @Override public boolean writeFromBuffer(ByteBuffer src, boolean blocking) throws IOException { writeLock.lock(); try { int chunkLimit = src.limit(); while (src.remaining() > 0) { int thisTime = Math.min(buffer.remaining(), src.remaining()); src.limit(src.position() + thisTime); buffer.put(src); src.limit(chunkLimit); if (flush(false, blocking)) { return true; } } return false; } finally { writeLock.unlock(); } } } abstract class StreamInputBuffer implements InputBuffer { abstract void receiveReset(); abstract void swallowUnread() throws IOException; abstract void notifyEof(); abstract ByteBuffer getInBuffer(); abstract void onDataAvailable() throws IOException; abstract boolean isReadyForRead(); abstract boolean isRequestBodyFullyRead(); abstract void insertReplayedBody(ByteChunk body); } class StandardStreamInputBuffer extends StreamInputBuffer { private final Lock readStateLock = new ReentrantLock(); /* * Two buffers are required to avoid various multi-threading issues. These issues arise from the fact that the * Stream (or the Request/Response) used by the application is processed in one thread but the connection is * processed in another. Therefore it is possible that a request body frame could be received before the * application is ready to read it. If it isn't buffered, processing of the connection (and hence all streams) * would block until the application read the data. Hence the incoming data has to be buffered. If only one * buffer was used then it could become corrupted if the connection thread is trying to add to it at the same * time as the application is read it. While it should be possible to avoid this corruption by careful use of * the buffer it would still require the same copies as using two buffers and the behaviour would be less clear. * * The buffers are created lazily because they quickly add up to a lot of memory and most requests do not have * bodies. */ // This buffer is used to populate the ByteChunk passed in to the read // method private byte[] outBuffer; // This buffer is the destination for incoming data. It is normally is // 'write mode'. private volatile ByteBuffer inBuffer; private volatile boolean readInterest; private volatile boolean closed; private boolean resetReceived; @Override public final int doRead(ApplicationBufferHandler applicationBufferHandler) throws IOException { ensureBuffersExist(); int written = -1; // It is still possible that the stream has been closed and inBuffer // set to null between the call to ensureBuffersExist() above and // the sync below. The checks just before and just inside the sync // ensure we don't get any NPEs reported. ByteBuffer tmpInBuffer = inBuffer; if (tmpInBuffer == null) { return -1; } // Ensure that only one thread accesses inBuffer at a time synchronized (tmpInBuffer) { if (inBuffer == null) { return -1; } boolean canRead = false; while (inBuffer.position() == 0 && (canRead = isActive() && !isInputFinished())) { // Need to block until some data is written try { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.inputBuffer.empty")); } long readTimeout = handler.getProtocol().getStreamReadTimeout(); if (readTimeout < 0) { inBuffer.wait(); } else { inBuffer.wait(readTimeout); } if (resetReceived) { throw new IOException(sm.getString("stream.inputBuffer.reset")); } if (inBuffer.position() == 0 && isActive() && !isInputFinished()) { String msg = sm.getString("stream.inputBuffer.readTimeout"); StreamException se = new StreamException(msg, Http2Error.ENHANCE_YOUR_CALM, getIdAsInt()); // Trigger a reset once control returns to Tomcat coyoteResponse.setError(); streamOutputBuffer.reset = se; throw new CloseNowException(msg, se); } } catch (InterruptedException e) { // Possible shutdown / rst or similar. Use an // IOException to signal to the client that further I/O // isn't possible for this Stream. throw new IOException(e); } } if (inBuffer.position() > 0) { // Data is available in the inBuffer. Copy it to the // outBuffer. inBuffer.flip(); written = inBuffer.remaining(); if (log.isTraceEnabled()) { log.trace(sm.getString("stream.inputBuffer.copy", Integer.toString(written))); } inBuffer.get(outBuffer, 0, written); inBuffer.clear(); } else if (!canRead) { return -1; } else { // Should never happen throw new IllegalStateException(); } } applicationBufferHandler.setByteBuffer(ByteBuffer.wrap(outBuffer, 0, written)); // Increment client-side flow control windows by the number of bytes // read handler.writeWindowUpdate(Stream.this, written, true); return written; } @Override final boolean isReadyForRead() { ensureBuffersExist(); readStateLock.lock(); try { if (available() > 0) { return true; } if (!isRequestBodyFullyRead()) { readInterest = true; } return false; } finally { readStateLock.unlock(); } } @Override final boolean isRequestBodyFullyRead() { readStateLock.lock(); try { return (inBuffer == null || inBuffer.position() == 0) && isInputFinished(); } finally { readStateLock.unlock(); } } @Override public final int available() { readStateLock.lock(); try { if (inBuffer == null) { return 0; } return inBuffer.position(); } finally { readStateLock.unlock(); } } /* * Called after placing some data in the inBuffer. */ @Override final void onDataAvailable() throws IOException { readStateLock.lock(); try { if (closed) { swallowUnread(); } else if (readInterest) { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.inputBuffer.dispatch")); } readInterest = false; coyoteRequest.action(ActionCode.DISPATCH_READ, null); // Always need to dispatch since this thread is processing // the incoming connection and streams are processed on their // own. coyoteRequest.action(ActionCode.DISPATCH_EXECUTE, null); } else { if (log.isTraceEnabled()) { log.trace(sm.getString("stream.inputBuffer.signal")); } synchronized (inBuffer) { inBuffer.notifyAll(); } } } finally { readStateLock.unlock(); } } @Override final ByteBuffer getInBuffer() { ensureBuffersExist(); return inBuffer; } @Override final void insertReplayedBody(ByteChunk body) { readStateLock.lock(); try { inBuffer = ByteBuffer.wrap(body.getBytes(), body.getStart(), body.getLength()); } finally { readStateLock.unlock(); } } private void ensureBuffersExist() { if (inBuffer == null && !closed) { // The client must obey Tomcat's window size when sending so // this is the initial window size set by Tomcat that the client // uses (i.e. the local setting is required here). int size = handler.getLocalSettings().getInitialWindowSize(); readStateLock.lock(); try { if (inBuffer == null && !closed) { inBuffer = ByteBuffer.allocate(size); outBuffer = new byte[size]; } } finally { readStateLock.unlock(); } } } @Override final void receiveReset() { if (inBuffer != null) { synchronized (inBuffer) { resetReceived = true; inBuffer.notifyAll(); } } } @Override final void notifyEof() { if (inBuffer != null) { synchronized (inBuffer) { inBuffer.notifyAll(); } } } @Override final void swallowUnread() throws IOException { readStateLock.lock(); try { closed = true; } finally { readStateLock.unlock(); } if (inBuffer != null) { int unreadByteCount = 0; synchronized (inBuffer) { unreadByteCount = inBuffer.position(); if (log.isTraceEnabled()) { log.trace(sm.getString("stream.inputBuffer.swallowUnread", Integer.valueOf(unreadByteCount))); } if (unreadByteCount > 0) { inBuffer.position(0); inBuffer.limit(inBuffer.limit() - unreadByteCount); } } // Do this outside of the sync because: // - it doesn't need to be inside the sync // - if inside the sync it can trigger a deadlock // https://markmail.org/message/vbglzkvj6wxlhh3p if (unreadByteCount > 0) { handler.onSwallowedDataFramePayload(getIdAsInt(), unreadByteCount); } } } } class SavedRequestStreamInputBuffer extends StreamInputBuffer { private final SavedRequestInputFilter inputFilter; SavedRequestStreamInputBuffer(SavedRequestInputFilter inputFilter) { this.inputFilter = inputFilter; } @Override public int doRead(ApplicationBufferHandler handler) throws IOException { return inputFilter.doRead(handler); } @Override public int available() { return inputFilter.available(); } @Override void receiveReset() { // NO-OP } @Override void swallowUnread() throws IOException { // NO-OP } @Override void notifyEof() { // NO-OP } @Override ByteBuffer getInBuffer() { return null; } @Override void onDataAvailable() throws IOException { // NO-OP } @Override boolean isReadyForRead() { return true; } @Override boolean isRequestBodyFullyRead() { return inputFilter.isFinished(); } @Override void insertReplayedBody(ByteChunk body) { // NO-OP } } }
apache/tomcat
java/org/apache/coyote/http2/Stream.java
179,642
/* * Copyright (c) 2011-2021 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.impl; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.resolver.AddressResolverGroup; import io.netty.util.ResourceLeakDetector; import io.netty.util.concurrent.GenericFutureListener; import io.vertx.core.Future; import io.vertx.core.*; import io.vertx.core.Timer; import io.vertx.core.datagram.DatagramSocket; import io.vertx.core.datagram.DatagramSocketOptions; import io.vertx.core.datagram.impl.DatagramSocketImpl; import io.vertx.core.dns.AddressResolverOptions; import io.vertx.core.dns.DnsClient; import io.vertx.core.dns.DnsClientOptions; import io.vertx.core.dns.impl.DnsClientImpl; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.impl.EventBusImpl; import io.vertx.core.eventbus.impl.EventBusInternal; import io.vertx.core.eventbus.impl.clustered.ClusteredEventBus; import io.vertx.core.file.FileSystem; import io.vertx.core.http.*; import io.vertx.core.http.impl.*; import io.vertx.core.impl.btc.BlockedThreadChecker; import io.vertx.core.net.*; import io.vertx.core.net.impl.*; import io.vertx.core.impl.transports.JDKTransport; import io.vertx.core.spi.file.FileResolver; import io.vertx.core.file.impl.FileSystemImpl; import io.vertx.core.file.impl.WindowsFileSystem; import io.vertx.core.impl.future.PromiseInternal; import io.vertx.core.impl.logging.Logger; import io.vertx.core.impl.logging.LoggerFactory; import io.vertx.core.dns.impl.DnsAddressResolverProvider; import io.vertx.core.spi.transport.Transport; import io.vertx.core.shareddata.SharedData; import io.vertx.core.shareddata.impl.SharedDataImpl; import io.vertx.core.spi.ExecutorServiceFactory; import io.vertx.core.spi.VerticleFactory; import io.vertx.core.spi.VertxThreadFactory; import io.vertx.core.spi.cluster.ClusterManager; import io.vertx.core.spi.cluster.NodeSelector; import io.vertx.core.spi.metrics.Metrics; import io.vertx.core.spi.metrics.MetricsProvider; import io.vertx.core.spi.metrics.PoolMetrics; import io.vertx.core.spi.metrics.VertxMetrics; import io.vertx.core.spi.tracing.VertxTracer; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.ref.Cleaner; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Supplier; /** * @author <a href="http://tfox.org">Tim Fox</a> */ public class VertxImpl implements VertxInternal, MetricsProvider { private static String version; /** * Default shared cleaner for Vert.x */ private static final Cleaner cleaner = Cleaner.create(); /** * Context dispatch info for context running with non vertx threads (Loom). */ static final ThreadLocal<ContextDispatch> nonVertxContextDispatch = new ThreadLocal<>(); // We need to initialize nonVertxContextDispatch before log because log may use the context on startup. // https://github.com/eclipse-vertx/vert.x/issues/4611 private static final Logger log = LoggerFactory.getLogger(VertxImpl.class); static final Object[] EMPTY_CONTEXT_LOCALS = new Object[0]; private static final String CLUSTER_MAP_NAME = "__vertx.haInfo"; private static final String NETTY_IO_RATIO_PROPERTY_NAME = "vertx.nettyIORatio"; private static final int NETTY_IO_RATIO = Integer.getInteger(NETTY_IO_RATIO_PROPERTY_NAME, 50); // Not cached for graalvm private static ThreadFactory virtualThreadFactory() { try { Class<?> builderClass = ClassLoader.getSystemClassLoader().loadClass("java.lang.Thread$Builder"); Class<?> ofVirtualClass = ClassLoader.getSystemClassLoader().loadClass("java.lang.Thread$Builder$OfVirtual"); Method ofVirtualMethod = Thread.class.getDeclaredMethod("ofVirtual"); Object builder = ofVirtualMethod.invoke(null); Method nameMethod = ofVirtualClass.getDeclaredMethod("name", String.class, long.class); Method factoryMethod = builderClass.getDeclaredMethod("factory"); builder = nameMethod.invoke(builder, "vert.x-virtual-thread-", 0L); return (ThreadFactory) factoryMethod.invoke(builder); } catch (Exception e) { return null; } } static { // Disable Netty's resource leak detection to reduce the performance overhead if not set by user // Supports both the default netty leak detection system property and the deprecated one if (System.getProperty("io.netty.leakDetection.level") == null && System.getProperty("io.netty.leakDetectionLevel") == null) { ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); } } private final FileSystem fileSystem = getFileSystem(); private final SharedData sharedData; private final VertxMetrics metrics; private final ConcurrentMap<Long, InternalTimerHandler> timeouts = new ConcurrentHashMap<>(); private final AtomicLong timeoutCounter = new AtomicLong(0); private final ClusterManager clusterManager; private final NodeSelector nodeSelector; private final DeploymentManager deploymentManager; private final VerticleManager verticleManager; private final FileResolver fileResolver; private final Map<ServerID, NetServerInternal> sharedNetServers = new HashMap<>(); private final int contextLocals; final WorkerPool workerPool; final WorkerPool internalWorkerPool; final WorkerPool virtualThreaWorkerPool; private final VertxThreadFactory threadFactory; private final ExecutorServiceFactory executorServiceFactory; private final ThreadFactory eventLoopThreadFactory; private final EventLoopGroup eventLoopGroup; private final EventLoopGroup acceptorEventLoopGroup; private final ExecutorService virtualThreadExecutor; private final BlockedThreadChecker checker; private final HostnameResolver hostnameResolver; private final AddressResolverOptions addressResolverOptions; private final EventBusInternal eventBus; private volatile HAManager haManager; private boolean closed; private volatile Handler<Throwable> exceptionHandler; private final int defaultWorkerPoolSize; private final long maxWorkerExecTime; private final TimeUnit maxWorkerExecTimeUnit; private final long maxEventLoopExecTime; private final TimeUnit maxEventLoopExecTimeUnit; private final CloseFuture closeFuture; private final Transport transport; private final VertxTracer tracer; private final ThreadLocal<WeakReference<ContextInternal>> stickyContext = new ThreadLocal<>(); private final boolean disableTCCL; private final Boolean useDaemonThread; VertxImpl(VertxOptions options, ClusterManager clusterManager, NodeSelector nodeSelector, VertxMetrics metrics, VertxTracer<?, ?> tracer, Transport transport, FileResolver fileResolver, VertxThreadFactory threadFactory, ExecutorServiceFactory executorServiceFactory) { // Sanity check if (Vertx.currentContext() != null) { log.warn("You're already on a Vert.x context, are you sure you want to create a new Vertx instance?"); } Boolean useDaemonThread = options.getUseDaemonThread(); int workerPoolSize = options.getWorkerPoolSize(); int internalBlockingPoolSize = options.getInternalBlockingPoolSize(); BlockedThreadChecker checker = new BlockedThreadChecker(options.getBlockedThreadCheckInterval(), options.getBlockedThreadCheckIntervalUnit(), options.getWarningExceptionTime(), options.getWarningExceptionTimeUnit()); long maxEventLoopExecuteTime = options.getMaxEventLoopExecuteTime(); TimeUnit maxEventLoopExecuteTimeUnit = options.getMaxEventLoopExecuteTimeUnit(); ThreadFactory acceptorEventLoopThreadFactory = createThreadFactory(threadFactory, checker, useDaemonThread, maxEventLoopExecuteTime, maxEventLoopExecuteTimeUnit, "vert.x-acceptor-thread-", false); TimeUnit maxWorkerExecuteTimeUnit = options.getMaxWorkerExecuteTimeUnit(); long maxWorkerExecuteTime = options.getMaxWorkerExecuteTime(); ThreadFactory workerThreadFactory = createThreadFactory(threadFactory, checker, useDaemonThread, maxWorkerExecuteTime, maxWorkerExecuteTimeUnit, "vert.x-worker-thread-", true); ExecutorService workerExec = executorServiceFactory.createExecutor(workerThreadFactory, workerPoolSize, workerPoolSize); PoolMetrics workerPoolMetrics = metrics != null ? metrics.createPoolMetrics("worker", "vert.x-worker-thread", options.getWorkerPoolSize()) : null; ThreadFactory internalWorkerThreadFactory = createThreadFactory(threadFactory, checker, useDaemonThread, maxWorkerExecuteTime, maxWorkerExecuteTimeUnit, "vert.x-internal-blocking-", true); ExecutorService internalWorkerExec = executorServiceFactory.createExecutor(internalWorkerThreadFactory, internalBlockingPoolSize, internalBlockingPoolSize); PoolMetrics internalBlockingPoolMetrics = metrics != null ? metrics.createPoolMetrics("worker", "vert.x-internal-blocking", internalBlockingPoolSize) : null; ThreadFactory virtualThreadFactory = virtualThreadFactory(); contextLocals = LocalSeq.get(); closeFuture = new CloseFuture(log); maxEventLoopExecTime = maxEventLoopExecuteTime; maxEventLoopExecTimeUnit = maxEventLoopExecuteTimeUnit; eventLoopThreadFactory = createThreadFactory(threadFactory, checker, useDaemonThread, maxEventLoopExecTime, maxEventLoopExecTimeUnit, "vert.x-eventloop-thread-", false); eventLoopGroup = transport.eventLoopGroup(Transport.IO_EVENT_LOOP_GROUP, options.getEventLoopPoolSize(), eventLoopThreadFactory, NETTY_IO_RATIO); // The acceptor event loop thread needs to be from a different pool otherwise can get lags in accepted connections // under a lot of load acceptorEventLoopGroup = transport.eventLoopGroup(Transport.ACCEPTOR_EVENT_LOOP_GROUP, 1, acceptorEventLoopThreadFactory, 100); virtualThreadExecutor = virtualThreadFactory != null ? new ThreadPerTaskExecutorService(virtualThreadFactory) : null; virtualThreaWorkerPool = virtualThreadFactory != null ? new WorkerPool(virtualThreadExecutor, null) : null; internalWorkerPool = new WorkerPool(internalWorkerExec, internalBlockingPoolMetrics); workerPool = new WorkerPool(workerExec, workerPoolMetrics); defaultWorkerPoolSize = options.getWorkerPoolSize(); maxWorkerExecTime = maxWorkerExecuteTime; maxWorkerExecTimeUnit = maxWorkerExecuteTimeUnit; disableTCCL = options.getDisableTCCL(); this.checker = checker; this.useDaemonThread = useDaemonThread; this.executorServiceFactory = executorServiceFactory; this.threadFactory = threadFactory; this.metrics = metrics; this.transport = transport; this.fileResolver = fileResolver; this.addressResolverOptions = options.getAddressResolverOptions(); this.hostnameResolver = new HostnameResolver(this, options.getAddressResolverOptions()); this.tracer = tracer == VertxTracer.NOOP ? null : tracer; this.clusterManager = clusterManager; this.nodeSelector = nodeSelector; this.eventBus = clusterManager != null ? new ClusteredEventBus(this, options, clusterManager, nodeSelector) : new EventBusImpl(this); this.sharedData = new SharedDataImpl(this, clusterManager); this.deploymentManager = new DeploymentManager(this); this.verticleManager = new VerticleManager(this, deploymentManager); } void init() { eventBus.start(Promise.promise()); if (metrics != null) { metrics.vertxCreated(this); } } Future<Vertx> initClustered(VertxOptions options) { nodeSelector.init(this, clusterManager); clusterManager.init(this, nodeSelector); Promise<Void> initPromise = Promise.promise(); Promise<Void> joinPromise = Promise.promise(); joinPromise.future().onComplete(ar -> { if (ar.succeeded()) { createHaManager(options, initPromise); } else { initPromise.fail(ar.cause()); } }); clusterManager.join(joinPromise); return initPromise .future() .transform(ar -> { if (ar.succeeded()) { if (metrics != null) { metrics.vertxCreated(this); } return Future.succeededFuture(this); } else { log.error("Failed to initialize clustered Vert.x", ar.cause()); return close().transform(v -> Future.failedFuture(ar.cause())); } }); } private void createHaManager(VertxOptions options, Promise<Void> initPromise) { if (options.isHAEnabled()) { this.executeBlocking(() -> { haManager = new HAManager(this, deploymentManager, verticleManager, clusterManager, clusterManager.getSyncMap(CLUSTER_MAP_NAME), options.getQuorumSize(), options.getHAGroup()); return haManager; }, false).onComplete(ar -> { if (ar.succeeded()) { startEventBus(true, initPromise); } else { initPromise.fail(ar.cause()); } }); } else { startEventBus(false, initPromise); } } private void startEventBus(boolean haEnabled, Promise<Void> initPromise) { Promise<Void> promise = Promise.promise(); eventBus.start(promise); promise.future().onComplete(ar -> { if (ar.succeeded()) { if (haEnabled) { initializeHaManager(initPromise); } else { initPromise.complete(); } } else { initPromise.fail(ar.cause()); } }); } private void initializeHaManager(Promise<Void> initPromise) { this.<Void>executeBlocking(() -> { // Init the manager (i.e register listener and check the quorum) // after the event bus has been fully started and updated its state // it will have also set the clustered changed view handler on the ha manager haManager.init(); return null; }, false).onComplete(initPromise); } /** * @return The FileSystem implementation for the OS */ protected FileSystem getFileSystem() { return Utils.isWindows() ? new WindowsFileSystem(this) : new FileSystemImpl(this); } @Override public long maxEventLoopExecTime() { return maxEventLoopExecTime; } @Override public TimeUnit maxEventLoopExecTimeUnit() { return maxEventLoopExecTimeUnit; } @Override public DatagramSocket createDatagramSocket(DatagramSocketOptions options) { CloseFuture closeFuture = new CloseFuture(log); DatagramSocketImpl so = DatagramSocketImpl.create(this, closeFuture, options); closeFuture.add(so); CloseFuture fut = resolveCloseFuture(); fut.add(closeFuture); return so; } public NetServerImpl createNetServer(NetServerOptions options) { return new NetServerImpl(this, options.copy()); } public NetClient createNetClient(NetClientOptions options) { CloseFuture fut = resolveCloseFuture(); NetClientBuilder builder = new NetClientBuilder(this, options); builder.metrics(metricsSPI() != null ? metricsSPI().createNetClientMetrics(options) : null); NetClientInternal netClient = builder.build(); fut.add(netClient); return new CleanableNetClient(netClient, cleaner); } @Override public Transport transport() { return transport; } @Override public Cleaner cleaner() { return cleaner; } @Override public boolean isNativeTransportEnabled() { return !(transport instanceof JDKTransport); } @Override public Throwable unavailableNativeTransportCause() { if (isNativeTransportEnabled()) { return null; } return transport.unavailabilityCause(); } public FileSystem fileSystem() { return fileSystem; } public SharedData sharedData() { return sharedData; } public HttpServer createHttpServer(HttpServerOptions serverOptions) { return new HttpServerImpl(this, serverOptions); } @Override public WebSocketClient createWebSocketClient(WebSocketClientOptions options) { HttpClientOptions o = new HttpClientOptions(options); o.setDefaultHost(options.getDefaultHost()); o.setDefaultPort(options.getDefaultPort()); o.setVerifyHost(options.isVerifyHost()); o.setShared(options.isShared()); o.setName(options.getName()); CloseFuture cf = resolveCloseFuture(); WebSocketClient client; Closeable closeable; if (options.isShared()) { CloseFuture closeFuture = new CloseFuture(); client = createSharedResource("__vertx.shared.webSocketClients", options.getName(), closeFuture, cf_ -> { WebSocketClientImpl impl = new WebSocketClientImpl(this, o, options); cf_.add(completion -> impl.close().onComplete(completion)); return impl; }); client = new CleanableWebSocketClient(client, cleaner, (timeout, timeunit) -> closeFuture.close()); closeable = closeFuture; } else { WebSocketClientImpl impl = new WebSocketClientImpl(this, o, options); closeable = impl; client = new CleanableWebSocketClient(impl, cleaner, impl::shutdown); } cf.add(closeable); return client; } @Override public HttpClientBuilder httpClientBuilder() { return new HttpClientBuilderInternal(this); } public EventBus eventBus() { return eventBus; } @Override public long setPeriodic(long initialDelay, long delay, Handler<Long> handler) { ContextInternal ctx = getOrCreateContext(); return scheduleTimeout(ctx.unwrap(), true, initialDelay, delay, TimeUnit.MILLISECONDS, ctx.isDeployment(), handler); } public long setTimer(long delay, Handler<Long> handler) { ContextInternal ctx = getOrCreateContext(); return scheduleTimeout(ctx, false, delay, TimeUnit.MILLISECONDS, ctx.isDeployment(), handler); } @Override public Timer timer(long delay, TimeUnit unit) { Objects.requireNonNull(unit); if (delay <= 0) { throw new IllegalArgumentException("Invalid delay: " + delay); } ContextInternal ctx = getOrCreateContext(); io.netty.util.concurrent.ScheduledFuture<Void> fut = ctx.nettyEventLoop().schedule(() -> null, delay, unit); TimerImpl promise = new TimerImpl(ctx, fut); fut.addListener(promise); return promise; } @Override public <T> PromiseInternal<T> promise() { ContextInternal context = getOrCreateContext(); return context.promise(); } public <T> PromiseInternal<T> promise(Promise<T> p) { if (p instanceof PromiseInternal) { PromiseInternal<T> promise = (PromiseInternal<T>) p; if (promise.context() != null) { return promise; } } PromiseInternal<T> promise = promise(); promise.future().onComplete(p); return promise; } public void runOnContext(Handler<Void> task) { ContextInternal context = getOrCreateContext(); context.runOnContext(task); } // The background pool is used for making blocking calls to legacy synchronous APIs public WorkerPool getWorkerPool() { return workerPool; } @Override public WorkerPool getInternalWorkerPool() { return internalWorkerPool; } public EventLoopGroup getEventLoopGroup() { return eventLoopGroup; } public EventLoopGroup getAcceptorEventLoopGroup() { return acceptorEventLoopGroup; } public ContextInternal getOrCreateContext() { ContextInternal ctx = getContext(); if (ctx == null) { // We are running embedded - Create a context ctx = createEventLoopContext(); stickyContext.set(new WeakReference<>(ctx)); } return ctx; } public Map<ServerID, NetServerInternal> sharedTcpServers() { return sharedNetServers; } @Override public boolean isMetricsEnabled() { return metrics != null; } @Override public Metrics getMetrics() { return metrics; } public boolean cancelTimer(long id) { InternalTimerHandler handler = timeouts.get(id); if (handler != null) { return handler.cancel(); } else { return false; } } private Object[] createContextLocals() { if (contextLocals == 0) { return EMPTY_CONTEXT_LOCALS; } else { return new Object[contextLocals]; } } private ContextImpl createEventLoopContext(EventLoop eventLoop, CloseFuture closeFuture, WorkerPool workerPool, Deployment deployment, ClassLoader tccl) { return new ContextImpl(this, createContextLocals(), ThreadingModel.EVENT_LOOP, eventLoop, new EventLoopExecutor(eventLoop), internalWorkerPool, workerPool != null ? workerPool : this.workerPool, new TaskQueue(), deployment, closeFuture, disableTCCL ? null : tccl); } @Override public ContextImpl createEventLoopContext(Deployment deployment, CloseFuture closeFuture, WorkerPool workerPool, ClassLoader tccl) { return createEventLoopContext(eventLoopGroup.next(), closeFuture, workerPool, deployment, tccl); } @Override public ContextImpl createEventLoopContext(EventLoop eventLoop, WorkerPool workerPool, ClassLoader tccl) { return createEventLoopContext(eventLoop, closeFuture, workerPool, null, tccl); } @Override public ContextImpl createEventLoopContext() { return createEventLoopContext(null, closeFuture, null, Thread.currentThread().getContextClassLoader()); } private ContextImpl createWorkerContext(EventLoop eventLoop, CloseFuture closeFuture, WorkerPool workerPool, Deployment deployment, ClassLoader tccl) { TaskQueue orderedTasks = new TaskQueue(); WorkerPool wp = workerPool != null ? workerPool : this.workerPool; return new ContextImpl(this, createContextLocals(), ThreadingModel.WORKER, eventLoop, new WorkerExecutor(wp, orderedTasks), internalWorkerPool, wp, orderedTasks, deployment, closeFuture, disableTCCL ? null : tccl); } @Override public ContextInternal createWorkerContext(EventLoop eventLoop, WorkerPool workerPool, ClassLoader tccl) { return createWorkerContext(eventLoop, closeFuture, workerPool, null, tccl); } @Override public ContextImpl createWorkerContext(Deployment deployment, CloseFuture closeFuture, WorkerPool workerPool, ClassLoader tccl) { return createWorkerContext(eventLoopGroup.next(), closeFuture, workerPool, deployment, tccl); } @Override public ContextImpl createWorkerContext() { return createWorkerContext(null, closeFuture, null, Thread.currentThread().getContextClassLoader()); } private ContextImpl createVirtualThreadContext(EventLoop eventLoop, CloseFuture closeFuture, Deployment deployment, ClassLoader tccl) { if (!isVirtualThreadAvailable()) { throw new IllegalStateException("This Java runtime does not support virtual threads"); } TaskQueue orderedTasks = new TaskQueue(); return new ContextImpl(this, createContextLocals(), ThreadingModel.VIRTUAL_THREAD, eventLoop, new WorkerExecutor(virtualThreaWorkerPool, orderedTasks), internalWorkerPool, virtualThreaWorkerPool, orderedTasks, deployment, closeFuture, disableTCCL ? null : tccl); } @Override public ContextImpl createVirtualThreadContext(Deployment deployment, CloseFuture closeFuture, ClassLoader tccl) { return createVirtualThreadContext(eventLoopGroup.next(), closeFuture, deployment, tccl); } @Override public ContextImpl createVirtualThreadContext(EventLoop eventLoop, ClassLoader tccl) { return createVirtualThreadContext(eventLoop, closeFuture, null, tccl); } @Override public ContextImpl createVirtualThreadContext() { return createVirtualThreadContext(null, closeFuture, Thread.currentThread().getContextClassLoader()); } @Override public DnsClient createDnsClient(int port, String host) { return createDnsClient(new DnsClientOptions().setHost(host).setPort(port)); } @Override public DnsClient createDnsClient() { return createDnsClient(new DnsClientOptions()); } @Override public DnsClient createDnsClient(DnsClientOptions options) { String host = options.getHost(); int port = options.getPort(); if (host == null || port < 0) { DnsAddressResolverProvider provider = DnsAddressResolverProvider.create(this, addressResolverOptions); InetSocketAddress address = provider.nameServerAddresses().get(0); // provide the host and port options = new DnsClientOptions(options) .setHost(address.getAddress().getHostAddress()) .setPort(address.getPort()); } return new DnsClientImpl(this, options); } private long scheduleTimeout(ContextInternal context, boolean periodic, long initialDelay, long delay, TimeUnit timeUnit, boolean addCloseHook, Handler<Long> handler) { if (delay < 1) { throw new IllegalArgumentException("Cannot schedule a timer with delay < 1 ms"); } if (initialDelay < 0) { throw new IllegalArgumentException("Cannot schedule a timer with initialDelay < 0"); } long timerId = timeoutCounter.getAndIncrement(); InternalTimerHandler task = new InternalTimerHandler(timerId, handler, periodic, context); timeouts.put(timerId, task); if (addCloseHook) { context.addCloseHook(task); } EventLoop el = context.nettyEventLoop(); if (periodic) { task.future = el.scheduleAtFixedRate(task, initialDelay, delay, timeUnit); } else { task.future = el.schedule(task, delay, timeUnit); } return task.id; } public long scheduleTimeout(ContextInternal context, boolean periodic, long delay, TimeUnit timeUnit, boolean addCloseHook, Handler<Long> handler) { return scheduleTimeout(context, periodic, delay, delay, timeUnit, addCloseHook, handler); } public ContextInternal getContext() { ContextInternal context = ContextInternal.current(); if (context != null && context.owner() == this) { return context; } else { WeakReference<ContextInternal> ref = stickyContext.get(); return ref != null ? ref.get() : null; } } public ClusterManager getClusterManager() { return clusterManager; } private Future<Void> closeClusterManager() { Future<Void> fut; if (clusterManager != null) { Promise<Void> leavePromise = getOrCreateContext().promise(); clusterManager.leave(leavePromise); fut = leavePromise.future(); } else { fut = getOrCreateContext().succeededFuture(); } return fut.transform(ar -> { if (ar.failed()) { log.error("Failed to leave cluster", ar.cause()); } return Future.succeededFuture(); }); } @Override public synchronized Future<Void> close() { // Create this promise purposely without a context because the close operation will close thread pools if (closed || eventBus == null) { // Just call the handler directly since pools shutdown return Future.succeededFuture(); } closed = true; Future<Void> fut = closeFuture .close() .transform(ar -> deploymentManager.undeployAll()); if (haManager != null) { fut = fut.transform(ar -> executeBlocking(() -> { haManager.stop(); return null; }, false)); } fut = fut .transform(ar -> hostnameResolver.close()) .transform(ar -> Future.future(h -> eventBus.close((Promise) h))) .transform(ar -> closeClusterManager()) .transform(ar -> { Promise<Void> promise = Promise.promise(); deleteCacheDirAndShutdown(promise); return promise.future(); }); Future<Void> val = fut; Promise<Void> p = Promise.promise(); val.onComplete(ar -> { eventLoopThreadFactory.newThread(() -> { if (ar.succeeded()) { p.complete(); } else { p.fail(ar.cause()); } }).start(); }); return p.future(); } @Override public Future<String> deployVerticle(String name, DeploymentOptions options) { if (options.isHa() && haManager() != null) { Promise<String> promise = getOrCreateContext().promise(); haManager().deployVerticle(name, options, promise); return promise.future(); } else { return verticleManager.deployVerticle(name, options).map(Deployment::deploymentID); } } @Override public Future<String> deployVerticle(Verticle verticle, DeploymentOptions options) { if (options.getInstances() != 1) { throw new IllegalArgumentException("Can't specify > 1 instances for already created verticle"); } return deployVerticle((Callable<Verticle>) () -> verticle, options); } @Override public Future<String> deployVerticle(Class<? extends Verticle> verticleClass, DeploymentOptions options) { return deployVerticle((Callable<Verticle>) verticleClass::newInstance, options); } @Override public Future<String> deployVerticle(Supplier<Verticle> verticleSupplier, DeploymentOptions options) { return deployVerticle((Callable<Verticle>) verticleSupplier::get, options); } private Future<String> deployVerticle(Callable<Verticle> verticleSupplier, DeploymentOptions options) { boolean closed; synchronized (this) { closed = this.closed; } if (closed) { // If we are closed use a context less future return Future.failedFuture("Vert.x closed"); } else { return deploymentManager.deployVerticle(verticleSupplier, options); } } @Override public Future<Void> undeploy(String deploymentID) { Future<Void> future; HAManager haManager = haManager(); if (haManager != null) { future = this.executeBlocking(() -> { haManager.removeFromHA(deploymentID); return null; }, false); } else { future = getOrCreateContext().succeededFuture(); } return future.compose(v -> deploymentManager.undeployVerticle(deploymentID)); } @Override public Set<String> deploymentIDs() { return deploymentManager.deployments(); } @Override public void registerVerticleFactory(VerticleFactory factory) { verticleManager.registerVerticleFactory(factory); } @Override public void unregisterVerticleFactory(VerticleFactory factory) { verticleManager.unregisterVerticleFactory(factory); } @Override public Set<VerticleFactory> verticleFactories() { return verticleManager.verticleFactories(); } @Override public boolean isClustered() { return clusterManager != null; } @Override public EventLoopGroup nettyEventLoopGroup() { return eventLoopGroup; } // For testing public void simulateKill() { if (haManager() != null) { haManager().simulateKill(); } } @Override public Deployment getDeployment(String deploymentID) { return deploymentManager.getDeployment(deploymentID); } @Override public synchronized void failoverCompleteHandler(FailoverCompleteHandler failoverCompleteHandler) { if (haManager() != null) { haManager().setFailoverCompleteHandler(failoverCompleteHandler); } } @Override public boolean isKilled() { return haManager().isKilled(); } @Override public void failDuringFailover(boolean fail) { if (haManager() != null) { haManager().failDuringFailover(fail); } } @Override public VertxMetrics metricsSPI() { return metrics; } @Override public File resolveFile(String fileName) { return fileResolver.resolveFile(fileName); } @Override public Future<InetAddress> resolveAddress(String hostname) { return hostnameResolver.resolveHostname(hostname); } @Override public HostnameResolver hostnameResolver() { return hostnameResolver; } @Override public DnsAddressResolverProvider dnsAddressResolverProvider(InetSocketAddress addr) { AddressResolverOptions options = new AddressResolverOptions(addressResolverOptions); options.setServers(Collections.singletonList(addr.getHostString() + ":" + addr.getPort())); options.setOptResourceEnabled(false); return DnsAddressResolverProvider.create(this, options); } @Override public AddressResolverGroup<InetSocketAddress> nettyAddressResolverGroup() { return hostnameResolver.nettyAddressResolverGroup(); } @Override public FileResolver fileResolver() { return fileResolver; } @Override public BlockedThreadChecker blockedThreadChecker() { return checker; } @SuppressWarnings("unchecked") private void deleteCacheDirAndShutdown(Promise<Void> promise) { executeBlockingInternal(() -> { fileResolver.close(); return null; }).onComplete(ar -> { workerPool.close(); internalWorkerPool.close(); List<WorkerPool> objects = SharedResourceHolder.clearSharedResource(this, "__vertx.shared.workerPools"); for (WorkerPool workerPool : objects) { workerPool.close(); } if (virtualThreadExecutor != null) { virtualThreadExecutor.shutdown(); try { virtualThreadExecutor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException ignore) { } } acceptorEventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() { @Override public void operationComplete(io.netty.util.concurrent.Future future) throws Exception { if (!future.isSuccess()) { log.warn("Failure in shutting down acceptor event loop group", future.cause()); } eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() { @Override public void operationComplete(io.netty.util.concurrent.Future future) throws Exception { if (!future.isSuccess()) { log.warn("Failure in shutting down event loop group", future.cause()); } if (metrics != null) { metrics.close(); } if (tracer != null) { tracer.close(); } checker.close(); eventLoopThreadFactory.newThread(promise::complete).start(); } }); } }); }); } public HAManager haManager() { return haManager; } /** * Timers are stored in the {@link #timeouts} map at creation time. * <p/> * Timers are removed from the {@link #timeouts} map when they are cancelled or are fired. The thread * removing the timer successfully owns the timer termination (i.e cancel or timer) to avoid race conditions * between timeout and cancellation. * <p/> * This class does not rely on the internal {@link #future} for the termination to handle the worker case * since the actual timer {@link #handler} execution is scheduled when the {@link #future} executes. */ class InternalTimerHandler implements Handler<Void>, Closeable, Runnable { private final Handler<Long> handler; private final boolean periodic; private final long id; private final ContextInternal context; private final AtomicBoolean disposed = new AtomicBoolean(); private volatile java.util.concurrent.Future<?> future; InternalTimerHandler(long id, Handler<Long> runnable, boolean periodic, ContextInternal context) { this.context = context; this.id = id; this.handler = runnable; this.periodic = periodic; } @Override public void run() { ContextInternal dispatcher = context; if (periodic) { dispatcher = dispatcher.duplicate(); } dispatcher.emit(this); } public void handle(Void v) { if (periodic) { if (!disposed.get()) { handler.handle(id); } } else if (disposed.compareAndSet(false, true)) { timeouts.remove(id); try { handler.handle(id); } finally { // Clean up after it's fired context.removeCloseHook(this); } } } private boolean cancel() { boolean cancelled = tryCancel(); if (cancelled) { if (context.isDeployment()) { context.removeCloseHook(this); } } return cancelled; } private boolean tryCancel() { if (disposed.compareAndSet(false, true)) { timeouts.remove(id); future.cancel(false); return true; } else { return false; } } // Called via Context close hook when Verticle is undeployed public void close(Promise<Void> completion) { tryCancel(); completion.complete(); } } @Override public WorkerExecutorImpl createSharedWorkerExecutor(String name) { return createSharedWorkerExecutor(name, defaultWorkerPoolSize); } @Override public WorkerExecutorImpl createSharedWorkerExecutor(String name, int poolSize) { return createSharedWorkerExecutor(name, poolSize, maxWorkerExecTime); } @Override public synchronized WorkerExecutorImpl createSharedWorkerExecutor(String name, int poolSize, long maxExecuteTime) { return createSharedWorkerExecutor(name, poolSize, maxExecuteTime, maxWorkerExecTimeUnit); } @Override public synchronized WorkerExecutorImpl createSharedWorkerExecutor(String name, int poolSize, long maxExecuteTime, TimeUnit maxExecuteTimeUnit) { CloseFuture execCf = new CloseFuture(); WorkerPool sharedWorkerPool = createSharedWorkerPool(execCf, name, poolSize, maxExecuteTime, maxExecuteTimeUnit); CloseFuture parentCf = resolveCloseFuture(); parentCf.add(execCf); return new WorkerExecutorImpl(this, cleaner, sharedWorkerPool); } public WorkerPool createSharedWorkerPool(String name, int poolSize, long maxExecuteTime, TimeUnit maxExecuteTimeUnit) { return createSharedWorkerPool(new CloseFuture(), name, poolSize, maxExecuteTime, maxExecuteTimeUnit); } private synchronized WorkerPool createSharedWorkerPool(CloseFuture closeFuture, String name, int poolSize, long maxExecuteTime, TimeUnit maxExecuteTimeUnit) { if (poolSize < 1) { throw new IllegalArgumentException("poolSize must be > 0"); } if (maxExecuteTime < 1) { throw new IllegalArgumentException("maxExecuteTime must be > 0"); } WorkerPool shared = createSharedResource("__vertx.shared.workerPools", name, closeFuture, cf -> { ThreadFactory workerThreadFactory = createThreadFactory(threadFactory, checker, useDaemonThread, maxExecuteTime, maxExecuteTimeUnit, name + "-", true); ExecutorService workerExec = executorServiceFactory.createExecutor(workerThreadFactory, poolSize, poolSize); PoolMetrics workerMetrics = metrics != null ? metrics.createPoolMetrics("worker", name, poolSize) : null; WorkerPool pool = new WorkerPool(workerExec, workerMetrics); cf.add(completion -> { pool.close(); completion.complete(); }); return pool; }); return new WorkerPool(shared.executor(), shared.metrics()) { @Override void close() { closeFuture.close(); } }; } @Override public WorkerPool wrapWorkerPool(ExecutorService executor) { PoolMetrics workerMetrics = metrics != null ? metrics.createPoolMetrics("worker", null, -1) : null; return new WorkerPool(executor, workerMetrics); } private static ThreadFactory createThreadFactory(VertxThreadFactory threadFactory, BlockedThreadChecker checker, Boolean useDaemonThread, long maxExecuteTime, TimeUnit maxExecuteTimeUnit, String prefix, boolean worker) { AtomicInteger threadCount = new AtomicInteger(0); return runnable -> { VertxThread thread = threadFactory.newVertxThread(runnable, prefix + threadCount.getAndIncrement(), worker, maxExecuteTime, maxExecuteTimeUnit); checker.registerThread(thread, thread.info); if (useDaemonThread != null && thread.isDaemon() != useDaemonThread) { thread.setDaemon(useDaemonThread); } return thread; }; } @Override public Vertx exceptionHandler(Handler<Throwable> handler) { exceptionHandler = handler; return this; } @Override public Handler<Throwable> exceptionHandler() { return exceptionHandler; } @Override public CloseFuture closeFuture() { return closeFuture; } @Override public VertxTracer tracer() { return tracer; } @Override public void addCloseHook(Closeable hook) { closeFuture.add(hook); } @Override public void removeCloseHook(Closeable hook) { closeFuture.remove(hook); } @Override public boolean isVirtualThreadAvailable() { return virtualThreadExecutor != null; } private CloseFuture resolveCloseFuture() { ContextInternal context = getContext(); return context != null ? context.closeFuture() : closeFuture; } /** * Execute the {@code task} disabling the thread-local association for the duration * of the execution. {@link Vertx#currentContext()} will return {@code null}, * @param task the task to execute * @throws IllegalStateException if the current thread is not a Vertx thread */ void executeIsolated(Handler<Void> task) { if (Thread.currentThread() instanceof VertxThread) { ContextInternal prev = beginDispatch(null); try { task.handle(null); } finally { endDispatch(prev); } } else { task.handle(null); } } static class ContextDispatch { ContextInternal context; ClassLoader topLevelTCCL; } /** * Begin the emission of a context event. * <p> * This is a low level interface that should not be used, instead {@link ContextInternal#dispatch(Object, io.vertx.core.Handler)} * shall be used. * * @param context the context on which the event is emitted on * @return the current context that shall be restored */ ContextInternal beginDispatch(ContextInternal context) { Thread thread = Thread.currentThread(); ContextInternal prev; if (thread instanceof VertxThread) { VertxThread vertxThread = (VertxThread) thread; prev = vertxThread.context; if (!ContextImpl.DISABLE_TIMINGS) { vertxThread.executeStart(); } vertxThread.context = context; if (!disableTCCL) { if (prev == null) { vertxThread.topLevelTCCL = Thread.currentThread().getContextClassLoader(); } if (context != null) { thread.setContextClassLoader(context.classLoader()); } } } else { prev = beginDispatch2(thread, context); } return prev; } private ContextInternal beginDispatch2(Thread thread, ContextInternal context) { ContextDispatch current = nonVertxContextDispatch.get(); ContextInternal prev; if (current != null) { prev = current.context; } else { current = new ContextDispatch(); nonVertxContextDispatch.set(current); prev = null; } current.context = context; if (!disableTCCL) { if (prev == null) { current.topLevelTCCL = Thread.currentThread().getContextClassLoader(); } thread.setContextClassLoader(context.classLoader()); } return prev; } /** * End the emission of a context task. * <p> * This is a low level interface that should not be used, instead {@link ContextInternal#dispatch(Object, io.vertx.core.Handler)} * shall be used. * * @param prev the previous context thread to restore, might be {@code null} */ void endDispatch(ContextInternal prev) { Thread thread = Thread.currentThread(); if (thread instanceof VertxThread) { VertxThread vertxThread = (VertxThread) thread; vertxThread.context = prev; if (!disableTCCL) { ClassLoader tccl; if (prev == null) { tccl = vertxThread.topLevelTCCL; vertxThread.topLevelTCCL = null; } else { tccl = prev.classLoader(); } Thread.currentThread().setContextClassLoader(tccl); } if (!ContextImpl.DISABLE_TIMINGS) { vertxThread.executeEnd(); } } else { endDispatch2(prev); } } private void endDispatch2(ContextInternal prev) { ClassLoader tccl; ContextDispatch current = nonVertxContextDispatch.get(); if (prev != null) { current.context = prev; tccl = prev.classLoader(); } else { nonVertxContextDispatch.remove(); tccl = current.topLevelTCCL; } if (!disableTCCL) { Thread.currentThread().setContextClassLoader(tccl); } } /** * Reads the version from the {@code vertx-version.txt} file. * * @return the version */ public static String version() { if (version != null) { return version; } try (InputStream is = VertxImpl.class.getClassLoader().getResourceAsStream("META-INF/vertx/vertx-version.txt")) { if (is == null) { throw new IllegalStateException("Cannot find vertx-version.txt on classpath"); } try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8).useDelimiter("\\A")) { return version = scanner.hasNext() ? scanner.next().trim() : ""; } } catch (IOException e) { throw new IllegalStateException(e.getMessage()); } }}
eclipse-vertx/vert.x
src/main/java/io/vertx/core/impl/VertxImpl.java
179,643
package com.airbnb.lottie; import android.os.Handler; import android.os.Looper; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import com.airbnb.lottie.utils.Logger; import com.airbnb.lottie.utils.LottieThreadFactory; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; /** * Helper to run asynchronous tasks with a result. * Results can be obtained with {@link #addListener(LottieListener)}. * Failures can be obtained with {@link #addFailureListener(LottieListener)}. * <p> * A task will produce a single result or a single failure. */ @SuppressWarnings("UnusedReturnValue") public class LottieTask<T> { /** * Set this to change the executor that LottieTasks are run on. This will be the executor that composition parsing and url * fetching happens on. * <p> * You may change this to run deserialization synchronously for testing. */ @SuppressWarnings("WeakerAccess") public static Executor EXECUTOR = Executors.newCachedThreadPool(new LottieThreadFactory()); /* Preserve add order. */ private final Set<LottieListener<T>> successListeners = new LinkedHashSet<>(1); private final Set<LottieListener<Throwable>> failureListeners = new LinkedHashSet<>(1); private final Handler handler = new Handler(Looper.getMainLooper()); @Nullable private volatile LottieResult<T> result = null; @RestrictTo(RestrictTo.Scope.LIBRARY) public LottieTask(Callable<LottieResult<T>> runnable) { this(runnable, false); } public LottieTask(T result) { setResult(new LottieResult<>(result)); } /** * runNow is only used for testing. */ @RestrictTo(RestrictTo.Scope.LIBRARY) LottieTask(Callable<LottieResult<T>> runnable, boolean runNow) { if (runNow) { try { setResult(runnable.call()); } catch (Throwable e) { setResult(new LottieResult<>(e)); } } else { EXECUTOR.execute(new LottieFutureTask<T>(this, runnable)); } } private void setResult(@Nullable LottieResult<T> result) { if (this.result != null) { throw new IllegalStateException("A task may only be set once."); } this.result = result; notifyListeners(); } /** * Add a task listener. If the task has completed, the listener will be called synchronously. * * @return the task for call chaining. */ public synchronized LottieTask<T> addListener(LottieListener<T> listener) { LottieResult<T> result = this.result; if (result != null && result.getValue() != null) { listener.onResult(result.getValue()); } successListeners.add(listener); return this; } /** * Remove a given task listener. The task will continue to execute so you can re-add * a listener if necessary. * * @return the task for call chaining. */ public synchronized LottieTask<T> removeListener(LottieListener<T> listener) { successListeners.remove(listener); return this; } /** * Add a task failure listener. This will only be called in the even that an exception * occurs. If an exception has already occurred, the listener will be called immediately. * * @return the task for call chaining. */ public synchronized LottieTask<T> addFailureListener(LottieListener<Throwable> listener) { LottieResult<T> result = this.result; if (result != null && result.getException() != null) { listener.onResult(result.getException()); } failureListeners.add(listener); return this; } /** * Remove a given task failure listener. The task will continue to execute so you can re-add * a listener if necessary. * * @return the task for call chaining. */ public synchronized LottieTask<T> removeFailureListener(LottieListener<Throwable> listener) { failureListeners.remove(listener); return this; } @Nullable public LottieResult<T> getResult() { return result; } private void notifyListeners() { // Listeners should be called on the main thread. if (Looper.myLooper() == Looper.getMainLooper()) { notifyListenersInternal(); } else { handler.post(this::notifyListenersInternal); } } private void notifyListenersInternal() { // Local reference in case it gets set on a background thread. LottieResult<T> result = LottieTask.this.result; if (result == null) { return; } if (result.getValue() != null) { notifySuccessListeners(result.getValue()); } else { notifyFailureListeners(result.getException()); } } private synchronized void notifySuccessListeners(T value) { // Allows listeners to remove themselves in onResult. // Otherwise we risk ConcurrentModificationException. List<LottieListener<T>> listenersCopy = new ArrayList<>(successListeners); for (LottieListener<T> l : listenersCopy) { l.onResult(value); } } private synchronized void notifyFailureListeners(Throwable e) { // Allows listeners to remove themselves in onResult. // Otherwise we risk ConcurrentModificationException. List<LottieListener<Throwable>> listenersCopy = new ArrayList<>(failureListeners); if (listenersCopy.isEmpty()) { Logger.warning("Lottie encountered an error but no failure listener was added:", e); return; } for (LottieListener<Throwable> l : listenersCopy) { l.onResult(e); } } private static class LottieFutureTask<T> extends FutureTask<LottieResult<T>> { private LottieTask<T> lottieTask; LottieFutureTask(LottieTask<T> task, Callable<LottieResult<T>> callable) { super(callable); lottieTask = task; } @Override protected void done() { try { if (isCancelled()) { // We don't need to notify and listeners if the task is cancelled. return; } try { lottieTask.setResult(get()); } catch (InterruptedException | ExecutionException e) { lottieTask.setResult(new LottieResult<>(e)); } } finally { // LottieFutureTask can be held in memory for up to 60 seconds after the task is done, which would // result in holding on to the associated LottieTask instance and leaking its listeners. To avoid // that, we clear our the reference to the LottieTask instance. // // How is LottieFutureTask held for up to 60 seconds? It's a bug in how the VM cleans up stack // local variables. When you have a loop that polls a blocking queue and assigns the result // to a local variable, after looping the local variable will still reference the previous value // until the queue returns the next result. // // Executors.newCachedThreadPool() relies on a SynchronousQueue and creates a cached thread pool // with a default keep alice of 60 seconds. After a given worker thread runs a task, that thread // will wait for up to 60 seconds for a new task to come, and while waiting it's also accidentally // keeping a reference to the previous task. // // See commit d577e728e9bccbafc707af3060ea914caa73c14f in AOSP for how that was fixed for Looper. lottieTask = null; } } } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieTask.java
179,644
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.hexagonal.domain; import static com.iluwatar.hexagonal.domain.LotteryConstants.SERVICE_BANK_ACCOUNT; import static com.iluwatar.hexagonal.domain.LotteryConstants.TICKET_PRIZE; import com.google.inject.Inject; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import com.iluwatar.hexagonal.eventlog.LotteryEventLog; import java.util.Optional; /** * Implementation for lottery service. */ public class LotteryService { private final LotteryTicketRepository repository; private final LotteryEventLog notifications; private final WireTransfers wireTransfers; /** * Constructor. */ @Inject public LotteryService(LotteryTicketRepository repository, LotteryEventLog notifications, WireTransfers wireTransfers) { this.repository = repository; this.notifications = notifications; this.wireTransfers = wireTransfers; } /** * Submit lottery ticket to participate in the lottery. */ public Optional<LotteryTicketId> submitTicket(LotteryTicket ticket) { var playerDetails = ticket.playerDetails(); var playerAccount = playerDetails.bankAccount(); var result = wireTransfers.transferFunds(TICKET_PRIZE, playerAccount, SERVICE_BANK_ACCOUNT); if (!result) { notifications.ticketSubmitError(playerDetails); return Optional.empty(); } var optional = repository.save(ticket); if (optional.isPresent()) { notifications.ticketSubmitted(playerDetails); } return optional; } /** * Check if lottery ticket has won. */ public LotteryTicketCheckResult checkTicketForPrize( LotteryTicketId id, LotteryNumbers winningNumbers ) { return LotteryUtils.checkTicketForPrize(repository, id, winningNumbers); } }
iluwatar/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryService.java
179,645
package com.airbnb.lottie.network; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; /** * The result of the operation of obtaining a Lottie animation */ public interface LottieFetchResult extends Closeable { /** * @return Is the operation successful */ boolean isSuccessful(); /** * @return Received content stream */ @NonNull InputStream bodyByteStream() throws IOException; /** * @return Type of content received */ @Nullable String contentType(); /** * @return Operation error */ @Nullable String error(); }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/network/LottieFetchResult.java
179,646
class Solution { public int kEmptySlots(int[] bulbs, int k) { int n = bulbs.length; BinaryIndexedTree tree = new BinaryIndexedTree(n); boolean[] vis = new boolean[n + 1]; for (int i = 1; i <= n; ++i) { int x = bulbs[i - 1]; tree.update(x, 1); vis[x] = true; int y = x - k - 1; if (y > 0 && vis[y] && tree.query(x - 1) - tree.query(y) == 0) { return i; } y = x + k + 1; if (y <= n && vis[y] && tree.query(y - 1) - tree.query(x) == 0) { return i; } } return -1; } } class BinaryIndexedTree { private int n; private int[] c; public BinaryIndexedTree(int n) { this.n = n; this.c = new int[n + 1]; } public void update(int x, int delta) { for (; x <= n; x += x & -x) { c[x] += delta; } } public int query(int x) { int s = 0; for (; x > 0; x -= x & -x) { s += c[x]; } return s; } }
doocs/leetcode
solution/0600-0699/0683.K Empty Slots/Solution.java
179,647
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.action.bulk; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.SparseFixedBitSet; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.core.Assertions; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.ingest.IngestService; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; /** * Manages mutations to a bulk request that arise from the application of ingest pipelines. The modifier acts as an iterator over the * documents of a bulk request, keeping a record of all dropped and failed write requests in the overall bulk operation. * Once all pipelines have been applied, the modifier is used to create a new bulk request that will be used for executing the * remaining writes. When this final bulk operation is completed, the modifier is used to combine the results with those from the * ingest service to create the final bulk response. */ final class BulkRequestModifier implements Iterator<DocWriteRequest<?>> { private static final Logger logger = LogManager.getLogger(BulkRequestModifier.class); private static final String DROPPED_OR_FAILED_ITEM_WITH_AUTO_GENERATED_ID = "auto-generated"; final BulkRequest bulkRequest; final SparseFixedBitSet failedSlots; final List<BulkItemResponse> itemResponses; final AtomicIntegerArray originalSlots; final FailureStoreDocumentConverter failureStoreDocumentConverter; volatile int currentSlot = -1; BulkRequestModifier(BulkRequest bulkRequest) { this.bulkRequest = bulkRequest; this.failedSlots = new SparseFixedBitSet(bulkRequest.requests().size()); this.itemResponses = new ArrayList<>(bulkRequest.requests().size()); this.originalSlots = new AtomicIntegerArray(bulkRequest.requests().size()); // oversize, but that's ok this.failureStoreDocumentConverter = new FailureStoreDocumentConverter(); } @Override public DocWriteRequest<?> next() { return bulkRequest.requests().get(++currentSlot); } @Override public boolean hasNext() { return (currentSlot + 1) < bulkRequest.requests().size(); } /** * Creates a new bulk request containing all documents from the original bulk request that have not been marked as failed * or dropped. Any failed or dropped documents are tracked as a side effect of this call so that they may be reflected in the * final bulk response. * * @return A new bulk request without the write operations removed during any ingest pipeline executions. */ BulkRequest getBulkRequest() { if (itemResponses.isEmpty()) { return bulkRequest; } else { BulkRequest modifiedBulkRequest = new BulkRequest(); modifiedBulkRequest.setRefreshPolicy(bulkRequest.getRefreshPolicy()); modifiedBulkRequest.waitForActiveShards(bulkRequest.waitForActiveShards()); modifiedBulkRequest.timeout(bulkRequest.timeout()); int slot = 0; List<DocWriteRequest<?>> requests = bulkRequest.requests(); for (int i = 0; i < requests.size(); i++) { DocWriteRequest<?> request = requests.get(i); if (failedSlots.get(i) == false) { modifiedBulkRequest.add(request); originalSlots.set(slot++, i); } } return modifiedBulkRequest; } } /** * If documents were dropped or failed in ingest, this method wraps the action listener that will be notified when the * updated bulk operation is completed. The wrapped listener combines the dropped and failed document results from the ingest * service with the results returned from running the remaining write operations. * * @param ingestTookInMillis Time elapsed for ingestion to be passed to final result. * @param actionListener The action listener that expects the final bulk response. * @return An action listener that combines ingest failure results with the results from writing the remaining documents. */ ActionListener<BulkResponse> wrapActionListenerIfNeeded(long ingestTookInMillis, ActionListener<BulkResponse> actionListener) { if (itemResponses.isEmpty()) { return actionListener.map( response -> new BulkResponse(response.getItems(), response.getTook().getMillis(), ingestTookInMillis) ); } else { return actionListener.map(response -> { // these items are the responses from the subsequent bulk request, their 'slots' // are not correct for this response we're building final BulkItemResponse[] bulkResponses = response.getItems(); final BulkItemResponse[] allResponses = new BulkItemResponse[bulkResponses.length + itemResponses.size()]; // the item responses are from the original request, so their slots are correct. // these are the responses for requests that failed early and were not passed on to the subsequent bulk. for (BulkItemResponse item : itemResponses) { allResponses[item.getItemId()] = item; } // use the original slots for the responses from the bulk for (int i = 0; i < bulkResponses.length; i++) { allResponses[originalSlots.get(i)] = bulkResponses[i]; } if (Assertions.ENABLED) { assertResponsesAreCorrect(bulkResponses, allResponses); } return new BulkResponse(allResponses, response.getTook().getMillis(), ingestTookInMillis); }); } } private void assertResponsesAreCorrect(BulkItemResponse[] bulkResponses, BulkItemResponse[] allResponses) { // check for an empty intersection between the ids final Set<Integer> failedIds = itemResponses.stream().map(BulkItemResponse::getItemId).collect(Collectors.toSet()); final Set<Integer> responseIds = IntStream.range(0, bulkResponses.length) .map(originalSlots::get) // resolve subsequent bulk ids back to the original slots .boxed() .collect(Collectors.toSet()); assert Sets.haveEmptyIntersection(failedIds, responseIds) : "bulk item response slots cannot have failed and been processed in the subsequent bulk request, failed ids: " + failedIds + ", response ids: " + responseIds; // check for the correct number of responses final int expectedResponseCount = bulkRequest.requests.size(); final int actualResponseCount = failedIds.size() + responseIds.size(); assert expectedResponseCount == actualResponseCount : "Expected [" + expectedResponseCount + "] responses, but found [" + actualResponseCount + "]"; // check that every response is present for (int i = 0; i < allResponses.length; i++) { assert allResponses[i] != null : "BulkItemResponse at index [" + i + "] was null"; } } /** * Mark the document at the given slot in the bulk request as having failed in the ingest service. * @param slot the slot in the bulk request to mark as failed. * @param e the failure encountered. */ synchronized void markItemAsFailed(int slot, Exception e) { final DocWriteRequest<?> docWriteRequest = bulkRequest.requests().get(slot); final String id = Objects.requireNonNullElse(docWriteRequest.id(), DROPPED_OR_FAILED_ITEM_WITH_AUTO_GENERATED_ID); // We hit a error during preprocessing a request, so we: // 1) Remember the request item slot from the bulk, so that when we're done processing all requests we know what failed // 2) Add a bulk item failure for this request // 3) Continue with the next request in the bulk. failedSlots.set(slot); BulkItemResponse.Failure failure = new BulkItemResponse.Failure(docWriteRequest.index(), id, e); itemResponses.add(BulkItemResponse.failure(slot, docWriteRequest.opType(), failure)); } /** * Mark the document at the given slot in the bulk request as having been dropped by the ingest service. * @param slot the slot in the bulk request to mark as dropped. */ synchronized void markItemAsDropped(int slot) { final DocWriteRequest<?> docWriteRequest = bulkRequest.requests().get(slot); final String id = Objects.requireNonNullElse(docWriteRequest.id(), DROPPED_OR_FAILED_ITEM_WITH_AUTO_GENERATED_ID); failedSlots.set(slot); UpdateResponse dropped = new UpdateResponse( new ShardId(docWriteRequest.index(), IndexMetadata.INDEX_UUID_NA_VALUE, 0), id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, docWriteRequest.version(), DocWriteResponse.Result.NOOP ); itemResponses.add(BulkItemResponse.success(slot, docWriteRequest.opType(), dropped)); } /** * Mark the document at the given slot in the bulk request as having failed in the ingest service. The document will be redirected * to a data stream's failure store. * @param slot the slot in the bulk request to redirect. * @param targetIndexName the index that the document was targeting at the time of failure. * @param e the failure encountered. */ public void markItemForFailureStore(int slot, String targetIndexName, Exception e) { if (DataStream.isFailureStoreFeatureFlagEnabled() == false) { // Assert false for development, but if we somehow find ourselves here, default to failure logic. assert false : "Attempting to route a failed write request type to a failure store but the failure store is not enabled! " + "This should be guarded against in TransportBulkAction#shouldStoreFailure()"; markItemAsFailed(slot, e); } else { // We get the index write request to find the source of the failed document IndexRequest indexRequest = TransportBulkAction.getIndexWriteRequest(bulkRequest.requests().get(slot)); if (indexRequest == null) { // This is unlikely to happen ever since only source oriented operations (index, create, upsert) are considered for // ingest, but if it does happen, attempt to trip an assertion. If running in production, be defensive: Mark it failed // as normal, and log the info for later debugging if needed. assert false : "Attempting to mark invalid write request type for failure store. Only IndexRequest or UpdateRequest allowed. " + "type: [" + bulkRequest.requests().get(slot).getClass().getName() + "], index: [" + targetIndexName + "]"; markItemAsFailed(slot, e); logger.debug( () -> "Attempted to redirect an invalid write operation after ingest failure - type: [" + bulkRequest.requests().get(slot).getClass().getName() + "], index: [" + targetIndexName + "]" ); } else { try { IndexRequest errorDocument = failureStoreDocumentConverter.transformFailedRequest(indexRequest, e, targetIndexName); // This is a fresh index request! We need to do some preprocessing on it. If we do not, when this is returned to // the bulk action, the action will see that it hasn't been processed by ingest yet and attempt to ingest it again. errorDocument.isPipelineResolved(true); errorDocument.setPipeline(IngestService.NOOP_PIPELINE_NAME); errorDocument.setFinalPipeline(IngestService.NOOP_PIPELINE_NAME); bulkRequest.requests.set(slot, errorDocument); } catch (IOException ioException) { // This is unlikely to happen because the conversion is so simple, but be defensive and attempt to report about it // if we need the info later. e.addSuppressed(ioException); // Prefer to return the original exception to the end user instead of this new one. logger.debug( () -> "Encountered exception while attempting to redirect a failed ingest operation: index [" + targetIndexName + "], source: [" + indexRequest.source().utf8ToString() + "]", ioException ); markItemAsFailed(slot, e); } } } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/action/bulk/BulkRequestModifier.java
179,648
package com.airbnb.lottie.network; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; import java.io.IOException; /** * Implement this interface to handle network fetching manually when animations are requested via url. By default, Lottie will use an * {@link java.net.HttpURLConnection} under the hood but this enables you to hook into your own network stack. By default, Lottie will also handle * caching the * animations but if you want to provide your own cache directory, you may implement {@link LottieNetworkCacheProvider}. * * @see com.airbnb.lottie.Lottie#initialize */ public interface LottieNetworkFetcher { @WorkerThread @NonNull LottieFetchResult fetchSync(@NonNull String url) throws IOException; }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/network/LottieNetworkFetcher.java
179,649
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.common.util; import org.apache.lucene.util.hppc.BitMixer; import org.elasticsearch.core.Releasable; /** * Base implementation for a hash table that is paged, recycles arrays and grows in-place. */ abstract class AbstractPagedHashMap implements Releasable { // Open addressing typically requires having smaller load factors compared to linked lists because // collisions may result into worse lookup performance. static final float DEFAULT_MAX_LOAD_FACTOR = 0.6f; static long hash(long value) { // Don't use the value directly. Under some cases eg dates, it could be that the low bits don't carry much value and we would like // all bits of the hash to carry as much value return BitMixer.mix64(value); } final BigArrays bigArrays; final float maxLoadFactor; long size, maxSize; long mask; AbstractPagedHashMap(long capacity, float maxLoadFactor, BigArrays bigArrays) { if (capacity < 0) { throw new IllegalArgumentException("capacity must be >= 0"); } if (maxLoadFactor <= 0 || maxLoadFactor >= 1) { throw new IllegalArgumentException("maxLoadFactor must be > 0 and < 1"); } this.bigArrays = bigArrays; this.maxLoadFactor = maxLoadFactor; long buckets = 1L + (long) (capacity / maxLoadFactor); buckets = Math.max(1, Long.highestOneBit(buckets - 1) << 1); // next power of two assert buckets == Long.highestOneBit(buckets); maxSize = (long) (buckets * maxLoadFactor); assert maxSize >= capacity; size = 0; mask = buckets - 1; } /** * Return the number of allocated slots to store this hash table. */ public long capacity() { return mask + 1; } /** * Return the number of longs in this hash table. */ public long size() { return size; } static long slot(long hash, long mask) { return hash & mask; } static long nextSlot(long curSlot, long mask) { return (curSlot + 1) & mask; // linear probing } /** Resize to the given capacity. */ protected abstract void resize(long capacity); protected abstract boolean used(long bucket); /** Remove the entry at the given index and add it back */ protected abstract void removeAndAdd(long index); protected final void grow() { // The difference of this implementation of grow() compared to standard hash tables is that we are growing in-place, which makes // the re-mapping of keys to slots a bit more tricky. assert size == maxSize; final long prevSize = size; final long buckets = capacity(); // Resize arrays final long newBuckets = buckets << 1; assert newBuckets == Long.highestOneBit(newBuckets) : newBuckets; // power of 2 resize(newBuckets); mask = newBuckets - 1; // First let's remap in-place: most data will be put in its final position directly for (long i = 0; i < buckets; ++i) { if (used(i)) { removeAndAdd(i); } } // The only entries which have not been put in their final position in the previous loop are those that were stored in a slot that // is < slot(key, mask). This only happens when slot(key, mask) returned a slot that was close to the end of the array and collision // resolution has put it back in the first slots. This time, collision resolution will have put them at the beginning of the newly // allocated slots. Let's re-add them to make sure they are in the right slot. This 2nd loop will typically exit very early. for (long i = buckets; i < newBuckets; ++i) { if (used(i)) { removeAndAdd(i); // add it back } else { break; } } assert size == prevSize; maxSize = (long) (newBuckets * maxLoadFactor); assert size < maxSize; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/common/util/AbstractPagedHashMap.java
179,651
package edu.stanford.nlp.io; import java.io.IOException; import java.io.Reader; /** * A Lexer interface to be used with {@link edu.stanford.nlp.process.LexerTokenizer}. You can put a {@link Reader} inside * a Lexer with the {@link #yyreset} method. An easy way to build classes implementing this * interface is with JFlex (http://jflex.de). Just make sure to include the following in the * JFlex source file * * In the <i>Options and Macros</i> section of the source file, include * * %class JFlexDummyLexer<br> * %standalone<br> * %unicode<br> * %int<br> * <br> * %implements edu.stanford.nlp.io.Lexer<br> * <br> * %{<br> * public void pushBack(int n) {<br> * yypushback(n);<br> * }<br> * <br> * public int getYYEOF() {<br> * return YYEOF;<br> * }<br> * %}<br> * * Alternatively, you can customize your own lexer and get lots of * flexibility out. * * @author Roger Levy */ public interface Lexer { int ACCEPT = 1; int IGNORE = 0; /** * Gets the next token from input and returns an integer value * signalling what to do with the token. */ int yylex() throws IOException; /** * returns the matched input text region */ String yytext(); /** * Pushes back {@code length} character positions in the * lexer. Conventionally used to push back exactly one token. */ void pushBack(int length); /** * returns value for YYEOF */ int getYYEOF(); /** * put a {@link Reader} inside the Lexer. */ void yyreset(Reader r) throws IOException; }
stanfordnlp/CoreNLP
src/edu/stanford/nlp/io/Lexer.java
179,654
package com.airbnb.lottie; /** * Register this listener via {@link LottieCompositionFactory#registerLottieTaskIdleListener(LottieTaskIdleListener)}. * * Can be used to create an espresso idle resource. Refer to {@link LottieCompositionFactory#registerLottieTaskIdleListener(LottieTaskIdleListener)} * for more information. */ public interface LottieTaskIdleListener { void onIdleChanged(boolean idle); }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/LottieTaskIdleListener.java
179,659
package org.thoughtcrime.securesms.jobs; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.annimon.stream.Stream; import net.zetetic.database.sqlcipher.SQLiteDatabase; import org.signal.core.util.Stopwatch; import org.signal.core.util.logging.Log; import org.signal.libsignal.protocol.InvalidKeyException; import org.thoughtcrime.securesms.crypto.UnidentifiedAccessUtil; import org.thoughtcrime.securesms.database.RecipientTable; import org.thoughtcrime.securesms.database.SignalDatabase; import org.thoughtcrime.securesms.database.UnknownStorageIdTable; import org.thoughtcrime.securesms.database.model.RecipientRecord; import org.thoughtcrime.securesms.dependencies.ApplicationDependencies; import org.thoughtcrime.securesms.jobmanager.Job; import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint; import org.thoughtcrime.securesms.keyvalue.SignalStore; import org.thoughtcrime.securesms.migrations.StorageServiceMigrationJob; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.storage.AccountRecordProcessor; import org.thoughtcrime.securesms.storage.ContactRecordProcessor; import org.thoughtcrime.securesms.storage.GroupV1RecordProcessor; import org.thoughtcrime.securesms.storage.GroupV2RecordProcessor; import org.thoughtcrime.securesms.storage.StorageRecordUpdate; import org.thoughtcrime.securesms.storage.StorageSyncHelper; import org.thoughtcrime.securesms.storage.StorageSyncHelper.IdDifferenceResult; import org.thoughtcrime.securesms.storage.StorageSyncHelper.WriteOperationResult; import org.thoughtcrime.securesms.storage.StorageSyncModels; import org.thoughtcrime.securesms.storage.StorageSyncValidations; import org.thoughtcrime.securesms.storage.StoryDistributionListRecordProcessor; import org.thoughtcrime.securesms.transport.RetryLaterException; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.signalservice.api.SignalServiceAccountManager; import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException; import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage; import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage; import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException; import org.whispersystems.signalservice.api.storage.SignalAccountRecord; import org.whispersystems.signalservice.api.storage.SignalContactRecord; import org.whispersystems.signalservice.api.storage.SignalGroupV1Record; import org.whispersystems.signalservice.api.storage.SignalGroupV2Record; import org.whispersystems.signalservice.api.storage.SignalRecord; import org.whispersystems.signalservice.api.storage.SignalStorageManifest; import org.whispersystems.signalservice.api.storage.SignalStorageRecord; import org.whispersystems.signalservice.api.storage.SignalStoryDistributionListRecord; import org.whispersystems.signalservice.api.storage.StorageId; import org.whispersystems.signalservice.api.storage.StorageKey; import org.whispersystems.signalservice.internal.push.SyncMessage; import org.whispersystems.signalservice.internal.storage.protos.ManifestRecord; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Does a full sync of our local storage state with the remote storage state. Will write any pending * local changes and resolve any conflicts with remote storage. * * This should be performed whenever a change is made locally, or whenever we want to retrieve * changes that have been made remotely. * * == Important Implementation Notes == * * - We want to use a transaction to guarantee atomicity of our changes and to prevent other threads * from writing while the sync is happening. But that means we also need to be very careful with * what happens inside the transaction. Namely, we *cannot* perform network activity inside the * transaction. * * - This puts us in a funny situation where we have to get remote data, begin a transaction to * resolve the sync, and then end the transaction (and therefore commit our changes) *before* * we write the data remotely. Normally, this would be dangerous, as our view of the data could * fall out of sync if the network request fails. However, because of how the sync works, as long * as we don't update our local manifest version until after the network request succeeds, it * should all sort itself out in the retry. Because if our network request failed, then we * wouldn't have written all of the new IDs, and we'll still see a bunch of remote-only IDs that * we'll merge with local data to generate another equally-valid set of remote changes. * * * == Technical Overview == * * The Storage Service is, at it's core, a dumb key-value store. It stores various types of records, * each of which is given an ID. It also stores a manifest, which has the complete list of all IDs. * The manifest has a monotonically-increasing version associated with it. Whenever a change is * made to the stored data, you upload a new manifest with the updated ID set. * * An ID corresponds to an unchanging snapshot of a record. That is, if the underlying record is * updated, that update is performed by deleting the old ID/record and inserting a new one. This * makes it easy to determine what's changed in a given version of a manifest -- simply diff the * list of IDs in the manifest with the list of IDs we have locally. * * So, at it's core, syncing isn't all that complicated. * - If we see the remote manifest version is newer than ours, then we grab the manifest and compute * the diff in IDs. * - Then, we fetch the actual records that correspond to the remote-only IDs. * - Afterwards, we take those records and merge them into our local data store. * - Next, we assume that our local state represents the most up-to-date information, and so we * calculate and write a change set that represents the diff between our state and the remote * state. * - Finally, handle any possible records in our "unknown ID store" that might have become known to us. * * Of course, you'll notice that there's a lot of code to support that goal. That's mostly because * converting local data into a format that can be compared with, merged, and eventually written * back to both local and remote data stores is tiresome. There's also lots of general bookkeeping, * error handling, cleanup scenarios, logging, etc. * * == Syncing a new field on an existing record == * * - Add the field the the respective proto * - Update the respective model (i.e. {@link SignalContactRecord}) * - Add getters * - Update the builder * - Update {@link SignalRecord#describeDiff(SignalRecord)}. * - Update the respective record processor (i.e {@link ContactRecordProcessor}). You need to make * sure that you're: * - Merging the attributes, likely preferring remote * - Adding to doParamsMatch() * - Adding the parameter to the builder chain when creating a merged model * - Update builder usage in StorageSyncModels * - Handle the new data when writing to the local storage * (i.e. {@link RecipientTable#applyStorageSyncContactUpdate(StorageRecordUpdate)}). * - Make sure that whenever you change the field in the UI, we rotate the storageId for that row * and call {@link StorageSyncHelper#scheduleSyncForDataChange()}. * - If you're syncing a field that was otherwise already present in the UI, you'll probably want * to enqueue a {@link StorageServiceMigrationJob} as an app migration to make sure it gets * synced. */ public class StorageSyncJob extends BaseJob { public static final String KEY = "StorageSyncJobV2"; public static final String QUEUE_KEY = "StorageSyncingJobs"; private static final String TAG = Log.tag(StorageSyncJob.class); public StorageSyncJob() { this(new Parameters.Builder().addConstraint(NetworkConstraint.KEY) .setQueue(QUEUE_KEY) .setMaxInstancesForFactory(2) .setLifespan(TimeUnit.DAYS.toMillis(1)) .setMaxAttempts(3) .build()); } private StorageSyncJob(@NonNull Parameters parameters) { super(parameters); } @Override public @Nullable byte[] serialize() { return null; } @Override public @NonNull String getFactoryKey() { return KEY; } @Override protected void onRun() throws IOException, RetryLaterException, UntrustedIdentityException { if (!SignalStore.svr().hasPin() && !SignalStore.svr().hasOptedOut()) { Log.i(TAG, "Doesn't have a PIN. Skipping."); return; } if (!SignalStore.account().isRegistered()) { Log.i(TAG, "Not registered. Skipping."); return; } if (!Recipient.self().getHasE164() || !Recipient.self().getHasServiceId()) { Log.w(TAG, "Missing E164 or ACI!"); return; } if (SignalStore.internalValues().storageServiceDisabled()) { Log.w(TAG, "Storage service has been manually disabled. Skipping."); return; } try { boolean needsMultiDeviceSync = performSync(); if (TextSecurePreferences.isMultiDevice(context) && needsMultiDeviceSync) { ApplicationDependencies.getJobManager().add(new MultiDeviceStorageSyncRequestJob()); } SignalStore.storageService().onSyncCompleted(); } catch (InvalidKeyException e) { if (SignalStore.account().isPrimaryDevice()) { Log.w(TAG, "Failed to decrypt remote storage! Force-pushing and syncing the storage key to linked devices.", e); ApplicationDependencies.getJobManager().startChain(new MultiDeviceKeysUpdateJob()) .then(new StorageForcePushJob()) .then(new MultiDeviceStorageSyncRequestJob()) .enqueue(); } else { Log.w(TAG, "Failed to decrypt remote storage! Requesting new keys from primary.", e); SignalStore.storageService().clearStorageKeyFromPrimary(); ApplicationDependencies.getSignalServiceMessageSender().sendSyncMessage(SignalServiceSyncMessage.forRequest(RequestMessage.forType(SyncMessage.Request.Type.KEYS)), UnidentifiedAccessUtil.getAccessForSync(context)); } } } @Override protected boolean onShouldRetry(@NonNull Exception e) { return e instanceof PushNetworkException || e instanceof RetryLaterException; } @Override public void onFailure() { } private boolean performSync() throws IOException, RetryLaterException, InvalidKeyException { final Stopwatch stopwatch = new Stopwatch("StorageSync"); final SQLiteDatabase db = SignalDatabase.getRawDatabase(); final SignalServiceAccountManager accountManager = ApplicationDependencies.getSignalServiceAccountManager(); final UnknownStorageIdTable storageIdDatabase = SignalDatabase.unknownStorageIds(); final StorageKey storageServiceKey = SignalStore.storageService().getOrCreateStorageKey(); final SignalStorageManifest localManifest = SignalStore.storageService().getManifest(); final SignalStorageManifest remoteManifest = accountManager.getStorageManifestIfDifferentVersion(storageServiceKey, localManifest.getVersion()).orElse(localManifest); stopwatch.split("remote-manifest"); Recipient self = freshSelf(); boolean needsMultiDeviceSync = false; boolean needsForcePush = false; if (self.getStorageId() == null) { Log.w(TAG, "No storageId for self. Generating."); SignalDatabase.recipients().updateStorageId(self.getId(), StorageSyncHelper.generateKey()); self = freshSelf(); } Log.i(TAG, "Our version: " + localManifest.getVersionString() + ", their version: " + remoteManifest.getVersionString()); if (remoteManifest.getVersion() > localManifest.getVersion()) { Log.i(TAG, "[Remote Sync] Newer manifest version found!"); List<StorageId> localStorageIdsBeforeMerge = getAllLocalStorageIds(self); IdDifferenceResult idDifference = StorageSyncHelper.findIdDifference(remoteManifest.getStorageIds(), localStorageIdsBeforeMerge); if (idDifference.hasTypeMismatches() && SignalStore.account().isPrimaryDevice()) { Log.w(TAG, "[Remote Sync] Found type mismatches in the ID sets! Scheduling a force push after this sync completes."); needsForcePush = true; } Log.i(TAG, "[Remote Sync] Pre-Merge ID Difference :: " + idDifference); if (idDifference.getLocalOnlyIds().size() > 0) { int updated = SignalDatabase.recipients().removeStorageIdsFromLocalOnlyUnregisteredRecipients(idDifference.getLocalOnlyIds()); if (updated > 0) { Log.w(TAG, "Found " + updated + " records that were deleted remotely but only marked unregistered locally. Removed those from local store. Recalculating diff."); localStorageIdsBeforeMerge = getAllLocalStorageIds(self); idDifference = StorageSyncHelper.findIdDifference(remoteManifest.getStorageIds(), localStorageIdsBeforeMerge); } } stopwatch.split("remote-id-diff"); if (!idDifference.isEmpty()) { Log.i(TAG, "[Remote Sync] Retrieving records for key difference."); List<SignalStorageRecord> remoteOnlyRecords = accountManager.readStorageRecords(storageServiceKey, idDifference.getRemoteOnlyIds()); stopwatch.split("remote-records"); if (remoteOnlyRecords.size() != idDifference.getRemoteOnlyIds().size()) { Log.w(TAG, "[Remote Sync] Could not find all remote-only records! Requested: " + idDifference.getRemoteOnlyIds().size() + ", Found: " + remoteOnlyRecords.size() + ". These stragglers should naturally get deleted during the sync."); } StorageRecordCollection remoteOnly = new StorageRecordCollection(remoteOnlyRecords); db.beginTransaction(); try { Log.i(TAG, "[Remote Sync] Remote-Only :: Contacts: " + remoteOnly.contacts.size() + ", GV1: " + remoteOnly.gv1.size() + ", GV2: " + remoteOnly.gv2.size() + ", Account: " + remoteOnly.account.size() + ", DLists: " + remoteOnly.storyDistributionLists.size()); processKnownRecords(context, remoteOnly); List<SignalStorageRecord> unknownInserts = remoteOnly.unknown; List<StorageId> unknownDeletes = Stream.of(idDifference.getLocalOnlyIds()).filter(StorageId::isUnknown).toList(); Log.i(TAG, "[Remote Sync] Unknowns :: " + unknownInserts.size() + " inserts, " + unknownDeletes.size() + " deletes"); storageIdDatabase.insert(unknownInserts); storageIdDatabase.delete(unknownDeletes); db.setTransactionSuccessful(); } finally { db.endTransaction(); ApplicationDependencies.getDatabaseObserver().notifyConversationListListeners(); stopwatch.split("remote-merge-transaction"); } } else { Log.i(TAG, "[Remote Sync] Remote version was newer, but there were no remote-only IDs."); } } else if (remoteManifest.getVersion() < localManifest.getVersion()) { Log.w(TAG, "[Remote Sync] Remote version was older. User might have switched accounts."); } if (remoteManifest != localManifest) { Log.i(TAG, "[Remote Sync] Saved new manifest. Now at version: " + remoteManifest.getVersionString()); SignalStore.storageService().setManifest(remoteManifest); } Log.i(TAG, "We are up-to-date with the remote storage state."); final WriteOperationResult remoteWriteOperation; db.beginTransaction(); try { self = freshSelf(); int removedUnregistered = SignalDatabase.recipients().removeStorageIdsFromOldUnregisteredRecipients(System.currentTimeMillis()); if (removedUnregistered > 0) { Log.i(TAG, "Removed " + removedUnregistered + " recipients from storage service that have been unregistered for longer than 30 days."); } List<StorageId> localStorageIds = getAllLocalStorageIds(self); IdDifferenceResult idDifference = StorageSyncHelper.findIdDifference(remoteManifest.getStorageIds(), localStorageIds); List<SignalStorageRecord> remoteInserts = buildLocalStorageRecords(context, self, idDifference.getLocalOnlyIds().stream().filter(it -> !it.isUnknown()).collect(Collectors.toList())); List<byte[]> remoteDeletes = Stream.of(idDifference.getRemoteOnlyIds()).map(StorageId::getRaw).toList(); Log.i(TAG, "ID Difference :: " + idDifference); remoteWriteOperation = new WriteOperationResult(new SignalStorageManifest(remoteManifest.getVersion() + 1, SignalStore.account().getDeviceId(), localStorageIds), remoteInserts, remoteDeletes); db.setTransactionSuccessful(); } finally { db.endTransaction(); stopwatch.split("local-data-transaction"); } if (!remoteWriteOperation.isEmpty()) { Log.i(TAG, "We have something to write remotely."); Log.i(TAG, "WriteOperationResult :: " + remoteWriteOperation); StorageSyncValidations.validate(remoteWriteOperation, remoteManifest, needsForcePush, self); Optional<SignalStorageManifest> conflict = accountManager.writeStorageRecords(storageServiceKey, remoteWriteOperation.getManifest(), remoteWriteOperation.getInserts(), remoteWriteOperation.getDeletes()); if (conflict.isPresent()) { Log.w(TAG, "Hit a conflict when trying to resolve the conflict! Retrying."); throw new RetryLaterException(); } Log.i(TAG, "Saved new manifest. Now at version: " + remoteWriteOperation.getManifest().getVersionString()); SignalStore.storageService().setManifest(remoteWriteOperation.getManifest()); stopwatch.split("remote-write"); needsMultiDeviceSync = true; } else { Log.i(TAG, "No remote writes needed. Still at version: " + remoteManifest.getVersionString()); } List<Integer> knownTypes = getKnownTypes(); List<StorageId> knownUnknownIds = SignalDatabase.unknownStorageIds().getAllWithTypes(knownTypes); if (knownUnknownIds.size() > 0) { Log.i(TAG, "We have " + knownUnknownIds.size() + " unknown records that we can now process."); List<SignalStorageRecord> remote = accountManager.readStorageRecords(storageServiceKey, knownUnknownIds); StorageRecordCollection records = new StorageRecordCollection(remote); Log.i(TAG, "Found " + remote.size() + " of the known-unknowns remotely."); db.beginTransaction(); try { processKnownRecords(context, records); SignalDatabase.unknownStorageIds().getAllWithTypes(knownTypes); db.setTransactionSuccessful(); } finally { db.endTransaction(); } Log.i(TAG, "Enqueueing a storage sync job to handle any possible merges after applying unknown records."); ApplicationDependencies.getJobManager().add(new StorageSyncJob()); } stopwatch.split("known-unknowns"); if (needsForcePush && SignalStore.account().isPrimaryDevice()) { Log.w(TAG, "Scheduling a force push."); ApplicationDependencies.getJobManager().add(new StorageForcePushJob()); } stopwatch.stop(TAG); return needsMultiDeviceSync; } private static void processKnownRecords(@NonNull Context context, @NonNull StorageRecordCollection records) throws IOException { new ContactRecordProcessor().process(records.contacts, StorageSyncHelper.KEY_GENERATOR); new GroupV1RecordProcessor(context).process(records.gv1, StorageSyncHelper.KEY_GENERATOR); new GroupV2RecordProcessor(context).process(records.gv2, StorageSyncHelper.KEY_GENERATOR); new AccountRecordProcessor(context, freshSelf()).process(records.account, StorageSyncHelper.KEY_GENERATOR); new StoryDistributionListRecordProcessor().process(records.storyDistributionLists, StorageSyncHelper.KEY_GENERATOR); } private static @NonNull List<StorageId> getAllLocalStorageIds(@NonNull Recipient self) { return Util.concatenatedList(SignalDatabase.recipients().getContactStorageSyncIds(), Collections.singletonList(StorageId.forAccount(self.getStorageId())), SignalDatabase.unknownStorageIds().getAllUnknownIds()); } private static @NonNull List<SignalStorageRecord> buildLocalStorageRecords(@NonNull Context context, @NonNull Recipient self, @NonNull Collection<StorageId> ids) { if (ids.isEmpty()) { return Collections.emptyList(); } RecipientTable recipientTable = SignalDatabase.recipients(); UnknownStorageIdTable storageIdDatabase = SignalDatabase.unknownStorageIds(); List<SignalStorageRecord> records = new ArrayList<>(ids.size()); for (StorageId id : ids) { ManifestRecord.Identifier.Type type = ManifestRecord.Identifier.Type.fromValue(id.getType()); if (type == null) { type = ManifestRecord.Identifier.Type.UNKNOWN; } switch (type) { case CONTACT: case GROUPV1: case GROUPV2: RecipientRecord settings = recipientTable.getByStorageId(id.getRaw()); if (settings != null) { if (settings.getRecipientType() == RecipientTable.RecipientType.GV2 && settings.getSyncExtras().getGroupMasterKey() == null) { throw new MissingGv2MasterKeyError(); } else { records.add(StorageSyncModels.localToRemoteRecord(settings)); } } else { throw new MissingRecipientModelError("Missing local recipient model! Type: " + id.getType()); } break; case ACCOUNT: if (!Arrays.equals(self.getStorageId(), id.getRaw())) { throw new AssertionError("Local storage ID doesn't match self!"); } records.add(StorageSyncHelper.buildAccountRecord(context, self)); break; case STORY_DISTRIBUTION_LIST: RecipientRecord record = recipientTable.getByStorageId(id.getRaw()); if (record != null) { if (record.getDistributionListId() != null) { records.add(StorageSyncModels.localToRemoteRecord(record)); } else { throw new MissingRecipientModelError("Missing local recipient model (no DistributionListId)! Type: " + id.getType()); } } else { throw new MissingRecipientModelError("Missing local recipient model! Type: " + id.getType()); } break; default: SignalStorageRecord unknown = storageIdDatabase.getById(id.getRaw()); if (unknown != null) { records.add(unknown); } else { throw new MissingUnknownModelError("Missing local unknown model! Type: " + id.getType()); } break; } } return records; } private static @NonNull Recipient freshSelf() { Recipient.self().live().refresh(); return Recipient.self(); } private static List<Integer> getKnownTypes() { return Arrays.stream(ManifestRecord.Identifier.Type.values()) .filter(it -> !it.equals(ManifestRecord.Identifier.Type.UNKNOWN)) .map(ManifestRecord.Identifier.Type::getValue) .collect(Collectors.toList()); } private static final class StorageRecordCollection { final List<SignalContactRecord> contacts = new LinkedList<>(); final List<SignalGroupV1Record> gv1 = new LinkedList<>(); final List<SignalGroupV2Record> gv2 = new LinkedList<>(); final List<SignalAccountRecord> account = new LinkedList<>(); final List<SignalStorageRecord> unknown = new LinkedList<>(); final List<SignalStoryDistributionListRecord> storyDistributionLists = new LinkedList<>(); StorageRecordCollection(Collection<SignalStorageRecord> records) { for (SignalStorageRecord record : records) { if (record.getContact().isPresent()) { contacts.add(record.getContact().get()); } else if (record.getGroupV1().isPresent()) { gv1.add(record.getGroupV1().get()); } else if (record.getGroupV2().isPresent()) { gv2.add(record.getGroupV2().get()); } else if (record.getAccount().isPresent()) { account.add(record.getAccount().get()); } else if (record.getStoryDistributionList().isPresent()) { storyDistributionLists.add(record.getStoryDistributionList().get()); } else if (record.getId().isUnknown()) { unknown.add(record); } else { Log.w(TAG, "Bad record! Type is a known value (" + record.getId().getType() + "), but doesn't have a matching inner record. Dropping it."); } } } } private static final class MissingGv2MasterKeyError extends Error {} private static final class MissingRecipientModelError extends Error { public MissingRecipientModelError(String message) { super(message); } } private static final class MissingUnknownModelError extends Error { public MissingUnknownModelError(String message) { super(message); } } public static final class Factory implements Job.Factory<StorageSyncJob> { @Override public @NonNull StorageSyncJob create(@NonNull Parameters parameters, @Nullable byte[] serializedData) { return new StorageSyncJob(parameters); } } }
signalapp/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/jobs/StorageSyncJob.java
179,661
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.hexagonal.domain; import com.google.common.base.Joiner; import java.security.SecureRandom; import java.util.Collections; import java.util.HashSet; import java.util.PrimitiveIterator; import java.util.Set; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Value object representing lottery numbers. This lottery uses sets of 4 numbers. The numbers must * be unique and between 1 and 20. */ @EqualsAndHashCode @ToString public class LotteryNumbers { private final Set<Integer> numbers; public static final int MIN_NUMBER = 1; public static final int MAX_NUMBER = 20; public static final int NUM_NUMBERS = 4; /** * Constructor. Creates random lottery numbers. */ private LotteryNumbers() { numbers = new HashSet<>(); generateRandomNumbers(); } /** * Constructor. Uses given numbers. */ private LotteryNumbers(Set<Integer> givenNumbers) { numbers = new HashSet<>(); numbers.addAll(givenNumbers); } /** * Creates a random lottery number. * * @return random LotteryNumbers */ public static LotteryNumbers createRandom() { return new LotteryNumbers(); } /** * Creates lottery number from given set of numbers. * * @return given LotteryNumbers */ public static LotteryNumbers create(Set<Integer> givenNumbers) { return new LotteryNumbers(givenNumbers); } /** * Get numbers. * * @return lottery numbers */ public Set<Integer> getNumbers() { return Collections.unmodifiableSet(numbers); } /** * Get numbers as string. * * @return numbers as comma separated string */ public String getNumbersAsString() { return Joiner.on(',').join(numbers); } /** * Generates 4 unique random numbers between 1-20 into numbers set. */ private void generateRandomNumbers() { numbers.clear(); var generator = new RandomNumberGenerator(MIN_NUMBER, MAX_NUMBER); while (numbers.size() < NUM_NUMBERS) { var num = generator.nextInt(); numbers.add(num); } } /** * Helper class for generating random numbers. */ private static class RandomNumberGenerator { private final PrimitiveIterator.OfInt randomIterator; /** * Initialize a new random number generator that generates random numbers in the range [min, * max]. * * @param min the min value (inclusive) * @param max the max value (inclusive) */ public RandomNumberGenerator(int min, int max) { randomIterator = new SecureRandom().ints(min, max + 1).iterator(); } /** * Gets next random integer in [min, max] range. * * @return a random number in the range (min, max) */ public int nextInt() { return randomIterator.nextInt(); } } }
smedals/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryNumbers.java
179,663
package com.airbnb.lottie.model.layer; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.LottieImageAsset; import com.airbnb.lottie.LottieProperty; import com.airbnb.lottie.animation.LPaint; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation; import com.airbnb.lottie.utils.Utils; import com.airbnb.lottie.value.LottieValueCallback; public class ImageLayer extends BaseLayer { private final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); private final Rect src = new Rect(); private final Rect dst = new Rect(); @Nullable private final LottieImageAsset lottieImageAsset; @Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation; @Nullable private BaseKeyframeAnimation<Bitmap, Bitmap> imageAnimation; ImageLayer(LottieDrawable lottieDrawable, Layer layerModel) { super(lottieDrawable, layerModel); lottieImageAsset = lottieDrawable.getLottieImageAssetForId(layerModel.getRefId()); } @Override public void drawLayer(@NonNull Canvas canvas, Matrix parentMatrix, int parentAlpha) { Bitmap bitmap = getBitmap(); if (bitmap == null || bitmap.isRecycled() || lottieImageAsset == null) { return; } float density = Utils.dpScale(); paint.setAlpha(parentAlpha); if (colorFilterAnimation != null) { paint.setColorFilter(colorFilterAnimation.getValue()); } canvas.save(); canvas.concat(parentMatrix); src.set(0, 0, bitmap.getWidth(), bitmap.getHeight()); if (lottieDrawable.getMaintainOriginalImageBounds()) { dst.set(0, 0, (int) (lottieImageAsset.getWidth() * density), (int) (lottieImageAsset.getHeight() * density)); } else { dst.set(0, 0, (int) (bitmap.getWidth() * density), (int) (bitmap.getHeight() * density)); } canvas.drawBitmap(bitmap, src, dst, paint); canvas.restore(); } @Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) { super.getBounds(outBounds, parentMatrix, applyParents); if (lottieImageAsset != null) { float scale = Utils.dpScale(); outBounds.set(0, 0, lottieImageAsset.getWidth() * scale, lottieImageAsset.getHeight() * scale); boundsMatrix.mapRect(outBounds); } } @Nullable private Bitmap getBitmap() { if (imageAnimation != null) { Bitmap callbackBitmap = imageAnimation.getValue(); if (callbackBitmap != null) { return callbackBitmap; } } String refId = layerModel.getRefId(); Bitmap bitmapFromDrawable = lottieDrawable.getBitmapForId(refId); if (bitmapFromDrawable != null) { return bitmapFromDrawable; } LottieImageAsset asset = this.lottieImageAsset; if (asset != null) { return asset.getBitmap(); } return null; } @SuppressWarnings("SingleStatementInBlock") @Override public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) { super.addValueCallback(property, callback); if (property == LottieProperty.COLOR_FILTER) { if (callback == null) { colorFilterAnimation = null; } else { //noinspection unchecked colorFilterAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback); } } else if (property == LottieProperty.IMAGE) { if (callback == null) { imageAnimation = null; } else { //noinspection unchecked imageAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Bitmap>) callback); } } } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/model/layer/ImageLayer.java
179,668
/** * Copyright (c) 2013-2024 Nikita Koksharov * * 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.redisson.cluster; import org.redisson.misc.RedisURI; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import static org.redisson.connection.MasterSlaveConnectionManager.MAX_SLOT; /** * * @author Nikita Koksharov * */ public class ClusterPartition { public enum Type {MASTER, SLAVE} private Type type = Type.MASTER; private final String nodeId; private boolean masterFail; private RedisURI masterAddress; private final Set<RedisURI> slaveAddresses = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Set<RedisURI> failedSlaves = Collections.newSetFromMap(new ConcurrentHashMap<>()); private BitSet slots; private Set<ClusterSlotRange> slotRanges = Collections.emptySet(); private ClusterPartition parent; public ClusterPartition(String nodeId) { super(); this.nodeId = nodeId; } public ClusterPartition getParent() { return parent; } public void setParent(ClusterPartition parent) { this.parent = parent; } public void setType(Type type) { this.type = type; } public Type getType() { return type; } public String getNodeId() { return nodeId; } public void setMasterFail(boolean masterFail) { this.masterFail = masterFail; } public boolean isMasterFail() { return masterFail; } public void updateSlotRanges(Set<ClusterSlotRange> ranges, BitSet slots) { this.slotRanges = ranges; this.slots = slots; } public void setSlotRanges(Set<ClusterSlotRange> ranges) { slots = new BitSet(MAX_SLOT); for (ClusterSlotRange clusterSlotRange : ranges) { slots.set(clusterSlotRange.getStartSlot(), clusterSlotRange.getEndSlot() + 1); } slotRanges = ranges; } public Set<ClusterSlotRange> getSlotRanges() { return Collections.unmodifiableSet(slotRanges); } public Iterable<Integer> getSlots() { return slots.stream()::iterator; } public BitSet slots() { return slots; } public BitSet copySlots() { return (BitSet) slots.clone(); } public boolean hasSlot(int slot) { return slots.get(slot); } public int getSlotsAmount() { return slots.cardinality(); } public RedisURI getMasterAddress() { return masterAddress; } public void setMasterAddress(RedisURI masterAddress) { this.masterAddress = masterAddress; } public void addFailedSlaveAddress(RedisURI address) { failedSlaves.add(address); } public Set<RedisURI> getFailedSlaveAddresses() { return Collections.unmodifiableSet(failedSlaves); } public void removeFailedSlaveAddress(RedisURI uri) { failedSlaves.remove(uri); } public void addSlaveAddress(RedisURI address) { slaveAddresses.add(address); } public Set<RedisURI> getSlaveAddresses() { return Collections.unmodifiableSet(slaveAddresses); } public void removeSlaveAddress(RedisURI uri) { slaveAddresses.remove(uri); failedSlaves.remove(uri); } @Override public int hashCode() { return Objects.hash(nodeId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterPartition that = (ClusterPartition) o; return Objects.equals(nodeId, that.nodeId); } @Override public String toString() { return "ClusterPartition [nodeId=" + nodeId + ", masterFail=" + masterFail + ", masterAddress=" + masterAddress + ", slaveAddresses=" + slaveAddresses + ", failedSlaves=" + failedSlaves + ", slotRanges=" + slotRanges + "]"; } }
redisson/redisson
redisson/src/main/java/org/redisson/cluster/ClusterPartition.java
179,669
package com.airbnb.lottie.animation.content; import static com.airbnb.lottie.utils.MiscUtils.clamp; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import androidx.annotation.Nullable; import androidx.core.graphics.PaintCompat; import com.airbnb.lottie.L; import com.airbnb.lottie.LottieDrawable; import com.airbnb.lottie.LottieProperty; import com.airbnb.lottie.animation.LPaint; import com.airbnb.lottie.animation.keyframe.BaseKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ColorKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.DropShadowKeyframeAnimation; import com.airbnb.lottie.animation.keyframe.ValueCallbackKeyframeAnimation; import com.airbnb.lottie.model.KeyPath; import com.airbnb.lottie.model.content.ShapeFill; import com.airbnb.lottie.model.layer.BaseLayer; import com.airbnb.lottie.utils.MiscUtils; import com.airbnb.lottie.value.LottieValueCallback; import java.util.ArrayList; import java.util.List; public class FillContent implements DrawingContent, BaseKeyframeAnimation.AnimationListener, KeyPathElementContent { private final Path path = new Path(); private final Paint paint = new LPaint(Paint.ANTI_ALIAS_FLAG); private final BaseLayer layer; private final String name; private final boolean hidden; private final List<PathContent> paths = new ArrayList<>(); private final BaseKeyframeAnimation<Integer, Integer> colorAnimation; private final BaseKeyframeAnimation<Integer, Integer> opacityAnimation; @Nullable private BaseKeyframeAnimation<ColorFilter, ColorFilter> colorFilterAnimation; private final LottieDrawable lottieDrawable; @Nullable private BaseKeyframeAnimation<Float, Float> blurAnimation; float blurMaskFilterRadius; @Nullable private DropShadowKeyframeAnimation dropShadowAnimation; public FillContent(final LottieDrawable lottieDrawable, BaseLayer layer, ShapeFill fill) { this.layer = layer; name = fill.getName(); hidden = fill.isHidden(); this.lottieDrawable = lottieDrawable; if (layer.getBlurEffect() != null) { blurAnimation = layer.getBlurEffect().getBlurriness().createAnimation(); blurAnimation.addUpdateListener(this); layer.addAnimation(blurAnimation); } if (layer.getDropShadowEffect() != null) { dropShadowAnimation = new DropShadowKeyframeAnimation(this, layer, layer.getDropShadowEffect()); } if (fill.getColor() == null || fill.getOpacity() == null) { colorAnimation = null; opacityAnimation = null; return; } PaintCompat.setBlendMode(paint, layer.getBlendMode().toNativeBlendMode()); path.setFillType(fill.getFillType()); colorAnimation = fill.getColor().createAnimation(); colorAnimation.addUpdateListener(this); layer.addAnimation(colorAnimation); opacityAnimation = fill.getOpacity().createAnimation(); opacityAnimation.addUpdateListener(this); layer.addAnimation(opacityAnimation); } @Override public void onValueChanged() { lottieDrawable.invalidateSelf(); } @Override public void setContents(List<Content> contentsBefore, List<Content> contentsAfter) { for (int i = 0; i < contentsAfter.size(); i++) { Content content = contentsAfter.get(i); if (content instanceof PathContent) { paths.add((PathContent) content); } } } @Override public String getName() { return name; } @Override public void draw(Canvas canvas, Matrix parentMatrix, int parentAlpha) { if (hidden) { return; } if (L.isTraceEnabled()) { L.beginSection("FillContent#draw"); } int color = ((ColorKeyframeAnimation) this.colorAnimation).getIntValue(); int alpha = (int) ((parentAlpha / 255f * opacityAnimation.getValue() / 100f) * 255); paint.setColor((clamp(alpha, 0, 255) << 24) | (color & 0xFFFFFF)); if (colorFilterAnimation != null) { paint.setColorFilter(colorFilterAnimation.getValue()); } if (blurAnimation != null) { float blurRadius = blurAnimation.getValue(); if (blurRadius == 0f) { paint.setMaskFilter(null); } else if (blurRadius != blurMaskFilterRadius) { BlurMaskFilter blur = layer.getBlurMaskFilter(blurRadius); paint.setMaskFilter(blur); } blurMaskFilterRadius = blurRadius; } if (dropShadowAnimation != null) { dropShadowAnimation.applyTo(paint); } path.reset(); for (int i = 0; i < paths.size(); i++) { path.addPath(paths.get(i).getPath(), parentMatrix); } canvas.drawPath(path, paint); if (L.isTraceEnabled()) { L.endSection("FillContent#draw"); } } @Override public void getBounds(RectF outBounds, Matrix parentMatrix, boolean applyParents) { path.reset(); for (int i = 0; i < paths.size(); i++) { this.path.addPath(paths.get(i).getPath(), parentMatrix); } path.computeBounds(outBounds, false); // Add padding to account for rounding errors. outBounds.set( outBounds.left - 1, outBounds.top - 1, outBounds.right + 1, outBounds.bottom + 1 ); } @Override public void resolveKeyPath( KeyPath keyPath, int depth, List<KeyPath> accumulator, KeyPath currentPartialKeyPath) { MiscUtils.resolveKeyPath(keyPath, depth, accumulator, currentPartialKeyPath, this); } @SuppressWarnings("unchecked") @Override public <T> void addValueCallback(T property, @Nullable LottieValueCallback<T> callback) { if (property == LottieProperty.COLOR) { colorAnimation.setValueCallback((LottieValueCallback<Integer>) callback); } else if (property == LottieProperty.OPACITY) { opacityAnimation.setValueCallback((LottieValueCallback<Integer>) callback); } else if (property == LottieProperty.COLOR_FILTER) { if (colorFilterAnimation != null) { layer.removeAnimation(colorFilterAnimation); } if (callback == null) { colorFilterAnimation = null; } else { colorFilterAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<ColorFilter>) callback); colorFilterAnimation.addUpdateListener(this); layer.addAnimation(colorFilterAnimation); } } else if (property == LottieProperty.BLUR_RADIUS) { if (blurAnimation != null) { blurAnimation.setValueCallback((LottieValueCallback<Float>) callback); } else { blurAnimation = new ValueCallbackKeyframeAnimation<>((LottieValueCallback<Float>) callback); blurAnimation.addUpdateListener(this); layer.addAnimation(blurAnimation); } } else if (property == LottieProperty.DROP_SHADOW_COLOR && dropShadowAnimation != null) { dropShadowAnimation.setColorCallback((LottieValueCallback<Integer>) callback); } else if (property == LottieProperty.DROP_SHADOW_OPACITY && dropShadowAnimation != null) { dropShadowAnimation.setOpacityCallback((LottieValueCallback<Float>) callback); } else if (property == LottieProperty.DROP_SHADOW_DIRECTION && dropShadowAnimation != null) { dropShadowAnimation.setDirectionCallback((LottieValueCallback<Float>) callback); } else if (property == LottieProperty.DROP_SHADOW_DISTANCE && dropShadowAnimation != null) { dropShadowAnimation.setDistanceCallback((LottieValueCallback<Float>) callback); } else if (property == LottieProperty.DROP_SHADOW_RADIUS && dropShadowAnimation != null) { dropShadowAnimation.setRadiusCallback((LottieValueCallback<Float>) callback); } } }
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/animation/content/FillContent.java
179,671
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.hexagonal.service; import com.iluwatar.hexagonal.banking.WireTransfers; import com.iluwatar.hexagonal.domain.LotteryNumbers; import com.iluwatar.hexagonal.domain.LotteryService; import com.iluwatar.hexagonal.domain.LotteryTicket; import com.iluwatar.hexagonal.domain.LotteryTicketCheckResult; import com.iluwatar.hexagonal.domain.LotteryTicketId; import com.iluwatar.hexagonal.domain.PlayerDetails; import java.util.Arrays; import java.util.Scanner; import java.util.stream.Collectors; import org.slf4j.Logger; /** * Console implementation for lottery console service. */ public class LotteryConsoleServiceImpl implements LotteryConsoleService { private final Logger logger; /** * Constructor. */ public LotteryConsoleServiceImpl(Logger logger) { this.logger = logger; } @Override public void checkTicket(LotteryService service, Scanner scanner) { logger.info("What is the ID of the lottery ticket?"); var id = readString(scanner); logger.info("Give the 4 comma separated winning numbers?"); var numbers = readString(scanner); try { var winningNumbers = Arrays.stream(numbers.split(",")) .map(Integer::parseInt) .limit(4) .collect(Collectors.toSet()); final var lotteryTicketId = new LotteryTicketId(Integer.parseInt(id)); final var lotteryNumbers = LotteryNumbers.create(winningNumbers); var result = service.checkTicketForPrize(lotteryTicketId, lotteryNumbers); if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.WIN_PRIZE)) { logger.info("Congratulations! The lottery ticket has won!"); } else if (result.getResult().equals(LotteryTicketCheckResult.CheckResult.NO_PRIZE)) { logger.info("Unfortunately the lottery ticket did not win."); } else { logger.info("Such lottery ticket has not been submitted."); } } catch (Exception e) { logger.info("Failed checking the lottery ticket - please try again."); } } @Override public void submitTicket(LotteryService service, Scanner scanner) { logger.info("What is your email address?"); var email = readString(scanner); logger.info("What is your bank account number?"); var account = readString(scanner); logger.info("What is your phone number?"); var phone = readString(scanner); var details = new PlayerDetails(email, account, phone); logger.info("Give 4 comma separated lottery numbers?"); var numbers = readString(scanner); try { var chosen = Arrays.stream(numbers.split(",")) .map(Integer::parseInt) .collect(Collectors.toSet()); var lotteryNumbers = LotteryNumbers.create(chosen); var lotteryTicket = new LotteryTicket(new LotteryTicketId(), details, lotteryNumbers); service.submitTicket(lotteryTicket).ifPresentOrElse( (id) -> logger.info("Submitted lottery ticket with id: {}", id), () -> logger.info("Failed submitting lottery ticket - please try again.") ); } catch (Exception e) { logger.info("Failed submitting lottery ticket - please try again."); } } @Override public void addFundsToLotteryAccount(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); var account = readString(scanner); logger.info("How many credits do you want to deposit?"); var amount = readString(scanner); bank.setFunds(account, Integer.parseInt(amount)); logger.info("The account {} now has {} credits.", account, bank.getFunds(account)); } @Override public void queryLotteryAccountFunds(WireTransfers bank, Scanner scanner) { logger.info("What is the account number?"); var account = readString(scanner); logger.info("The account {} has {} credits.", account, bank.getFunds(account)); } private String readString(Scanner scanner) { logger.info("> "); return scanner.next(); } }
smedals/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/service/LotteryConsoleServiceImpl.java
179,672
/** * Copyright (c) 2013-2024 Nikita Koksharov * * 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.redisson.connection; import org.redisson.client.RedisClient; import org.redisson.misc.RedisURI; import java.util.Objects; /** * * @author Nikita Koksharov * */ public class NodeSource { public enum Redirect {MOVED, ASK} private Integer slot; private RedisURI addr; private RedisClient redisClient; private Redirect redirect; private MasterSlaveEntry entry; public NodeSource(NodeSource nodeSource, RedisClient redisClient) { this.slot = nodeSource.slot; this.addr = nodeSource.addr; this.redisClient = redisClient; this.redirect = nodeSource.getRedirect(); this.entry = nodeSource.getEntry(); } public NodeSource(MasterSlaveEntry entry) { this.entry = entry; } public NodeSource(Integer slot) { this.slot = slot; } public NodeSource(MasterSlaveEntry entry, RedisClient redisClient) { this.entry = entry; this.redisClient = redisClient; } public NodeSource(RedisClient redisClient) { this.redisClient = redisClient; } public NodeSource(Integer slot, RedisClient redisClient) { this.slot = slot; this.redisClient = redisClient; } public NodeSource(Integer slot, RedisURI addr, Redirect redirect) { this.slot = slot; this.addr = addr; this.redirect = redirect; } public MasterSlaveEntry getEntry() { return entry; } public Redirect getRedirect() { return redirect; } public Integer getSlot() { return slot; } public RedisClient getRedisClient() { return redisClient; } public RedisURI getAddr() { return addr; } @Override public String toString() { return "NodeSource [slot=" + slot + ", addr=" + addr + ", redisClient=" + redisClient + ", redirect=" + redirect + ", entry=" + entry + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeSource that = (NodeSource) o; return Objects.equals(slot, that.slot) && Objects.equals(addr, that.addr) && Objects.equals(redisClient, that.redisClient) && redirect == that.redirect && Objects.equals(entry, that.entry); } @Override public int hashCode() { return Objects.hash(slot, addr, redisClient, redirect, entry); } }
redisson/redisson
redisson/src/main/java/org/redisson/connection/NodeSource.java
179,673
/* * Copyright (c) 2011-2023 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.impl; import java.util.concurrent.atomic.AtomicInteger; /** * @author <a href="mailto:[email protected]">Julien Viet</a> */ class LocalSeq { // 0 : reserved slot for local context map private static final AtomicInteger seq = new AtomicInteger(1); /** * Hook for testing purposes */ static void reset() { seq.set((1)); } static int get() { return seq.get(); } static int next() { return seq.getAndIncrement(); } }
eclipse-vertx/vert.x
src/main/java/io/vertx/core/impl/LocalSeq.java
179,675
/* * 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.kafka.streams.state; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.internals.ApiUtils; import org.apache.kafka.streams.kstream.Windowed; import org.apache.kafka.streams.processor.StateStore; import java.time.Instant; import static org.apache.kafka.streams.internals.ApiUtils.prepareMillisCheckFailMsgPrefix; /** * Interface for storing the aggregated values of fixed-size time windows. * <p> * Note, that the stores' physical key type is {@link Windowed Windowed&lt;K&gt;}. * * @param <K> Type of keys * @param <V> Type of values */ public interface WindowStore<K, V> extends StateStore, ReadOnlyWindowStore<K, V> { /** * Put a key-value pair into the window with given window start timestamp * <p> * If serialized value bytes are null it is interpreted as delete. Note that deletes will be * ignored in the case of an underlying store that retains duplicates. * * @param key The key to associate the value to * @param value The value; can be null * @param windowStartTimestamp The timestamp of the beginning of the window to put the key/value into * @throws InvalidStateStoreException if the store is not initialized * @throws NullPointerException if the given key is {@code null} */ void put(K key, V value, long windowStartTimestamp); /** * Get all the key-value pairs with the given key and the time range from all the existing windows. * <p> * This iterator must be closed after use. * <p> * The time range is inclusive and applies to the starting timestamp of the window. * For example, if we have the following windows: * <pre> * +-------------------------------+ * | key | start time | end time | * +-------+------------+----------+ * | A | 10 | 20 | * +-------+------------+----------+ * | A | 15 | 25 | * +-------+------------+----------+ * | A | 20 | 30 | * +-------+------------+----------+ * | A | 25 | 35 | * +-------------------------------- * </pre> * And we call {@code store.fetch("A", 10, 20)} then the results will contain the first * three windows from the table above, i.e., all those where 10 &lt;= start time &lt;= 20. * <p> * For each key, the iterator guarantees ordering of windows, starting from the oldest/earliest * available window to the newest/latest window. * * @param key the key to fetch * @param timeFrom time range start (inclusive) * @param timeTo time range end (inclusive) * @return an iterator over key-value pairs {@code <timestamp, value>} * @throws InvalidStateStoreException if the store is not initialized * @throws NullPointerException if the given key is {@code null} */ // WindowStore keeps a long-based implementation of ReadOnlyWindowStore#fetch Instant-based // if super#fetch is removed, keep this implementation as it serves PAPI Stores. WindowStoreIterator<V> fetch(K key, long timeFrom, long timeTo); @Override default WindowStoreIterator<V> fetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return fetch( key, ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } default WindowStoreIterator<V> backwardFetch(final K key, final long timeFrom, final long timeTo) { throw new UnsupportedOperationException(); } @Override default WindowStoreIterator<V> backwardFetch(final K key, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return backwardFetch( key, ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } /** * Get all the key-value pairs in the given key range and time range from all the existing windows. * <p> * This iterator must be closed after use. * * @param keyFrom the first key in the range * A null value indicates a starting position from the first element in the store. * @param keyTo the last key in the range * A null value indicates that the range ends with the last element in the store. * @param timeFrom time range start (inclusive) * @param timeTo time range end (inclusive) * @return an iterator over windowed key-value pairs {@code <Windowed<K>, value>} * @throws InvalidStateStoreException if the store is not initialized */ // WindowStore keeps a long-based implementation of ReadOnlyWindowStore#fetch Instant-based // if super#fetch is removed, keep this implementation as it serves PAPI Stores. KeyValueIterator<Windowed<K>, V> fetch(K keyFrom, K keyTo, long timeFrom, long timeTo); @Override default KeyValueIterator<Windowed<K>, V> fetch(final K keyFrom, final K keyTo, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return fetch( keyFrom, keyTo, ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } default KeyValueIterator<Windowed<K>, V> backwardFetch(final K keyFrom, final K keyTo, final long timeFrom, final long timeTo) { throw new UnsupportedOperationException(); } @Override default KeyValueIterator<Windowed<K>, V> backwardFetch(final K keyFrom, final K keyTo, final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return backwardFetch( keyFrom, keyTo, ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } /** * Gets all the key-value pairs that belong to the windows within in the given time range. * * @param timeFrom the beginning of the time slot from which to search (inclusive) * @param timeTo the end of the time slot from which to search (inclusive) * @return an iterator over windowed key-value pairs {@code <Windowed<K>, value>} * @throws InvalidStateStoreException if the store is not initialized */ // WindowStore keeps a long-based implementation of ReadOnlyWindowStore#fetch Instant-based // if super#fetch is removed, keep this implementation as it serves PAPI Stores. KeyValueIterator<Windowed<K>, V> fetchAll(long timeFrom, long timeTo); @Override default KeyValueIterator<Windowed<K>, V> fetchAll(final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return fetchAll( ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } default KeyValueIterator<Windowed<K>, V> backwardFetchAll(final long timeFrom, final long timeTo) { throw new UnsupportedOperationException(); } @Override default KeyValueIterator<Windowed<K>, V> backwardFetchAll(final Instant timeFrom, final Instant timeTo) throws IllegalArgumentException { return backwardFetchAll( ApiUtils.validateMillisecondInstant(timeFrom, prepareMillisCheckFailMsgPrefix(timeFrom, "timeFrom")), ApiUtils.validateMillisecondInstant(timeTo, prepareMillisCheckFailMsgPrefix(timeTo, "timeTo"))); } }
apache/kafka
streams/src/main/java/org/apache/kafka/streams/state/WindowStore.java
179,676
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ml.job.config; import org.elasticsearch.ResourceAlreadyExistsException; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.cluster.SimpleDiffable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.logging.DeprecationCategory; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.TimeValue; import org.elasticsearch.xcontent.ObjectParser; import org.elasticsearch.xcontent.ObjectParser.ValueType; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xpack.core.common.time.TimeUtils; import org.elasticsearch.xpack.core.ml.MlConfigVersion; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.core.ml.job.messages.Messages; import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndexFields; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts; import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper; import org.elasticsearch.xpack.core.ml.utils.MlStrings; import org.elasticsearch.xpack.core.ml.utils.ToXContentParams; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import static org.elasticsearch.xpack.core.ml.job.messages.Messages.JOB_CONFIG_DATAFEED_CONFIG_JOB_ID_MISMATCH; import static org.elasticsearch.xpack.core.ml.utils.ToXContentParams.EXCLUDE_GENERATED; /** * This class represents a configured and created Job. The creation time is set * to the time the object was constructed and the finished time and last * data time fields are {@code null} until the job has seen some data or it is * finished respectively. */ public class Job implements SimpleDiffable<Job>, Writeable, ToXContentObject { public static final String TYPE = "job"; public static final String ANOMALY_DETECTOR_JOB_TYPE = "anomaly_detector"; private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(Job.class); /* * Field names used in serialization */ public static final ParseField ID = new ParseField("job_id"); public static final ParseField JOB_TYPE = new ParseField("job_type"); public static final ParseField JOB_VERSION = new ParseField("job_version"); public static final ParseField GROUPS = new ParseField("groups"); public static final ParseField ANALYSIS_CONFIG = AnalysisConfig.ANALYSIS_CONFIG; public static final ParseField ANALYSIS_LIMITS = new ParseField("analysis_limits"); public static final ParseField CREATE_TIME = new ParseField("create_time"); public static final ParseField CUSTOM_SETTINGS = new ParseField("custom_settings"); public static final ParseField DATA_DESCRIPTION = new ParseField("data_description"); public static final ParseField DESCRIPTION = new ParseField("description"); public static final ParseField FINISHED_TIME = new ParseField("finished_time"); public static final ParseField MODEL_PLOT_CONFIG = new ParseField("model_plot_config"); public static final ParseField RENORMALIZATION_WINDOW_DAYS = new ParseField("renormalization_window_days"); public static final ParseField BACKGROUND_PERSIST_INTERVAL = new ParseField("background_persist_interval"); public static final ParseField MODEL_SNAPSHOT_RETENTION_DAYS = new ParseField("model_snapshot_retention_days"); public static final ParseField DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS = new ParseField("daily_model_snapshot_retention_after_days"); public static final ParseField RESULTS_RETENTION_DAYS = new ParseField("results_retention_days"); public static final ParseField MODEL_SNAPSHOT_ID = new ParseField("model_snapshot_id"); public static final ParseField MODEL_SNAPSHOT_MIN_VERSION = new ParseField("model_snapshot_min_version"); public static final ParseField RESULTS_INDEX_NAME = new ParseField("results_index_name"); public static final ParseField DELETING = new ParseField("deleting"); public static final ParseField ALLOW_LAZY_OPEN = new ParseField("allow_lazy_open"); public static final ParseField BLOCKED = new ParseField("blocked"); public static final ParseField DATAFEED_CONFIG = new ParseField("datafeed_config"); // Used for QueryPage public static final ParseField RESULTS_FIELD = new ParseField("jobs"); // These parsers follow the pattern that metadata is parsed leniently (to allow for enhancements), whilst config is parsed strictly public static final ObjectParser<Builder, Void> LENIENT_PARSER = createParser(true, true); // Use the REST request parser to parse a job passed to the API, to disallow setting internal fields. public static final ObjectParser<Builder, Void> REST_REQUEST_PARSER = createParser(false, false); public static final TimeValue MIN_BACKGROUND_PERSIST_INTERVAL = TimeValue.timeValueHours(1); /** * This includes the overhead of thread stacks and data structures that the program might use that * are not instrumented. (For the <code>autodetect</code> process categorization is not instrumented, * and the <code>normalize</code> process is not instrumented at all.) But this overhead does NOT * include the memory used by loading the executable code. */ public static final ByteSizeValue PROCESS_MEMORY_OVERHEAD = ByteSizeValue.ofMb(10); public static final long DEFAULT_MODEL_SNAPSHOT_RETENTION_DAYS = 10; public static final long DEFAULT_DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS = 1; private static ObjectParser<Builder, Void> createParser(boolean allowInternalFields, boolean ignoreUnknownFields) { ObjectParser<Builder, Void> parser = new ObjectParser<>("job_details", ignoreUnknownFields, Builder::new); parser.declareString(Builder::setId, ID); parser.declareStringArray(Builder::setGroups, GROUPS); parser.declareStringOrNull(Builder::setDescription, DESCRIPTION); parser.declareObject( Builder::setAnalysisConfig, ignoreUnknownFields ? AnalysisConfig.LENIENT_PARSER : AnalysisConfig.STRICT_PARSER, ANALYSIS_CONFIG ); parser.declareObject( Builder::setAnalysisLimits, ignoreUnknownFields ? AnalysisLimits.LENIENT_PARSER : AnalysisLimits.STRICT_PARSER, ANALYSIS_LIMITS ); parser.declareObject( Builder::setDataDescription, ignoreUnknownFields ? DataDescription.LENIENT_PARSER : DataDescription.STRICT_PARSER, DATA_DESCRIPTION ); parser.declareObject( Builder::setModelPlotConfig, ignoreUnknownFields ? ModelPlotConfig.LENIENT_PARSER : ModelPlotConfig.STRICT_PARSER, MODEL_PLOT_CONFIG ); parser.declareLong(Builder::setRenormalizationWindowDays, RENORMALIZATION_WINDOW_DAYS); parser.declareString( (builder, val) -> builder.setBackgroundPersistInterval( TimeValue.parseTimeValue(val, BACKGROUND_PERSIST_INTERVAL.getPreferredName()) ), BACKGROUND_PERSIST_INTERVAL ); parser.declareLong(Builder::setResultsRetentionDays, RESULTS_RETENTION_DAYS); parser.declareLong(Builder::setModelSnapshotRetentionDays, MODEL_SNAPSHOT_RETENTION_DAYS); parser.declareLong(Builder::setDailyModelSnapshotRetentionAfterDays, DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS); parser.declareField(Builder::setCustomSettings, (p, c) -> p.mapOrdered(), CUSTOM_SETTINGS, ValueType.OBJECT); parser.declareString(Builder::setResultsIndexName, RESULTS_INDEX_NAME); parser.declareBoolean(Builder::setAllowLazyOpen, ALLOW_LAZY_OPEN); parser.declareObject( Builder::setDatafeed, ignoreUnknownFields ? DatafeedConfig.LENIENT_PARSER : DatafeedConfig.STRICT_PARSER, DATAFEED_CONFIG ); if (allowInternalFields) { parser.declareString(Builder::setJobType, JOB_TYPE); parser.declareString(Builder::setJobVersion, JOB_VERSION); parser.declareField( Builder::setCreateTime, p -> TimeUtils.parseTimeField(p, CREATE_TIME.getPreferredName()), CREATE_TIME, ValueType.VALUE ); parser.declareField( Builder::setFinishedTime, p -> TimeUtils.parseTimeField(p, FINISHED_TIME.getPreferredName()), FINISHED_TIME, ValueType.VALUE ); parser.declareStringOrNull(Builder::setModelSnapshotId, MODEL_SNAPSHOT_ID); parser.declareStringOrNull(Builder::setModelSnapshotMinVersion, MODEL_SNAPSHOT_MIN_VERSION); parser.declareBoolean(Builder::setDeleting, DELETING); parser.declareObject(Builder::setBlocked, ignoreUnknownFields ? Blocked.LENIENT_PARSER : Blocked.STRICT_PARSER, BLOCKED); } return parser; } private final String jobId; private final String jobType; /** * The version when the job was created. * Will be null for versions before 5.5. */ @Nullable private final MlConfigVersion jobVersion; private final List<String> groups; private final String description; // TODO: Use java.time for the Dates here: x-pack-elasticsearch#829 private final Date createTime; private final Date finishedTime; private final AnalysisConfig analysisConfig; private final AnalysisLimits analysisLimits; private final DataDescription dataDescription; private final ModelPlotConfig modelPlotConfig; private final Long renormalizationWindowDays; private final TimeValue backgroundPersistInterval; private final Long modelSnapshotRetentionDays; private final Long dailyModelSnapshotRetentionAfterDays; private final Long resultsRetentionDays; private final Map<String, Object> customSettings; private final String modelSnapshotId; private final MlConfigVersion modelSnapshotMinVersion; private final String resultsIndexName; private final boolean deleting; private final boolean allowLazyOpen; private final Blocked blocked; private final DatafeedConfig datafeedConfig; private Job( String jobId, String jobType, MlConfigVersion jobVersion, List<String> groups, String description, Date createTime, Date finishedTime, AnalysisConfig analysisConfig, AnalysisLimits analysisLimits, DataDescription dataDescription, ModelPlotConfig modelPlotConfig, Long renormalizationWindowDays, TimeValue backgroundPersistInterval, Long modelSnapshotRetentionDays, Long dailyModelSnapshotRetentionAfterDays, Long resultsRetentionDays, Map<String, Object> customSettings, String modelSnapshotId, MlConfigVersion modelSnapshotMinVersion, String resultsIndexName, boolean deleting, boolean allowLazyOpen, Blocked blocked, DatafeedConfig datafeedConfig ) { this.jobId = jobId; this.jobType = jobType; this.jobVersion = jobVersion; this.groups = Collections.unmodifiableList(groups); this.description = description; this.createTime = createTime; this.finishedTime = finishedTime; this.analysisConfig = analysisConfig; this.analysisLimits = analysisLimits; this.dataDescription = dataDescription; this.modelPlotConfig = modelPlotConfig; this.renormalizationWindowDays = renormalizationWindowDays; this.backgroundPersistInterval = backgroundPersistInterval; this.modelSnapshotRetentionDays = modelSnapshotRetentionDays; this.dailyModelSnapshotRetentionAfterDays = dailyModelSnapshotRetentionAfterDays; this.resultsRetentionDays = resultsRetentionDays; this.customSettings = customSettings == null ? null : Collections.unmodifiableMap(customSettings); this.modelSnapshotId = modelSnapshotId; this.modelSnapshotMinVersion = modelSnapshotMinVersion; this.resultsIndexName = resultsIndexName; this.allowLazyOpen = allowLazyOpen; if (deleting == false && blocked.getReason() == Blocked.Reason.DELETE) { this.deleting = true; } else { this.deleting = deleting; } if (deleting && blocked.getReason() != Blocked.Reason.DELETE) { this.blocked = new Blocked(Blocked.Reason.DELETE, null); } else { this.blocked = blocked; } this.datafeedConfig = datafeedConfig; } public Job(StreamInput in) throws IOException { jobId = in.readString(); jobType = in.readString(); jobVersion = in.readBoolean() ? MlConfigVersion.readVersion(in) : null; groups = in.readCollectionAsImmutableList(StreamInput::readString); description = in.readOptionalString(); createTime = new Date(in.readVLong()); finishedTime = in.readBoolean() ? new Date(in.readVLong()) : null; analysisConfig = new AnalysisConfig(in); analysisLimits = in.readOptionalWriteable(AnalysisLimits::new); dataDescription = in.readOptionalWriteable(DataDescription::new); modelPlotConfig = in.readOptionalWriteable(ModelPlotConfig::new); renormalizationWindowDays = in.readOptionalLong(); backgroundPersistInterval = in.readOptionalTimeValue(); modelSnapshotRetentionDays = in.readOptionalLong(); dailyModelSnapshotRetentionAfterDays = in.readOptionalLong(); resultsRetentionDays = in.readOptionalLong(); Map<String, Object> readCustomSettings = in.readGenericMap(); customSettings = readCustomSettings == null ? null : Collections.unmodifiableMap(readCustomSettings); modelSnapshotId = in.readOptionalString(); if (in.readBoolean()) { modelSnapshotMinVersion = MlConfigVersion.readVersion(in); } else { modelSnapshotMinVersion = null; } resultsIndexName = in.readString(); deleting = in.readBoolean(); allowLazyOpen = in.readBoolean(); blocked = new Blocked(in); this.datafeedConfig = in.readOptionalWriteable(DatafeedConfig::new); } /** * Get the persisted job document name from the Job Id. * Throws if {@code jobId} is not a valid job Id. * * @param jobId The job id * @return The id of document the job is persisted in */ public static String documentId(String jobId) { if (MlStrings.isValidId(jobId) == false) { throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ID, ID.getPreferredName(), jobId)); } if (MlStrings.hasValidLengthForId(jobId) == false) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_ID_TOO_LONG, MlStrings.ID_LENGTH_LIMIT)); } return ANOMALY_DETECTOR_JOB_TYPE + "-" + jobId; } /** * Returns the job id from the doc id. Returns {@code null} if the doc id is invalid. */ @Nullable public static String extractJobIdFromDocumentId(String docId) { String jobId = docId.replaceAll("^" + ANOMALY_DETECTOR_JOB_TYPE + "-", ""); return jobId.equals(docId) ? null : jobId; } /** * Return the Job Id. * * @return The job Id string */ public String getId() { return jobId; } public String getJobType() { return jobType; } public MlConfigVersion getJobVersion() { return jobVersion; } public List<String> getGroups() { return groups; } /** * A good starting name for the index storing the job's results. * This defaults to the shared results index if a specific index name is not set. * This method must <em>only</em> be used during initial job creation. * After that the read/write aliases must always be used to access the job's * results index, as the underlying index may roll or be reindexed. * @return The job's initial results index name */ public String getInitialResultsIndexName() { return AnomalyDetectorsIndexFields.RESULTS_INDEX_PREFIX + resultsIndexName; } /** * Get the unmodified <code>results_index_name</code> field from the job. * This is provided to allow a job to be copied via the builder. * After creation this does not necessarily reflect the actual concrete * index used by the job. A job's results must always be read and written * using the read and write aliases. * @return The job's configured "index name" */ private String getResultsIndexNameNoPrefix() { return resultsIndexName; } /** * The job description * * @return job description */ public String getDescription() { return description; } /** * The Job creation time. This name is preferred when serialising to the * REST API. * * @return The date the job was created */ public Date getCreateTime() { return createTime; } /** * The time the job was finished or <code>null</code> if not finished. * * @return The date the job was last retired or <code>null</code> */ public Date getFinishedTime() { return finishedTime; } /** * The analysis configuration object * * @return The AnalysisConfig */ public AnalysisConfig getAnalysisConfig() { return analysisConfig; } /** * The analysis options object * * @return The AnalysisLimits */ public AnalysisLimits getAnalysisLimits() { return analysisLimits; } public ModelPlotConfig getModelPlotConfig() { return modelPlotConfig; } /** * If not set the input data is assumed to be csv with a '_time' field in * epoch format. * * @return A DataDescription or <code>null</code> * @see DataDescription */ public DataDescription getDataDescription() { return dataDescription; } /** * The duration of the renormalization window in days * * @return renormalization window in days */ public Long getRenormalizationWindowDays() { return renormalizationWindowDays; } /** * The background persistence interval * * @return background persistence interval */ public TimeValue getBackgroundPersistInterval() { return backgroundPersistInterval; } public Long getModelSnapshotRetentionDays() { return modelSnapshotRetentionDays; } public Long getDailyModelSnapshotRetentionAfterDays() { return dailyModelSnapshotRetentionAfterDays; } public Long getResultsRetentionDays() { return resultsRetentionDays; } public Map<String, Object> getCustomSettings() { return customSettings; } public String getModelSnapshotId() { return modelSnapshotId; } public MlConfigVersion getModelSnapshotMinVersion() { return modelSnapshotMinVersion; } public boolean isDeleting() { return deleting; } public boolean isResetting() { return blocked != null && Blocked.Reason.RESET.equals(blocked.getReason()); } public boolean allowLazyOpen() { return allowLazyOpen; } public Blocked getBlocked() { return blocked; } /** * Get all input data fields mentioned in the job configuration, * namely analysis fields and the time field. * * @return the collection of fields - never <code>null</code> */ public Collection<String> allInputFields() { Set<String> allFields = new TreeSet<>(); // analysis fields if (analysisConfig != null) { allFields.addAll(analysisConfig.analysisFields()); } // time field if (dataDescription != null) { String timeField = dataDescription.getTimeField(); if (timeField != null) { allFields.add(timeField); } } // remove empty strings allFields.remove(""); // the categorisation field isn't an input field allFields.remove(AnalysisConfig.ML_CATEGORY_FIELD); return allFields; } /** * Returns the timestamp before which data is not accepted by the job. * This is the latest record timestamp minus the job latency. * @param dataCounts the job data counts * @return the timestamp before which data is not accepted by the job */ public long earliestValidTimestamp(DataCounts dataCounts) { long currentTime = 0; Date latestRecordTimestamp = dataCounts.getLatestRecordTimeStamp(); if (latestRecordTimestamp != null) { TimeValue latency = analysisConfig.getLatency(); long latencyMillis = latency == null ? 0 : latency.millis(); currentTime = latestRecordTimestamp.getTime() - latencyMillis; } return currentTime; } public Optional<DatafeedConfig> getDatafeedConfig() { return Optional.ofNullable(datafeedConfig); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(jobId); out.writeString(jobType); if (jobVersion != null) { out.writeBoolean(true); MlConfigVersion.writeVersion(jobVersion, out); } else { out.writeBoolean(false); } out.writeStringCollection(groups); out.writeOptionalString(description); out.writeVLong(createTime.getTime()); if (finishedTime != null) { out.writeBoolean(true); out.writeVLong(finishedTime.getTime()); } else { out.writeBoolean(false); } analysisConfig.writeTo(out); out.writeOptionalWriteable(analysisLimits); out.writeOptionalWriteable(dataDescription); out.writeOptionalWriteable(modelPlotConfig); out.writeOptionalLong(renormalizationWindowDays); out.writeOptionalTimeValue(backgroundPersistInterval); out.writeOptionalLong(modelSnapshotRetentionDays); out.writeOptionalLong(dailyModelSnapshotRetentionAfterDays); out.writeOptionalLong(resultsRetentionDays); out.writeGenericMap(customSettings); out.writeOptionalString(modelSnapshotId); if (modelSnapshotMinVersion != null) { out.writeBoolean(true); MlConfigVersion.writeVersion(modelSnapshotMinVersion, out); } else { out.writeBoolean(false); } out.writeString(resultsIndexName); out.writeBoolean(deleting); out.writeBoolean(allowLazyOpen); blocked.writeTo(out); out.writeOptionalWriteable(datafeedConfig); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); doXContentBody(builder, params); builder.endObject(); return builder; } public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { final String humanReadableSuffix = "_string"; builder.field(ID.getPreferredName(), jobId); if (params.paramAsBoolean(EXCLUDE_GENERATED, false) == false) { builder.field(JOB_TYPE.getPreferredName(), jobType); if (jobVersion != null) { builder.field(JOB_VERSION.getPreferredName(), jobVersion); } builder.timeField(CREATE_TIME.getPreferredName(), CREATE_TIME.getPreferredName() + humanReadableSuffix, createTime.getTime()); if (finishedTime != null) { builder.timeField( FINISHED_TIME.getPreferredName(), FINISHED_TIME.getPreferredName() + humanReadableSuffix, finishedTime.getTime() ); } if (modelSnapshotId != null) { builder.field(MODEL_SNAPSHOT_ID.getPreferredName(), modelSnapshotId); } if (deleting) { builder.field(DELETING.getPreferredName(), deleting); } if (modelSnapshotMinVersion != null) { builder.field(MODEL_SNAPSHOT_MIN_VERSION.getPreferredName(), modelSnapshotMinVersion); } if (customSettings != null) { builder.field(CUSTOM_SETTINGS.getPreferredName(), customSettings); } // TODO in v8.0.0 move this out so that it will be included when `exclude_generated` is `true` if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false) == false) { if (datafeedConfig != null) { builder.field(DATAFEED_CONFIG.getPreferredName(), datafeedConfig, params); } } } else { if (customSettings != null) { HashMap<String, Object> newCustomSettings = new HashMap<>(customSettings); newCustomSettings.remove("created_by"); builder.field(CUSTOM_SETTINGS.getPreferredName(), newCustomSettings); } } if (groups.isEmpty() == false) { builder.field(GROUPS.getPreferredName(), groups); } if (description != null) { builder.field(DESCRIPTION.getPreferredName(), description); } builder.field(ANALYSIS_CONFIG.getPreferredName(), analysisConfig, params); if (analysisLimits != null) { builder.field(ANALYSIS_LIMITS.getPreferredName(), analysisLimits, params); } if (dataDescription != null) { builder.field(DATA_DESCRIPTION.getPreferredName(), dataDescription, params); } if (modelPlotConfig != null) { builder.field(MODEL_PLOT_CONFIG.getPreferredName(), modelPlotConfig, params); } if (renormalizationWindowDays != null) { builder.field(RENORMALIZATION_WINDOW_DAYS.getPreferredName(), renormalizationWindowDays); } if (backgroundPersistInterval != null) { builder.field(BACKGROUND_PERSIST_INTERVAL.getPreferredName(), backgroundPersistInterval.getStringRep()); } if (modelSnapshotRetentionDays != null) { builder.field(MODEL_SNAPSHOT_RETENTION_DAYS.getPreferredName(), modelSnapshotRetentionDays); } if (dailyModelSnapshotRetentionAfterDays != null) { builder.field(DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS.getPreferredName(), dailyModelSnapshotRetentionAfterDays); } if (resultsRetentionDays != null) { builder.field(RESULTS_RETENTION_DAYS.getPreferredName(), resultsRetentionDays); } builder.field(RESULTS_INDEX_NAME.getPreferredName(), resultsIndexName); builder.field(ALLOW_LAZY_OPEN.getPreferredName(), allowLazyOpen); if (blocked.getReason() != Blocked.Reason.NONE) { builder.field(BLOCKED.getPreferredName(), blocked); } return builder; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Job == false) { return false; } Job that = (Job) other; return Objects.equals(this.jobId, that.jobId) && Objects.equals(this.jobType, that.jobType) && Objects.equals(this.jobVersion, that.jobVersion) && Objects.equals(this.groups, that.groups) && Objects.equals(this.description, that.description) && Objects.equals(this.createTime, that.createTime) && Objects.equals(this.finishedTime, that.finishedTime) && Objects.equals(this.analysisConfig, that.analysisConfig) && Objects.equals(this.analysisLimits, that.analysisLimits) && Objects.equals(this.dataDescription, that.dataDescription) && Objects.equals(this.modelPlotConfig, that.modelPlotConfig) && Objects.equals(this.renormalizationWindowDays, that.renormalizationWindowDays) && Objects.equals(this.backgroundPersistInterval, that.backgroundPersistInterval) && Objects.equals(this.modelSnapshotRetentionDays, that.modelSnapshotRetentionDays) && Objects.equals(this.dailyModelSnapshotRetentionAfterDays, that.dailyModelSnapshotRetentionAfterDays) && Objects.equals(this.resultsRetentionDays, that.resultsRetentionDays) && Objects.equals(this.customSettings, that.customSettings) && Objects.equals(this.modelSnapshotId, that.modelSnapshotId) && Objects.equals(this.modelSnapshotMinVersion, that.modelSnapshotMinVersion) && Objects.equals(this.resultsIndexName, that.resultsIndexName) && Objects.equals(this.deleting, that.deleting) && Objects.equals(this.allowLazyOpen, that.allowLazyOpen) && Objects.equals(this.blocked, that.blocked) && Objects.equals(this.datafeedConfig, that.datafeedConfig); } @Override public int hashCode() { return Objects.hash( jobId, jobType, jobVersion, groups, description, createTime, finishedTime, analysisConfig, analysisLimits, dataDescription, modelPlotConfig, renormalizationWindowDays, backgroundPersistInterval, modelSnapshotRetentionDays, dailyModelSnapshotRetentionAfterDays, resultsRetentionDays, customSettings, modelSnapshotId, modelSnapshotMinVersion, resultsIndexName, deleting, allowLazyOpen, blocked, datafeedConfig ); } // Class already extends from AbstractDiffable, so copied from ToXContentToBytes#toString() @Override public final String toString() { return Strings.toString(this); } private static void checkValueNotLessThan(long minVal, String name, Long value) { if (value != null && value < minVal) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_FIELD_VALUE_TOO_LOW, name, minVal, value)); } } /** * Returns the job types that are compatible with a node with {@code mlConfigVersion} * @param mlConfigVersion the version ML configuration in use * @return the compatible job types */ public static Set<String> getCompatibleJobTypes(MlConfigVersion mlConfigVersion) { Set<String> compatibleTypes = new HashSet<>(); compatibleTypes.add(ANOMALY_DETECTOR_JOB_TYPE); return compatibleTypes; } public static class Builder implements Writeable { private String id; private String jobType = ANOMALY_DETECTOR_JOB_TYPE; private MlConfigVersion jobVersion; private List<String> groups = Collections.emptyList(); private String description; private AnalysisConfig analysisConfig; private AnalysisLimits analysisLimits; private DataDescription dataDescription; private Date createTime; private Date finishedTime; private ModelPlotConfig modelPlotConfig; private Long renormalizationWindowDays; private TimeValue backgroundPersistInterval; private Long modelSnapshotRetentionDays = DEFAULT_MODEL_SNAPSHOT_RETENTION_DAYS; private Long dailyModelSnapshotRetentionAfterDays; private Long resultsRetentionDays; private Map<String, Object> customSettings; private String modelSnapshotId; private MlConfigVersion modelSnapshotMinVersion; private String resultsIndexName; private boolean deleting; private boolean allowLazyOpen; private Blocked blocked = Blocked.none(); private DatafeedConfig.Builder datafeedConfig; public Builder() {} public Builder(String id) { this.id = id; } public Builder(Job job) { this.id = job.getId(); this.jobType = job.getJobType(); this.jobVersion = job.getJobVersion(); this.groups = new ArrayList<>(job.getGroups()); this.description = job.getDescription(); this.analysisConfig = job.getAnalysisConfig(); this.analysisLimits = job.getAnalysisLimits(); this.dataDescription = job.getDataDescription(); this.createTime = job.getCreateTime(); this.finishedTime = job.getFinishedTime(); this.modelPlotConfig = job.getModelPlotConfig(); this.renormalizationWindowDays = job.getRenormalizationWindowDays(); this.backgroundPersistInterval = job.getBackgroundPersistInterval(); this.modelSnapshotRetentionDays = job.getModelSnapshotRetentionDays(); this.dailyModelSnapshotRetentionAfterDays = job.getDailyModelSnapshotRetentionAfterDays(); this.resultsRetentionDays = job.getResultsRetentionDays(); this.customSettings = job.getCustomSettings() == null ? null : new LinkedHashMap<>(job.getCustomSettings()); this.modelSnapshotId = job.getModelSnapshotId(); this.modelSnapshotMinVersion = job.getModelSnapshotMinVersion(); this.resultsIndexName = job.getResultsIndexNameNoPrefix(); this.deleting = job.isDeleting(); this.allowLazyOpen = job.allowLazyOpen(); this.blocked = job.getBlocked(); this.datafeedConfig = job.getDatafeedConfig().isPresent() ? new DatafeedConfig.Builder(job.datafeedConfig) : null; } public Builder(StreamInput in) throws IOException { id = in.readOptionalString(); jobType = in.readString(); jobVersion = in.readBoolean() ? MlConfigVersion.readVersion(in) : null; groups = in.readStringCollectionAsList(); description = in.readOptionalString(); createTime = in.readBoolean() ? new Date(in.readVLong()) : null; finishedTime = in.readBoolean() ? new Date(in.readVLong()) : null; analysisConfig = in.readOptionalWriteable(AnalysisConfig::new); analysisLimits = in.readOptionalWriteable(AnalysisLimits::new); dataDescription = in.readOptionalWriteable(DataDescription::new); modelPlotConfig = in.readOptionalWriteable(ModelPlotConfig::new); renormalizationWindowDays = in.readOptionalLong(); backgroundPersistInterval = in.readOptionalTimeValue(); modelSnapshotRetentionDays = in.readOptionalLong(); dailyModelSnapshotRetentionAfterDays = in.readOptionalLong(); resultsRetentionDays = in.readOptionalLong(); customSettings = in.readGenericMap(); modelSnapshotId = in.readOptionalString(); if (in.readBoolean()) { modelSnapshotMinVersion = MlConfigVersion.readVersion(in); } else { modelSnapshotMinVersion = null; } resultsIndexName = in.readOptionalString(); deleting = in.readBoolean(); allowLazyOpen = in.readBoolean(); blocked = new Blocked(in); datafeedConfig = in.readOptionalWriteable(DatafeedConfig.Builder::new); } public Builder setId(String id) { this.id = id; return this; } public String getId() { return id; } public void setJobVersion(MlConfigVersion jobVersion) { this.jobVersion = jobVersion; } private void setJobVersion(String jobVersion) { this.jobVersion = MlConfigVersion.fromString(jobVersion); } private void setJobType(String jobType) { this.jobType = jobType; } public void setGroups(List<String> groups) { this.groups = groups == null ? Collections.emptyList() : groups; } public List<String> getGroups() { return groups; } public Builder setCustomSettings(Map<String, Object> customSettings) { this.customSettings = customSettings; return this; } public Builder setDescription(String description) { this.description = description; return this; } public Builder setAnalysisConfig(AnalysisConfig.Builder configBuilder) { analysisConfig = ExceptionsHelper.requireNonNull(configBuilder, ANALYSIS_CONFIG.getPreferredName()).build(); return this; } public AnalysisConfig getAnalysisConfig() { return analysisConfig; } public Builder setAnalysisLimits(AnalysisLimits analysisLimits) { this.analysisLimits = ExceptionsHelper.requireNonNull(analysisLimits, ANALYSIS_LIMITS.getPreferredName()); return this; } public Builder setCreateTime(Date createTime) { this.createTime = createTime; return this; } public Builder setFinishedTime(Date finishedTime) { this.finishedTime = finishedTime; return this; } public Builder setDataDescription(DataDescription.Builder dataDescription) { this.dataDescription = ExceptionsHelper.requireNonNull(dataDescription, DATA_DESCRIPTION.getPreferredName()).build(); return this; } public Builder setModelPlotConfig(ModelPlotConfig modelPlotConfig) { this.modelPlotConfig = modelPlotConfig; return this; } public Builder setBackgroundPersistInterval(TimeValue backgroundPersistInterval) { this.backgroundPersistInterval = backgroundPersistInterval; return this; } public Builder setRenormalizationWindowDays(Long renormalizationWindowDays) { this.renormalizationWindowDays = renormalizationWindowDays; return this; } public Builder setModelSnapshotRetentionDays(Long modelSnapshotRetentionDays) { this.modelSnapshotRetentionDays = modelSnapshotRetentionDays; return this; } public Long getModelSnapshotRetentionDays() { return modelSnapshotRetentionDays; } public Builder setDailyModelSnapshotRetentionAfterDays(Long dailyModelSnapshotRetentionAfterDays) { this.dailyModelSnapshotRetentionAfterDays = dailyModelSnapshotRetentionAfterDays; return this; } public Builder setResultsRetentionDays(Long resultsRetentionDays) { this.resultsRetentionDays = resultsRetentionDays; return this; } public Builder setModelSnapshotId(String modelSnapshotId) { this.modelSnapshotId = modelSnapshotId; return this; } public Builder setModelSnapshotMinVersion(MlConfigVersion modelSnapshotMinVersion) { this.modelSnapshotMinVersion = modelSnapshotMinVersion; return this; } Builder setModelSnapshotMinVersion(String modelSnapshotMinVersion) { this.modelSnapshotMinVersion = MlConfigVersion.fromString(modelSnapshotMinVersion); return this; } public Builder setResultsIndexName(String resultsIndexName) { this.resultsIndexName = resultsIndexName; return this; } public Builder setDeleting(boolean deleting) { this.deleting = deleting; return this; } public Builder setAllowLazyOpen(boolean allowLazyOpen) { this.allowLazyOpen = allowLazyOpen; return this; } public Builder setBlocked(Blocked blocked) { this.blocked = ExceptionsHelper.requireNonNull(blocked, BLOCKED); return this; } public Builder setDatafeed(DatafeedConfig.Builder datafeed) { this.datafeedConfig = datafeed; return this; } public DatafeedConfig.Builder getDatafeedConfig() { return datafeedConfig; } /** * This is used for parsing. If the datafeed_config exists AND its indices options are `null`, we set them to these options * * @param indicesOptions To set if the datafeed indices options are null * @return The job builder. */ public Builder setDatafeedIndicesOptionsIfRequired(IndicesOptions indicesOptions) { if (this.datafeedConfig != null && this.datafeedConfig.getIndicesOptions() == null) { this.datafeedConfig.setIndicesOptions(indicesOptions); } return this; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(id); out.writeString(jobType); if (jobVersion != null) { out.writeBoolean(true); MlConfigVersion.writeVersion(jobVersion, out); } else { out.writeBoolean(false); } out.writeStringCollection(groups); out.writeOptionalString(description); if (createTime != null) { out.writeBoolean(true); out.writeVLong(createTime.getTime()); } else { out.writeBoolean(false); } if (finishedTime != null) { out.writeBoolean(true); out.writeVLong(finishedTime.getTime()); } else { out.writeBoolean(false); } out.writeOptionalWriteable(analysisConfig); out.writeOptionalWriteable(analysisLimits); out.writeOptionalWriteable(dataDescription); out.writeOptionalWriteable(modelPlotConfig); out.writeOptionalLong(renormalizationWindowDays); out.writeOptionalTimeValue(backgroundPersistInterval); out.writeOptionalLong(modelSnapshotRetentionDays); out.writeOptionalLong(dailyModelSnapshotRetentionAfterDays); out.writeOptionalLong(resultsRetentionDays); out.writeGenericMap(customSettings); out.writeOptionalString(modelSnapshotId); if (modelSnapshotMinVersion != null) { out.writeBoolean(true); MlConfigVersion.writeVersion(modelSnapshotMinVersion, out); } else { out.writeBoolean(false); } out.writeOptionalString(resultsIndexName); out.writeBoolean(deleting); out.writeBoolean(allowLazyOpen); blocked.writeTo(out); out.writeOptionalWriteable(datafeedConfig); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Job.Builder that = (Job.Builder) o; return Objects.equals(this.id, that.id) && Objects.equals(this.jobType, that.jobType) && Objects.equals(this.jobVersion, that.jobVersion) && Objects.equals(this.groups, that.groups) && Objects.equals(this.description, that.description) && Objects.equals(this.analysisConfig, that.analysisConfig) && Objects.equals(this.analysisLimits, that.analysisLimits) && Objects.equals(this.dataDescription, that.dataDescription) && Objects.equals(this.createTime, that.createTime) && Objects.equals(this.finishedTime, that.finishedTime) && Objects.equals(this.modelPlotConfig, that.modelPlotConfig) && Objects.equals(this.renormalizationWindowDays, that.renormalizationWindowDays) && Objects.equals(this.backgroundPersistInterval, that.backgroundPersistInterval) && Objects.equals(this.modelSnapshotRetentionDays, that.modelSnapshotRetentionDays) && Objects.equals(this.dailyModelSnapshotRetentionAfterDays, that.dailyModelSnapshotRetentionAfterDays) && Objects.equals(this.resultsRetentionDays, that.resultsRetentionDays) && Objects.equals(this.customSettings, that.customSettings) && Objects.equals(this.modelSnapshotId, that.modelSnapshotId) && Objects.equals(this.modelSnapshotMinVersion, that.modelSnapshotMinVersion) && Objects.equals(this.resultsIndexName, that.resultsIndexName) && Objects.equals(this.deleting, that.deleting) && Objects.equals(this.allowLazyOpen, that.allowLazyOpen) && Objects.equals(this.blocked, that.blocked) && Objects.equals(this.datafeedConfig, that.datafeedConfig); } @Override public int hashCode() { return Objects.hash( id, jobType, jobVersion, groups, description, analysisConfig, analysisLimits, dataDescription, createTime, finishedTime, modelPlotConfig, renormalizationWindowDays, backgroundPersistInterval, modelSnapshotRetentionDays, dailyModelSnapshotRetentionAfterDays, resultsRetentionDays, customSettings, modelSnapshotId, modelSnapshotMinVersion, resultsIndexName, deleting, allowLazyOpen, blocked, datafeedConfig ); } /** * Call this method to validate that the job JSON provided by a user is valid. * Throws an exception if there are any problems; normal return implies valid. */ public void validateInputFields() { if (analysisConfig == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_MISSING_ANALYSISCONFIG)); } if (dataDescription == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_MISSING_DATA_DESCRIPTION)); } checkTimeFieldNotInAnalysisConfig(dataDescription, analysisConfig); checkValidBackgroundPersistInterval(); checkValueNotLessThan(0, RENORMALIZATION_WINDOW_DAYS.getPreferredName(), renormalizationWindowDays); checkValueNotLessThan(0, RESULTS_RETENTION_DAYS.getPreferredName(), resultsRetentionDays); if (MlStrings.isValidId(id) == false) { throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ID, ID.getPreferredName(), id)); } if (MlStrings.hasValidLengthForId(id) == false) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_ID_TOO_LONG, MlStrings.ID_LENGTH_LIMIT)); } validateModelSnapshotRetentionSettings(); validateGroups(); // Results index name not specified in user input means use the default, so is acceptable in this validation if (Strings.isNullOrEmpty(resultsIndexName) == false && MlStrings.isValidId(resultsIndexName) == false) { throw new IllegalArgumentException( Messages.getMessage(Messages.INVALID_ID, RESULTS_INDEX_NAME.getPreferredName(), resultsIndexName) ); } // Creation time is NOT required in user input, hence validated only on build } /** * This is meant to be called when a new job is created. * It will optionally validate the model memory limit against the max limit * and it will set the current version defaults to missing values. */ public void validateAnalysisLimitsAndSetDefaults(@Nullable ByteSizeValue maxModelMemoryLimit) { analysisLimits = AnalysisLimits.validateAndSetDefaults( analysisLimits, maxModelMemoryLimit, AnalysisLimits.DEFAULT_MODEL_MEMORY_LIMIT_MB ); } /** * This is meant to be called when a new job is created. * It sets {@link #dailyModelSnapshotRetentionAfterDays} to the default value if it is not set and the default makes sense. */ public void validateModelSnapshotRetentionSettingsAndSetDefaults() { validateModelSnapshotRetentionSettings(); if (dailyModelSnapshotRetentionAfterDays == null && modelSnapshotRetentionDays != null && modelSnapshotRetentionDays > DEFAULT_DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS) { dailyModelSnapshotRetentionAfterDays = DEFAULT_DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS; } final long SECONDS_IN_A_DAY = 86400; if (analysisConfig.getBucketSpan().seconds() > SECONDS_IN_A_DAY) { if (analysisConfig.getBucketSpan().seconds() % SECONDS_IN_A_DAY != 0) { deprecationLogger.critical( DeprecationCategory.OTHER, "bucket_span", "bucket_span {} [{}s] is not an integral multiple of the number of seconds in 1d [{}s]. This is now deprecated.", analysisConfig.getBucketSpan().toString(), analysisConfig.getBucketSpan().seconds(), SECONDS_IN_A_DAY ); } } else { if (SECONDS_IN_A_DAY % analysisConfig.getBucketSpan().seconds() != 0) { deprecationLogger.critical( DeprecationCategory.OTHER, "bucket_span", "bucket_span {} [{}s] is not an integral divisor of the number of seconds in 1d [{}s]. This is now deprecated.", analysisConfig.getBucketSpan().toString(), analysisConfig.getBucketSpan().seconds(), SECONDS_IN_A_DAY ); } } if (analysisConfig.getModelPruneWindow() == null) { long modelPruneWindowSeconds = analysisConfig.getBucketSpan().seconds() / 2 + AnalysisConfig.DEFAULT_MODEL_PRUNE_WINDOW .seconds(); modelPruneWindowSeconds -= (modelPruneWindowSeconds % analysisConfig.getBucketSpan().seconds()); if (modelPruneWindowSeconds < AnalysisConfig.DEFAULT_MODEL_PRUNE_WINDOW.seconds()) { modelPruneWindowSeconds += analysisConfig.getBucketSpan().seconds(); } modelPruneWindowSeconds = Math.max(20 * analysisConfig.getBucketSpan().seconds(), modelPruneWindowSeconds); AnalysisConfig.Builder analysisConfigBuilder = new AnalysisConfig.Builder(analysisConfig); final long SECONDS_IN_AN_HOUR = 3600; final long SECONDS_IN_A_MINUTE = 60; if (modelPruneWindowSeconds % SECONDS_IN_A_DAY == 0) { analysisConfigBuilder.setModelPruneWindow(TimeValue.timeValueDays(modelPruneWindowSeconds / SECONDS_IN_A_DAY)); } else if (modelPruneWindowSeconds % SECONDS_IN_AN_HOUR == 0) { analysisConfigBuilder.setModelPruneWindow(TimeValue.timeValueHours(modelPruneWindowSeconds / SECONDS_IN_AN_HOUR)); } else if (modelPruneWindowSeconds % SECONDS_IN_A_MINUTE == 0) { analysisConfigBuilder.setModelPruneWindow(TimeValue.timeValueMinutes(modelPruneWindowSeconds / SECONDS_IN_A_MINUTE)); } else { analysisConfigBuilder.setModelPruneWindow(TimeValue.timeValueSeconds(modelPruneWindowSeconds)); } this.setAnalysisConfig(analysisConfigBuilder); } } /** * Validates that {@link #modelSnapshotRetentionDays} and {@link #dailyModelSnapshotRetentionAfterDays} make sense, * both individually and in combination. */ public void validateModelSnapshotRetentionSettings() { checkValueNotLessThan(0, MODEL_SNAPSHOT_RETENTION_DAYS.getPreferredName(), modelSnapshotRetentionDays); checkValueNotLessThan(0, DAILY_MODEL_SNAPSHOT_RETENTION_AFTER_DAYS.getPreferredName(), dailyModelSnapshotRetentionAfterDays); if (modelSnapshotRetentionDays != null && dailyModelSnapshotRetentionAfterDays != null && dailyModelSnapshotRetentionAfterDays > modelSnapshotRetentionDays) { throw new IllegalArgumentException( Messages.getMessage( Messages.JOB_CONFIG_MODEL_SNAPSHOT_RETENTION_SETTINGS_INCONSISTENT, dailyModelSnapshotRetentionAfterDays, modelSnapshotRetentionDays ) ); } } private void validateGroups() { for (String group : this.groups) { if (MlStrings.isValidId(group) == false) { throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_GROUP, group)); } if (this.id.equals(group)) { // cannot have a group name the same as the job id throw new ResourceAlreadyExistsException(Messages.getMessage(Messages.JOB_AND_GROUP_NAMES_MUST_BE_UNIQUE, group)); } } } /** * Validates that the Detector configs are unique up to detectorIndex field (which is ignored). */ public void validateDetectorsAreUnique() { Set<Detector> canonicalDetectors = new HashSet<>(); for (Detector detector : this.analysisConfig.getDetectors()) { // While testing for equality, ignore detectorIndex field as this field is auto-generated. Detector canonicalDetector = new Detector.Builder(detector).setDetectorIndex(0).build(); if (canonicalDetectors.add(canonicalDetector) == false) { throw new IllegalArgumentException( Messages.getMessage(Messages.JOB_CONFIG_DUPLICATE_DETECTORS_DISALLOWED, detector.getDetectorDescription()) ); } } } /** * Builds a job with the given {@code createTime} and the current version. * This should be used when a new job is created as opposed to {@link #build()}. * * @param createTime The time this job was created * @return The job */ public Job build(@SuppressWarnings("HiddenField") Date createTime) { setCreateTime(createTime); setJobVersion(MlConfigVersion.CURRENT); return build(); } /** * Builds a job. * This should be used when an existing job is being built * as opposed to {@link #build(Date)}. * * @return The job */ public Job build() { // If at the build stage there are missing values from analysis limits, // it means we are reading a pre 6.3 job. Since 6.1, the model_memory_limit // is always populated. So, if the value is missing, we fill with the pre 6.1 // default. We do not need to check against the max limit here so we pass null. analysisLimits = AnalysisLimits.validateAndSetDefaults( analysisLimits, null, AnalysisLimits.PRE_6_1_DEFAULT_MODEL_MEMORY_LIMIT_MB ); validateInputFields(); // Creation time is NOT required in user input, hence validated only on build ExceptionsHelper.requireNonNull(createTime, CREATE_TIME.getPreferredName()); if (Strings.isNullOrEmpty(resultsIndexName)) { resultsIndexName = AnomalyDetectorsIndexFields.RESULTS_INDEX_DEFAULT; } else if (resultsIndexName.equals(AnomalyDetectorsIndexFields.RESULTS_INDEX_DEFAULT) == false) { // User-defined names are prepended with "custom" // Conditional guards against multiple prepending due to updates instead of first creation resultsIndexName = resultsIndexName.startsWith("custom-") ? resultsIndexName : "custom-" + resultsIndexName; } if (datafeedConfig != null) { if (datafeedConfig.getId() == null) { datafeedConfig.setId(id); } if (datafeedConfig.getJobId() != null && datafeedConfig.getJobId().equals(id) == false) { throw new IllegalArgumentException( Messages.getMessage(JOB_CONFIG_DATAFEED_CONFIG_JOB_ID_MISMATCH, datafeedConfig.getJobId(), id) ); } datafeedConfig.setJobId(id); } return new Job( id, jobType, jobVersion, groups, description, createTime, finishedTime, analysisConfig, analysisLimits, dataDescription, modelPlotConfig, renormalizationWindowDays, backgroundPersistInterval, modelSnapshotRetentionDays, dailyModelSnapshotRetentionAfterDays, resultsRetentionDays, customSettings, modelSnapshotId, modelSnapshotMinVersion, resultsIndexName, deleting, allowLazyOpen, blocked, Optional.ofNullable(datafeedConfig).map(DatafeedConfig.Builder::build).orElse(null) ); } private void checkValidBackgroundPersistInterval() { if (backgroundPersistInterval != null) { TimeUtils.checkMultiple(backgroundPersistInterval, TimeUnit.SECONDS, BACKGROUND_PERSIST_INTERVAL); checkValueNotLessThan( MIN_BACKGROUND_PERSIST_INTERVAL.getSeconds(), BACKGROUND_PERSIST_INTERVAL.getPreferredName(), backgroundPersistInterval.getSeconds() ); } } static void checkTimeFieldNotInAnalysisConfig(DataDescription dataDescription, AnalysisConfig analysisConfig) { if (analysisConfig.analysisFields().contains(dataDescription.getTimeField())) { throw new IllegalArgumentException(Messages.getMessage(Messages.JOB_CONFIG_TIME_FIELD_NOT_ALLOWED_IN_ANALYSIS_CONFIG)); } } } }
elastic/elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/config/Job.java
179,682
import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.*; public class JDecisionTreeViewer extends JFrame implements Runnable { Experiments myExperiments; JDecisionTreePane myTabbedPane; boolean plotAvailable; JDecisionTreeViewer() { super(); plotAvailable = false; } JDecisionTreeViewer(String s) { super(s); plotAvailable = false; } public void start() { Thread th = new Thread(this); th.start(); } public void go(Experiments e) { myExperiments = e; start(); setVisible(true); } public void captureAndSave() { String nameSave = myExperiments.myAlgos.myDomain.myDS.pathSave + "treeplot_" + Utils.NOW + "_" + DecisionTreeSkipTreeArc.ALL_ALPHA_TYPES[PoincareDiskEmbeddingUI.ALPHA_TYPE_PLOT] + "_Algo" + myTabbedPane.poincareDisk.index_algorithm_plot + "_SplitCV" + myTabbedPane.poincareDisk.index_split_CV_plot + "_Tree" + myTabbedPane.poincareDisk.index_tree_number_plot + ".png"; Rectangle rect = myTabbedPane.poincareDisk.getCaptureRectangle(); BufferedImage fc = null; try { fc = new Robot().createScreenCapture(rect); } catch (AWTException a) { } File output = new File(nameSave); try { ImageIO.write(fc, "png", output); } catch (IOException a) { } } public void run() { Container pane = getContentPane(); pane.setLayout(new BorderLayout()); int ss = 600; myTabbedPane = new JDecisionTreePane(this); JPanel upperPane = new JPanel(); upperPane.setLayout(new BorderLayout()); upperPane.setPreferredSize(new Dimension(ss, ss)); upperPane.setMinimumSize(new Dimension(ss, ss)); upperPane.setMaximumSize(new Dimension(ss, ss)); upperPane.add(myTabbedPane, BorderLayout.CENTER); pane.add(upperPane, BorderLayout.CENTER); pack(); } }
google-research/google-research
tempered_boosting/JDecisionTreeViewer.java
179,683
package com.baeldung.r; /** * FastR showcase. * * @author Donato Rimenti */ public class FastRMean { /** * Invokes the customMean R function passing the given values as arguments. * * @param values the input to the mean script * @return the result of the R script */ public double mean(int[] values) { Context polyglot = Context.newBuilder() .allowAllAccess(true) .build(); String meanScriptContent = RUtils.getMeanScriptContent(); polyglot.eval("R", meanScriptContent); Value rBindings = polyglot.getBindings("R"); Value rInput = rBindings.getMember("c") .execute(values); return rBindings.getMember("customMean") .execute(rInput) .asDouble(); } }
eugenp/tutorials
libraries/src/main/java/com/baeldung/r/FastRMean.java
179,686
package com.baeldung.jfreechart; import java.awt.Font; import javax.swing.JFrame; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.BarRenderer; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.data.category.DefaultCategoryDataset; public class CombinationChartExample { public static void main(String[] args) { // Create datasets DefaultCategoryDataset lineDataset = new DefaultCategoryDataset(); lineDataset.addValue(200, "Sales", "January"); lineDataset.addValue(150, "Sales", "February"); lineDataset.addValue(180, "Sales", "March"); DefaultCategoryDataset barDataset = new DefaultCategoryDataset(); barDataset.addValue(400, "Profit", "January"); barDataset.addValue(300, "Profit", "February"); barDataset.addValue(250, "Profit", "March"); // Create a combination chart CategoryPlot plot = new CategoryPlot(); plot.setDataset(0, lineDataset); plot.setRenderer(0, new LineAndShapeRenderer()); plot.setDataset(1, barDataset); plot.setRenderer(1, new BarRenderer()); plot.setDomainAxis(new CategoryAxis("Month")); plot.setRangeAxis(new NumberAxis("Value")); plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinesVisible(true); JFreeChart chart = new JFreeChart( "Monthly Sales and Profit", // chart title null, // null means to use default font plot, // combination chart as CategoryPlot true); // legend // Display the chart ChartPanel chartPanel = new ChartPanel(chart); JFrame frame = new JFrame(); frame.setSize(800, 600); frame.setContentPane(chartPanel); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
eugenp/tutorials
libraries-4/src/main/java/com/baeldung/jfreechart/CombinationChartExample.java
179,687
/** * Copyright (c) 2013-2024 Nikita Koksharov * * 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.redisson.cluster; import java.util.Objects; /** * * @author Nikita Koksharov * */ public class ClusterSlotRange { private final int startSlot; private final int endSlot; public ClusterSlotRange(int startSlot, int endSlot) { super(); this.startSlot = startSlot; this.endSlot = endSlot; } public int getStartSlot() { return startSlot; } public int getEndSlot() { return endSlot; } public boolean hasSlot(int slot) { return slot >= startSlot && slot <= endSlot; } public int size() { return endSlot - startSlot + 1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterSlotRange that = (ClusterSlotRange) o; return startSlot == that.startSlot && endSlot == that.endSlot; } @Override public int hashCode() { return Objects.hash(startSlot, endSlot); } @Override public String toString() { return "[" + startSlot + "-" + endSlot + "]"; } }
redisson/redisson
redisson/src/main/java/org/redisson/cluster/ClusterSlotRange.java
179,688
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * 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.iluwatar.hexagonal.domain; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Represents lottery ticket check result. */ @Getter @EqualsAndHashCode @RequiredArgsConstructor public class LotteryTicketCheckResult { /** * Enumeration of Type of Outcomes of a Lottery. */ public enum CheckResult { WIN_PRIZE, NO_PRIZE, TICKET_NOT_SUBMITTED } private final CheckResult result; private final int prizeAmount; /** * Constructor. */ public LotteryTicketCheckResult(CheckResult result) { this.result = result; prizeAmount = 0; } }
smedals/java-design-patterns
hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryTicketCheckResult.java
179,689
// Copyright 2014 The Bazel 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 net.starlark.java.syntax; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.FormatMethod; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import net.starlark.java.spelling.SpellChecker; /** * The Resolver resolves each identifier in a syntax tree to its binding, and performs other * validity checks. * * <p>When a variable is defined, it is visible in the entire block. For example, a global variable * is visible in the entire file; a variable in a function is visible in the entire function block * (even on the lines before its first assignment). * * <p>Resolution is a mutation of the syntax tree, as it attaches binding information to Identifier * nodes. (In the future, it will attach additional information to functions to support lexical * scope, and even compilation of the trees to bytecode.) Resolution errors are reported in the * analogous manner to scan/parse errors: for a StarlarkFile, they are appended to {@code * StarlarkFile.errors}; for an expression they are reported by an SyntaxError.Exception exception. * It is legal to resolve a file that already contains scan/parse errors, though it may lead to * secondary errors. */ public final class Resolver extends NodeVisitor { // TODO(adonovan): // - use "keyword" (not "named") and "required" (not "mandatory") terminology everywhere, // including the spec. // - move the "no if statements at top level" check to bazel's check{Build,*}Syntax // (that's a spec change), or put it behind a FileOptions flag (no spec change). /** Scope discriminates the scope of a binding: global, local, etc. */ public enum Scope { /** Binding is local to a function, comprehension, or file (e.g. load). */ LOCAL, /** Binding is non-local and occurs outside any function or comprehension. */ GLOBAL, /** Binding is local to a function, comprehension, or file, but shared with nested functions. */ CELL, /** Binding is an implicit parameter whose value is the CELL of some enclosing function. */ FREE, /** Binding is predeclared by the application (e.g. glob in Bazel). */ PREDECLARED, /** Binding is predeclared by the core (e.g. None). */ UNIVERSAL; @Override public String toString() { return super.toString().toLowerCase(); } } /** * A Binding is a static abstraction of a variable. The Resolver maps each Identifier to a * Binding. */ public static final class Binding { private Scope scope; private final int index; // index within frame (LOCAL/CELL), freevars (FREE), or module (GLOBAL) @Nullable private final Identifier first; // first binding use, if syntactic private Binding(Scope scope, int index, @Nullable Identifier first) { this.scope = scope; this.index = index; this.first = first; } /** Returns the name of this binding's identifier. */ @Nullable public String getName() { return first != null ? first.getName() : null; } /** Returns the scope of the binding. */ public Scope getScope() { return scope; } /** * Returns the index of a binding within its function's frame (LOCAL/CELL), freevars (FREE), or * module (GLOBAL). */ public int getIndex() { return index; } @Override public String toString() { return first == null ? scope.toString() : String.format( "%s[%d] %s @ %s", scope, index, first.getName(), first.getStartLocation()); } } /** A Resolver.Function records information about a resolved function. */ public static final class Function { private final String name; private final Location location; private final ImmutableList<Parameter> params; private final ImmutableList<Statement> body; private final boolean hasVarargs; private final boolean hasKwargs; private final int numKeywordOnlyParams; private final ImmutableList<String> parameterNames; private final boolean isToplevel; private final ImmutableList<Binding> locals; private final int[] cellIndices; private final ImmutableList<Binding> freevars; private final ImmutableList<String> globals; // TODO(adonovan): move to Program. private Function( String name, Location loc, ImmutableList<Parameter> params, ImmutableList<Statement> body, boolean hasVarargs, boolean hasKwargs, int numKeywordOnlyParams, List<Binding> locals, List<Binding> freevars, List<String> globals) { this.name = name; this.location = loc; this.params = params; this.body = body; this.hasVarargs = hasVarargs; this.hasKwargs = hasKwargs; this.numKeywordOnlyParams = numKeywordOnlyParams; ImmutableList.Builder<String> names = ImmutableList.builderWithExpectedSize(params.size()); for (Parameter p : params) { names.add(p.getName()); } this.parameterNames = names.build(); this.isToplevel = name.equals("<toplevel>"); this.locals = ImmutableList.copyOf(locals); this.freevars = ImmutableList.copyOf(freevars); this.globals = ImmutableList.copyOf(globals); // Create an index of the locals that are cells. int ncells = 0; int nlocals = locals.size(); for (int i = 0; i < nlocals; i++) { if (locals.get(i).scope == Scope.CELL) { ncells++; } } this.cellIndices = new int[ncells]; for (int i = 0, j = 0; i < nlocals; i++) { if (locals.get(i).scope == Scope.CELL) { cellIndices[j++] = i; } } } /** * Returns the name of the function. It may be "<toplevel>" for the implicit function that holds * the top-level statements of a file, or "<expr>" for the implicit function that evaluates a * single expression. */ public String getName() { return name; } /** Returns the value denoted by the function's doc string literal, or null if absent. */ @Nullable public String getDocumentation() { if (getBody().isEmpty()) { return null; } Statement first = getBody().get(0); if (!(first instanceof ExpressionStatement)) { return null; } Expression expr = ((ExpressionStatement) first).getExpression(); if (!(expr instanceof StringLiteral)) { return null; } return ((StringLiteral) expr).getValue(); } /** Returns the function's local bindings, parameters first. */ public ImmutableList<Binding> getLocals() { return locals; } /** * Returns the indices within {@code getLocals()} of the "cells", that is, local variables of * thus function that are shared with nested functions. The caller must not modify the result. */ public int[] getCellIndices() { return cellIndices; } /** * Returns the list of names of globals referenced by this function. The order matches the * indices used in compiled code. */ public ImmutableList<String> getGlobals() { return globals; } /** * Returns the list of enclosing CELL or FREE bindings referenced by this function. At run time, * these values, all of which are cells containing variables local to some enclosing function, * will be stored in the closure. (CELL bindings in this list are local to the immediately * enclosing function, while FREE bindings pass through one or more intermediate enclosing * functions.) */ public ImmutableList<Binding> getFreeVars() { return freevars; } /** Returns the location of the function's identifier. */ public Location getLocation() { return location; } /** * Returns the function's parameters, in "run-time order": non-keyword-only parameters, * keyword-only parameters, {@code *args}, and finally {@code **kwargs}. A bare {@code *} * parameter is dropped. */ public ImmutableList<Parameter> getParameters() { return params; } /** * Returns the effective statements of the function's body. (For the implicit function created * to evaluate a single standalone expression, this may contain a synthesized Return statement.) */ // TODO(adonovan): eliminate when we switch to compiler. public ImmutableList<Statement> getBody() { return body; } /** Reports whether the function has an {@code *args} parameter. */ public boolean hasVarargs() { return hasVarargs; } /** Reports whether the function has a {@code **kwargs} parameter. */ public boolean hasKwargs() { return hasKwargs; } /** * Returns the number of the function's keyword-only parameters, such as {@code c} in {@code def * f(a, *b, c, **d)} or {@code def f(a, *, c, **d)}. */ public int numKeywordOnlyParams() { return numKeywordOnlyParams; } /** Returns the names of the parameters. Order is as for {@link #getParameters}. */ public ImmutableList<String> getParameterNames() { return parameterNames; } /** * isToplevel indicates that this is the <toplevel> function containing top-level statements of * a file. */ // TODO(adonovan): remove this when we remove Bazel's "export" hack, // or switch to a compiled representation of function bodies. public boolean isToplevel() { return isToplevel; } } /** * A Module is a static abstraction of a Starlark module (see {@link * net.starlark.java.eval.Module})). It describes, for the resolver and compiler, the set of * variable names that are predeclared, either by the interpreter (UNIVERSAL) or by the * application (PREDECLARED), plus the set of pre-defined global names (which is typically empty, * except in a REPL or EvaluationTestCase scenario). */ public interface Module { /** * Resolves a name to a GLOBAL, PREDECLARED, or UNIVERSAL binding. * * @throws Undefined if the name is not defined. */ Scope resolve(String name) throws Undefined; /** * An Undefined exception indicates a failure to resolve a top-level name. If {@code candidates} * is non-null, it provides the set of accessible top-level names, which, along with local * names, will be used as candidates for spelling suggestions. */ final class Undefined extends Exception { @Nullable private final Set<String> candidates; public Undefined(String message, @Nullable Set<String> candidates) { super(message); this.candidates = candidates; } } } // A simple implementation of the Module for testing. // It defines only the predeclared names---no "universal" names (e.g. None) // or initially-defined globals (as happens in a REPL). // Realistically, most clients will use an eval.Module. // TODO(adonovan): move into test/ tree. public static Module moduleWithPredeclared(String... names) { ImmutableSet<String> predeclared = ImmutableSet.copyOf(names); return (name) -> { if (predeclared.contains(name)) { return Scope.PREDECLARED; } throw new Resolver.Module.Undefined( String.format("name '%s' is not defined", name), predeclared); }; } /** * Represents a lexical block. * * <p>Blocks should not be confused with frames. A block generally (but not always) corresponds to * a syntactic element that may introduce variables; the variable is only accessible within the * block (and its descendants, unless shadowed). A frame is the place where the variable's content * will be stored, and is associated with the current enclosing function. Blocks are used to map * an identifier to the proper variable binding, whereas frames are used to ensure each binding * has a distinct slot of memory. * * <p>In particular, comprehension expressions have their own block but share the same underlying * frame as their enclosing function. This means that comprehension-local variables are not * accessible outside the comprehension, yet these variables are still stored alongside the other * local variables of the function. */ private static class Block { @Nullable private final Block parent; // enclosing block, or null for tail of list @Nullable Node syntax; // Comprehension, DefStatement/LambdaExpression, StarlarkFile, or null private final ArrayList<Binding> frame; // accumulated locals of enclosing function // Accumulated CELL/FREE bindings of the enclosing function that will provide // the values for the free variables of this function; see Function.getFreeVars. // Null for toplevel functions and expressions, which have no free variables. @Nullable private final ArrayList<Binding> freevars; // Bindings for names defined in this block. // Also, as an optimization, memoized lookups of enclosing bindings. private final Map<String, Binding> bindings = new HashMap<>(); Block( @Nullable Block parent, @Nullable Node syntax, ArrayList<Binding> frame, @Nullable ArrayList<Binding> freevars) { this.parent = parent; this.syntax = syntax; this.frame = frame; this.freevars = freevars; } } private final List<SyntaxError> errors; private final FileOptions options; private final Module module; // List whose order defines the numbering of global variables in this program. private final List<String> globals = new ArrayList<>(); // A cache of PREDECLARED, UNIVERSAL, and GLOBAL bindings queried from the module. private final Map<String, Binding> toplevel = new HashMap<>(); // Linked list of blocks, innermost first, for functions and comprehensions and (finally) file. private Block locals; private int loopCount; private Resolver(List<SyntaxError> errors, Module module, FileOptions options) { this.errors = errors; this.module = module; this.options = options; } // Formats and reports an error at the start of the specified node. @FormatMethod private void errorf(Node node, String format, Object... args) { errorf(node.getStartLocation(), format, args); } // Formats and reports an error at the specified location. @FormatMethod private void errorf(Location loc, String format, Object... args) { errors.add(new SyntaxError(loc, String.format(format, args))); } /** * First pass: add bindings for all variables to the current block. This is done because symbols * are sometimes used before their definition point (e.g. functions are not necessarily declared * in order). */ private void createBindingsForBlock(Iterable<Statement> stmts) { for (Statement stmt : stmts) { createBindings(stmt); } } private void createBindings(Statement stmt) { switch (stmt.kind()) { case ASSIGNMENT: createBindingsForLHS(((AssignmentStatement) stmt).getLHS()); break; case IF: IfStatement ifStmt = (IfStatement) stmt; createBindingsForBlock(ifStmt.getThenBlock()); if (ifStmt.getElseBlock() != null) { createBindingsForBlock(ifStmt.getElseBlock()); } break; case FOR: ForStatement forStmt = (ForStatement) stmt; createBindingsForLHS(forStmt.getVars()); createBindingsForBlock(forStmt.getBody()); break; case DEF: DefStatement def = (DefStatement) stmt; bind(def.getIdentifier(), /*isLoad=*/ false); break; case LOAD: LoadStatement load = (LoadStatement) stmt; Set<String> names = new HashSet<>(); for (LoadStatement.Binding b : load.getBindings()) { // Reject load('...', '_private'). Identifier orig = b.getOriginalName(); if (orig.isPrivate() && !options.allowLoadPrivateSymbols()) { errorf(orig, "symbol '%s' is private and cannot be imported", orig.getName()); } // A load statement may not bind a single name more than once, // even if options.allowToplevelRebinding. Identifier local = b.getLocalName(); if (names.add(local.getName())) { bind(local, /*isLoad=*/ true); } else { errorf(local, "load statement defines '%s' more than once", local.getName()); } } break; case EXPRESSION: case FLOW: case RETURN: // nothing to declare } } private void createBindingsForLHS(Expression lhs) { for (Identifier id : Identifier.boundIdentifiers(lhs)) { bind(id, /*isLoad=*/ false); } } private void assign(Expression lhs) { if (lhs instanceof Identifier) { // Bindings are created by the first pass (createBindings), // so there's nothing to do here. } else if (lhs instanceof IndexExpression) { visit(lhs); } else if (lhs instanceof ListExpression) { for (Expression elem : ((ListExpression) lhs).getElements()) { assign(elem); } } else if (lhs instanceof DotExpression) { visit(((DotExpression) lhs).getObject()); } else { errorf(lhs, "cannot assign to '%s'", lhs); } } @Override public void visit(Identifier id) { Binding bind = use(id); if (bind != null) { id.setBinding(bind); return; } } @Override public void visit(ReturnStatement node) { if (locals.syntax instanceof StarlarkFile) { errorf(node, "return statements must be inside a function"); } super.visit(node); } @Override public void visit(CallExpression node) { // validate call arguments boolean seenVarargs = false; boolean seenKwargs = false; Set<String> keywords = null; for (Argument arg : node.getArguments()) { if (arg instanceof Argument.Positional) { if (seenVarargs) { errorf(arg, "positional argument may not follow *args"); } else if (seenKwargs) { errorf(arg, "positional argument may not follow **kwargs"); } else if (keywords != null) { errorf(arg, "positional argument may not follow keyword argument"); } } else if (arg instanceof Argument.Keyword) { String keyword = ((Argument.Keyword) arg).getName(); if (seenVarargs) { errorf(arg, "keyword argument %s may not follow *args", keyword); } else if (seenKwargs) { errorf(arg, "keyword argument %s may not follow **kwargs", keyword); } if (keywords == null) { keywords = new HashSet<>(); } if (!keywords.add(keyword)) { errorf(arg, "duplicate keyword argument: %s", keyword); } } else if (arg instanceof Argument.Star) { if (seenKwargs) { errorf(arg, "*args may not follow **kwargs"); } else if (seenVarargs) { errorf(arg, "multiple *args not allowed"); } seenVarargs = true; } else if (arg instanceof Argument.StarStar) { if (seenKwargs) { errorf(arg, "multiple **kwargs not allowed"); } seenKwargs = true; } } super.visit(node); } @Override public void visit(ForStatement node) { if (locals.syntax instanceof StarlarkFile) { errorf( node, "for loops are not allowed at the top level. You may move it inside a function " + "or use a comprehension, [f(x) for x in sequence]"); } loopCount++; visit(node.getCollection()); assign(node.getVars()); visitBlock(node.getBody()); Preconditions.checkState(loopCount > 0); loopCount--; } @Override public void visit(LoadStatement node) { if (!(locals.syntax instanceof StarlarkFile)) { errorf(node, "load statement not at top level"); } // Skip super.visit: don't revisit local Identifier as a use. } @Override public void visit(FlowStatement node) { if (node.getFlowKind() != TokenKind.PASS && loopCount <= 0) { errorf(node, "%s statement must be inside a for loop", node.getFlowKind()); } super.visit(node); } @Override public void visit(DotExpression node) { visit(node.getObject()); // Do not visit the field. } @Override public void visit(Comprehension node) { ImmutableList<Comprehension.Clause> clauses = node.getClauses(); // Following Python3, the first for clause is resolved // outside the comprehension block. All the other loops // are resolved in the scope of their own bindings, // permitting forward references. Comprehension.For for0 = (Comprehension.For) clauses.get(0); visit(for0.getIterable()); // A comprehension defines a distinct lexical block in the same function's frame. // New bindings go in the frame but aren't visible to the parent block. pushLocalBlock(node, this.locals.frame, this.locals.freevars); for (Comprehension.Clause clause : clauses) { if (clause instanceof Comprehension.For) { Comprehension.For forClause = (Comprehension.For) clause; createBindingsForLHS(forClause.getVars()); } } for (int i = 0; i < clauses.size(); i++) { Comprehension.Clause clause = clauses.get(i); if (clause instanceof Comprehension.For) { Comprehension.For forClause = (Comprehension.For) clause; if (i > 0) { visit(forClause.getIterable()); } assign(forClause.getVars()); } else { Comprehension.If ifClause = (Comprehension.If) clause; visit(ifClause.getCondition()); } } visit(node.getBody()); popLocalBlock(); } @Override public void visit(DefStatement node) { node.setResolvedFunction( resolveFunction( node, node.getIdentifier().getName(), node.getIdentifier().getStartLocation(), node.getParameters(), node.getBody())); } @Override public void visit(LambdaExpression expr) { expr.setResolvedFunction( resolveFunction( expr, "lambda", expr.getStartLocation(), expr.getParameters(), ImmutableList.of(ReturnStatement.make(expr.getBody())))); } @Override public void visit(IfStatement node) { if (locals.syntax instanceof StarlarkFile) { errorf( node, "if statements are not allowed at the top level. You may move it inside a function " + "or use an if expression (x if condition else y)."); } super.visit(node); } @Override public void visit(AssignmentStatement node) { visit(node.getRHS()); // Disallow: [e, ...] += rhs // Other bad cases are handled in assign. if (node.isAugmented() && node.getLHS() instanceof ListExpression) { errorf( node.getOperatorLocation(), "cannot perform augmented assignment on a list or tuple expression"); } assign(node.getLHS()); } // Resolves a non-binding identifier to an existing binding, or null. @Nullable private Binding use(Identifier id) { String name = id.getName(); // Locally defined in this function, comprehension, // or file block, or an enclosing one? Binding bind = lookupLexical(name, locals); if (bind != null) { return bind; } // Defined at toplevel (global, predeclared, universal)? bind = toplevel.get(name); if (bind != null) { return bind; } Scope scope; try { scope = module.resolve(name); } catch (Resolver.Module.Undefined ex) { if (!Identifier.isValid(name)) { // If Identifier was created by Parser.makeErrorExpression, it // contains misparsed text. Ignore ex and report an appropriate error. errorf(id, "contains syntax errors"); } else if (ex.candidates != null) { // Exception provided toplevel candidates. // Show spelling suggestions of all symbols in scope, String suggestion = SpellChecker.didYouMean(name, getAllSymbols(ex.candidates)); errorf(id, "%s%s", ex.getMessage(), suggestion); } else { errorf(id, "%s", ex.getMessage()); } return null; } switch (scope) { case GLOBAL: bind = new Binding(scope, globals.size(), id); // Accumulate globals in module. globals.add(name); break; case PREDECLARED: case UNIVERSAL: bind = new Binding(scope, 0, id); // index not used break; default: throw new IllegalStateException("bad scope: " + scope); } toplevel.put(name, bind); return bind; } // lookupLexical finds a lexically enclosing local binding of the name, // plumbing it through enclosing functions as needed. private static Binding lookupLexical(String name, Block b) { Binding bind = b.bindings.get(name); if (bind != null) { return bind; } if (b.parent != null) { bind = lookupLexical(name, b.parent); if (bind != null) { // If a local binding was found in a parent block, // and this block is a function, then it is a free variable // of this function and must be plumbed through. // Add an implicit FREE binding (a hidden parameter) to this function, // and record the outer binding that will supply its value when // we construct the closure. // Also, mark the outer LOCAL as a CELL: a shared, indirect local. // (For a comprehension block there's nothing to do, // because it's part of the same frame as the enclosing block.) // // This step may occur many times if the lookupLexical // recursion returns through many functions. if (b.syntax instanceof DefStatement || b.syntax instanceof LambdaExpression) { Scope scope = bind.getScope(); if (scope == Scope.LOCAL || scope == Scope.FREE || scope == Scope.CELL) { if (scope == Scope.LOCAL) { bind.scope = Scope.CELL; } int index = b.freevars.size(); b.freevars.add(bind); bind = new Binding(Scope.FREE, index, bind.first); } } // Memoize, to avoid duplicate free vars and repeated walks. b.bindings.put(name, bind); } } return bind; } // Common code for def, lambda. private Function resolveFunction( Node syntax, // DefStatement or LambdaExpression String name, Location loc, ImmutableList<Parameter> parameters, ImmutableList<Statement> body) { // Resolve defaults in enclosing environment. for (Parameter param : parameters) { if (param instanceof Parameter.Optional) { visit(param.getDefaultValue()); } } // Enter function block. ArrayList<Binding> frame = new ArrayList<>(); ArrayList<Binding> freevars = new ArrayList<>(); pushLocalBlock(syntax, frame, freevars); // Check parameter order and convert to run-time order: // positionals, keyword-only, *args, **kwargs. Parameter.Star star = null; Parameter.StarStar starStar = null; boolean seenOptional = false; int numKeywordOnlyParams = 0; // TODO(adonovan): opt: when all Identifiers are resolved to bindings accumulated // in the function, params can be a prefix of the function's array of bindings. ImmutableList.Builder<Parameter> params = ImmutableList.builderWithExpectedSize(parameters.size()); for (Parameter param : parameters) { if (param instanceof Parameter.Mandatory) { // e.g. id if (starStar != null) { errorf( param, "required parameter %s may not follow **%s", param.getName(), starStar.getName()); } else if (star != null) { numKeywordOnlyParams++; } else if (seenOptional) { errorf( param, "required positional parameter %s may not follow an optional parameter", param.getName()); } bindParam(params, param); } else if (param instanceof Parameter.Optional) { // e.g. id = default seenOptional = true; if (starStar != null) { errorf(param, "optional parameter may not follow **%s", starStar.getName()); } else if (star != null) { numKeywordOnlyParams++; } bindParam(params, param); } else if (param instanceof Parameter.Star) { // * or *args if (starStar != null) { errorf(param, "* parameter may not follow **%s", starStar.getName()); } else if (star != null) { errorf(param, "multiple * parameters not allowed"); } else { star = (Parameter.Star) param; } } else { // **kwargs if (starStar != null) { errorf(param, "multiple ** parameters not allowed"); } starStar = (Parameter.StarStar) param; } } // * or *args if (star != null) { if (star.getIdentifier() != null) { bindParam(params, star); } else if (numKeywordOnlyParams == 0) { errorf(star, "bare * must be followed by keyword-only parameters"); } } // **kwargs if (starStar != null) { bindParam(params, starStar); } createBindingsForBlock(body); visitAll(body); popLocalBlock(); return new Function( name, loc, params.build(), body, star != null && star.getIdentifier() != null, starStar != null, numKeywordOnlyParams, frame, freevars, globals); } private void bindParam(ImmutableList.Builder<Parameter> params, Parameter param) { if (bind(param.getIdentifier(), /*isLoad=*/ false)) { errorf(param, "duplicate parameter: %s", param.getName()); } params.add(param); } /** * Process a binding use of a name by adding a binding to the current block if not already bound, * and associate the identifier with it. Reports whether the name was already bound in this block. */ private boolean bind(Identifier id, boolean isLoad) { String name = id.getName(); boolean isNew = false; Binding bind; // TODO(adonovan): factor out bindLocal/bindGlobal cases // and simply the condition below. // outside any function/comprehension, and not a (local) load? => global binding. if (locals.syntax instanceof StarlarkFile && !(isLoad && !options.loadBindsGlobally())) { bind = toplevel.get(name); if (bind == null) { // New global binding: add to module and to toplevel cache. isNew = true; bind = new Binding(Scope.GLOBAL, globals.size(), id); globals.add(name); toplevel.put(name, bind); // Does this new global binding conflict with a file-local load binding? Binding prevLocal = locals.bindings.get(name); if (prevLocal != null) { globalLocalConflict(id, bind.scope, prevLocal); // global, local } } else { toplevelRebinding(id, bind); // global, global } } else { // Binding is local to file, function, or comprehension. bind = locals.bindings.get(name); if (bind == null) { // New local binding: add to current block's bindings map, current function's frame. // (These are distinct entities in the case where the current block is a comprehension.) isNew = true; bind = new Binding(Scope.LOCAL, locals.frame.size(), id); locals.bindings.put(name, bind); locals.frame.add(bind); } if (isLoad) { // Does this (file-local) load binding conflict with a previous one? if (!isNew) { toplevelRebinding(id, bind); // local, local } // ...or a previous global? Binding prev = toplevel.get(name); if (prev != null && prev.scope == Scope.GLOBAL) { globalLocalConflict(id, bind.scope, prev); // local, global } } } id.setBinding(bind); return !isNew; } // Report conflicting top-level bindings of same scope, unless options.allowToplevelRebinding. private void toplevelRebinding(Identifier id, Binding prev) { if (!options.allowToplevelRebinding()) { errorf(id, "'%s' redeclared at top level", id.getName()); if (prev.first != null) { errorf(prev.first, "'%s' previously declared here", id.getName()); } } } // Report global/local scope conflict on top-level bindings. private void globalLocalConflict(Identifier id, Scope scope, Binding prev) { String newqual = scope == Scope.GLOBAL ? "global" : "file-local"; String oldqual = prev.getScope() == Scope.GLOBAL ? "global" : "file-local"; errorf(id, "conflicting %s declaration of '%s'", newqual, id.getName()); if (prev.first != null) { errorf(prev.first, "'%s' previously declared as %s here", id.getName(), oldqual); } } // Returns the union of accessible local and top-level symbols. private Set<String> getAllSymbols(Set<String> predeclared) { Set<String> all = new HashSet<>(); for (Block b = locals; b != null; b = b.parent) { all.addAll(b.bindings.keySet()); } all.addAll(predeclared); all.addAll(toplevel.keySet()); return all; } // Report an error if a load statement appears after another kind of statement. private void checkLoadAfterStatement(List<Statement> statements) { Statement firstStatement = null; for (Statement statement : statements) { // Ignore string literals (e.g. docstrings). if (statement instanceof ExpressionStatement && ((ExpressionStatement) statement).getExpression() instanceof StringLiteral) { continue; } if (statement instanceof LoadStatement) { if (firstStatement == null) { continue; } errorf(statement, "load statements must appear before any other statement"); errorf(firstStatement, "\tfirst non-load statement appears here"); } if (firstStatement == null) { firstStatement = statement; } } } /** * Performs static checks, including resolution of identifiers in {@code file} in the environment * defined by {@code module}. The StarlarkFile is mutated. Errors are appended to {@link * StarlarkFile#errors}. */ public static void resolveFile(StarlarkFile file, Module module) { Resolver r = new Resolver(file.errors, module, file.getOptions()); ImmutableList<Statement> stmts = file.getStatements(); // Check that load statements are on top. if (r.options.requireLoadStatementsFirst()) { r.checkLoadAfterStatement(stmts); } ArrayList<Binding> frame = new ArrayList<>(); r.pushLocalBlock(file, frame, /*freevars=*/ null); // First pass: creating bindings for statements in this block. r.createBindingsForBlock(stmts); // Second pass: visit all references. r.visitAll(stmts); r.popLocalBlock(); // If the final statement is an expression, synthesize a return statement. int n = stmts.size(); if (n > 0 && stmts.get(n - 1) instanceof ExpressionStatement) { Expression expr = ((ExpressionStatement) stmts.get(n - 1)).getExpression(); stmts = ImmutableList.<Statement>builder() .addAll(stmts.subList(0, n - 1)) .add(ReturnStatement.make(expr)) .build(); } // Annotate with resolved information about the toplevel function. file.setResolvedFunction( new Function( "<toplevel>", file.getStartLocation(), /*params=*/ ImmutableList.of(), /*body=*/ stmts, /*hasVarargs=*/ false, /*hasKwargs=*/ false, /*numKeywordOnlyParams=*/ 0, frame, /*freevars=*/ ImmutableList.of(), r.globals)); } /** * Performs static checks, including resolution of identifiers in {@code expr} in the environment * defined by {@code module}. This operation mutates the Expression. Syntax must be resolved * before it is evaluated. */ public static Function resolveExpr(Expression expr, Module module, FileOptions options) throws SyntaxError.Exception { List<SyntaxError> errors = new ArrayList<>(); Resolver r = new Resolver(errors, module, options); ArrayList<Binding> frame = new ArrayList<>(); r.pushLocalBlock(null, frame, /*freevars=*/ null); // for bindings in list comprehensions r.visit(expr); r.popLocalBlock(); if (!errors.isEmpty()) { throw new SyntaxError.Exception(errors); } // Return no-arg function that computes the expression. return new Function( "<expr>", expr.getStartLocation(), /*params=*/ ImmutableList.of(), ImmutableList.of(ReturnStatement.make(expr)), /*hasVarargs=*/ false, /*hasKwargs=*/ false, /*numKeywordOnlyParams=*/ 0, frame, /*freevars=*/ ImmutableList.of(), r.globals); } private void pushLocalBlock( Node syntax, ArrayList<Binding> frame, @Nullable ArrayList<Binding> freevars) { locals = new Block(locals, syntax, frame, freevars); } private void popLocalBlock() { locals = locals.parent; } }
bazelbuild/bazel
src/main/java/net/starlark/java/syntax/Resolver.java
179,690
package net.fe.modifier; import net.fe.builderStage.ShopMenu; import net.fe.builderStage.TeamBuilderStage; import net.fe.builderStage.TeamSelectionStage; import net.fe.overworldStage.OverworldStage; import net.fe.unit.Unit; // Everyone's hit rate is halved and crit rate doubled public class Vegas implements Modifier { /** * */ private static final long serialVersionUID = 3407505862142624494L; @Override public void modifyTeam(TeamBuilderStage stage) { } @Override public void modifyShop(ShopMenu shop) { } @Override public void modifyUnits(TeamSelectionStage stage) { } @Override public void initOverworld(OverworldStage stage) { for(Unit u : stage.getAllUnits()) { u.addSkill(new Gamble()); } } @Override public void endOfTurn(OverworldStage stage) { // TODO Auto-generated method stub } @Override public String getDescription() { return "Gamble! All units have halved hit rates and doubled crit rates."; } public String toString() { return "Vegas"; } }
chudooder/FEMultiplayer
src/net/fe/modifier/Vegas.java
179,691
package net.fe.modifier; import net.fe.builderStage.ShopMenu; import net.fe.builderStage.TeamBuilderResources; import net.fe.unit.Item; import net.fe.unit.Unit; // TODO: Auto-generated Javadoc /** * Everyone's hit rate is halved and crit rate doubled */ public final class Vegas implements Modifier { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 3407505862142624494L; /* (non-Javadoc) * @see net.fe.modifier.Modifier#modifyTeam(net.fe.builderStage.TeamBuilderStage) */ @Override public TeamBuilderResources modifyTeamResources(TeamBuilderResources limits) { return limits; } /* (non-Javadoc) * @see net.fe.modifier.Modifier#modifyShop(net.fe.builderStage.ShopMenu) */ @Override public Iterable<Item> modifyShop(Iterable<Item> shop) { return shop; } /* (non-Javadoc) * @see net.fe.modifier.Modifier#initOverworld(net.fe.overworldStage.OverworldStage) */ @Override public void initOverworldUnits(Iterable<Unit> units) { for(Unit u : units) { u.addSkill(new Gamble()); } } /* (non-Javadoc) * @see net.fe.modifier.Modifier#getDescription() */ @Override public String getDescription() { return "Gamble! All units have halved hit rates and doubled crit rates."; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return "Vegas"; } }
HamaIndustries/FEMultiPlayer-V2
src/net/fe/modifier/Vegas.java