file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
Line.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/Line.java | package mahomaps.map;
import javax.microedition.lcdui.Graphics;
import mahomaps.screens.MapCanvas;
public class Line {
public final Geopoint start;
private final Geopoint[] source;
private int forZoom = -1;
private int[] cache = null;
private int thickness = 2;
public int drawFrom = 0;
public Line(Geopoint start, Geopoint[] source) {
this.start = start;
this.source = source;
}
private void Invalidate(MapState ms) {
ms = ms.Clone();
forZoom = ms.zoom;
int xa = start.GetScreenX(ms);
int ya = start.GetScreenY(ms);
int[] temp = new int[source.length * 2];
int ti = -1;
for (int i = Math.max(0, drawFrom); i < source.length; i++) {
int px = source[i].GetScreenX(ms) - xa;
int py = source[i].GetScreenY(ms) - ya;
if (ti >= 0) {
if (temp[ti * 2] != px || temp[ti * 2 + 1] != py)
ti++;
} else {
ti++;
}
temp[ti * 2] = px;
temp[ti * 2 + 1] = py;
}
cache = new int[(ti + 1) * 2];
System.arraycopy(temp, 0, cache, 0, cache.length);
if (forZoom <= 7)
thickness = 0;
else if (forZoom <= 14)
thickness = 1;
else
thickness = 2;
}
public void Invalidate() {
forZoom = -1;
}
public synchronized void Draw(Graphics g, MapCanvas map) {
if (map.state.zoom != forZoom)
Invalidate(map.state);
final int cw = map.getWidth();
final int ch = map.getHeight();
final int px = start.GetScreenX(map.state);
final int py = start.GetScreenY(map.state);
for (int i = 2; i < cache.length; i += 2) {
int x1 = px + cache[i - 2];
int y1 = py + cache[i - 1];
int x2 = px + cache[i];
int y2 = py + cache[i + 1];
boolean vis1 = Math.abs(x1) < cw && Math.abs(y1) < ch;
boolean vis2 = Math.abs(x2) < cw && Math.abs(y2) < ch;
if (!vis1 && !vis2)
continue;
g.setColor(0xff0000);
if (thickness == 0) {
g.drawLine(x1, y1, x2, y2);
} else {
// second point
if (thickness == 1) {
g.fillRect(x2 - 1, y2 - 1, 2, 2);
} else {
g.fillRect(x2 - (thickness >> 1), y2 - thickness, thickness, thickness << 1);
g.fillRect(x2 - thickness, y2 - (thickness >> 1), thickness << 1, thickness);
}
// line
{
final int hor = Math.abs(x2 - x1);
final int ver = Math.abs(y2 - y1);
if (hor > ver) {
g.fillTriangle(x1, y1 - thickness, x1, y1 + thickness, x2, y2 + thickness);
g.fillTriangle(x1, y1 - thickness, x2, y2 - thickness, x2, y2 + thickness);
} else {
g.fillTriangle(x1 - thickness, y1, x1 + thickness, y1, x2 - thickness, y2);
g.fillTriangle(x2 + thickness, y2, x1 + thickness, y1, x2 - thickness, y2);
}
}
}
}
}
}
| 2,612 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
TileId.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/TileId.java | package mahomaps.map;
public class TileId {
public final int x;
public final int y;
public final int zoom;
public final int map;
public TileId(int x, int y, int zoom, int map) {
this.x = x;
this.y = y;
this.zoom = zoom;
this.map = map;
}
}
| 257 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MapState.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/MapState.java | package mahomaps.map;
import cc.nnproject.json.JSON;
import cc.nnproject.json.JSONObject;
import mahomaps.Settings;
public class MapState {
public int tileX, tileY;
public int xOffset, yOffset;
public int zoom;
public final void ClampOffset() {
while (xOffset > 0) {
tileX--;
xOffset -= 256;
}
while (yOffset > 0) {
tileY--;
yOffset -= 256;
}
while (xOffset < -255) {
tileX++;
xOffset += 256;
}
while (yOffset < -255) {
tileY++;
yOffset += 256;
}
final int tc = (1 << zoom);
if (tileX < 0)
tileX += tc;
if (tileX >= tc)
tileX -= tc;
if (tileY < 0) {
tileY = 0;
yOffset = 0;
}
if (tileY >= tc) {
tileY = tc - 1;
yOffset = -255;
}
}
public MapState Clone() {
MapState ms = new MapState();
ms.tileX = tileX;
ms.tileY = tileY;
ms.xOffset = xOffset;
ms.yOffset = yOffset;
ms.zoom = zoom;
return ms;
}
public MapState ZoomIn() {
if (zoom >= 18)
return Clone();
MapState ms = new MapState();
ms.zoom = zoom + 1;
ms.tileX = tileX * 2;
ms.tileY = tileY * 2;
ms.xOffset = xOffset * 2;
ms.yOffset = yOffset * 2;
ms.ClampOffset();
return ms;
}
public MapState ZoomOut() {
if (zoom <= 0)
return Clone();
MapState ms = new MapState();
ms.zoom = zoom - 1;
ms.tileX = tileX / 2;
ms.tileY = tileY / 2;
ms.xOffset = (xOffset - (tileX % 2 == 1 ? 256 : 0)) / 2;
ms.yOffset = (yOffset - (tileY % 2 == 1 ? 256 : 0)) / 2;
ms.ClampOffset();
return ms;
}
public static MapState FocusAt(Geopoint p) {
return FocusAt(p, Settings.focusZoom);
}
public static MapState FocusAt(Geopoint p, int zoom) {
MapState ms = new MapState();
ms.zoom = zoom;
ms.xOffset -= p.GetScreenX(ms);
ms.yOffset -= p.GetScreenY(ms);
ms.ClampOffset();
return ms;
}
public static MapState Default() {
MapState ms = new MapState();
ms.zoom = 0;
ms.xOffset = -128;
ms.yOffset = -128;
return ms;
}
public String Encode() {
JSONObject j = new JSONObject();
j.put("z", zoom);
j.put("x", tileX);
j.put("y", tileY);
j.put("xo", xOffset);
j.put("yo", yOffset);
return j.toString();
}
public static MapState Decode(String s) {
final JSONObject j = JSON.getObject(s);
final MapState ms = new MapState();
ms.zoom = j.getInt("z", 0);
ms.tileX = j.getInt("x", 0);
ms.tileY = j.getInt("y", 0);
ms.xOffset = j.getInt("xo", 0);
ms.yOffset = j.getInt("yo", 0);
ms.ClampOffset();
return ms;
}
public String toString() {
return "X: " + xOffset + "|" + tileX + " Y: " + yOffset + "|" + tileY + " Z: " + zoom;
}
}
| 2,562 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
TilesProvider.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/TilesProvider.java | package mahomaps.map;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;
import mahomaps.Gate;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import mahomaps.api.YmapsApiBase;
import mahomaps.overlays.TileCacheForbiddenOverlay;
import mahomaps.overlays.TileDownloadForbiddenOverlay;
import tube42.lib.imagelib.ImageUtils;
import mahomaps.overlays.CacheFailedOverlay;
public class TilesProvider implements Runnable {
private static final String INVALID_THREAD_ERR = "Map paint can be performed only from update thread.";
public final String lang;
/**
* Path to the local folder with tiles. Must be with trailing slash and with
* protocol, i.e. file:///E:/ym/
*/
private String localPath;
/**
* Кэш всех загруженых плиток. Данный список должен изменяться ТОЛЬКО из потока
* цикла отрисовки. Содержимое объектов списка должно изменяться ТОЛЬКО из
* потока скачивания тайлов.
* <hr>
* Блокировки: <br>
* Вектор - перебор объектов для удаления или для выбора для скачивание <br>
* Объект вектора - изменения {@link TileCache#state} или удаление из вектора.
*/
private Vector cache = new Vector();
private final Gate downloadGate = new Gate(false);
private final Gate cacheGate = new Gate(true);
private final Object cacheAccessLock = new Object();
private boolean paintState = false;
private Thread networkTh;
private Thread cacheTh;
public static final String[] tilesUrls = new String[] {
// scheme light
"https://core-renderer-tiles.maps.yandex.net/tiles?l=map&lang=",
// sat
"https://core-sat.maps.yandex.net/tiles?l=sat&lang=",
// hybrid
"http://nnp.nnchan.ru/mergedtile.php?lang=",
// scheme dark
"https://core-renderer-tiles.maps.yandex.net/tiles?l=map&theme=dark&lang=" };
public static final int[] layerNames = new int[] { 55, 154, 155, 167 };
public static final String[] GetLayerNames() {
if (layerNames.length != tilesUrls.length)
throw new IllegalStateException("Not all tiles have names!");
String[] s = new String[layerNames.length];
for (int i = 0; i < s.length; i++) {
s[i] = MahoMapsApp.text[layerNames[i]];
}
return s;
}
public String GetLocalPath() {
return localPath;
}
public TilesProvider(String lang) {
if (lang == null)
throw new NullPointerException("Language must be non-null!");
this.lang = lang;
}
public void Start() {
if (networkTh != null || cacheTh != null)
throw new IllegalStateException("Can't start already running tiles provider!");
networkTh = new Thread(this, "Tiles downloader");
cacheTh = new Thread(this, "Tiles cache reader");
networkTh.start();
cacheTh.start();
}
public void Stop() {
if (networkTh != null)
networkTh.interrupt();
networkTh = null;
if (cacheTh != null)
cacheTh.interrupt();
cacheTh = null;
}
public void InitFSCache(String path) throws IOException, SecurityException {
FileConnection fc = (FileConnection) Connector.open(path);
try {
if (!fc.exists())
fc.mkdir();
localPath = path;
} finally {
fc.close();
}
}
public void ForceMissingDownload() {
synchronized (cache) {
for (int i = 0; i < cache.size(); i++) {
TileCache tc = (TileCache) cache.elementAt(i);
synchronized (tc) {
if (tc.state == TileCache.STATE_MISSING || tc.state == TileCache.STATE_ERROR) {
tc.state = TileCache.STATE_CACHE_PENDING;
}
}
}
}
cacheGate.Reset();
downloadGate.Reset();
}
public void run() {
if (Thread.currentThread() == networkTh) {
RunNetwork();
} else if (Thread.currentThread() == cacheTh) {
RunCache();
} else {
throw new IllegalStateException("Unknown thread type!");
}
}
public void RunCache() {
try {
// цикл обработки
while (true) {
int i = -1;
// цикл перебора тайлов в очереди
while (true) {
TileCache tc = null;
synchronized (cache) {
// инкремент + проверки выхода за границы
i++;
int s = cache.size();
if (i >= s)
break;
tc = (TileCache) cache.elementAt(i);
}
{
// attempt to check state without taking lock
int s = tc.state;
switch (s) {
case TileCache.STATE_CACHE_PENDING:
case TileCache.STATE_CACHE_LOADING:
// we need to take lock and recheck.
break;
default:
// we can't transit from any futher state to cache reads.
// next tile!
continue;
}
}
synchronized (tc) {
switch (tc.state) {
case TileCache.STATE_CACHE_PENDING:
// состояние
tc.state = TileCache.STATE_CACHE_LOADING;
// читаем кэш
break;
case TileCache.STATE_CACHE_LOADING:
throw new IllegalStateException(
tc.toString() + " was in cache loading state before loading sequence!");
default:
throw new IllegalStateException(tc.toString()
+ " changed its state from cache pending/wait to something else during monitor catch!");
}
}
Image img = tryLoad(tc);
boolean tryDownloadAnyway = false;
// if tile is not cached...
if (img == null) {
// and cache lookup actually was attempted...
if (Settings.cacheMode != Settings.CACHE_DISABLED) {
// but we can't download it
if (!Settings.allowDownload) {
// let's try lower zooms and upscale them.
img = tryLoadFallback(tc);
}
// or scaling explicitly allowed before downloading
else if (Settings.readCachedBeforeDownloading) {
// let's try lower zooms and upscale them.
img = tryLoadFallback(tc);
// but still attempt to download
tryDownloadAnyway = true;
}
}
}
synchronized (tc) {
if (img != null) {
tc.img = img;
// readCachedBeforeDownloading is still require server lookup
if (tryDownloadAnyway) {
tc.state = TileCache.STATE_SERVER_PENDING;
downloadGate.Reset();
} else {
tc.state = TileCache.STATE_READY;
MahoMapsApp.GetCanvas().requestRepaint();
}
} else if (Settings.allowDownload) {
tc.state = TileCache.STATE_SERVER_PENDING;
downloadGate.Reset();
} else {
tc.state = TileCache.STATE_MISSING;
}
}
} // конец перебора очереди
cacheGate.Pass();
}
} catch (InterruptedException e) {
}
}
private final Image tryLoad(TileId id) {
if (Settings.cacheMode == Settings.CACHE_FS && localPath != null) {
return tryLoadFromFS(id);
} else if (Settings.cacheMode == Settings.CACHE_RMS) {
return tryLoadFromRMS(id);
}
return null;
}
private final Image tryLoadFallback(TileId id) {
final int map = id.map;
int zoom = id.zoom;
int downscale = 1; // how small is required tile comparing to loaded one
int x = id.x;
int y = id.y;
int xoff = 0; // in tile sizes
int yoff = 0;
while (true) {
zoom -= 1;
if (zoom < 0 || downscale >= 64)
return null;
if (x % 2 == 1)
xoff += downscale;
if (y % 2 == 1)
yoff += downscale;
// at downscale of 2 above ops require 1, at 4 - 2 and so on
downscale *= 2;
x /= 2;
y /= 2;
Image raw = tryLoad(new TileId(x, y, zoom, map));
if (raw != null) {
int size = (256 / downscale); // of tile
// System.out.println("downscale: " + downscale + ", size: " + size);
// System.out.println("x: " + xoff + ", y: " + yoff);
int xoffp = xoff * size; // in pixels
int yoffp = yoff * size;
Image cropped = ImageUtils.crop(raw, xoffp, yoffp, xoffp + size, yoffp + size);
raw = null; // to free heap
return ImageUtils.resize(cropped, 256, 256, true, false);
}
}
}
public void RunNetwork() {
try {
// цикл обработки
while (true) {
if (!Settings.allowDownload) {
try {
downloadGate.Pass();
} catch (InterruptedException e) {
return;
}
}
int idleCount = 0; // счётчик готовых тайлов (если равен длине кэша - ничего грузить не надо)
int i = -1;
int l = -1;
boolean queueChanged = false;
// цикл перебора тайлов в очереди
while (true) {
TileCache tc = null;
synchronized (cache) {
// инкремент + проверки выхода за границы
i++;
int s = cache.size();
if (l == -1)
l = s;
else if (l != s)
queueChanged = true;
if (i >= s)
break;
tc = (TileCache) cache.elementAt(i);
}
// if tile is ready already, it can't be downloaded again. Skipping without
// taking lock.
if (tc.state == TileCache.STATE_READY) {
idleCount++;
continue;
}
synchronized (tc) {
switch (tc.state) {
case TileCache.STATE_CACHE_PENDING:
case TileCache.STATE_CACHE_LOADING:
// ждём чтения кэша
// к следующему тайлу
continue;
case TileCache.STATE_SERVER_PENDING:
// переключаем состояние
tc.state = TileCache.STATE_SERVER_LOADING;
// начинаем загрузку
break;
case TileCache.STATE_SERVER_LOADING:
throw new IllegalStateException(
tc.toString() + " was in server loading state before loading sequence!");
case TileCache.STATE_READY:
idleCount++;
// к следующему тайлу
continue;
case TileCache.STATE_ERROR:
// переключаем состояние
tc.state = TileCache.STATE_SERVER_LOADING;
// начинаем загрузку
break;
case TileCache.STATE_UNLOADED:
idleCount++;
// к следующему тайлу
continue;
case TileCache.STATE_MISSING:
idleCount++;
// к следующему тайлу
continue;
}
}
Image img = Settings.allowDownload ? download(tc) : null;
boolean fallbackUsed = false;
// if nothing loaded
if (img == null) {
// if the cache available...
if (Settings.cacheMode != Settings.CACHE_DISABLED) {
// let's try lower zooms and upscale them.
// If download is forbidden, this happened in cache thread and this path won't
// run at all.
img = tryLoadFallback(tc);
if (img != null)
fallbackUsed = true;
}
}
boolean waitAfterError = false;
synchronized (tc) {
if (img == null) {
if (Settings.allowDownload) {
tc.state = TileCache.STATE_ERROR;
waitAfterError = true;
} else {
tc.state = TileCache.STATE_MISSING;
}
} else {
tc.img = img;
if (fallbackUsed) {
// image is present, but it's bad. We still want to download a proper one.
tc.state = TileCache.STATE_ERROR;
waitAfterError = true;
} else {
tc.state = TileCache.STATE_READY;
}
MahoMapsApp.GetCanvas().requestRepaint();
}
}
if (waitAfterError)
Thread.sleep(4000);
}
if (idleCount != cache.size() || queueChanged) {
Thread.yield();
continue;
}
downloadGate.Pass();
}
} catch (InterruptedException e) {
}
}
/**
* Скачивает тайл с сервера и помещает его в кэш. Не обрабатывает статусы тайла!
* Не проверяет, разрешена ли загрузка!
*
* @param id Тайл для скачки.
* @return Тайл, либо null в случае ошибки.
* @throws InterruptedException Если поток прерван.
*/
private Image download(TileId id) throws InterruptedException {
HttpConnection hc = null;
FileConnection fc = null;
try {
hc = (HttpConnection) Connector.open(getUrl(id) + MahoMapsApp.getConnectionParams());
int len = (int) hc.getLength();
ByteArrayOutputStream blob = len <= 0 ? new ByteArrayOutputStream() : new ByteArrayOutputStream(len);
byte[] buf = new byte[8192];
InputStream s = hc.openInputStream();
while (true) {
int read = s.read(buf);
if (read == -1)
break;
blob.write(buf, 0, read);
}
buf = null;
s.close();
hc.close();
hc = null;
byte[] blobc = blob.toByteArray();
blob = null;
if (Settings.cacheMode == Settings.CACHE_FS && localPath != null) {
synchronized (cacheAccessLock) {
try {
fc = (FileConnection) Connector.open(getFileName(id), Connector.WRITE);
fc.create();
OutputStream os = fc.openOutputStream();
os.write(blobc);
os.flush();
os.close();
} catch (SecurityException e) {
MahoMapsApp.Overlays().PushOverlay(new TileCacheForbiddenOverlay());
Settings.cacheMode = Settings.CACHE_DISABLED;
} catch (IOException e) {
MahoMapsApp.Overlays().PushOverlay(new CacheFailedOverlay());
Settings.cacheMode = Settings.CACHE_DISABLED;
} finally {
if (fc != null)
fc.close();
fc = null;
}
}
} else if (Settings.cacheMode == Settings.CACHE_RMS) {
synchronized (cacheAccessLock) {
try {
RecordStore r = RecordStore.openRecordStore(getRmsName(id), true);
if (r.getNumRecords() == 0)
r.addRecord(new byte[1], 0, 1);
r.setRecord(1, blobc, 0, blobc.length);
r.closeRecordStore();
} catch (RecordStoreFullException e) {
// TODO: Выводить алерт что место закончилось
} catch (Exception e) {
// TODO: Выводить на экран алерт что закэшить не удалось
e.printStackTrace();
}
}
}
Image img = Image.createImage(blobc, 0, blobc.length);
return img;
} catch (SecurityException e) {
try {
MahoMapsApp.Overlays().PushOverlay(new TileDownloadForbiddenOverlay());
Settings.allowDownload = false;
} catch (RuntimeException e1) {
}
} catch (Exception e) {
} catch (OutOfMemoryError e) {
} finally {
if (hc != null) {
try {
hc.close();
} catch (IOException ex) {
}
}
}
return null;
}
/**
* Пытается прочесть изображение тайла из ФС.
*
* @param id Тайл для поиска.
* @return Изображение, если тайл сохранён, иначе null.
*/
private Image tryLoadFromFS(TileId id) {
synchronized (cacheAccessLock) {
FileConnection fc = null;
try {
fc = (FileConnection) Connector.open(getFileName(id), Connector.READ);
if (!fc.exists()) {
fc.close();
return null;
}
InputStream s = fc.openInputStream();
ByteArrayOutputStream o = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int read;
while ((read = s.read(buf)) != -1) {
o.write(buf, 0, read);
}
s.close();
byte[] b = o.toByteArray();
o.close();
return Image.createImage(b, 0, b.length);
} catch (SecurityException e) {
MahoMapsApp.Overlays().PushOverlay(new TileCacheForbiddenOverlay());
Settings.cacheMode = Settings.CACHE_DISABLED;
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
} finally {
if (fc != null) {
try {
fc.close();
} catch (IOException ex) {
}
}
}
return null;
}
}
/**
* Пытается прочесть изображение тайла из RMS.
*
* @param id Тайл для поиска.
* @return Изображение, если тайл сохранён, иначе null.
*/
private Image tryLoadFromRMS(TileId id) {
synchronized (cacheAccessLock) {
byte[] b = null;
try {
RecordStore r = RecordStore.openRecordStore(getRmsName(id), true);
if (r.getNumRecords() > 0) {
b = r.getRecord(1);
}
r.closeRecordStore();
} catch (RecordStoreNotOpenException e) {
e.printStackTrace();
} catch (RecordStoreException e) {
e.printStackTrace();
}
if (b != null) {
return Image.createImage(b, 0, b.length);
}
return null;
}
}
/**
* Выполняет операции, необходимые перед очередной отрисовкой.
*/
public void BeginMapPaint() {
if (Thread.currentThread() != MahoMapsApp.thread)
throw new IllegalThreadStateException(INVALID_THREAD_ERR);
if (paintState)
throw new IllegalStateException("Paint is already in progress.");
paintState = true;
// lock is not needed because it's modified only from tile get / tile cleanup,
// which happens in this thread.
for (int i = 0; i < cache.size(); i++) {
((TileCache) cache.elementAt(i)).unuseCount++;
}
}
/**
* Выполняет операции, необходимые после очередной отрисовки.
*/
public void EndMapPaint(MapState ms) {
if (Thread.currentThread() != MahoMapsApp.thread)
throw new IllegalThreadStateException(INVALID_THREAD_ERR);
if (!paintState)
throw new IllegalStateException("Paint was not performed.");
paintState = false;
final int reqZoom = ms.zoom;
boolean removed = false;
synchronized (cache) {
for (int i = cache.size() - 1; i > -1; i--) {
TileCache t = (TileCache) cache.elementAt(i);
if (t.unuseCount > 20 || t.zoom != reqZoom) {
synchronized (t) {
switch (t.state) {
case TileCache.STATE_CACHE_LOADING:
case TileCache.STATE_SERVER_LOADING:
// we can't remove this tile
continue;
default:
t.state = TileCache.STATE_UNLOADED;
cache.removeElementAt(i);
removed = true;
break;
}
}
}
}
}
if (removed)
cacheGate.Reset();
}
/**
* Возвращает объект кэша плитки для отрисовки.
*
* @param tileId Идентификатор требуемой плитки.
* @return Объект кэша плитки в любом из возможных состояний. <b>Может вернуть
* null</b> если координаты плитки не находятся в пределах карты
* (например, Y отрицательный).
*/
public TileCache getTile(TileId tileId) {
if (!paintState)
throw new IllegalStateException("Paint was not performing now, can't get tile!");
if (Thread.currentThread() != MahoMapsApp.thread)
throw new IllegalThreadStateException(INVALID_THREAD_ERR);
int max = 0x1 << tileId.zoom;
if (tileId.y < 0)
return null;
if (tileId.y >= max)
return null;
int x = tileId.x;
while (x < 0)
x += max;
while (x >= max)
x -= max;
tileId = new TileId(x, tileId.y, tileId.zoom, tileId.map);
TileCache cached = null;
// modified only from cleanup - lock is not needed
for (int i = 0; i < cache.size(); i++) {
TileCache tile = (TileCache) cache.elementAt(i);
if (tile.is(tileId)) {
cached = tile;
break;
}
}
if (cached != null) {
cached.unuseCount = 0;
return cached;
}
cached = new TileCache(tileId);
cached.state = TileCache.STATE_CACHE_PENDING;
// avoid modifying vector during bounds checks
synchronized (cache) {
cache.addElement(cached);
}
cacheGate.Reset();
return cached;
}
private String getUrl(TileId tileId) {
String url = tilesUrls[tileId.map] + lang + "&x=" + tileId.x + "&y=" + tileId.y + "&z=" + tileId.zoom;
if (Settings.proxyTiles && url.startsWith("https")) {
return Settings.proxyServer + YmapsApiBase.EncodeUrl(url);
}
return url;
}
private String getFileName(TileId id) {
return localPath + getRmsName(id);
}
private String getRmsName(TileId id) {
return "tile_" + lang + "_" + id.x + "_" + id.y + "_" + id.zoom + (id.map > 0 ? "_" + id.map : "");
}
public int GetCachedTilesCount() {
synchronized (cacheAccessLock) {
if (Settings.cacheMode == Settings.CACHE_RMS) {
String[] names = RecordStore.listRecordStores();
if (names == null)
return 0;
int c = 0;
for (int i = 0; i < names.length; i++) {
if (names[i].indexOf("tile_") == 0)
c++;
}
return c;
}
if (Settings.cacheMode == Settings.CACHE_FS) {
FileConnection fc = null;
try {
fc = (FileConnection) Connector.open(localPath, Connector.READ);
Enumeration e = fc.list();
int c = 0;
while (e.hasMoreElements()) {
String object = (String) e.nextElement();
if (object.indexOf("tile_") == 0)
c++;
}
return c;
} catch (Exception e) {
} finally {
if (fc != null)
try {
fc.close();
} catch (IOException e) {
}
}
}
}
return 0;
}
/**
* Удаляет ВСЕ тайлы из выбранного хранилища кэша (рмс/фс).
*/
public void ClearCache() {
synchronized (cacheAccessLock) {
if (Settings.cacheMode == Settings.CACHE_RMS) {
String[] names = RecordStore.listRecordStores();
if (names == null)
return;
for (int i = 0; i < names.length; i++) {
if (names[i].indexOf("tile_") == 0) {
try {
RecordStore.deleteRecordStore(names[i]);
} catch (RecordStoreNotFoundException e) {
} catch (RecordStoreException e) {
}
}
}
}
if (Settings.cacheMode == Settings.CACHE_FS) {
FileConnection fc = null;
try {
fc = (FileConnection) Connector.open(localPath, Connector.READ);
Enumeration e = fc.list();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
if (name.indexOf("tile_") == 0) {
FileConnection fc2 = null;
try {
fc2 = (FileConnection) Connector.open(localPath + name, Connector.WRITE);
fc2.delete();
} catch (Exception e2) {
} finally {
if (fc2 != null)
try {
fc2.close();
} catch (IOException e3) {
}
}
}
}
} catch (Exception e) {
} finally {
if (fc != null)
try {
fc.close();
} catch (IOException e) {
}
}
}
}
}
}
| 22,879 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
UIElement.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/UIElement.java | package mahomaps.ui;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
public abstract class UIElement {
public abstract void Paint(Graphics g, int x, int y, int w, int h);
public int X, Y, W, H;
// INPUT
private static volatile Vector queue = new Vector();
private static volatile Vector queueTemp = new Vector();
private static int selectedIndex = -1;
private static boolean isSelectedInQueue = false;
private static ITouchAcceptor holdElement = null;
public static boolean touchInput;
protected static synchronized void RegisterForInput(ITouchAcceptor ta, int x, int y, int w, int h) {
queueTemp.addElement(new UITouchZone(ta, x, y, w, h));
if (ta == holdElement)
isSelectedInQueue = true;
}
public static synchronized void CommitInputQueue() {
queue = queueTemp;
queueTemp = new Vector(queue.size());
if (holdElement != null) {
if (!isSelectedInQueue) {
InvokeReleaseEvent();
selectedIndex = -1;
}
}
isSelectedInQueue = false;
}
public static synchronized boolean InvokePressEvent(int x, int y) {
InvokeReleaseEvent();
Vector v = queue;
for (int i = v.size() - 1; i >= 0; i--) {
UITouchZone z = (UITouchZone) v.elementAt(i);
if (z.contains(x, y)) {
selectedIndex = i;
z.element.OnPress();
holdElement = z.element;
return true;
}
}
return false;
}
public static synchronized boolean InvokePressEvent(ITouchAcceptor ta) {
InvokeReleaseEvent();
Vector v = queue;
for (int i = v.size() - 1; i >= 0; i--) {
UITouchZone z = (UITouchZone) v.elementAt(i);
if (z.element == ta) {
selectedIndex = i;
z.element.OnPress();
holdElement = z.element;
return true;
}
}
return false;
}
public static synchronized boolean InvokePressEvent(int i) {
InvokeReleaseEvent();
if (i < 0)
return false;
if (i >= queue.size())
return false;
UITouchZone z = (UITouchZone) queue.elementAt(i);
selectedIndex = i;
z.element.OnPress();
holdElement = z.element;
return true;
}
public static synchronized void InvokeReleaseEvent() {
ITouchAcceptor z = holdElement;
holdElement = null;
if (z != null)
z.OnRelease();
}
public static synchronized void SelectUp() {
selectedIndex--;
if (selectedIndex < 0)
selectedIndex = queue.size() - 1;
InvokePressEvent(selectedIndex);
}
public static synchronized void SelectDown() {
selectedIndex++;
if (selectedIndex >= queue.size())
selectedIndex = 0;
InvokePressEvent(selectedIndex);
}
public static synchronized void Deselect() {
selectedIndex = -1;
InvokeReleaseEvent();
}
public static synchronized void TriggerSelected() {
if (holdElement != null)
holdElement.OnTap();
}
public static synchronized boolean IsQueueEmpty() {
return queue.size() == 0;
}
/**
* Looks through the input queue, and invokes touch event on last found
* acceptor.
*
* @param x X.
* @param y Y.
* @return false, if nothing was triggered.
*/
public static synchronized boolean InvokeTouchEvent(int x, int y) {
Vector v = queue;
for (int i = v.size() - 1; i >= 0; i--) {
UITouchZone z = (UITouchZone) v.elementAt(i);
if (z.contains(x, y)) {
z.element.OnTap();
return true;
}
}
return false;
}
}
| 3,249 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
IButtonHandler.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/IButtonHandler.java | package mahomaps.ui;
public interface IButtonHandler {
public void OnButtonTap(UIElement sender, int uid);
}
| 111 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
UIComposite.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/UIComposite.java | package mahomaps.ui;
import java.util.Vector;
public abstract class UIComposite extends UIElement {
public final Vector children = new Vector();
public UIComposite() {
}
public UIComposite(UIElement[] elems) {
for (int i = 0; i < elems.length; i++) {
children.addElement(elems[i]);
}
}
}
| 307 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
ITouchAcceptor.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/ITouchAcceptor.java | package mahomaps.ui;
public interface ITouchAcceptor {
/**
* Событие зажатия. Вызывается при зажатии элемента. Должно использоваться
* только для переключения визуальных состояний.
*/
public void OnPress();
/**
* Событие отпускания. Вызывается, когда ввод больше не считается нажатием, либо
* ввод отпущен. Должно использоваться только для переключения визуальных
* состояний.
*/
public void OnRelease();
/**
* Событие нажатия. Вызывается, когда ввод зажат и отпущен на данном элементе.
* Вызывается после {@link #OnRelease()}.
*/
public void OnTap();
}
| 898 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
Button.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/Button.java | package mahomaps.ui;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class Button extends UIElement implements ITouchAcceptor {
public String text;
private int id;
private IButtonHandler handler;
public int margin = 3;
private boolean hold = false;
public Button(String text, int id, IButtonHandler handler) {
this.text = text;
this.id = id;
this.handler = handler;
UpdateHeight();
}
public void Paint(Graphics g, int x, int y, int w, int h) {
RegisterForInput(this, x, y, w, h);
UpdateHeight();
g.setFont(Font.getFont(0, 0, 8));
if (hold) {
g.setColor(0xFC6155);
g.fillRoundRect(x + margin, y + margin, w - margin - margin, h - margin - margin, 10, 10);
g.setColor(0x343434);
if (UIElement.touchInput)
g.fillRoundRect(x + margin * 2, y + margin * 2, w - margin * 4, h - margin * 4, 10, 10);
else
g.fillRoundRect(x + margin * 4, y + margin + 1, w - margin * 8, h - margin * 2 - 2, 10, 10);
} else {
g.setColor(0x343434);
g.fillRoundRect(x + margin, y + margin, w - margin - margin, h - margin - margin, 10, 10);
}
int fh = g.getFont().getHeight();
g.setColor(-1);
g.drawString(text, x + w / 2, y + h / 2 - fh / 2, Graphics.TOP | Graphics.HCENTER);
}
private final void UpdateHeight() {
this.H = Font.getFont(0, 0, 8).getHeight() + margin * (UIElement.touchInput ? 4 : 2);
}
public void OnPress() {
hold = true;
}
public void OnRelease() {
hold = false;
}
public void OnTap() {
if (handler != null)
handler.OnButtonTap(this, id);
}
}
| 1,565 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SimpleText.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/SimpleText.java | package mahomaps.ui;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class SimpleText extends UIElement {
private String text;
private Font font;
private int hAnchor;
private int vAnchor;
public SimpleText(String s, Font f, int hAnchor, int vAnchor) {
this.text = s;
if (f == null)
f = Font.getFont(0, 0, 8);
this.font = f;
this.hAnchor = hAnchor;
this.vAnchor = vAnchor;
this.W = font.stringWidth(text);
this.H = font.getHeight();
}
public SimpleText(String s) {
this.text = s;
this.font = Font.getFont(0, 0, 8);
this.hAnchor = 0;
this.vAnchor = 0;
this.W = font.stringWidth(text);
this.H = font.getHeight();
}
public void Paint(Graphics g, int x, int y, int w, int h) {
if (text == null)
return;
int rx;
switch (hAnchor) {
case 0:
case Graphics.LEFT:
hAnchor = Graphics.LEFT;
rx = x + 3;
break;
case Graphics.HCENTER:
rx = x + (w >> 1);
break;
case Graphics.RIGHT:
rx = x + w - 3;
break;
default:
throw new IllegalArgumentException();
}
int ry;
int va;
switch (vAnchor) {
case 0:
case Graphics.TOP:
ry = y;
va = Graphics.TOP;
break;
case Graphics.VCENTER:
ry = y + (h >> 1) - (font.getHeight() >> 1);
va = Graphics.TOP;
break;
case Graphics.BOTTOM:
ry = y + h;
va = Graphics.BOTTOM;
default:
throw new IllegalArgumentException();
}
g.setFont(font);
g.setColor(-1);
g.drawString(text, rx, ry, hAnchor | va);
}
}
| 1,495 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
ControlButton.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/ControlButton.java | package mahomaps.ui;
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import tube42.lib.imagelib.ImageUtils;
public class ControlButton extends UIElement implements ITouchAcceptor {
/**
* Do not access this directly! Use {@link #GetUiSheet()}.
*/
private static Image _sheet;
protected int n;
private final IButtonHandler handler;
private final int uid;
private boolean hold;
private int margin = 5;
protected static Image GetUiSheet() {
if (_sheet != null)
return _sheet;
try {
_sheet = Image.createImage("/ui50.png");
Canvas c = MahoMapsApp.GetCanvas();
if (Settings.uiSize == 1) {
// sheet is already 50x50
} else {
// 30x30 is forced, or automated due to small screen
if (c.getWidth() <= 320 || c.getHeight() <= 320 || Settings.uiSize == 2) {
_sheet = ImageUtils.resize(_sheet, 60, _sheet.getHeight() * 30 / 50, true, false);
}
}
} catch (IOException e) {
_sheet = Image.createImage(1, 1);
e.printStackTrace();
}
return _sheet;
}
public ControlButton(int n, IButtonHandler handler, int uid) {
this.n = n;
this.handler = handler;
this.uid = uid;
}
public void Paint(Graphics g, int x, int y, int w, int h) {
Image s = GetUiSheet();
final int size = s.getWidth() >> 1;
W = size + margin;
H = size + margin;
g.drawRegion(s, hold ? size : 0, n * size, size, size, 0, x, y, 0);
RegisterForInput(this, x, y, W, H);
}
public void OnPress() {
hold = true;
}
public void OnRelease() {
hold = false;
}
public void OnTap() {
if (handler != null)
handler.OnButtonTap(this, uid);
}
}
| 1,748 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
ControlButtonsContainer.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/ControlButtonsContainer.java | package mahomaps.ui;
import java.util.Vector;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import mahomaps.MahoMapsApp;
import mahomaps.screens.MapCanvas;
public class ControlButtonsContainer extends UIElement implements IButtonHandler {
private final MapCanvas map;
private final UIElement[] btns;
public Vector info;
public ControlButtonsContainer(MapCanvas map) {
this.map = map;
btns = new UIElement[] { new SearchButton(this), new MenuButton(this), new ControlButton(2, this, 3),
new ControlButton(3, this, 4), new GeolocationButton(map) };
}
public void Paint(Graphics g, int x, int y, int w, int h) {
int cy = h;
int cx = w;
for (int i = 4; i >= 0; i--) {
UIElement elem = btns[i];
cy -= elem.H;
if (cy < 0) {
cy = h - elem.H;
cx -= elem.W;
if (cy < 0)
return;
}
elem.Paint(g, cx - elem.W, cy, elem.W, elem.H);
}
}
public void PaintInfo(Graphics g, int x, int y, int w, int h) {
Vector s = info;
if (s != null && s.size() > 0) {
Font f = Font.getFont(0, 0, 8);
final int fh = f.getHeight();
final int ih = s.size() * fh;
int iy = h - ih - 3 - 5;
int iw = 0;
for (int i = 0; i < s.size(); i++) {
int lw = f.stringWidth((String) s.elementAt(i)) + 6;
if (lw > iw)
iw = lw;
}
g.setFont(f);
g.setColor(0x1E1E1E);
g.fillRoundRect(5, iy - 3, iw + 6, ih + 6, 10, 10);
g.setColor(-1);
for (int i = 0; i < s.size(); i++) {
g.drawString((String) s.elementAt(i), 11, iy, 0);
iy += fh;
}
}
}
public void OnButtonTap(UIElement sender, int uid) {
switch (uid) {
case 1:
map.BeginTextSearch();
break;
case 2:
MahoMapsApp.BringMenu();
break;
case 3:
map.state = map.state.ZoomIn();
break;
case 4:
map.state = map.state.ZoomOut();
break;
}
}
}
| 1,838 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
FillFlowContainer.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/FillFlowContainer.java | package mahomaps.ui;
import java.util.Enumeration;
import javax.microedition.lcdui.Graphics;
public class FillFlowContainer extends UIComposite {
public FillFlowContainer() {
super();
}
public FillFlowContainer(UIElement[] elems) {
super(elems);
}
public void Paint(Graphics g, int x, int y, int w, int h) {
Enumeration e = children.elements();
int th = 0;
int mw = 0;
while (e.hasMoreElements()) {
UIElement elem = (UIElement) e.nextElement();
elem.Paint(g, x, y, w, elem.H);
y += elem.H;
th += elem.H;
if (elem.W > mw)
mw = elem.W;
}
W = mw;
H = th;
}
}
| 606 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
UITouchZone.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/UITouchZone.java | package mahomaps.ui;
import mahomaps.map.Rect;
public class UITouchZone extends Rect {
public UITouchZone(ITouchAcceptor elem, int x, int y, int w, int h) {
super(x, y, w, h);
element = elem;
}
public final ITouchAcceptor element;
}
| 245 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
GeolocationButton.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/GeolocationButton.java | package mahomaps.ui;
import javax.microedition.lcdui.Graphics;
import mahomaps.MahoMapsApp;
import mahomaps.map.GeoUpdateThread;
import mahomaps.screens.MapCanvas;
public class GeolocationButton extends ControlButton {
private final MapCanvas map;
private boolean hasGeo;
public GeolocationButton(MapCanvas map) {
super(4, null, 0);
this.map = map;
try {
Class.forName("javax.microedition.location.LocationProvider");
hasGeo = true;
} catch (Throwable e) {
hasGeo = false;
}
}
public void Paint(Graphics g, int x, int y, int w, int h) {
if (map.geo == null) {
n = 4;
} else {
switch (map.geo.state) {
case GeoUpdateThread.STATE_PENDING:
case GeoUpdateThread.STATE_OK_PENDING:
n = 5;
break;
case GeoUpdateThread.STATE_OK:
n = 6;
break;
default:
n = 7;
break;
}
}
if (hasGeo && MahoMapsApp.route == null)
super.Paint(g, x, y, w, h);
else
H = 0;
}
public void OnTap() {
map.ShowGeo();
}
}
| 984 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
StaticContainer.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/StaticContainer.java | package mahomaps.ui;
import java.util.Enumeration;
import javax.microedition.lcdui.Graphics;
public class StaticContainer extends UIComposite {
public StaticContainer() {
super();
}
public StaticContainer(UIElement[] elems) {
super(elems);
}
public void Paint(Graphics g, int x, int y, int w, int h) {
Enumeration e = children.elements();
while (e.hasMoreElements()) {
UIElement elem = (UIElement) e.nextElement();
elem.Paint(g, x + elem.X, y + elem.Y, elem.W, elem.H);
}
}
}
| 505 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
ColumnsContainer.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/ColumnsContainer.java | package mahomaps.ui;
import javax.microedition.lcdui.Graphics;
public class ColumnsContainer extends UIComposite {
public int stretchableElement = -1;
public ColumnsContainer() {
}
public ColumnsContainer(UIElement[] elems) {
super(elems);
}
public void Paint(Graphics g, int x, int y, int w, int h) {
int[] widths = new int[children.size()];
int wsum = 0;
int rh = 1;
for (int i = 0; i < children.size(); i++) {
UIElement el = ((UIElement) children.elementAt(i));
widths[i] = el.W;
wsum += el.W;
if (el.H > rh)
rh = el.H;
}
this.W = wsum;
this.H = rh;
if (stretchableElement > -1) {
int avail = w - wsum;
widths[stretchableElement] += avail;
} else {
int avail = (w - wsum) / widths.length;
for (int i = 0; i < widths.length; i++) {
widths[i] += avail;
}
}
int rx = x;
for (int i = 0; i < children.size(); i++) {
UIElement el = ((UIElement) children.elementAt(i));
el.Paint(g, rx, y, widths[i], rh);
rx += widths[i];
}
}
}
| 1,010 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MenuButton.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/MenuButton.java | package mahomaps.ui;
import javax.microedition.lcdui.Graphics;
import mahomaps.MahoMapsApp;
public class MenuButton extends ControlButton {
public MenuButton(IButtonHandler handler) {
super(1, handler, 2);
}
public void Paint(Graphics g, int x, int y, int w, int h) {
if (MahoMapsApp.route == null)
super.Paint(g, x, y, w, h);
else
H = 0;
}
}
| 364 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SearchButton.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/ui/SearchButton.java | package mahomaps.ui;
import javax.microedition.lcdui.Graphics;
import mahomaps.MahoMapsApp;
public class SearchButton extends ControlButton {
public SearchButton(IButtonHandler handler) {
super(0, handler, 1);
}
public void Paint(Graphics g, int x, int y, int w, int h) {
if (MahoMapsApp.lastSearch == null && MahoMapsApp.route == null)
super.Paint(g, x, y, w, h);
else
H = 0;
}
}
| 402 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
Http403Exception.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/api/Http403Exception.java | package mahomaps.api;
public class Http403Exception extends Exception {
public Http403Exception() {
}
}
| 107 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
YmapsApiBase.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/api/YmapsApiBase.java | package mahomaps.api;
import cc.nnproject.json.*;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
public abstract class YmapsApiBase {
private final String tokenMark = "token\":\"";
private final Hashtable cookies = new Hashtable();
protected final String GetToken(String key) throws Exception {
HttpConnection hc = null;
InputStream raw = null;
InputStreamReader stream = null;
String url = "https://api-maps.yandex.ru/2.1/?lang=ru_RU&apikey=" + key;
if (Settings.proxyApi) {
url = Settings.proxyServer + YmapsApiBase.EncodeUrl(url);
}
try {
hc = (HttpConnection) Connector.open(url + MahoMapsApp.getConnectionParams());
hc.setRequestMethod("GET");
hc.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
int r = hc.getResponseCode();
AcceptCookies(hc);
raw = hc.openInputStream();
if (r != 200) {
ByteArrayOutputStream o = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int len;
while ((len = raw.read(buf)) != -1) {
o.write(buf, 0, len);
}
String str = new String(o.toByteArray(), "UTF-8");
o.close();
throw new IOException("Http code: " + r + "\nResponse: " + str);
}
stream = new InputStreamReader(raw, "UTF-8");
while (true) {
int c = stream.read();
if (c == -1)
throw new EOFException();
if (c == '"') {
boolean ok = true;
for (int i = 0; i < tokenMark.length(); i++) {
c = stream.read();
if (c == -1)
throw new EOFException();
if (tokenMark.charAt(i) == (char) c) {
// pass
} else {
ok = false;
break;
}
}
if (!ok)
continue;
StringBuffer buf = new StringBuffer();
while (true) {
c = stream.read();
if (c == -1)
throw new EOFException();
if (c == '"')
break;
buf.append((char) c);
}
return buf.toString();
}
}
} finally {
try {
if (stream != null)
stream.close();
if (raw != null)
raw.close();
if (hc != null)
hc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
protected String GetUtf(String url) throws IOException, Http403Exception, SecurityException {
if (Settings.proxyApi) {
url = Settings.proxyServer + YmapsApiBase.EncodeUrl(url);
}
System.out.println("GET " + url);
HttpConnection hc = (HttpConnection) Connector.open(url + MahoMapsApp.getConnectionParams());
InputStream is = null;
ByteArrayOutputStream o = null;
try {
hc.setRequestMethod("GET");
hc.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
SendCookies(hc);
int r = hc.getResponseCode();
AcceptCookies(hc);
if (r == 403 || r == 401)
throw new Http403Exception();
is = hc.openInputStream();
o = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int len;
while ((len = is.read(buf)) != -1) {
o.write(buf, 0, len);
}
String str = new String(o.toByteArray(), "UTF-8");
if (r != 200)
throw new IOException("Code: " + r + "\n" + str);
return str;
} catch (NullPointerException e) {
e.printStackTrace();
throw new IOException(e.toString());
} finally {
if (is != null)
is.close();
if (hc != null)
hc.close();
if (o != null)
o.close();
}
}
private void AcceptCookies(HttpConnection hc) throws IOException {
for (int i = 0; i < 100; i++) {
String h = hc.getHeaderFieldKey(i);
if (h == null) {
if (i > 2)
break;
continue;
}
if ("Set-Cookie".equals(h)) {
String val = hc.getHeaderField(i);
if (val != null) {
val = val.substring(0, val.indexOf(';'));
int fec = val.indexOf('=');
String id = val.substring(0, fec);
String content = val.substring(fec + 1);
cookies.put(id, content);
}
}
}
}
private void SendCookies(HttpConnection hc) throws IOException {
System.out.println("Sending " + cookies.size() + " cookies");
StringBuffer buf = new StringBuffer(cookies.size() * 100);
boolean first = true;
Enumeration keys = cookies.keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
String val = (String) cookies.get(key);
if (first) {
first = false;
} else {
buf.append("; ");
}
buf.append(key);
buf.append("=");
buf.append(val);
}
hc.setRequestProperty("Cookie", buf.toString());
}
protected void LoadCookies(JSONObject j) {
JSONArray names = j.keysAsArray();
for (int i = 0; i < names.size(); i++) {
String key = names.getString(i);
cookies.put(key, j.getString(key));
}
}
protected JSONObject SaveCookies() {
return new JSONObject(cookies);
}
public static String EncodeUrl(String s) {
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ((65 <= ch) && (ch <= 90)) {
sbuf.append((char) ch);
} else if ((97 <= ch) && (ch <= 122)) {
sbuf.append((char) ch);
} else if ((48 <= ch) && (ch <= 57)) {
sbuf.append((char) ch);
} else if (ch == 32) {
sbuf.append("%20");
} else if ((ch == 45) || (ch == 95) || (ch == 46) || (ch == 33) || (ch == 126) || (ch == 42) || (ch == 39)
|| (ch == 40) || (ch == 41) || (ch == 58) || (ch == 47)) {
sbuf.append((char) ch);
} else if (ch <= 127) {
sbuf.append(hex(ch));
} else if (ch <= 2047) {
sbuf.append(hex(0xC0 | ch >> 6));
sbuf.append(hex(0x80 | ch & 0x3F));
} else {
sbuf.append(hex(0xE0 | ch >> 12));
sbuf.append(hex(0x80 | ch >> 6 & 0x3F));
sbuf.append(hex(0x80 | ch & 0x3F));
}
}
return sbuf.toString();
}
private static String hex(int ch) {
String x = Integer.toHexString(ch);
return "%" + (x.length() == 1 ? "0" : "") + x;
}
}
| 6,177 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
YmapsApi.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/api/YmapsApi.java | package mahomaps.api;
import java.io.IOException;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.rms.RecordStore;
import cc.nnproject.json.*;
import mahomaps.Settings;
import mahomaps.map.Geopoint;
public final class YmapsApi extends YmapsApiBase {
private static final String RMS_NAME = "mm_v1_api";
public final String key = "d81964d6-b80c-46ed-9b29-d980a45d32f9";
public String token = null;
public final synchronized void RefreshToken() throws Exception {
token = null;
token = GetToken(key);
Save();
}
private final String GetSearchUrl(String text, Geopoint around, double zone) {
String[] cs = around.GetRounded();
return "https://api-maps.yandex.ru/services/search/v2/?format=json&lang=" + Settings.GetLangString() + "&token="
+ token + "&rspn=0&results=40&origin=jsapi2SearchControl"
+ "&snippets=businessrating%2F1.x%2Cmasstransit%2F1.x&ask_direct=1&experimental_maxadv=200&apikey="
+ key + "&text=" + EncodeUrl(text) + "&ll=" + cs[1] + "%2C" + cs[0] + "&spn=" + zone + "%2C" + zone;
}
private final String GetRouteUrl(Geopoint a, Geopoint b, int type) {
String typeS = "";
switch (type) {
case ROUTE_BYFOOT:
typeS = "&rtt=pd";
break;
case ROUTE_AUTO:
break;
case ROUTE_TRANSPORT:
typeS = "&rtt=mt";
break;
default:
throw new IllegalArgumentException();
}
return "https://api-maps.yandex.ru/services/route/2.0/?lang=" + Settings.GetLangString() + "&token=" + token
+ "&rll=" + a.lon + "%2C" + a.lat + "~" + b.lon + "%2C" + b.lat + "&rtm=dtr&results=1&apikey=" + key
+ typeS;
}
public final JSONArray Search(String text, Geopoint around, double zone)
throws JSONException, IOException, Http403Exception {
JSONArray j = (JSON.getObject(GetUtf(GetSearchUrl(text, around, zone)))).getArray("features");
return j;
}
public final JSONObject Route(Geopoint a, Geopoint b, int type)
throws JSONException, IOException, Http403Exception {
JSONArray j = (JSON.getObject(GetUtf(GetRouteUrl(a, b, type)))).getArray("features");
if (j.size() == 0)
throw new ConnectionNotFoundException();
JSONObject j1 = j.getObject(0).getArray("features").getObject(0);
return j1;
}
public static final int ROUTE_BYFOOT = 1;
public static final int ROUTE_AUTO = 2;
public static final int ROUTE_TRANSPORT = 3;
public void Save() {
JSONObject j = new JSONObject();
if (token != null)
j.put("token", token);
JSONObject obj = SaveCookies();
if (obj != null && obj.size() != 0)
j.put("cookies", SaveCookies());
j.put("time", System.currentTimeMillis());
try {
byte[] d = j.toString().getBytes();
RecordStore r = RecordStore.openRecordStore(RMS_NAME, true);
if (r.getNumRecords() == 0) {
r.addRecord(new byte[1], 0, 1);
}
r.setRecord(1, d, 0, d.length);
r.closeRecordStore();
} catch (Exception e) {
e.printStackTrace();
}
}
public final synchronized void TryRead() {
try {
RecordStore r = RecordStore.openRecordStore(RMS_NAME, true);
byte[] d = null;
if (r.getNumRecords() > 0) {
d = r.getRecord(1);
}
r.closeRecordStore();
// parse
if (d == null)
return;
JSONObject j = JSON.getObject(new String(d));
token = j.getNullableString("token");
long dif = j.getLong("time", 0);
// reset session each 8 hours (1000ms * 60s * 60m * 8h)
if (dif > 1000L * 3600L * 8L)
return;
JSONObject cs = j.getNullableObject("cookies");
if (cs != null && cs.size() != 0 && token != null)
LoadCookies(cs);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
| 3,586 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
BookmarksScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/BookmarksScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.rms.RecordStore;
import cc.nnproject.json.JSON;
import cc.nnproject.json.JSONArray;
import cc.nnproject.json.JSONObject;
import mahomaps.MahoMapsApp;
import mahomaps.map.Geopoint;
import mahomaps.map.MapState;
import mahomaps.overlays.RouteBuildOverlay;
public class BookmarksScreen extends List implements CommandListener {
public final static String RMS_NAME = "mm_v1_bookmarks";
private JSONArray list;
private Command from = new Command(MahoMapsApp.text[104], Command.ITEM, 0);
private Command to = new Command(MahoMapsApp.text[105], Command.ITEM, 1);
private Command del = new Command(MahoMapsApp.text[149], Command.ITEM, 2);
private Command rename = new Command(MahoMapsApp.text[150], Command.ITEM, 2);
public BookmarksScreen() {
super(MahoMapsApp.text[148], Choice.IMPLICIT);
list = read();
list.build();
fillList();
addCommand(MahoMapsApp.back);
if (list.size() > 0) {
addCommand(from);
addCommand(to);
addCommand(del);
addCommand(rename);
}
setCommandListener(this);
}
private void fillList() {
for (int i = 0; i < list.size(); i++) {
append(list.getObject(i).getString("name", "Not named"), null);
}
}
private static JSONArray read() {
try {
RecordStore r = RecordStore.openRecordStore(RMS_NAME, true);
byte[] d = null;
if (r.getNumRecords() > 0) {
d = r.getRecord(1);
}
r.closeRecordStore();
if (d == null)
return JSON.getArray("[]");
return JSON.getArray(new String(d, "UTF-8"));
} catch (Throwable e) {
return JSON.getArray("[]");
}
}
public static void BeginAdd(final Geopoint p, String defaultName) {
final TextBox tb = new TextBox(MahoMapsApp.text[151], defaultName == null ? "" : defaultName, 100, 0);
tb.addCommand(MahoMapsApp.back);
tb.addCommand(MahoMapsApp.ok);
tb.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back)
MahoMapsApp.BringMap();
else if (c == MahoMapsApp.ok) {
String text = tb.getString();
if (text != null && text.length() > 0) {
Add(p, text);
}
MahoMapsApp.BringMap();
}
}
});
MahoMapsApp.BringSubScreen(tb);
}
public static void Add(Geopoint p, String name) {
JSONArray arr = read();
JSONObject obj = new JSONObject();
obj.put("name", name);
obj.put("lat", p.lat);
obj.put("lon", p.lon);
arr.add(obj);
Save(arr);
}
private static void Save(JSONArray arr) {
try {
byte[] d = arr.toString().getBytes("UTF-8");
RecordStore r = RecordStore.openRecordStore(RMS_NAME, true);
if (r.getNumRecords() == 0)
r.addRecord(new byte[1], 0, 1);
r.setRecord(1, d, 0, d.length);
r.closeRecordStore();
} catch (Exception e) {
e.printStackTrace();
}
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
if (d instanceof TextBox) {
MahoMapsApp.BringSubScreen(this);
return;
}
MahoMapsApp.BringMap();
return;
}
if (list.size() == 0)
return;
int n = getSelectedIndex();
if (n == -1)
return;
if (c == MahoMapsApp.ok) {
// будем надеяться что фокус элемента не сбросится пока юзер будет вводить текст
String s = ((TextBox) d).getString();
set(n, s, null);
list.getObject(n).put("name", s);
return;
}
if (c == del) {
list.remove(n);
delete(n);
Save(list);
return;
}
if (c == rename) {
final TextBox tb = new TextBox(MahoMapsApp.text[151], getString(n), 100, 0);
tb.addCommand(MahoMapsApp.back);
tb.addCommand(MahoMapsApp.ok);
tb.setCommandListener(this);
MahoMapsApp.BringSubScreen(tb);
return;
}
JSONObject obj = list.getObject(n);
Geopoint p = new Geopoint(obj.getDouble("lat"), obj.getDouble("lon"));
if (c == SELECT_COMMAND) {
MahoMapsApp.GetCanvas().state = MapState.FocusAt(p);
MahoMapsApp.BringMap();
} else if (c == from) {
RouteBuildOverlay.Get().SetA(p);
MahoMapsApp.BringMap();
} else if (c == to) {
RouteBuildOverlay.Get().SetB(p);
MahoMapsApp.BringMap();
}
}
}
| 4,399 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
AboutScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/AboutScreen.java | package mahomaps.screens;
import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
public class AboutScreen extends Form implements CommandListener, ItemCommandListener {
StringItem website = new StringItem(MahoMapsApp.text[33], "nnp.nnchan.ru", Item.HYPERLINK);
StringItem chat = new StringItem(MahoMapsApp.text[34], "t.me/nnmidletschat", Item.HYPERLINK);
StringItem gh = new StringItem("GitHub", "github.com/mahomaps", Item.HYPERLINK);
int i1, i2, i3, i4;
public AboutScreen() {
super(MahoMapsApp.text[12]);
SetF();
setCommandListener(this);
addCommand(MahoMapsApp.back);
try {
Image img = Image.createImage("/splash.png");
ImageItem i = new ImageItem(null, img, Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_CENTER, "logo");
append(i);
} catch (IOException e) {
}
StringItem s = new StringItem("MahoMaps",
MahoMapsApp.text[35] + "\n" + MahoMapsApp.text[36] + " 1." + MahoMapsApp.version);
add(s);
if (MahoMapsApp.platform != null && MahoMapsApp.platform.indexOf("S60") != -1
&& MahoMapsApp.platform.indexOf("platform_version=3.2") == -1) {
// фокус на начало экрана
try {
MahoMapsApp.display.setCurrentItem(s);
} catch (Throwable e) {
}
}
SetI();
add(new StringItem("Предложил", "GingerFox87"));
add(new StringItem("Тимлид", "Feodor0090 (aka sym_ansel)"));
add(new StringItem("Поддержать нас рублём",
s(i1) + " " + s(i2) + " " + s(i3) + " " + s(i4)));
add(new StringItem("Программирование", "Feodor0090 (aka sym_ansel)\nShinovon"));
add(new StringItem("Дизайн", "MuseCat"));
add(new StringItem("Прокси", "Shinovon\nrehdzi"));
add(new StringItem("CI/CD", "vipaoL"));
add(new StringItem("Тестеры", "MuseCat\nGingerFox87\nДмитрий Михно\nvipaoL"));
add(new StringItem("Группа поддержки", "stacorp"));
add(new StringItem("Поиграйте в игры от", "Cygames"));
add(new StringItem("Писалось под музыку от", "Lantis"));
website.setDefaultCommand(MahoMapsApp.openLink);
website.setItemCommandListener(this);
add(website);
chat.setDefaultCommand(MahoMapsApp.openLink);
chat.setItemCommandListener(this);
add(chat);
gh.setDefaultCommand(MahoMapsApp.openLink);
gh.setItemCommandListener(this);
add(gh);
try {
ImageItem i = new ImageItem(null, Image.createImage("/stick.png"),
Item.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_CENTER, "торшер");
append(i);
} catch (IOException e) {
}
add(new StringItem(MahoMapsApp.text[67], "Powered by butthurt from nnchat\n292 labs (tm)"));
add(new StringItem(MahoMapsApp.text[68],
"Гитхаб Анселя:\ngithub.com/Feodor0090\n" + "Канал Анселя:\nt.me/sym_ansel_blog\n"
+ "Борда rehdzi:\nnnchan.ru\n" + "Канал Димы:\nt.me/blogprostodimonich\n"
+ "Канал Лиса:\nt.me/GingerFox87_blog\n" + "Игра Выполя:\nt.me/mobap_game\n"));
Settings.PushUsageFlag(1);
}
private static String s(int i) {
String s = String.valueOf(i);
while(s.length() < 4) s = "0" + s;
return s;
}
private void add(StringItem item) {
item.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_LEFT);
append(item);
}
private void SetI() {
i1 = 5536;
i2 = 9141;
i3 = 0062;
i4 = 0677;
}
private void SetF() {
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMenu();
}
}
public void commandAction(Command c, Item item) {
if (c == MahoMapsApp.openLink) {
if (item == website) {
MahoMapsApp.open("http://nnp.nnchan.ru");
} else if (item == chat) {
MahoMapsApp.open("http://mp.nnchan.ru/chat.php?c=nnmidletschat");
} else if (item == gh) {
MahoMapsApp.open("https://github.com/mahomaps");
}
}
}
}
| 4,358 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SearchLoader.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/SearchLoader.java | package mahomaps.screens;
import java.io.IOException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.StringItem;
import cc.nnproject.json.*;
import mahomaps.MahoMapsApp;
import mahomaps.api.Http403Exception;
import mahomaps.map.Geopoint;
public class SearchLoader extends Form implements Runnable, CommandListener {
private Thread th;
public final String query;
public final Geopoint point;
public SearchLoader(String query, Geopoint point) {
super(query);
this.query = query;
this.point = point;
setCommandListener(this);
th = new Thread(this, "Search API request");
th.start();
}
public void run() {
append(new Gauge(MahoMapsApp.text[14], false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING));
try {
JSONArray arr = MahoMapsApp.api.Search(query, point, 0.1d);
MahoMapsApp.BringSubScreen(new SearchScreen(query, point, arr));
} catch (IOException e) {
deleteAll();
append(new StringItem(MahoMapsApp.text[111], MahoMapsApp.text[159]));
append(new StringItem(MahoMapsApp.text[24], e.getMessage()));
e.printStackTrace();
} catch (Http403Exception e) {
deleteAll();
append(new StringItem(MahoMapsApp.text[135], MahoMapsApp.text[136]));
} catch (Exception e) {
deleteAll();
append(new StringItem(e.getClass().getName(), e.getMessage()));
e.printStackTrace();
} catch (OutOfMemoryError e) {
deleteAll();
append(new StringItem(MahoMapsApp.text[121], MahoMapsApp.text[160]));
}
addCommand(MahoMapsApp.back);
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMap();
}
}
}
| 1,804 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
APIReconnectForm.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/APIReconnectForm.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
public class APIReconnectForm extends Form implements Runnable, CommandListener, ItemCommandListener {
public APIReconnectForm() {
super("MahoMaps v1");
setCommandListener(this);
if (MahoMapsApp.api.token == null) {
StartTokenRefresh();
} else {
ShowOk();
}
}
public void run() {
Thread.yield();
try {
MahoMapsApp.api.RefreshToken();
ShowSuc();
} catch (Exception e) {
ShowFail(e);
}
}
private void StartTokenRefresh() {
removeCommand(MahoMapsApp.back);
deleteAll();
append(new Gauge(MahoMapsApp.text[14], false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING));
(new Thread(this, "API reconnect")).start();
}
private void ShowOk() {
deleteAll();
append(new StringItem(MahoMapsApp.text[15], MahoMapsApp.text[16]));
StringItem b = new StringItem(MahoMapsApp.text[20], MahoMapsApp.text[5], Item.BUTTON);
b.setLayout(Item.LAYOUT_NEWLINE_BEFORE | Item.LAYOUT_LEFT);
b.setDefaultCommand(MahoMapsApp.reset);
b.setItemCommandListener(this);
append(b);
addCommand(MahoMapsApp.back);
}
private void ShowSuc() {
deleteAll();
append(new StringItem(MahoMapsApp.text[15], MahoMapsApp.text[16]));
addCommand(MahoMapsApp.back);
}
private void ShowFail(Exception e) {
deleteAll();
if (e instanceof SecurityException) {
append(new StringItem(MahoMapsApp.text[15], MahoMapsApp.text[21]));
} else {
append(new StringItem(MahoMapsApp.text[15], MahoMapsApp.text[22]));
append(new StringItem(MahoMapsApp.text[19], MahoMapsApp.text[Settings.proxyApi ? 17 : 18]));
append(new StringItem(MahoMapsApp.text[23], e.getClass().getName()));
append(new StringItem(MahoMapsApp.text[24], e.getMessage()));
}
addCommand(MahoMapsApp.back);
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMenu();
}
}
public void commandAction(Command c, Item item) {
if (c == MahoMapsApp.reset) {
MahoMapsApp.api.token = null;
MahoMapsApp.api.Save();
StartTokenRefresh();
}
}
}
| 2,441 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MenuScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/MenuScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import mahomaps.MahoMapsApp;
import mahomaps.map.TilesProvider;
public class MenuScreen extends List implements CommandListener {
private final TilesProvider tiles;
public MenuScreen(TilesProvider tiles) {
super("MahoMaps v1", Choice.IMPLICIT,
new String[] { MahoMapsApp.text[148], MahoMapsApp.text[153], MahoMapsApp.text[9], MahoMapsApp.text[10],
MahoMapsApp.text[11], MahoMapsApp.text[69], MahoMapsApp.text[12], MahoMapsApp.text[13],
MahoMapsApp.text[0] },
null);
this.tiles = tiles;
addCommand(MahoMapsApp.back);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (d == this) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMap();
} else if (c == SELECT_COMMAND) {
int sel = getSelectedIndex();
if (sel == 0) {
MahoMapsApp.BringSubScreen(new BookmarksScreen());
} else if (sel == 1) {
MahoMapsApp.BringSubScreen(new MapLayerSelectionScreen());
} else if (sel == 2) {
MahoMapsApp.BringSubScreen(new APIReconnectForm());
} else if (sel == 3) {
MahoMapsApp.BringSubScreen(new KeyboardHelpScreen());
} else if (sel == 4) {
MahoMapsApp.BringSubScreen(new SettingsScreen());
} else if (sel == 5) {
MahoMapsApp.BringSubScreen(new CacheManager(tiles));
} else if (sel == 6) {
MahoMapsApp.BringSubScreen(new AboutScreen());
} else if (sel == 7) {
MahoMapsApp.BringSubScreen(new OtherAppsScreen());
} else if (sel == 8) {
MahoMapsApp.Exit();
}
}
}
}
}
| 1,763 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SearchResultScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/SearchResultScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import cc.nnproject.json.*;
import mahomaps.MahoMapsApp;
import mahomaps.overlays.SearchOverlay;
public class SearchResultScreen extends Form implements CommandListener {
private Command back = new Command("Список", Command.BACK, 0);
private final SearchOverlay o;
public SearchResultScreen(JSONObject obj, SearchOverlay o) {
super("Результат поиска");
this.o = o;
JSONObject props = obj.getObject("properties");
JSONArray point = obj.getObject("geometry").getArray("coordinates");
String name = props.getNullableString("name");
StringItem nameItem = new StringItem(MahoMapsApp.text[161], name);
nameItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(nameItem);
String descr = props.getString("description", null);
if (descr != null) {
StringItem descrItem = new StringItem(MahoMapsApp.text[162], descr);
descrItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(descrItem);
}
StringItem coordsItem = new StringItem(MahoMapsApp.text[163], point.getDouble(1) + " " + point.getDouble(0));
coordsItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(coordsItem);
JSONObject org = props.getNullableObject("CompanyMetaData");
if (org != null) {
JSONObject hours = org.getNullableObject("Hours");
if (hours != null) {
StringItem hoursItem = new StringItem(MahoMapsApp.text[164], hours.getNullableString("text"));
hoursItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(hoursItem);
}
if (org.getNullableString("url") != null) {
StringItem urlItem = new StringItem(MahoMapsApp.text[165], org.getNullableString("url"));
urlItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(urlItem);
}
JSONArray phones = org.getNullableArray("Phones");
if (phones != null && phones.size() != 0) {
StringItem phonesItem = new StringItem(MahoMapsApp.text[166], phones.getObject(0).getNullableString("formatted"));
phonesItem.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(phonesItem);
}
}
addCommand(back);
addCommand(MahoMapsApp.toMap);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == back) {
o.SetNullSelection();
MahoMapsApp.BringSubScreen(MahoMapsApp.lastSearch);
} else if (c == MahoMapsApp.toMap) {
MahoMapsApp.BringMap();
}
}
}
| 2,753 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
CacheManager.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/CacheManager.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import mahomaps.map.TilesProvider;
public class CacheManager extends Form implements CommandListener, ItemCommandListener, Runnable {
StringItem delAll = new StringItem(null, MahoMapsApp.text[70], Item.BUTTON);
private Command sel = new Command(MahoMapsApp.text[29], Command.OK, 0);
private TilesProvider tiles;
public CacheManager(TilesProvider tiles) {
super(MahoMapsApp.text[69]);
this.tiles = tiles;
addCommand(MahoMapsApp.back);
setCommandListener(this);
append(new StringItem(MahoMapsApp.text[71], getCacheType()));
append(new StringItem(MahoMapsApp.text[72], "" + tiles.GetCachedTilesCount()));
if (Settings.cacheMode == Settings.CACHE_FS)
append(new StringItem(MahoMapsApp.text[71], tiles.GetLocalPath()));
delAll.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
delAll.setDefaultCommand(sel);
delAll.setItemCommandListener(this);
append(delAll);
}
private static String getCacheType() {
switch (Settings.cacheMode) {
case Settings.CACHE_DISABLED:
return MahoMapsApp.text[73];
case Settings.CACHE_FS:
return MahoMapsApp.text[53];
case Settings.CACHE_RMS:
return "RMS";
default:
return null;
}
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back)
MahoMapsApp.BringMenu();
}
public void commandAction(Command c, Item item) {
if (c == sel) {
if (item == delAll) {
deleteAll();
removeCommand(MahoMapsApp.back);
append(new Gauge(MahoMapsApp.text[74], false, Gauge.INDEFINITE, Gauge.CONTINUOUS_RUNNING));
append(new StringItem(null, MahoMapsApp.text[75]));
(new Thread(this, "Cache clear")).start();
}
}
}
public void run() {
tiles.ClearCache();
MahoMapsApp.Exit();
}
}
| 2,158 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MultitouchCanvas.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/MultitouchCanvas.java | package mahomaps.screens;
import javax.microedition.lcdui.game.GameCanvas;
import mahomaps.MahoMapsApp;
public abstract class MultitouchCanvas extends GameCanvas {
private final boolean isKemulator;
protected MultitouchCanvas() {
super(false);
isKemulator = MahoMapsApp.IsKemulator();
}
protected final void pointerDragged(int x, int y) {
String pn = isKemulator ? null : System.getProperty("com.nokia.pointer.number");
int n = pn == null ? 0 : (pn.charAt(0) - '0');
pointerDragged(x, y, n);
}
protected final void pointerPressed(int x, int y) {
String pn = isKemulator ? null : System.getProperty("com.nokia.pointer.number");
int n = pn == null ? 0 : (pn.charAt(0) - '0');
pointerPressed(x, y, n);
}
protected final void pointerReleased(int x, int y) {
String pn = isKemulator ? null: System.getProperty("com.nokia.pointer.number");
int n = pn == null ? 0 : (pn.charAt(0) - '0');
pointerReleased(x, y, n);
}
protected abstract void pointerDragged(int x, int y, int n);
protected abstract void pointerPressed(int x, int y, int n);
protected abstract void pointerReleased(int x, int y, int n);
}
| 1,140 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MapCanvas.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/MapCanvas.java | package mahomaps.screens;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.TextBox;
import mahomaps.FpsLimiter;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import mahomaps.map.GeoUpdateThread;
import mahomaps.map.Geopoint;
import mahomaps.map.Line;
import mahomaps.map.MapState;
import mahomaps.map.TileCache;
import mahomaps.map.TileId;
import mahomaps.map.TilesProvider;
import mahomaps.overlays.NoApiTokenOverlay;
import mahomaps.overlays.OverlaysManager;
import mahomaps.overlays.SelectOverlay;
import mahomaps.overlays.TileCacheForbiddenOverlay;
import mahomaps.overlays.TileDownloadForbiddenOverlay;
import mahomaps.route.RouteTracker;
import mahomaps.ui.ControlButtonsContainer;
import mahomaps.ui.UIElement;
public class MapCanvas extends MultitouchCanvas implements CommandListener {
public volatile MapState state = Settings.ReadStateOrDefault();
// search lcdui parts
private Command search = new Command(MahoMapsApp.text[27], Command.OK, 1);
private TextBox searchBox = new TextBox(MahoMapsApp.text[27], "", 100, 0);
// geolocation stuff
public GeoUpdateThread geo = null;
public Geopoint geolocation;
// input states
private boolean mapFocused = true;
private int repeatCount = 0;
int startPx, startPy;
int lastPx, lastPy;
// tiles/overlays stuff
private final TilesProvider tiles;
public final ControlButtonsContainer controls;
public final OverlaysManager overlays = new OverlaysManager(this);
public Line line;
// draw/input states/temps/caches
boolean dragActive;
public boolean hidden = false;
private int lastOverlaysW;
public final FpsLimiter repaintGate = new FpsLimiter();
private Graphics cachedGraphics;
/*
* up down left right (1<< 0 1 2 3)
*/
private int keysState = 0;
private Thread repeatThread;
private final Runnable repeatAction = new Runnable() {
public void run() {
try {
Thread.sleep(200); // wait a little before repeats
while (true) {
Thread.sleep(16); // interruption will throw here stopping the thread
if (!mapFocused) {
synchronized (repeatAction) {
repeatThread = null;
return;
}
}
int val = Math.min(20, repeatCount / 3);
if ((keysState & 1) != 0)
state.yOffset += val;
if ((keysState & 2) != 0)
state.yOffset -= val;
if ((keysState & 4) != 0)
state.xOffset += val;
if ((keysState & 8) != 0)
state.xOffset -= val;
state.ClampOffset();
repeatCount++;
requestRepaint();
}
} catch (InterruptedException e) {
}
}
};
public MapCanvas(TilesProvider tiles) {
this.tiles = tiles;
setFullScreenMode(true);
geolocation = new Geopoint(0, 0);
geolocation.type = Geopoint.LOCATION;
searchBox.addCommand(MahoMapsApp.back);
searchBox.addCommand(search);
searchBox.setCommandListener(this);
UIElement.touchInput = hasPointerEvents();
controls = new ControlButtonsContainer(this);
CheckApiAcsess();
if (Settings.cacheMode == Settings.CACHE_DISABLED)
overlays.PushOverlay(new TileCacheForbiddenOverlay());
if (!Settings.allowDownload)
overlays.PushOverlay(new TileDownloadForbiddenOverlay());
}
/**
* Проверяет есть ли доступ к апи. Выводит окно предупреждения.
*
* @return False если нету.
*/
public boolean CheckApiAcsess() {
if (MahoMapsApp.api.token == null) {
overlays.PushOverlay(new NoApiTokenOverlay());
return false;
}
return true;
}
public Geopoint GetSearchAnchor() {
if (geo != null && geo.DrawPoint()) {
return geolocation;
}
Geopoint p = Geopoint.GetAtCoords(state, 0, 0);
if (p.lat > 80d)
p.lat = 80d;
if (p.lat < -80d)
p.lat = -80d;
return p;
}
// DRAW SECTION
private void repaint(Graphics g) {
int w = getWidth();
int h = getHeight();
g.setGrayScale(127);
g.fillRect(0, 0, w, h);
drawMap(g, w, h);
drawOverlay(g, w, h);
UIElement.CommitInputQueue();
if (UIElement.IsQueueEmpty() && !UIElement.touchInput && !mapFocused) {
mapFocused = true;
UIElement.Deselect();
requestRepaint();
}
}
private void drawMap(Graphics g, int w, int h) {
MapState ms = state;
if (ms == null) // wtf!?
throw new NullPointerException("Map state was null at frame begin");
tiles.BeginMapPaint();
g.translate(w >> 1, h >> 1);
int trX = 1;
while (trX * 256 < (w >> 1))
trX++;
int trY = 1;
while (trY * 256 < (h >> 1))
trY++;
// кэширование для защиты от подмены переключенным потоком
final int xo = ms.xOffset;
final int tx = ms.tileX;
int y = ms.yOffset - trY * 256;
int yi = ms.tileY - trY;
while (y < h / 2) {
int x = xo - trX * 256;
int xi = tx - trX;
while (x < w / 2) {
TileCache tile = tiles.getTile(new TileId(xi, yi, ms.zoom, Settings.map));
if (tile != null)
tile.paint(g, x, y);
x += 256;
xi++;
}
y += 256;
yi++;
}
Line l = line;
if (l != null)
l.Draw(g, this);
if (geo != null && geo.DrawPoint()) {
geolocation.paint(g, ms);
}
if (!UIElement.touchInput) {
g.setColor(0xff0000);
g.drawLine(-6, 0, -2, 0);
g.drawLine(2, 0, 6, 0);
g.drawLine(0, -6, 0, -2);
g.drawLine(0, 2, 0, 6);
}
overlays.DrawMap(g, ms);
g.translate(-(w >> 1), -(h >> 1));
tiles.EndMapPaint(state);
}
private void drawOverlay(Graphics g, int w, int h) {
Font f = Font.getFont(0, 0, 8);
g.setColor(0);
g.setFont(f);
if (Settings.drawDebugInfo)
g.drawString(state.toString(), 0, 0, 0);
try {
controls.info = GetGeoInfo();
} catch (Exception e) {
// wtf!!!???
throw new RuntimeException("geo infa ebanulas " + e.toString());
}
final boolean t = UIElement.touchInput;
final RouteTracker rt = MahoMapsApp.route;
int fh = f.getHeight();
if (!t)
h -= fh;
lastOverlaysW = getOverlaysW(w, h);
if (t || rt == null)
overlays.Draw(g, lastOverlaysW, h);
if (t) {
int ch = h;
if (lastOverlaysW == w)
ch -= overlays.overlaysH;
controls.Paint(g, 0, 0, w, ch);
}
controls.PaintInfo(g, 0, 0, w, h - overlays.overlaysH);
if (rt != null) {
mapFocused = true;
rt.Update();
rt.Draw(g, w);
}
if (!t) {
g.setColor(0);
g.fillRect(0, h, w, fh);
g.setColor(-1);
g.setFont(f);
if (rt == null) {
g.drawString(MahoMapsApp.text[28], 0, h, 0);
g.drawString(MahoMapsApp.text[29], w / 2, h, Graphics.TOP | Graphics.HCENTER);
if (mapFocused) {
if (!UIElement.IsQueueEmpty())
g.drawString(MahoMapsApp.text[30], w, h, Graphics.TOP | Graphics.RIGHT);
} else {
g.drawString(MahoMapsApp.text[31], w, h, Graphics.TOP | Graphics.RIGHT);
}
} else {
g.drawString(MahoMapsApp.text[32], w, h, Graphics.TOP | Graphics.RIGHT);
}
}
}
private Vector GetGeoInfo() {
if (geo == null || Settings.showGeo == 0) {
return null;
}
Vector v = new Vector();
if (geo.state == GeoUpdateThread.STATE_UNSUPPORTED) {
v.addElement(MahoMapsApp.text[GeoUpdateThread.states[geo.state]]);
return v;
}
// статус и время
int passed = (int) ((System.currentTimeMillis() - geo.lastUpdateTime) / 1000);
if (geo.state != GeoUpdateThread.STATE_OK) {
v.addElement(MahoMapsApp.text[GeoUpdateThread.states[geo.state]]);
v.addElement(MahoMapsApp.text[83] + passed + MahoMapsApp.text[84]);
} else if (passed >= 5) {
v.addElement(MahoMapsApp.text[85] + (passed < 24 * 60 * 60 ? passed + MahoMapsApp.text[86] : ""));
}
// метод и спутники
{
String s = geo.method;
if (geo.totalSattelitesInView >= 0) {
String s2 = (geo.sattelites >= 0 ? geo.sattelites + "/" : "") + geo.totalSattelitesInView;
if (s == null) {
s = MahoMapsApp.text[87] + ": " + s2;
} else {
s += " (" + s2 + ")";
}
}
if (s != null)
v.addElement(s);
}
// координаты
if (geo.DrawPoint() && Settings.showGeo == 2) {
String[] r = geolocation.GetRounded();
v.addElement(r[0]);
v.addElement(r[1]);
}
return v;
}
private static int getOverlaysW(int w, int h) {
if (w <= h) {
// portait
return w;
}
if (h + 100 > w) {
// album, but too square (less than 100 pixels free)
return w;
}
// album, wide enough
return h;
}
public void run() throws InterruptedException {
while (true) {
final RouteTracker rt = MahoMapsApp.route;
if (MahoMapsApp.paused || hidden) {
if (rt == null) {
// we are hidden
repaintGate.Pass();
} else {
// we are hidden, but route is active
repaintGate.Begin();
rt.Update();
// drawing does nothing
repaintGate.End(50); // 20 ups
}
} else {
// we are visible
repaintGate.Begin();
Graphics g = cachedGraphics;
if (g == null)
cachedGraphics = g = getGraphics();
repaint(g);
flushGraphics();
repaintGate.End(rt != null ? 33 : 2000);
}
}
}
public void requestRepaint() {
repaintGate.Reset();
}
public void ShowGeo() {
if (MahoMapsApp.route != null)
return;
if (geo == null) {
geo = new GeoUpdateThread(geolocation, this);
geo.start();
Settings.PushUsageFlag(8);
} else if (geo.DrawPoint()) {
state = MapState.FocusAt(geolocation);
} else if (geo.state == GeoUpdateThread.STATE_UNAVAILABLE) {
geo.restart();
}
requestRepaint();
}
// INPUT
protected void keyPressed(int k) {
// "home" button
if (k == -12)
return;
UIElement.touchInput = false;
if (MahoMapsApp.route != null) {
// когда маршрут ведётся, можно только изменять масштаб и закрывать маршрут.
switch (k) {
case -7:
case -22:
MahoMapsApp.route.overlay.OnButtonTap(null, 0);
break;
case KEY_NUM1:
case KEY_STAR:
state = state.ZoomOut();
break;
case KEY_NUM3:
case KEY_POUND:
state = state.ZoomIn();
break;
}
requestRepaint();
return;
}
if (k == -6 || k == -21) { // -21 и -22 для моторол
MahoMapsApp.BringMenu();
return;
}
if (k == -7 || k == -22) {
tryStopRepeatThread(true);
if (mapFocused) {
if (!UIElement.IsQueueEmpty()) {
mapFocused = false;
UIElement.SelectDown();
}
} else {
mapFocused = true;
UIElement.Deselect();
}
requestRepaint();
return;
}
handling: {
int ga = 0;
try {
ga = getGameAction(k);
} catch (IllegalArgumentException e) { // j2l moment
}
if (mapFocused) {
switch (ga) {
case FIRE:
tryStopRepeatThread(true);
Geopoint s = Geopoint.GetAtCoords(state, 0, 0);
if (s.IsValid() && MahoMapsApp.lastSearch == null) {
// немного костылей:
// сбрасываем ввод
UIElement.CommitInputQueue();
// добавляем оверлей, он переотрисовывается заполняя очередь ввода
overlays.PushOverlay(new SelectOverlay(s));
// применяем очередь
UIElement.CommitInputQueue();
// снятие фокуса с карты
mapFocused = false;
// выбор кнопки
UIElement.SelectDown();
// после нажатия кнопки канва перерисует себя, вернув очередь ввода в адекватное
// состояние
}
break handling;
case UP:
keysState |= 1 << 0;
state.yOffset += 10;
state.ClampOffset();
tryStartRepeatThread();
break handling;
case DOWN:
keysState |= 1 << 1;
state.yOffset -= 10;
state.ClampOffset();
tryStartRepeatThread();
break handling;
case LEFT:
keysState |= 1 << 2;
state.xOffset += 10;
state.ClampOffset();
tryStartRepeatThread();
break handling;
case RIGHT:
keysState |= 1 << 3;
state.xOffset -= 10;
state.ClampOffset();
tryStartRepeatThread();
break handling;
}
switch (k) {
case KEY_NUM1:
ShowGeo();
break handling;
case KEY_NUM3:
// geo status toggle
Settings.showGeo++;
if (Settings.showGeo > 2)
Settings.showGeo = 0;
break handling;
case KEY_NUM7:
BeginTextSearch();
break handling;
case KEY_NUM9:
MahoMapsApp.BringSubScreen(new BookmarksScreen());
break handling;
case KEY_STAR:
state = state.ZoomIn();
break handling;
case KEY_POUND:
state = state.ZoomOut();
break handling;
case KEY_NUM0:
// layer toggle
MahoMapsApp.BringSubScreen(new MapLayerSelectionScreen());
break handling;
}
} else {
switch (ga) {
case FIRE:
UIElement.TriggerSelected();
break;
case UP:
case LEFT:
UIElement.SelectUp();
break;
case DOWN:
case RIGHT:
UIElement.SelectDown();
break;
}
}
}
requestRepaint();
}
protected void keyReleased(int k) {
int ga = 0;
try {
ga = getGameAction(k);
} catch (IllegalArgumentException e) {
}
switch (ga) {
case UP:
keysState &= ~(1 << 0);
tryStopRepeatThread(false);
break;
case DOWN:
keysState &= ~(1 << 1);
tryStopRepeatThread(false);
break;
case LEFT:
keysState &= ~(1 << 2);
tryStopRepeatThread(false);
break;
case RIGHT:
keysState &= ~(1 << 3);
tryStopRepeatThread(false);
break;
}
requestRepaint();
}
protected void pointerPressed(int x, int y, int n) {
UIElement.touchInput = true;
mapFocused = true;
if (n == 0) {
UIElement.InvokePressEvent(x, y);
dragActive = false;
startPx = x;
startPy = y;
lastPx = x;
lastPy = y;
}
requestRepaint();
}
protected void pointerDragged(int x, int y, int n) {
if (n == 0) {
if (!dragActive) {
if (Math.abs(x - startPx) > 8 || Math.abs(y - startPy) > 8) {
UIElement.InvokeReleaseEvent();
dragActive = true;
} else
return;
}
if (MahoMapsApp.route != null)
return;
state.xOffset += x - lastPx;
state.yOffset += y - lastPy;
lastPx = x;
lastPy = y;
state.ClampOffset();
}
requestRepaint();
}
protected void pointerReleased(int x, int y, int n) {
if (n != 0)
return;
handling: {
if (dragActive) {
dragActive = false;
break handling;
}
UIElement.InvokeReleaseEvent();
if (UIElement.InvokeTouchEvent(x, y))
break handling;
if (y > getHeight() - overlays.overlaysH && x < lastOverlaysW)
break handling;
if (overlays.OnGeopointTap(x, y))
break handling;
// tap at map
if (MahoMapsApp.lastSearch == null && MahoMapsApp.route == null) {
Geopoint s = Geopoint.GetAtCoords(state, x - getWidth() / 2, y - getHeight() / 2);
if (s.IsValid()) {
overlays.PushOverlay(new SelectOverlay(s));
break handling;
}
}
}
requestRepaint();
}
public void dispose() {
if (geo != null)
geo.Dispose();
Settings.SaveState(state);
}
public void BeginTextSearch() {
if (MahoMapsApp.route != null)
return;
if (CheckApiAcsess()) {
if (MahoMapsApp.lastSearch == null) {
MahoMapsApp.BringSubScreen(searchBox);
}
}
}
public void commandAction(Command c, Displayable d) {
if (d == searchBox) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMap();
} else {
overlays.CloseOverlay(SelectOverlay.ID);
Geopoint sa = GetSearchAnchor();
MahoMapsApp.BringSubScreen(new SearchLoader(searchBox.getString(), sa));
Settings.PushUsageFlag(16);
}
}
}
protected void sizeChanged(int w, int h) {
cachedGraphics = null;
super.sizeChanged(w, h);
requestRepaint();
}
protected void hideNotify() {
hidden = true;
tryStopRepeatThread(true);
}
protected void showNotify() {
cachedGraphics = null;
hidden = false;
super.showNotify();
requestRepaint();
}
private final void tryStartRepeatThread() {
synchronized (repeatAction) {
if (keysState != 0 && repeatThread == null) {
Thread t = new Thread(repeatAction, "Key repeat");
t.setPriority(Thread.MAX_PRIORITY);
repeatCount = 0;
t.start();
repeatThread = t;
}
}
}
private final void tryStopRepeatThread(boolean force) {
synchronized (repeatAction) {
if (keysState == 0 || force) {
Thread t = repeatThread;
if (t != null) {
t.interrupt();
repeatThread = null;
}
}
}
}
}
| 16,508 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
MapLayerSelectionScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/MapLayerSelectionScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import mahomaps.map.TilesProvider;
public class MapLayerSelectionScreen extends List implements CommandListener {
public MapLayerSelectionScreen() {
super(MahoMapsApp.text[153], IMPLICIT, TilesProvider.GetLayerNames(), null);
setSelectedIndex(Settings.map, true);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
Settings.map = getSelectedIndex();
Settings.Save();
MahoMapsApp.BringMap();
}
}
| 702 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
OtherAppsScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/OtherAppsScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
public class OtherAppsScreen extends Form implements CommandListener, ItemCommandListener {
StringItem vk = new StringItem("VK", "VK4ME (curoviyxru)", Item.HYPERLINK);
StringItem tg = new StringItem("Telegram", "MPGram Web (shinovon)", Item.HYPERLINK);
StringItem jt = new StringItem("YouTube", "JTube (shinovon)", Item.HYPERLINK);
StringItem bt = new StringItem("Translator", "Bing Translate (shinovon)", Item.HYPERLINK);
StringItem nm = new StringItem("osu! beatmaps player", "nmania (Feodor0090)", Item.HYPERLINK);
StringItem kem = new StringItem("J2ME emulator for Windows", "KEmulator nnmod (shinovon)", Item.HYPERLINK);
StringItem j2l = new StringItem("J2ME emulator for Android", "J2MEL (nikita36078)", Item.HYPERLINK);
public OtherAppsScreen() {
super(MahoMapsApp.text[13]);
setCommandListener(this);
addCommand(MahoMapsApp.back);
append(new StringItem(null, MahoMapsApp.text[25]));
appendLink(vk);
appendLink(tg);
appendLink(jt);
appendLink(bt);
appendLink(nm);
appendLink(kem);
appendLink(j2l);
Settings.PushUsageFlag(2);
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMenu();
}
}
private void appendLink(StringItem item) {
item.setDefaultCommand(MahoMapsApp.openLink);
item.setItemCommandListener(this);
item.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(item);
}
public void commandAction(Command c, Item item) {
if (c == MahoMapsApp.openLink) {
if (item == vk) {
MahoMapsApp.open("http://v4.crx.moe/");
} else if (item == tg) {
MahoMapsApp.open("http://mp.nnchan.ru/");
} else if (item == jt) {
MahoMapsApp.open("http://nnp.nnchan.ru/jtube/");
} else if (item == bt) {
MahoMapsApp.open("http://nnp.nnchan.ru/bingt/");
} else if (item == nm) {
MahoMapsApp.open("https://github.com/Feodor0090/nmania");
} else if (item == kem) {
MahoMapsApp.open("http://nnp.nnchan.ru/kem/");
} else if (item == j2l) {
MahoMapsApp.open("https://github.com/nikita36078/J2ME-Loader");
}
}
}
}
| 2,478 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
UpdateScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/UpdateScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
public class UpdateScreen extends Form implements ItemCommandListener, CommandListener {
private String url;
public UpdateScreen(String text, String url) {
super("MahoMaps v1");
this.url = url;
if (text == null)
text = MahoMapsApp.text[26];
append(text);
if (url != null) {
StringItem b = new StringItem(null, MahoMapsApp.text[168], Item.BUTTON);
b.setLayout(Item.LAYOUT_EXPAND | Item.LAYOUT_NEWLINE_BEFORE);
b.addCommand(MahoMapsApp.openLink);
b.setDefaultCommand(MahoMapsApp.openLink);
b.setItemCommandListener(this);
append(b);
}
addCommand(MahoMapsApp.back);
setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMap();
}
}
public void commandAction(Command c, Item item) {
if (c == MahoMapsApp.openLink) {
MahoMapsApp.open(url);
}
}
}
| 1,244 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
Splash.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/Splash.java | package mahomaps.screens;
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import mahomaps.MahoMapsApp;
import tube42.lib.imagelib.ColorUtils;
public class Splash extends Canvas {
private Image image;
public Splash() {
this.setFullScreenMode(true);
try {
image = Image.createImage("/splash.png");
} catch (IOException e) {
}
}
protected void paint(Graphics g) {
int w = getWidth();
int h = getHeight();
final int c1 = 0xa74134;
final int c2 = 0xf8503c;
for (int i = 0; i < h; i++) {
g.setColor(ColorUtils.blend(c1, c2, i * 255 / h));
g.drawLine(0, i, w, i);
}
g.setColor(-1);
if (this.image == null) {
g.setFont(Font.getFont(0, Font.STYLE_BOLD, Font.SIZE_LARGE));
int x = w >> 1;
int y = h >> 1;
g.drawString("Maho", x, y, Graphics.BOTTOM | Graphics.HCENTER);
g.drawString("Maps", x, y, Graphics.TOP | Graphics.HCENTER);
} else {
g.drawImage(image, w >> 1, h >> 1, Graphics.VCENTER | Graphics.HCENTER);
}
if (MahoMapsApp.commit != null) {
g.setFont(Font.getDefaultFont());
g.drawString(MahoMapsApp.commit, w >> 1, h, Graphics.BOTTOM | Graphics.HCENTER);
}
}
}
| 1,281 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SettingsScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/SettingsScreen.java | package mahomaps.screens;
import java.io.IOException;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextField;
import mahomaps.MahoMapsApp;
import mahomaps.Settings;
import tube42.lib.imagelib.ImageUtils;
public class SettingsScreen extends Form implements CommandListener {
private ChoiceGroup focusZoom = new ChoiceGroup(MahoMapsApp.text[46], Choice.POPUP,
new String[] { "15", "16", "17", "18" }, null);
private ChoiceGroup geoLook;
private ChoiceGroup geoStatus = new ChoiceGroup(MahoMapsApp.text[47], Choice.POPUP,
new String[] { MahoMapsApp.text[48], MahoMapsApp.text[49], MahoMapsApp.text[50] }, null);
private ChoiceGroup tileInfo = new ChoiceGroup(MahoMapsApp.text[51], Choice.POPUP,
new String[] { MahoMapsApp.text[18], MahoMapsApp.text[17] }, null);
private ChoiceGroup cache = new ChoiceGroup(MahoMapsApp.text[52], Choice.POPUP,
new String[] { MahoMapsApp.text[18], MahoMapsApp.text[53], "RMS" }, null);
private ChoiceGroup download = new ChoiceGroup(MahoMapsApp.text[54], Choice.MULTIPLE,
new String[] { MahoMapsApp.text[17], "Upscale existing cache before downloading" }, null);
private ChoiceGroup proxyUsage = new ChoiceGroup(MahoMapsApp.text[19], Choice.MULTIPLE,
new String[] { MahoMapsApp.text[156], MahoMapsApp.text[157], }, null);
private TextField proxyServer = new TextField(MahoMapsApp.text[158], "", 256, TextField.URL);
private ChoiceGroup uiSize = new ChoiceGroup(MahoMapsApp.text[56], Choice.POPUP,
new String[] { MahoMapsApp.text[57], "50x50", "30x30" }, null);
private ChoiceGroup lang = new ChoiceGroup(MahoMapsApp.text[58], Choice.POPUP,
new String[] { MahoMapsApp.text[59], MahoMapsApp.text[60], MahoMapsApp.text[61] }, null);
private ChoiceGroup uiLang = new ChoiceGroup(MahoMapsApp.text[62], Choice.POPUP,
new String[] { "Русский", "English", "Français", "العربية" }, null);
private ChoiceGroup bbNetwork = new ChoiceGroup(MahoMapsApp.text[63], Choice.EXCLUSIVE,
new String[] { MahoMapsApp.text[64], "Wi-Fi" }, null);
public SettingsScreen() {
super(MahoMapsApp.text[11]);
addCommand(MahoMapsApp.back);
setCommandListener(this);
Image[] imgs = null;
try {
final int size = 20;
Image sheet = ImageUtils.halve(Image.createImage("/geo40.png"));
Image i1 = Image.createImage(size, size);
i1.getGraphics().drawImage(sheet, 0, 0, 0);
Image i2 = Image.createImage(size, size);
i2.getGraphics().drawImage(sheet, 0, -size, 0);
Image i3 = Image.createImage(size, size);
i3.getGraphics().drawImage(sheet, 0, -(size * 2), 0);
Image i4 = Image.createImage(size, size);
i4.getGraphics().drawImage(sheet, 0, -(size * 3), 0);
imgs = new Image[] { i1, i2, i3, i4 };
} catch (IOException e) {
}
geoLook = new ChoiceGroup(MahoMapsApp.text[65], Choice.EXCLUSIVE,
new String[] { MahoMapsApp.text[66], "\"Я\"", "\"Ы\"", "\"Ъ\"" }, imgs);
if (Settings.focusZoom < 15)
Settings.focusZoom = 15;
if (Settings.focusZoom > 18)
Settings.focusZoom = 18;
focusZoom.setSelectedIndex(Settings.focusZoom - 15, true);
geoLook.setSelectedIndex(Settings.geoLook, true);
geoStatus.setSelectedIndex(Settings.showGeo, true);
tileInfo.setSelectedIndex(Settings.drawDebugInfo ? 1 : 0, true);
cache.setSelectedIndex(Settings.cacheMode, true);
download.setSelectedIndex(0, Settings.allowDownload);
download.setSelectedIndex(1, Settings.readCachedBeforeDownloading);
proxyUsage.setSelectedIndex(0, Settings.proxyTiles);
proxyUsage.setSelectedIndex(1, Settings.proxyApi);
uiSize.setSelectedIndex(Settings.uiSize, true);
lang.setSelectedIndex(Settings.apiLang, true);
uiLang.setSelectedIndex(Settings.uiLang, true);
proxyServer.setString(Settings.proxyServer);
append(focusZoom);
append(geoLook);
append(geoStatus);
append(tileInfo);
append(cache);
append(download);
append(proxyUsage);
append(proxyServer);
append(uiSize);
append(lang);
append(uiLang);
if (MahoMapsApp.bb) {
bbNetwork.setSelectedIndex(Settings.bbWifi ? 1 : 0, true);
append(bbNetwork);
}
}
private void Apply() {
Settings.focusZoom = focusZoom.getSelectedIndex() + 15;
Settings.geoLook = geoLook.getSelectedIndex();
Settings.showGeo = geoStatus.getSelectedIndex();
Settings.drawDebugInfo = tileInfo.getSelectedIndex() == 1;
Settings.cacheMode = cache.getSelectedIndex();
Settings.allowDownload = download.isSelected(0);
Settings.readCachedBeforeDownloading = download.isSelected(1);
Settings.proxyTiles = proxyUsage.isSelected(0);
Settings.proxyApi = proxyUsage.isSelected(1);
Settings.uiSize = uiSize.getSelectedIndex();
Settings.apiLang = lang.getSelectedIndex();
Settings.uiLang = uiLang.getSelectedIndex();
if (MahoMapsApp.bb) {
Settings.bbWifi = bbNetwork.getSelectedIndex() == 1;
}
if (Settings.allowDownload) {
MahoMapsApp.tiles.ForceMissingDownload();
}
Settings.proxyServer = proxyServer.getString();
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
Apply();
if (!MahoMapsApp.TryInitFSCache(false))
return;
// triggers settings save
Settings.PushUsageFlag(4);
MahoMapsApp.BringMenu();
}
}
}
| 5,435 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
SearchScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/SearchScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import cc.nnproject.json.*;
import mahomaps.MahoMapsApp;
import mahomaps.map.Geopoint;
import mahomaps.overlays.SearchOverlay;
public class SearchScreen extends List implements CommandListener {
public final String query;
public JSONArray results;
private SearchOverlay overlay;
public boolean onePointFocused = false;
private Command reset = new Command(MahoMapsApp.text[5], Command.BACK, 0);
public SearchScreen(String query, Geopoint point, JSONArray results) {
super(query, Choice.IMPLICIT);
setFitPolicy(TEXT_WRAP_ON);
this.query = query;
this.results = results;
for (int i = 0; i < results.size(); i++) {
JSONObject obj = results.getObject(i);
JSONObject props = obj.getObject("properties");
append(props.getString("name") + (props.has("description") && !props.isNull("description") ? " (" + props.getString("description", "") + ")" : ""), null);
}
MahoMapsApp.lastSearch = this;
overlay = new SearchOverlay(point, query, results, this);
MahoMapsApp.Overlays().PushOverlay(overlay);
addCommand(reset);
addCommand(MahoMapsApp.toMap);
setCommandListener(this);
}
public static void ResetSearch() {
MahoMapsApp.lastSearch = null;
MahoMapsApp.Overlays().CloseOverlay(SearchOverlay.ID);
}
public void commandAction(Command c, Displayable d) {
if (c == reset) {
ResetSearch();
MahoMapsApp.BringMap();
} else if (c == MahoMapsApp.toMap) {
MahoMapsApp.BringMap();
} else if (c == SELECT_COMMAND) {
overlay.SetSelection(results.getObject(getSelectedIndex()));
MahoMapsApp.BringSubScreen(new SearchResultScreen(results.getObject(getSelectedIndex()), overlay));
}
}
}
| 1,884 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
KeyboardHelpScreen.java | /FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/screens/KeyboardHelpScreen.java | package mahomaps.screens;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import mahomaps.MahoMapsApp;
public class KeyboardHelpScreen extends Form implements CommandListener {
public KeyboardHelpScreen() {
super(MahoMapsApp.text[10]);
add(new StringItem(MahoMapsApp.text[76], "D-PAD"));
add(new StringItem(MahoMapsApp.text[77], "*, #"));
add(new StringItem(MahoMapsApp.text[78], "1"));
add(new StringItem(MahoMapsApp.text[152], "3"));
add(new StringItem(MahoMapsApp.text[27], "7"));
add(new StringItem(MahoMapsApp.text[148], "9"));
add(new StringItem(MahoMapsApp.text[153], "0"));
add(new StringItem(MahoMapsApp.text[79], MahoMapsApp.text[81]));
add(new StringItem(MahoMapsApp.text[80], MahoMapsApp.text[82]));
addCommand(MahoMapsApp.back);
setCommandListener(this);
}
private void add(StringItem item) {
item.setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE);
append(item);
}
public void commandAction(Command c, Displayable d) {
if (c == MahoMapsApp.back) {
MahoMapsApp.BringMenu();
}
}
}
| 1,262 | Java | .java | mahomaps/mm-v1 | 18 | 4 | 11 | 2023-05-01T09:07:22Z | 2024-05-05T22:00:52Z |
UtilsUnitTest.java | /FileExtraction/Java_unseen/community-code_amps/app/src/test/java/com/communitycode/amps/main/UtilsUnitTest.java | package com.communitycode.amps.main;
import org.junit.Test;
import static com.communitycode.amps.main.Utils.convertCelsiusToFahrenheit;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class UtilsUnitTest {
@Test
public void convertCelsiusToFahrenheit_sanity() throws Exception {
assertEquals(32, convertCelsiusToFahrenheit(0), 0);
assertEquals(212, convertCelsiusToFahrenheit(100), 0);
}
} | 586 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
CurrentTrackerUnitTest.java | /FileExtraction/Java_unseen/community-code_amps/app/src/test/java/com/communitycode/amps/main/CurrentTrackerUnitTest.java | package com.communitycode.amps.main;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class CurrentTrackerUnitTest {
@Test
public void addHistory_overflow() throws Exception {
BatteryInfoInterface mockBatteryInfo = mock(BatteryInfoInterface.class);
CurrentTracker currentTracker = new CurrentTracker(null, mockBatteryInfo);
for (int i = 0; i < CurrentTracker.MAX_HISTORY*2; i++) {
currentTracker.addHistory(i);
}
assertEquals(CurrentTracker.MAX_HISTORY, currentTracker.currentHistory.size());
assertEquals( "Check first in first out",
CurrentTracker.MAX_HISTORY, currentTracker.currentHistory.get(0).intValue());
}
@Test
public void updateAmpStatistics_emptyHistory() throws Exception {
BatteryInfoInterface mockBatteryInfo = mock(BatteryInfoInterface.class);
CurrentTracker currentTracker = new CurrentTracker(null, mockBatteryInfo);
currentTracker.updateAmpStatistics();
verify(mockBatteryInfo).setMinAmps(null);
verify(mockBatteryInfo).setMaxAmps(null);
verify(mockBatteryInfo).setCurrentAmps(null);
}
@Test
public void updateAmpStatistics_hasHistory() throws Exception {
BatteryInfoInterface mockBatteryInfo = mock(BatteryInfoInterface.class);
CurrentTracker currentTracker = new CurrentTracker(null, mockBatteryInfo);
currentTracker.addHistory(10);
currentTracker.addHistory(-10);
currentTracker.addHistory(5);
currentTracker.addHistory(10);
currentTracker.addHistory(-3);
currentTracker.updateAmpStatistics();
verify(mockBatteryInfo).setMinAmps(-10);
verify(mockBatteryInfo).setMaxAmps(10);
verify(mockBatteryInfo).setCurrentAmps(-3);
}
}
| 1,915 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryMethodPicklerTest.java | /FileExtraction/Java_unseen/community-code_amps/app/src/test/java/com/communitycode/amps/main/settings/BatteryMethodPicklerTest.java | package com.communitycode.amps.main.settings;
import com.communitycode.amps.main.BatteryInfoInterface;
import com.communitycode.amps.main.CurrentTracker;
import com.communitycode.amps.main.battery.BatteryMethodInterface;
import com.communitycode.amps.main.battery.OfficialBatteryMethod;
import com.communitycode.amps.main.battery.UnofficialBatteryMethod;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
public class BatteryMethodPicklerTest {
@Test
public void official() throws Exception {
OfficialBatteryMethod officialBatteryMethod = new OfficialBatteryMethod(null);
String json = BatteryMethodPickler.toJson(officialBatteryMethod);
BatteryMethodInterface method = BatteryMethodPickler.fromJson(json, null);
assertTrue(OfficialBatteryMethod.class.isInstance(method));
}
@Test
public void unofficial_null() throws Exception {
UnofficialBatteryMethod unofficialBatteryMethod = new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_max", 1.0F, null, null, new String[]{});
String json = BatteryMethodPickler.toJson(unofficialBatteryMethod);
UnofficialBatteryMethod method = (UnofficialBatteryMethod) BatteryMethodPickler.fromJson(json, null);
assertEquals(method.chargeField, unofficialBatteryMethod.chargeField);
assertEquals(method.dischargeField, unofficialBatteryMethod.dischargeField);
assertEquals(method.filePath, unofficialBatteryMethod.filePath);
assertEquals(method.reader, unofficialBatteryMethod.reader);
assertEquals(method.scale, unofficialBatteryMethod.scale, 0.01);
}
@Test
public void unofficial_full() throws Exception {
UnofficialBatteryMethod unofficialBatteryMethod = new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_max", 1.0F, "asdf", "fdsa", new String[]{});
String json = BatteryMethodPickler.toJson(unofficialBatteryMethod);
UnofficialBatteryMethod method = (UnofficialBatteryMethod) BatteryMethodPickler.fromJson(json, null);
assertEquals(method.chargeField, unofficialBatteryMethod.chargeField);
assertEquals(method.dischargeField, unofficialBatteryMethod.dischargeField);
assertEquals(method.filePath, unofficialBatteryMethod.filePath);
assertEquals(method.reader, unofficialBatteryMethod.reader);
assertEquals(method.scale, unofficialBatteryMethod.scale, 0.01);
}
}
| 2,542 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
MainActivity.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/MainActivity.java | package com.communitycode.amps.main;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.BatteryManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.communitycode.amps.main.settings.SettingsActivity;
import java.text.NumberFormat;
import java.util.ArrayList;
import static com.communitycode.amps.main.Utils.convertCelsiusToFahrenheit;
import static com.communitycode.amps.main.Utils.flattenViewGroup;
public class MainActivity extends AppCompatActivity implements BatteryInfoInterface {
private BatteryPresenter mBatteryPresenter;
private void findAndSetText(int id, String text) {
if (text == null) {
findAndSetText(id, R.string.blank_value);
}
else {
((TextView) findViewById(id)).setText(text);
}
}
private void findAndSetText(int id, int resourceId) {
((TextView) findViewById(id)).setText(getResources().getString(resourceId));
}
public void changeAccentColor(int colorResId) {
int color = getResources().getColor(colorResId);
final String ACCENT = getResources().getString(R.string.accent_tag);
// update text views
ArrayList<View> views = flattenViewGroup((ViewGroup) findViewById(R.id.root_main_activity));
for (int i = 0 ; i < views.size(); i ++) {
View view = views.get(i);
if (view instanceof TextView) {
TextView textView = (TextView) view;
Object tag = textView.getTag();
if (tag != null && tag.equals(ACCENT)) {
textView.setTextColor(color);
}
}
}
// update throbber
ProgressBar throbber = findViewById(R.id.indeterminateBar);
throbber.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
public void resetCurrentHistory(View view) {
mBatteryPresenter.resetCurrentHistory();
}
public void goToCurrentInformation(View view) {
BatteryInfoAlertDialog fragment = new BatteryInfoAlertDialog();
getSupportFragmentManager()
.beginTransaction()
.add(fragment, "dialog")
.commit();
}
public void showAmpInfoButton(boolean visible) {
TextView textView = findViewById(R.id.amp_info);
int i = visible ? View.VISIBLE : View.INVISIBLE;
textView.setVisibility(i);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findAndSetText(R.id.build_id_value, Build.ID);
findAndSetText(R.id.android_version_value, Build.VERSION.RELEASE);
findAndSetText(R.id.model_value, Build.MODEL);
mBatteryPresenter = new BatteryPresenter(this, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
mBatteryPresenter.start();
}
@Override
protected void onPause() {
super.onPause();
mBatteryPresenter.stop();
}
@Override
// value in milliamps
public void setMaxAmps(Integer value) {
if (value == null) {
findAndSetText(R.id.max_value, R.string.blank_value);
}
else {
findAndSetText(R.id.max_value, getString(R.string.mA, value));
}
}
@Override
// value in milliamps
public void setMinAmps(Integer value) {
if (value == null) {
findAndSetText(R.id.min_value, R.string.blank_value);
}
else {
findAndSetText(R.id.min_value, getString(R.string.mA, value));
}
}
@Override
// value in milliamps
public void setCurrentAmps(Integer value) {
if (value == null) {
findAndSetText(R.id.amps_value, R.string.blank_value);
}
else {
findAndSetText(R.id.amps_value, getString(R.string.mA, value));
}
}
@Override
// value in volts
public void setVoltage(Double value) {
if (value == null) {
findAndSetText(R.id.voltage_value, R.string.blank_value);
}
else {
findAndSetText(R.id.voltage_value, getString(R.string.V, value));
}
}
@Override
// value in Celsius
public void setTemperature(Double value) {
if (value == null) {
findAndSetText(R.id.temperature_value, R.string.blank_value);
}
else {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isCelsius = sharedPref.getBoolean("use_celsius", true);
if (isCelsius) {
findAndSetText(R.id.temperature_value, getString(R.string.degrees_c, value));
}
else {
value = convertCelsiusToFahrenheit(value);
findAndSetText(R.id.temperature_value, getString(R.string.degrees_f, value));
}
}
}
@Override
// status one of BatteryManager.BATTERY_STATUS_*
public void setChargingStatus(int status) {
int statusLbl;
switch (status) {
case BatteryManager.BATTERY_STATUS_CHARGING:
statusLbl = R.string.battery_status_charging;
changeAccentColor(R.color.chargingAccent);
break;
case BatteryManager.BATTERY_STATUS_FULL:
statusLbl = R.string.battery_status_full;
changeAccentColor(R.color.fullAccent);
break;
case BatteryManager.BATTERY_STATUS_UNKNOWN:
statusLbl = -1;
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
default:
statusLbl = R.string.battery_status_discharging;
changeAccentColor(R.color.dischargingAccent);
break;
}
if (statusLbl != -1) {
findAndSetText(R.id.charging_status_value, statusLbl);
}
else {
findAndSetText(R.id.charging_status_value, R.string.blank_value);
}
}
@Override
// plugged one of BatteryManager.BATTERY_PLUGGED_*
public void setPluggedInStatus(int plugged) {
int pluggedLbl;
switch (plugged) {
case BatteryManager.BATTERY_PLUGGED_WIRELESS:
pluggedLbl = R.string.battery_plugged_wireless;
break;
case BatteryManager.BATTERY_PLUGGED_USB:
pluggedLbl = R.string.battery_plugged_usb;
break;
case BatteryManager.BATTERY_PLUGGED_AC:
pluggedLbl = R.string.battery_plugged_ac;
break;
default:
pluggedLbl = R.string.battery_plugged_none;
break;
}
findAndSetText(R.id.plugged_in_value, pluggedLbl);
}
@Override
// health one of BatteryManager.BATTERY_HEALTH_*
public void setBatteryHealth(int health) {
int healthLbl = -1;
switch (health) {
case BatteryManager.BATTERY_HEALTH_COLD:
healthLbl = R.string.battery_health_cold;
break;
case BatteryManager.BATTERY_HEALTH_DEAD:
healthLbl = R.string.battery_health_dead;
break;
case BatteryManager.BATTERY_HEALTH_GOOD:
healthLbl = R.string.battery_health_good;
break;
case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
healthLbl = R.string.battery_health_over_voltage;
break;
case BatteryManager.BATTERY_HEALTH_OVERHEAT:
healthLbl = R.string.battery_health_overheat;
break;
case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
healthLbl = R.string.battery_health_unspecified_failure;
break;
case BatteryManager.BATTERY_HEALTH_UNKNOWN:
default:
break;
}
if (healthLbl == -1) {
findAndSetText(R.id.health_value, R.string.blank_value);
}
else {
findAndSetText(R.id.health_value, healthLbl);
}
}
@Override
public void setBatteryPercent(Double value) {
if (value == null) {
findAndSetText(R.id.battery_level_value, R.string.blank_value);
}
else {
findAndSetText(R.id.battery_level_value, NumberFormat.getPercentInstance().format(value));
}
}
@Override
public void setBatteryTechnology(String value) {
if (value == null) {
findAndSetText(R.id.technology_value, R.string.blank_value);
}
else {
findAndSetText(R.id.technology_value, value);
}
}
}
| 10,291 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
CurrentTracker.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/CurrentTracker.java | package com.communitycode.amps.main;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.preference.PreferenceManager;
import com.communitycode.amps.main.battery.BatteryMethodInterface;
import com.communitycode.amps.main.battery.OfficialBatteryMethod;
import com.communitycode.amps.main.battery.UnofficialBatteryApi;
import com.communitycode.amps.main.settings.BatteryMethodPickler;
import java.util.ArrayList;
public class CurrentTracker {
protected static final int MAX_HISTORY = 1000;
private static final int UPDATE_DELAY = 500;
// current in milliamps
protected ArrayList<Integer> currentHistory = new ArrayList<>();
private Runnable sendData;
final private Handler handler = new Handler();
final private Context mCtx;
final private BatteryInfoInterface mBatteryInfoInterface;
public CurrentTracker (Context ctx, BatteryInfoInterface batteryInfoInterface) {
mCtx = ctx;
mBatteryInfoInterface = batteryInfoInterface;
sendData = new Runnable(){
public void run(){
try {
updateAmps();
handler.postDelayed(this, UPDATE_DELAY);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
}
public void start() {
handler.post(sendData);
}
public void stop() {
handler.removeCallbacks(sendData);
}
private void updateAmps() {
Integer current = null;
boolean showAmpInfo = true;
// Get current by preference
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mCtx);
String json = sharedPref.getString("unofficial_measurement", null);
BatteryMethodInterface method = BatteryMethodPickler.fromJson(json, mCtx);
if (method != null) {
current = method.read();
}
else {
// Get current by best guess
current = new OfficialBatteryMethod(mCtx).read();
if (current == null || current == 0) {
current = UnofficialBatteryApi.getCurrent();
}
else {
// Official method worked and preference is not set. No need to clutter the UI.
showAmpInfo = false;
}
}
mBatteryInfoInterface.showAmpInfoButton(showAmpInfo);
if (current != null) {
addHistory(current);
updateAmpStatistics();
}
}
protected void addHistory(int value) {
currentHistory.add(value);
while (currentHistory.size() > MAX_HISTORY) {
currentHistory.remove(0);
}
}
public void resetHistory() {
currentHistory.clear();
updateAmpStatistics();
}
protected void updateAmpStatistics() {
if (currentHistory.size() > 0) {
int max = currentHistory.get(0);
int min = currentHistory.get(0);
for (int i = 0; i < currentHistory.size(); i++) {
int val = currentHistory.get(i);
max = val > max ? val : max;
min = val < min ? val : min;
}
int last = currentHistory.get(currentHistory.size() - 1);
mBatteryInfoInterface.setMaxAmps(max);
mBatteryInfoInterface.setMinAmps(min);
mBatteryInfoInterface.setCurrentAmps(last);
}
else {
mBatteryInfoInterface.setMaxAmps(null);
mBatteryInfoInterface.setMinAmps(null);
mBatteryInfoInterface.setCurrentAmps(null);
}
}
}
| 3,697 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryPresenter.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/BatteryPresenter.java | package com.communitycode.amps.main;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.util.Log;
public class BatteryPresenter {
private final BatteryInfoInterface mBatteryInfoInterface;
private final Context mCtx;
private final CurrentTracker mCurrentTracker;
private final BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
// Avoid crashing the app
updateBatteryData(intent);
} catch(Exception e) {
Log.e("error", e.getMessage());
}
}
};
private void updateBatteryData(Intent intent) {
int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, 0);
mBatteryInfoInterface.setBatteryHealth(health);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
boolean isError = level == -1 || scale == -1 || scale == 0;
mBatteryInfoInterface.setBatteryPercent(isError ? null : level /(double) scale);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
mBatteryInfoInterface.setPluggedInStatus(plugged);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
mBatteryInfoInterface.setChargingStatus(status);
String technology = intent.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
isError = technology == null || "".equals(technology);
mBatteryInfoInterface.setBatteryTechnology(isError ? null : technology);
double temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)/10f;
mBatteryInfoInterface.setTemperature(temperature > 0 ? temperature : null);
double voltage = ((double) intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0))/1000;
mBatteryInfoInterface.setVoltage(voltage > 0 ? voltage : null);
}
public BatteryPresenter(Context ctx, BatteryInfoInterface batteryInfoInterface) {
mBatteryInfoInterface = batteryInfoInterface;
mCtx = ctx;
mCurrentTracker = new CurrentTracker(ctx, batteryInfoInterface);
}
public void resetCurrentHistory() {
mCurrentTracker.resetHistory();
}
public void start() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mCtx.registerReceiver(batteryInfoReceiver, intentFilter);
mCurrentTracker.start();
}
public void stop() {
mCtx.unregisterReceiver(batteryInfoReceiver);
mCurrentTracker.stop();
}
}
| 2,853 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryInfoAlertDialog.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/BatteryInfoAlertDialog.java | package com.communitycode.amps.main;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import com.communitycode.amps.main.settings.SettingsActivity;
public class BatteryInfoAlertDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.battery_info_alert_message)
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(R.string.go_to_battery_info_settings, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getContext(), SettingsActivity.class);
startActivity(intent);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
| 1,274 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
Utils.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/Utils.java | package com.communitycode.amps.main;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class Utils {
public static ArrayList<View> flattenViewGroup(ViewGroup root) {
ArrayList<View> views = new ArrayList<>();
if (root == null) {
return views;
}
for (int i = 0; i < root.getChildCount(); i++) {
final View child = root.getChildAt(i);
views.add(child);
if (child instanceof ViewGroup) {
views.addAll(flattenViewGroup((ViewGroup) child));
}
}
return views;
}
public static double convertCelsiusToFahrenheit(double value) {
return value*1.8 + 32;
}
}
| 742 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryInfoInterface.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/BatteryInfoInterface.java | package com.communitycode.amps.main;
public interface BatteryInfoInterface {
// value in milliamps
void setMaxAmps(Integer value);
// value in milliamps
void setMinAmps(Integer value);
// value in milliamps
void setCurrentAmps(Integer value);
// value in volts
void setVoltage(Double value);
// value in Celsius
void setTemperature(Double value);
// status one of BatteryManager.BATTERY_STATUS_*
void setChargingStatus(int status);
// plugged one of BatteryManager.BATTERY_PLUGGED_*
void setPluggedInStatus(int plugged);
// health one of BatteryManager.BATTERY_HEALTH_*
void setBatteryHealth(int health);
void setBatteryPercent(Double value);
void setBatteryTechnology(String value);
void showAmpInfoButton(boolean visible);
}
| 817 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
SettingsActivity.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/settings/SettingsActivity.java | package com.communitycode.amps.main.settings;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
| 505 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
SettingsFragment.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/settings/SettingsFragment.java | package com.communitycode.amps.main.settings;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import com.communitycode.amps.main.R;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
}
} | 443 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryMethodPickler.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/settings/BatteryMethodPickler.java | package com.communitycode.amps.main.settings;
import android.content.Context;
import android.util.Log;
import com.communitycode.amps.main.battery.BatteryMethodInterface;
import com.communitycode.amps.main.battery.OfficialBatteryMethod;
import com.communitycode.amps.main.battery.UnofficialBatteryMethod;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.lang.reflect.Type;
public class BatteryMethodPickler {
private static Class<BatteryMethodInterface>[] x = new Class[]{OfficialBatteryMethod.class, UnofficialBatteryMethod.class};
public static String DISCHARGEFIELD = "DISCHARGEFIELD";
public static String CHARGEFIELD = "CHARGEFIELD";
public static String FILEPATH = "FILEPATH";
public static String SCALE = "SCALE";
public static String READER = "READER";
public static String TYPE = "TYPE";
public static String OFFICIALBATTERYMETHOD = "OFFICIALBATTERYMETHOD";
public static String UNOFFICIALBATTERYMETHOD = "UNOFFICIALBATTERYMETHOD";
public static BatteryMethodInterface fromJson(String json, Context mCtx) {
if (json == null) {
return null;
}
try {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
String type = jsonObject.get(TYPE).getAsString();
if (type.equals(OFFICIALBATTERYMETHOD)) {
return new OfficialBatteryMethod(mCtx);
}
else if (type.equals(UNOFFICIALBATTERYMETHOD)) {
return new UnofficialBatteryMethod(
jsonObject.get(READER).getAsInt(),
jsonObject.get(FILEPATH).getAsString(),
jsonObject.get(SCALE).getAsFloat(),
jsonObject.has(DISCHARGEFIELD) ? jsonObject.get(DISCHARGEFIELD).getAsString() : null,
jsonObject.has(CHARGEFIELD) ? jsonObject.get(CHARGEFIELD).getAsString() : null,
new String[] {});
}
else {
Log.d("Amps", "Unknown method. Json="+json);
}
}
catch (Exception e) {
Log.d("Amps", "Failed to parse preference. Json=" + json + " error=" + e.getMessage());
}
return null;
}
public static String toJson(BatteryMethodInterface obj) {
if (OfficialBatteryMethod.class.isInstance(obj)) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(TYPE, OFFICIALBATTERYMETHOD);
Gson gson = new Gson();
return gson.toJson(jsonObject);
}
else if (UnofficialBatteryMethod.class.isInstance(obj)) {
UnofficialBatteryMethod method = (UnofficialBatteryMethod) obj;
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(TYPE, UNOFFICIALBATTERYMETHOD);
jsonObject.addProperty(DISCHARGEFIELD, method.dischargeField);
jsonObject.addProperty(CHARGEFIELD, method.chargeField);
jsonObject.addProperty(FILEPATH, method.filePath);
jsonObject.addProperty(READER, method.reader);
jsonObject.addProperty(SCALE, method.scale);
Gson gson = new Gson();
return gson.toJson(jsonObject);
}
return null;
}
}
| 3,485 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
UnofficialBatteryMethodAdapter.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/settings/UnofficialBatteryMethodAdapter.java | package com.communitycode.amps.main.settings;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.communitycode.amps.main.R;
import java.util.ArrayList;
public class UnofficialBatteryMethodAdapter extends RecyclerView.Adapter<UnofficialBatteryMethodAdapter.ViewHolder> {
private int mCheckedPosition;
private ArrayList<MethodInfo> mDataset;
private OnClickHandler mOnClickListener;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
private final CheckBox mCheckBox;
// each data item is just a string in this case
public View mView;
public TextView mFilePath;
public TextView mCurrentValue;
public ViewHolder(View v) {
super(v);
mFilePath = v.findViewById(R.id.filePath);
mCheckBox = v.findViewById(R.id.checkbox);
mCurrentValue = v.findViewById(R.id.currentValue);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public UnofficialBatteryMethodAdapter(ArrayList<MethodInfo> myDataset, int checkedPosition) {
mDataset = myDataset;
mCheckedPosition = checkedPosition;
}
// Create new views (invoked by the layout manager)
@Override
public UnofficialBatteryMethodAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
Context context = parent.getContext();
LayoutInflater li = LayoutInflater.from(context);
View view = li.inflate(R.layout.unofficialbatteryapi_dialog, parent, false);
return new ViewHolder(view);
}
public void setOnClickListener(OnClickHandler onClickListener) {
mOnClickListener = onClickListener;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Context context = holder.mView.getContext();
MethodInfo method = mDataset.get(position);
View.OnClickListener onClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (mOnClickListener != null) {
mOnClickListener.onClick(holder.getAdapterPosition());
}
}
};
holder.mView.setOnClickListener(onClickListener);
holder.mFilePath.setText(method.name);
Integer val = method.value;
if (val == null) {
val = 0;
}
holder.mCurrentValue.setText(context.getString(R.string.value, val));
holder.mCheckBox.setChecked(mCheckedPosition == position);
holder.mCheckBox.setOnClickListener(onClickListener);
}
public void setCheckedPosition(int position) {
this.notifyItemChanged(mCheckedPosition);
mCheckedPosition = position;
this.notifyItemChanged(position);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.size();
}
public interface OnClickHandler {
void onClick(int position);
}
public static class MethodInfo {
public String name;
public Integer value;
MethodInfo(String name, Integer value) {
this.name = name;
this.value = value;
}
}
} | 3,966 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
UnofficialBatteryApiPreference.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/settings/UnofficialBatteryApiPreference.java | package com.communitycode.amps.main.settings;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import com.communitycode.amps.main.R;
import com.communitycode.amps.main.battery.BatteryMethodInterface;
import com.communitycode.amps.main.battery.OfficialBatteryMethod;
import com.communitycode.amps.main.battery.UnofficialBatteryApi;
import com.communitycode.amps.main.battery.UnofficialBatteryMethod;
import java.util.ArrayList;
import java.util.List;
public class UnofficialBatteryApiPreference extends DialogPreference {
private ArrayList<UnofficialBatteryMethodAdapter.MethodInfo> mEntries;
private ArrayList<String> mEntryValues;
private String mValue;
private String mSummary;
private int mClickedDialogEntryIndex;
private boolean mValueSet;
public UnofficialBatteryApiPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mEntries = new ArrayList<>();
mEntryValues = new ArrayList<>();
BatteryMethodInterface official = new OfficialBatteryMethod(context);
UnofficialBatteryMethodAdapter.MethodInfo defaultMethod =
new UnofficialBatteryMethodAdapter.MethodInfo(context.getString(R.string.xdefault),
official.read());
mEntries.add(defaultMethod);
mEntryValues.add(BatteryMethodPickler.toJson(official));
for (UnofficialBatteryMethod method : distinct(filterApplicable(UnofficialBatteryApi.methods))) {
mEntries.add(new UnofficialBatteryMethodAdapter.MethodInfo(method.filePath, method.read()));
mEntryValues.add(BatteryMethodPickler.toJson(method));
}
setPositiveButtonText(null);
setNegativeButtonText(android.R.string.cancel);
setDialogIcon(null);
}
public static List<UnofficialBatteryMethod> filterApplicable(UnofficialBatteryMethod[] methods) {
ArrayList<UnofficialBatteryMethod> applicableMethods = new ArrayList<>();
for (UnofficialBatteryMethod method : methods) {
if (method.isApplicable(UnofficialBatteryApi.BUILD_MODEL)) {
applicableMethods.add(method);
}
}
return applicableMethods;
}
public static List<UnofficialBatteryMethod> distinct(List<UnofficialBatteryMethod> methods) {
ArrayList<UnofficialBatteryMethod> uniqueMethods = new ArrayList<>();
for(UnofficialBatteryMethod a : methods) {
boolean found = false;
for (UnofficialBatteryMethod b : uniqueMethods) {
if (a.equalsIgnoreTransient(b)) {
found = true;
break;
}
}
if (!found) {
uniqueMethods.add(a);
}
}
return uniqueMethods;
}
/**
* Sets the value of the key. This should be one of the entries in
* entry values.
*
* @param value The value to set for the key.
*/
public void setValue(String value) {
// Always persist/notify the first time.
final boolean changed = !TextUtils.equals(mValue, value);
if (changed || !mValueSet) {
mValue = value;
mValueSet = true;
persistString(value);
if (changed) {
notifyChanged();
}
}
}
/**
* Returns the summary of this ListPreference. If the summary
* has a {@linkplain java.lang.String#format String formatting}
* marker in it (i.e. "%s" or "%1$s"), then the current entry
* value will be substituted in its place.
*
* @return the summary with appropriate string substitution
*/
@Override
public CharSequence getSummary() {
final UnofficialBatteryMethodAdapter.MethodInfo entry = getEntry();
if (mSummary == null) {
return super.getSummary();
} else {
return String.format(mSummary, entry == null ? "" : entry.name);
}
}
/**
* Sets the summary for this Preference with a CharSequence.
* If the summary has a
* {@linkplain java.lang.String#format String formatting}
* marker in it (i.e. "%s" or "%1$s"), then the current entry
* value will be substituted in its place when it's retrieved.
*
* @param summary The summary for the preference.
*/
@Override
public void setSummary(CharSequence summary) {
super.setSummary(summary);
if (summary == null && mSummary != null) {
mSummary = null;
} else if (summary != null && !summary.equals(mSummary)) {
mSummary = summary.toString();
}
}
/**
* Returns the value of the key. This should be one of the entries in
* entry values
*
* @return The value of the key.
*/
public String getValue() {
return mValue;
}
/**
* Returns the entry corresponding to the current value.
*
* @return The entry corresponding to the current value, or null.
*/
public UnofficialBatteryMethodAdapter.MethodInfo getEntry() {
int index = getValueIndex();
return index >= 0 && mEntries != null ? mEntries.get(index) : null;
}
/**
* Returns the index of the given value (in the entry values array).
*
* @param value The value whose index should be returned.
* @return The index of the value, or -1 if not found.
*/
public int findIndexOfValue(String value) {
if (value != null && mEntryValues != null) {
for (int i = mEntryValues.size() - 1; i >= 0; i--) {
if (mEntryValues.get(i).equals(value)) {
return i;
}
}
}
return -1;
}
private int getValueIndex() {
return findIndexOfValue(mValue);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
if (mEntries == null || mEntryValues == null) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array.");
}
Context context = builder.getContext();
RecyclerView mRecyclerView = new RecyclerView(context);
RecyclerView.LayoutManager mLayoutManager;
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(context);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mClickedDialogEntryIndex = getValueIndex();
final UnofficialBatteryMethodAdapter mAdapter = new UnofficialBatteryMethodAdapter(mEntries, mClickedDialogEntryIndex);
mAdapter.setOnClickListener(new UnofficialBatteryMethodAdapter.OnClickHandler() {
public void onClick(int position) {
UnofficialBatteryApiPreference that = UnofficialBatteryApiPreference.this;
mAdapter.setCheckedPosition(position);
that.mClickedDialogEntryIndex = that.mClickedDialogEntryIndex == position ? -1 : position;
Dialog dialog = that.getDialog();
that.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
mRecyclerView.setAdapter(mAdapter);
builder.setView(mRecyclerView);
builder.setPositiveButton(null, null);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && mClickedDialogEntryIndex >= 0 && mEntryValues != null) {
String value = mEntryValues.get(mClickedDialogEntryIndex);
if (callChangeListener(value)) {
setValue(value);
}
}
// Same item was clicked. Deselect item
if (positiveResult && mClickedDialogEntryIndex == -1) {
String value = null;
if (callChangeListener(value)) {
setValue(value);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString(mValue) : (String) defaultValue);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
final SavedState myState = new SavedState(superState);
myState.value = getValue();
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setValue(myState.value);
}
private static class SavedState extends BaseSavedState {
String value;
public SavedState(Parcel source) {
super(source);
value = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(value);
}
public SavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
} | 10,492 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
UnofficialBatteryApi.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/UnofficialBatteryApi.java | package com.communitycode.amps.main.battery;
import android.os.Build;
import java.util.Locale;
public class UnofficialBatteryApi {
public static final String BUILD_MODEL = Build.MODEL.toLowerCase(Locale.ENGLISH);
public static Integer getCurrent() {
for (UnofficialBatteryMethod unofficialBatteryMethod : methods) {
if (unofficialBatteryMethod.isApplicable(BUILD_MODEL)) {
Integer val = unofficialBatteryMethod.read();
if (val != null) {
return val;
}
}
}
return null;
}
public static final UnofficialBatteryMethod[] methods = {
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_max", 1.0F, null, null, new String[]{"gt-i9300", "gt-i9300T", "gt-i9305", "gt-i9305N", "gt-i9305T", "shv-e210k", "shv-e210l", "shv-e210s", "sgh-t999", "sgh-t999l", "sgh-t999v", "sgh-i747", "sgh-i747m", "sgh-n064", "sc-06d", "sgh-n035", "sc-03e", "SCH-j021", "scl21", "sch-r530", "sch-i535", "sch-S960l", "gt-i9308", "sch-i939", "sch-s968c"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_now", 1.0F, null, null, new String[]{"nexus 7", "one", "lg-d851"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/da9052-bat/current_avg", 1.0F, null, null, new String[]{"sl930"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_now", 1.0F, null, null, new String[]{"sgh-i337", "gt-i9505", "gt-i9500", "sch-i545", "find 5", "sgh-m919", "sgh-i537"}),
new UnofficialBatteryMethod(1, "/sys/devices/platform/mt6329-battery/FG_Battery_CurrentConsumption", 1.0F, null, null, new String[]{"cynus"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/BatteryAverageCurrent", 1.0F, null, null, new String[]{"zp900", "jy-g3", "zp800", "zp800h", "zp810", "w100", "zte v987"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_avg", 1.0F, null, null, new String[]{"gt-p31", "gt-p51"}),
new UnofficialBatteryMethod(2, "/sys/class/power_supply/battery/batt_attr_text", 1.0F, "I_MBAT", "I_MBAT", new String[]{"htc one x"}),
new UnofficialBatteryMethod(2, "/sys/class/power_supply/battery/smem_text", 1.0F, "eval_current", "batt_current", new String[]{"wildfire s"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_now", 1.0F, null, null, new String[]{"triumph", "ls670", "gt-i9300", "sm-n9005", "gt-n7100", "sgh-i317"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/batt_current", 1.0F, null, null, new String[]{"desire hd", "desire z", "inspire", "pg41200"}),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_now", 0.1F, null, null, new String[]{"LG-D850", "LG-D851", "LG-D852", "LG-D855", "LG-D856", "LG-D858", "LG-D859"}),
new UnofficialBatteryMethod(1, "/sys/devices/platform/ds2784-battery/getcurrent", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/i2c-adapter/i2c-0/0-0036/power_supply/ds2746-battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/i2c-adapter/i2c-0/0-0036/power_supply/battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/tegra-i2c.4/i2c-4/4-0040/current1_input", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bq27425_battery/charge_now", 0.1F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bq27541-bat/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(3, "/sys/class/power_supply/battery/smem_text", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/batt_current", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(2, "/sys/class/power_supply/battery/batt_attr_text", 1.0F, "batt_discharge_current", "batt_current", new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/batt_chg_current", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/charger_current", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/max17042-0/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bq27520/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/cpcap_battery/power_supply/usb/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/EcControl/BatCurrent", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/batt_current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/batt_current_adc", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/max170xx_battery/current_now", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/ab8500_fg/current_now", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/android-battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/ds2784-fuelgauge/current_now", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/Battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/msm-charger/power_supply/battery_gauge/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/battery/power_supply/battery/BatteryAverageCurrent", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/mt6320-battery/power_supply/battery/BatteryAverageCurrent", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/devices/platform/msm-battery/power_supply/battery/chg_current_adc", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bq27x41/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bq27541_battery/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/cw2015_battery/current_now", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/dollar_cove_battery/current_now", 0.001F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/bms/current_now", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_avg", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/BatteryAverageCurrent", 1.0F, null, null, new String[0]),
new UnofficialBatteryMethod(1, "/sys/class/power_supply/battery/current_max", 1.0F, null, null, new String[0])
};
}
| 7,661 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
OfficialBatteryMethod.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/OfficialBatteryMethod.java | package com.communitycode.amps.main.battery;
import android.content.Context;
import android.os.BatteryManager;
import android.os.Build;
public class OfficialBatteryMethod implements BatteryMethodInterface {
private final transient Context mCtx;
public OfficialBatteryMethod(Context context) {
mCtx = context;
}
public Integer read() {
if (Build.VERSION.SDK_INT < 21) {
return null;
}
BatteryManager mBatteryManager = (BatteryManager) mCtx.getSystemService(Context.BATTERY_SERVICE);
if (mBatteryManager == null) {
return null;
}
int current = mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
if (current != Integer.MIN_VALUE) {
return current / 1000;
}
return null;
}
}
| 839 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
UnofficialBatteryMethod.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/UnofficialBatteryMethod.java | package com.communitycode.amps.main.battery;
import com.communitycode.amps.main.battery.reader.BatteryAttrTextReader;
import com.communitycode.amps.main.battery.reader.OneLineReader;
import com.communitycode.amps.main.battery.reader.SMemTextReader;
import java.io.File;
public class UnofficialBatteryMethod implements BatteryMethodInterface {
public String dischargeField;
public String chargeField;
public String filePath;
public float scale;
public int reader;
public transient String[] modelFilter;
public UnofficialBatteryMethod(int reader, String filePath, float scale, String dischargeField, String chargeField, String[] modelFilter) {
this.filePath = filePath;
this.scale = scale;
this.reader = reader;
this.dischargeField = dischargeField;
this.chargeField = chargeField;
this.modelFilter = modelFilter;
}
public boolean checkModelFilter(String model) {
if (modelFilter.length == 0) {
return true;
}
for (String val : modelFilter) {
if (model.contains(val)) {
return true;
}
}
return false;
}
public boolean isApplicable(String model) {
if (checkModelFilter(model)) {
File f = new File(filePath);
return f.exists();
}
return false;
}
public Integer read() {
File f = new File(filePath);
Integer val = null;
switch (reader) {
case 1:
val = OneLineReader.getValue(f);
break;
case 2:
val = BatteryAttrTextReader.getValue(f, this.dischargeField, this.chargeField);
break;
case 3:
val = SMemTextReader.getValue();
break;
}
if (val == null) {
return null;
}
else {
return Math.round(val * scale);
}
}
public boolean equalsIgnoreTransient(UnofficialBatteryMethod b) {
return filePath.equals(b.filePath)
&& reader == b.reader
&& scale == b.scale
&& chargeField.equals(b.chargeField)
&& dischargeField.equals(b.dischargeField);
}
}
| 2,287 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
BatteryAttrTextReader.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/reader/BatteryAttrTextReader.java | /*
* Copyright (c) 2010-2013 Ran Manor
*
* This file is part of CurrentWidget.
*
* CurrentWidget is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CurrentWidget is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CurrentWidget. If not, see <http://www.gnu.org/licenses/>.
*
* Modified 23 March 2018
*/
package com.communitycode.amps.main.battery.reader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import android.util.Log;
public class BatteryAttrTextReader {
public static Integer getValue(File f, String dischargeField, String chargeField) {
String text;
Integer value = null;
FileReader fr = null;
BufferedReader br = null;
try {
// @@@ debug
//StringReader fr = new StringReader("vref: 1248\r\nbatt_id: 3\r\nbatt_vol: 4068\r\nbatt_current: 0\r\nbatt_discharge_current: 123\r\nbatt_temperature: 329\r\nbatt_temp_protection:normal\r\nPd_M:0\r\nI_MBAT:-313\r\npercent_last(RP): 94\r\npercent_update: 71\r\nlevel: 71\r\nfirst_level: 100\r\nfull_level:100\r\ncapacity:1580\r\ncharging_source: USB\r\ncharging_enabled: Slow\r\n");
fr = new FileReader(f);
br = new BufferedReader(fr);
String line = br.readLine();
final String chargeFieldHead = chargeField + ": ";
final String dischargeFieldHead = dischargeField + ": ";
while (line != null)
{
if (line.contains(chargeField))
{
text = line.substring(line.indexOf(chargeFieldHead) + chargeFieldHead.length());
try {
value = Integer.parseInt(text);
if (value != 0)
break;
}
catch (NumberFormatException nfe) {
Log.e("Amps", nfe.getMessage(), nfe);
}
}
// "batt_discharge_current:"
if (line.contains(dischargeField))
{
text = line.substring(line.indexOf(dischargeFieldHead) + dischargeFieldHead.length());
try {
value = (-1)*Math.abs(Integer.parseInt(text));
}
catch (NumberFormatException nfe) {
Log.e("Amps", nfe.getMessage(), nfe);
}
break;
}
line = br.readLine();
}
}
catch (Exception ex) {
Log.e("Amps", ex.getMessage(), ex);
}
finally
{
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
}
catch (Exception ex)
{
Log.e("Amps", ex.getMessage(), ex);
}
}
return value;
}
}
| 3,486 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
SMemTextReader.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/reader/SMemTextReader.java | /*
* Copyright (c) 2010-2011 Ran Manor
*
* This file is part of CurrentWidget.
*
* CurrentWidget is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CurrentWidget is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CurrentWidget. If not, see <http://www.gnu.org/licenses/>.
*
* Modified 23 March 2018
*/
package com.communitycode.amps.main.battery.reader;
import java.io.BufferedReader;
import java.io.FileReader;
import android.util.Log;
public class SMemTextReader {
public static Integer getValue() {
boolean success = false;
String text = null;
BufferedReader br = null;
FileReader fr = null;
try {
// @@@ debug StringReader fr = new StringReader("batt_id: 1\r\nbatt_vol: 3840\r\nbatt_vol_last: 0\r\nbatt_temp: 1072\r\nbatt_current: 1\r\nbatt_current_last: 0\r\nbatt_discharge_current: 112\r\nVREF_2: 0\r\nVREF: 1243\r\nADC4096_VREF: 4073\r\nRtemp: 70\r\nTemp: 324\r\nTemp_last: 0\r\npd_M: 20\r\nMBAT_pd: 3860\r\nI_MBAT: -114\r\npd_temp: 0\r\npercent_last: 57\r\npercent_update: 58\r\ndis_percent: 64\r\nvbus: 0\r\nusbid: 1\r\ncharging_source: 0\r\nMBAT_IN: 1\r\nfull_bat: 1300000\r\neval_current: 115\r\neval_current_last: 0\r\ncharging_enabled: 0\r\ntimeout: 30\r\nfullcharge: 0\r\nlevel: 58\r\ndelta: 1\r\nchg_time: 0\r\nlevel_change: 0\r\nsleep_timer_count: 11\r\nOT_led_on: 0\r\noverloading_charge: 0\r\na2m_cable_type: 0\r\nover_vchg: 0\r\n");
fr = new FileReader("/sys/class/power_supply/battery/smem_text");
br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
if (line.contains("I_MBAT")) {
text = line.substring(line.indexOf("I_MBAT: ") + 8);
success = true;
break;
}
line = br.readLine();
}
} catch (Exception ex) {
Log.e("Amps", ex.getMessage(), ex);
}
finally
{
try {
if (fr != null) {
fr.close();
}
if (br != null) {
br.close();
}
}
catch (Exception ex)
{
Log.e("Amps", ex.getMessage(), ex);
}
}
Integer value = null;
if (success) {
try {
value = Integer.parseInt(text);
} catch (NumberFormatException nfe) {
Log.e("Amps", nfe.getMessage(), nfe);
value = null;
}
}
return value;
}
} | 3,096 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
OneLineReader.java | /FileExtraction/Java_unseen/community-code_amps/app/src/main/java/com/communitycode/amps/main/battery/reader/OneLineReader.java | /*
* Copyright (c) 2010-2011 Ran Manor
*
* This file is part of CurrentWidget.
*
* CurrentWidget is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CurrentWidget is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CurrentWidget. If not, see <http://www.gnu.org/licenses/>.
*
* Modified 23 March 2018
*/
package com.communitycode.amps.main.battery.reader;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class OneLineReader {
public static Integer getValue(File _f) {
String text = null;
FileInputStream fs = null;
InputStreamReader sr = null;
BufferedReader br = null;
try {
fs = new FileInputStream(_f);
sr = new InputStreamReader(fs);
br = new BufferedReader(sr);
text = br.readLine();
} catch (Exception ex) {
// Expected to fail frequently due to permissions
Log.d("Amps", ex.getMessage(), ex);
}
finally
{
try {
if (fs != null) {
fs.close();
}
if (sr != null) {
sr.close();
}
if (br != null) {
br.close();
}
}
catch (Exception ex)
{
Log.e("Amps", ex.getMessage(), ex);
}
}
Integer value = null;
try {
if (text != null) {
value = Integer.parseInt(text);
}
} catch (NumberFormatException nfe) {
// Expected to fail frequently due to unknown format of text
Log.d("Amps", nfe.getMessage(), nfe);
}
return value;
}
} | 2,306 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
ActivityTest.java | /FileExtraction/Java_unseen/community-code_amps/app/src/androidTest/java/com/communitycode/amps/main/ActivityTest.java | package com.communitycode.amps.main;
// Disable test as intermediate progress bar prevents espresso's getActivity from working.
//
//import android.support.test.espresso.ViewInteraction;
//import android.support.test.rule.ActivityTestRule;
//import android.support.test.runner.AndroidJUnit4;
//import android.test.suitebuilder.annotation.LargeTest;
//import android.view.View;
//import android.view.ViewGroup;
//import android.view.ViewParent;
//
//import org.hamcrest.Description;
//import org.hamcrest.Matcher;
//import org.hamcrest.TypeSafeMatcher;
//import org.junit.Rule;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//
//import static android.support.test.InstrumentationRegistry.getInstrumentation;
//import static android.support.test.espresso.Espresso.onView;
//import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
//import static android.support.test.espresso.action.ViewActions.click;
//import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
//import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
//import static android.support.test.espresso.matcher.ViewMatchers.withId;
//import static android.support.test.espresso.matcher.ViewMatchers.withText;
//import static org.hamcrest.Matchers.allOf;
//import static org.hamcrest.Matchers.is;
//
//
//@LargeTest
//@RunWith(AndroidJUnit4.class)
//public class ActivityTest {
// @Rule
// public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
//
//
// @Test
// public void activityTest() {
// // Added a sleep statement to match the app's execution delay.
// // The recommended way to handle such scenarios is to use Espresso idling resources:
// // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// ViewInteraction mainTextView = onView(
// allOf(withId(R.id.title), withText("Amps"),
// isDisplayed()));
//
// assert(mainTextView != null);
//
// openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
//
// // Added a sleep statement to match the app's execution delay.
// // The recommended way to handle such scenarios is to use Espresso idling resources:
// // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// ViewInteraction appCompatTextView = onView(
// allOf(withId(R.id.title), withText("Settings"),
// childAtPosition(
// childAtPosition(
// withClassName(is("android.support.v7.view.menu.ListMenuItemView")),
// 0),
// 0),
// isDisplayed()));
// appCompatTextView.perform(click());
//
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// ViewInteraction settingsTextView = onView(
// allOf(withId(R.id.title), withText("Settings"),
// isDisplayed()));
//
// assert(settingsTextView != null);
//
// }
//
// private static Matcher<View> childAtPosition(
// final Matcher<View> parentMatcher, final int position) {
//
// return new TypeSafeMatcher<View>() {
// @Override
// public void describeTo(Description description) {
// description.appendText("Child at position " + position + " in parent ");
// parentMatcher.describeTo(description);
// }
//
// @Override
// public boolean matchesSafely(View view) {
// ViewParent parent = view.getParent();
// return parent instanceof ViewGroup && parentMatcher.matches(parent)
// && view.equals(((ViewGroup) parent).getChildAt(position));
// }
// };
// }
//}
| 4,385 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
UtilsInstrumentedTest.java | /FileExtraction/Java_unseen/community-code_amps/app/src/androidTest/java/com/communitycode/amps/main/UtilsInstrumentedTest.java | package com.communitycode.amps.main;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.communitycode.amps.main.Utils.flattenViewGroup;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class UtilsInstrumentedTest {
@Test
public void flattenViewGroup_null() throws Exception {
View[] expected = {};
assertArrayEquals(expected, flattenViewGroup(null).toArray());
}
@Test
public void flattenViewGroup_singleElement() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
ViewGroup viewGroup = new LinearLayout(appContext);
View A = new View(appContext);
viewGroup.addView(A);
View[] expected = {
A
};
assertArrayEquals(expected, flattenViewGroup(viewGroup).toArray());
}
@Test
public void flattenViewGroup_multipleElements() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
ViewGroup viewGroup = new LinearLayout(appContext);
View A = new View(appContext);
View B = new View(appContext);
viewGroup.addView(A);
viewGroup.addView(B);
View[] expected = {
A, B
};
assertArrayEquals(expected, flattenViewGroup(viewGroup).toArray());
}
@Test
public void flattenViewGroup_nestedElements() throws Exception {
Context appContext = InstrumentationRegistry.getTargetContext();
ViewGroup viewGroup = new LinearLayout(appContext);
View A = new View(appContext);
View B = new View(appContext);
ViewGroup C = new LinearLayout(appContext);
viewGroup.addView(A);
viewGroup.addView(C);
C.addView(B);
View[] expected = {
A, C, B
};
assertArrayEquals(expected, flattenViewGroup(viewGroup).toArray());
}
}
| 2,309 | Java | .java | community-code/amps | 29 | 14 | 5 | 2018-02-15T00:21:59Z | 2019-06-30T16:25:55Z |
ParserTest.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/test/java/org/openjdk/backports/ParserTest.java | package org.openjdk.backports;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.backports.jira.Parsers;
public class ParserTest {
static final String SAMPLE_COMMENT_OLD = "URL: http://hg.openjdk.java.net/jdk/jdk/rev/66f5241da404\n" +
"User: shade\n" +
"Date: 2019-04-15 16:22:25 +0000";
static final String SAMPLE_COMMENT = "Changeset: d9cb410e\n" +
"Author: Aleksey Shipilev <[email protected]>\n" +
"Date: 2022-07-31 18:52:16 +0000\n" +
"URL: https://git.openjdk.org/jdk/commit/d9cb410efc07a60e426f2399e020dcaccaba7dfa";
@Test
public void parseURL() {
Assert.assertEquals(
"http://hg.openjdk.java.net/jdk/jdk/rev/66f5241da404",
Parsers.parseURL(SAMPLE_COMMENT_OLD).get()
);
Assert.assertEquals(
"https://git.openjdk.org/jdk/commit/d9cb410efc07a60e426f2399e020dcaccaba7dfa",
Parsers.parseURL(SAMPLE_COMMENT).get()
);
}
@Test
public void parseUser() {
Assert.assertEquals(
"shade",
Parsers.parseUser(SAMPLE_COMMENT_OLD).get()
);
Assert.assertEquals(
"shade",
Parsers.parseUser(SAMPLE_COMMENT).get()
);
}
@Test
public void parseDayAgo() {
Assert.assertTrue(Parsers.parseDaysAgo(SAMPLE_COMMENT_OLD).isPresent());
Assert.assertTrue(Parsers.parseDaysAgo(SAMPLE_COMMENT).isPresent());
}
@Test
public void parseSecondsAgo() {
Assert.assertTrue(Parsers.parseSecondsAgo(SAMPLE_COMMENT_OLD).isPresent());
Assert.assertTrue(Parsers.parseSecondsAgo(SAMPLE_COMMENT).isPresent());
}
@Test
public void parsePriority() {
Assert.assertEquals(1, Parsers.parsePriority("P1"));
Assert.assertEquals(2, Parsers.parsePriority("P2"));
Assert.assertEquals(3, Parsers.parsePriority("P3"));
Assert.assertEquals(4, Parsers.parsePriority("P4"));
Assert.assertEquals(5, Parsers.parsePriority("P5"));
Assert.assertEquals(-1, Parsers.parsePriority("P"));
Assert.assertEquals(-1, Parsers.parsePriority("Px"));
Assert.assertEquals(-1, Parsers.parsePriority(""));
}
}
| 2,278 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
VersionsTest.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/test/java/org/openjdk/backports/VersionsTest.java | package org.openjdk.backports;
import org.junit.Assert;
import org.junit.Test;
import org.openjdk.backports.jira.Versions;
public class VersionsTest {
@Test
public void testParseVersion() {
Assert.assertEquals(8, Versions.parseMajorShenandoah("8-shenandoah"));
Assert.assertEquals(11, Versions.parseMajorShenandoah("11-shenandoah"));
Assert.assertEquals(-1, Versions.parseMajor("8-shenandoah"));
Assert.assertEquals(-1, Versions.parseMajor("11-shenandoah"));
Assert.assertEquals(-1, Versions.parseMajorShenandoah("8-aarch64"));
Assert.assertEquals(0, Versions.parseMajor("8-aarch64"));
Assert.assertEquals(0, Versions.parseMajor("emb-8u26"));
Assert.assertEquals(10, Versions.parseMajor("10"));
Assert.assertEquals(10, Versions.parseMajor("10.0.2"));
Assert.assertEquals(10, Versions.parseMajor("10u-open"));
Assert.assertEquals(10, Versions.parseMajor("10-pool"));
Assert.assertEquals(11, Versions.parseMajor("11"));
Assert.assertEquals(11, Versions.parseMajor("11.0.3"));
Assert.assertEquals(11, Versions.parseMajor("11.0.3-oracle"));
Assert.assertEquals(11, Versions.parseMajor("11-pool"));
Assert.assertEquals(12, Versions.parseMajor("12"));
Assert.assertEquals(12, Versions.parseMajor("12.0.2"));
Assert.assertEquals(12, Versions.parseMajor("12-pool"));
Assert.assertEquals(13, Versions.parseMajor("13"));
Assert.assertEquals(13, Versions.parseMajor("13.0.1"));
Assert.assertEquals(13, Versions.parseMajor("13.0.3"));
Assert.assertEquals(13, Versions.parseMajor("13-pool"));
Assert.assertEquals(14, Versions.parseMajor("14"));
Assert.assertEquals(14, Versions.parseMajor("14-pool"));
Assert.assertEquals(15, Versions.parseMajor("15"));
Assert.assertEquals(15, Versions.parseMajor("15-pool"));
Assert.assertEquals(7, Versions.parseMajor("7"));
Assert.assertEquals(7, Versions.parseMajor("7u40"));
Assert.assertEquals(7, Versions.parseMajor("7u231"));
Assert.assertEquals(6, Versions.parseMajor("6"));
Assert.assertEquals(8, Versions.parseMajor("8"));
Assert.assertEquals(8, Versions.parseMajor("8u40"));
Assert.assertEquals(8, Versions.parseMajor("8u111"));
Assert.assertEquals(8, Versions.parseMajor("8-pool"));
Assert.assertEquals(9, Versions.parseMajor("9"));
Assert.assertEquals(9, Versions.parseMajor("9.0.4"));
Assert.assertEquals(9, Versions.parseMajor("9-pool"));
Assert.assertEquals(6, Versions.parseMajor("OpenJDK6"));
Assert.assertEquals(7, Versions.parseMajor("openjdk7u"));
Assert.assertEquals(8, Versions.parseMajor("openjdk8u"));
Assert.assertEquals(8, Versions.parseMajor("openjdk8u212"));
Assert.assertEquals(0, Versions.parseMajor("solaris_10u7"));
}
@Test
public void testParseSubversion() {
Assert.assertEquals(-1, Versions.parseMinor("8-shenandoah"));
Assert.assertEquals(-1, Versions.parseMinor("11-shenandoah"));
Assert.assertEquals(-1, Versions.parseMinor("8-aarch64"));
Assert.assertEquals(3, Versions.parseMinor("11.0.3"));
Assert.assertEquals(-1, Versions.parseMinor("7"));
Assert.assertEquals(40, Versions.parseMinor("7u40"));
Assert.assertEquals(231, Versions.parseMinor("7u231"));
Assert.assertEquals(-1, Versions.parseMinor("8"));
Assert.assertEquals(40, Versions.parseMinor("8u40"));
Assert.assertEquals(111, Versions.parseMinor("8u111"));
Assert.assertEquals(-1, Versions.parseMinor("8-pool"));
Assert.assertEquals(-1, Versions.parseMinor("OpenJDK6"));
Assert.assertEquals(-1, Versions.parseMinor("openjdk7u"));
Assert.assertEquals(0, Versions.parseMinor("openjdk8u"));
Assert.assertEquals(212, Versions.parseMinor("openjdk8u212"));
Assert.assertEquals(6, Versions.parseMinor("11.0.6.0.1"));
Assert.assertEquals(6, Versions.parseMinor("11.0.6.0.1-oracle"));
}
@Test
public void testIsOracle() {
Assert.assertFalse(Versions.isOracle("8u192"));
Assert.assertFalse(Versions.isOracle("8u202"));
Assert.assertFalse(Versions.isOracle("openjdk8u212"));
Assert.assertTrue(Versions.isOracle("8u211"));
Assert.assertTrue(Versions.isOracle("8u212"));
Assert.assertFalse(Versions.isOracle("11.0.3"));
Assert.assertTrue(Versions.isOracle("11.0.3-oracle"));
Assert.assertFalse(Versions.isOracle("13.0.1"));
Assert.assertTrue(Versions.isOracle("13.0.1-oracle"));
Assert.assertFalse(Versions.isOracle("17.0.1"));
Assert.assertTrue(Versions.isOracle("17.0.1-oracle"));
}
@Test
public void testIsShared() {
Assert.assertTrue(Versions.isShared("8u192"));
Assert.assertTrue(Versions.isShared("openjdk8u202"));
Assert.assertTrue(Versions.isShared("8u202"));
Assert.assertFalse(Versions.isShared("openjdk8u212"));
Assert.assertFalse(Versions.isShared("8u211"));
Assert.assertFalse(Versions.isShared("8u212"));
Assert.assertTrue(Versions.isShared("11"));
Assert.assertTrue(Versions.isShared("11.0.1"));
Assert.assertTrue(Versions.isShared("11.0.2"));
Assert.assertFalse(Versions.isShared("11.0.3"));
Assert.assertFalse(Versions.isShared("11.0.3-oracle"));
Assert.assertTrue(Versions.isShared("13"));
Assert.assertTrue(Versions.isShared("13.0.1"));
Assert.assertTrue(Versions.isShared("13.0.2"));
Assert.assertFalse(Versions.isShared("13.0.3"));
Assert.assertFalse(Versions.isShared("13.0.1-oracle"));
Assert.assertFalse(Versions.isShared("13.0.2-oracle"));
Assert.assertFalse(Versions.isShared("13.0.3-oracle"));
Assert.assertTrue(Versions.isShared("14"));
Assert.assertTrue(Versions.isShared("14.0.1"));
Assert.assertTrue(Versions.isShared("14.0.2"));
Assert.assertFalse(Versions.isShared("14.0.3"));
Assert.assertFalse(Versions.isShared("14.0.1-oracle"));
Assert.assertFalse(Versions.isShared("14.0.2-oracle"));
Assert.assertFalse(Versions.isShared("14.0.3-oracle"));
Assert.assertTrue(Versions.isShared("17"));
Assert.assertTrue(Versions.isShared("17.0.1"));
Assert.assertTrue(Versions.isShared("17.0.2"));
Assert.assertFalse(Versions.isShared("17.0.3"));
Assert.assertFalse(Versions.isShared("17.0.1-oracle"));
Assert.assertFalse(Versions.isShared("17.0.2-oracle"));
Assert.assertFalse(Versions.isShared("17.0.3-oracle"));
}
@Test
public void testStripVendor() {
Assert.assertEquals("8u212", Versions.stripVendor("openjdk8u212"));
Assert.assertEquals("8u212", Versions.stripVendor("8u212"));
Assert.assertEquals("11.0.3", Versions.stripVendor("11.0.3"));
Assert.assertEquals("11.0.3", Versions.stripVendor("11.0.3-oracle"));
Assert.assertEquals("13.0.1", Versions.stripVendor("13.0.1"));
Assert.assertEquals("13.0.1", Versions.stripVendor("13.0.1-oracle"));
Assert.assertEquals("13.0.3", Versions.stripVendor("13.0.3"));
}
@Test
public void testCompare() {
Assert.assertEquals(-1, Versions.compare("11.0.2", "11.0.3"));
Assert.assertEquals(-1, Versions.compare("11.0.2", "11.0.3-oracle"));
Assert.assertEquals(-1, Versions.compare("11.0.2-oracle", "11.0.3"));
Assert.assertEquals(-1, Versions.compare("11.0.2-oracle", "11.0.3-oracle"));
Assert.assertEquals(0, Versions.compare("11.0.2", "11.0.2"));
Assert.assertEquals(0, Versions.compare("11.0.2", "11.0.2-oracle"));
Assert.assertEquals(0, Versions.compare("11.0.2-oracle", "11.0.2-oracle"));
Assert.assertEquals(1, Versions.compare("11.0.3", "11.0.2"));
Assert.assertEquals(1, Versions.compare("11.0.3", "11.0.2-oracle"));
Assert.assertEquals(1, Versions.compare("11.0.3-oracle", "11.0.2"));
Assert.assertEquals(1, Versions.compare("11.0.3-oracle", "11.0.2-oracle"));
Assert.assertEquals(1, Versions.compare("11.0.10", "11.0.9"));
Assert.assertEquals(1, Versions.compare("11.0.10", "11.0.9-oracle"));
Assert.assertEquals(1, Versions.compare("11.0.10-oracle", "11.0.9"));
Assert.assertEquals(1, Versions.compare("11.0.10-oracle", "11.0.9-oracle"));
Assert.assertEquals(-1, Versions.compare("8u212", "8u222"));
Assert.assertEquals(-1, Versions.compare("8u212", "openjdk8u222"));
Assert.assertEquals(-1, Versions.compare("openjdk8u212", "8u222"));
Assert.assertEquals(-1, Versions.compare("openjdk8u212", "openjdk8u222"));
Assert.assertEquals(0, Versions.compare("8u212", "8u212"));
Assert.assertEquals(0, Versions.compare("8u211", "8u212"));
Assert.assertEquals(0, Versions.compare("8u212", "8u211"));
Assert.assertEquals(0, Versions.compare("8u212", "openjdk8u212"));
Assert.assertEquals(0, Versions.compare("8u211", "openjdk8u212"));
Assert.assertEquals(0, Versions.compare("openjdk8u212", "8u212"));
Assert.assertEquals(0, Versions.compare("openjdk8u212", "8u211"));
Assert.assertEquals(1, Versions.compare("8u222", "8u212"));
Assert.assertEquals(1, Versions.compare("8u222", "openjdk8u212"));
Assert.assertEquals(1, Versions.compare("openjdk8u222", "8u212"));
Assert.assertEquals(1, Versions.compare("openjdk8u222", "openjdk8u212"));
}
}
| 9,681 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
StringUtilsTest.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/test/java/org/openjdk/backports/StringUtilsTest.java | package org.openjdk.backports;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class StringUtilsTest {
@Test
public void lines() {
String[] examples = {
"line1\rline2\rline3\r",
"line1\nline2\nline3\n",
"line1\r\nline2\r\nline3\r\n",
};
for (String ex : examples) {
List<String> lines = StringUtils.lines(ex);
Assert.assertEquals(3, lines.size());
Assert.assertEquals("line1", lines.get(0));
Assert.assertEquals("line2", lines.get(1));
Assert.assertEquals("line3", lines.get(2));
}
}
}
| 674 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Options.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/Options.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import java.io.IOException;
public class Options {
private final String[] args;
private String authProps;
private String labelReport;
private String labelHistoryReport;
private String pushesReport;
private String pendingPushReport;
private String releaseNotesReport;
private String affiliationReport;
private String issueReport;
private Long filterReport;
private String logPrefix;
private String hgRepos;
private Actionable minLevel;
private boolean directOnly;
private Integer parityReport;
private boolean includeCarryovers;
private int maxConnections;
public Options(String[] args) {
this.args = args;
}
public boolean parse() throws IOException {
OptionParser parser = new OptionParser();
OptionSpec<String> optAuthProps = parser.accepts("auth",
"Use this property file with user/pass authentication pair.")
.withRequiredArg().ofType(String.class).describedAs("file").defaultsTo("auth.props");
OptionSpec<String> optLabelReport = parser.accepts("label",
"Report the backporting status for a given label.")
.withRequiredArg().ofType(String.class).describedAs("tag");
OptionSpec<String> optLabelHistoryReport = parser.accepts("label-history",
"Report the change history for a given label.")
.withRequiredArg().ofType(String.class).describedAs("tag");
OptionSpec<String> optPushesReport = parser.accepts("pushes",
"Report the backport pushes for a given release.")
.withRequiredArg().ofType(String.class).describedAs("release");
OptionSpec<String> optPendingPushReport = parser.accepts("pending-push",
"Report backports that were approved and are pending for push for a given release.")
.withRequiredArg().ofType(String.class).describedAs("release");
OptionSpec<String> optIssueReport = parser.accepts("issue",
"Report single issue status.")
.withRequiredArg().ofType(String.class).describedAs("bug-id");
OptionSpec<Long> optFilterReport = parser.accepts("filter",
"Report issues matching a given filter.")
.withRequiredArg().ofType(long.class).describedAs("filter-id");
OptionSpec<Integer> optParityReport = parser.accepts("parity",
"Report parity statistics for a given release.")
.withRequiredArg().ofType(Integer.class).describedAs("release-train");
OptionSpec<String> optReleaseNotesReport = parser.accepts("release-notes",
"Report release notes for a given release.")
.withRequiredArg().ofType(String.class).describedAs("release");
OptionSpec<String> optLogPrefix = parser.accepts("output-prefix",
"Use this output file prefix")
.withRequiredArg().ofType(String.class).describedAs("output prefix").defaultsTo("output");
OptionSpec<String> optUpdateHgDB = parser.accepts("hg-repos",
"Use these repositories for Mercurial metadata")
.withRequiredArg().ofType(String.class).describedAs("paths-to-local-hg");
OptionSpec<Actionable> optMinLevel = parser.accepts("min-level",
"Minimal actionable level to print.")
.withRequiredArg().ofType(Actionable.class).describedAs("level").defaultsTo(Actionable.NONE);
OptionSpec<Void> optAffiliationReport = parser.accepts("affiliation",
"Report contributor affiliations.");
OptionSpec<Void> optDirectOnly = parser.accepts("direct-only",
"For push reports, ignore backports and handle direct pushes only.");
OptionSpec<Void> optIncludeCarryovers = parser.accepts("include-carryovers",
"For release reports, include carry-overs from other releases.");
OptionSpec<Integer> optMaxConnections = parser.accepts("max-connections",
"Max connections to have to remote JIRA server.")
.withRequiredArg().ofType(Integer.class).describedAs("#").defaultsTo(20);
parser.accepts("h", "Print this help.");
OptionSet set;
try {
set = parser.parse(args);
} catch (OptionException e) {
System.err.println("ERROR: " + e.getMessage());
System.err.println();
parser.printHelpOn(System.err);
return false;
}
if (!set.hasOptions()) {
System.err.println("ERROR: Please specify what report to generate.");
System.err.println();
parser.printHelpOn(System.err);
return false;
}
if (set.has("h")) {
parser.printHelpOn(System.out);
return false;
}
authProps = optAuthProps.value(set);
labelReport = optLabelReport.value(set);
labelHistoryReport = optLabelHistoryReport.value(set);
pushesReport = optPushesReport.value(set);
pendingPushReport = optPendingPushReport.value(set);
issueReport = optIssueReport.value(set);
filterReport = optFilterReport.value(set);
parityReport = optParityReport.value(set);
releaseNotesReport = optReleaseNotesReport.value(set);
affiliationReport = set.has(optAffiliationReport) ? "yes" : null;
logPrefix = optLogPrefix.value(set);
hgRepos = optUpdateHgDB.value(set);
minLevel = optMinLevel.value(set);
directOnly = set.has(optDirectOnly);
includeCarryovers = set.has(optIncludeCarryovers);
maxConnections = set.valueOf(optMaxConnections);
return true;
}
public String getAuthProps() {
return authProps;
}
public String getLabelReport() {
return labelReport;
}
public String getLabelHistoryReport() {
return labelHistoryReport;
}
public String getPushesReport() {
return pushesReport;
}
public String getPendingPushReport() {
return pendingPushReport;
}
public String getReleaseNotesReport() {
return releaseNotesReport;
}
public String getIssueReport() {
return issueReport;
}
public String getAffiliationReport() {
return affiliationReport;
}
public Long getFilterReport() {
return filterReport;
}
public Integer getParityReport() {
return parityReport;
}
public String getHgRepos() { return hgRepos; }
public Actionable getMinLevel() { return minLevel; }
public boolean directOnly() { return directOnly; }
public boolean includeCarryovers() { return includeCarryovers; }
public String getLogPrefix() {
return logPrefix;
}
public int getMaxConnections() {
return maxConnections;
}
}
| 8,269 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Auth.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/Auth.java | /*
* Copyright (c) 2023, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
public class Auth {
private final String user;
private final String pass;
public Auth(String user, String pass) {
this.user = user;
this.pass = pass;
}
public Auth() {
this.user = null;
this.pass = null;
}
public String getUser() {
return user;
}
public String getPass() {
return pass;
}
public boolean isAnonymous() {
return user == null || pass == null;
}
}
| 1,694 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Actionable.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/Actionable.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
public enum Actionable {
NONE,
WAITING,
REQUESTED,
PUSHABLE,
MISSING,
CRITICAL,
;
public Actionable mix(Actionable a) {
return Actionable.values()[Math.max(ordinal(), a.ordinal())];
}
}
| 1,454 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Actions.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/Actions.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
public class Actions implements Comparable<Actions> {
Actionable actionable;
int importance;
public Actions() {
actionable = Actionable.NONE;
}
public void update(Actionable act) {
update(act, 0);
}
public void update(Actionable act, int impt) {
actionable = actionable.mix(act);
if (act.ordinal() > Actionable.NONE.ordinal()) {
importance += impt;
}
}
@Override
public int compareTo(Actions other) {
int v1 = Integer.compare(other.actionable.ordinal(), actionable.ordinal());
if (v1 != 0) {
return v1;
}
return Integer.compare(other.importance, importance);
}
public Actionable getActionable() {
return actionable;
}
}
| 2,005 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Main.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/Main.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
import org.openjdk.backports.hg.HgDB;
import org.openjdk.backports.jira.Clients;
import org.openjdk.backports.jira.Connect;
import org.openjdk.backports.report.csv.*;
import org.openjdk.backports.report.html.*;
import org.openjdk.backports.report.model.*;
import org.openjdk.backports.report.text.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
public class Main {
public static final String JIRA_URL = "https://bugs.openjdk.org/";
public static void main(String[] args) {
Options options = new Options(args);
try {
if (options.parse()) {
Auth auth = null;
if (new File(options.getAuthProps()).exists()) {
Properties p = new Properties();
try (FileInputStream fis = new FileInputStream(options.getAuthProps())){
p.load(fis);
} catch (IOException e) {
throw new RuntimeException(e);
}
auth = new Auth(p.getProperty("user"), p.getProperty("pass"));
} else {
auth = new Auth(
System.getenv().getOrDefault("OPENJDK_USER", null),
System.getenv().getOrDefault("OPENJDK_PASSWORD", null)
);
}
try (Clients cli = Connect.getClients(JIRA_URL, auth, options.getMaxConnections())) {
PrintStream debugLog = System.out;
String logPrefix = options.getLogPrefix();
HgDB hgDB = new HgDB();
if (options.getHgRepos() != null) {
hgDB.load(options.getHgRepos());
}
debugLog.print("Authentication: ");
if (auth.isAnonymous()) {
debugLog.println("anonymous");
} else {
debugLog.println("as " + auth.getUser());
}
debugLog.println();
if (options.getLabelReport() != null) {
LabelModel m = new LabelModel(cli, hgDB, debugLog, options.getMinLevel(), options.getLabelReport());
new LabelTextReport(m, debugLog, logPrefix).generate();
new LabelCSVReport (m, debugLog, logPrefix).generate();
new LabelHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getLabelHistoryReport() != null) {
LabelHistoryModel m = new LabelHistoryModel(cli, debugLog, options.getLabelHistoryReport());
new LabelHistoryTextReport(m, debugLog, logPrefix).generate();
new LabelHistoryCSVReport (m, debugLog, logPrefix).generate();
new LabelHistoryHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getPendingPushReport() != null) {
PendingPushModel m = new PendingPushModel(cli, hgDB, debugLog, options.getPendingPushReport());
new PendingPushTextReport(m, debugLog, logPrefix).generate();
new PendingPushCSVReport (m, debugLog, logPrefix).generate();
new PendingPushHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getIssueReport() != null) {
IssueModel m = new IssueModel(cli, hgDB, debugLog, options.getIssueReport());
new IssueTextReport(m, debugLog, logPrefix).generate();
new IssueCSVReport (m, debugLog, logPrefix).generate();
new IssueHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getPushesReport() != null) {
PushesModel m = new PushesModel(cli, debugLog, options.directOnly(), options.getPushesReport());
new PushesTextReport(m, debugLog, logPrefix).generate();
new PushesCSVReport (m, debugLog, logPrefix).generate();
new PushesHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getReleaseNotesReport() != null) {
ReleaseNotesModel m = new ReleaseNotesModel(cli, debugLog, options.includeCarryovers(), options.getReleaseNotesReport());
new ReleaseNotesTextReport(m, debugLog, logPrefix).generate();
// No CSV report for this, it is not supposed to be machine-readable
new ReleaseNotesHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getFilterReport() != null) {
FilterModel m = new FilterModel(cli, debugLog, options.getFilterReport());
new FilterTextReport(m, debugLog, logPrefix).generate();
new FilterCSVReport (m, debugLog, logPrefix).generate();
new FilterHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getAffiliationReport() != null) {
AffiliationModel m = new AffiliationModel(cli, debugLog);
new AffiliationTextReport(m, debugLog, logPrefix).generate();
new AffiliationCSVReport (m, debugLog, logPrefix).generate();
new AffiliationHTMLReport(m, debugLog, logPrefix).generate();
}
if (options.getParityReport() != null) {
ParityModel m = new ParityModel(cli, debugLog, options.getParityReport());
new ParityTextReport(m, debugLog, logPrefix).generate();
new ParityCSVReport (m, debugLog, logPrefix).generate();
new ParityHTMLReport(m, debugLog, logPrefix).generate();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 7,514 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
StringUtils.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/StringUtils.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports;
import org.apache.commons.lang3.text.WordUtils;
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.List;
import java.util.stream.Collectors;
public class StringUtils {
public static final int DEFAULT_WIDTH = 100;
public static String rewrap(String str, int width) {
return rewrap(str, width, Integer.MAX_VALUE);
}
public static String rewrap(String str, int width, int maxParagraphs) {
StringBuilder sb = new StringBuilder();
int pCount = 0;
for (String paragraph : paragraphs(str)) {
if (pCount >= maxParagraphs) break;
if (pCount != 0) {
sb.append(System.lineSeparator());
sb.append(System.lineSeparator());
}
paragraph = paragraph.replaceAll("\n", " ");
sb.append(WordUtils.wrap(paragraph, width));
pCount++;
}
return sb.toString();
}
public static String[] paragraphs(String str) {
return str.replaceAll("\r", "").split("\n\n");
}
public static String leftPad(String str, int pad) {
StringBuilder sb = new StringBuilder();
for (int c = 0; c < pad; c++) {
sb.append(" ");
}
String sPad = sb.toString();
return sPad + str.replaceAll("\n", "\n" + sPad);
}
public static String stripNull(String v) {
return (v != null) ? v : "";
}
public static String tabLine(char v) {
return tabLine(v, DEFAULT_WIDTH);
}
public static String tabLine(char v, int width) {
StringBuilder sb = new StringBuilder();
for (int c = 0; c < width; c++) {
sb.append(v);
}
return sb.toString();
}
public static String csvEscape(String s) {
return "\"" + s.replaceAll("\\\"", "'") + "\"";
}
public static String cutoff(String s, int limit) {
if (s == null) {
return s;
}
return s.substring(0, Math.min(s.length(), limit));
}
public static List<String> lines(String s) {
BufferedReader br = new BufferedReader(new StringReader(s));
return br.lines().collect(Collectors.toList());
}
}
| 3,435 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
HgDB.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/hg/HgDB.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.hg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class HgDB {
private final Set<HgRecord> records;
public HgDB() {
this.records = Collections.newSetFromMap(new ConcurrentHashMap<>());
}
public void load(String hgRepos) {
PrintStream pw = System.out;
if (hgRepos == null || hgRepos.isEmpty()) {
return;
}
Arrays.stream(hgRepos.split(",")).parallel().forEach(r -> loadRepo(pw, r));
pw.println("HG DB has " + records.size() + " records.");
pw.println();
}
private void loadRepo(PrintStream pw, String repoPath) {
String repo = "N/A";
try {
List<String> lines = exec("hg", "paths", "-R", repoPath);
for (String line : lines) {
if (line.startsWith("default = ")) {
String[] split = line.split(" = ");
repo = split[1];
}
}
} catch (Exception e) {
pw.println("Cannot figure out repo url for " + repoPath);
return;
}
try {
List<String> lines = exec("hg", "log", "-M", "-R", repoPath, "-T",
"{node|short}BACKPORT-SEPARATOR{desc|addbreaks|splitlines}BACKPORT-SEPARATOR{author}\n");
for (String line : lines) {
String[] split = line.split("BACKPORT-SEPARATOR");
records.add(new HgRecord(repo, split[0], split[1], split[2]));
}
pw.println("Loaded " + lines.size() + " changesets from " + repoPath);
} catch (Exception e) {
pw.println("Cannot get changeset log for " + repoPath);
return;
}
}
private List<String> exec(String... command) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder().command(command);
Process p = pb.start();
List<String> result = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
result.add(line);
}
p.waitFor();
return result;
}
public boolean hasRepo(String repo) {
for (HgRecord record : records) {
if (record.repo.contains(repo)) {
return true;
}
}
return false;
}
public List<HgRecord> search(String repo, String synopsis) {
List<HgRecord> result = new ArrayList<>();
for (HgRecord record : records) {
if (record.repo.contains(repo) && record.synopsisStartsWith(synopsis)) {
result.add(record);
}
}
return result;
}
}
| 4,112 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
HgRecord.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/hg/HgRecord.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.hg;
public class HgRecord {
final String repo;
final String hash;
final String[] synopsis;
final String author;
HgRecord(String repo, String hash, String synopsis, String author) {
this.repo = repo;
this.hash = hash;
this.synopsis = synopsis.split("<br/> ");
this.author = author;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HgRecord record = (HgRecord) o;
if (!repo.equals(record.repo)) return false;
return hash.equals(record.hash);
}
@Override
public int hashCode() {
int result = repo.hashCode();
result = 31 * result + hash.hashCode();
return result;
}
@Override
public String toString() {
return repo + "/rev/" + hash;
}
public boolean synopsisStartsWith(String needle) {
for (String syn : synopsis) {
if (syn.startsWith(needle)) return true;
}
return false;
}
}
| 2,295 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
BackportStatus.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/BackportStatus.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report;
public enum BackportStatus {
NOT_AFFECTED,
INHERITED,
FIXED,
BAKING,
MISSING,
MISSING_ORACLE,
APPROVED,
REJECTED,
REQUESTED,
WARNING,
;
}
| 1,414 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Common.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/Common.java | /*
* Copyright (c) 2018, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report;
import com.atlassian.jira.rest.client.api.domain.Issue;
import java.util.Comparator;
public class Common {
// JDK versions we care for in backports
protected static final int[] VERSIONS_TO_CARE_FOR = {8, 11, 17};
protected static final int[] VERSIONS_TO_CARE_FOR_REV = {17, 11, 8};
// Issue bake time before backport is considered
protected static final int ISSUE_BAKE_TIME_DAYS = 10;
// Backport importances
protected static int importanceMerge() {
return 5;
}
protected static int importanceDefault(int release) {
switch (release) {
case 7:
case 8:
case 11:
case 17:
return 10;
case 13:
case 15:
return 1;
default:
return 1;
}
}
protected static int importanceCritical(int release) {
switch (release) {
case 7:
case 8:
case 11:
case 17:
return 50;
case 13:
case 15:
return 20;
default:
return 15;
}
}
protected static int importanceOracle(int release) {
switch (release) {
case 7:
case 8:
case 11:
case 17:
return 30;
case 13:
case 15:
return 10;
default:
return 5;
}
}
// Sort issues by synopsis, alphabetically. This would cluster similar issues
// together, even when they are separated by large difference in IDs.
protected static final Comparator<Issue> DEFAULT_ISSUE_SORT = Comparator.comparing(i -> i.getSummary().trim().toLowerCase());
protected static String statusToText(BackportStatus status) {
switch (status) {
case NOT_AFFECTED:
return "Not affected";
case INHERITED:
return "Inherited";
case FIXED:
return "Fixed";
case BAKING:
return "WAITING for patch to bake a little";
case MISSING:
return "MISSING";
case MISSING_ORACLE:
return "MISSING (+ on Oracle backport list)";
case APPROVED:
return "APPROVED";
case REJECTED:
return "Rejected";
case REQUESTED:
return "Requested";
case WARNING:
return "WARNING";
default:
throw new IllegalStateException("Unknown status: " + status);
}
}
}
| 3,895 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
FilterCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/FilterCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.report.model.FilterModel;
import java.io.PrintStream;
public class FilterCSVReport extends AbstractCSVReport {
private final FilterModel model;
public FilterCSVReport(FilterModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
for (Issue i : model.issues()) {
out.println("\"" + i.getKey() + "\", \"" + i.getSummary() + "\"");
}
}
}
| 1,831 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AbstractCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/AbstractCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import org.openjdk.backports.report.Common;
import java.io.IOException;
import java.io.PrintStream;
abstract class AbstractCSVReport extends Common {
protected final PrintStream debugLog;
protected final String logPrefix;
public AbstractCSVReport(PrintStream debugLog, String logPrefix) {
this.debugLog = debugLog;
this.logPrefix = logPrefix;
}
public final void generate() throws IOException {
String fileName = logPrefix + ".csv";
PrintStream out = new PrintStream(fileName);
debugLog.println("Generating CSV log to " + fileName);
doGenerate(out);
out.close();
}
protected abstract void doGenerate(PrintStream out);
}
| 1,945 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PendingPushCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/PendingPushCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.PendingPushModel;
import java.io.PrintStream;
public class PendingPushCSVReport extends AbstractCSVReport {
private final PendingPushModel model;
public PendingPushCSVReport(PendingPushModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
for (IssueModel m : model.models()) {
new IssueCSVReport(m, debugLog, logPrefix).generateSimple(out);
}
}
}
| 1,857 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
IssueCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/IssueCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.report.BackportStatus;
import org.openjdk.backports.report.model.IssueModel;
import java.io.PrintStream;
import java.util.List;
public class IssueCSVReport extends AbstractCSVReport {
private final IssueModel model;
public IssueCSVReport(IssueModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
protected void doGenerate(PrintStream out) {
generateSimple(out);
}
protected void generateSimple(PrintStream out) {
Issue issue = model.issue();
out.print("\"" + issue.getKey() + "\", ");
out.print("\"" + issue.getSummary() + "\", ");
for (int release : IssueModel.VERSIONS_TO_CARE_FOR) {
List<Issue> issues = model.existingPorts().get(release);
if (issues != null) {
out.print("\"Fixed\", ");
} else {
BackportStatus status = model.pendingPorts().get(release);
out.print("\"" + status + "\", ");
}
}
out.println();
}
}
| 2,391 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PushesCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/PushesCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.PushesModel;
import java.io.PrintStream;
public class PushesCSVReport extends AbstractCSVReport {
private final PushesModel model;
public PushesCSVReport(PushesModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
protected void doGenerate(PrintStream out) {
UserCache users = model.users();
for (Issue i : model.byTime()) {
String pushUser = Accessors.getPushUser(i);
out.printf("\"%s\", \"%s\", \"%s\", \"%s\"%n",
i.getKey(),
i.getSummary(),
users.getDisplayName(pushUser),
users.getAffiliation(pushUser));
}
for (Issue i : model.noChangesets()) {
out.printf("\"%s\", \"%s\", \"N/A\", \"N/A\"%n",
i.getKey(),
i.getSummary());
}
}
}
| 2,346 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ParityCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/ParityCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.report.model.ParityModel;
import java.io.PrintStream;
import java.util.Map;
public class ParityCSVReport extends AbstractCSVReport {
private final ParityModel model;
public ParityCSVReport(ParityModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
Map<String, Map<Issue, ParityModel.SingleVersMetadata>> map = model.onlyOracle();
for (String rel : map.keySet()) {
Map<Issue, ParityModel.SingleVersMetadata> m = map.get(rel);
for (Issue k : m.keySet()) {
out.printf("\"%s\", \"%s\", \"%s\"%n",
k.getKey(),
k.getSummary(),
m.get(k));
}
}
}
}
| 2,161 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/LabelCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.LabelModel;
import java.io.PrintStream;
public class LabelCSVReport extends AbstractCSVReport {
private final LabelModel model;
public LabelCSVReport(LabelModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
for (IssueModel im : model.issues()) {
new IssueCSVReport(im, debugLog, logPrefix).generateSimple(out);
}
}
}
| 1,829 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AffiliationCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/AffiliationCSVReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.AffiliationModel;
import java.io.PrintStream;
import java.util.List;
public class AffiliationCSVReport extends AbstractCSVReport {
private final AffiliationModel model;
public AffiliationCSVReport(AffiliationModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
public void doGenerate(PrintStream out) {
List<String> userIds = model.userIds();
UserCache users = model.users();
for (String uid : userIds) {
out.printf("\"%s\", \"%s\", \"%s\"%n",
uid,
users.getDisplayName(uid),
users.getAffiliation(uid));
}
}
}
| 2,043 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelHistoryCSVReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/csv/LabelHistoryCSVReport.java | /*
* Copyright (c) 2020, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.csv;
import org.openjdk.backports.report.model.LabelHistoryModel;
import java.io.PrintStream;
public class LabelHistoryCSVReport extends AbstractCSVReport {
private final LabelHistoryModel model;
public LabelHistoryCSVReport(LabelHistoryModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
for (LabelHistoryModel.Record r : model.records()) {
out.printf("\"%s\", \"%s\", \"%s\", \"%s\"%n",
r.date.toLocalDate().toString(),
r.user,
r.issue.getKey(),
r.issue.getSummary());
}
}
}
| 1,969 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PendingPushHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/PendingPushHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import org.openjdk.backports.jira.Versions;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.PendingPushModel;
import java.io.PrintStream;
import java.util.Date;
public class PendingPushHTMLReport extends AbstractHTMLReport {
private final PendingPushModel model;
public PendingPushHTMLReport(PendingPushModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("<h1>PENDING PUSH REPORT: " + model.release() + "</h2>");
out.println();
out.println("<p>This report shows backports that were approved, but not yet pushed.");
out.println("Some of them are true orphans with original backport requesters never got sponsored.</p>");
out.println();
out.println("<p>Report generated: " + new Date() + "</p>");
out.println();
int v = Versions.parseMajor(model.release());
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap></th>");
out.println("<th nowrap>JDK " + v + "</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (IssueModel m : model.models()) {
new IssueHTMLReport(m, debugLog, logPrefix).generateTableLine(out, v, v);
}
out.println("</table>");
}
}
| 2,743 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
IssueHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/IssueHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.Main;
import org.openjdk.backports.StringUtils;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.report.BackportStatus;
import org.openjdk.backports.report.model.IssueModel;
import java.io.PrintStream;
import java.util.*;
public class IssueHTMLReport extends AbstractHTMLReport {
private final IssueModel model;
private final Issue issue;
public IssueHTMLReport(IssueModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
this.issue = model.issue();
}
@Override
public void doGenerate(PrintStream out) {
out.println("<h1>ISSUE REPORT: " + issue.getKey() + "</h1>");
out.println("This report shows a single issue status.");
out.println();
out.println("Report generated: " + new Date());
out.println();
generateSimple(out);
}
public void generateTableLine(PrintStream out, int minV, int maxV) {
out.println("<tr>");
SortedMap<Integer, BackportStatus> shBackports = model.shenandoahPorts();
out.println("<td>");
if (!shBackports.isEmpty()) {
for (Map.Entry<Integer, BackportStatus> e : shBackports.entrySet()) {
out.println(shortStatusHTMLLine(e.getKey(), e.getValue(), model.shenandoahPortsDetails().get(e.getKey())));
}
}
out.println("</td>");
for (int release = minV; release <= maxV; release++) {
List<Issue> issues = model.existingPorts().get(release);
out.println("<td>");
if (issues != null) {
if (release == model.fixVersion()) {
out.println("<span title=\"JDK " + release + ": Fixed in this release\">");
out.println("<font color=black>\u2749</font>");
out.println("</span>");
} else {
out.println("<span title=\"JDK " + release + ": Ported to this release\">");
out.println("<font color=green>\u2714</font>");
out.println("</span>");
}
} else {
BackportStatus status = model.pendingPorts().get(release);
String details = model.pendingPortsDetails().get(release);
out.println(shortStatusHTMLLine(release, status, details));
}
out.println("</td>");
}
out.println("<td nowrap>" + issueLink(issue) + "</td>");
out.println("<td nowrap>" + issue.getSummary() + "</td>");
out.println("</tr>");
}
public void generateSimple(PrintStream out) {
out.println("<td nowrap>" + issueLink(issue) + "</td>");
out.println("<td nowrap>" + issue.getSummary() + "</td>");
out.println("<td nowrap>" + (issue.getReporter() != null ? issue.getReporter().getDisplayName() : "None") + "</td>");
out.println("<td nowrap>" + (issue.getAssignee() != null ? issue.getAssignee().getDisplayName() : "None") + "</td>");
out.println("<td nowrap>" + issue.getPriority().getName() + "</td>");
out.println("<td nowrap>" + model.components() + "</td>");
out.println(" Backports and Forwardports:");
for (int release : IssueModel.VERSIONS_TO_CARE_FOR) {
if (release == model.fixVersion()) continue;
List<Issue> issues = model.existingPorts().get(release);
if (issues != null) {
for (Issue i : issues) {
out.printf(" %2d: %s%n", release, shortIssueLine(i));
}
} else {
BackportStatus status = model.pendingPorts().get(release);
String details = model.pendingPortsDetails().get(release);
out.printf(" %2d: %s%s%n", release, (details.isEmpty() ? "" : ": " + details), status);
}
}
out.println();
SortedMap<Integer, BackportStatus> shBackports = model.shenandoahPorts();
if (!shBackports.isEmpty()) {
out.println(" Shenandoah Backports:");
for (Map.Entry<Integer, BackportStatus> e : shBackports.entrySet()) {
String details = model.pendingPortsDetails().get(e.getKey());
out.printf(" %2d: %s%s%n", e.getKey(), e.getValue(), (details.isEmpty() ? "" : ": " + details));
}
out.println();
}
Collection<Issue> relNotes = model.releaseNotes();
if (!relNotes.isEmpty()) {
out.println();
out.println(" Release Notes:");
out.println();
printReleaseNotes(out, relNotes);
}
List<String> warns = model.warnings();
if (!warns.isEmpty()) {
out.println(" WARNINGS:");
for (String m : warns) {
out.println(" " + m);
}
out.println();
}
}
private static String shortIssueLine(Issue issue) {
return String.format("%s, %10s, %s, %s",
Accessors.getFixVersion(issue),
issue.getKey(),
Accessors.getPushURL(issue),
Accessors.getPushDaysAgo(issue) + " day(s) ago");
}
private static String shortStatusHTMLLine(int release, BackportStatus status, String details) {
StringBuilder sb = new StringBuilder();
if (status == null) {
sb.append("<font color=white>\u2716</font>");
} else {
sb.append("<span title=\"JDK ")
.append(release)
.append(": ")
.append(statusToText(status))
.append((details == null || details.isEmpty()) ? "" : ": " + details)
.append("\">");
switch (status) {
case BAKING:
sb.append("\u2668");
break;
case INHERITED:
sb.append("<font color=white>\u2714</font>");
break;
case FIXED:
sb.append("<font color=green>\u2714</font>");
break;
case MISSING:
case MISSING_ORACLE:
case REJECTED:
sb.append("<font color=red>\u2716</font>");
break;
case NOT_AFFECTED:
sb.append("<font color=white>\u2716</font>");
break;
case REQUESTED:
sb.append("\u270B");
break;
case APPROVED:
sb.append("\u270A");
break;
case WARNING:
sb.append("<b><font color=red>\u26A0</font></b>");
break;
default:
throw new IllegalStateException("Unhandled status: " + status);
}
sb.append("</span>");
}
return sb.toString();
}
protected static void printReleaseNotes(PrintStream out, Collection<Issue> relNotes) {
Set<String> dup = new HashSet<>();
for (Issue rn : relNotes) {
String summary = StringUtils.leftPad(rn.getKey() + ": " + rn.getSummary().replaceFirst("Release Note: ", ""), 2);
String descr = StringUtils.leftPad(StringUtils.rewrap(StringUtils.stripNull(rn.getDescription()), StringUtils.DEFAULT_WIDTH - 6), 6);
if (dup.add(descr)) {
out.println(summary);
out.println();
out.println(descr);
out.println();
}
}
}
}
| 8,963 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ReleaseNotesHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/ReleaseNotesHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.github.rjeschke.txtmark.Processor;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openjdk.backports.report.model.ReleaseNotesModel;
import java.io.PrintStream;
import java.util.*;
public class ReleaseNotesHTMLReport extends AbstractHTMLReport {
private final ReleaseNotesModel model;
public ReleaseNotesHTMLReport(ReleaseNotesModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("<h1>RELEASE NOTES: JDK " + model.release() + "</h1>");
out.println("<p>Notes generated: " + new Date() + "<p>");
out.println("<h2>JEPs</h2>");
List<Issue> jeps = model.jeps();
if (jeps.isEmpty()) {
out.println("<p>None.</p>");
} else {
out.println("<table>");
out.println("<tr>");
out.println("<th>Issue</th>");
out.println("<th>Description</th>");
out.println("</tr>");
for (Issue i : jeps) {
out.println("<tr>");
out.println("<td class='multicell'>" + issueLink(i) + "</td>");
out.println("<td><b>" + i.getSummary() + "</b></td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td></td>");
out.println("<td class='embedded-block'>");
String desc = i.getDescription();
if (desc != null && !desc.isEmpty()) {
Document doc = Jsoup.parse(Processor.process(desc));
Element p = doc.body().selectFirst("p");
if (p != null) {
out.println(p.text());
} else {
out.println("Error selecting the description");
}
out.println("<br>");
} else {
out.println("<p>No description.</p>");
}
out.println("</td>");
out.println("</tr>");
}
out.println("</table>");
}
out.println("<h2>RELEASE NOTES</h2>");
Map<String, Multimap<Issue, Issue>> rns = model.relNotes();
boolean haveRelNotes = false;
for (String component : rns.keySet()) {
boolean printed = false;
Multimap<Issue, Issue> m = rns.get(component);
for (Issue i : m.keySet()) {
haveRelNotes = true;
if (!printed) {
out.println("<h3>" + component + "</h3>");
out.println("<table>");
out.println("<tr>");
out.println("<th>Issue</th>");
out.println("<th>Description</th>");
out.println("</tr>");
printed = true;
}
Set<String> dup = new HashSet<>();
boolean firstPrint = true;
for (Issue rn : m.get(i)) {
out.println("<tr>");
if (firstPrint) {
out.println("<td class='multicell' rowspan='" + m.get(i).size() + "'>" + issueLink(i) + "</td>");
firstPrint = false;
}
out.println("<td class='embedded-block'>");
String descr = rn.getDescription();
String summary = rn.getSummary().replaceFirst("Release Note: ", "");
if (dup.add(descr)) {
out.println("<p><b>" + summary + "</b></p>");
out.println("<br>");
out.println(Processor.process(descr));
out.println("<br>");
}
out.println("</td>");
out.println("</tr>");
}
}
if (printed) {
out.println("</table>");
}
}
if (!haveRelNotes) {
out.println("<p>None.</p>");
}
out.println();
out.println("<h2>FIXED ISSUES</h2>");
out.println();
Multimap<String, Issue> byComponent = model.byComponent();
for (String component : byComponent.keySet()) {
out.println("<h3>" + component + "</h3>");
Multimap<String, Issue> byPriority = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
for (Issue i : byComponent.get(component)) {
byPriority.put(i.getPriority().getName(), i);
}
out.println("<table>");
out.println("<tr>");
out.println("<th>Priority</th>");
out.println("<th>Bug</th>");
out.println("<th width='99%'>Summary</th>");
out.println("</tr>");
for (String prio : byPriority.keySet()) {
for (Issue i : byPriority.get(prio)) {
out.println("<tr>");
out.println("<td>" + prio + "</td>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
}
out.println("</table>");
}
out.println();
if (model.includeCarryovers()) {
out.println("<h2>CARRIED OVER FROM PREVIOUS RELEASES</h2>");
out.println("<p>These have fixes for the given release, but they are also fixed in the previous");
out.println("minor version of the same major release.</p>");
out.println();
SortedSet<Issue> carriedOver = model.carriedOver();
if (carriedOver.isEmpty()) {
out.println("<p>None.</p>");
}
out.println("<table>");
out.println("<tr>");
out.println("<th>Priority</th>");
out.println("<th>Bug</th>");
out.println("<th width='99%'>Summary</th>");
out.println("</tr>");
for (Issue i : carriedOver) {
out.println("<tr>");
out.println("<td>" + i.getPriority().getName() + "</td>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
}
| 7,938 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AffiliationHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/AffiliationHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.AffiliationModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.List;
public class AffiliationHTMLReport extends AbstractHTMLReport {
private final AffiliationModel model;
public AffiliationHTMLReport(AffiliationModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
public void doGenerate(PrintStream out) {
out.println("<h1>AFFILIATION REPORT</h1>");
out.println("<p>Report generated: " + new Date() + "</p>");
List<String> userIds = model.userIds();
UserCache users = model.users();
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>ID</th>");
out.println("<th nowrap>Name</th>");
out.println("<th nowrap>Organization</th>");
out.println("</tr>");
for (String uid : userIds) {
out.println("<tr>");
out.println("<td nowrap><a href='https://openjdk.org/census#" + uid + "'>" + uid + "</a></td>");
out.println("<td nowrap>" + users.getDisplayName(uid) + "</td>");
out.println("<td nowrap>" + users.getAffiliation(uid) + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
| 2,617 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
FilterHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/FilterHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.Multimap;
import org.openjdk.backports.report.model.FilterModel;
import java.io.PrintStream;
import java.util.Date;
public class FilterHTMLReport extends AbstractHTMLReport {
private final FilterModel model;
public FilterHTMLReport(FilterModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
public void doGenerate(PrintStream out) {
out.println("<h1>FILTER REPORT: " + model.name() + "</h1>");
out.println("<p>Report generated: " + new Date() + "</p>");
Multimap<String, Issue> byComponent = model.byComponent();
for (String component : byComponent.keySet()) {
out.println("<h2>" + component + "</h2>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (Issue i : byComponent.get(component)) {
out.println("<tr>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
}
| 2,625 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PushesHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/PushesHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.*;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.PushesModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class PushesHTMLReport extends AbstractHTMLReport {
private final PushesModel model;
public PushesHTMLReport(PushesModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
protected void doGenerate(PrintStream out) {
out.println("<h1>PUSHES REPORT: " + model.release() + "</h1>");
out.println("<p>");
if (model.directOnly()) {
out.println("This report shows who pushed the changesets to the given release.");
out.println("This usually shows who did the development work, not sponsors/reviewers.");
} else {
out.println("This report shows who pushed the backports to the given release.");
out.println("This usually shows who did the backporting, testing, and review work.");
}
out.println("</p>");
out.println("<p>Report generated: " + new Date() + "</p>");
UserCache users = model.users();
Multiset<String> byPriority = model.byPriority();
Multiset<String> byComponent = model.byComponent();
out.println("<h2>Distribution by priority</h2>");
out.println("<table>");
out.println("<tr>");
out.println("<th>Count</th>");
out.println("<th>Priority</th>");
out.println("</tr>");
for (String prio : byPriority.elementSet()) {
out.println("<tr>");
out.println("<td>" + byPriority.count(prio) + "</td>");
out.println("<td>" + prio + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<h2>Distribution by components</h2>");
out.println("<table>");
out.println("<tr>");
out.println("<th colspan=2>Count</th>");
out.println("<th colspan=3>Component</th>");
out.println("</tr>");
{
Multiset<String> firsts = TreeMultiset.create();
Map<String, Multiset<String>> seconds = new HashMap<>();
for (String component : byComponent.elementSet()) {
String first = component.split("/")[0];
Multiset<String> bu = seconds.computeIfAbsent(first, k -> HashMultiset.create());
bu.add(component, byComponent.count(component));
firsts.add(first, byComponent.count(component));
}
int total = byComponent.size();
out.println("<tr>");
out.println("<td align=right><b>" + total + "</b></td>");
out.println("<td align=right><b>100%</b></td>");
out.println("<td colspan=3><b>Total</b></td>");
out.println("</tr>");
for (String first : Multisets.copyHighestCountFirst(firsts).elementSet()) {
String percFirst = String.format("%.1f%%", 100.0 * firsts.count(first) / total);
out.println("<tr>");
out.println("<td align=right><b>" + firsts.count(first) + "</b></td>");
out.println("<td align=right><b>" + percFirst + "</b></td>");
out.println("<td colspan=3><b>" + first + "</b></td>");
out.println("</tr>");
Multiset<String> ms = seconds.get(first);
for (String component : Multisets.copyHighestCountFirst(ms).elementSet()) {
String percComponent = String.format("%.1f%%", 100.0 * ms.count(component) / total);
out.println("<tr>");
out.println("<td colspan=2></td>");
out.println("<td align=right>" + ms.count(component) + "</td>");
out.println("<td align=right>" + percComponent + "</td>");
out.println("<td>" + component + "</td>");
out.println("</tr>");
}
}
}
out.println("</table>");
out.println("<table cellpadding=10>");
out.println("<tr>");
out.println("<td colspan=2>");
out.println("<h2>Distribution by affiliation</h2>");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>");
out.println("<h3>This Release Pushes</h3>");
out.println("</td>");
out.println("<td>");
out.println("<h3>Original Pushes</h3>");
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td style='vertical-align: text-top'>");
printAffiliation(out, users, model.byCommitter());
out.println("</td>");
out.println("<td style='vertical-align: text-top'>");
printAffiliation(out, users, model.byOriginalCommitter());
out.println("</td>");
out.println("</tr>");
out.println("<table>");
out.println("<h2>Chronological push log:</h2>");
out.println();
out.println("<table>");
out.println("<tr>");
out.println("<th>Days Ago</th>");
out.println("<th colspan=2>This Release Push By</th>");
out.println("<th colspan=2>Original Push By</th>");
out.println("<th>Bug</th>");
out.println("<th width='99%'>Summary</th>");
out.println("</tr>");
out.println("<tr>");
out.println("<th></th>");
out.println("<th>Name</th>");
out.println("<th>Affiliation</th>");
out.println("<th>Name</th>");
out.println("<th>Affiliation</th>");
out.println("<th></th>");
out.println("<th width='99%'></th>");
out.println("</tr>");
for (Issue i : model.byTime()) {
String backportUser = Accessors.getPushUser(i);
String originalUser = Accessors.getPushUser(model.issueToParent().get(i));
out.println("<tr>");
out.println("<td>" + TimeUnit.SECONDS.toDays(Accessors.getPushSecondsAgo(i)) + "</td>");
out.println("<td>" + users.getDisplayName(backportUser) + "</td>");
out.println("<td>" + users.getAffiliation(backportUser) + "</td>");
out.println("<td>" + users.getDisplayName(originalUser) + "</td>");
out.println("<td>" + users.getAffiliation(originalUser) + "</td>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<h2>No changesets log</h2>");
out.println("<table>");
for (Issue i : model.noChangesets()) {
out.println("<tr>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<h2>Committer push log</h2>");
out.println();
{
Multimap<String, Issue> byCommitter = model.byCommitter();
for (String committer : byCommitter.keySet()) {
out.println("<h3>" + users.getDisplayName(committer) + ", " + users.getAffiliation(committer) + "</h3>");
out.println("<table>");
out.println("<tr>");
out.println("<th>Bug</th>");
out.println("<th width='99%'>Summary</th>");
out.println("</tr>");
for (Issue i : byCommitter.get(committer)) {
out.println("<tr>");
out.println("<td>" + issueLink(i) + "</td>");
out.println("<td>" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
}
private void printAffiliation(PrintStream out, UserCache users, Multimap<String, Issue> byCommitter) {
out.println("<table>");
out.println("<tr>");
out.println("<th colspan=2>Count</th>");
out.println("<th colspan=3>Committer</th>");
out.println("</tr>");
{
Multiset<String> byAffiliation = TreeMultiset.create();
Map<String, Multiset<String>> byAffiliationAndCommitter = new HashMap<>();
for (String committer : byCommitter.keySet()) {
String aff = users.getAffiliation(committer);
byAffiliation.add(aff, byCommitter.get(committer).size());
Multiset<String> bu = byAffiliationAndCommitter.computeIfAbsent(aff, k -> HashMultiset.create());
bu.add(users.getDisplayName(committer), byCommitter.get(committer).size());
}
int total = byCommitter.size();
out.println("<tr>");
out.println("<td align=right><b>" + total + "</b></td>");
out.println("<td align=right><b>100%</b></td>");
out.println("<td colspan=3><b>Total</b></td>");
out.println("</tr>");
for (String aff : Multisets.copyHighestCountFirst(byAffiliation).elementSet()) {
String percAff = String.format("%.1f%%", 100.0 * byAffiliation.count(aff) / total);
out.println("<tr>");
out.println("<td align=right><b>" + byAffiliation.count(aff) + "</b></td>");
out.println("<td align=right><b>" + percAff + "</b></td>");
out.println("<td colspan=3><b>" + aff + "</b></td>");
out.println("</tr>");
Multiset<String> committers = byAffiliationAndCommitter.get(aff);
for (String committer : Multisets.copyHighestCountFirst(committers).elementSet()) {
String percCommitter = String.format("%.1f%%", 100.0 * committers.count(committer) / total);
out.println("<tr>");
out.println("<td colspan=2></td>");
out.println("<td align=right>" + committers.count(committer) + "</td>");
out.println("<td align=right>" + percCommitter + "</td>");
out.println("<td>" + committer + "</td>");
out.println("</tr>");
}
}
}
out.println("</table>");
}
}
| 11,758 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelHistoryHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/LabelHistoryHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import org.openjdk.backports.report.model.LabelHistoryModel;
import java.io.PrintStream;
import java.util.Date;
public class LabelHistoryHTMLReport extends AbstractHTMLReport {
private final LabelHistoryModel model;
public LabelHistoryHTMLReport(LabelHistoryModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
public void doGenerate(PrintStream out) {
out.println("<h1>LABEL HISTORY REPORT: " + model.label() + "</h1>");
out.println("<p>Report generated: " + new Date() + "</p>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Date Added</th>");
out.println("<th nowrap>Added By</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (LabelHistoryModel.Record r : model.records()) {
out.println("<tr>");
out.println("<td>" + r.date.toLocalDate().toString() + "</td>");
out.println("<td>" + r.user + "</td>");
out.println("<td>" + issueLink(r.issue) + "</td>");
out.println("<td>" + r.issue.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
| 2,573 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ParityHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/ParityHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.report.model.ParityModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.Map;
public class ParityHTMLReport extends AbstractHTMLReport {
private final ParityModel model;
public ParityHTMLReport(ParityModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("<h1>PARITY REPORT: JDK " + model.majorVer() + "</h1>");
out.println();
out.println("<p>This report shows the bird-eye view of parity between OpenJDK and Oracle JDK.</p>");
out.println();
out.println("<p>Report generated: " + new Date() + "</p>");
out.println();
out.println("<h2> EXCLUSIVE: ONLY IN ORACLE JDK</h2>");
out.println();
out.println("<p>This is where Oracle JDK is ahead of OpenJDK.</p>");
out.println("<p>No relevant backports are detected in OpenJDK.</p>");
out.println("<p>This misses the future backporting work.</p>");
out.println("<p>[...] marks the interest tags.</p>");
out.println("<p>(*) marks the existing pull request.</p>");
out.println("<p>(*) marks the backporting work in progress.</p>");
out.println();
printWithVersionMeta(out, model.onlyOracle());
out.println();
out.println("<h2>EXCLUSIVE: OPENJDK REJECTED</h2>");
out.println();
out.println("<p>These are the issues that were ruled as either not affecting OpenJDK, or otherwise rejected by maintainers.</p>");
out.println();
printWithVersion(out, model.openRejected());
out.println();
out.println("<h2>EXCLUSIVE: ONLY IN OPENJDK</h2>");
out.println();
out.println("<p>This is where OpenJDK is ahead of Oracle JDK.</p>");
out.println("<p>No relevant backports are detected in Oracle JDK yet.</p>");
out.println("<p>This misses the ongoing backporting work.</p>");
out.println();
printWithVersion(out, model.onlyOpen());
out.println();
out.println("<h2>LATE PARITY: ORACLE JDK FOLLOWS OPENJDK IN LATER RELEASES</h2>");
out.println();
out.println("<p>This is where OpenJDK used to be ahead, and then Oracle JDK caught up in future releases.</p>");
out.println();
printDouble(out, model.lateOpenFirst());
out.println();
out.println("<h2>LATE PARITY: OPENJDK FOLLOWS ORACLE JDK IN LATER RELEASES</h2>");
out.println();
out.println("<p>This is where Oracle JDK used to be ahead, and then OpenJDK caught up in future releases.</p>");
out.println();
printDouble(out, model.lateOracleFirst());
out.println();
out.println("<h2>EXACT PARITY: ORACLE JDK FOLLOWS OPENJDK</h2>");
out.println();
out.println("<p>This is where OpenJDK made the first backport in the release, and then Oracle JDK followed.</p>");
out.println("<p>No difference in the final release detected.</p>");
out.println();
printSingle(out, model.exactOpenFirst());
out.println();
out.println("<h2>EXACT PARITY: OPENJDK FOLLOWS ORACLE JDK</h2>");
out.println();
out.println("<p>This is where Oracle JDK made the first backport in the release, and then OpenJDK followed.</p>");
out.println("<p>No difference in the final release detected.</p>");
out.println();
printSingle(out, model.exactOracleFirst());
out.println();
out.println("<h2>EXACT PARITY: UNKNOWN TIMING</h2>");
out.println();
out.println("<p>This is where the difference in time within the release was not identified reliably.</p>");
out.println("<p>No difference in the final release detected.</p>");
out.println();
printDouble(out, model.exactUnknown());
out.println();
}
void printWithVersion(PrintStream out, Map<String, Map<Issue, ParityModel.SingleVers>> issues) {
int size = 0;
for (Map.Entry<String, Map<Issue, ParityModel.SingleVers>> kv : issues.entrySet()) {
size += kv.getValue().size();
}
out.println("<p>" + size + " issues in total</p>");
for (Map.Entry<String, Map<Issue, ParityModel.SingleVers>> kv : issues.entrySet()) {
out.println("<h3>" + kv.getKey() + "</h3>");
out.println("<p>" + kv.getValue().size() + " issues</p>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Version</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (Map.Entry<Issue, ParityModel.SingleVers> kv2 : kv.getValue().entrySet()) {
Issue i = kv2.getKey();
ParityModel.SingleVers ver = kv2.getValue();
out.println("<tr>");
out.println("<td nowrap>" + ver.version() + "</td>");
out.println("<td nowrap>" + issueLink(i) + "</td>");
out.println("<td nowrap width=\"99%\">" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
void printWithVersionMeta(PrintStream out, Map<String, Map<Issue, ParityModel.SingleVersMetadata>> issues) {
int size = 0;
for (Map.Entry<String, Map<Issue, ParityModel.SingleVersMetadata>> kv : issues.entrySet()) {
size += kv.getValue().size();
}
out.println("<p>" + size + " issues in total</p>");
for (Map.Entry<String, Map<Issue, ParityModel.SingleVersMetadata>> kv : issues.entrySet()) {
out.println("<h3>" + kv.getKey() + "</h3>");
out.println("<p>" + kv.getValue().size() + " issues</p>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Version</th>");
out.println("<th nowrap>Interest</th>");
out.println("<th nowrap>RFR</th>");
out.println("<th nowrap>BP</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (Map.Entry<Issue, ParityModel.SingleVersMetadata> kv2 : kv.getValue().entrySet()) {
Issue i = kv2.getKey();
ParityModel.SingleVersMetadata ver = kv2.getValue();
out.println("<tr>");
out.println("<td nowrap>" + ver.version() + "</td>");
out.println("<td nowrap>" + ver.interestTags() + "</td>");
out.println("<td nowrap>");
for (String link : ver.reviewLinks()) {
out.println("<a href='" + link + "'>RFR</a> ");
}
out.println("</td>");
out.println("<td nowrap>" + (ver.backportRequested() ? "(*)" : "") + "</td>");
out.println("<td nowrap>" + issueLink(i) + "</td>");
out.println("<td nowrap width=\"99%\">" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
void printSingle(PrintStream out, Map<Issue, ParityModel.SingleVers> issues) {
out.println("<p>" + issues.size() + " issues.</p>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Version</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (Map.Entry<Issue,ParityModel.SingleVers> kv : issues.entrySet()) {
Issue i = kv.getKey();
ParityModel.SingleVers dVers = kv.getValue();
out.println("<tr>");
out.println("<td nowrap>" + dVers.version() + "</td>");
out.println("<td nowrap>" + issueLink(i) + "</td>");
out.println("<td nowrap width=\"99%\">" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
void printDouble(PrintStream out, Map<Issue, ParityModel.DoubleVers> issues) {
out.println("<p>" + issues.size() + " issues.</p>");
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap>Version 1</th>");
out.println("<th nowrap>Version 2</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
for (Map.Entry<Issue,ParityModel.DoubleVers> kv : issues.entrySet()) {
Issue i = kv.getKey();
ParityModel.DoubleVers dVers = kv.getValue();
out.println("<tr>");
out.println("<td nowrap>" + dVers.version1() + "</td>");
out.println("<td nowrap>" + dVers.version2() + "</td>");
out.println("<td nowrap>" + issueLink(i) + "</td>");
out.println("<td nowrap width=\"99%\">" + i.getSummary() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
}
| 10,512 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AbstractHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/AbstractHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.Main;
import org.openjdk.backports.report.Common;
import java.io.*;
abstract class AbstractHTMLReport extends Common {
protected final PrintStream debugLog;
protected final String logPrefix;
public AbstractHTMLReport(PrintStream debugLog, String logPrefix) {
this.debugLog = debugLog;
this.logPrefix = logPrefix;
}
public final void generate() throws IOException {
String fileName = logPrefix + ".html";
PrintStream out = new PrintStream(fileName);
debugLog.println("Generating HTML log to " + fileName);
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<style>");
try (InputStream is = AbstractHTMLReport.class.getResourceAsStream("/style.css");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr)) {
String line;
while ((line = br.readLine()) != null) {
out.println(line);
}
}
out.println("</style>");
out.println("<body>");
doGenerate(out);
out.println("</body>");
out.println("</html>");
out.close();
}
protected abstract void doGenerate(PrintStream out);
protected String issueLink(Issue issue) {
return "<a href=\"" + Main.JIRA_URL + "browse/" + issue.getKey() + "\">" + issue.getKey() + "</a>";
}
}
| 2,786 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelHTMLReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/html/LabelHTMLReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.html;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.TreeMultimap;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.LabelModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.TreeSet;
public class LabelHTMLReport extends AbstractHTMLReport {
private final LabelModel model;
public LabelHTMLReport(LabelModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("<h1>LABEL REPORT: " + model.label() + "</h1>");
out.println();
out.println("<p>This report shows bugs with the given label, along with their backporting status.</p>");
out.println();
out.println("<p>Report generated: " + new Date() + "</p>");
out.println();
out.println("<p>Minimal actionable level to display: " + model.minLevel() + "</p>");
out.println();
LinkedListMultimap<String, IssueModel> map = model.byComponent();
for (String comp : new TreeSet<>(map.keySet())) {
out.println("<h3>" + comp + "</h3>");
int minV = model.minVersion();
int maxV = model.maxVersion();
out.println("<table>");
out.println("<tr>");
out.println("<th nowrap colspan=" + (maxV - minV + 2) + ">Fix Versions</th>");
out.println("<th nowrap>Bug</th>");
out.println("<th nowrap width=\"99%\">Synopsis</th>");
out.println("</tr>");
out.println("<tr>");
out.println("<th nowrap>sh/8</th>");
for (int r = minV; r <= maxV; r++) {
out.println("<th nowrap>" + r + "</th>");
}
out.println("<thnowrap></th>");
out.println("<th></th>");
out.println("</tr>");
for (IssueModel im : map.get(comp)) {
new IssueHTMLReport(im, debugLog, logPrefix).generateTableLine(out, minV, maxV);
}
out.println("</table>");
}
}
}
| 3,438 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AbstractTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/AbstractTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import org.openjdk.backports.StringUtils;
import org.openjdk.backports.report.Common;
import java.io.IOException;
import java.io.PrintStream;
abstract class AbstractTextReport extends Common {
protected final PrintStream debugLog;
protected final String logPrefix;
public AbstractTextReport(PrintStream debugLog, String logPrefix) {
this.debugLog = debugLog;
this.logPrefix = logPrefix;
}
public final void generate() throws IOException {
String fileName = logPrefix + ".txt";
PrintStream out = new PrintStream(fileName);
debugLog.println("Generating TXT log to " + fileName);
doGenerate(out);
out.close();
}
protected abstract void doGenerate(PrintStream out);
protected void printMajorDelimiterLine(PrintStream out) {
out.println(StringUtils.tabLine('='));
}
protected void printMinorDelimiterLine(PrintStream out) {
out.println(StringUtils.tabLine('-'));
}
}
| 2,222 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
LabelHistoryTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/LabelHistoryTextReport.java | /*
* Copyright (c) 2020, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import org.openjdk.backports.report.model.LabelHistoryModel;
import java.io.PrintStream;
import java.util.Date;
public class LabelHistoryTextReport extends AbstractTextReport {
private final LabelHistoryModel model;
public LabelHistoryTextReport(LabelHistoryModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("LABEL HISTORY REPORT: " + model.label());
printMajorDelimiterLine(out);
out.println();
out.println("This report shows when the given label was added.");
out.println();
out.println("Report generated: " + new Date());
out.println();
for (LabelHistoryModel.Record r : model.records()) {
out.printf("%10s, %" + model.users().maxDisplayName() + "s, %s: %s%n",
r.date.toLocalDate().toString(),
r.user,
r.issue.getKey(),
r.issue.getSummary());
}
}
}
| 2,321 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
IssueTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/IssueTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.Main;
import org.openjdk.backports.StringUtils;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.report.BackportStatus;
import org.openjdk.backports.report.model.IssueModel;
import java.io.PrintStream;
import java.util.*;
public class IssueTextReport extends AbstractTextReport {
private final IssueModel model;
private final Issue issue;
public IssueTextReport(IssueModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
this.issue = model.issue();
}
@Override
protected void doGenerate(PrintStream out) {
out.println("ISSUE REPORT: " + issue.getKey());
printMajorDelimiterLine(out);
out.println();
out.println("This report shows a single issue status.");
out.println();
out.println("Report generated: " + new Date());
out.println();
generateSimple(out);
}
public void generateSimple(PrintStream out) {
out.println();
out.println(issue.getKey() + ": " + issue.getSummary());
out.println();
out.println(" Original Bug:");
out.println(" URL: " + Main.JIRA_URL + "browse/" + issue.getKey());
out.println(" Reporter: " + (issue.getReporter() != null ? issue.getReporter().getDisplayName() : "None"));
out.println(" Assignee: " + (issue.getAssignee() != null ? issue.getAssignee().getDisplayName() : "None"));
out.println(" Priority: " + issue.getPriority().getName());
out.println(" Components: " + model.components());
out.println();
out.println(" Original Fix:");
out.printf(" %2d: %s%n", model.fixVersion(), shortIssueLine(issue));
out.println();
out.println(" Backports and Forwardports:");
for (int release : IssueModel.VERSIONS_TO_CARE_FOR_REV) {
if (release == model.fixVersion()) continue;
List<Issue> issues = model.existingPorts().get(release);
if (issues != null) {
for (Issue i : issues) {
out.printf(" %2d: %s%n", release, shortIssueLine(i));
}
} else {
BackportStatus status = model.pendingPorts().get(release);
String details = model.pendingPortsDetails().get(release);
out.printf(" %2d: %s%s%n", release, statusToText(status), (details.isEmpty() ? "" : ": " + details));
}
}
out.println();
SortedMap<Integer, BackportStatus> shBackports = model.shenandoahPorts();
if (!shBackports.isEmpty()) {
out.println(" Shenandoah Backports:");
for (Map.Entry<Integer, BackportStatus> e : shBackports.entrySet()) {
String details = model.shenandoahPortsDetails().get(e.getKey());
out.printf(" %2d: %s%s%n", e.getKey(), statusToText(e.getValue()), (details.isEmpty() ? "" : ": " + details));
}
out.println();
}
Collection<Issue> relNotes = model.releaseNotes();
if (!relNotes.isEmpty()) {
out.println(" Release Notes:");
out.println();
printReleaseNotes(out, relNotes);
}
List<String> warns = model.warnings();
if (!warns.isEmpty()) {
out.println(" WARNINGS:");
for (String m : warns) {
out.println(" " + m);
}
out.println();
}
}
private static String shortIssueLine(Issue issue) {
return String.format("%s, %10s, %s, %s",
Accessors.getFixVersion(issue),
issue.getKey(),
Accessors.getPushURL(issue),
Accessors.getPushDaysAgo(issue) + " day(s) ago");
}
protected static void printReleaseNotes(PrintStream out, Collection<Issue> relNotes) {
Set<String> dup = new HashSet<>();
for (Issue rn : relNotes) {
String summary = StringUtils.leftPad(rn.getKey() + ": " + rn.getSummary().replaceFirst("Release Note: ", ""), 2);
String descr = StringUtils.leftPad(StringUtils.rewrap(StringUtils.stripNull(rn.getDescription()), StringUtils.DEFAULT_WIDTH - 6), 6);
if (dup.add(descr)) {
out.println(summary);
out.println();
out.println(descr);
out.println();
}
}
}
}
| 5,793 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PushesTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/PushesTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.*;
import org.openjdk.backports.jira.Accessors;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.PushesModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class PushesTextReport extends AbstractTextReport {
private final PushesModel model;
public PushesTextReport(PushesModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
protected void doGenerate(PrintStream out) {
out.println("PUSHES REPORT: " + model.release());
printMajorDelimiterLine(out);
out.println();
if (model.directOnly()) {
out.println("This report shows who pushed the changesets to the given release.");
out.println("This usually shows who did the development work, not sponsors/reviewers.");
} else {
out.println("This report shows who pushed the backports to the given release.");
out.println("This usually shows who did the backporting, testing, and review work.");
}
out.println();
out.println("Report generated: " + new Date());
out.println();
UserCache users = model.users();
Multiset<String> byPriority = model.byPriority();
Multiset<String> byComponent = model.byComponent();
out.println("Distribution by priority:");
for (String prio : byPriority.elementSet()) {
out.printf(" %3d: %s%n", byPriority.count(prio), prio);
}
out.println();
out.println("Distribution by components:");
{
Multiset<String> firsts = TreeMultiset.create();
Map<String, Multiset<String>> seconds = new HashMap<>();
for (String component : byComponent.elementSet()) {
String first = component.split("/")[0];
Multiset<String> bu = seconds.computeIfAbsent(first, k -> HashMultiset.create());
bu.add(component, byComponent.count(component));
firsts.add(first, byComponent.count(component));
}
int total = byComponent.size();
out.printf(" %3d: <total issues>%n", total);
for (String first : Multisets.copyHighestCountFirst(firsts).elementSet()) {
String percFirst = String.format("(%.1f%%)", 100.0 * firsts.count(first) / total);
out.printf(" %3d %7s: %s%n", firsts.count(first), percFirst, first);
Multiset<String> ms = seconds.get(first);
for (String component : Multisets.copyHighestCountFirst(ms).elementSet()) {
String percComponent = String.format("(%.1f%%)", 100.0 * ms.count(component) / total);
out.printf(" %3d %7s: %s%n", ms.count(component), percComponent, component);
}
}
}
out.println();
Multimap<String, Issue> byCommitter = model.byCommitter();
out.println("Distribution by affiliation:");
{
Multiset<String> byAffiliation = TreeMultiset.create();
Map<String, Multiset<String>> byAffiliationAndCommitter = new HashMap<>();
for (String committer : byCommitter.keySet()) {
String aff = users.getAffiliation(committer);
byAffiliation.add(aff, byCommitter.get(committer).size());
Multiset<String> bu = byAffiliationAndCommitter.computeIfAbsent(aff, k -> HashMultiset.create());
bu.add(users.getDisplayName(committer), byCommitter.get(committer).size());
}
int total = byCommitter.size();
out.printf(" %3d: <total issues>%n", total);
for (String aff : Multisets.copyHighestCountFirst(byAffiliation).elementSet()) {
String percAff = String.format("(%.1f%%)", 100.0 * byAffiliation.count(aff) / total);
out.printf(" %3d %7s: %s%n", byAffiliation.count(aff), percAff, aff);
Multiset<String> committers = byAffiliationAndCommitter.get(aff);
for (String committer : Multisets.copyHighestCountFirst(committers).elementSet()) {
String percCommitter = String.format("(%.1f%%)", 100.0 * committers.count(committer) / total);
out.printf(" %3d %7s: %s%n", committers.count(committer), percCommitter, committer);
}
}
}
out.println();
out.println("Chronological push log:");
out.println();
for (Issue i : model.byTime()) {
String pushUser = Accessors.getPushUser(i);
out.printf(" %3d day(s) ago, %" + users.maxDisplayName() + "s, %" + users.maxAffiliation() + "s, %s: %s%n",
TimeUnit.SECONDS.toDays(Accessors.getPushSecondsAgo(i)),
users.getDisplayName(pushUser), users.getAffiliation(pushUser),
i.getKey(), i.getSummary());
}
out.println();
out.println("No changesets log:");
out.println();
for (Issue i : model.noChangesets()) {
out.printf(" %s: %s%n", i.getKey(), i.getSummary());
}
out.println();
out.println("Committer push log:");
out.println();
for (String committer : byCommitter.keySet()) {
out.println(" " + users.getDisplayName(committer) + ", " + users.getAffiliation(committer) + ":");
for (Issue i : byCommitter.get(committer)) {
out.println(" " + i.getKey() + ": " + i.getSummary());
}
out.println();
}
}
}
| 7,064 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ReleaseNotesTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/ReleaseNotesTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.openjdk.backports.Main;
import org.openjdk.backports.StringUtils;
import org.openjdk.backports.report.model.ReleaseNotesModel;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;
public class ReleaseNotesTextReport extends AbstractTextReport {
private final ReleaseNotesModel model;
public ReleaseNotesTextReport(ReleaseNotesModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("RELEASE NOTES FOR: " + model.release());
printMajorDelimiterLine(out);
out.println();
out.println("Notes generated: " + new Date());
out.println();
out.println("Hint: Prefix bug IDs with " + Main.JIRA_URL + "browse/ to reach the relevant JIRA entry.");
out.println();
out.println("JAVA ENHANCEMENT PROPOSALS (JEP):");
out.println();
List<Issue> jeps = model.jeps();
if (jeps.isEmpty()) {
out.println(" None.");
}
for (Issue i : jeps) {
out.println(" " + i.getSummary());
out.println();
String[] par = StringUtils.paragraphs(i.getDescription());
if (par.length > 2) {
// Second one is summary
out.println(StringUtils.leftPad(StringUtils.rewrap(par[1], 100, 2), 6));
} else {
out.println(StringUtils.leftPad("No description.", 6));
}
out.println();
}
out.println();
out.println("RELEASE NOTES:");
out.println();
Map<String, Multimap<Issue, Issue>> rns = model.relNotes();
boolean haveRelNotes = false;
for (String component : rns.keySet()) {
boolean printed = false;
Multimap<Issue, Issue> m = rns.get(component);
for (Issue i : m.keySet()) {
haveRelNotes = true;
if (!printed) {
out.println(component + ":");
out.println();
printed = true;
}
PrintWriter pw = new PrintWriter(out);
Set<String> dup = new HashSet<>();
for (Issue rn : m.get(i)) {
String summary = StringUtils.leftPad(" " + i.getKey() + ": " + rn.getSummary().replaceFirst("Release Note: ", ""), 2);
String descr = StringUtils.leftPad(StringUtils.rewrap(StringUtils.stripNull(rn.getDescription()), StringUtils.DEFAULT_WIDTH - 6), 6);
if (dup.add(descr)) {
pw.println(summary);
pw.println();
pw.println(descr);
pw.println();
}
}
pw.flush();
}
}
if (!haveRelNotes) {
out.println(" None.");
}
out.println();
out.println("ALL FIXED ISSUES, BY COMPONENT AND PRIORITY:");
out.println();
Multimap<String, Issue> byComponent = model.byComponent();
for (String component : byComponent.keySet()) {
out.println(component + ":");
Multimap<String, Issue> byPriority = TreeMultimap.create(String::compareTo, DEFAULT_ISSUE_SORT);
for (Issue i : byComponent.get(component)) {
byPriority.put(i.getPriority().getName(), i);
}
for (String prio : byPriority.keySet()) {
for (Issue i : byPriority.get(prio)) {
out.printf(" (%s) %s: %s%n", prio, i.getKey(), i.getSummary());
}
}
out.println();
}
out.println();
if (model.includeCarryovers()) {
out.println("CARRIED OVER FROM PREVIOUS RELEASES:");
out.println(" These have fixes for the given release, but they are also fixed in the previous");
out.println(" minor version of the same major release.");
out.println();
SortedSet<Issue> carriedOver = model.carriedOver();
if (carriedOver.isEmpty()) {
out.println(" None.");
}
for (Issue i : carriedOver) {
out.printf(" (%s) %s: %s%n", i.getPriority().getName(), i.getKey(), i.getSummary());
}
out.println();
}
}
}
| 5,866 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
AffiliationTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/AffiliationTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import org.openjdk.backports.jira.UserCache;
import org.openjdk.backports.report.model.AffiliationModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.List;
public class AffiliationTextReport extends AbstractTextReport {
private final AffiliationModel model;
public AffiliationTextReport(AffiliationModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
public void doGenerate(PrintStream out) {
out.println("AFFILIATION REPORT");
printMajorDelimiterLine(out);
out.println();
out.println("Report generated: " + new Date());
out.println();
List<String> userIds = model.userIds();
UserCache users = model.users();
// Get all data and compute column widths
int maxUid = 0;
for (String uid : userIds) {
users.getDisplayName(uid);
users.getAffiliation(uid);
maxUid = Math.max(maxUid, uid.length());
}
int maxDisplayName = users.maxDisplayName();
int maxAffiliation = users.maxAffiliation();
for (String uid : userIds) {
out.printf("%" + maxUid + "s, %" + maxDisplayName + "s, %" + maxAffiliation + "s%n",
uid, users.getDisplayName(uid), users.getAffiliation(uid));
}
}
}
| 2,619 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
PendingPushTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/PendingPushTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import org.openjdk.backports.report.model.IssueModel;
import org.openjdk.backports.report.model.PendingPushModel;
import java.io.PrintStream;
import java.util.Date;
public class PendingPushTextReport extends AbstractTextReport {
private final PendingPushModel model;
public PendingPushTextReport(PendingPushModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("PENDING PUSH REPORT: " + model.release());
printMajorDelimiterLine(out);
out.println();
out.println("This report shows backports that were approved, but not yet pushed.");
out.println("Some of them are true orphans with original backport requesters never got sponsored.");
out.println();
out.println("Report generated: " + new Date());
out.println();
printMinorDelimiterLine(out);
for (IssueModel m : model.models()) {
new IssueTextReport(m, debugLog, logPrefix).generateSimple(out);
printMinorDelimiterLine(out);
}
}
}
| 2,393 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
ParityTextReport.java | /FileExtraction/Java_unseen/shipilev_jdk-backports-monitor/src/main/java/org/openjdk/backports/report/text/ParityTextReport.java | /*
* Copyright (c) 2019, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.backports.report.text;
import com.atlassian.jira.rest.client.api.domain.Issue;
import org.openjdk.backports.report.model.ParityModel;
import java.io.PrintStream;
import java.util.Date;
import java.util.Map;
public class ParityTextReport extends AbstractTextReport {
private final ParityModel model;
public ParityTextReport(ParityModel model, PrintStream debugLog, String logPrefix) {
super(debugLog, logPrefix);
this.model = model;
}
@Override
protected void doGenerate(PrintStream out) {
out.println("PARITY REPORT FOR JDK: " + model.majorVer());
printMajorDelimiterLine(out);
out.println();
out.println("This report shows the bird-eye view of parity between OpenJDK and Oracle JDK.");
out.println();
out.println("Report generated: " + new Date());
out.println();
out.println("=== EXCLUSIVE: ONLY IN ORACLE JDK");
out.println();
out.println("This is where Oracle JDK is ahead of OpenJDK.");
out.println("No relevant backports are detected in OpenJDK.");
out.println("This misses the future backporting work.");
out.println("[...] marks the interest tags.");
out.println("(!) marks the existing pull request.");
out.println("(*) marks the backporting work in progress.");
out.println();
printWithVersionMeta(out, model.onlyOracle());
out.println();
out.println("=== EXCLUSIVE: OPENJDK REJECTED");
out.println();
out.println("These are the issues that were ruled as either not");
out.println("affecting OpenJDK, or otherwise rejected by maintainers.");
printWithVersion(out, model.openRejected());
out.println();
out.println("=== EXCLUSIVE: ONLY IN OPENJDK");
out.println();
out.println("This is where OpenJDK is ahead of Oracle JDK.");
out.println("No relevant backports are detected in Oracle JDK yet.");
out.println("This misses the ongoing backporting work.");
out.println();
printWithVersion(out, model.onlyOpen());
out.println();
out.println("=== LATE PARITY: ORACLE JDK FOLLOWS OPENJDK IN LATER RELEASES");
out.println();
out.println("This is where OpenJDK used to be ahead, and then Oracle JDK caught up in future releases.");
out.println();
printDouble(out, model.lateOpenFirst());
out.println();
out.println("=== LATE PARITY: OPENJDK FOLLOWS ORACLE JDK IN LATER RELEASES");
out.println();
out.println("This is where Oracle JDK used to be ahead, and then OpenJDK caught up in future releases.");
out.println();
printDouble(out, model.lateOracleFirst());
out.println();
out.println("=== EXACT PARITY: ORACLE JDK FOLLOWS OPENJDK");
out.println();
out.println("This is where OpenJDK made the first backport in the release, and then Oracle JDK followed.");
out.println("No difference in the final release detected.");
out.println();
printSingle(out, model.exactOpenFirst());
out.println();
out.println("=== EXACT PARITY: OPENJDK FOLLOWS ORACLE JDK");
out.println();
out.println("This is where Oracle JDK made the first backport in the release, and then OpenJDK followed.");
out.println("No difference in the final release detected.");
out.println();
printSingle(out, model.exactOracleFirst());
out.println();
out.println("=== EXACT PARITY: UNKNOWN TIMING");
out.println();
out.println("This is where the difference in time within the release was not identified reliably.");
out.println("No difference in the final release detected.");
out.println();
printDouble(out, model.exactUnknown());
out.println();
}
void printWithVersionMeta(PrintStream out, Map<String, Map<Issue, ParityModel.SingleVersMetadata>> issues) {
int size = 0;
for (Map.Entry<String, Map<Issue, ParityModel.SingleVersMetadata>> kv : issues.entrySet()) {
size += kv.getValue().size();
}
out.println(size + " issues in total");
out.println();
for (Map.Entry<String, Map<Issue, ParityModel.SingleVersMetadata>> kv : issues.entrySet()) {
out.println(kv.getKey() + " (" + kv.getValue().size() + " issues):");
for (Map.Entry<Issue, ParityModel.SingleVersMetadata> kv2 : kv.getValue().entrySet()) {
Issue i = kv2.getKey();
ParityModel.SingleVersMetadata vers = kv2.getValue();
out.printf("%-" + model.getVersLen() + "s, %7s %3s %3s %s: %s%n",
vers.version(),
"[" + vers.interestTags() + "]",
!vers.reviewLinks().isEmpty() ? "(!)" : "",
vers.backportRequested() ? "(*)" : "",
i.getKey(),
i.getSummary());
}
out.println();
}
}
void printWithVersion(PrintStream out, Map<String, Map<Issue, ParityModel.SingleVers>> issues) {
int size = 0;
for (Map.Entry<String, Map<Issue, ParityModel.SingleVers>> kv : issues.entrySet()) {
size += kv.getValue().size();
}
out.println(size + " issues in total");
out.println();
for (Map.Entry<String, Map<Issue, ParityModel.SingleVers>> kv : issues.entrySet()) {
out.println(kv.getKey() + " (" + kv.getValue().size() + " issues):");
for (Map.Entry<Issue, ParityModel.SingleVers> kv2 : kv.getValue().entrySet()) {
Issue i = kv2.getKey();
ParityModel.SingleVers vers = kv2.getValue();
out.printf("%-" + model.getVersLen() + "s, %s: %s%n",
vers.version(),
i.getKey(),
i.getSummary());
}
out.println();
}
}
void printSingle(PrintStream out, Map<Issue, ParityModel.SingleVers> issues) {
out.println(issues.size() + " issues:");
for (Map.Entry<Issue,ParityModel.SingleVers> kv : issues.entrySet()) {
Issue i = kv.getKey();
ParityModel.SingleVers vers = kv.getValue();
out.printf("%-" + model.getVersLen() + "s, %s: %s%n",
vers.version(),
i.getKey(),
i.getSummary());
}
out.println();
}
void printDouble(PrintStream out, Map<Issue, ParityModel.DoubleVers> issues) {
out.println(issues.size() + " issues:");
for (Map.Entry<Issue,ParityModel.DoubleVers> kv : issues.entrySet()) {
Issue i = kv.getKey();
ParityModel.DoubleVers vers = kv.getValue();
out.printf("%-" + model.getVersLen() + "s, %-" + model.getVersLen() + "s, %s: %s%n",
vers.version1(),
vers.version2(),
i.getKey(),
i.getSummary());
}
out.println();
}
}
| 8,348 | Java | .java | shipilev/jdk-backports-monitor | 14 | 6 | 1 | 2018-12-07T23:09:11Z | 2023-04-14T18:11:27Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.